diff --git a/.gitignore b/.gitignore index bb99e96551..0c26b31aa1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ /staging/ /types/ -/dist/ /dist_type/ /test/bench/results/ /docs/API diff --git a/dist/maplibre-gl-csp-dev.js b/dist/maplibre-gl-csp-dev.js new file mode 100644 index 0000000000..b296b49148 --- /dev/null +++ b/dist/maplibre-gl-csp-dev.js @@ -0,0 +1,57964 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v4.7.0/LICENSE.txt + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : +typeof define === 'function' && define.amd ? define(['exports'], factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.maplibregl = {})); +})(this, (function (exports) { 'use strict'; + +var name = "maplibre-gl"; +var description = "BSD licensed community fork of mapbox-gl, a WebGL interactive maps library"; +var version$2 = "4.7.0"; +var main = "dist/maplibre-gl.js"; +var style = "dist/maplibre-gl.css"; +var license = "BSD-3-Clause"; +var homepage = "https://maplibre.org/"; +var funding = "https://github.com/maplibre/maplibre-gl-js?sponsor=1"; +var bugs = { + url: "https://github.com/maplibre/maplibre-gl-js/issues/" +}; +var repository = { + type: "git", + url: "git://github.com/maplibre/maplibre-gl-js.git" +}; +var types$2 = "dist/maplibre-gl.d.ts"; +var type = "module"; +var dependencies = { + "@mapbox/geojson-rewind": "^0.5.2", + "@mapbox/jsonlint-lines-primitives": "^2.0.2", + "@mapbox/point-geometry": "^0.1.0", + "@mapbox/tiny-sdf": "^2.0.6", + "@mapbox/unitbezier": "^0.0.1", + "@mapbox/vector-tile": "^1.3.1", + "@mapbox/whoots-js": "^3.1.0", + "@maplibre/maplibre-gl-style-spec": "^20.3.1", + "@types/geojson": "^7946.0.14", + "@types/geojson-vt": "3.2.5", + "@types/mapbox__point-geometry": "^0.1.4", + "@types/mapbox__vector-tile": "^1.3.4", + "@types/pbf": "^3.0.5", + "@types/supercluster": "^7.1.3", + earcut: "^3.0.0", + "geojson-vt": "^4.0.2", + "gl-matrix": "^3.4.3", + "global-prefix": "^4.0.0", + kdbush: "^4.0.2", + "murmurhash-js": "^1.0.0", + pbf: "^3.3.0", + potpack: "^2.0.0", + quickselect: "^3.0.0", + supercluster: "^8.0.1", + tinyqueue: "^3.0.0", + "vt-pbf": "^3.1.3" +}; +var devDependencies = { + autoprefixer: "^10.4.20", + "@mapbox/mapbox-gl-rtl-text": "^0.3.0", + "@mapbox/mvt-fixtures": "^3.10.0", + "@rollup/plugin-commonjs": "^26.0.1", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-replace": "^5.0.7", + "@rollup/plugin-strip": "^3.0.4", + "@rollup/plugin-terser": "^0.4.4", + "@rollup/plugin-typescript": "^11.1.6", + "@types/benchmark": "^2.1.5", + "@types/cssnano": "^5.0.0", + "@types/d3": "^7.4.3", + "@types/diff": "^5.2.2", + "@types/earcut": "^2.1.4", + "@types/eslint": "^8.56.7", + "@types/gl": "^6.0.5", + "@types/glob": "^8.1.0", + "@types/jest": "^29.5.12", + "@types/jsdom": "^21.1.7", + "@types/minimist": "^1.2.5", + "@types/murmurhash-js": "^1.0.6", + "@types/nise": "^1.4.5", + "@types/node": "^22.5.4", + "@types/offscreencanvas": "^2019.7.3", + "@types/pixelmatch": "^5.2.6", + "@types/pngjs": "^6.0.5", + "@types/react": "^18.3.5", + "@types/react-dom": "^18.3.0", + "@types/request": "^2.48.12", + "@types/shuffle-seed": "^1.1.3", + "@types/window-or-global": "^1.0.6", + "@typescript-eslint/eslint-plugin": "^7.18.0", + "@typescript-eslint/parser": "^7.18.0", + address: "^2.0.3", + benchmark: "^2.1.4", + canvas: "^2.11.2", + cssnano: "^7.0.6", + d3: "^7.9.0", + "d3-queue": "^3.0.7", + "devtools-protocol": "^0.0.1352404", + diff: "^7.0.0", + "dts-bundle-generator": "^9.5.1", + eslint: "^8.57.0", + "eslint-config-mourner": "^3.0.0", + "eslint-plugin-html": "^8.1.1", + "eslint-plugin-import": "^2.30.0", + "eslint-plugin-jest": "^28.8.3", + "eslint-plugin-react": "^7.35.2", + "eslint-plugin-tsdoc": "0.3.0", + expect: "^29.7.0", + glob: "^11.0.0", + "is-builtin-module": "^4.0.0", + jest: "^29.7.0", + "jest-environment-jsdom": "^29.7.0", + "jest-junit": "^16.0.0", + "jest-monocart-coverage": "^1.1.1", + "jest-webgl-canvas-mock": "^2.5.3", + jsdom: "^25.0.0", + "junit-report-builder": "^5.0.0", + minimist: "^1.2.8", + "mock-geolocation": "^1.0.11", + "monocart-coverage-reports": "^2.10.3", + nise: "^6.0.0", + "npm-font-open-sans": "^1.1.0", + "npm-run-all": "^4.1.5", + "pdf-merger-js": "^5.1.2", + pixelmatch: "^6.0.0", + pngjs: "^7.0.0", + postcss: "^8.4.45", + "postcss-cli": "^11.0.0", + "postcss-inline-svg": "^6.0.0", + "pretty-bytes": "^6.1.1", + puppeteer: "^23.3.0", + react: "^18.3.1", + "react-dom": "^18.3.1", + rollup: "^4.21.2", + "rollup-plugin-sourcemaps": "^0.6.3", + rw: "^1.3.3", + semver: "^7.6.3", + "shuffle-seed": "^1.1.6", + "source-map-explorer": "^2.5.3", + st: "^3.0.0", + stylelint: "^16.9.0", + "stylelint-config-standard": "^36.0.1", + "ts-jest": "^29.2.5", + "ts-node": "^10.9.2", + tslib: "^2.7.0", + typedoc: "^0.26.6", + "typedoc-plugin-markdown": "^4.2.7", + "typedoc-plugin-missing-exports": "^3.0.0", + typescript: "^5.5.4" +}; +var scripts = { + "generate-dist-package": "node --no-warnings --loader ts-node/esm build/generate-dist-package.js", + "generate-shaders": "node --no-warnings --loader ts-node/esm build/generate-shaders.ts", + "generate-struct-arrays": "node --no-warnings --loader ts-node/esm build/generate-struct-arrays.ts", + "generate-style-code": "node --no-warnings --loader ts-node/esm build/generate-style-code.ts", + "generate-typings": "dts-bundle-generator --export-referenced-types --umd-module-name=maplibregl -o ./dist/maplibre-gl.d.ts ./src/index.ts", + "generate-docs": "typedoc && node --no-warnings --loader ts-node/esm build/generate-docs.ts", + "generate-images": "node --no-warnings --loader ts-node/esm build/generate-doc-images.ts", + "build-dist": "npm run build-css && npm run generate-typings && npm run build-dev && npm run build-csp-dev && npm run build-prod && npm run build-prod-unminified && npm run build-csp", + "build-dev": "rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:dev", + "watch-dev": "rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:dev --watch", + "build-prod": "rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:production,MINIFY:true", + "build-prod-unminified": "rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:production", + "build-csp": "rollup --configPlugin @rollup/plugin-typescript -c rollup.config.csp.ts --environment BUILD:production,MINIFY:true", + "build-csp-dev": "rollup --configPlugin @rollup/plugin-typescript -c rollup.config.csp.ts --environment BUILD:dev", + "build-css": "postcss -o dist/maplibre-gl.css src/css/maplibre-gl.css", + "watch-css": "postcss --watch -o dist/maplibre-gl.css src/css/maplibre-gl.css", + "build-benchmarks": "npm run build-dev && rollup --configPlugin @rollup/plugin-typescript -c test/bench/rollup_config_benchmarks.ts", + "watch-benchmarks": "rollup --configPlugin @rollup/plugin-typescript -c test/bench/rollup_config_benchmarks.ts --watch", + "start-server": "st --no-cache -H localhost --port 9966 .", + "start-docs": "docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material", + start: "run-p watch-css watch-dev start-server", + "start-bench": "run-p watch-css watch-benchmarks start-server", + lint: "eslint --cache --ext .ts,.tsx,.js,.html --ignore-path .gitignore .", + "lint-css": "stylelint **/*.css --fix -f verbose", + test: "run-p lint lint-css test-render jest", + jest: "jest", + "test-build": "jest --selectProjects=build --reporters=default", + "test-build-ci": "jest --selectProjects=build", + "test-integration": "jest --selectProjects=integration --reporters=default", + "test-integration-ci": "jest --coverage --selectProjects=integration", + "test-render": "node --no-warnings --loader ts-node/esm test/integration/render/run_render_tests.ts", + "test-unit": "jest --selectProjects=unit --reporters=default", + "test-unit-ci": "jest --coverage --selectProjects unit", + "test-watch-roots": "jest --watch", + codegen: "run-p --print-label generate-dist-package generate-style-code generate-struct-arrays generate-shaders && npm run generate-typings", + benchmark: "node --no-warnings --loader ts-node/esm test/bench/run-benchmarks.ts", + "gl-stats": "node --no-warnings --loader ts-node/esm test/bench/gl-stats.ts", + prepare: "npm run codegen", + typecheck: "tsc --noEmit && tsc --project tsconfig.dist.json", + tsnode: "node --experimental-loader=ts-node/esm --no-warnings" +}; +var files = [ + "build/", + "dist/*", + "src/" +]; +var engines = { + npm: ">=8.1.0", + node: ">=16.14.0" +}; +var packageJSON = { + name: name, + description: description, + version: version$2, + main: main, + style: style, + license: license, + homepage: homepage, + funding: funding, + bugs: bugs, + repository: repository, + types: types$2, + type: type, + dependencies: dependencies, + devDependencies: devDependencies, + scripts: scripts, + files: files, + engines: engines +}; + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; + +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; + +function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; + +function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +}; + +function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; + +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +var __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); + +function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +/** @deprecated */ +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}; + +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +} + +function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +function __classPrivateFieldIn(state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} + +function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + +} + +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + function next() { + while (env.stack.length) { + var rec = env.stack.pop(); + try { + var result = rec.dispose && rec.dispose.call(rec.value); + if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + catch (e) { + fail(e); + } + } + if (env.hasError) throw env.error; + } + return next(); +} + +var tslib_es6 = { + __extends: __extends, + __assign: __assign, + __rest: __rest, + __decorate: __decorate, + __param: __param, + __metadata: __metadata, + __awaiter: __awaiter, + __generator: __generator, + __createBinding: __createBinding, + __exportStar: __exportStar, + __values: __values, + __read: __read, + __spread: __spread, + __spreadArrays: __spreadArrays, + __spreadArray: __spreadArray, + __await: __await, + __asyncGenerator: __asyncGenerator, + __asyncDelegator: __asyncDelegator, + __asyncValues: __asyncValues, + __makeTemplateObject: __makeTemplateObject, + __importStar: __importStar, + __importDefault: __importDefault, + __classPrivateFieldGet: __classPrivateFieldGet, + __classPrivateFieldSet: __classPrivateFieldSet, + __classPrivateFieldIn: __classPrivateFieldIn, + __addDisposableResource: __addDisposableResource, + __disposeResources: __disposeResources, +}; + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs$1 (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function getDefaultExportFromNamespaceIfPresent (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; +} + +function getDefaultExportFromNamespaceIfNotNamed (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; +} + +function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a () { + if (this instanceof a) { + return Reflect.construct(f, arguments, this.constructor); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} + +'use strict'; + +var pointGeometry = Point$1; + +/** + * A standalone point geometry with useful accessor, comparison, and + * modification methods. + * + * @class Point + * @param {Number} x the x-coordinate. this could be longitude or screen + * pixels, or any other sort of unit. + * @param {Number} y the y-coordinate. this could be latitude or screen + * pixels, or any other sort of unit. + * @example + * var point = new Point(-77, 38); + */ +function Point$1(x, y) { + this.x = x; + this.y = y; +} + +Point$1.prototype = { + + /** + * Clone this point, returning a new point that can be modified + * without affecting the old one. + * @return {Point} the clone + */ + clone: function() { return new Point$1(this.x, this.y); }, + + /** + * Add this point's x & y coordinates to another point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + add: function(p) { return this.clone()._add(p); }, + + /** + * Subtract this point's x & y coordinates to from point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + sub: function(p) { return this.clone()._sub(p); }, + + /** + * Multiply this point's x & y coordinates by point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + multByPoint: function(p) { return this.clone()._multByPoint(p); }, + + /** + * Divide this point's x & y coordinates by point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + divByPoint: function(p) { return this.clone()._divByPoint(p); }, + + /** + * Multiply this point's x & y coordinates by a factor, + * yielding a new point. + * @param {Point} k factor + * @return {Point} output point + */ + mult: function(k) { return this.clone()._mult(k); }, + + /** + * Divide this point's x & y coordinates by a factor, + * yielding a new point. + * @param {Point} k factor + * @return {Point} output point + */ + div: function(k) { return this.clone()._div(k); }, + + /** + * Rotate this point around the 0, 0 origin by an angle a, + * given in radians + * @param {Number} a angle to rotate around, in radians + * @return {Point} output point + */ + rotate: function(a) { return this.clone()._rotate(a); }, + + /** + * Rotate this point around p point by an angle a, + * given in radians + * @param {Number} a angle to rotate around, in radians + * @param {Point} p Point to rotate around + * @return {Point} output point + */ + rotateAround: function(a,p) { return this.clone()._rotateAround(a,p); }, + + /** + * Multiply this point by a 4x1 transformation matrix + * @param {Array} m transformation matrix + * @return {Point} output point + */ + matMult: function(m) { return this.clone()._matMult(m); }, + + /** + * Calculate this point but as a unit vector from 0, 0, meaning + * that the distance from the resulting point to the 0, 0 + * coordinate will be equal to 1 and the angle from the resulting + * point to the 0, 0 coordinate will be the same as before. + * @return {Point} unit vector point + */ + unit: function() { return this.clone()._unit(); }, + + /** + * Compute a perpendicular point, where the new y coordinate + * is the old x coordinate and the new x coordinate is the old y + * coordinate multiplied by -1 + * @return {Point} perpendicular point + */ + perp: function() { return this.clone()._perp(); }, + + /** + * Return a version of this point with the x & y coordinates + * rounded to integers. + * @return {Point} rounded point + */ + round: function() { return this.clone()._round(); }, + + /** + * Return the magitude of this point: this is the Euclidean + * distance from the 0, 0 coordinate to this point's x and y + * coordinates. + * @return {Number} magnitude + */ + mag: function() { + return Math.sqrt(this.x * this.x + this.y * this.y); + }, + + /** + * Judge whether this point is equal to another point, returning + * true or false. + * @param {Point} other the other point + * @return {boolean} whether the points are equal + */ + equals: function(other) { + return this.x === other.x && + this.y === other.y; + }, + + /** + * Calculate the distance from this point to another point + * @param {Point} p the other point + * @return {Number} distance + */ + dist: function(p) { + return Math.sqrt(this.distSqr(p)); + }, + + /** + * Calculate the distance from this point to another point, + * without the square root step. Useful if you're comparing + * relative distances. + * @param {Point} p the other point + * @return {Number} distance + */ + distSqr: function(p) { + var dx = p.x - this.x, + dy = p.y - this.y; + return dx * dx + dy * dy; + }, + + /** + * Get the angle from the 0, 0 coordinate to this point, in radians + * coordinates. + * @return {Number} angle + */ + angle: function() { + return Math.atan2(this.y, this.x); + }, + + /** + * Get the angle from this point to another point, in radians + * @param {Point} b the other point + * @return {Number} angle + */ + angleTo: function(b) { + return Math.atan2(this.y - b.y, this.x - b.x); + }, + + /** + * Get the angle between this point and another point, in radians + * @param {Point} b the other point + * @return {Number} angle + */ + angleWith: function(b) { + return this.angleWithSep(b.x, b.y); + }, + + /* + * Find the angle of the two vectors, solving the formula for + * the cross product a x b = |a||b|sin(θ) for θ. + * @param {Number} x the x-coordinate + * @param {Number} y the y-coordinate + * @return {Number} the angle in radians + */ + angleWithSep: function(x, y) { + return Math.atan2( + this.x * y - this.y * x, + this.x * x + this.y * y); + }, + + _matMult: function(m) { + var x = m[0] * this.x + m[1] * this.y, + y = m[2] * this.x + m[3] * this.y; + this.x = x; + this.y = y; + return this; + }, + + _add: function(p) { + this.x += p.x; + this.y += p.y; + return this; + }, + + _sub: function(p) { + this.x -= p.x; + this.y -= p.y; + return this; + }, + + _mult: function(k) { + this.x *= k; + this.y *= k; + return this; + }, + + _div: function(k) { + this.x /= k; + this.y /= k; + return this; + }, + + _multByPoint: function(p) { + this.x *= p.x; + this.y *= p.y; + return this; + }, + + _divByPoint: function(p) { + this.x /= p.x; + this.y /= p.y; + return this; + }, + + _unit: function() { + this._div(this.mag()); + return this; + }, + + _perp: function() { + var y = this.y; + this.y = this.x; + this.x = -y; + return this; + }, + + _rotate: function(angle) { + var cos = Math.cos(angle), + sin = Math.sin(angle), + x = cos * this.x - sin * this.y, + y = sin * this.x + cos * this.y; + this.x = x; + this.y = y; + return this; + }, + + _rotateAround: function(angle, p) { + var cos = Math.cos(angle), + sin = Math.sin(angle), + x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y), + y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y); + this.x = x; + this.y = y; + return this; + }, + + _round: function() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } +}; + +/** + * Construct a point from an array if necessary, otherwise if the input + * is already a Point, or an unknown type, return it unchanged + * @param {Array|Point|*} a any kind of input value + * @return {Point} constructed point, or passed-through value. + * @example + * // this + * var point = Point.convert([0, 1]); + * // is equivalent to + * var point = new Point(0, 1); + */ +Point$1.convert = function (a) { + if (a instanceof Point$1) { + return a; + } + if (Array.isArray(a)) { + return new Point$1(a[0], a[1]); + } + return a; +}; + +var Point$2 = /*@__PURE__*/getDefaultExportFromCjs$1(pointGeometry); + +'use strict'; + +var unitbezier$1 = UnitBezier$2; + +function UnitBezier$2(p1x, p1y, p2x, p2y) { + // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). + this.cx = 3.0 * p1x; + this.bx = 3.0 * (p2x - p1x) - this.cx; + this.ax = 1.0 - this.cx - this.bx; + + this.cy = 3.0 * p1y; + this.by = 3.0 * (p2y - p1y) - this.cy; + this.ay = 1.0 - this.cy - this.by; + + this.p1x = p1x; + this.p1y = p1y; + this.p2x = p2x; + this.p2y = p2y; +} + +UnitBezier$2.prototype = { + sampleCurveX: function (t) { + // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. + return ((this.ax * t + this.bx) * t + this.cx) * t; + }, + + sampleCurveY: function (t) { + return ((this.ay * t + this.by) * t + this.cy) * t; + }, + + sampleCurveDerivativeX: function (t) { + return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; + }, + + solveCurveX: function (x, epsilon) { + if (epsilon === undefined) epsilon = 1e-6; + + if (x < 0.0) return 0.0; + if (x > 1.0) return 1.0; + + var t = x; + + // First try a few iterations of Newton's method - normally very fast. + for (var i = 0; i < 8; i++) { + var x2 = this.sampleCurveX(t) - x; + if (Math.abs(x2) < epsilon) return t; + + var d2 = this.sampleCurveDerivativeX(t); + if (Math.abs(d2) < 1e-6) break; + + t = t - x2 / d2; + } + + // Fall back to the bisection method for reliability. + var t0 = 0.0; + var t1 = 1.0; + t = x; + + for (i = 0; i < 20; i++) { + x2 = this.sampleCurveX(t); + if (Math.abs(x2 - x) < epsilon) break; + + if (x > x2) { + t0 = t; + } else { + t1 = t; + } + + t = (t1 - t0) * 0.5 + t0; + } + + return t; + }, + + solve: function (x, epsilon) { + return this.sampleCurveY(this.solveCurveX(x, epsilon)); + } +}; + +var UnitBezier$3 = /*@__PURE__*/getDefaultExportFromCjs$1(unitbezier$1); + +let supportsOffscreenCanvas; +function offscreenCanvasSupported() { + if (supportsOffscreenCanvas == null) { + supportsOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && + new OffscreenCanvas(1, 1).getContext('2d') && + typeof createImageBitmap === 'function'; + } + return supportsOffscreenCanvas; +} + +let offscreenCanvasDistorted; +/** + * Some browsers don't return the exact pixels from a canvas to prevent user fingerprinting (see #3185). + * This function writes pixels to an OffscreenCanvas and reads them back using getImageData, returning false + * if they don't match. + * + * @returns true if the browser supports OffscreenCanvas but it distorts getImageData results, false otherwise. + */ +function isOffscreenCanvasDistorted() { + if (offscreenCanvasDistorted == null) { + offscreenCanvasDistorted = false; + if (offscreenCanvasSupported()) { + const size = 5; + const canvas = new OffscreenCanvas(size, size); + const context = canvas.getContext('2d', { willReadFrequently: true }); + if (context) { + // fill each pixel with an RGB value that should make the byte at index i equal to i (except alpha channel): + // [0, 1, 2, 255, 4, 5, 6, 255, 8, 9, 10, 255, ...] + for (let i = 0; i < size * size; i++) { + const base = i * 4; + context.fillStyle = `rgb(${base},${base + 1},${base + 2})`; + context.fillRect(i % size, Math.floor(i / size), 1, 1); + } + const data = context.getImageData(0, 0, size, size).data; + for (let i = 0; i < size * size * 4; i++) { + if (i % 4 !== 3 && data[i] !== i) { + offscreenCanvasDistorted = true; + break; + } + } + } + } + } + return offscreenCanvasDistorted || false; +} + +/** + * For a given collection of 2D points, returns their axis-aligned bounding box, + * in the format [minX, minY, maxX, maxY]. + */ +function getAABB(points) { + let tlX = Infinity; + let tlY = Infinity; + let brX = -Infinity; + let brY = -Infinity; + for (const p of points) { + tlX = Math.min(tlX, p.x); + tlY = Math.min(tlY, p.y); + brX = Math.max(brX, p.x); + brY = Math.max(brY, p.y); + } + return [tlX, tlY, brX, brY]; +} +/** + * Given a value `t` that varies between 0 and 1, return + * an interpolation function that eases between 0 and 1 in a pleasing + * cubic in-out fashion. + */ +function easeCubicInOut(t) { + if (t <= 0) + return 0; + if (t >= 1) + return 1; + const t2 = t * t, t3 = t2 * t; + return 4 * (t < 0.5 ? t3 : 3 * (t - t2) + t3 - 0.75); +} +/** + * Given given (x, y), (x1, y1) control points for a bezier curve, + * return a function that interpolates along that curve. + * + * @param p1x - control point 1 x coordinate + * @param p1y - control point 1 y coordinate + * @param p2x - control point 2 x coordinate + * @param p2y - control point 2 y coordinate + */ +function bezier$1(p1x, p1y, p2x, p2y) { + const bezier = new UnitBezier$3(p1x, p1y, p2x, p2y); + return (t) => { + return bezier.solve(t); + }; +} +/** + * A default bezier-curve powered easing function with + * control points (0.25, 0.1) and (0.25, 1) + */ +const defaultEasing = bezier$1(0.25, 0.1, 0.25, 1); +/** + * constrain n to the given range via min + max + * + * @param n - value + * @param min - the minimum value to be returned + * @param max - the maximum value to be returned + * @returns the clamped value + */ +function clamp$1(n, min, max) { + return Math.min(max, Math.max(min, n)); +} +/** + * constrain n to the given range, excluding the minimum, via modular arithmetic + * + * @param n - value + * @param min - the minimum value to be returned, exclusive + * @param max - the maximum value to be returned, inclusive + * @returns constrained number + */ +function wrap(n, min, max) { + const d = max - min; + const w = ((n - min) % d + d) % d + min; + return (w === min) ? max : w; +} +/** + * Compute the difference between the keys in one object and the keys + * in another object. + * + * @returns keys difference + */ +function keysDifference(obj, other) { + const difference = []; + for (const i in obj) { + if (!(i in other)) { + difference.push(i); + } + } + return difference; +} +function extend(dest, ...sources) { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; +} +/** + * Given an object and a number of properties as strings, return version + * of that object with only those properties. + * + * @param src - the object + * @param properties - an array of property names chosen + * to appear on the resulting object. + * @returns object with limited properties. + * @example + * ```ts + * let foo = { name: 'Charlie', age: 10 }; + * let justName = pick(foo, ['name']); // justName = { name: 'Charlie' } + * ``` + */ +function pick(src, properties) { + const result = {}; + for (let i = 0; i < properties.length; i++) { + const k = properties[i]; + if (k in src) { + result[k] = src[k]; + } + } + return result; +} +let id = 1; +/** + * Return a unique numeric id, starting at 1 and incrementing with + * each call. + * + * @returns unique numeric id. + */ +function uniqueId() { + return id++; +} +/** + * Return whether a given value is a power of two + */ +function isPowerOfTwo(value) { + return (Math.log(value) / Math.LN2) % 1 === 0; +} +/** + * Return the next power of two, or the input value if already a power of two + */ +function nextPowerOfTwo(value) { + if (value <= 1) + return 1; + return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2)); +} +/** + * Create an object by mapping all the values of an existing object while + * preserving their keys. + */ +function mapObject(input, iterator, context) { + const output = {}; + for (const key in input) { + output[key] = iterator.call(context || this, input[key], key, input); + } + return output; +} +/** + * Create an object by filtering out values of an existing object. + */ +function filterObject(input, iterator, context) { + const output = {}; + for (const key in input) { + if (iterator.call(context || this, input[key], key, input)) { + output[key] = input[key]; + } + } + return output; +} +/** + * Deeply compares two object literals. + * @param a - first object literal to be compared + * @param b - second object literal to be compared + * @returns true if the two object literals are deeply equal, false otherwise + */ +function deepEqual$1(a, b) { + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) { + if (!deepEqual$1(a[i], b[i])) + return false; + } + return true; + } + if (typeof a === 'object' && a !== null && b !== null) { + if (!(typeof b === 'object')) + return false; + const keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) + return false; + for (const key in a) { + if (!deepEqual$1(a[key], b[key])) + return false; + } + return true; + } + return a === b; +} +/** + * Deeply clones two objects. + */ +function clone$9(input) { + if (Array.isArray(input)) { + return input.map(clone$9); + } + else if (typeof input === 'object' && input) { + return mapObject(input, clone$9); + } + else { + return input; + } +} +/** + * Check if two arrays have at least one common element. + */ +function arraysIntersect(a, b) { + for (let l = 0; l < a.length; l++) { + if (b.indexOf(a[l]) >= 0) + return true; + } + return false; +} +/** + * Print a warning message to the console and ensure duplicate warning messages + * are not printed. + */ +const warnOnceHistory = {}; +function warnOnce(message) { + if (!warnOnceHistory[message]) { + // console isn't defined in some WebWorkers, see #2558 + if (typeof console !== 'undefined') + console.warn(message); + warnOnceHistory[message] = true; + } +} +/** + * Indicates if the provided Points are in a counter clockwise (true) or clockwise (false) order + * + * @returns true for a counter clockwise set of points + */ +// https://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/ +function isCounterClockwise(a, b, c) { + return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x); +} +/** + * For two lines a and b in 2d space, defined by any two points along the lines, + * find the intersection point, or return null if the lines are parallel + * + * @param a1 - First point on line a + * @param a2 - Second point on line a + * @param b1 - First point on line b + * @param b2 - Second point on line b + * + * @returns the intersection point of the two lines or null if they are parallel + */ +function findLineIntersection(a1, a2, b1, b2) { + const aDeltaY = a2.y - a1.y; + const aDeltaX = a2.x - a1.x; + const bDeltaY = b2.y - b1.y; + const bDeltaX = b2.x - b1.x; + const denominator = (bDeltaY * aDeltaX) - (bDeltaX * aDeltaY); + if (denominator === 0) { + // Lines are parallel + return null; + } + const originDeltaY = a1.y - b1.y; + const originDeltaX = a1.x - b1.x; + const aInterpolation = (bDeltaX * originDeltaY - bDeltaY * originDeltaX) / denominator; + // Find intersection by projecting out from origin of first segment + return new Point$2(a1.x + (aInterpolation * aDeltaX), a1.y + (aInterpolation * aDeltaY)); +} +/** + * Converts spherical coordinates to cartesian coordinates. + * + * @param spherical - Spherical coordinates, in [radial, azimuthal, polar] + * @returns cartesian coordinates in [x, y, z] + */ +function sphericalToCartesian([r, azimuthal, polar]) { + // We abstract "north"/"up" (compass-wise) to be 0° when really this is 90° (π/2): + // correct for that here + azimuthal += 90; + // Convert azimuthal and polar angles to radians + azimuthal *= Math.PI / 180; + polar *= Math.PI / 180; + return { + x: r * Math.cos(azimuthal) * Math.sin(polar), + y: r * Math.sin(azimuthal) * Math.sin(polar), + z: r * Math.cos(polar) + }; +} +/** + * Returns true if the when run in the web-worker context. + * + * @returns `true` if the when run in the web-worker context. + */ +function isWorker(self) { + // @ts-ignore + return typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof WorkerGlobalScope; +} +/** + * Parses data from 'Cache-Control' headers. + * + * @param cacheControl - Value of 'Cache-Control' header + * @returns object containing parsed header info. + */ +function parseCacheControl(cacheControl) { + // Taken from [Wreck](https://github.com/hapijs/wreck) + const re = /(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g; + const header = {}; + cacheControl.replace(re, ($0, $1, $2, $3) => { + const value = $2 || $3; + header[$1] = value ? value.toLowerCase() : true; + return ''; + }); + if (header['max-age']) { + const maxAge = parseInt(header['max-age'], 10); + if (isNaN(maxAge)) + delete header['max-age']; + else + header['max-age'] = maxAge; + } + return header; +} +let _isSafari = null; +/** + * Returns true when run in WebKit derived browsers. + * This is used as a workaround for a memory leak in Safari caused by using Transferable objects to + * transfer data between WebWorkers and the main thread. + * https://github.com/mapbox/mapbox-gl-js/issues/8771 + * + * This should be removed once the underlying Safari issue is fixed. + * + * @param scope - Since this function is used both on the main thread and WebWorker context, + * let the calling scope pass in the global scope object. + * @returns `true` when run in WebKit derived browsers. + */ +function isSafari(scope) { + if (_isSafari == null) { + const userAgent = scope.navigator ? scope.navigator.userAgent : null; + _isSafari = !!scope.safari || + !!(userAgent && (/\b(iPad|iPhone|iPod)\b/.test(userAgent) || (!!userAgent.match('Safari') && !userAgent.match('Chrome')))); + } + return _isSafari; +} +function storageAvailable(type) { + try { + const storage = window[type]; + storage.setItem('_mapbox_test_', 1); + storage.removeItem('_mapbox_test_'); + return true; + } + catch (e) { + return false; + } +} +// The following methods are from https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem +//Unicode compliant base64 encoder for strings +function b64EncodeUnicode(str) { + return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => { + return String.fromCharCode(Number('0x' + p1)); //eslint-disable-line + })); +} +// Unicode compliant decoder for base64-encoded strings +function b64DecodeUnicode(str) { + return decodeURIComponent(atob(str).split('').map((c) => { + return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); //eslint-disable-line + }).join('')); +} +function isImageBitmap(image) { + return typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap; +} +/** + * Converts an ArrayBuffer to an ImageBitmap. + * + * Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work + * perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting + * ArrayBuffers. + * + * @param data - Data to convert + * @returns - A promise resolved when the conversion is finished + */ +const arrayBufferToImageBitmap = (data) => __awaiter(void 0, void 0, void 0, function* () { + if (data.byteLength === 0) { + return createImageBitmap(new ImageData(1, 1)); + } + const blob = new Blob([new Uint8Array(data)], { type: 'image/png' }); + try { + return createImageBitmap(blob); + } + catch (e) { + throw 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.`); + } +}); +const transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII='; +/** + * Converts an ArrayBuffer to an HTMLImageElement. + * + * Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work + * perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting + * ArrayBuffers. + * + * @param data - Data to convert + * @returns - A promise resolved when the conversion is finished + */ +const arrayBufferToImage = (data) => { + return new Promise((resolve, reject) => { + const img = new Image(); + img.onload = () => { + resolve(img); + URL.revokeObjectURL(img.src); + // prevent image dataURI memory leak in Safari; + // but don't free the image immediately because it might be uploaded in the next frame + // https://github.com/mapbox/mapbox-gl-js/issues/10226 + img.onload = null; + window.requestAnimationFrame(() => { img.src = transparentPngUrl; }); + }; + img.onerror = () => reject(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.')); + const blob = new Blob([new Uint8Array(data)], { type: 'image/png' }); + img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl; + }); +}; +/** + * Computes the webcodecs VideoFrame API options to select a rectangle out of + * an image and write it into the destination rectangle. + * + * Rect (x/y/width/height) select the overlapping rectangle from the source image + * and layout (offset/stride) write that overlapping rectangle to the correct place + * in the destination image. + * + * Offset is the byte offset in the dest image that the first pixel appears at + * and stride is the number of bytes to the start of the next row: + * ┌───────────┐ + * │ dest │ + * │ ┌───┼───────┐ + * │offset→│▓▓▓│ source│ + * │ │▓▓▓│ │ + * │ └───┼───────┘ + * │stride ⇠╌╌╌│ + * │╌╌╌╌╌╌→ │ + * └───────────┘ + * + * @param image - source image containing a width and height attribute + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns the layout and rect options to pass into VideoFrame API + */ +function computeVideoFrameParameters(image, x, y, width, height) { + const destRowOffset = Math.max(-x, 0) * 4; + const firstSourceRow = Math.max(0, y); + const firstDestRow = firstSourceRow - y; + const offset = firstDestRow * width * 4 + destRowOffset; + const stride = width * 4; + const sourceLeft = Math.max(0, x); + const sourceTop = Math.max(0, y); + const sourceRight = Math.min(image.width, x + width); + const sourceBottom = Math.min(image.height, y + height); + return { + rect: { + x: sourceLeft, + y: sourceTop, + width: sourceRight - sourceLeft, + height: sourceBottom - sourceTop + }, + layout: [{ offset, stride }] + }; +} +/** + * Reads pixels from an ImageBitmap/Image/canvas using webcodec VideoFrame API. + * + * @param data - image, imagebitmap, or canvas to parse + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred + */ +function readImageUsingVideoFrame(image, x, y, width, height) { + return __awaiter(this, void 0, void 0, function* () { + if (typeof VideoFrame === 'undefined') { + throw new Error('VideoFrame not supported'); + } + const frame = new VideoFrame(image, { timestamp: 0 }); + try { + const format = frame === null || frame === void 0 ? void 0 : frame.format; + if (!format || !(format.startsWith('BGR') || format.startsWith('RGB'))) { + throw new Error(`Unrecognized format ${format}`); + } + const swapBR = format.startsWith('BGR'); + const result = new Uint8ClampedArray(width * height * 4); + yield frame.copyTo(result, computeVideoFrameParameters(image, x, y, width, height)); + if (swapBR) { + for (let i = 0; i < result.length; i += 4) { + const tmp = result[i]; + result[i] = result[i + 2]; + result[i + 2] = tmp; + } + } + return result; + } + finally { + frame.close(); + } + }); +} +let offscreenCanvas; +let offscreenCanvasContext; +/** + * Reads pixels from an ImageBitmap/Image/canvas using OffscreenCanvas + * + * @param data - image, imagebitmap, or canvas to parse + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred + */ +function readImageDataUsingOffscreenCanvas(imgBitmap, x, y, width, height) { + const origWidth = imgBitmap.width; + const origHeight = imgBitmap.height; + // Lazily initialize OffscreenCanvas + if (!offscreenCanvas || !offscreenCanvasContext) { + // Dem tiles are typically 256x256 + offscreenCanvas = new OffscreenCanvas(origWidth, origHeight); + offscreenCanvasContext = offscreenCanvas.getContext('2d', { willReadFrequently: true }); + } + offscreenCanvas.width = origWidth; + offscreenCanvas.height = origHeight; + offscreenCanvasContext.drawImage(imgBitmap, 0, 0, origWidth, origHeight); + const imgData = offscreenCanvasContext.getImageData(x, y, width, height); + offscreenCanvasContext.clearRect(0, 0, origWidth, origHeight); + return imgData.data; +} +/** + * Reads RGBA pixels from an preferring OffscreenCanvas, but falling back to VideoFrame if supported and + * the browser is mangling OffscreenCanvas getImageData results. + * + * @param data - image, imagebitmap, or canvas to parse + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns a promise containing the parsed RGBA pixel values of the image + */ +function getImageData(image, x, y, width, height) { + return __awaiter(this, void 0, void 0, function* () { + if (isOffscreenCanvasDistorted()) { + try { + return yield readImageUsingVideoFrame(image, x, y, width, height); + } + catch (e) { + // fall back to OffscreenCanvas + } + } + return readImageDataUsingOffscreenCanvas(image, x, y, width, height); + }); +} +/** + * This method is used in order to register an event listener using a lambda function. + * The return value will allow unsubscribing from the event, without the need to store the method reference. + * @param target - The target + * @param message - The message + * @param listener - The listener + * @param options - The options + * @returns a subscription object that can be used to unsubscribe from the event + */ +function subscribe(target, message, listener, options) { + target.addEventListener(message, listener, options); + return { + unsubscribe: () => { + target.removeEventListener(message, listener, options); + } + }; +} +/** + * This method converts degrees to radians. + * The return value is the radian value. + * @param degrees - The number of degrees + * @returns radians + */ +function degreesToRadians(degrees) { + return degrees * Math.PI / 180; +} +/** + * The maximum world tile zoom (Z). + * In other words, the upper bound supported for tile zoom. + */ +const MAX_TILE_ZOOM = 25; +/** + * The minimum world tile zoom (Z). + * In other words, the lower bound supported for tile zoom. + */ +const MIN_TILE_ZOOM = 0; + +/** + * An error message to use when an operation is aborted + */ +const ABORT_ERROR = 'AbortError'; +/** + * Check if an error is an abort error + * @param error - An error object + * @returns - true if the error is an abort error + */ +function isAbortError(error) { + return error.message === ABORT_ERROR; +} +/** + * Use this when you need to create an abort error. + * @returns An error object with the message "AbortError" + */ +function createAbortError() { + return new Error(ABORT_ERROR); +} + +const now = typeof performance !== 'undefined' && performance && performance.now ? + performance.now.bind(performance) : + Date.now.bind(Date); +let linkEl; +let reducedMotionQuery; +/** */ +const browser = { + /** + * Provides a function that outputs milliseconds: either performance.now() + * or a fallback to Date.now() + */ + now, + frameAsync(abortController) { + return new Promise((resolve, reject) => { + const frame = requestAnimationFrame(resolve); + abortController.signal.addEventListener('abort', () => { + cancelAnimationFrame(frame); + reject(createAbortError()); + }); + }); + }, + getImageData(img, padding = 0) { + const context = this.getImageCanvasContext(img); + return context.getImageData(-padding, -padding, img.width + 2 * padding, img.height + 2 * padding); + }, + getImageCanvasContext(img) { + const canvas = window.document.createElement('canvas'); + const context = canvas.getContext('2d', { willReadFrequently: true }); + if (!context) { + throw new Error('failed to create canvas 2d context'); + } + canvas.width = img.width; + canvas.height = img.height; + context.drawImage(img, 0, 0, img.width, img.height); + return context; + }, + resolveURL(path) { + if (!linkEl) + linkEl = document.createElement('a'); + linkEl.href = path; + return linkEl.href; + }, + hardwareConcurrency: typeof navigator !== 'undefined' && navigator.hardwareConcurrency || 4, + get prefersReducedMotion() { + // In case your test crashes when checking matchMedia, call setMatchMedia from 'src/util/test/util' + if (!matchMedia) + return false; + //Lazily initialize media query + if (reducedMotionQuery == null) { + reducedMotionQuery = matchMedia('(prefers-reduced-motion: reduce)'); + } + return reducedMotionQuery.matches; + }, +}; + +class DOM { + static testProp(props) { + if (!DOM.docStyle) + return props[0]; + for (let i = 0; i < props.length; i++) { + if (props[i] in DOM.docStyle) { + return props[i]; + } + } + return props[0]; + } + static create(tagName, className, container) { + const el = window.document.createElement(tagName); + if (className !== undefined) + el.className = className; + if (container) + container.appendChild(el); + return el; + } + static createNS(namespaceURI, tagName) { + const el = window.document.createElementNS(namespaceURI, tagName); + return el; + } + static disableDrag() { + if (DOM.docStyle && DOM.selectProp) { + DOM.userSelect = DOM.docStyle[DOM.selectProp]; + DOM.docStyle[DOM.selectProp] = 'none'; + } + } + static enableDrag() { + if (DOM.docStyle && DOM.selectProp) { + DOM.docStyle[DOM.selectProp] = DOM.userSelect; + } + } + static setTransform(el, value) { + el.style[DOM.transformProp] = value; + } + static addEventListener(target, type, callback, options = {}) { + if ('passive' in options) { + target.addEventListener(type, callback, options); + } + else { + target.addEventListener(type, callback, options.capture); + } + } + static removeEventListener(target, type, callback, options = {}) { + if ('passive' in options) { + target.removeEventListener(type, callback, options); + } + else { + target.removeEventListener(type, callback, options.capture); + } + } + // Suppress the next click, but only if it's immediate. + static suppressClickInternal(e) { + e.preventDefault(); + e.stopPropagation(); + window.removeEventListener('click', DOM.suppressClickInternal, true); + } + static suppressClick() { + window.addEventListener('click', DOM.suppressClickInternal, true); + window.setTimeout(() => { + window.removeEventListener('click', DOM.suppressClickInternal, true); + }, 0); + } + static getScale(element) { + const rect = element.getBoundingClientRect(); + return { + x: (rect.width / element.offsetWidth) || 1, + y: (rect.height / element.offsetHeight) || 1, + boundingClientRect: rect, + }; + } + static getPoint(el, scale, e) { + const rect = scale.boundingClientRect; + return new Point$2( + // rect.left/top values are in page scale (like clientX/Y), + // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies). + ((e.clientX - rect.left) / scale.x) - el.clientLeft, ((e.clientY - rect.top) / scale.y) - el.clientTop); + } + static mousePos(el, e) { + const scale = DOM.getScale(el); + return DOM.getPoint(el, scale, e); + } + static touchPos(el, touches) { + const points = []; + const scale = DOM.getScale(el); + for (let i = 0; i < touches.length; i++) { + points.push(DOM.getPoint(el, scale, touches[i])); + } + return points; + } + static mouseButton(e) { + return e.button; + } + static remove(node) { + if (node.parentNode) { + node.parentNode.removeChild(node); + } + } +} +DOM.docStyle = typeof window !== 'undefined' && window.document && window.document.documentElement.style; +DOM.selectProp = DOM.testProp(['userSelect', 'MozUserSelect', 'WebkitUserSelect', 'msUserSelect']); +DOM.transformProp = DOM.testProp(['transform', 'WebkitTransform']); + +const config = { + MAX_PARALLEL_IMAGE_REQUESTS: 16, + MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME: 8, + MAX_TILE_CACHE_ZOOM_LEVELS: 5, + REGISTERED_PROTOCOLS: {}, + WORKER_URL: '' +}; + +function getProtocol(url) { + return config.REGISTERED_PROTOCOLS[url.substring(0, url.indexOf('://'))]; +} +/** + * Adds a custom load resource function that will be called when using a URL that starts with a custom url schema. + * This will happen in the main thread, and workers might call it if they don't know how to handle the protocol. + * The example below will be triggered for custom:// urls defined in the sources list in the style definitions. + * The function passed will receive the request parameters and should return with the resulting resource, + * for example a pbf vector tile, non-compressed, represented as ArrayBuffer. + * + * @param customProtocol - the protocol to hook, for example 'custom' + * @param loadFn - the function to use when trying to fetch a tile specified by the customProtocol + * @example + * ```ts + * // This will fetch a file using the fetch API (this is obviously a non interesting example...) + * addProtocol('custom', async (params, abortController) => { + * const t = await fetch(`https://${params.url.split("://")[1]}`); + * if (t.status == 200) { + * const buffer = await t.arrayBuffer(); + * return {data: buffer} + * } else { + * throw new Error(`Tile fetch error: ${t.statusText}`); + * } + * }); + * // the following is an example of a way to return an error when trying to load a tile + * addProtocol('custom2', async (params, abortController) => { + * throw new Error('someErrorMessage')); + * }); + * ``` + */ +function addProtocol(customProtocol, loadFn) { + config.REGISTERED_PROTOCOLS[customProtocol] = loadFn; +} +/** + * Removes a previously added protocol in the main thread. + * + * @param customProtocol - the custom protocol to remove registration for + * @example + * ```ts + * removeProtocol('custom'); + * ``` + */ +function removeProtocol(customProtocol) { + delete config.REGISTERED_PROTOCOLS[customProtocol]; +} + +/** + * This is used to identify the global dispatcher id when sending a message from the worker without a target map id. + */ +const GLOBAL_DISPATCHER_ID = 'global-dispatcher'; +/** + * An error thrown when a HTTP request results in an error response. + */ +class AJAXError extends Error { + /** + * @param status - The response's HTTP status code. + * @param statusText - The response's HTTP status text. + * @param url - The request's URL. + * @param body - The response's body. + */ + constructor(status, statusText, url, body) { + super(`AJAXError: ${statusText} (${status}): ${url}`); + this.status = status; + this.statusText = statusText; + this.url = url; + this.body = body; + } +} +/** + * Ensure that we're sending the correct referrer from blob URL worker bundles. + * For files loaded from the local file system, `location.origin` will be set + * to the string(!) "null" (Firefox), or "file://" (Chrome, Safari, Edge), + * and we will set an empty referrer. Otherwise, we're using the document's URL. + */ +const getReferrer = () => isWorker(self) ? + self.worker && self.worker.referrer : + (window.location.protocol === 'blob:' ? window.parent : window).location.href; +/** + * Determines whether a URL is a file:// URL. This is obviously the case if it begins + * with file://. Relative URLs are also file:// URLs iff the original document was loaded + * via a file:// URL. + * @param url - The URL to check + * @returns `true` if the URL is a file:// URL, `false` otherwise + */ +const isFileURL = url => /^file:/.test(url) || (/^file:/.test(getReferrer()) && !/^\w+:/.test(url)); +function makeFetchRequest(requestParameters, abortController) { + return __awaiter(this, void 0, void 0, function* () { + const request = new Request(requestParameters.url, { + method: requestParameters.method || 'GET', + body: requestParameters.body, + credentials: requestParameters.credentials, + headers: requestParameters.headers, + cache: requestParameters.cache, + referrer: getReferrer(), + signal: abortController.signal + }); + // If the user has already set an Accept header, do not overwrite it here + if (requestParameters.type === 'json' && !request.headers.has('Accept')) { + request.headers.set('Accept', 'application/json'); + } + const response = yield fetch(request); + if (!response.ok) { + const body = yield response.blob(); + throw new AJAXError(response.status, response.statusText, requestParameters.url, body); + } + let parsePromise; + if ((requestParameters.type === 'arrayBuffer' || requestParameters.type === 'image')) { + parsePromise = response.arrayBuffer(); + } + else if (requestParameters.type === 'json') { + parsePromise = response.json(); + } + else { + parsePromise = response.text(); + } + const result = yield parsePromise; + if (abortController.signal.aborted) { + throw createAbortError(); + } + return { data: result, cacheControl: response.headers.get('Cache-Control'), expires: response.headers.get('Expires') }; + }); +} +function makeXMLHttpRequest(requestParameters, abortController) { + return new Promise((resolve, reject) => { + var _a; + const xhr = new XMLHttpRequest(); + xhr.open(requestParameters.method || 'GET', requestParameters.url, true); + if (requestParameters.type === 'arrayBuffer' || requestParameters.type === 'image') { + xhr.responseType = 'arraybuffer'; + } + for (const k in requestParameters.headers) { + xhr.setRequestHeader(k, requestParameters.headers[k]); + } + if (requestParameters.type === 'json') { + xhr.responseType = 'text'; + // Do not overwrite the user-provided Accept header + if (!((_a = requestParameters.headers) === null || _a === void 0 ? void 0 : _a.Accept)) { + xhr.setRequestHeader('Accept', 'application/json'); + } + } + xhr.withCredentials = requestParameters.credentials === 'include'; + xhr.onerror = () => { + reject(new Error(xhr.statusText)); + }; + xhr.onload = () => { + if (abortController.signal.aborted) { + return; + } + if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response !== null) { + let data = xhr.response; + if (requestParameters.type === 'json') { + // We're manually parsing JSON here to get better error messages. + try { + data = JSON.parse(xhr.response); + } + catch (err) { + reject(err); + return; + } + } + resolve({ data, cacheControl: xhr.getResponseHeader('Cache-Control'), expires: xhr.getResponseHeader('Expires') }); + } + else { + const body = new Blob([xhr.response], { type: xhr.getResponseHeader('Content-Type') }); + reject(new AJAXError(xhr.status, xhr.statusText, requestParameters.url, body)); + } + }; + abortController.signal.addEventListener('abort', () => { + xhr.abort(); + reject(createAbortError()); + }); + xhr.send(requestParameters.body); + }); +} +/** + * We're trying to use the Fetch API if possible. However, requests for resources with the file:// URI scheme don't work with the Fetch API. + * In this case we unconditionally use XHR on the current thread since referrers don't matter. + * This method can also use the registered method if `addProtocol` was called. + * @param requestParameters - The request parameters + * @param abortController - The abort controller allowing to cancel the request + * @returns a promise resolving to the response, including cache control and expiry data + */ +const makeRequest = function (requestParameters, abortController) { + if (/:\/\//.test(requestParameters.url) && !(/^https?:|^file:/.test(requestParameters.url))) { + const protocolLoadFn = getProtocol(requestParameters.url); + if (protocolLoadFn) { + return protocolLoadFn(requestParameters, abortController); + } + if (isWorker(self) && self.worker && self.worker.actor) { + return self.worker.actor.sendAsync({ type: "GR" /* MessageType.getResource */, data: requestParameters, targetMapId: GLOBAL_DISPATCHER_ID }, abortController); + } + } + if (!isFileURL(requestParameters.url)) { + if (fetch && Request && AbortController && Object.prototype.hasOwnProperty.call(Request.prototype, 'signal')) { + return makeFetchRequest(requestParameters, abortController); + } + if (isWorker(self) && self.worker && self.worker.actor) { + return self.worker.actor.sendAsync({ type: "GR" /* MessageType.getResource */, data: requestParameters, mustQueue: true, targetMapId: GLOBAL_DISPATCHER_ID }, abortController); + } + } + return makeXMLHttpRequest(requestParameters, abortController); +}; +const getJSON = (requestParameters, abortController) => { + return makeRequest(extend(requestParameters, { type: 'json' }), abortController); +}; +const getArrayBuffer = (requestParameters, abortController) => { + return makeRequest(extend(requestParameters, { type: 'arrayBuffer' }), abortController); +}; +function sameOrigin(inComingUrl) { + // A relative URL "/foo" or "./foo" will throw exception in URL's ctor, + // try-catch is expansive so just use a heuristic check to avoid it + // also check data URL + if (!inComingUrl || + inComingUrl.indexOf('://') <= 0 || // relative URL + inComingUrl.indexOf('data:image/') === 0 || // data image URL + inComingUrl.indexOf('blob:') === 0) { // blob + return true; + } + const urlObj = new URL(inComingUrl); + const locationObj = window.location; + return urlObj.protocol === locationObj.protocol && urlObj.host === locationObj.host; +} +const getVideo = (urls) => { + const video = window.document.createElement('video'); + video.muted = true; + return new Promise((resolve) => { + video.onloadstart = () => { + resolve(video); + }; + for (const url of urls) { + const s = window.document.createElement('source'); + if (!sameOrigin(url)) { + video.crossOrigin = 'Anonymous'; + } + s.src = url; + video.appendChild(s); + } + }); +}; + +const webpSupported = { + supported: false, + testSupport +}; +let glForTesting; +let webpCheckComplete = false; +let webpImgTest; +let webpImgTestOnloadComplete = false; +if (typeof document !== 'undefined') { + webpImgTest = document.createElement('img'); + webpImgTest.onload = () => { + if (glForTesting) + testWebpTextureUpload(glForTesting); + glForTesting = null; + webpImgTestOnloadComplete = true; + }; + webpImgTest.onerror = () => { + webpCheckComplete = true; + glForTesting = null; + }; + webpImgTest.src = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA='; +} +function testSupport(gl) { + if (webpCheckComplete || !webpImgTest) + return; + // HTMLImageElement.complete is set when an image is done loading it's source + // regardless of whether the load was successful or not. + // It's possible for an error to set HTMLImageElement.complete to true which would trigger + // testWebpTextureUpload and mistakenly set exported.supported to true in browsers which don't support webp + // To avoid this, we set a flag in the image's onload handler and only call testWebpTextureUpload + // after a successful image load event. + if (webpImgTestOnloadComplete) { + testWebpTextureUpload(gl); + } + else { + glForTesting = gl; + } +} +function testWebpTextureUpload(gl) { + // Edge 18 supports WebP but not uploading a WebP image to a gl texture + // Test support for this before allowing WebP images. + // https://github.com/mapbox/mapbox-gl-js/issues/7671 + const texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + try { + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, webpImgTest); + // The error does not get triggered in Edge if the context is lost + if (gl.isContextLost()) + return; + webpSupported.supported = true; + } + catch (e) { + // Catch "Unspecified Error." in Edge 18. + } + gl.deleteTexture(texture); + webpCheckComplete = true; +} + +/** + * By default, the image queue is self driven, meaning as soon as one requested item is processed, + * it will move on to next one as quickly as it can while limiting + * the number of concurrent requests to MAX_PARALLEL_IMAGE_REQUESTS. The default behavior + * ensures that static views of the map can be rendered with minimal delay. + * + * However, the default behavior can prevent dynamic views of the map from rendering + * smoothly in that many requests can finish in one render frame, putting too much pressure on GPU. + * + * When the view of the map is moving dynamically, smoother frame rates can be achieved + * by throttling the number of items processed by the queue per frame. This can be + * accomplished by using {@link addThrottleControl} to allow the caller to + * use a lambda function to determine when the queue should be throttled (e.g. when isMoving()) + * and manually calling {@link processQueue} in the render loop. + */ +var ImageRequest; +(function (ImageRequest) { + let imageRequestQueue; + let currentParallelImageRequests; + let throttleControlCallbackHandleCounter; + let throttleControlCallbacks; + /** + * Reset the image request queue, removing all pending requests. + */ + ImageRequest.resetRequestQueue = () => { + imageRequestQueue = []; + currentParallelImageRequests = 0; + throttleControlCallbackHandleCounter = 0; + throttleControlCallbacks = {}; + }; + /** + * Install a callback to control when image queue throttling is desired. + * (e.g. when the map view is moving) + * @param callback - The callback function to install + * @returns handle that identifies the installed callback. + */ + ImageRequest.addThrottleControl = (callback) => { + const handle = throttleControlCallbackHandleCounter++; + throttleControlCallbacks[handle] = callback; + return handle; + }; + /** + * Remove a previously installed callback by passing in the handle returned + * by {@link addThrottleControl}. + * @param callbackHandle - The handle for the callback to remove. + */ + ImageRequest.removeThrottleControl = (callbackHandle) => { + delete throttleControlCallbacks[callbackHandle]; + // Try updating the queue + processQueue(); + }; + /** + * Check to see if any of the installed callbacks are requesting the queue + * to be throttled. + * @returns `true` if any callback is causing the queue to be throttled. + */ + const isThrottled = () => { + for (const key of Object.keys(throttleControlCallbacks)) { + if (throttleControlCallbacks[key]()) { + return true; + } + } + return false; + }; + /** + * Request to load an image. + * @param requestParameters - Request parameters. + * @param abortController - allows to abort the request. + * @param supportImageRefresh - `true`, if the image request need to support refresh based on cache headers. + * @returns - A promise resolved when the image is loaded. + */ + ImageRequest.getImage = (requestParameters, abortController, supportImageRefresh = true) => { + return new Promise((resolve, reject) => { + if (webpSupported.supported) { + if (!requestParameters.headers) { + requestParameters.headers = {}; + } + requestParameters.headers.accept = 'image/webp,*/*'; + } + extend(requestParameters, { type: 'image' }); + const request = { + abortController, + requestParameters, + supportImageRefresh, + state: 'queued', + onError: (error) => { + reject(error); + }, + onSuccess: (response) => { + resolve(response); + } + }; + imageRequestQueue.push(request); + processQueue(); + }); + }; + const arrayBufferToCanvasImageSource = (data) => { + const imageBitmapSupported = typeof createImageBitmap === 'function'; + if (imageBitmapSupported) { + return arrayBufferToImageBitmap(data); + } + else { + return arrayBufferToImage(data); + } + }; + const doImageRequest = (itemInQueue) => __awaiter(this, void 0, void 0, function* () { + itemInQueue.state = 'running'; + const { requestParameters, supportImageRefresh, onError, onSuccess, abortController } = itemInQueue; + // - If refreshExpiredTiles is false, then we can use HTMLImageElement to download raster images. + // - Fetch/XHR (via MakeRequest API) will be used to download images for following scenarios: + // 1. Style image sprite will had a issue with HTMLImageElement as described + // here: https://github.com/mapbox/mapbox-gl-js/issues/1470 + // 2. If refreshExpiredTiles is true (default), then in order to read the image cache header, + // fetch/XHR request will be required + // - For any special case handling like use of AddProtocol, worker initiated request or additional headers + // let makeRequest handle it. + // - HtmlImageElement request automatically adds accept header for all the browser supported images + const canUseHTMLImageElement = supportImageRefresh === false && + !isWorker(self) && + !getProtocol(requestParameters.url) && + (!requestParameters.headers || + Object.keys(requestParameters.headers).reduce((acc, item) => acc && item === 'accept', true)); + currentParallelImageRequests++; + const getImagePromise = canUseHTMLImageElement ? + getImageUsingHtmlImage(requestParameters, abortController) : + makeRequest(requestParameters, abortController); + try { + const response = yield getImagePromise; + delete itemInQueue.abortController; + itemInQueue.state = 'completed'; + if (response.data instanceof HTMLImageElement || isImageBitmap(response.data)) { + // User using addProtocol can directly return HTMLImageElement/ImageBitmap type + // If HtmlImageElement is used to get image then response type will be HTMLImageElement + onSuccess(response); + } + else if (response.data) { + const img = yield arrayBufferToCanvasImageSource(response.data); + onSuccess({ data: img, cacheControl: response.cacheControl, expires: response.expires }); + } + } + catch (err) { + delete itemInQueue.abortController; + onError(err); + } + finally { + currentParallelImageRequests--; + processQueue(); + } + }); + /** + * Process some number of items in the image request queue. + */ + const processQueue = () => { + const maxImageRequests = isThrottled() ? + config.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME : + config.MAX_PARALLEL_IMAGE_REQUESTS; + // limit concurrent image loads to help with raster sources performance on big screens + for (let numImageRequests = currentParallelImageRequests; numImageRequests < maxImageRequests && imageRequestQueue.length > 0; numImageRequests++) { + const topItemInQueue = imageRequestQueue.shift(); + if (topItemInQueue.abortController.signal.aborted) { + numImageRequests--; + continue; + } + doImageRequest(topItemInQueue); + } + }; + const getImageUsingHtmlImage = (requestParameters, abortController) => { + return new Promise((resolve, reject) => { + const image = new Image(); + const url = requestParameters.url; + const credentials = requestParameters.credentials; + if (credentials && credentials === 'include') { + image.crossOrigin = 'use-credentials'; + } + else if ((credentials && credentials === 'same-origin') || !sameOrigin(url)) { + image.crossOrigin = 'anonymous'; + } + abortController.signal.addEventListener('abort', () => { + // Set src to '' to actually cancel the request + image.src = ''; + reject(createAbortError()); + }); + image.fetchPriority = 'high'; + image.onload = () => { + image.onerror = image.onload = null; + resolve({ data: image }); + }; + image.onerror = () => { + image.onerror = image.onload = null; + if (abortController.signal.aborted) { + return; + } + reject(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.')); + }; + image.src = url; + }); + }; +})(ImageRequest || (ImageRequest = {})); +ImageRequest.resetRequestQueue(); + +class RequestManager { + constructor(transformRequestFn) { + this._transformRequestFn = transformRequestFn; + } + transformRequest(url, type) { + if (this._transformRequestFn) { + return this._transformRequestFn(url, type) || { url }; + } + return { url }; + } + setTransformRequest(transformRequest) { + this._transformRequestFn = transformRequest; + } +} + +function _addEventListener(type, listener, listenerList) { + const listenerExists = listenerList[type] && listenerList[type].indexOf(listener) !== -1; + if (!listenerExists) { + listenerList[type] = listenerList[type] || []; + listenerList[type].push(listener); + } +} +function _removeEventListener(type, listener, listenerList) { + if (listenerList && listenerList[type]) { + const index = listenerList[type].indexOf(listener); + if (index !== -1) { + listenerList[type].splice(index, 1); + } + } +} +/** + * The event class + */ +class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } +} +/** + * An error event + */ +class ErrorEvent extends Event { + constructor(error, data = {}) { + super('error', extend({ error }, data)); + } +} +/** + * Methods mixed in to other classes for event capabilities. + * + * @group Event Related + */ +class Evented { + /** + * Adds a listener to a specified event type. + * + * @param type - The event type to add a listen for. + * @param listener - The function to be called when the event is fired. + * The listener function is called with the data object passed to `fire`, + * extended with `target` and `type` properties. + */ + on(type, listener) { + this._listeners = this._listeners || {}; + _addEventListener(type, listener, this._listeners); + return this; + } + /** + * Removes a previously registered event listener. + * + * @param type - The event type to remove listeners for. + * @param listener - The listener function to remove. + */ + off(type, listener) { + _removeEventListener(type, listener, this._listeners); + _removeEventListener(type, listener, this._oneTimeListeners); + return this; + } + /** + * Adds a listener that will be called only once to a specified event type. + * + * The listener will be called first time the event fires after the listener is registered. + * + * @param type - The event type to listen for. + * @param listener - The function to be called when the event is fired the first time. + * @returns `this` or a promise if a listener is not provided + */ + once(type, listener) { + if (!listener) { + return new Promise((resolve) => this.once(type, resolve)); + } + this._oneTimeListeners = this._oneTimeListeners || {}; + _addEventListener(type, listener, this._oneTimeListeners); + return this; + } + fire(event, properties) { + // Compatibility with (type: string, properties: Object) signature from previous versions. + // See https://github.com/mapbox/mapbox-gl-js/issues/6522, + // https://github.com/mapbox/mapbox-gl-draw/issues/766 + if (typeof event === 'string') { + event = new Event(event, properties || {}); + } + const type = event.type; + if (this.listens(type)) { + event.target = this; + // make sure adding or removing listeners inside other listeners won't cause an infinite loop + const listeners = this._listeners && this._listeners[type] ? this._listeners[type].slice() : []; + for (const listener of listeners) { + listener.call(this, event); + } + const oneTimeListeners = this._oneTimeListeners && this._oneTimeListeners[type] ? this._oneTimeListeners[type].slice() : []; + for (const listener of oneTimeListeners) { + _removeEventListener(type, listener, this._oneTimeListeners); + listener.call(this, event); + } + const parent = this._eventedParent; + if (parent) { + extend(event, typeof this._eventedParentData === 'function' ? this._eventedParentData() : this._eventedParentData); + parent.fire(event); + } + // To ensure that no error events are dropped, print them to the + // console if they have no listeners. + } + else if (event instanceof ErrorEvent) { + console.error(event.error); + } + return this; + } + /** + * Returns a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type. + * + * @param type - The event type + * @returns `true` if there is at least one registered listener for specified event type, `false` otherwise + */ + listens(type) { + return ((this._listeners && this._listeners[type] && this._listeners[type].length > 0) || + (this._oneTimeListeners && this._oneTimeListeners[type] && this._oneTimeListeners[type].length > 0) || + (this._eventedParent && this._eventedParent.listens(type))); + } + /** + * Bubble all events fired by this instance of Evented to this parent instance of Evented. + */ + setEventedParent(parent, data) { + this._eventedParent = parent; + this._eventedParentData = data; + return this; + } +} + +var $version = 8; +var $root = { + version: { + required: true, + type: "enum", + values: [ + 8 + ] + }, + name: { + type: "string" + }, + metadata: { + type: "*" + }, + center: { + type: "array", + value: "number" + }, + zoom: { + type: "number" + }, + bearing: { + type: "number", + "default": 0, + period: 360, + units: "degrees" + }, + pitch: { + type: "number", + "default": 0, + units: "degrees" + }, + light: { + type: "light" + }, + sky: { + type: "sky" + }, + projection: { + type: "projection" + }, + terrain: { + type: "terrain" + }, + sources: { + required: true, + type: "sources" + }, + sprite: { + type: "sprite" + }, + glyphs: { + type: "string" + }, + transition: { + type: "transition" + }, + layers: { + required: true, + type: "array", + value: "layer" + } +}; +var sources = { + "*": { + type: "source" + } +}; +var source = [ + "source_vector", + "source_raster", + "source_raster_dem", + "source_geojson", + "source_video", + "source_image" +]; +var source_vector = { + type: { + required: true, + type: "enum", + values: { + vector: { + } + } + }, + url: { + type: "string" + }, + tiles: { + type: "array", + value: "string" + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ] + }, + scheme: { + type: "enum", + values: { + xyz: { + }, + tms: { + } + }, + "default": "xyz" + }, + minzoom: { + type: "number", + "default": 0 + }, + maxzoom: { + type: "number", + "default": 22 + }, + attribution: { + type: "string" + }, + promoteId: { + type: "promoteId" + }, + volatile: { + type: "boolean", + "default": false + }, + "*": { + type: "*" + } +}; +var source_raster = { + type: { + required: true, + type: "enum", + values: { + raster: { + } + } + }, + url: { + type: "string" + }, + tiles: { + type: "array", + value: "string" + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ] + }, + minzoom: { + type: "number", + "default": 0 + }, + maxzoom: { + type: "number", + "default": 22 + }, + tileSize: { + type: "number", + "default": 512, + units: "pixels" + }, + scheme: { + type: "enum", + values: { + xyz: { + }, + tms: { + } + }, + "default": "xyz" + }, + attribution: { + type: "string" + }, + volatile: { + type: "boolean", + "default": false + }, + "*": { + type: "*" + } +}; +var source_raster_dem = { + type: { + required: true, + type: "enum", + values: { + "raster-dem": { + } + } + }, + url: { + type: "string" + }, + tiles: { + type: "array", + value: "string" + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ] + }, + minzoom: { + type: "number", + "default": 0 + }, + maxzoom: { + type: "number", + "default": 22 + }, + tileSize: { + type: "number", + "default": 512, + units: "pixels" + }, + attribution: { + type: "string" + }, + encoding: { + type: "enum", + values: { + terrarium: { + }, + mapbox: { + }, + custom: { + } + }, + "default": "mapbox" + }, + redFactor: { + type: "number", + "default": 1 + }, + blueFactor: { + type: "number", + "default": 1 + }, + greenFactor: { + type: "number", + "default": 1 + }, + baseShift: { + type: "number", + "default": 0 + }, + volatile: { + type: "boolean", + "default": false + }, + "*": { + type: "*" + } +}; +var source_geojson = { + type: { + required: true, + type: "enum", + values: { + geojson: { + } + } + }, + data: { + required: true, + type: "*" + }, + maxzoom: { + type: "number", + "default": 18 + }, + attribution: { + type: "string" + }, + buffer: { + type: "number", + "default": 128, + maximum: 512, + minimum: 0 + }, + filter: { + type: "*" + }, + tolerance: { + type: "number", + "default": 0.375 + }, + cluster: { + type: "boolean", + "default": false + }, + clusterRadius: { + type: "number", + "default": 50, + minimum: 0 + }, + clusterMaxZoom: { + type: "number" + }, + clusterMinPoints: { + type: "number" + }, + clusterProperties: { + type: "*" + }, + lineMetrics: { + type: "boolean", + "default": false + }, + generateId: { + type: "boolean", + "default": false + }, + promoteId: { + type: "promoteId" + } +}; +var source_video = { + type: { + required: true, + type: "enum", + values: { + video: { + } + } + }, + urls: { + required: true, + type: "array", + value: "string" + }, + coordinates: { + required: true, + type: "array", + length: 4, + value: { + type: "array", + length: 2, + value: "number" + } + } +}; +var source_image = { + type: { + required: true, + type: "enum", + values: { + image: { + } + } + }, + url: { + required: true, + type: "string" + }, + coordinates: { + required: true, + type: "array", + length: 4, + value: { + type: "array", + length: 2, + value: "number" + } + } +}; +var layer = { + id: { + type: "string", + required: true + }, + type: { + type: "enum", + values: { + fill: { + }, + line: { + }, + symbol: { + }, + circle: { + }, + heatmap: { + }, + "fill-extrusion": { + }, + raster: { + }, + hillshade: { + }, + background: { + } + }, + required: true + }, + metadata: { + type: "*" + }, + source: { + type: "string" + }, + "source-layer": { + type: "string" + }, + minzoom: { + type: "number", + minimum: 0, + maximum: 24 + }, + maxzoom: { + type: "number", + minimum: 0, + maximum: 24 + }, + filter: { + type: "filter" + }, + layout: { + type: "layout" + }, + paint: { + type: "paint" + } +}; +var layout$7 = [ + "layout_fill", + "layout_line", + "layout_circle", + "layout_heatmap", + "layout_fill-extrusion", + "layout_symbol", + "layout_raster", + "layout_hillshade", + "layout_background" +]; +var layout_background = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_fill = { + "fill-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_circle = { + "circle-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_heatmap = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_line = { + "line-cap": { + type: "enum", + values: { + butt: { + }, + round: { + }, + square: { + } + }, + "default": "butt", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-join": { + type: "enum", + values: { + bevel: { + }, + round: { + }, + miter: { + } + }, + "default": "miter", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "line-miter-limit": { + type: "number", + "default": 2, + requires: [ + { + "line-join": "miter" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-round-limit": { + type: "number", + "default": 1.05, + requires: [ + { + "line-join": "round" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_symbol = { + "symbol-placement": { + type: "enum", + values: { + point: { + }, + line: { + }, + "line-center": { + } + }, + "default": "point", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-spacing": { + type: "number", + "default": 250, + minimum: 1, + units: "pixels", + requires: [ + { + "symbol-placement": "line" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-avoid-edges": { + type: "boolean", + "default": false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "symbol-z-order": { + type: "enum", + values: { + auto: { + }, + "viewport-y": { + }, + source: { + } + }, + "default": "auto", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-allow-overlap": { + type: "boolean", + "default": false, + requires: [ + "icon-image", + { + "!": "icon-overlap" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-overlap": { + type: "enum", + values: { + never: { + }, + always: { + }, + cooperative: { + } + }, + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-ignore-placement": { + type: "boolean", + "default": false, + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-optional": { + type: "boolean", + "default": false, + requires: [ + "icon-image", + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-rotation-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-size": { + type: "number", + "default": 1, + minimum: 0, + units: "factor of the original icon size", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-text-fit": { + type: "enum", + values: { + none: { + }, + width: { + }, + height: { + }, + both: { + } + }, + "default": "none", + requires: [ + "icon-image", + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-text-fit-padding": { + type: "array", + value: "number", + length: 4, + "default": [ + 0, + 0, + 0, + 0 + ], + units: "pixels", + requires: [ + "icon-image", + "text-field", + { + "icon-text-fit": [ + "both", + "width", + "height" + ] + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-image": { + type: "resolvedImage", + tokens: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-rotate": { + type: "number", + "default": 0, + period: 360, + units: "degrees", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-padding": { + type: "padding", + "default": [ + 2 + ], + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-keep-upright": { + type: "boolean", + "default": false, + requires: [ + "icon-image", + { + "icon-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-offset": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-anchor": { + type: "enum", + values: { + center: { + }, + left: { + }, + right: { + }, + top: { + }, + bottom: { + }, + "top-left": { + }, + "top-right": { + }, + "bottom-left": { + }, + "bottom-right": { + } + }, + "default": "center", + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-pitch-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-pitch-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotation-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + "viewport-glyph": { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-field": { + type: "formatted", + "default": "", + tokens: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-font": { + type: "array", + value: "string", + "default": [ + "Open Sans Regular", + "Arial Unicode MS Regular" + ], + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-size": { + type: "number", + "default": 16, + minimum: 0, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-width": { + type: "number", + "default": 10, + minimum: 0, + units: "ems", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-line-height": { + type: "number", + "default": 1.2, + units: "ems", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-letter-spacing": { + type: "number", + "default": 0, + units: "ems", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-justify": { + type: "enum", + values: { + auto: { + }, + left: { + }, + center: { + }, + right: { + } + }, + "default": "center", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-radial-offset": { + type: "number", + units: "ems", + "default": 0, + requires: [ + "text-field" + ], + "property-type": "data-driven", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + } + }, + "text-variable-anchor": { + type: "array", + value: "enum", + values: { + center: { + }, + left: { + }, + right: { + }, + top: { + }, + bottom: { + }, + "top-left": { + }, + "top-right": { + }, + "bottom-left": { + }, + "bottom-right": { + } + }, + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-variable-anchor-offset": { + type: "variableAnchorOffsetCollection", + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-anchor": { + type: "enum", + values: { + center: { + }, + left: { + }, + right: { + }, + top: { + }, + bottom: { + }, + "top-left": { + }, + "top-right": { + }, + "bottom-left": { + }, + "bottom-right": { + } + }, + "default": "center", + requires: [ + "text-field", + { + "!": "text-variable-anchor" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-angle": { + type: "number", + "default": 45, + units: "degrees", + requires: [ + "text-field", + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-writing-mode": { + type: "array", + value: "enum", + values: { + horizontal: { + }, + vertical: { + } + }, + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotate": { + type: "number", + "default": 0, + period: 360, + units: "degrees", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-padding": { + type: "number", + "default": 2, + minimum: 0, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-keep-upright": { + type: "boolean", + "default": true, + requires: [ + "text-field", + { + "text-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-transform": { + type: "enum", + values: { + none: { + }, + uppercase: { + }, + lowercase: { + } + }, + "default": "none", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-offset": { + type: "array", + value: "number", + units: "ems", + length: 2, + "default": [ + 0, + 0 + ], + requires: [ + "text-field", + { + "!": "text-radial-offset" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-allow-overlap": { + type: "boolean", + "default": false, + requires: [ + "text-field", + { + "!": "text-overlap" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-overlap": { + type: "enum", + values: { + never: { + }, + always: { + }, + cooperative: { + } + }, + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-ignore-placement": { + type: "boolean", + "default": false, + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-optional": { + type: "boolean", + "default": false, + requires: [ + "text-field", + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_raster = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_hillshade = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var filter = { + type: "array", + value: "*" +}; +var filter_operator = { + type: "enum", + values: { + "==": { + }, + "!=": { + }, + ">": { + }, + ">=": { + }, + "<": { + }, + "<=": { + }, + "in": { + }, + "!in": { + }, + all: { + }, + any: { + }, + none: { + }, + has: { + }, + "!has": { + } + } +}; +var geometry_type = { + type: "enum", + values: { + Point: { + }, + LineString: { + }, + Polygon: { + } + } +}; +var function_stop = { + type: "array", + minimum: 0, + maximum: 24, + value: [ + "number", + "color" + ], + length: 2 +}; +var expression$1 = { + type: "array", + value: "*", + minimum: 1 +}; +var light = { + anchor: { + type: "enum", + "default": "viewport", + values: { + map: { + }, + viewport: { + } + }, + "property-type": "data-constant", + transition: false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + } + }, + position: { + type: "array", + "default": [ + 1.15, + 210, + 30 + ], + length: 3, + value: "number", + "property-type": "data-constant", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + } + }, + color: { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + intensity: { + type: "number", + "property-type": "data-constant", + "default": 0.5, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + } +}; +var sky = { + "sky-color": { + type: "color", + "property-type": "data-constant", + "default": "#88C6FC", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "horizon-color": { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "fog-color": { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "fog-ground-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.5, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "horizon-fog-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.8, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "sky-horizon-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.8, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "atmosphere-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.8, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + } +}; +var terrain = { + source: { + type: "string", + required: true + }, + exaggeration: { + type: "number", + minimum: 0, + "default": 1 + } +}; +var projection$1 = { + type: { + type: "enum", + "default": "mercator", + values: { + mercator: { + }, + globe: { + } + } + } +}; +var paint$9 = [ + "paint_fill", + "paint_line", + "paint_circle", + "paint_heatmap", + "paint_fill-extrusion", + "paint_symbol", + "paint_raster", + "paint_hillshade", + "paint_background" +]; +var paint_fill = { + "fill-antialias": { + type: "boolean", + "default": true, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "fill-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-outline-color": { + type: "color", + transition: true, + requires: [ + { + "!": "fill-pattern" + }, + { + "fill-antialias": true + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "fill-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + } +}; +var paint_line = { + "line-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "line-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "line-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-width": { + type: "number", + "default": 1, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-gap-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-offset": { + type: "number", + "default": 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-dasharray": { + type: "array", + value: "number", + minimum: 0, + transition: true, + units: "line widths", + requires: [ + { + "!": "line-pattern" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "line-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "line-gradient": { + type: "color", + transition: false, + requires: [ + { + "!": "line-dasharray" + }, + { + "!": "line-pattern" + }, + { + source: "geojson", + has: { + lineMetrics: true + } + } + ], + expression: { + interpolated: true, + parameters: [ + "line-progress" + ] + }, + "property-type": "color-ramp" + } +}; +var paint_circle = { + "circle-radius": { + type: "number", + "default": 5, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-blur": { + type: "number", + "default": 0, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "circle-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-scale": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "viewport", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-stroke-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + } +}; +var paint_heatmap = { + "heatmap-radius": { + type: "number", + "default": 30, + minimum: 1, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-weight": { + type: "number", + "default": 1, + minimum: 0, + transition: false, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-intensity": { + type: "number", + "default": 1, + minimum: 0, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "heatmap-color": { + type: "color", + "default": [ + "interpolate", + [ + "linear" + ], + [ + "heatmap-density" + ], + 0, + "rgba(0, 0, 255, 0)", + 0.1, + "royalblue", + 0.3, + "cyan", + 0.5, + "lime", + 0.7, + "yellow", + 1, + "red" + ], + transition: false, + expression: { + interpolated: true, + parameters: [ + "heatmap-density" + ] + }, + "property-type": "color-ramp" + }, + "heatmap-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_symbol = { + "icon-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-color": { + type: "color", + "default": "rgba(0, 0, 0, 0)", + transition: true, + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "icon-image", + "icon-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-color": { + type: "color", + "default": "#000000", + transition: true, + overridable: true, + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-color": { + type: "color", + "default": "rgba(0, 0, 0, 0)", + transition: true, + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "text-field", + "text-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_raster = { + "raster-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-hue-rotate": { + type: "number", + "default": 0, + period: 360, + transition: true, + units: "degrees", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-min": { + type: "number", + "default": 0, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-max": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-saturation": { + type: "number", + "default": 0, + minimum: -1, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-contrast": { + type: "number", + "default": 0, + minimum: -1, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-resampling": { + type: "enum", + values: { + linear: { + }, + nearest: { + } + }, + "default": "linear", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-fade-duration": { + type: "number", + "default": 300, + minimum: 0, + transition: false, + units: "milliseconds", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_hillshade = { + "hillshade-illumination-direction": { + type: "number", + "default": 335, + minimum: 0, + maximum: 359, + transition: false, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-illumination-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "viewport", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-exaggeration": { + type: "number", + "default": 0.5, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-shadow-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-highlight-color": { + type: "color", + "default": "#FFFFFF", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-accent-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_background = { + "background-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "background-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "background-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "background-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var transition = { + duration: { + type: "number", + "default": 300, + minimum: 0, + units: "milliseconds" + }, + delay: { + type: "number", + "default": 0, + minimum: 0, + units: "milliseconds" + } +}; +var promoteId = { + "*": { + type: "string" + } +}; +var v8Spec = { + $version: $version, + $root: $root, + sources: sources, + source: source, + source_vector: source_vector, + source_raster: source_raster, + source_raster_dem: source_raster_dem, + source_geojson: source_geojson, + source_video: source_video, + source_image: source_image, + layer: layer, + layout: layout$7, + layout_background: layout_background, + layout_fill: layout_fill, + layout_circle: layout_circle, + layout_heatmap: layout_heatmap, + "layout_fill-extrusion": { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}, + layout_line: layout_line, + layout_symbol: layout_symbol, + layout_raster: layout_raster, + layout_hillshade: layout_hillshade, + filter: filter, + filter_operator: filter_operator, + geometry_type: geometry_type, + "function": { + expression: { + type: "expression" + }, + stops: { + type: "array", + value: "function_stop" + }, + base: { + type: "number", + "default": 1, + minimum: 0 + }, + property: { + type: "string", + "default": "$zoom" + }, + type: { + type: "enum", + values: { + identity: { + }, + exponential: { + }, + interval: { + }, + categorical: { + } + }, + "default": "exponential" + }, + colorSpace: { + type: "enum", + values: { + rgb: { + }, + lab: { + }, + hcl: { + } + }, + "default": "rgb" + }, + "default": { + type: "*", + required: false + } +}, + function_stop: function_stop, + expression: expression$1, + light: light, + sky: sky, + terrain: terrain, + projection: projection$1, + paint: paint$9, + paint_fill: paint_fill, + "paint_fill-extrusion": { + "fill-extrusion-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "fill-extrusion-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "fill-extrusion-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "fill-extrusion-height": { + type: "number", + "default": 0, + minimum: 0, + units: "meters", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-base": { + type: "number", + "default": 0, + minimum: 0, + units: "meters", + transition: true, + requires: [ + "fill-extrusion-height" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-vertical-gradient": { + type: "boolean", + "default": true, + transition: false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}, + paint_line: paint_line, + paint_circle: paint_circle, + paint_heatmap: paint_heatmap, + paint_symbol: paint_symbol, + paint_raster: paint_raster, + paint_hillshade: paint_hillshade, + paint_background: paint_background, + transition: transition, + "property-type": { + "data-driven": { + type: "property-type" + }, + "cross-faded": { + type: "property-type" + }, + "cross-faded-data-driven": { + type: "property-type" + }, + "color-ramp": { + type: "property-type" + }, + "data-constant": { + type: "property-type" + }, + constant: { + type: "property-type" + } +}, + promoteId: promoteId +}; + +const refProperties = ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout']; + +function deref(layer, parent) { + const result = {}; + for (const k in layer) { + if (k !== 'ref') { + result[k] = layer[k]; + } + } + refProperties.forEach((k) => { + if (k in parent) { + result[k] = parent[k]; + } + }); + return result; +} +/** + * Given an array of layers, some of which may contain `ref` properties + * whose value is the `id` of another property, return a new array where + * such layers have been augmented with the 'type', 'source', etc. properties + * from the parent layer, and the `ref` property has been removed. + * + * The input is not modified. The output may contain references to portions + * of the input. + * + * @private + * @param {Array} layers + * @returns {Array} + */ +function derefLayers(layers) { + layers = layers.slice(); + const map = Object.create(null); + for (let i = 0; i < layers.length; i++) { + map[layers[i].id] = layers[i]; + } + for (let i = 0; i < layers.length; i++) { + if ('ref' in layers[i]) { + layers[i] = deref(layers[i], map[layers[i].ref]); + } + } + return layers; +} + +/** + * Deeply compares two object literals. + * + * @private + */ +function deepEqual(a, b) { + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) { + if (!deepEqual(a[i], b[i])) + return false; + } + return true; + } + if (typeof a === 'object' && a !== null && b !== null) { + if (!(typeof b === 'object')) + return false; + const keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) + return false; + for (const key in a) { + if (!deepEqual(a[key], b[key])) + return false; + } + return true; + } + return a === b; +} + +/** + * The main reason for this method is to allow type check when adding a command to the array. + * @param commands - The commands array to add to + * @param command - The command to add + */ +function addCommand(commands, command) { + commands.push(command); +} +function addSource(sourceId, after, commands) { + addCommand(commands, { command: 'addSource', args: [sourceId, after[sourceId]] }); +} +function removeSource(sourceId, commands, sourcesRemoved) { + addCommand(commands, { command: 'removeSource', args: [sourceId] }); + sourcesRemoved[sourceId] = true; +} +function updateSource(sourceId, after, commands, sourcesRemoved) { + removeSource(sourceId, commands, sourcesRemoved); + addSource(sourceId, after, commands); +} +function canUpdateGeoJSON(before, after, sourceId) { + let prop; + for (prop in before[sourceId]) { + if (!Object.prototype.hasOwnProperty.call(before[sourceId], prop)) + continue; + if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + for (prop in after[sourceId]) { + if (!Object.prototype.hasOwnProperty.call(after[sourceId], prop)) + continue; + if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + return true; +} +function diffSources(before, after, commands, sourcesRemoved) { + before = before || {}; + after = after || {}; + let sourceId; + // look for sources to remove + for (sourceId in before) { + if (!Object.prototype.hasOwnProperty.call(before, sourceId)) + continue; + if (!Object.prototype.hasOwnProperty.call(after, sourceId)) { + removeSource(sourceId, commands, sourcesRemoved); + } + } + // look for sources to add/update + for (sourceId in after) { + if (!Object.prototype.hasOwnProperty.call(after, sourceId)) + continue; + if (!Object.prototype.hasOwnProperty.call(before, sourceId)) { + addSource(sourceId, after, commands); + } + else if (!deepEqual(before[sourceId], after[sourceId])) { + if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) { + addCommand(commands, { command: 'setGeoJSONSourceData', args: [sourceId, after[sourceId].data] }); + } + else { + // no update command, must remove then add + updateSource(sourceId, after, commands, sourcesRemoved); + } + } + } +} +function diffLayerPropertyChanges(before, after, commands, layerId, klass, command) { + before = before || {}; + after = after || {}; + for (const prop in before) { + if (!Object.prototype.hasOwnProperty.call(before, prop)) + continue; + if (!deepEqual(before[prop], after[prop])) { + commands.push({ command, args: [layerId, prop, after[prop], klass] }); + } + } + for (const prop in after) { + if (!Object.prototype.hasOwnProperty.call(after, prop) || Object.prototype.hasOwnProperty.call(before, prop)) + continue; + if (!deepEqual(before[prop], after[prop])) { + commands.push({ command, args: [layerId, prop, after[prop], klass] }); + } + } +} +function pluckId(layer) { + return layer.id; +} +function indexById(group, layer) { + group[layer.id] = layer; + return group; +} +function diffLayers(before, after, commands) { + before = before || []; + after = after || []; + // order of layers by id + const beforeOrder = before.map(pluckId); + const afterOrder = after.map(pluckId); + // index of layer by id + const beforeIndex = before.reduce(indexById, {}); + const afterIndex = after.reduce(indexById, {}); + // track order of layers as if they have been mutated + const tracker = beforeOrder.slice(); + // layers that have been added do not need to be diffed + const clean = Object.create(null); + let layerId; + let beforeLayer; + let afterLayer; + let insertBeforeLayerId; + let prop; + // remove layers + for (let i = 0, d = 0; i < beforeOrder.length; i++) { + layerId = beforeOrder[i]; + if (!Object.prototype.hasOwnProperty.call(afterIndex, layerId)) { + addCommand(commands, { command: 'removeLayer', args: [layerId] }); + tracker.splice(tracker.indexOf(layerId, d), 1); + } + else { + // limit where in tracker we need to look for a match + d++; + } + } + // add/reorder layers + for (let i = 0, d = 0; i < afterOrder.length; i++) { + // work backwards as insert is before an existing layer + layerId = afterOrder[afterOrder.length - 1 - i]; + if (tracker[tracker.length - 1 - i] === layerId) + continue; + if (Object.prototype.hasOwnProperty.call(beforeIndex, layerId)) { + // remove the layer before we insert at the correct position + addCommand(commands, { command: 'removeLayer', args: [layerId] }); + tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1); + } + else { + // limit where in tracker we need to look for a match + d++; + } + // add layer at correct position + insertBeforeLayerId = tracker[tracker.length - i]; + addCommand(commands, { command: 'addLayer', args: [afterIndex[layerId], insertBeforeLayerId] }); + tracker.splice(tracker.length - i, 0, layerId); + clean[layerId] = true; + } + // update layers + for (let i = 0; i < afterOrder.length; i++) { + layerId = afterOrder[i]; + beforeLayer = beforeIndex[layerId]; + afterLayer = afterIndex[layerId]; + // no need to update if previously added (new or moved) + if (clean[layerId] || deepEqual(beforeLayer, afterLayer)) + continue; + // If source, source-layer, or type have changes, then remove the layer + // and add it back 'from scratch'. + if (!deepEqual(beforeLayer.source, afterLayer.source) || !deepEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !deepEqual(beforeLayer.type, afterLayer.type)) { + addCommand(commands, { command: 'removeLayer', args: [layerId] }); + // we add the layer back at the same position it was already in, so + // there's no need to update the `tracker` + insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1]; + addCommand(commands, { command: 'addLayer', args: [afterLayer, insertBeforeLayerId] }); + continue; + } + // layout, paint, filter, minzoom, maxzoom + diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, 'setLayoutProperty'); + diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, 'setPaintProperty'); + if (!deepEqual(beforeLayer.filter, afterLayer.filter)) { + addCommand(commands, { command: 'setFilter', args: [layerId, afterLayer.filter] }); + } + if (!deepEqual(beforeLayer.minzoom, afterLayer.minzoom) || !deepEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) { + addCommand(commands, { command: 'setLayerZoomRange', args: [layerId, afterLayer.minzoom, afterLayer.maxzoom] }); + } + // handle all other layer props, including paint.* + for (prop in beforeLayer) { + if (!Object.prototype.hasOwnProperty.call(beforeLayer, prop)) + continue; + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || + prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') + continue; + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), 'setPaintProperty'); + } + else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) { + addCommand(commands, { command: 'setLayerProperty', args: [layerId, prop, afterLayer[prop]] }); + } + } + for (prop in afterLayer) { + if (!Object.prototype.hasOwnProperty.call(afterLayer, prop) || Object.prototype.hasOwnProperty.call(beforeLayer, prop)) + continue; + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || + prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') + continue; + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), 'setPaintProperty'); + } + else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) { + addCommand(commands, { command: 'setLayerProperty', args: [layerId, prop, afterLayer[prop]] }); + } + } + } +} +/** + * Diff two stylesheet + * + * Creates semanticly aware diffs that can easily be applied at runtime. + * Operations produced by the diff closely resemble the maplibre-gl-js API. Any + * error creating the diff will fall back to the 'setStyle' operation. + * + * Example diff: + * [ + * { command: 'setConstant', args: ['@water', '#0000FF'] }, + * { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] } + * ] + * + * @private + * @param {*} [before] stylesheet to compare from + * @param {*} after stylesheet to compare to + * @returns Array list of changes + */ +function diffStyles(before, after) { + if (!before) + return [{ command: 'setStyle', args: [after] }]; + let commands = []; + try { + // Handle changes to top-level properties + if (!deepEqual(before.version, after.version)) { + return [{ command: 'setStyle', args: [after] }]; + } + if (!deepEqual(before.center, after.center)) { + commands.push({ command: 'setCenter', args: [after.center] }); + } + if (!deepEqual(before.zoom, after.zoom)) { + commands.push({ command: 'setZoom', args: [after.zoom] }); + } + if (!deepEqual(before.bearing, after.bearing)) { + commands.push({ command: 'setBearing', args: [after.bearing] }); + } + if (!deepEqual(before.pitch, after.pitch)) { + commands.push({ command: 'setPitch', args: [after.pitch] }); + } + if (!deepEqual(before.sprite, after.sprite)) { + commands.push({ command: 'setSprite', args: [after.sprite] }); + } + if (!deepEqual(before.glyphs, after.glyphs)) { + commands.push({ command: 'setGlyphs', args: [after.glyphs] }); + } + if (!deepEqual(before.transition, after.transition)) { + commands.push({ command: 'setTransition', args: [after.transition] }); + } + if (!deepEqual(before.light, after.light)) { + commands.push({ command: 'setLight', args: [after.light] }); + } + if (!deepEqual(before.terrain, after.terrain)) { + commands.push({ command: 'setTerrain', args: [after.terrain] }); + } + if (!deepEqual(before.sky, after.sky)) { + commands.push({ command: 'setSky', args: [after.sky] }); + } + if (!deepEqual(before.projection, after.projection)) { + commands.push({ command: 'setProjection', args: [after.projection] }); + } + // Handle changes to `sources` + // If a source is to be removed, we also--before the removeSource + // command--need to remove all the style layers that depend on it. + const sourcesRemoved = {}; + // First collect the {add,remove}Source commands + const removeOrAddSourceCommands = []; + diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved); + // Push a removeLayer command for each style layer that depends on a + // source that's being removed. + // Also, exclude any such layers them from the input to `diffLayers` + // below, so that diffLayers produces the appropriate `addLayers` + // command + const beforeLayers = []; + if (before.layers) { + before.layers.forEach((layer) => { + if ('source' in layer && sourcesRemoved[layer.source]) { + commands.push({ command: 'removeLayer', args: [layer.id] }); + } + else { + beforeLayers.push(layer); + } + }); + } + commands = commands.concat(removeOrAddSourceCommands); + // Handle changes to `layers` + diffLayers(beforeLayers, after.layers, commands); + } + catch (e) { + // fall back to setStyle + console.warn('Unable to compute style diff:', e); + commands = [{ command: 'setStyle', args: [after] }]; + } + return commands; +} + +// Note: Do not inherit from Error. It breaks when transpiling to ES5. +class ValidationError { + constructor(key, value, message, identifier) { + this.message = (key ? `${key}: ` : '') + message; + if (identifier) + this.identifier = identifier; + if (value !== null && value !== undefined && value.__line__) { + this.line = value.__line__; + } + } +} + +// Note: Do not inherit from Error. It breaks when transpiling to ES5. +class ParsingError { + constructor(error) { + this.error = error; + this.message = error.message; + const match = error.message.match(/line (\d+)/); + this.line = match ? parseInt(match[1], 10) : 0; + } +} + +function extendBy(output, ...inputs) { + for (const input of inputs) { + for (const k in input) { + output[k] = input[k]; + } + } + return output; +} + +class ExpressionParsingError extends Error { + constructor(key, message) { + super(message); + this.message = message; + this.key = key; + } +} + +/** + * Tracks `let` bindings during expression parsing. + * @private + */ +class Scope { + constructor(parent, bindings = []) { + this.parent = parent; + this.bindings = {}; + for (const [name, expression] of bindings) { + this.bindings[name] = expression; + } + } + concat(bindings) { + return new Scope(this, bindings); + } + get(name) { + if (this.bindings[name]) { + return this.bindings[name]; + } + if (this.parent) { + return this.parent.get(name); + } + throw new Error(`${name} not found in scope.`); + } + has(name) { + if (this.bindings[name]) + return true; + return this.parent ? this.parent.has(name) : false; + } +} + +const NullType = { kind: 'null' }; +const NumberType = { kind: 'number' }; +const StringType = { kind: 'string' }; +const BooleanType = { kind: 'boolean' }; +const ColorType = { kind: 'color' }; +const ObjectType = { kind: 'object' }; +const ValueType = { kind: 'value' }; +const ErrorType = { kind: 'error' }; +const CollatorType = { kind: 'collator' }; +const FormattedType = { kind: 'formatted' }; +const PaddingType = { kind: 'padding' }; +const ResolvedImageType = { kind: 'resolvedImage' }; +const VariableAnchorOffsetCollectionType = { kind: 'variableAnchorOffsetCollection' }; +function array$1(itemType, N) { + return { + kind: 'array', + itemType, + N + }; +} +function toString$1(type) { + if (type.kind === 'array') { + const itemType = toString$1(type.itemType); + return typeof type.N === 'number' ? + `array<${itemType}, ${type.N}>` : + type.itemType.kind === 'value' ? 'array' : `array<${itemType}>`; + } + else { + return type.kind; + } +} +const valueMemberTypes = [ + NullType, + NumberType, + StringType, + BooleanType, + ColorType, + FormattedType, + ObjectType, + array$1(ValueType), + PaddingType, + ResolvedImageType, + VariableAnchorOffsetCollectionType +]; +/** + * Returns null if `t` is a subtype of `expected`; otherwise returns an + * error message. + * @private + */ +function checkSubtype(expected, t) { + if (t.kind === 'error') { + // Error is a subtype of every type + return null; + } + else if (expected.kind === 'array') { + if (t.kind === 'array' && + ((t.N === 0 && t.itemType.kind === 'value') || !checkSubtype(expected.itemType, t.itemType)) && + (typeof expected.N !== 'number' || expected.N === t.N)) { + return null; + } + } + else if (expected.kind === t.kind) { + return null; + } + else if (expected.kind === 'value') { + for (const memberType of valueMemberTypes) { + if (!checkSubtype(memberType, t)) { + return null; + } + } + } + return `Expected ${toString$1(expected)} but found ${toString$1(t)} instead.`; +} +function isValidType(provided, allowedTypes) { + return allowedTypes.some(t => t.kind === provided.kind); +} +function isValidNativeType(provided, allowedTypes) { + return allowedTypes.some(t => { + if (t === 'null') { + return provided === null; + } + else if (t === 'array') { + return Array.isArray(provided); + } + else if (t === 'object') { + return provided && !Array.isArray(provided) && typeof provided === 'object'; + } + else { + return t === typeof provided; + } + }); +} +/** + * Verify whether the specified type is of the same type as the specified sample. + * + * @param provided Type to verify + * @param sample Sample type to reference + * @returns `true` if both objects are of the same type, `false` otherwise + * @example basic types + * if (verifyType(outputType, ValueType)) { + * // type narrowed to: + * outputType.kind; // 'value' + * } + * @example array types + * if (verifyType(outputType, array(NumberType))) { + * // type narrowed to: + * outputType.kind; // 'array' + * outputType.itemType; // NumberTypeT + * outputType.itemType.kind; // 'number' + * } + */ +function verifyType(provided, sample) { + if (provided.kind === 'array' && sample.kind === 'array') { + return provided.itemType.kind === sample.itemType.kind && typeof provided.N === 'number'; + } + return provided.kind === sample.kind; +} + +// See https://observablehq.com/@mbostock/lab-and-rgb +const Xn = 0.96422, Yn = 1, Zn = 0.82521, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1, deg2rad = Math.PI / 180, rad2deg = 180 / Math.PI; +function constrainAngle(angle) { + angle = angle % 360; + if (angle < 0) { + angle += 360; + } + return angle; +} +function rgbToLab([r, g, b, alpha]) { + r = rgb2xyz(r); + g = rgb2xyz(g); + b = rgb2xyz(b); + let x, z; + const y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn); + if (r === g && g === b) { + x = z = y; + } + else { + x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn); + z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn); + } + const l = 116 * y - 16; + return [(l < 0) ? 0 : l, 500 * (x - y), 200 * (y - z), alpha]; +} +function rgb2xyz(x) { + return (x <= 0.04045) ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); +} +function xyz2lab(t) { + return (t > t3) ? Math.pow(t, 1 / 3) : t / t2 + t0; +} +function labToRgb([l, a, b, alpha]) { + let y = (l + 16) / 116, x = isNaN(a) ? y : y + a / 500, z = isNaN(b) ? y : y - b / 200; + y = Yn * lab2xyz(y); + x = Xn * lab2xyz(x); + z = Zn * lab2xyz(z); + return [ + xyz2rgb(3.1338561 * x - 1.6168667 * y - 0.4906146 * z), // D50 -> sRGB + xyz2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z), + xyz2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z), + alpha, + ]; +} +function xyz2rgb(x) { + x = (x <= 0.00304) ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055; + return (x < 0) ? 0 : (x > 1) ? 1 : x; // clip to 0..1 range +} +function lab2xyz(t) { + return (t > t1) ? t * t * t : t2 * (t - t0); +} +function rgbToHcl(rgbColor) { + const [l, a, b, alpha] = rgbToLab(rgbColor); + const c = Math.sqrt(a * a + b * b); + const h = Math.round(c * 10000) ? constrainAngle(Math.atan2(b, a) * rad2deg) : NaN; + return [h, c, l, alpha]; +} +function hclToRgb([h, c, l, alpha]) { + h = isNaN(h) ? 0 : h * deg2rad; + return labToRgb([l, Math.cos(h) * c, Math.sin(h) * c, alpha]); +} +// https://drafts.csswg.org/css-color-4/#hsl-to-rgb +function hslToRgb([h, s, l, alpha]) { + h = constrainAngle(h); + s /= 100; + l /= 100; + function f(n) { + const k = (n + h / 30) % 12; + const a = s * Math.min(l, 1 - l); + return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); + } + return [f(0), f(8), f(4), alpha]; +} + +/** + * CSS color parser compliant with CSS Color 4 Specification. + * Supports: named colors, `transparent` keyword, all rgb hex notations, + * rgb(), rgba(), hsl() and hsla() functions. + * Does not round the parsed values to integers from the range 0..255. + * + * Syntax: + * + * = | + * = | + * + * rgb() = rgb( {3} [ / ]? ) | rgb( {3} [ / ]? ) + * rgb() = rgb( #{3} , ? ) | rgb( #{3} , ? ) + * + * hsl() = hsl( [ / ]? ) + * hsl() = hsl( , , , ? ) + * + * Caveats: + * - - with optional `deg` suffix; `grad`, `rad`, `turn` are not supported + * - `none` keyword is not supported + * - comments inside rgb()/hsl() are not supported + * - legacy color syntax rgba() is supported with an identical grammar and behavior to rgb() + * - legacy color syntax hsla() is supported with an identical grammar and behavior to hsl() + * + * @param input CSS color string to parse. + * @returns Color in sRGB color space, with `red`, `green`, `blue` + * and `alpha` channels normalized to the range 0..1, + * or `undefined` if the input is not a valid color string. + */ +function parseCssColor(input) { + input = input.toLowerCase().trim(); + if (input === 'transparent') { + return [0, 0, 0, 0]; + } + // 'white', 'black', 'blue' + const namedColorsMatch = namedColors[input]; + if (namedColorsMatch) { + const [r, g, b] = namedColorsMatch; + return [r / 255, g / 255, b / 255, 1]; + } + // #f0c, #f0cf, #ff00cc, #ff00ccff + if (input.startsWith('#')) { + const hexRegexp = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/; + if (hexRegexp.test(input)) { + const step = input.length < 6 ? 1 : 2; + let i = 1; + return [ + parseHex(input.slice(i, i += step)), + parseHex(input.slice(i, i += step)), + parseHex(input.slice(i, i += step)), + parseHex(input.slice(i, i + step) || 'ff'), + ]; + } + } + // rgb(128 0 0), rgb(50% 0% 0%), rgba(255,0,255,0.6), rgb(255 0 255 / 60%), rgb(100% 0% 100% /.6) + if (input.startsWith('rgb')) { + const rgbRegExp = /^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/; + const rgbMatch = input.match(rgbRegExp); + if (rgbMatch) { + const [_, // eslint-disable-line @typescript-eslint/no-unused-vars + r, // + rp, // % (optional) + f1, // , (optional) + g, // + gp, // % (optional) + f2, // , (optional) + b, // + bp, // % (optional) + f3, // ,|/ (optional) + a, // (optional) + ap, // % (optional) + ] = rgbMatch; + const argFormat = [f1 || ' ', f2 || ' ', f3].join(''); + if (argFormat === ' ' || + argFormat === ' /' || + argFormat === ',,' || + argFormat === ',,,') { + const valFormat = [rp, gp, bp].join(''); + const maxValue = (valFormat === '%%%') ? 100 : + (valFormat === '') ? 255 : 0; + if (maxValue) { + const rgba = [ + clamp(+r / maxValue, 0, 1), + clamp(+g / maxValue, 0, 1), + clamp(+b / maxValue, 0, 1), + a ? parseAlpha(+a, ap) : 1, + ]; + if (validateNumbers(rgba)) { + return rgba; + } + // invalid numbers + } + // values must be all numbers or all percentages + } + return; // comma optional syntax requires no commas at all + } + } + // hsl(120 50% 80%), hsla(120deg,50%,80%,.9), hsl(12e1 50% 80% / 90%) + const hslRegExp = /^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/; + const hslMatch = input.match(hslRegExp); + if (hslMatch) { + const [_, // eslint-disable-line @typescript-eslint/no-unused-vars + h, // + f1, // , (optional) + s, // + f2, // , (optional) + l, // + f3, // ,|/ (optional) + a, // (optional) + ap, // % (optional) + ] = hslMatch; + const argFormat = [f1 || ' ', f2 || ' ', f3].join(''); + if (argFormat === ' ' || + argFormat === ' /' || + argFormat === ',,' || + argFormat === ',,,') { + const hsla = [ + +h, + clamp(+s, 0, 100), + clamp(+l, 0, 100), + a ? parseAlpha(+a, ap) : 1, + ]; + if (validateNumbers(hsla)) { + return hslToRgb(hsla); + } + // invalid numbers + } + // comma optional syntax requires no commas at all + } +} +function parseHex(hex) { + return parseInt(hex.padEnd(2, hex), 16) / 255; +} +function parseAlpha(a, asPercentage) { + return clamp(asPercentage ? (a / 100) : a, 0, 1); +} +function clamp(n, min, max) { + return Math.min(Math.max(min, n), max); +} +/** + * The regular expression for numeric values is not super specific, and it may + * happen that it will accept a value that is not a valid number. In order to + * detect and eliminate such values this function exists. + * + * @param array Array of uncertain numbers. + * @returns `true` if the specified array contains only valid numbers, `false` otherwise. + */ +function validateNumbers(array) { + return !array.some(Number.isNaN); +} +/** + * To generate: + * - visit {@link https://www.w3.org/TR/css-color-4/#named-colors} + * - run in the console: + * @example + * copy(`{\n${[...document.querySelector('.named-color-table tbody').children].map((tr) => `${tr.cells[2].textContent.trim()}: [${tr.cells[4].textContent.trim().split(/\s+/).join(', ')}],`).join('\n')}\n}`); + */ +const namedColors = { + aliceblue: [240, 248, 255], + antiquewhite: [250, 235, 215], + aqua: [0, 255, 255], + aquamarine: [127, 255, 212], + azure: [240, 255, 255], + beige: [245, 245, 220], + bisque: [255, 228, 196], + black: [0, 0, 0], + blanchedalmond: [255, 235, 205], + blue: [0, 0, 255], + blueviolet: [138, 43, 226], + brown: [165, 42, 42], + burlywood: [222, 184, 135], + cadetblue: [95, 158, 160], + chartreuse: [127, 255, 0], + chocolate: [210, 105, 30], + coral: [255, 127, 80], + cornflowerblue: [100, 149, 237], + cornsilk: [255, 248, 220], + crimson: [220, 20, 60], + cyan: [0, 255, 255], + darkblue: [0, 0, 139], + darkcyan: [0, 139, 139], + darkgoldenrod: [184, 134, 11], + darkgray: [169, 169, 169], + darkgreen: [0, 100, 0], + darkgrey: [169, 169, 169], + darkkhaki: [189, 183, 107], + darkmagenta: [139, 0, 139], + darkolivegreen: [85, 107, 47], + darkorange: [255, 140, 0], + darkorchid: [153, 50, 204], + darkred: [139, 0, 0], + darksalmon: [233, 150, 122], + darkseagreen: [143, 188, 143], + darkslateblue: [72, 61, 139], + darkslategray: [47, 79, 79], + darkslategrey: [47, 79, 79], + darkturquoise: [0, 206, 209], + darkviolet: [148, 0, 211], + deeppink: [255, 20, 147], + deepskyblue: [0, 191, 255], + dimgray: [105, 105, 105], + dimgrey: [105, 105, 105], + dodgerblue: [30, 144, 255], + firebrick: [178, 34, 34], + floralwhite: [255, 250, 240], + forestgreen: [34, 139, 34], + fuchsia: [255, 0, 255], + gainsboro: [220, 220, 220], + ghostwhite: [248, 248, 255], + gold: [255, 215, 0], + goldenrod: [218, 165, 32], + gray: [128, 128, 128], + green: [0, 128, 0], + greenyellow: [173, 255, 47], + grey: [128, 128, 128], + honeydew: [240, 255, 240], + hotpink: [255, 105, 180], + indianred: [205, 92, 92], + indigo: [75, 0, 130], + ivory: [255, 255, 240], + khaki: [240, 230, 140], + lavender: [230, 230, 250], + lavenderblush: [255, 240, 245], + lawngreen: [124, 252, 0], + lemonchiffon: [255, 250, 205], + lightblue: [173, 216, 230], + lightcoral: [240, 128, 128], + lightcyan: [224, 255, 255], + lightgoldenrodyellow: [250, 250, 210], + lightgray: [211, 211, 211], + lightgreen: [144, 238, 144], + lightgrey: [211, 211, 211], + lightpink: [255, 182, 193], + lightsalmon: [255, 160, 122], + lightseagreen: [32, 178, 170], + lightskyblue: [135, 206, 250], + lightslategray: [119, 136, 153], + lightslategrey: [119, 136, 153], + lightsteelblue: [176, 196, 222], + lightyellow: [255, 255, 224], + lime: [0, 255, 0], + limegreen: [50, 205, 50], + linen: [250, 240, 230], + magenta: [255, 0, 255], + maroon: [128, 0, 0], + mediumaquamarine: [102, 205, 170], + mediumblue: [0, 0, 205], + mediumorchid: [186, 85, 211], + mediumpurple: [147, 112, 219], + mediumseagreen: [60, 179, 113], + mediumslateblue: [123, 104, 238], + mediumspringgreen: [0, 250, 154], + mediumturquoise: [72, 209, 204], + mediumvioletred: [199, 21, 133], + midnightblue: [25, 25, 112], + mintcream: [245, 255, 250], + mistyrose: [255, 228, 225], + moccasin: [255, 228, 181], + navajowhite: [255, 222, 173], + navy: [0, 0, 128], + oldlace: [253, 245, 230], + olive: [128, 128, 0], + olivedrab: [107, 142, 35], + orange: [255, 165, 0], + orangered: [255, 69, 0], + orchid: [218, 112, 214], + palegoldenrod: [238, 232, 170], + palegreen: [152, 251, 152], + paleturquoise: [175, 238, 238], + palevioletred: [219, 112, 147], + papayawhip: [255, 239, 213], + peachpuff: [255, 218, 185], + peru: [205, 133, 63], + pink: [255, 192, 203], + plum: [221, 160, 221], + powderblue: [176, 224, 230], + purple: [128, 0, 128], + rebeccapurple: [102, 51, 153], + red: [255, 0, 0], + rosybrown: [188, 143, 143], + royalblue: [65, 105, 225], + saddlebrown: [139, 69, 19], + salmon: [250, 128, 114], + sandybrown: [244, 164, 96], + seagreen: [46, 139, 87], + seashell: [255, 245, 238], + sienna: [160, 82, 45], + silver: [192, 192, 192], + skyblue: [135, 206, 235], + slateblue: [106, 90, 205], + slategray: [112, 128, 144], + slategrey: [112, 128, 144], + snow: [255, 250, 250], + springgreen: [0, 255, 127], + steelblue: [70, 130, 180], + tan: [210, 180, 140], + teal: [0, 128, 128], + thistle: [216, 191, 216], + tomato: [255, 99, 71], + turquoise: [64, 224, 208], + violet: [238, 130, 238], + wheat: [245, 222, 179], + white: [255, 255, 255], + whitesmoke: [245, 245, 245], + yellow: [255, 255, 0], + yellowgreen: [154, 205, 50], +}; + +/** + * Color representation used by WebGL. + * Defined in sRGB color space and pre-blended with alpha. + * @private + */ +class Color { + /** + * @param r Red component premultiplied by `alpha` 0..1 + * @param g Green component premultiplied by `alpha` 0..1 + * @param b Blue component premultiplied by `alpha` 0..1 + * @param [alpha=1] Alpha component 0..1 + * @param [premultiplied=true] Whether the `r`, `g` and `b` values have already + * been multiplied by alpha. If `true` nothing happens if `false` then they will + * be multiplied automatically. + */ + constructor(r, g, b, alpha = 1, premultiplied = true) { + this.r = r; + this.g = g; + this.b = b; + this.a = alpha; + if (!premultiplied) { + this.r *= alpha; + this.g *= alpha; + this.b *= alpha; + if (!alpha) { + // alpha = 0 erases completely rgb channels. This behavior is not desirable + // if this particular color is later used in color interpolation. + // Because of that, a reference to original color is saved. + this.overwriteGetter('rgb', [r, g, b, alpha]); + } + } + } + /** + * Parses CSS color strings and converts colors to sRGB color space if needed. + * Officially supported color formats: + * - keyword, e.g. 'aquamarine' or 'steelblue' + * - hex (with 3, 4, 6 or 8 digits), e.g. '#f0f' or '#e9bebea9' + * - rgb and rgba, e.g. 'rgb(0,240,120)' or 'rgba(0%,94%,47%,0.1)' or 'rgb(0 240 120 / .3)' + * - hsl and hsla, e.g. 'hsl(0,0%,83%)' or 'hsla(0,0%,83%,.5)' or 'hsl(0 0% 83% / 20%)' + * + * @param input CSS color string to parse. + * @returns A `Color` instance, or `undefined` if the input is not a valid color string. + */ + static parse(input) { + // in zoom-and-property function input could be an instance of Color class + if (input instanceof Color) { + return input; + } + if (typeof input !== 'string') { + return; + } + const rgba = parseCssColor(input); + if (rgba) { + return new Color(...rgba, false); + } + } + /** + * Used in color interpolation and by 'to-rgba' expression. + * + * @returns Gien color, with reversed alpha blending, in sRGB color space. + */ + get rgb() { + const { r, g, b, a } = this; + const f = a || Infinity; // reverse alpha blending factor + return this.overwriteGetter('rgb', [r / f, g / f, b / f, a]); + } + /** + * Used in color interpolation. + * + * @returns Gien color, with reversed alpha blending, in HCL color space. + */ + get hcl() { + return this.overwriteGetter('hcl', rgbToHcl(this.rgb)); + } + /** + * Used in color interpolation. + * + * @returns Gien color, with reversed alpha blending, in LAB color space. + */ + get lab() { + return this.overwriteGetter('lab', rgbToLab(this.rgb)); + } + /** + * Lazy getter pattern. When getter is called for the first time lazy value + * is calculated and then overwrites getter function in given object instance. + * + * @example: + * const redColor = Color.parse('red'); + * let x = redColor.hcl; // this will invoke `get hcl()`, which will calculate + * // the value of red in HCL space and invoke this `overwriteGetter` function + * // which in turn will set a field with a key 'hcl' in the `redColor` object. + * // In other words it will override `get hcl()` from its `Color` prototype + * // with its own property: hcl = [calculated red value in hcl]. + * let y = redColor.hcl; // next call will no longer invoke getter but simply + * // return the previously calculated value + * x === y; // true - `x` is exactly the same object as `y` + * + * @param getterKey Getter key + * @param lazyValue Lazily calculated value to be memoized by current instance + * @private + */ + overwriteGetter(getterKey, lazyValue) { + Object.defineProperty(this, getterKey, { value: lazyValue }); + return lazyValue; + } + /** + * Used by 'to-string' expression. + * + * @returns Serialized color in format `rgba(r,g,b,a)` + * where r,g,b are numbers within 0..255 and alpha is number within 1..0 + * + * @example + * var purple = new Color.parse('purple'); + * purple.toString; // = "rgba(128,0,128,1)" + * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)'); + * translucentGreen.toString(); // = "rgba(26,207,26,0.73)" + */ + toString() { + const [r, g, b, a] = this.rgb; + return `rgba(${[r, g, b].map(n => Math.round(n * 255)).join(',')},${a})`; + } +} +Color.black = new Color(0, 0, 0, 1); +Color.white = new Color(1, 1, 1, 1); +Color.transparent = new Color(0, 0, 0, 0); +Color.red = new Color(1, 0, 0, 1); + +// Flow type declarations for Intl cribbed from +// https://github.com/facebook/flow/issues/1270 +class Collator { + constructor(caseSensitive, diacriticSensitive, locale) { + if (caseSensitive) + this.sensitivity = diacriticSensitive ? 'variant' : 'case'; + else + this.sensitivity = diacriticSensitive ? 'accent' : 'base'; + this.locale = locale; + this.collator = new Intl.Collator(this.locale ? this.locale : [], { sensitivity: this.sensitivity, usage: 'search' }); + } + compare(lhs, rhs) { + return this.collator.compare(lhs, rhs); + } + resolvedLocale() { + // We create a Collator without "usage: search" because we don't want + // the search options encoded in our result (e.g. "en-u-co-search") + return new Intl.Collator(this.locale ? this.locale : []) + .resolvedOptions().locale; + } +} + +class FormattedSection { + constructor(text, image, scale, fontStack, textColor) { + this.text = text; + this.image = image; + this.scale = scale; + this.fontStack = fontStack; + this.textColor = textColor; + } +} +class Formatted { + constructor(sections) { + this.sections = sections; + } + static fromString(unformatted) { + return new Formatted([new FormattedSection(unformatted, null, null, null, null)]); + } + isEmpty() { + if (this.sections.length === 0) + return true; + return !this.sections.some(section => section.text.length !== 0 || + (section.image && section.image.name.length !== 0)); + } + static factory(text) { + if (text instanceof Formatted) { + return text; + } + else { + return Formatted.fromString(text); + } + } + toString() { + if (this.sections.length === 0) + return ''; + return this.sections.map(section => section.text).join(''); + } +} + +/** + * A set of four numbers representing padding around a box. Create instances from + * bare arrays or numeric values using the static method `Padding.parse`. + * @private + */ +class Padding { + constructor(values) { + this.values = values.slice(); + } + /** + * Numeric padding values + * @param input A padding value + * @returns A `Padding` instance, or `undefined` if the input is not a valid padding value. + */ + static parse(input) { + if (input instanceof Padding) { + return input; + } + // Backwards compatibility: bare number is treated the same as array with single value. + // Padding applies to all four sides. + if (typeof input === 'number') { + return new Padding([input, input, input, input]); + } + if (!Array.isArray(input)) { + return undefined; + } + if (input.length < 1 || input.length > 4) { + return undefined; + } + for (const val of input) { + if (typeof val !== 'number') { + return undefined; + } + } + // Expand shortcut properties into explicit 4-sided values + switch (input.length) { + case 1: + input = [input[0], input[0], input[0], input[0]]; + break; + case 2: + input = [input[0], input[1], input[0], input[1]]; + break; + case 3: + input = [input[0], input[1], input[2], input[1]]; + break; + } + return new Padding(input); + } + toString() { + return JSON.stringify(this.values); + } +} + +/** Set of valid anchor positions, as a set for validation */ +const anchors = new Set(['center', 'left', 'right', 'top', 'bottom', 'top-left', 'top-right', 'bottom-left', 'bottom-right']); +/** + * Utility class to assist managing values for text-variable-anchor-offset property. Create instances from + * bare arrays using the static method `VariableAnchorOffsetCollection.parse`. + * @private + */ +class VariableAnchorOffsetCollection { + constructor(values) { + this.values = values.slice(); + } + static parse(input) { + if (input instanceof VariableAnchorOffsetCollection) { + return input; + } + if (!Array.isArray(input) || + input.length < 1 || + input.length % 2 !== 0) { + return undefined; + } + for (let i = 0; i < input.length; i += 2) { + // Elements in even positions should be anchor positions; Elements in odd positions should be offset values + const anchorValue = input[i]; + const offsetValue = input[i + 1]; + if (typeof anchorValue !== 'string' || !anchors.has(anchorValue)) { + return undefined; + } + if (!Array.isArray(offsetValue) || offsetValue.length !== 2 || typeof offsetValue[0] !== 'number' || typeof offsetValue[1] !== 'number') { + return undefined; + } + } + return new VariableAnchorOffsetCollection(input); + } + toString() { + return JSON.stringify(this.values); + } +} + +class ResolvedImage { + constructor(options) { + this.name = options.name; + this.available = options.available; + } + toString() { + return this.name; + } + static fromString(name) { + if (!name) + return null; // treat empty values as no image + return new ResolvedImage({ name, available: false }); + } +} + +function validateRGBA(r, g, b, a) { + if (!(typeof r === 'number' && r >= 0 && r <= 255 && + typeof g === 'number' && g >= 0 && g <= 255 && + typeof b === 'number' && b >= 0 && b <= 255)) { + const value = typeof a === 'number' ? [r, g, b, a] : [r, g, b]; + return `Invalid rgba value [${value.join(', ')}]: 'r', 'g', and 'b' must be between 0 and 255.`; + } + if (!(typeof a === 'undefined' || (typeof a === 'number' && a >= 0 && a <= 1))) { + return `Invalid rgba value [${[r, g, b, a].join(', ')}]: 'a' must be between 0 and 1.`; + } + return null; +} +function isValue(mixed) { + if (mixed === null || + typeof mixed === 'string' || + typeof mixed === 'boolean' || + typeof mixed === 'number' || + mixed instanceof Color || + mixed instanceof Collator || + mixed instanceof Formatted || + mixed instanceof Padding || + mixed instanceof VariableAnchorOffsetCollection || + mixed instanceof ResolvedImage) { + return true; + } + else if (Array.isArray(mixed)) { + for (const item of mixed) { + if (!isValue(item)) { + return false; + } + } + return true; + } + else if (typeof mixed === 'object') { + for (const key in mixed) { + if (!isValue(mixed[key])) { + return false; + } + } + return true; + } + else { + return false; + } +} +function typeOf(value) { + if (value === null) { + return NullType; + } + else if (typeof value === 'string') { + return StringType; + } + else if (typeof value === 'boolean') { + return BooleanType; + } + else if (typeof value === 'number') { + return NumberType; + } + else if (value instanceof Color) { + return ColorType; + } + else if (value instanceof Collator) { + return CollatorType; + } + else if (value instanceof Formatted) { + return FormattedType; + } + else if (value instanceof Padding) { + return PaddingType; + } + else if (value instanceof VariableAnchorOffsetCollection) { + return VariableAnchorOffsetCollectionType; + } + else if (value instanceof ResolvedImage) { + return ResolvedImageType; + } + else if (Array.isArray(value)) { + const length = value.length; + let itemType; + for (const item of value) { + const t = typeOf(item); + if (!itemType) { + itemType = t; + } + else if (itemType === t) { + continue; + } + else { + itemType = ValueType; + break; + } + } + return array$1(itemType || ValueType, length); + } + else { + return ObjectType; + } +} +function toString(value) { + const type = typeof value; + if (value === null) { + return ''; + } + else if (type === 'string' || type === 'number' || type === 'boolean') { + return String(value); + } + else if (value instanceof Color || value instanceof Formatted || value instanceof Padding || value instanceof VariableAnchorOffsetCollection || value instanceof ResolvedImage) { + return value.toString(); + } + else { + return JSON.stringify(value); + } +} + +class Literal { + constructor(type, value) { + this.type = type; + this.value = value; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (!isValue(args[1])) + return context.error('invalid value'); + const value = args[1]; + let type = typeOf(value); + // special case: infer the item type if possible for zero-length arrays + const expected = context.expectedType; + if (type.kind === 'array' && + type.N === 0 && + expected && + expected.kind === 'array' && + (typeof expected.N !== 'number' || expected.N === 0)) { + type = expected; + } + return new Literal(type, value); + } + evaluate() { + return this.value; + } + eachChild() { } + outputDefined() { + return true; + } +} + +class RuntimeError { + constructor(message) { + this.name = 'ExpressionEvaluationError'; + this.message = message; + } + toJSON() { + return this.message; + } +} + +const types$1 = { + string: StringType, + number: NumberType, + boolean: BooleanType, + object: ObjectType +}; +class Assertion { + constructor(type, args) { + this.type = type; + this.args = args; + } + static parse(args, context) { + if (args.length < 2) + return context.error('Expected at least one argument.'); + let i = 1; + let type; + const name = args[0]; + if (name === 'array') { + let itemType; + if (args.length > 2) { + const type = args[1]; + if (typeof type !== 'string' || !(type in types$1) || type === 'object') + return context.error('The item type argument of "array" must be one of string, number, boolean', 1); + itemType = types$1[type]; + i++; + } + else { + itemType = ValueType; + } + let N; + if (args.length > 3) { + if (args[2] !== null && + (typeof args[2] !== 'number' || + args[2] < 0 || + args[2] !== Math.floor(args[2]))) { + return context.error('The length argument to "array" must be a positive integer literal', 2); + } + N = args[2]; + i++; + } + type = array$1(itemType, N); + } + else { + if (!types$1[name]) + throw new Error(`Types doesn't contain name = ${name}`); + type = types$1[name]; + } + const parsed = []; + for (; i < args.length; i++) { + const input = context.parse(args[i], i, ValueType); + if (!input) + return null; + parsed.push(input); + } + return new Assertion(type, parsed); + } + evaluate(ctx) { + for (let i = 0; i < this.args.length; i++) { + const value = this.args[i].evaluate(ctx); + const error = checkSubtype(this.type, typeOf(value)); + if (!error) { + return value; + } + else if (i === this.args.length - 1) { + throw new RuntimeError(`Expected value to be of type ${toString$1(this.type)}, but found ${toString$1(typeOf(value))} instead.`); + } + } + throw new Error(); + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return this.args.every(arg => arg.outputDefined()); + } +} + +const types = { + 'to-boolean': BooleanType, + 'to-color': ColorType, + 'to-number': NumberType, + 'to-string': StringType +}; +/** + * Special form for error-coalescing coercion expressions "to-number", + * "to-color". Since these coercions can fail at runtime, they accept multiple + * arguments, only evaluating one at a time until one succeeds. + * + * @private + */ +class Coercion { + constructor(type, args) { + this.type = type; + this.args = args; + } + static parse(args, context) { + if (args.length < 2) + return context.error('Expected at least one argument.'); + const name = args[0]; + if (!types[name]) + throw new Error(`Can't parse ${name} as it is not part of the known types`); + if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2) + return context.error('Expected one argument.'); + const type = types[name]; + const parsed = []; + for (let i = 1; i < args.length; i++) { + const input = context.parse(args[i], i, ValueType); + if (!input) + return null; + parsed.push(input); + } + return new Coercion(type, parsed); + } + evaluate(ctx) { + switch (this.type.kind) { + case 'boolean': + return Boolean(this.args[0].evaluate(ctx)); + case 'color': { + let input; + let error; + for (const arg of this.args) { + input = arg.evaluate(ctx); + error = null; + if (input instanceof Color) { + return input; + } + else if (typeof input === 'string') { + const c = ctx.parseColor(input); + if (c) + return c; + } + else if (Array.isArray(input)) { + if (input.length < 3 || input.length > 4) { + error = `Invalid rbga value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`; + } + else { + error = validateRGBA(input[0], input[1], input[2], input[3]); + } + if (!error) { + return new Color(input[0] / 255, input[1] / 255, input[2] / 255, input[3]); + } + } + } + throw new RuntimeError(error || `Could not parse color from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`); + } + case 'padding': { + let input; + for (const arg of this.args) { + input = arg.evaluate(ctx); + const pad = Padding.parse(input); + if (pad) { + return pad; + } + } + throw new RuntimeError(`Could not parse padding from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`); + } + case 'variableAnchorOffsetCollection': { + let input; + for (const arg of this.args) { + input = arg.evaluate(ctx); + const coll = VariableAnchorOffsetCollection.parse(input); + if (coll) { + return coll; + } + } + throw new RuntimeError(`Could not parse variableAnchorOffsetCollection from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`); + } + case 'number': { + let value = null; + for (const arg of this.args) { + value = arg.evaluate(ctx); + if (value === null) + return 0; + const num = Number(value); + if (isNaN(num)) + continue; + return num; + } + throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`); + } + case 'formatted': + // There is no explicit 'to-formatted' but this coercion can be implicitly + // created by properties that expect the 'formatted' type. + return Formatted.fromString(toString(this.args[0].evaluate(ctx))); + case 'resolvedImage': + return ResolvedImage.fromString(toString(this.args[0].evaluate(ctx))); + default: + return toString(this.args[0].evaluate(ctx)); + } + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return this.args.every(arg => arg.outputDefined()); + } +} + +const geometryTypes = ['Unknown', 'Point', 'LineString', 'Polygon']; +class EvaluationContext { + constructor() { + this.globals = null; + this.feature = null; + this.featureState = null; + this.formattedSection = null; + this._parseColorCache = {}; + this.availableImages = null; + this.canonical = null; + } + id() { + return this.feature && 'id' in this.feature ? this.feature.id : null; + } + geometryType() { + return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null; + } + geometry() { + return this.feature && 'geometry' in this.feature ? this.feature.geometry : null; + } + canonicalID() { + return this.canonical; + } + properties() { + return this.feature && this.feature.properties || {}; + } + parseColor(input) { + let cached = this._parseColorCache[input]; + if (!cached) { + cached = this._parseColorCache[input] = Color.parse(input); + } + return cached; + } +} + +/** + * State associated parsing at a given point in an expression tree. + * @private + */ +class ParsingContext { + constructor(registry, isConstantFunc, path = [], expectedType, scope = new Scope(), errors = []) { + this.registry = registry; + this.path = path; + this.key = path.map(part => `[${part}]`).join(''); + this.scope = scope; + this.errors = errors; + this.expectedType = expectedType; + this._isConstant = isConstantFunc; + } + /** + * @param expr the JSON expression to parse + * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed + * @param options + * @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. + * @private + */ + parse(expr, index, expectedType, bindings, options = {}) { + if (index) { + return this.concat(index, expectedType, bindings)._parse(expr, options); + } + return this._parse(expr, options); + } + _parse(expr, options) { + if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') { + expr = ['literal', expr]; + } + function annotate(parsed, type, typeAnnotation) { + if (typeAnnotation === 'assert') { + return new Assertion(type, [parsed]); + } + else if (typeAnnotation === 'coerce') { + return new Coercion(type, [parsed]); + } + else { + return parsed; + } + } + if (Array.isArray(expr)) { + if (expr.length === 0) { + return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].'); + } + const op = expr[0]; + if (typeof op !== 'string') { + this.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use ["literal", [...]].`, 0); + return null; + } + const Expr = this.registry[op]; + if (Expr) { + let parsed = Expr.parse(expr, this); + if (!parsed) + return null; + if (this.expectedType) { + const expected = this.expectedType; + const actual = parsed.type; + // When we expect a number, string, boolean, or array but have a value, wrap it in an assertion. + // When we expect a color or formatted string, but have a string or value, wrap it in a coercion. + // Otherwise, we do static type-checking. + // + // These behaviors are overridable for: + // * The "coalesce" operator, which needs to omit type annotations. + // * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion. + // + if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') { + parsed = annotate(parsed, expected, options.typeAnnotation || 'assert'); + } + else if ((expected.kind === 'color' || expected.kind === 'formatted' || expected.kind === 'resolvedImage') && (actual.kind === 'value' || actual.kind === 'string')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } + else if (expected.kind === 'padding' && (actual.kind === 'value' || actual.kind === 'number' || actual.kind === 'array')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } + else if (expected.kind === 'variableAnchorOffsetCollection' && (actual.kind === 'value' || actual.kind === 'array')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } + else if (this.checkSubtype(expected, actual)) { + return null; + } + } + // If an expression's arguments are all literals, we can evaluate + // it immediately and replace it with a literal value in the + // parsed/compiled result. Expressions that expect an image should + // not be resolved here so we can later get the available images. + if (!(parsed instanceof Literal) && (parsed.type.kind !== 'resolvedImage') && this._isConstant(parsed)) { + const ec = new EvaluationContext(); + try { + parsed = new Literal(parsed.type, parsed.evaluate(ec)); + } + catch (e) { + this.error(e.message); + return null; + } + } + return parsed; + } + return this.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); + } + else if (typeof expr === 'undefined') { + return this.error('\'undefined\' value invalid. Use null instead.'); + } + else if (typeof expr === 'object') { + return this.error('Bare objects invalid. Use ["literal", {...}] instead.'); + } + else { + return this.error(`Expected an array, but found ${typeof expr} instead.`); + } + } + /** + * Returns a copy of this context suitable for parsing the subexpression at + * index `index`, optionally appending to 'let' binding map. + * + * Note that `errors` property, intended for collecting errors while + * parsing, is copied by reference rather than cloned. + * @private + */ + concat(index, expectedType, bindings) { + const path = typeof index === 'number' ? this.path.concat(index) : this.path; + const scope = bindings ? this.scope.concat(bindings) : this.scope; + return new ParsingContext(this.registry, this._isConstant, path, expectedType || null, scope, this.errors); + } + /** + * Push a parsing (or type checking) error into the `this.errors` + * @param error The message + * @param keys Optionally specify the source of the error at a child + * of the current expression at `this.key`. + * @private + */ + error(error, ...keys) { + const key = `${this.key}${keys.map(k => `[${k}]`).join('')}`; + this.errors.push(new ExpressionParsingError(key, error)); + } + /** + * Returns null if `t` is a subtype of `expected`; otherwise returns an + * error message and also pushes it to `this.errors`. + * @param expected The expected type + * @param t The actual type + * @returns null if `t` is a subtype of `expected`; otherwise returns an error message + */ + checkSubtype(expected, t) { + const error = checkSubtype(expected, t); + if (error) + this.error(error); + return error; + } +} + +class Let { + constructor(bindings, result) { + this.type = result.type; + this.bindings = [].concat(bindings); + this.result = result; + } + evaluate(ctx) { + return this.result.evaluate(ctx); + } + eachChild(fn) { + for (const binding of this.bindings) { + fn(binding[1]); + } + fn(this.result); + } + static parse(args, context) { + if (args.length < 4) + return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`); + const bindings = []; + for (let i = 1; i < args.length - 1; i += 2) { + const name = args[i]; + if (typeof name !== 'string') { + return context.error(`Expected string, but found ${typeof name} instead.`, i); + } + if (/[^a-zA-Z0-9_]/.test(name)) { + return context.error('Variable names must contain only alphanumeric characters or \'_\'.', i); + } + const value = context.parse(args[i + 1], i + 1); + if (!value) + return null; + bindings.push([name, value]); + } + const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings); + if (!result) + return null; + return new Let(bindings, result); + } + outputDefined() { + return this.result.outputDefined(); + } +} + +class Var { + constructor(name, boundExpression) { + this.type = boundExpression.type; + this.name = name; + this.boundExpression = boundExpression; + } + static parse(args, context) { + if (args.length !== 2 || typeof args[1] !== 'string') + return context.error('\'var\' expression requires exactly one string literal argument.'); + const name = args[1]; + if (!context.scope.has(name)) { + return context.error(`Unknown variable "${name}". Make sure "${name}" has been bound in an enclosing "let" expression before using it.`, 1); + } + return new Var(name, context.scope.get(name)); + } + evaluate(ctx) { + return this.boundExpression.evaluate(ctx); + } + eachChild() { } + outputDefined() { + return false; + } +} + +class At { + constructor(type, index, input) { + this.type = type; + this.index = index; + this.input = input; + } + static parse(args, context) { + if (args.length !== 3) + return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); + const index = context.parse(args[1], 1, NumberType); + const input = context.parse(args[2], 2, array$1(context.expectedType || ValueType)); + if (!index || !input) + return null; + const t = input.type; + return new At(t.itemType, index, input); + } + evaluate(ctx) { + const index = this.index.evaluate(ctx); + const array = this.input.evaluate(ctx); + if (index < 0) { + throw new RuntimeError(`Array index out of bounds: ${index} < 0.`); + } + if (index >= array.length) { + throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`); + } + if (index !== Math.floor(index)) { + throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`); + } + return array[index]; + } + eachChild(fn) { + fn(this.index); + fn(this.input); + } + outputDefined() { + return false; + } +} + +class In { + constructor(needle, haystack) { + this.type = BooleanType; + this.needle = needle; + this.haystack = haystack; + } + static parse(args, context) { + if (args.length !== 3) { + return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); + } + const needle = context.parse(args[1], 1, ValueType); + const haystack = context.parse(args[2], 2, ValueType); + if (!needle || !haystack) + return null; + if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) { + return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(needle.type)} instead`); + } + return new In(needle, haystack); + } + evaluate(ctx) { + const needle = this.needle.evaluate(ctx); + const haystack = this.haystack.evaluate(ctx); + if (!haystack) + return false; + if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) { + throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(typeOf(needle))} instead.`); + } + if (!isValidNativeType(haystack, ['string', 'array'])) { + throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString$1(typeOf(haystack))} instead.`); + } + return haystack.indexOf(needle) >= 0; + } + eachChild(fn) { + fn(this.needle); + fn(this.haystack); + } + outputDefined() { + return true; + } +} + +class IndexOf { + constructor(needle, haystack, fromIndex) { + this.type = NumberType; + this.needle = needle; + this.haystack = haystack; + this.fromIndex = fromIndex; + } + static parse(args, context) { + if (args.length <= 2 || args.length >= 5) { + return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`); + } + const needle = context.parse(args[1], 1, ValueType); + const haystack = context.parse(args[2], 2, ValueType); + if (!needle || !haystack) + return null; + if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) { + return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(needle.type)} instead`); + } + if (args.length === 4) { + const fromIndex = context.parse(args[3], 3, NumberType); + if (!fromIndex) + return null; + return new IndexOf(needle, haystack, fromIndex); + } + else { + return new IndexOf(needle, haystack); + } + } + evaluate(ctx) { + const needle = this.needle.evaluate(ctx); + const haystack = this.haystack.evaluate(ctx); + if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) { + throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(typeOf(needle))} instead.`); + } + let fromIndex; + if (this.fromIndex) { + fromIndex = this.fromIndex.evaluate(ctx); + } + if (isValidNativeType(haystack, ['string'])) { + const rawIndex = haystack.indexOf(needle, fromIndex); + if (rawIndex === -1) { + return -1; + } + else { + // The index may be affected by surrogate pairs, so get the length of the preceding substring. + return [...haystack.slice(0, rawIndex)].length; + } + } + else if (isValidNativeType(haystack, ['array'])) { + return haystack.indexOf(needle, fromIndex); + } + else { + throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString$1(typeOf(haystack))} instead.`); + } + } + eachChild(fn) { + fn(this.needle); + fn(this.haystack); + if (this.fromIndex) { + fn(this.fromIndex); + } + } + outputDefined() { + return false; + } +} + +class Match { + constructor(inputType, outputType, input, cases, outputs, otherwise) { + this.inputType = inputType; + this.type = outputType; + this.input = input; + this.cases = cases; + this.outputs = outputs; + this.otherwise = otherwise; + } + static parse(args, context) { + if (args.length < 5) + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + if (args.length % 2 !== 1) + return context.error('Expected an even number of arguments.'); + let inputType; + let outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + const cases = {}; + const outputs = []; + for (let i = 2; i < args.length - 1; i += 2) { + let labels = args[i]; + const value = args[i + 1]; + if (!Array.isArray(labels)) { + labels = [labels]; + } + const labelContext = context.concat(i); + if (labels.length === 0) { + return labelContext.error('Expected at least one branch label.'); + } + for (const label of labels) { + if (typeof label !== 'number' && typeof label !== 'string') { + return labelContext.error('Branch labels must be numbers or strings.'); + } + else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) { + return labelContext.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`); + } + else if (typeof label === 'number' && Math.floor(label) !== label) { + return labelContext.error('Numeric branch labels must be integer values.'); + } + else if (!inputType) { + inputType = typeOf(label); + } + else if (labelContext.checkSubtype(inputType, typeOf(label))) { + return null; + } + if (typeof cases[String(label)] !== 'undefined') { + return labelContext.error('Branch labels must be unique.'); + } + cases[String(label)] = outputs.length; + } + const result = context.parse(value, i, outputType); + if (!result) + return null; + outputType = outputType || result.type; + outputs.push(result); + } + const input = context.parse(args[1], 1, ValueType); + if (!input) + return null; + const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) + return null; + if (input.type.kind !== 'value' && context.concat(1).checkSubtype(inputType, input.type)) { + return null; + } + return new Match(inputType, outputType, input, cases, outputs, otherwise); + } + evaluate(ctx) { + const input = this.input.evaluate(ctx); + const output = (typeOf(input) === this.inputType && this.outputs[this.cases[input]]) || this.otherwise; + return output.evaluate(ctx); + } + eachChild(fn) { + fn(this.input); + this.outputs.forEach(fn); + fn(this.otherwise); + } + outputDefined() { + return this.outputs.every(out => out.outputDefined()) && this.otherwise.outputDefined(); + } +} + +class Case { + constructor(type, branches, otherwise) { + this.type = type; + this.branches = branches; + this.otherwise = otherwise; + } + static parse(args, context) { + if (args.length < 4) + return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`); + if (args.length % 2 !== 0) + return context.error('Expected an odd number of arguments.'); + let outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + const branches = []; + for (let i = 1; i < args.length - 1; i += 2) { + const test = context.parse(args[i], i, BooleanType); + if (!test) + return null; + const result = context.parse(args[i + 1], i + 1, outputType); + if (!result) + return null; + branches.push([test, result]); + outputType = outputType || result.type; + } + const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) + return null; + if (!outputType) + throw new Error('Can\'t infer output type'); + return new Case(outputType, branches, otherwise); + } + evaluate(ctx) { + for (const [test, expression] of this.branches) { + if (test.evaluate(ctx)) { + return expression.evaluate(ctx); + } + } + return this.otherwise.evaluate(ctx); + } + eachChild(fn) { + for (const [test, expression] of this.branches) { + fn(test); + fn(expression); + } + fn(this.otherwise); + } + outputDefined() { + return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined(); + } +} + +class Slice { + constructor(type, input, beginIndex, endIndex) { + this.type = type; + this.input = input; + this.beginIndex = beginIndex; + this.endIndex = endIndex; + } + static parse(args, context) { + if (args.length <= 2 || args.length >= 5) { + return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`); + } + const input = context.parse(args[1], 1, ValueType); + const beginIndex = context.parse(args[2], 2, NumberType); + if (!input || !beginIndex) + return null; + if (!isValidType(input.type, [array$1(ValueType), StringType, ValueType])) { + return context.error(`Expected first argument to be of type array or string, but found ${toString$1(input.type)} instead`); + } + if (args.length === 4) { + const endIndex = context.parse(args[3], 3, NumberType); + if (!endIndex) + return null; + return new Slice(input.type, input, beginIndex, endIndex); + } + else { + return new Slice(input.type, input, beginIndex); + } + } + evaluate(ctx) { + const input = this.input.evaluate(ctx); + const beginIndex = this.beginIndex.evaluate(ctx); + let endIndex; + if (this.endIndex) { + endIndex = this.endIndex.evaluate(ctx); + } + if (isValidNativeType(input, ['string'])) { + // Indices may be affected by surrogate pairs. + return [...input].slice(beginIndex, endIndex).join(''); + } + else if (isValidNativeType(input, ['array'])) { + return input.slice(beginIndex, endIndex); + } + else { + throw new RuntimeError(`Expected first argument to be of type array or string, but found ${toString$1(typeOf(input))} instead.`); + } + } + eachChild(fn) { + fn(this.input); + fn(this.beginIndex); + if (this.endIndex) { + fn(this.endIndex); + } + } + outputDefined() { + return false; + } +} + +/** + * Returns the index of the last stop <= input, or 0 if it doesn't exist. + * @private + */ +function findStopLessThanOrEqualTo(stops, input) { + const lastIndex = stops.length - 1; + let lowerIndex = 0; + let upperIndex = lastIndex; + let currentIndex = 0; + let currentValue, nextValue; + while (lowerIndex <= upperIndex) { + currentIndex = Math.floor((lowerIndex + upperIndex) / 2); + currentValue = stops[currentIndex]; + nextValue = stops[currentIndex + 1]; + if (currentValue <= input) { + if (currentIndex === lastIndex || input < nextValue) { // Search complete + return currentIndex; + } + lowerIndex = currentIndex + 1; + } + else if (currentValue > input) { + upperIndex = currentIndex - 1; + } + else { + throw new RuntimeError('Input is not a number.'); + } + } + return 0; +} + +class Step { + constructor(type, input, stops) { + this.type = type; + this.input = input; + this.labels = []; + this.outputs = []; + for (const [label, expression] of stops) { + this.labels.push(label); + this.outputs.push(expression); + } + } + static parse(args, context) { + if (args.length - 1 < 4) { + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + } + if ((args.length - 1) % 2 !== 0) { + return context.error('Expected an even number of arguments.'); + } + const input = context.parse(args[1], 1, NumberType); + if (!input) + return null; + const stops = []; + let outputType = null; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + for (let i = 1; i < args.length; i += 2) { + const label = i === 1 ? -Infinity : args[i]; + const value = args[i + 1]; + const labelKey = i; + const valueKey = i + 1; + if (typeof label !== 'number') { + return context.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + const parsed = context.parse(value, valueKey, outputType); + if (!parsed) + return null; + outputType = outputType || parsed.type; + stops.push([label, parsed]); + } + return new Step(outputType, input, stops); + } + evaluate(ctx) { + const labels = this.labels; + const outputs = this.outputs; + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + const value = this.input.evaluate(ctx); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + const stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + const index = findStopLessThanOrEqualTo(labels, value); + return outputs[index].evaluate(ctx); + } + eachChild(fn) { + fn(this.input); + for (const expression of this.outputs) { + fn(expression); + } + } + outputDefined() { + return this.outputs.every(out => out.outputDefined()); + } +} + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var unitbezier = UnitBezier; + +function UnitBezier(p1x, p1y, p2x, p2y) { + // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). + this.cx = 3.0 * p1x; + this.bx = 3.0 * (p2x - p1x) - this.cx; + this.ax = 1.0 - this.cx - this.bx; + + this.cy = 3.0 * p1y; + this.by = 3.0 * (p2y - p1y) - this.cy; + this.ay = 1.0 - this.cy - this.by; + + this.p1x = p1x; + this.p1y = p1y; + this.p2x = p2x; + this.p2y = p2y; +} + +UnitBezier.prototype = { + sampleCurveX: function (t) { + // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. + return ((this.ax * t + this.bx) * t + this.cx) * t; + }, + + sampleCurveY: function (t) { + return ((this.ay * t + this.by) * t + this.cy) * t; + }, + + sampleCurveDerivativeX: function (t) { + return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; + }, + + solveCurveX: function (x, epsilon) { + if (epsilon === undefined) epsilon = 1e-6; + + if (x < 0.0) return 0.0; + if (x > 1.0) return 1.0; + + var t = x; + + // First try a few iterations of Newton's method - normally very fast. + for (var i = 0; i < 8; i++) { + var x2 = this.sampleCurveX(t) - x; + if (Math.abs(x2) < epsilon) return t; + + var d2 = this.sampleCurveDerivativeX(t); + if (Math.abs(d2) < 1e-6) break; + + t = t - x2 / d2; + } + + // Fall back to the bisection method for reliability. + var t0 = 0.0; + var t1 = 1.0; + t = x; + + for (i = 0; i < 20; i++) { + x2 = this.sampleCurveX(t); + if (Math.abs(x2 - x) < epsilon) break; + + if (x > x2) { + t0 = t; + } else { + t1 = t; + } + + t = (t1 - t0) * 0.5 + t0; + } + + return t; + }, + + solve: function (x, epsilon) { + return this.sampleCurveY(this.solveCurveX(x, epsilon)); + } +}; + +var UnitBezier$1 = /*@__PURE__*/getDefaultExportFromCjs(unitbezier); + +/** + * Checks whether the specified color space is one of the supported interpolation color spaces. + * + * @param colorSpace Color space key to verify. + * @returns `true` if the specified color space is one of the supported + * interpolation color spaces, `false` otherwise + */ +function isSupportedInterpolationColorSpace(colorSpace) { + return colorSpace === 'rgb' || colorSpace === 'hcl' || colorSpace === 'lab'; +} +/** + * @param interpolationType Interpolation type + * @returns interpolation fn + * @deprecated use `interpolate[type]` instead + */ +const interpolateFactory = (interpolationType) => { + switch (interpolationType) { + case 'number': return number; + case 'color': return color; + case 'array': return array; + case 'padding': return padding$1; + case 'variableAnchorOffsetCollection': return variableAnchorOffsetCollection; + } +}; +function number(from, to, t) { + return from + t * (to - from); +} +function color(from, to, t, spaceKey = 'rgb') { + switch (spaceKey) { + case 'rgb': { + const [r, g, b, alpha] = array(from.rgb, to.rgb, t); + return new Color(r, g, b, alpha, false); + } + case 'hcl': { + const [hue0, chroma0, light0, alphaF] = from.hcl; + const [hue1, chroma1, light1, alphaT] = to.hcl; + // https://github.com/gka/chroma.js/blob/cd1b3c0926c7a85cbdc3b1453b3a94006de91a92/src/interpolator/_hsx.js + let hue, chroma; + if (!isNaN(hue0) && !isNaN(hue1)) { + let dh = hue1 - hue0; + if (hue1 > hue0 && dh > 180) { + dh -= 360; + } + else if (hue1 < hue0 && hue0 - hue1 > 180) { + dh += 360; + } + hue = hue0 + t * dh; + } + else if (!isNaN(hue0)) { + hue = hue0; + if (light1 === 1 || light1 === 0) + chroma = chroma0; + } + else if (!isNaN(hue1)) { + hue = hue1; + if (light0 === 1 || light0 === 0) + chroma = chroma1; + } + else { + hue = NaN; + } + const [r, g, b, alpha] = hclToRgb([ + hue, + chroma !== null && chroma !== void 0 ? chroma : number(chroma0, chroma1, t), + number(light0, light1, t), + number(alphaF, alphaT, t), + ]); + return new Color(r, g, b, alpha, false); + } + case 'lab': { + const [r, g, b, alpha] = labToRgb(array(from.lab, to.lab, t)); + return new Color(r, g, b, alpha, false); + } + } +} +function array(from, to, t) { + return from.map((d, i) => { + return number(d, to[i], t); + }); +} +function padding$1(from, to, t) { + return new Padding(array(from.values, to.values, t)); +} +function variableAnchorOffsetCollection(from, to, t) { + const fromValues = from.values; + const toValues = to.values; + if (fromValues.length !== toValues.length) { + throw new RuntimeError(`Cannot interpolate values of different length. from: ${from.toString()}, to: ${to.toString()}`); + } + const output = []; + for (let i = 0; i < fromValues.length; i += 2) { + // Anchor entries must match + if (fromValues[i] !== toValues[i]) { + throw new RuntimeError(`Cannot interpolate values containing mismatched anchors. from[${i}]: ${fromValues[i]}, to[${i}]: ${toValues[i]}`); + } + output.push(fromValues[i]); + // Interpolate the offset values for each anchor + const [fx, fy] = fromValues[i + 1]; + const [tx, ty] = toValues[i + 1]; + output.push([number(fx, tx, t), number(fy, ty, t)]); + } + return new VariableAnchorOffsetCollection(output); +} +const interpolate = { + number, + color, + array, + padding: padding$1, + variableAnchorOffsetCollection +}; + +class Interpolate { + constructor(type, operator, interpolation, input, stops) { + this.type = type; + this.operator = operator; + this.interpolation = interpolation; + this.input = input; + this.labels = []; + this.outputs = []; + for (const [label, expression] of stops) { + this.labels.push(label); + this.outputs.push(expression); + } + } + static interpolationFactor(interpolation, input, lower, upper) { + let t = 0; + if (interpolation.name === 'exponential') { + t = exponentialInterpolation(input, interpolation.base, lower, upper); + } + else if (interpolation.name === 'linear') { + t = exponentialInterpolation(input, 1, lower, upper); + } + else if (interpolation.name === 'cubic-bezier') { + const c = interpolation.controlPoints; + const ub = new UnitBezier$1(c[0], c[1], c[2], c[3]); + t = ub.solve(exponentialInterpolation(input, 1, lower, upper)); + } + return t; + } + static parse(args, context) { + let [operator, interpolation, input, ...rest] = args; + if (!Array.isArray(interpolation) || interpolation.length === 0) { + return context.error('Expected an interpolation type expression.', 1); + } + if (interpolation[0] === 'linear') { + interpolation = { name: 'linear' }; + } + else if (interpolation[0] === 'exponential') { + const base = interpolation[1]; + if (typeof base !== 'number') + return context.error('Exponential interpolation requires a numeric base.', 1, 1); + interpolation = { + name: 'exponential', + base + }; + } + else if (interpolation[0] === 'cubic-bezier') { + const controlPoints = interpolation.slice(1); + if (controlPoints.length !== 4 || + controlPoints.some(t => typeof t !== 'number' || t < 0 || t > 1)) { + return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1); + } + interpolation = { + name: 'cubic-bezier', + controlPoints: controlPoints + }; + } + else { + return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0); + } + if (args.length - 1 < 4) { + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + } + if ((args.length - 1) % 2 !== 0) { + return context.error('Expected an even number of arguments.'); + } + input = context.parse(input, 2, NumberType); + if (!input) + return null; + const stops = []; + let outputType = null; + if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') { + outputType = ColorType; + } + else if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + for (let i = 0; i < rest.length; i += 2) { + const label = rest[i]; + const value = rest[i + 1]; + const labelKey = i + 3; + const valueKey = i + 4; + if (typeof label !== 'number') { + return context.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + const parsed = context.parse(value, valueKey, outputType); + if (!parsed) + return null; + outputType = outputType || parsed.type; + stops.push([label, parsed]); + } + if (!verifyType(outputType, NumberType) && + !verifyType(outputType, ColorType) && + !verifyType(outputType, PaddingType) && + !verifyType(outputType, VariableAnchorOffsetCollectionType) && + !verifyType(outputType, array$1(NumberType))) { + return context.error(`Type ${toString$1(outputType)} is not interpolatable.`); + } + return new Interpolate(outputType, operator, interpolation, input, stops); + } + evaluate(ctx) { + const labels = this.labels; + const outputs = this.outputs; + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + const value = this.input.evaluate(ctx); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + const stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + const index = findStopLessThanOrEqualTo(labels, value); + const lower = labels[index]; + const upper = labels[index + 1]; + const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper); + const outputLower = outputs[index].evaluate(ctx); + const outputUpper = outputs[index + 1].evaluate(ctx); + switch (this.operator) { + case 'interpolate': + return interpolate[this.type.kind](outputLower, outputUpper, t); + case 'interpolate-hcl': + return interpolate.color(outputLower, outputUpper, t, 'hcl'); + case 'interpolate-lab': + return interpolate.color(outputLower, outputUpper, t, 'lab'); + } + } + eachChild(fn) { + fn(this.input); + for (const expression of this.outputs) { + fn(expression); + } + } + outputDefined() { + return this.outputs.every(out => out.outputDefined()); + } +} +/** + * Returns a ratio that can be used to interpolate between exponential function + * stops. + * 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, + * and `a` and `b` are constants affording sufficient degrees of freedom to fit + * the function to the given stops. + * + * Here's a bit of algebra that lets us compute `f(x)` directly from the stop + * values without explicitly solving for `a` and `b`: + * + * First stop value: `f(x0) = y0 = a * base^x0 + b` + * Second stop value: `f(x1) = y1 = a * base^x1 + b` + * => `y1 - y0 = a(base^x1 - base^x0)` + * => `a = (y1 - y0)/(base^x1 - base^x0)` + * + * Desired value: `f(x) = y = a * base^x + b` + * => `f(x) = y0 + a * (base^x - base^x0)` + * + * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a + * little algebra: + * ``` + * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) + * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) + * ``` + * + * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have + * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as + * an interpolation factor between the two stops' output values. + * + * (Note: a slightly different form for `ratio`, + * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer + * expensive `Math.pow()` operations.) + * + * @private +*/ +function exponentialInterpolation(input, base, lowerValue, upperValue) { + const difference = upperValue - lowerValue; + const progress = input - lowerValue; + if (difference === 0) { + return 0; + } + else if (base === 1) { + return progress / difference; + } + else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} + +class Coalesce { + constructor(type, args) { + this.type = type; + this.args = args; + } + static parse(args, context) { + if (args.length < 2) { + return context.error('Expectected at least one argument.'); + } + let outputType = null; + const expectedType = context.expectedType; + if (expectedType && expectedType.kind !== 'value') { + outputType = expectedType; + } + const parsedArgs = []; + for (const arg of args.slice(1)) { + const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, { typeAnnotation: 'omit' }); + if (!parsed) + return null; + outputType = outputType || parsed.type; + parsedArgs.push(parsed); + } + if (!outputType) + throw new Error('No output type'); + // Above, we parse arguments without inferred type annotation so that + // they don't produce a runtime error for `null` input, which would + // preempt the desired null-coalescing behavior. + // Thus, if any of our arguments would have needed an annotation, we + // need to wrap the enclosing coalesce expression with it instead. + const needsAnnotation = expectedType && + parsedArgs.some(arg => checkSubtype(expectedType, arg.type)); + return needsAnnotation ? + new Coalesce(ValueType, parsedArgs) : + new Coalesce(outputType, parsedArgs); + } + evaluate(ctx) { + let result = null; + let argCount = 0; + let requestedImageName; + for (const arg of this.args) { + argCount++; + result = arg.evaluate(ctx); + // we need to keep track of the first requested image in a coalesce statement + // if coalesce can't find a valid image, we return the first image name so styleimagemissing can fire + if (result && result instanceof ResolvedImage && !result.available) { + if (!requestedImageName) { + requestedImageName = result.name; + } + result = null; + if (argCount === this.args.length) { + result = requestedImageName; + } + } + if (result !== null) + break; + } + return result; + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return this.args.every(arg => arg.outputDefined()); + } +} + +function isComparableType(op, type) { + if (op === '==' || op === '!=') { + // equality operator + return type.kind === 'boolean' || + type.kind === 'string' || + type.kind === 'number' || + type.kind === 'null' || + type.kind === 'value'; + } + else { + // ordering operator + return type.kind === 'string' || + type.kind === 'number' || + type.kind === 'value'; + } +} +function eq(ctx, a, b) { return a === b; } +function neq(ctx, a, b) { return a !== b; } +function lt(ctx, a, b) { return a < b; } +function gt(ctx, a, b) { return a > b; } +function lteq(ctx, a, b) { return a <= b; } +function gteq(ctx, a, b) { return a >= b; } +function eqCollate(ctx, a, b, c) { return c.compare(a, b) === 0; } +function neqCollate(ctx, a, b, c) { return !eqCollate(ctx, a, b, c); } +function ltCollate(ctx, a, b, c) { return c.compare(a, b) < 0; } +function gtCollate(ctx, a, b, c) { return c.compare(a, b) > 0; } +function lteqCollate(ctx, a, b, c) { return c.compare(a, b) <= 0; } +function gteqCollate(ctx, a, b, c) { return c.compare(a, b) >= 0; } +/** + * Special form for comparison operators, implementing the signatures: + * - (T, T, ?Collator) => boolean + * - (T, value, ?Collator) => boolean + * - (value, T, ?Collator) => boolean + * + * For inequalities, T must be either value, string, or number. For ==/!=, it + * can also be boolean or null. + * + * Equality semantics are equivalent to Javascript's strict equality (===/!==) + * -- i.e., when the arguments' types don't match, == evaluates to false, != to + * true. + * + * When types don't match in an ordering comparison, a runtime error is thrown. + * + * @private + */ +function makeComparison(op, compareBasic, compareWithCollator) { + const isOrderComparison = op !== '==' && op !== '!='; + return class Comparison { + constructor(lhs, rhs, collator) { + this.type = BooleanType; + this.lhs = lhs; + this.rhs = rhs; + this.collator = collator; + this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value'; + } + static parse(args, context) { + if (args.length !== 3 && args.length !== 4) + return context.error('Expected two or three arguments.'); + const op = args[0]; + let lhs = context.parse(args[1], 1, ValueType); + if (!lhs) + return null; + if (!isComparableType(op, lhs.type)) { + return context.concat(1).error(`"${op}" comparisons are not supported for type '${toString$1(lhs.type)}'.`); + } + let rhs = context.parse(args[2], 2, ValueType); + if (!rhs) + return null; + if (!isComparableType(op, rhs.type)) { + return context.concat(2).error(`"${op}" comparisons are not supported for type '${toString$1(rhs.type)}'.`); + } + if (lhs.type.kind !== rhs.type.kind && + lhs.type.kind !== 'value' && + rhs.type.kind !== 'value') { + return context.error(`Cannot compare types '${toString$1(lhs.type)}' and '${toString$1(rhs.type)}'.`); + } + if (isOrderComparison) { + // typing rules specific to less/greater than operators + if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') { + // (value, T) + lhs = new Assertion(rhs.type, [lhs]); + } + else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') { + // (T, value) + rhs = new Assertion(lhs.type, [rhs]); + } + } + let collator = null; + if (args.length === 4) { + if (lhs.type.kind !== 'string' && + rhs.type.kind !== 'string' && + lhs.type.kind !== 'value' && + rhs.type.kind !== 'value') { + return context.error('Cannot use collator to compare non-string types.'); + } + collator = context.parse(args[3], 3, CollatorType); + if (!collator) + return null; + } + return new Comparison(lhs, rhs, collator); + } + evaluate(ctx) { + const lhs = this.lhs.evaluate(ctx); + const rhs = this.rhs.evaluate(ctx); + if (isOrderComparison && this.hasUntypedArgument) { + const lt = typeOf(lhs); + const rt = typeOf(rhs); + // check that type is string or number, and equal + if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) { + throw new RuntimeError(`Expected arguments for "${op}" to be (string, string) or (number, number), but found (${lt.kind}, ${rt.kind}) instead.`); + } + } + if (this.collator && !isOrderComparison && this.hasUntypedArgument) { + const lt = typeOf(lhs); + const rt = typeOf(rhs); + if (lt.kind !== 'string' || rt.kind !== 'string') { + return compareBasic(ctx, lhs, rhs); + } + } + return this.collator ? + compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) : + compareBasic(ctx, lhs, rhs); + } + eachChild(fn) { + fn(this.lhs); + fn(this.rhs); + if (this.collator) { + fn(this.collator); + } + } + outputDefined() { + return true; + } + }; +} +const Equals = makeComparison('==', eq, eqCollate); +const NotEquals = makeComparison('!=', neq, neqCollate); +const LessThan = makeComparison('<', lt, ltCollate); +const GreaterThan = makeComparison('>', gt, gtCollate); +const LessThanOrEqual = makeComparison('<=', lteq, lteqCollate); +const GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate); + +class CollatorExpression { + constructor(caseSensitive, diacriticSensitive, locale) { + this.type = CollatorType; + this.locale = locale; + this.caseSensitive = caseSensitive; + this.diacriticSensitive = diacriticSensitive; + } + static parse(args, context) { + if (args.length !== 2) + return context.error('Expected one argument.'); + const options = args[1]; + if (typeof options !== 'object' || Array.isArray(options)) + return context.error('Collator options argument must be an object.'); + const caseSensitive = context.parse(options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType); + if (!caseSensitive) + return null; + const diacriticSensitive = context.parse(options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType); + if (!diacriticSensitive) + return null; + let locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) + return null; + } + return new CollatorExpression(caseSensitive, diacriticSensitive, locale); + } + evaluate(ctx) { + return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null); + } + eachChild(fn) { + fn(this.caseSensitive); + fn(this.diacriticSensitive); + if (this.locale) { + fn(this.locale); + } + } + outputDefined() { + // Technically the set of possible outputs is the combinatoric set of Collators produced + // by all possible outputs of locale/caseSensitive/diacriticSensitive + // But for the primary use of Collators in comparison operators, we ignore the Collator's + // possible outputs anyway, so we can get away with leaving this false for now. + return false; + } +} + +class NumberFormat { + constructor(number, locale, currency, minFractionDigits, maxFractionDigits) { + this.type = StringType; + this.number = number; + this.locale = locale; + this.currency = currency; + this.minFractionDigits = minFractionDigits; + this.maxFractionDigits = maxFractionDigits; + } + static parse(args, context) { + if (args.length !== 3) + return context.error('Expected two arguments.'); + const number = context.parse(args[1], 1, NumberType); + if (!number) + return null; + const options = args[2]; + if (typeof options !== 'object' || Array.isArray(options)) + return context.error('NumberFormat options argument must be an object.'); + let locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) + return null; + } + let currency = null; + if (options['currency']) { + currency = context.parse(options['currency'], 1, StringType); + if (!currency) + return null; + } + let minFractionDigits = null; + if (options['min-fraction-digits']) { + minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType); + if (!minFractionDigits) + return null; + } + let maxFractionDigits = null; + if (options['max-fraction-digits']) { + maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType); + if (!maxFractionDigits) + return null; + } + return new NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits); + } + evaluate(ctx) { + return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], { + style: this.currency ? 'currency' : 'decimal', + currency: this.currency ? this.currency.evaluate(ctx) : undefined, + minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined, + maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined, + }).format(this.number.evaluate(ctx)); + } + eachChild(fn) { + fn(this.number); + if (this.locale) { + fn(this.locale); + } + if (this.currency) { + fn(this.currency); + } + if (this.minFractionDigits) { + fn(this.minFractionDigits); + } + if (this.maxFractionDigits) { + fn(this.maxFractionDigits); + } + } + outputDefined() { + return false; + } +} + +class FormatExpression { + constructor(sections) { + this.type = FormattedType; + this.sections = sections; + } + static parse(args, context) { + if (args.length < 2) { + return context.error('Expected at least one argument.'); + } + const firstArg = args[1]; + if (!Array.isArray(firstArg) && typeof firstArg === 'object') { + return context.error('First argument must be an image or text section.'); + } + const sections = []; + let nextTokenMayBeObject = false; + for (let i = 1; i <= args.length - 1; ++i) { + const arg = args[i]; + if (nextTokenMayBeObject && typeof arg === 'object' && !Array.isArray(arg)) { + nextTokenMayBeObject = false; + let scale = null; + if (arg['font-scale']) { + scale = context.parse(arg['font-scale'], 1, NumberType); + if (!scale) + return null; + } + let font = null; + if (arg['text-font']) { + font = context.parse(arg['text-font'], 1, array$1(StringType)); + if (!font) + return null; + } + let textColor = null; + if (arg['text-color']) { + textColor = context.parse(arg['text-color'], 1, ColorType); + if (!textColor) + return null; + } + const lastExpression = sections[sections.length - 1]; + lastExpression.scale = scale; + lastExpression.font = font; + lastExpression.textColor = textColor; + } + else { + const content = context.parse(args[i], 1, ValueType); + if (!content) + return null; + const kind = content.type.kind; + if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage') + return context.error('Formatted text type must be \'string\', \'value\', \'image\' or \'null\'.'); + nextTokenMayBeObject = true; + sections.push({ content, scale: null, font: null, textColor: null }); + } + } + return new FormatExpression(sections); + } + evaluate(ctx) { + const evaluateSection = section => { + const evaluatedContent = section.content.evaluate(ctx); + if (typeOf(evaluatedContent) === ResolvedImageType) { + return new FormattedSection('', evaluatedContent, null, null, null); + } + return new FormattedSection(toString(evaluatedContent), null, section.scale ? section.scale.evaluate(ctx) : null, section.font ? section.font.evaluate(ctx).join(',') : null, section.textColor ? section.textColor.evaluate(ctx) : null); + }; + return new Formatted(this.sections.map(evaluateSection)); + } + eachChild(fn) { + for (const section of this.sections) { + fn(section.content); + if (section.scale) { + fn(section.scale); + } + if (section.font) { + fn(section.font); + } + if (section.textColor) { + fn(section.textColor); + } + } + } + outputDefined() { + // Technically the combinatoric set of all children + // Usually, this.text will be undefined anyway + return false; + } +} + +class ImageExpression { + constructor(input) { + this.type = ResolvedImageType; + this.input = input; + } + static parse(args, context) { + if (args.length !== 2) { + return context.error('Expected two arguments.'); + } + const name = context.parse(args[1], 1, StringType); + if (!name) + return context.error('No image name provided.'); + return new ImageExpression(name); + } + evaluate(ctx) { + const evaluatedImageName = this.input.evaluate(ctx); + const value = ResolvedImage.fromString(evaluatedImageName); + if (value && ctx.availableImages) + value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1; + return value; + } + eachChild(fn) { + fn(this.input); + } + outputDefined() { + // The output of image is determined by the list of available images in the evaluation context + return false; + } +} + +class Length { + constructor(input) { + this.type = NumberType; + this.input = input; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`); + const input = context.parse(args[1], 1); + if (!input) + return null; + if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value') + return context.error(`Expected argument of type string or array, but found ${toString$1(input.type)} instead.`); + return new Length(input); + } + evaluate(ctx) { + const input = this.input.evaluate(ctx); + if (typeof input === 'string') { + // The length may be affected by surrogate pairs. + return [...input].length; + } + else if (Array.isArray(input)) { + return input.length; + } + else { + throw new RuntimeError(`Expected value to be of type string or array, but found ${toString$1(typeOf(input))} instead.`); + } + } + eachChild(fn) { + fn(this.input); + } + outputDefined() { + return false; + } +} + +const EXTENT$1 = 8192; +function getTileCoordinates(p, canonical) { + const x = mercatorXfromLng$1(p[0]); + const y = mercatorYfromLat$1(p[1]); + const tilesAtZoom = Math.pow(2, canonical.z); + return [Math.round(x * tilesAtZoom * EXTENT$1), Math.round(y * tilesAtZoom * EXTENT$1)]; +} +function getLngLatFromTileCoord(coord, canonical) { + const tilesAtZoom = Math.pow(2, canonical.z); + const x = (coord[0] / EXTENT$1 + canonical.x) / tilesAtZoom; + const y = (coord[1] / EXTENT$1 + canonical.y) / tilesAtZoom; + return [lngFromMercatorXfromLng(x), latFromMercatorY$1(y)]; +} +function mercatorXfromLng$1(lng) { + return (180 + lng) / 360; +} +function lngFromMercatorXfromLng(mercatorX) { + return mercatorX * 360 - 180; +} +function mercatorYfromLat$1(lat) { + return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360; +} +function latFromMercatorY$1(mercatorY) { + return 360 / Math.PI * Math.atan(Math.exp((180 - mercatorY * 360) * Math.PI / 180)) - 90; +} +function updateBBox(bbox, coord) { + bbox[0] = Math.min(bbox[0], coord[0]); + bbox[1] = Math.min(bbox[1], coord[1]); + bbox[2] = Math.max(bbox[2], coord[0]); + bbox[3] = Math.max(bbox[3], coord[1]); +} +function boxWithinBox(bbox1, bbox2) { + if (bbox1[0] <= bbox2[0]) + return false; + if (bbox1[2] >= bbox2[2]) + return false; + if (bbox1[1] <= bbox2[1]) + return false; + if (bbox1[3] >= bbox2[3]) + return false; + return true; +} +function rayIntersect(p, p1, p2) { + 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]); +} +function pointOnBoundary(p, p1, p2) { + const x1 = p[0] - p1[0]; + const y1 = p[1] - p1[1]; + const x2 = p[0] - p2[0]; + const y2 = p[1] - p2[1]; + return (x1 * y2 - x2 * y1 === 0) && (x1 * x2 <= 0) && (y1 * y2 <= 0); +} +// a, b are end points for line segment1, c and d are end points for line segment2 +function segmentIntersectSegment(a, b, c, d) { + // check if two segments are parallel or not + // precondition is end point a, b is inside polygon, if line a->b is + // parallel to polygon edge c->d, then a->b won't intersect with c->d + const vectorP = [b[0] - a[0], b[1] - a[1]]; + const vectorQ = [d[0] - c[0], d[1] - c[1]]; + if (perp(vectorQ, vectorP) === 0) + return false; + // If lines are intersecting with each other, the relative location should be: + // a and b lie in different sides of segment c->d + // c and d lie in different sides of segment a->b + if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) + return true; + return false; +} +function lineIntersectPolygon(p1, p2, polygon) { + for (const ring of polygon) { + // loop through every edge of the ring + for (let j = 0; j < ring.length - 1; ++j) { + if (segmentIntersectSegment(p1, p2, ring[j], ring[j + 1])) { + return true; + } + } + } + return false; +} +// ray casting algorithm for detecting if point is in polygon +function pointWithinPolygon(point, rings, trueIfOnBoundary = false) { + let inside = false; + for (const ring of rings) { + for (let j = 0; j < ring.length - 1; j++) { + if (pointOnBoundary(point, ring[j], ring[j + 1])) + return trueIfOnBoundary; + if (rayIntersect(point, ring[j], ring[j + 1])) + inside = !inside; + } + } + return inside; +} +function pointWithinPolygons(point, polygons) { + for (const polygon of polygons) { + if (pointWithinPolygon(point, polygon)) + return true; + } + return false; +} +function lineStringWithinPolygon(line, polygon) { + // First, check if geometry points of line segments are all inside polygon + for (const point of line) { + if (!pointWithinPolygon(point, polygon)) { + return false; + } + } + // Second, check if there is line segment intersecting polygon edge + for (let i = 0; i < line.length - 1; ++i) { + if (lineIntersectPolygon(line[i], line[i + 1], polygon)) { + return false; + } + } + return true; +} +function lineStringWithinPolygons(line, polygons) { + for (const polygon of polygons) { + if (lineStringWithinPolygon(line, polygon)) + return true; + } + return false; +} +function perp(v1, v2) { + return (v1[0] * v2[1] - v1[1] * v2[0]); +} +// check if p1 and p2 are in different sides of line segment q1->q2 +function twoSided(p1, p2, q1, q2) { + // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3) + const x1 = p1[0] - q1[0]; + const y1 = p1[1] - q1[1]; + const x2 = p2[0] - q1[0]; + const y2 = p2[1] - q1[1]; + const x3 = q2[0] - q1[0]; + const y3 = q2[1] - q1[1]; + const det1 = (x1 * y3 - x3 * y1); + const det2 = (x2 * y3 - x3 * y2); + if ((det1 > 0 && det2 < 0) || (det1 < 0 && det2 > 0)) + return true; + return false; +} + +function getTilePolygon(coordinates, bbox, canonical) { + const polygon = []; + for (let i = 0; i < coordinates.length; i++) { + const ring = []; + for (let j = 0; j < coordinates[i].length; j++) { + const coord = getTileCoordinates(coordinates[i][j], canonical); + updateBBox(bbox, coord); + ring.push(coord); + } + polygon.push(ring); + } + return polygon; +} +function getTilePolygons(coordinates, bbox, canonical) { + const polygons = []; + for (let i = 0; i < coordinates.length; i++) { + const polygon = getTilePolygon(coordinates[i], bbox, canonical); + polygons.push(polygon); + } + return polygons; +} +function updatePoint(p, bbox, polyBBox, worldSize) { + if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) { + const halfWorldSize = worldSize * 0.5; + let shift = (p[0] - polyBBox[0] > halfWorldSize) ? -worldSize : (polyBBox[0] - p[0] > halfWorldSize) ? worldSize : 0; + if (shift === 0) { + shift = (p[0] - polyBBox[2] > halfWorldSize) ? -worldSize : (polyBBox[2] - p[0] > halfWorldSize) ? worldSize : 0; + } + p[0] += shift; + } + updateBBox(bbox, p); +} +function resetBBox(bbox) { + bbox[0] = bbox[1] = Infinity; + bbox[2] = bbox[3] = -Infinity; +} +function getTilePoints(geometry, pointBBox, polyBBox, canonical) { + const worldSize = Math.pow(2, canonical.z) * EXTENT$1; + const shifts = [canonical.x * EXTENT$1, canonical.y * EXTENT$1]; + const tilePoints = []; + for (const points of geometry) { + for (const point of points) { + const p = [point.x + shifts[0], point.y + shifts[1]]; + updatePoint(p, pointBBox, polyBBox, worldSize); + tilePoints.push(p); + } + } + return tilePoints; +} +function getTileLines(geometry, lineBBox, polyBBox, canonical) { + const worldSize = Math.pow(2, canonical.z) * EXTENT$1; + const shifts = [canonical.x * EXTENT$1, canonical.y * EXTENT$1]; + const tileLines = []; + for (const line of geometry) { + const tileLine = []; + for (const point of line) { + const p = [point.x + shifts[0], point.y + shifts[1]]; + updateBBox(lineBBox, p); + tileLine.push(p); + } + tileLines.push(tileLine); + } + if (lineBBox[2] - lineBBox[0] <= worldSize / 2) { + resetBBox(lineBBox); + for (const line of tileLines) { + for (const p of line) { + updatePoint(p, lineBBox, polyBBox, worldSize); + } + } + } + return tileLines; +} +function pointsWithinPolygons(ctx, polygonGeometry) { + const pointBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const polyBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const canonical = ctx.canonicalID(); + if (polygonGeometry.type === 'Polygon') { + const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) + return false; + for (const point of tilePoints) { + if (!pointWithinPolygon(point, tilePolygon)) + return false; + } + } + if (polygonGeometry.type === 'MultiPolygon') { + const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) + return false; + for (const point of tilePoints) { + if (!pointWithinPolygons(point, tilePolygons)) + return false; + } + } + return true; +} +function linesWithinPolygons(ctx, polygonGeometry) { + const lineBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const polyBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const canonical = ctx.canonicalID(); + if (polygonGeometry.type === 'Polygon') { + const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) + return false; + for (const line of tileLines) { + if (!lineStringWithinPolygon(line, tilePolygon)) + return false; + } + } + if (polygonGeometry.type === 'MultiPolygon') { + const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) + return false; + for (const line of tileLines) { + if (!lineStringWithinPolygons(line, tilePolygons)) + return false; + } + } + return true; +} +class Within { + constructor(geojson, geometries) { + this.type = BooleanType; + this.geojson = geojson; + this.geometries = geometries; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (isValue(args[1])) { + const geojson = args[1]; + if (geojson.type === 'FeatureCollection') { + const polygonsCoords = []; + for (const polygon of geojson.features) { + const { type, coordinates } = polygon.geometry; + if (type === 'Polygon') { + polygonsCoords.push(coordinates); + } + if (type === 'MultiPolygon') { + polygonsCoords.push(...coordinates); + } + } + if (polygonsCoords.length) { + const multipolygonWrapper = { + type: 'MultiPolygon', + coordinates: polygonsCoords + }; + return new Within(geojson, multipolygonWrapper); + } + } + else if (geojson.type === 'Feature') { + const type = geojson.geometry.type; + if (type === 'Polygon' || type === 'MultiPolygon') { + return new Within(geojson, geojson.geometry); + } + } + else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') { + return new Within(geojson, geojson); + } + } + return context.error('\'within\' expression requires valid geojson object that contains polygon geometry type.'); + } + evaluate(ctx) { + if (ctx.geometry() != null && ctx.canonicalID() != null) { + if (ctx.geometryType() === 'Point') { + return pointsWithinPolygons(ctx, this.geometries); + } + else if (ctx.geometryType() === 'LineString') { + return linesWithinPolygons(ctx, this.geometries); + } + } + return false; + } + eachChild() { } + outputDefined() { + return true; + } +} + +let TinyQueue$1 = class TinyQueue { + constructor(data = [], compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) { + this.data = data; + this.length = this.data.length; + this.compare = compare; + + if (this.length > 0) { + for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i); + } + } + + push(item) { + this.data.push(item); + this._up(this.length++); + } + + pop() { + if (this.length === 0) return undefined; + + const top = this.data[0]; + const bottom = this.data.pop(); + + if (--this.length > 0) { + this.data[0] = bottom; + this._down(0); + } + + return top; + } + + peek() { + return this.data[0]; + } + + _up(pos) { + const {data, compare} = this; + const item = data[pos]; + + while (pos > 0) { + const parent = (pos - 1) >> 1; + const current = data[parent]; + if (compare(item, current) >= 0) break; + data[pos] = current; + pos = parent; + } + + data[pos] = item; + } + + _down(pos) { + const {data, compare} = this; + const halfLength = this.length >> 1; + const item = data[pos]; + + while (pos < halfLength) { + let bestChild = (pos << 1) + 1; // initially it is the left child + const right = bestChild + 1; + + if (right < this.length && compare(data[right], data[bestChild]) < 0) { + bestChild = right; + } + if (compare(data[bestChild], item) >= 0) break; + + data[pos] = data[bestChild]; + pos = bestChild; + } + + data[pos] = item; + } +}; + +function quickselect(arr, k, left, right, compare) { + quickselectStep(arr, k, left, right || (arr.length - 1), compare || defaultCompare); +} + +function quickselectStep(arr, k, left, right, compare) { + + while (right > left) { + if (right - left > 600) { + var n = right - left + 1; + var m = k - left + 1; + var z = Math.log(n); + var s = 0.5 * Math.exp(2 * z / 3); + var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + quickselectStep(arr, k, newLeft, newRight, compare); + } + + var t = arr[k]; + var i = left; + var j = right; + + swap$2(arr, left, k); + if (compare(arr[right], t) > 0) swap$2(arr, left, right); + + while (i < j) { + swap$2(arr, i, j); + i++; + j--; + while (compare(arr[i], t) < 0) i++; + while (compare(arr[j], t) > 0) j--; + } + + if (compare(arr[left], t) === 0) swap$2(arr, left, j); + else { + j++; + swap$2(arr, j, right); + } + + if (j <= k) left = j + 1; + if (k <= j) right = j - 1; + } +} + +function swap$2(arr, i, j) { + var tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} + +function defaultCompare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * Classifies an array of rings into polygons with outer rings and holes + * @param rings - the rings to classify + * @param maxRings - the maximum number of rings to include in a polygon, use 0 to include all rings + * @returns an array of polygons with internal rings as holes + */ +function classifyRings$1(rings, maxRings) { + const len = rings.length; + if (len <= 1) + return [rings]; + const polygons = []; + let polygon; + let ccw; + for (const ring of rings) { + const area = calculateSignedArea(ring); + if (area === 0) + continue; + ring.area = Math.abs(area); + if (ccw === undefined) + ccw = area < 0; + if (ccw === area < 0) { + if (polygon) + polygons.push(polygon); + polygon = [ring]; + } + else { + polygon.push(ring); + } + } + if (polygon) + polygons.push(polygon); + // Earcut performance degrades with the # of rings in a polygon. For this + // reason, we limit strip out all but the `maxRings` largest rings. + if (maxRings > 1) { + for (let j = 0; j < polygons.length; j++) { + if (polygons[j].length <= maxRings) + continue; + quickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas); + polygons[j] = polygons[j].slice(0, maxRings); + } + } + return polygons; +} +function compareAreas(a, b) { + return b.area - a.area; +} +/** + * Returns the signed area for the polygon ring. Positive areas are exterior rings and + * have a clockwise winding. Negative areas are interior rings and have a counter clockwise + * ordering. + * + * @param ring - Exterior or interior ring + * @returns Signed area + */ +function calculateSignedArea(ring) { + let sum = 0; + for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + return sum; +} + +// This is taken from https://github.com/mapbox/cheap-ruler/ in order to take only the relevant parts +// Values that define WGS84 ellipsoid model of the Earth +const RE = 6378.137; // equatorial radius +const FE = 1 / 298.257223563; // flattening +const E2 = FE * (2 - FE); +const RAD = Math.PI / 180; +class CheapRuler { + constructor(lat) { + // Curvature formulas from https://en.wikipedia.org/wiki/Earth_radius#Meridional + const m = RAD * RE * 1000; + const coslat = Math.cos(lat * RAD); + const w2 = 1 / (1 - E2 * (1 - coslat * coslat)); + const w = Math.sqrt(w2); + // multipliers for converting longitude and latitude degrees into distance + this.kx = m * w * coslat; // based on normal radius of curvature + this.ky = m * w * w2 * (1 - E2); // based on meridonal radius of curvature + } + /** + * Given two points of the form [longitude, latitude], returns the distance. + * + * @param a - point [longitude, latitude] + * @param b - point [longitude, latitude] + * @returns distance + * @example + * const distance = ruler.distance([30.5, 50.5], [30.51, 50.49]); + * //=distance + */ + distance(a, b) { + const dx = this.wrap(a[0] - b[0]) * this.kx; + const dy = (a[1] - b[1]) * this.ky; + return Math.sqrt(dx * dx + dy * dy); + } + /** + * Returns an object of the form {point, index, t}, where point is closest point on the line + * from the given point, index is the start index of the segment with the closest point, + * and t is a parameter from 0 to 1 that indicates where the closest point is on that segment. + * + * @param line - an array of points that form the line + * @param p - point [longitude, latitude] + * @returns the nearest point, its index in the array and the proportion along the line + * @example + * const point = ruler.pointOnLine(line, [-67.04, 50.5]).point; + * //=point + */ + pointOnLine(line, p) { + let minDist = Infinity; + let minX, minY, minI, minT; + for (let i = 0; i < line.length - 1; i++) { + let x = line[i][0]; + let y = line[i][1]; + let dx = this.wrap(line[i + 1][0] - x) * this.kx; + let dy = (line[i + 1][1] - y) * this.ky; + let t = 0; + if (dx !== 0 || dy !== 0) { + t = (this.wrap(p[0] - x) * this.kx * dx + (p[1] - y) * this.ky * dy) / (dx * dx + dy * dy); + if (t > 1) { + x = line[i + 1][0]; + y = line[i + 1][1]; + } + else if (t > 0) { + x += (dx / this.kx) * t; + y += (dy / this.ky) * t; + } + } + dx = this.wrap(p[0] - x) * this.kx; + dy = (p[1] - y) * this.ky; + const sqDist = dx * dx + dy * dy; + if (sqDist < minDist) { + minDist = sqDist; + minX = x; + minY = y; + minI = i; + minT = t; + } + } + return { + point: [minX, minY], + index: minI, + t: Math.max(0, Math.min(1, minT)) + }; + } + wrap(deg) { + while (deg < -180) + deg += 360; + while (deg > 180) + deg -= 360; + return deg; + } +} + +const MinPointsSize = 100; +const MinLinePointsSize = 50; +function compareDistPair(a, b) { + return b[0] - a[0]; +} +function getRangeSize(range) { + return range[1] - range[0] + 1; +} +function isRangeSafe(range, threshold) { + return range[1] >= range[0] && range[1] < threshold; +} +function splitRange(range, isLine) { + if (range[0] > range[1]) { + return [null, null]; + } + const size = getRangeSize(range); + if (isLine) { + if (size === 2) { + return [range, null]; + } + const size1 = Math.floor(size / 2); + return [[range[0], range[0] + size1], + [range[0] + size1, range[1]]]; + } + if (size === 1) { + return [range, null]; + } + const size1 = Math.floor(size / 2) - 1; + return [[range[0], range[0] + size1], + [range[0] + size1 + 1, range[1]]]; +} +function getBBox(coords, range) { + if (!isRangeSafe(range, coords.length)) { + return [Infinity, Infinity, -Infinity, -Infinity]; + } + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + for (let i = range[0]; i <= range[1]; ++i) { + updateBBox(bbox, coords[i]); + } + return bbox; +} +function getPolygonBBox(polygon) { + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + for (const ring of polygon) { + for (const coord of ring) { + updateBBox(bbox, coord); + } + } + return bbox; +} +function isValidBBox(bbox) { + return bbox[0] !== -Infinity && bbox[1] !== -Infinity && bbox[2] !== Infinity && bbox[3] !== Infinity; +} +// Calculate the distance between two bounding boxes. +// Calculate the delta in x and y direction, and use two fake points {0.0, 0.0} +// and {dx, dy} to calculate the distance. Distance will be 0.0 if bounding box are overlapping. +function bboxToBBoxDistance(bbox1, bbox2, ruler) { + if (!isValidBBox(bbox1) || !isValidBBox(bbox2)) { + return NaN; + } + let dx = 0.0; + let dy = 0.0; + // bbox1 in left side + if (bbox1[2] < bbox2[0]) { + dx = bbox2[0] - bbox1[2]; + } + // bbox1 in right side + if (bbox1[0] > bbox2[2]) { + dx = bbox1[0] - bbox2[2]; + } + // bbox1 in above side + if (bbox1[1] > bbox2[3]) { + dy = bbox1[1] - bbox2[3]; + } + // bbox1 in down side + if (bbox1[3] < bbox2[1]) { + dy = bbox2[1] - bbox1[3]; + } + return ruler.distance([0.0, 0.0], [dx, dy]); +} +function pointToLineDistance(point, line, ruler) { + const nearestPoint = ruler.pointOnLine(line, point); + return ruler.distance(point, nearestPoint.point); +} +function segmentToSegmentDistance(p1, p2, q1, q2, ruler) { + const dist1 = Math.min(pointToLineDistance(p1, [q1, q2], ruler), pointToLineDistance(p2, [q1, q2], ruler)); + const dist2 = Math.min(pointToLineDistance(q1, [p1, p2], ruler), pointToLineDistance(q2, [p1, p2], ruler)); + return Math.min(dist1, dist2); +} +function lineToLineDistance(line1, range1, line2, range2, ruler) { + const rangeSafe = isRangeSafe(range1, line1.length) && isRangeSafe(range2, line2.length); + if (!rangeSafe) { + return Infinity; + } + let dist = Infinity; + for (let i = range1[0]; i < range1[1]; ++i) { + const p1 = line1[i]; + const p2 = line1[i + 1]; + for (let j = range2[0]; j < range2[1]; ++j) { + const q1 = line2[j]; + const q2 = line2[j + 1]; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } + dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); + } + } + return dist; +} +function pointsToPointsDistance(points1, range1, points2, range2, ruler) { + const rangeSafe = isRangeSafe(range1, points1.length) && isRangeSafe(range2, points2.length); + if (!rangeSafe) { + return NaN; + } + let dist = Infinity; + for (let i = range1[0]; i <= range1[1]; ++i) { + for (let j = range2[0]; j <= range2[1]; ++j) { + dist = Math.min(dist, ruler.distance(points1[i], points2[j])); + if (dist === 0.0) { + return dist; + } + } + } + return dist; +} +function pointToPolygonDistance(point, polygon, ruler) { + if (pointWithinPolygon(point, polygon, true)) { + return 0.0; + } + let dist = Infinity; + for (const ring of polygon) { + const front = ring[0]; + const back = ring[ring.length - 1]; + if (front !== back) { + dist = Math.min(dist, pointToLineDistance(point, [back, front], ruler)); + if (dist === 0.0) { + return dist; + } + } + const nearestPoint = ruler.pointOnLine(ring, point); + dist = Math.min(dist, ruler.distance(point, nearestPoint.point)); + if (dist === 0.0) { + return dist; + } + } + return dist; +} +function lineToPolygonDistance(line, range, polygon, ruler) { + if (!isRangeSafe(range, line.length)) { + return NaN; + } + for (let i = range[0]; i <= range[1]; ++i) { + if (pointWithinPolygon(line[i], polygon, true)) { + return 0.0; + } + } + let dist = Infinity; + for (let i = range[0]; i < range[1]; ++i) { + const p1 = line[i]; + const p2 = line[i + 1]; + for (const ring of polygon) { + for (let j = 0, len = ring.length, k = len - 1; j < len; k = j++) { + const q1 = ring[k]; + const q2 = ring[j]; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } + dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); + } + } + } + return dist; +} +function polygonIntersect(poly1, poly2) { + for (const ring of poly1) { + for (const point of ring) { + if (pointWithinPolygon(point, poly2, true)) { + return true; + } + } + } + return false; +} +function polygonToPolygonDistance(polygon1, polygon2, ruler, currentMiniDist = Infinity) { + const bbox1 = getPolygonBBox(polygon1); + const bbox2 = getPolygonBBox(polygon2); + if (currentMiniDist !== Infinity && bboxToBBoxDistance(bbox1, bbox2, ruler) >= currentMiniDist) { + return currentMiniDist; + } + if (boxWithinBox(bbox1, bbox2)) { + if (polygonIntersect(polygon1, polygon2)) { + return 0.0; + } + } + else if (polygonIntersect(polygon2, polygon1)) { + return 0.0; + } + let dist = Infinity; + for (const ring1 of polygon1) { + for (let i = 0, len1 = ring1.length, l = len1 - 1; i < len1; l = i++) { + const p1 = ring1[l]; + const p2 = ring1[i]; + for (const ring2 of polygon2) { + for (let j = 0, len2 = ring2.length, k = len2 - 1; j < len2; k = j++) { + const q1 = ring2[k]; + const q2 = ring2[j]; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } + dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); + } + } + } + } + return dist; +} +function updateQueue(distQueue, miniDist, ruler, points, polyBBox, rangeA) { + if (!rangeA) { + return; + } + const tempDist = bboxToBBoxDistance(getBBox(points, rangeA), polyBBox, ruler); + // Insert new pair to the queue if the bbox distance is less than + // miniDist, The pair with biggest distance will be at the top + if (tempDist < miniDist) { + distQueue.push([tempDist, rangeA, [0, 0]]); + } +} +function updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, range1, range2) { + if (!range1 || !range2) { + return; + } + const tempDist = bboxToBBoxDistance(getBBox(pointSet1, range1), getBBox(pointSet2, range2), ruler); + // Insert new pair to the queue if the bbox distance is less than + // miniDist, The pair with biggest distance will be at the top + if (tempDist < miniDist) { + distQueue.push([tempDist, range1, range2]); + } +} +// Divide and conquer, the time complexity is O(n*lgn), faster than Brute force +// O(n*n) Most of the time, use index for in-place processing. +function pointsToPolygonDistance(points, isLine, polygon, ruler, currentMiniDist = Infinity) { + let miniDist = Math.min(ruler.distance(points[0], polygon[0][0]), currentMiniDist); + if (miniDist === 0.0) { + return miniDist; + } + const distQueue = new TinyQueue$1([[0, [0, points.length - 1], [0, 0]]], compareDistPair); + const polyBBox = getPolygonBBox(polygon); + while (distQueue.length > 0) { + const distPair = distQueue.pop(); + if (distPair[0] >= miniDist) { + continue; + } + const range = distPair[1]; + // In case the set size are relatively small, we could use brute-force directly + const threshold = isLine ? MinLinePointsSize : MinPointsSize; + if (getRangeSize(range) <= threshold) { + if (!isRangeSafe(range, points.length)) { + return NaN; + } + if (isLine) { + const tempDist = lineToPolygonDistance(points, range, polygon, ruler); + if (isNaN(tempDist) || tempDist === 0.0) { + return tempDist; + } + miniDist = Math.min(miniDist, tempDist); + } + else { + for (let i = range[0]; i <= range[1]; ++i) { + const tempDist = pointToPolygonDistance(points[i], polygon, ruler); + miniDist = Math.min(miniDist, tempDist); + if (miniDist === 0.0) { + return 0.0; + } + } + } + } + else { + const newRangesA = splitRange(range, isLine); + updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[0]); + updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[1]); + } + } + return miniDist; +} +function pointSetToPointSetDistance(pointSet1, isLine1, pointSet2, isLine2, ruler, currentMiniDist = Infinity) { + let miniDist = Math.min(currentMiniDist, ruler.distance(pointSet1[0], pointSet2[0])); + if (miniDist === 0.0) { + return miniDist; + } + const distQueue = new TinyQueue$1([[0, [0, pointSet1.length - 1], [0, pointSet2.length - 1]]], compareDistPair); + while (distQueue.length > 0) { + const distPair = distQueue.pop(); + if (distPair[0] >= miniDist) { + continue; + } + const rangeA = distPair[1]; + const rangeB = distPair[2]; + const threshold1 = isLine1 ? MinLinePointsSize : MinPointsSize; + const threshold2 = isLine2 ? MinLinePointsSize : MinPointsSize; + // In case the set size are relatively small, we could use brute-force directly + if (getRangeSize(rangeA) <= threshold1 && getRangeSize(rangeB) <= threshold2) { + if (!isRangeSafe(rangeA, pointSet1.length) && isRangeSafe(rangeB, pointSet2.length)) { + return NaN; + } + let tempDist; + if (isLine1 && isLine2) { + tempDist = lineToLineDistance(pointSet1, rangeA, pointSet2, rangeB, ruler); + miniDist = Math.min(miniDist, tempDist); + } + else if (isLine1 && !isLine2) { + const sublibe = pointSet1.slice(rangeA[0], rangeA[1] + 1); + for (let i = rangeB[0]; i <= rangeB[1]; ++i) { + tempDist = pointToLineDistance(pointSet2[i], sublibe, ruler); + miniDist = Math.min(miniDist, tempDist); + if (miniDist === 0.0) { + return miniDist; + } + } + } + else if (!isLine1 && isLine2) { + const sublibe = pointSet2.slice(rangeB[0], rangeB[1] + 1); + for (let i = rangeA[0]; i <= rangeA[1]; ++i) { + tempDist = pointToLineDistance(pointSet1[i], sublibe, ruler); + miniDist = Math.min(miniDist, tempDist); + if (miniDist === 0.0) { + return miniDist; + } + } + } + else { + tempDist = pointsToPointsDistance(pointSet1, rangeA, pointSet2, rangeB, ruler); + miniDist = Math.min(miniDist, tempDist); + } + } + else { + const newRangesA = splitRange(rangeA, isLine1); + const newRangesB = splitRange(rangeB, isLine2); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[0]); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[1]); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[0]); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[1]); + } + } + return miniDist; +} +function pointToGeometryDistance(ctx, geometries) { + const tilePoints = ctx.geometry(); + const pointPosition = tilePoints.flat().map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); + if (tilePoints.length === 0) { + return NaN; + } + const ruler = new CheapRuler(pointPosition[0][1]); + let dist = Infinity; + for (const geometry of geometries) { + switch (geometry.type) { + case 'Point': + dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, [geometry.coordinates], false, ruler, dist)); + break; + case 'LineString': + dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, geometry.coordinates, true, ruler, dist)); + break; + case 'Polygon': + dist = Math.min(dist, pointsToPolygonDistance(pointPosition, false, geometry.coordinates, ruler, dist)); + break; + } + if (dist === 0.0) { + return dist; + } + } + return dist; +} +function lineStringToGeometryDistance(ctx, geometries) { + const tileLine = ctx.geometry(); + const linePositions = tileLine.flat().map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); + if (tileLine.length === 0) { + return NaN; + } + const ruler = new CheapRuler(linePositions[0][1]); + let dist = Infinity; + for (const geometry of geometries) { + switch (geometry.type) { + case 'Point': + dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, [geometry.coordinates], false, ruler, dist)); + break; + case 'LineString': + dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, geometry.coordinates, true, ruler, dist)); + break; + case 'Polygon': + dist = Math.min(dist, pointsToPolygonDistance(linePositions, true, geometry.coordinates, ruler, dist)); + break; + } + if (dist === 0.0) { + return dist; + } + } + return dist; +} +function polygonToGeometryDistance(ctx, geometries) { + const tilePolygon = ctx.geometry(); + if (tilePolygon.length === 0 || tilePolygon[0].length === 0) { + return NaN; + } + const polygons = classifyRings$1(tilePolygon, 0).map(polygon => { + return polygon.map(ring => { + return ring.map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); + }); + }); + const ruler = new CheapRuler(polygons[0][0][0][1]); + let dist = Infinity; + for (const geometry of geometries) { + for (const polygon of polygons) { + switch (geometry.type) { + case 'Point': + dist = Math.min(dist, pointsToPolygonDistance([geometry.coordinates], false, polygon, ruler, dist)); + break; + case 'LineString': + dist = Math.min(dist, pointsToPolygonDistance(geometry.coordinates, true, polygon, ruler, dist)); + break; + case 'Polygon': + dist = Math.min(dist, polygonToPolygonDistance(polygon, geometry.coordinates, ruler, dist)); + break; + } + if (dist === 0.0) { + return dist; + } + } + } + return dist; +} +function toSimpleGeometry(geometry) { + if (geometry.type === 'MultiPolygon') { + return geometry.coordinates.map(polygon => { + return { + type: 'Polygon', + coordinates: polygon + }; + }); + } + if (geometry.type === 'MultiLineString') { + return geometry.coordinates.map(lineString => { + return { + type: 'LineString', + coordinates: lineString + }; + }); + } + if (geometry.type === 'MultiPoint') { + return geometry.coordinates.map(point => { + return { + type: 'Point', + coordinates: point + }; + }); + } + return [geometry]; +} +class Distance { + constructor(geojson, geometries) { + this.type = NumberType; + this.geojson = geojson; + this.geometries = geometries; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`'distance' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (isValue(args[1])) { + const geojson = args[1]; + if (geojson.type === 'FeatureCollection') { + return new Distance(geojson, geojson.features.map(feature => toSimpleGeometry(feature.geometry)).flat()); + } + else if (geojson.type === 'Feature') { + return new Distance(geojson, toSimpleGeometry(geojson.geometry)); + } + else if ('type' in geojson && 'coordinates' in geojson) { + return new Distance(geojson, toSimpleGeometry(geojson)); + } + } + return context.error('\'distance\' expression requires valid geojson object that contains polygon geometry type.'); + } + evaluate(ctx) { + if (ctx.geometry() != null && ctx.canonicalID() != null) { + if (ctx.geometryType() === 'Point') { + return pointToGeometryDistance(ctx, this.geometries); + } + else if (ctx.geometryType() === 'LineString') { + return lineStringToGeometryDistance(ctx, this.geometries); + } + else if (ctx.geometryType() === 'Polygon') { + return polygonToGeometryDistance(ctx, this.geometries); + } + } + return NaN; + } + eachChild() { } + outputDefined() { + return true; + } +} + +const expressions$1 = { + // special forms + '==': Equals, + '!=': NotEquals, + '>': GreaterThan, + '<': LessThan, + '>=': GreaterThanOrEqual, + '<=': LessThanOrEqual, + 'array': Assertion, + 'at': At, + 'boolean': Assertion, + 'case': Case, + 'coalesce': Coalesce, + 'collator': CollatorExpression, + 'format': FormatExpression, + 'image': ImageExpression, + 'in': In, + 'index-of': IndexOf, + 'interpolate': Interpolate, + 'interpolate-hcl': Interpolate, + 'interpolate-lab': Interpolate, + 'length': Length, + 'let': Let, + 'literal': Literal, + 'match': Match, + 'number': Assertion, + 'number-format': NumberFormat, + 'object': Assertion, + 'slice': Slice, + 'step': Step, + 'string': Assertion, + 'to-boolean': Coercion, + 'to-color': Coercion, + 'to-number': Coercion, + 'to-string': Coercion, + 'var': Var, + 'within': Within, + 'distance': Distance +}; + +class CompoundExpression { + constructor(name, type, evaluate, args) { + this.name = name; + this.type = type; + this._evaluate = evaluate; + this.args = args; + } + evaluate(ctx) { + return this._evaluate(ctx, this.args); + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return false; + } + static parse(args, context) { + const op = args[0]; + const definition = CompoundExpression.definitions[op]; + if (!definition) { + return context.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); + } + // Now check argument types against each signature + const type = Array.isArray(definition) ? + definition[0] : definition.type; + const availableOverloads = Array.isArray(definition) ? + [[definition[1], definition[2]]] : + definition.overloads; + const overloads = availableOverloads.filter(([signature]) => (!Array.isArray(signature) || // varags + signature.length === args.length - 1 // correct param count + )); + let signatureContext = null; + for (const [params, evaluate] of overloads) { + // Use a fresh context for each attempted signature so that, if + // we eventually succeed, we haven't polluted `context.errors`. + signatureContext = new ParsingContext(context.registry, isExpressionConstant, context.path, null, context.scope); + // First parse all the args, potentially coercing to the + // types expected by this overload. + const parsedArgs = []; + let argParseFailed = false; + for (let i = 1; i < args.length; i++) { + const arg = args[i]; + const expectedType = Array.isArray(params) ? + params[i - 1] : + params.type; + const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType); + if (!parsed) { + argParseFailed = true; + break; + } + parsedArgs.push(parsed); + } + if (argParseFailed) { + // Couldn't coerce args of this overload to expected type, move + // on to next one. + continue; + } + if (Array.isArray(params)) { + if (params.length !== parsedArgs.length) { + signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`); + continue; + } + } + for (let i = 0; i < parsedArgs.length; i++) { + const expected = Array.isArray(params) ? params[i] : params.type; + const arg = parsedArgs[i]; + signatureContext.concat(i + 1).checkSubtype(expected, arg.type); + } + if (signatureContext.errors.length === 0) { + return new CompoundExpression(op, type, evaluate, parsedArgs); + } + } + if (overloads.length === 1) { + context.errors.push(...signatureContext.errors); + } + else { + const expected = overloads.length ? overloads : availableOverloads; + const signatures = expected + .map(([params]) => stringifySignature(params)) + .join(' | '); + const actualTypes = []; + // For error message, re-parse arguments without trying to + // apply any coercions + for (let i = 1; i < args.length; i++) { + const parsed = context.parse(args[i], 1 + actualTypes.length); + if (!parsed) + return null; + actualTypes.push(toString$1(parsed.type)); + } + context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`); + } + return null; + } + static register(registry, definitions) { + CompoundExpression.definitions = definitions; + for (const name in definitions) { + registry[name] = CompoundExpression; + } + } +} +function rgba(ctx, [r, g, b, a]) { + r = r.evaluate(ctx); + g = g.evaluate(ctx); + b = b.evaluate(ctx); + const alpha = a ? a.evaluate(ctx) : 1; + const error = validateRGBA(r, g, b, alpha); + if (error) + throw new RuntimeError(error); + return new Color(r / 255, g / 255, b / 255, alpha, false); +} +function has(key, obj) { + return key in obj; +} +function get(key, obj) { + const v = obj[key]; + return typeof v === 'undefined' ? null : v; +} +function binarySearch(v, a, i, j) { + while (i <= j) { + const m = (i + j) >> 1; + if (a[m] === v) + return true; + if (a[m] > v) + j = m - 1; + else + i = m + 1; + } + return false; +} +function varargs(type) { + return { type }; +} +CompoundExpression.register(expressions$1, { + 'error': [ + ErrorType, + [StringType], + (ctx, [v]) => { throw new RuntimeError(v.evaluate(ctx)); } + ], + 'typeof': [ + StringType, + [ValueType], + (ctx, [v]) => toString$1(typeOf(v.evaluate(ctx))) + ], + 'to-rgba': [ + array$1(NumberType, 4), + [ColorType], + (ctx, [v]) => { + const [r, g, b, a] = v.evaluate(ctx).rgb; + return [r * 255, g * 255, b * 255, a]; + }, + ], + 'rgb': [ + ColorType, + [NumberType, NumberType, NumberType], + rgba + ], + 'rgba': [ + ColorType, + [NumberType, NumberType, NumberType, NumberType], + rgba + ], + 'has': { + type: BooleanType, + overloads: [ + [ + [StringType], + (ctx, [key]) => has(key.evaluate(ctx), ctx.properties()) + ], [ + [StringType, ObjectType], + (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx)) + ] + ] + }, + 'get': { + type: ValueType, + overloads: [ + [ + [StringType], + (ctx, [key]) => get(key.evaluate(ctx), ctx.properties()) + ], [ + [StringType, ObjectType], + (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx)) + ] + ] + }, + 'feature-state': [ + ValueType, + [StringType], + (ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {}) + ], + 'properties': [ + ObjectType, + [], + (ctx) => ctx.properties() + ], + 'geometry-type': [ + StringType, + [], + (ctx) => ctx.geometryType() + ], + 'id': [ + ValueType, + [], + (ctx) => ctx.id() + ], + 'zoom': [ + NumberType, + [], + (ctx) => ctx.globals.zoom + ], + 'heatmap-density': [ + NumberType, + [], + (ctx) => ctx.globals.heatmapDensity || 0 + ], + 'line-progress': [ + NumberType, + [], + (ctx) => ctx.globals.lineProgress || 0 + ], + 'accumulated': [ + ValueType, + [], + (ctx) => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated + ], + '+': [ + NumberType, + varargs(NumberType), + (ctx, args) => { + let result = 0; + for (const arg of args) { + result += arg.evaluate(ctx); + } + return result; + } + ], + '*': [ + NumberType, + varargs(NumberType), + (ctx, args) => { + let result = 1; + for (const arg of args) { + result *= arg.evaluate(ctx); + } + return result; + } + ], + '-': { + type: NumberType, + overloads: [ + [ + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx) + ], [ + [NumberType], + (ctx, [a]) => -a.evaluate(ctx) + ] + ] + }, + '/': [ + NumberType, + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx) + ], + '%': [ + NumberType, + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx) + ], + 'ln2': [ + NumberType, + [], + () => Math.LN2 + ], + 'pi': [ + NumberType, + [], + () => Math.PI + ], + 'e': [ + NumberType, + [], + () => Math.E + ], + '^': [ + NumberType, + [NumberType, NumberType], + (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx)) + ], + 'sqrt': [ + NumberType, + [NumberType], + (ctx, [x]) => Math.sqrt(x.evaluate(ctx)) + ], + 'log10': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10 + ], + 'ln': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) + ], + 'log2': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2 + ], + 'sin': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.sin(n.evaluate(ctx)) + ], + 'cos': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.cos(n.evaluate(ctx)) + ], + 'tan': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.tan(n.evaluate(ctx)) + ], + 'asin': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.asin(n.evaluate(ctx)) + ], + 'acos': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.acos(n.evaluate(ctx)) + ], + 'atan': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.atan(n.evaluate(ctx)) + ], + 'min': [ + NumberType, + varargs(NumberType), + (ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx))) + ], + 'max': [ + NumberType, + varargs(NumberType), + (ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx))) + ], + 'abs': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.abs(n.evaluate(ctx)) + ], + 'round': [ + NumberType, + [NumberType], + (ctx, [n]) => { + const v = n.evaluate(ctx); + // Javascript's Math.round() rounds towards +Infinity for halfway + // values, even when they're negative. It's more common to round + // away from 0 (e.g., this is what python and C++ do) + return v < 0 ? -Math.round(-v) : Math.round(v); + } + ], + 'floor': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.floor(n.evaluate(ctx)) + ], + 'ceil': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.ceil(n.evaluate(ctx)) + ], + 'filter-==': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => ctx.properties()[k.value] === v.value + ], + 'filter-id-==': [ + BooleanType, + [ValueType], + (ctx, [v]) => ctx.id() === v.value + ], + 'filter-type-==': [ + BooleanType, + [StringType], + (ctx, [v]) => ctx.geometryType() === v.value + ], + 'filter-<': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a < b; + } + ], + 'filter-id-<': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a < b; + } + ], + 'filter->': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a > b; + } + ], + 'filter-id->': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a > b; + } + ], + 'filter-<=': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a <= b; + } + ], + 'filter-id-<=': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a <= b; + } + ], + 'filter->=': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-id->=': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-has': [ + BooleanType, + [ValueType], + (ctx, [k]) => k.value in ctx.properties() + ], + 'filter-has-id': [ + BooleanType, + [], + (ctx) => (ctx.id() !== null && ctx.id() !== undefined) + ], + 'filter-type-in': [ + BooleanType, + [array$1(StringType)], + (ctx, [v]) => v.value.indexOf(ctx.geometryType()) >= 0 + ], + 'filter-id-in': [ + BooleanType, + [array$1(ValueType)], + (ctx, [v]) => v.value.indexOf(ctx.id()) >= 0 + ], + 'filter-in-small': [ + BooleanType, + [StringType, array$1(ValueType)], + // assumes v is an array literal + (ctx, [k, v]) => v.value.indexOf(ctx.properties()[k.value]) >= 0 + ], + 'filter-in-large': [ + BooleanType, + [StringType, array$1(ValueType)], + // assumes v is a array literal with values sorted in ascending order and of a single type + (ctx, [k, v]) => binarySearch(ctx.properties()[k.value], v.value, 0, v.value.length - 1) + ], + 'all': { + type: BooleanType, + overloads: [ + [ + [BooleanType, BooleanType], + (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx) + ], + [ + varargs(BooleanType), + (ctx, args) => { + for (const arg of args) { + if (!arg.evaluate(ctx)) + return false; + } + return true; + } + ] + ] + }, + 'any': { + type: BooleanType, + overloads: [ + [ + [BooleanType, BooleanType], + (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx) + ], + [ + varargs(BooleanType), + (ctx, args) => { + for (const arg of args) { + if (arg.evaluate(ctx)) + return true; + } + return false; + } + ] + ] + }, + '!': [ + BooleanType, + [BooleanType], + (ctx, [b]) => !b.evaluate(ctx) + ], + 'is-supported-script': [ + BooleanType, + [StringType], + // At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant + (ctx, [s]) => { + const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript; + if (isSupportedScript) { + return isSupportedScript(s.evaluate(ctx)); + } + return true; + } + ], + 'upcase': [ + StringType, + [StringType], + (ctx, [s]) => s.evaluate(ctx).toUpperCase() + ], + 'downcase': [ + StringType, + [StringType], + (ctx, [s]) => s.evaluate(ctx).toLowerCase() + ], + 'concat': [ + StringType, + varargs(ValueType), + (ctx, args) => args.map(arg => toString(arg.evaluate(ctx))).join('') + ], + 'resolved-locale': [ + StringType, + [CollatorType], + (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale() + ] +}); +function stringifySignature(signature) { + if (Array.isArray(signature)) { + return `(${signature.map(toString$1).join(', ')})`; + } + else { + return `(${toString$1(signature.type)}...)`; + } +} +function isExpressionConstant(expression) { + if (expression instanceof Var) { + return isExpressionConstant(expression.boundExpression); + } + else if (expression instanceof CompoundExpression && expression.name === 'error') { + return false; + } + else if (expression instanceof CollatorExpression) { + // Although the results of a Collator expression with fixed arguments + // generally shouldn't change between executions, we can't serialize them + // as constant expressions because results change based on environment. + return false; + } + else if (expression instanceof Within) { + return false; + } + else if (expression instanceof Distance) { + return false; + } + const isTypeAnnotation = expression instanceof Coercion || + expression instanceof Assertion; + let childrenConstant = true; + expression.eachChild(child => { + // We can _almost_ assume that if `expressions` children are constant, + // they would already have been evaluated to Literal values when they + // were parsed. Type annotations are the exception, because they might + // have been inferred and added after a child was parsed. + // So we recurse into isConstant() for the children of type annotations, + // but otherwise simply check whether they are Literals. + if (isTypeAnnotation) { + childrenConstant = childrenConstant && isExpressionConstant(child); + } + else { + childrenConstant = childrenConstant && child instanceof Literal; + } + }); + if (!childrenConstant) { + return false; + } + return isFeatureConstant(expression) && + isGlobalPropertyConstant(expression, ['zoom', 'heatmap-density', 'line-progress', 'accumulated', 'is-supported-script']); +} +function isFeatureConstant(e) { + if (e instanceof CompoundExpression) { + if (e.name === 'get' && e.args.length === 1) { + return false; + } + else if (e.name === 'feature-state') { + return false; + } + else if (e.name === 'has' && e.args.length === 1) { + return false; + } + else if (e.name === 'properties' || + e.name === 'geometry-type' || + e.name === 'id') { + return false; + } + else if (/^filter-/.test(e.name)) { + return false; + } + } + if (e instanceof Within) { + return false; + } + if (e instanceof Distance) { + return false; + } + let result = true; + e.eachChild(arg => { + if (result && !isFeatureConstant(arg)) { + result = false; + } + }); + return result; +} +function isStateConstant(e) { + if (e instanceof CompoundExpression) { + if (e.name === 'feature-state') { + return false; + } + } + let result = true; + e.eachChild(arg => { + if (result && !isStateConstant(arg)) { + result = false; + } + }); + return result; +} +function isGlobalPropertyConstant(e, properties) { + if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) { + return false; + } + let result = true; + e.eachChild((arg) => { + if (result && !isGlobalPropertyConstant(arg, properties)) { + result = false; + } + }); + return result; +} + +function success(value) { + return { result: 'success', value }; +} +function error(value) { + return { result: 'error', value }; +} + +function supportsPropertyExpression(spec) { + return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-data-driven'; +} +function supportsZoomExpression(spec) { + return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1; +} +function supportsInterpolation(spec) { + return !!spec.expression && spec.expression.interpolated; +} + +function getType(val) { + if (val instanceof Number) { + return 'number'; + } + else if (val instanceof String) { + return 'string'; + } + else if (val instanceof Boolean) { + return 'boolean'; + } + else if (Array.isArray(val)) { + return 'array'; + } + else if (val === null) { + return 'null'; + } + else { + return typeof val; + } +} + +function isFunction$1(value) { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} +function identityFunction(x) { + return x; +} +function createFunction(parameters, propertySpec) { + const isColor = propertySpec.type === 'color'; + const zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object'; + const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + const zoomDependent = zoomAndFeatureDependent || !featureDependent; + const type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval'); + if (isColor || propertySpec.type === 'padding') { + const parseFn = isColor ? Color.parse : Padding.parse; + parameters = extendBy({}, parameters); + if (parameters.stops) { + parameters.stops = parameters.stops.map((stop) => { + return [stop[0], parseFn(stop[1])]; + }); + } + if (parameters.default) { + parameters.default = parseFn(parameters.default); + } + else { + parameters.default = parseFn(propertySpec.default); + } + } + if (parameters.colorSpace && !isSupportedInterpolationColorSpace(parameters.colorSpace)) { + throw new Error(`Unknown color space: "${parameters.colorSpace}"`); + } + let innerFun; + let hashedStops; + let categoricalKeyType; + if (type === 'exponential') { + innerFun = evaluateExponentialFunction; + } + else if (type === 'interval') { + innerFun = evaluateIntervalFunction; + } + else if (type === 'categorical') { + innerFun = evaluateCategoricalFunction; + // For categorical functions, generate an Object as a hashmap of the stops for fast searching + hashedStops = Object.create(null); + for (const stop of parameters.stops) { + hashedStops[stop[0]] = stop[1]; + } + // Infer key type based on first stop key-- used to encforce strict type checking later + categoricalKeyType = typeof parameters.stops[0][0]; + } + else if (type === 'identity') { + innerFun = evaluateIdentityFunction; + } + else { + throw new Error(`Unknown function type "${type}"`); + } + if (zoomAndFeatureDependent) { + const featureFunctions = {}; + const zoomStops = []; + for (let s = 0; s < parameters.stops.length; s++) { + const stop = parameters.stops[s]; + const zoom = stop[0].zoom; + if (featureFunctions[zoom] === undefined) { + featureFunctions[zoom] = { + zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default, + stops: [] + }; + zoomStops.push(zoom); + } + featureFunctions[zoom].stops.push([stop[0].value, stop[1]]); + } + const featureFunctionStops = []; + for (const z of zoomStops) { + featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]); + } + const interpolationType = { name: 'linear' }; + return { + kind: 'composite', + interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: featureFunctionStops.map(s => s[0]), + evaluate({ zoom }, properties) { + return evaluateExponentialFunction({ + stops: featureFunctionStops, + base: parameters.base + }, propertySpec, zoom).evaluate(zoom, properties); + } + }; + } + else if (zoomDependent) { + const interpolationType = type === 'exponential' ? + { name: 'exponential', base: parameters.base !== undefined ? parameters.base : 1 } : null; + return { + kind: 'camera', + interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: parameters.stops.map(s => s[0]), + evaluate: ({ zoom }) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType) + }; + } + else { + return { + kind: 'source', + evaluate(_, feature) { + const value = feature && feature.properties ? feature.properties[parameters.property] : undefined; + if (value === undefined) { + return coalesce$1(parameters.default, propertySpec.default); + } + return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType); + } + }; + } +} +function coalesce$1(a, b, c) { + if (a !== undefined) + return a; + if (b !== undefined) + return b; + if (c !== undefined) + return c; +} +function evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) { + const evaluated = typeof input === keyType ? hashedStops[input] : undefined; // Enforce strict typing on input + return coalesce$1(evaluated, parameters.default, propertySpec.default); +} +function evaluateIntervalFunction(parameters, propertySpec, input) { + // Edge cases + if (getType(input) !== 'number') + return coalesce$1(parameters.default, propertySpec.default); + const n = parameters.stops.length; + if (n === 1) + return parameters.stops[0][1]; + if (input <= parameters.stops[0][0]) + return parameters.stops[0][1]; + if (input >= parameters.stops[n - 1][0]) + return parameters.stops[n - 1][1]; + const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); + return parameters.stops[index][1]; +} +function evaluateExponentialFunction(parameters, propertySpec, input) { + const base = parameters.base !== undefined ? parameters.base : 1; + // Edge cases + if (getType(input) !== 'number') + return coalesce$1(parameters.default, propertySpec.default); + const n = parameters.stops.length; + if (n === 1) + return parameters.stops[0][1]; + if (input <= parameters.stops[0][0]) + return parameters.stops[0][1]; + if (input >= parameters.stops[n - 1][0]) + return parameters.stops[n - 1][1]; + const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); + const t = interpolationFactor(input, base, parameters.stops[index][0], parameters.stops[index + 1][0]); + const outputLower = parameters.stops[index][1]; + const outputUpper = parameters.stops[index + 1][1]; + const interp = interpolate[propertySpec.type] || identityFunction; + if (typeof outputLower.evaluate === 'function') { + return { + evaluate(...args) { + const evaluatedLower = outputLower.evaluate.apply(undefined, args); + const evaluatedUpper = outputUpper.evaluate.apply(undefined, args); + // Special case for fill-outline-color, which has no spec default. + if (evaluatedLower === undefined || evaluatedUpper === undefined) { + return undefined; + } + return interp(evaluatedLower, evaluatedUpper, t, parameters.colorSpace); + } + }; + } + return interp(outputLower, outputUpper, t, parameters.colorSpace); +} +function evaluateIdentityFunction(parameters, propertySpec, input) { + switch (propertySpec.type) { + case 'color': + input = Color.parse(input); + break; + case 'formatted': + input = Formatted.fromString(input.toString()); + break; + case 'resolvedImage': + input = ResolvedImage.fromString(input.toString()); + break; + case 'padding': + input = Padding.parse(input); + break; + default: + if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) { + input = undefined; + } + } + return coalesce$1(input, parameters.default, propertySpec.default); +} +/** + * Returns a ratio that can be used to interpolate between exponential function + * stops. + * + * 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, + * and `a` and `b` are constants affording sufficient degrees of freedom to fit + * the function to the given stops. + * + * Here's a bit of algebra that lets us compute `f(x)` directly from the stop + * values without explicitly solving for `a` and `b`: + * + * First stop value: `f(x0) = y0 = a * base^x0 + b` + * Second stop value: `f(x1) = y1 = a * base^x1 + b` + * => `y1 - y0 = a(base^x1 - base^x0)` + * => `a = (y1 - y0)/(base^x1 - base^x0)` + * + * Desired value: `f(x) = y = a * base^x + b` + * => `f(x) = y0 + a * (base^x - base^x0)` + * + * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a + * little algebra: + * ``` + * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) + * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) + * ``` + * + * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have + * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as + * an interpolation factor between the two stops' output values. + * + * (Note: a slightly different form for `ratio`, + * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer + * expensive `Math.pow()` operations.) + * + * @private + */ +function interpolationFactor(input, base, lowerValue, upperValue) { + const difference = upperValue - lowerValue; + const progress = input - lowerValue; + if (difference === 0) { + return 0; + } + else if (base === 1) { + return progress / difference; + } + else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} + +class StyleExpression { + constructor(expression, propertySpec) { + this.expression = expression; + this._warningHistory = {}; + this._evaluator = new EvaluationContext(); + this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null; + this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null; + } + evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + this._evaluator.globals = globals; + this._evaluator.feature = feature; + this._evaluator.featureState = featureState; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection; + return this.expression.evaluate(this._evaluator); + } + evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + this._evaluator.globals = globals; + this._evaluator.feature = feature || null; + this._evaluator.featureState = featureState || null; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection || null; + try { + const val = this.expression.evaluate(this._evaluator); + // eslint-disable-next-line no-self-compare + if (val === null || val === undefined || (typeof val === 'number' && val !== val)) { + return this._defaultValue; + } + if (this._enumValues && !(val in this._enumValues)) { + 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.`); + } + return val; + } + catch (e) { + if (!this._warningHistory[e.message]) { + this._warningHistory[e.message] = true; + if (typeof console !== 'undefined') { + console.warn(e.message); + } + } + return this._defaultValue; + } + } +} +function isExpression(expression) { + return Array.isArray(expression) && expression.length > 0 && + typeof expression[0] === 'string' && expression[0] in expressions$1; +} +/** + * Parse and typecheck the given style spec JSON expression. If + * options.defaultValue is provided, then the resulting StyleExpression's + * `evaluate()` method will handle errors by logging a warning (once per + * message) and returning the default value. Otherwise, it will throw + * evaluation errors. + * + * @private + */ +function createExpression(expression, propertySpec) { + const parser = new ParsingContext(expressions$1, isExpressionConstant, [], propertySpec ? getExpectedType(propertySpec) : undefined); + // For string-valued properties, coerce to string at the top level rather than asserting. + const parsed = parser.parse(expression, undefined, undefined, undefined, propertySpec && propertySpec.type === 'string' ? { typeAnnotation: 'coerce' } : undefined); + if (!parsed) { + return error(parser.errors); + } + return success(new StyleExpression(parsed, propertySpec)); +} +class ZoomConstantExpression { + constructor(kind, expression) { + this.kind = kind; + this._styleExpression = expression; + this.isStateDependent = kind !== 'constant' && !isStateConstant(expression.expression); + } + evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + } + evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + } +} +class ZoomDependentExpression { + constructor(kind, expression, zoomStops, interpolationType) { + this.kind = kind; + this.zoomStops = zoomStops; + this._styleExpression = expression; + this.isStateDependent = kind !== 'camera' && !isStateConstant(expression.expression); + this.interpolationType = interpolationType; + } + evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + } + evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + } + interpolationFactor(input, lower, upper) { + if (this.interpolationType) { + return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper); + } + else { + return 0; + } + } +} +function isZoomExpression(expression) { + return expression._styleExpression !== undefined; +} +function createPropertyExpression(expressionInput, propertySpec) { + const expression = createExpression(expressionInput, propertySpec); + if (expression.result === 'error') { + return expression; + } + const parsed = expression.value.expression; + const isFeatureConstantResult = isFeatureConstant(parsed); + if (!isFeatureConstantResult && !supportsPropertyExpression(propertySpec)) { + return error([new ExpressionParsingError('', 'data expressions not supported')]); + } + const isZoomConstant = isGlobalPropertyConstant(parsed, ['zoom']); + if (!isZoomConstant && !supportsZoomExpression(propertySpec)) { + return error([new ExpressionParsingError('', 'zoom expressions not supported')]); + } + const zoomCurve = findZoomCurve(parsed); + if (!zoomCurve && !isZoomConstant) { + return error([new ExpressionParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]); + } + else if (zoomCurve instanceof ExpressionParsingError) { + return error([zoomCurve]); + } + else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) { + return error([new ExpressionParsingError('', '"interpolate" expressions cannot be used with this property')]); + } + if (!zoomCurve) { + return success(isFeatureConstantResult ? + new ZoomConstantExpression('constant', expression.value) : + new ZoomConstantExpression('source', expression.value)); + } + const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined; + return success(isFeatureConstantResult ? + new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType) : + new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType)); +} +// serialization wrapper for old-style stop functions normalized to the +// expression interface +class StylePropertyFunction { + constructor(parameters, specification) { + this._parameters = parameters; + this._specification = specification; + extendBy(this, createFunction(this._parameters, this._specification)); + } + static deserialize(serialized) { + return new StylePropertyFunction(serialized._parameters, serialized._specification); + } + static serialize(input) { + return { + _parameters: input._parameters, + _specification: input._specification + }; + } +} +function normalizePropertyExpression(value, specification) { + if (isFunction$1(value)) { + return new StylePropertyFunction(value, specification); + } + else if (isExpression(value)) { + const expression = createPropertyExpression(value, specification); + if (expression.result === 'error') { + // this should have been caught in validation + throw new Error(expression.value.map(err => `${err.key}: ${err.message}`).join(', ')); + } + return expression.value; + } + else { + let constant = value; + if (specification.type === 'color' && typeof value === 'string') { + constant = Color.parse(value); + } + else if (specification.type === 'padding' && (typeof value === 'number' || Array.isArray(value))) { + constant = Padding.parse(value); + } + else if (specification.type === 'variableAnchorOffsetCollection' && Array.isArray(value)) { + constant = VariableAnchorOffsetCollection.parse(value); + } + return { + kind: 'constant', + evaluate: () => constant + }; + } +} +// Zoom-dependent expressions may only use ["zoom"] as the input to a top-level "step" or "interpolate" +// expression (collectively referred to as a "curve"). The curve may be wrapped in one or more "let" or +// "coalesce" expressions. +function findZoomCurve(expression) { + let result = null; + if (expression instanceof Let) { + result = findZoomCurve(expression.result); + } + else if (expression instanceof Coalesce) { + for (const arg of expression.args) { + result = findZoomCurve(arg); + if (result) { + break; + } + } + } + else if ((expression instanceof Step || expression instanceof Interpolate) && + expression.input instanceof CompoundExpression && + expression.input.name === 'zoom') { + result = expression; + } + if (result instanceof ExpressionParsingError) { + return result; + } + expression.eachChild((child) => { + const childResult = findZoomCurve(child); + if (childResult instanceof ExpressionParsingError) { + result = childResult; + } + else if (!result && childResult) { + result = new ExpressionParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'); + } + else if (result && childResult && result !== childResult) { + result = new ExpressionParsingError('', 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'); + } + }); + return result; +} +function getExpectedType(spec) { + const types = { + color: ColorType, + string: StringType, + number: NumberType, + enum: StringType, + boolean: BooleanType, + formatted: FormattedType, + padding: PaddingType, + resolvedImage: ResolvedImageType, + variableAnchorOffsetCollection: VariableAnchorOffsetCollectionType + }; + if (spec.type === 'array') { + return array$1(types[spec.value] || ValueType, spec.length); + } + return types[spec.type]; +} +function getDefaultValue(spec) { + if (spec.type === 'color' && isFunction$1(spec.default)) { + // Special case for heatmap-color: it uses the 'default:' to define a + // default color ramp, but createExpression expects a simple value to fall + // back to in case of runtime errors + return new Color(0, 0, 0, 0); + } + else if (spec.type === 'color') { + return Color.parse(spec.default) || null; + } + else if (spec.type === 'padding') { + return Padding.parse(spec.default) || null; + } + else if (spec.type === 'variableAnchorOffsetCollection') { + return VariableAnchorOffsetCollection.parse(spec.default) || null; + } + else if (spec.default === undefined) { + return null; + } + else { + return spec.default; + } +} + +function isExpressionFilter(filter) { + if (filter === true || filter === false) { + return true; + } + if (!Array.isArray(filter) || filter.length === 0) { + return false; + } + switch (filter[0]) { + case 'has': + return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type'; + case 'in': + return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2])); + case '!in': + case '!has': + case 'none': + return false; + case '==': + case '!=': + case '>': + case '>=': + case '<': + case '<=': + return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2])); + case 'any': + case 'all': + for (const f of filter.slice(1)) { + if (!isExpressionFilter(f) && typeof f !== 'boolean') { + return false; + } + } + return true; + default: + return true; + } +} +const filterSpec = { + 'type': 'boolean', + 'default': false, + 'transition': false, + 'property-type': 'data-driven', + 'expression': { + 'interpolated': false, + 'parameters': ['zoom', 'feature'] + } +}; +/** + * Given a filter expressed as nested arrays, return a new function + * that evaluates whether a given feature (with a .properties or .tags property) + * passes its test. + * + * @private + * @param {Array} filter MapLibre filter + * @returns {Function} filter-evaluating function + */ +function createFilter(filter) { + if (filter === null || filter === undefined) { + return { filter: () => true, needGeometry: false }; + } + if (!isExpressionFilter(filter)) { + filter = convertFilter$1(filter); + } + const compiled = createExpression(filter, filterSpec); + if (compiled.result === 'error') { + throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', ')); + } + else { + const needGeometry = geometryNeeded(filter); + return { filter: (globalProperties, feature, canonical) => compiled.value.evaluate(globalProperties, feature, {}, canonical), + needGeometry }; + } +} +// Comparison function to sort numbers and strings +function compare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} +function geometryNeeded(filter) { + if (!Array.isArray(filter)) + return false; + if (filter[0] === 'within' || filter[0] === 'distance') + return true; + for (let index = 1; index < filter.length; index++) { + if (geometryNeeded(filter[index])) + return true; + } + return false; +} +function convertFilter$1(filter) { + if (!filter) + return true; + const op = filter[0]; + if (filter.length <= 1) + return (op !== 'any'); + const converted = op === '==' ? convertComparisonOp$1(filter[1], filter[2], '==') : + op === '!=' ? convertNegation(convertComparisonOp$1(filter[1], filter[2], '==')) : + op === '<' || + op === '>' || + op === '<=' || + op === '>=' ? convertComparisonOp$1(filter[1], filter[2], op) : + op === 'any' ? convertDisjunctionOp(filter.slice(1)) : + op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter$1)) : + op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter$1).map(convertNegation)) : + op === 'in' ? convertInOp$1(filter[1], filter.slice(2)) : + op === '!in' ? convertNegation(convertInOp$1(filter[1], filter.slice(2))) : + op === 'has' ? convertHasOp$1(filter[1]) : + op === '!has' ? convertNegation(convertHasOp$1(filter[1])) : + true; + return converted; +} +function convertComparisonOp$1(property, value, op) { + switch (property) { + case '$type': + return [`filter-type-${op}`, value]; + case '$id': + return [`filter-id-${op}`, value]; + default: + return [`filter-${op}`, property, value]; + } +} +function convertDisjunctionOp(filters) { + return ['any'].concat(filters.map(convertFilter$1)); +} +function convertInOp$1(property, values) { + if (values.length === 0) { + return false; + } + switch (property) { + case '$type': + return ['filter-type-in', ['literal', values]]; + case '$id': + return ['filter-id-in', ['literal', values]]; + default: + if (values.length > 200 && !values.some(v => typeof v !== typeof values[0])) { + return ['filter-in-large', property, ['literal', values.sort(compare)]]; + } + else { + return ['filter-in-small', property, ['literal', values]]; + } + } +} +function convertHasOp$1(property) { + switch (property) { + case '$type': + return true; + case '$id': + return ['filter-has-id']; + default: + return ['filter-has', property]; + } +} +function convertNegation(filter) { + return ['!', filter]; +} + +/* + * Convert the given filter to an expression, storing the expected types for + * any feature properties referenced in expectedTypes. + * + * These expected types are needed in order to construct preflight type checks + * needed for handling 'any' filters. A preflight type check is necessary in + * order to mimic legacy filters' semantics around expected type mismatches. + * For example, consider the legacy filter: + * + * ["any", ["all", [">", "y", 0], [">", "y", 0]], [">", "x", 0]] + * + * Naively, we might convert this to the expression: + * + * ["any", ["all", [">", ["get", "y"], 0], [">", ["get", "z"], 0]], [">", ["get", "x"], 0]] + * + * But if we tried to evaluate this against, say `{x: 1, y: null, z: 0}`, the + * [">", ["get", "y"], 0] would cause an evaluation error, leading to the + * entire filter returning false. Legacy filter semantics, though, ask for + * [">", "y", 0] to simply return `false` when `y` is of the wrong type, + * allowing the subsequent terms of the outer "any" expression to be evaluated + * (resulting, in this case, in a `true` value, because x > 0). + * + * We account for this by inserting a preflight type-checking expression before + * each "any" term, allowing us to avoid evaluating the actual converted filter + * if any type mismatches would cause it to produce an evalaution error: + * + * ["any", + * ["case", + * ["all", ["==", ["typeof", ["get", "y"]], "number"], ["==", ["typeof", ["get", "z"], "number]], + * ["all", [">", ["get", "y"], 0], [">", ["get", "z"], 0]], + * false + * ], + * ["case", + * ["==", ["typeof", ["get", "x"], "number"]], + * [">", ["get", "x"], 0], + * false + * ] + * ] + * + * An alternative, possibly more direct approach would be to use type checks + * in the conversion of each comparison operator, so that the converted version + * of each individual ==, >=, etc. would mimic the legacy filter semantics. The + * downside of this approach is that it can lead to many more type checks than + * would otherwise be necessary: outside the context of an "any" expression, + * bailing out due to a runtime type error (expression semantics) and returning + * false (legacy filter semantics) are equivalent: they cause the filter to + * produce a `false` result. + */ +function convertFilter(filter, expectedTypes = {}) { + if (isExpressionFilter(filter)) + return filter; + if (!filter) + return true; + const legacyFilter = filter; + const legacyOp = legacyFilter[0]; + if (filter.length <= 1) + return (legacyOp !== 'any'); + switch (legacyOp) { + case '==': + case '!=': + case '<': + case '>': + case '<=': + case '>=': { + const [, property, value] = filter; + return convertComparisonOp(property, value, legacyOp, expectedTypes); + } + case 'any': { + const [, ...conditions] = legacyFilter; + const children = conditions.map((f) => { + const types = {}; + const child = convertFilter(f, types); + const typechecks = runtimeTypeChecks(types); + return typechecks === true ? child : ['case', typechecks, child, false]; + }); + return ['any', ...children]; + } + case 'all': { + const [, ...conditions] = legacyFilter; + const children = conditions.map(f => convertFilter(f, expectedTypes)); + return children.length > 1 ? ['all', ...children] : children[0]; + } + case 'none': { + const [, ...conditions] = legacyFilter; + return ['!', convertFilter(['any', ...conditions], {})]; + } + case 'in': { + const [, property, ...values] = legacyFilter; + return convertInOp(property, values); + } + case '!in': { + const [, property, ...values] = legacyFilter; + return convertInOp(property, values, true); + } + case 'has': + return convertHasOp(legacyFilter[1]); + case '!has': + return ['!', convertHasOp(legacyFilter[1])]; + default: + return true; + } +} +// Given a set of feature properties and an expected type for each one, +// construct an boolean expression that tests whether each property has the +// right type. +// E.g.: for {name: 'string', population: 'number'}, return +// [ 'all', +// ['==', ['typeof', ['get', 'name'], 'string']], +// ['==', ['typeof', ['get', 'population'], 'number]] +// ] +function runtimeTypeChecks(expectedTypes) { + const conditions = []; + for (const property in expectedTypes) { + const get = property === '$id' ? ['id'] : ['get', property]; + conditions.push(['==', ['typeof', get], expectedTypes[property]]); + } + if (conditions.length === 0) + return true; + if (conditions.length === 1) + return conditions[0]; + return ['all', ...conditions]; +} +function convertComparisonOp(property, value, op, expectedTypes) { + let get; + if (property === '$type') { + return [op, ['geometry-type'], value]; + } + else if (property === '$id') { + get = ['id']; + } + else { + get = ['get', property]; + } + if (expectedTypes && value !== null) { + const type = typeof value; + expectedTypes[property] = type; + } + if (op === '==' && property !== '$id' && value === null) { + return [ + 'all', + ['has', property], // missing property != null for legacy filters + ['==', get, null] + ]; + } + else if (op === '!=' && property !== '$id' && value === null) { + return [ + 'any', + ['!', ['has', property]], // missing property != null for legacy filters + ['!=', get, null] + ]; + } + return [op, get, value]; +} +function convertInOp(property, values, negate = false) { + if (values.length === 0) + return negate; + let get; + if (property === '$type') { + get = ['geometry-type']; + } + else if (property === '$id') { + get = ['id']; + } + else { + get = ['get', property]; + } + // Determine if the list of values to be searched is homogenously typed. + // If so (and if the type is string or number), then we can use a + // [match, input, [...values], true, false] construction rather than a + // bunch of `==` tests. + let uniformTypes = true; + const type = typeof values[0]; + for (const value of values) { + if (typeof value !== type) { + uniformTypes = false; + break; + } + } + if (uniformTypes && (type === 'string' || type === 'number')) { + // Match expressions must have unique values. + const uniqueValues = values.sort().filter((v, i) => i === 0 || values[i - 1] !== v); + return ['match', get, uniqueValues, !negate, negate]; + } + if (negate) { + return ['all', ...values.map(v => ['!=', get, v])]; + } + else { + return ['any', ...values.map(v => ['==', get, v])]; + } +} +function convertHasOp(property) { + if (property === '$type') { + return true; + } + else if (property === '$id') { + return ['!=', ['id'], null]; + } + else { + return ['has', property]; + } +} + +function convertLiteral(value) { + return typeof value === 'object' ? ['literal', value] : value; +} +function convertFunction(parameters, propertySpec) { + let stops = parameters.stops; + if (!stops) { + // identity function + return convertIdentityFunction(parameters, propertySpec); + } + const zoomAndFeatureDependent = stops && typeof stops[0][0] === 'object'; + const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + const zoomDependent = zoomAndFeatureDependent || !featureDependent; + stops = stops.map((stop) => { + if (!featureDependent && propertySpec.tokens && typeof stop[1] === 'string') { + return [stop[0], convertTokenString(stop[1])]; + } + return [stop[0], convertLiteral(stop[1])]; + }); + if (zoomAndFeatureDependent) { + return convertZoomAndPropertyFunction(parameters, propertySpec, stops); + } + else if (zoomDependent) { + return convertZoomFunction(parameters, propertySpec, stops); + } + else { + return convertPropertyFunction(parameters, propertySpec, stops); + } +} +function convertIdentityFunction(parameters, propertySpec) { + const get = ['get', parameters.property]; + if (parameters.default === undefined) { + // By default, expressions for string-valued properties get coerced. To preserve + // legacy function semantics, insert an explicit assertion instead. + return propertySpec.type === 'string' ? ['string', get] : get; + } + else if (propertySpec.type === 'enum') { + return [ + 'match', + get, + Object.keys(propertySpec.values), + get, + parameters.default + ]; + } + else { + const expression = [propertySpec.type === 'color' ? 'to-color' : propertySpec.type, get, convertLiteral(parameters.default)]; + if (propertySpec.type === 'array') { + expression.splice(1, 0, propertySpec.value, propertySpec.length || null); + } + return expression; + } +} +function getInterpolateOperator(parameters) { + switch (parameters.colorSpace) { + case 'hcl': return 'interpolate-hcl'; + case 'lab': return 'interpolate-lab'; + default: return 'interpolate'; + } +} +function convertZoomAndPropertyFunction(parameters, propertySpec, stops) { + const featureFunctionParameters = {}; + const featureFunctionStops = {}; + const zoomStops = []; + for (let s = 0; s < stops.length; s++) { + const stop = stops[s]; + const zoom = stop[0].zoom; + if (featureFunctionParameters[zoom] === undefined) { + featureFunctionParameters[zoom] = { + zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default, + }; + featureFunctionStops[zoom] = []; + zoomStops.push(zoom); + } + featureFunctionStops[zoom].push([stop[0].value, stop[1]]); + } + // the interpolation type for the zoom dimension of a zoom-and-property + // function is determined directly from the style property specification + // for which it's being used: linear for interpolatable properties, step + // otherwise. + const functionType = getFunctionType({}, propertySpec); + if (functionType === 'exponential') { + const expression = [getInterpolateOperator(parameters), ['linear'], ['zoom']]; + for (const z of zoomStops) { + const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]); + appendStopPair(expression, z, output, false); + } + return expression; + } + else { + const expression = ['step', ['zoom']]; + for (const z of zoomStops) { + const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]); + appendStopPair(expression, z, output, true); + } + fixupDegenerateStepCurve(expression); + return expression; + } +} +function coalesce(a, b) { + if (a !== undefined) + return a; + if (b !== undefined) + return b; +} +function getFallback(parameters, propertySpec) { + const defaultValue = convertLiteral(coalesce(parameters.default, propertySpec.default)); + /* + * Some fields with type: resolvedImage have an undefined default. + * Because undefined is an invalid value for resolvedImage, set fallback to + * an empty string instead of undefined to ensure output + * passes validation. + */ + if (defaultValue === undefined && propertySpec.type === 'resolvedImage') { + return ''; + } + return defaultValue; +} +function convertPropertyFunction(parameters, propertySpec, stops) { + const type = getFunctionType(parameters, propertySpec); + const get = ['get', parameters.property]; + if (type === 'categorical' && typeof stops[0][0] === 'boolean') { + const expression = ['case']; + for (const stop of stops) { + expression.push(['==', get, stop[0]], stop[1]); + } + expression.push(getFallback(parameters, propertySpec)); + return expression; + } + else if (type === 'categorical') { + const expression = ['match', get]; + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], false); + } + expression.push(getFallback(parameters, propertySpec)); + return expression; + } + else if (type === 'interval') { + const expression = ['step', ['number', get]]; + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], true); + } + fixupDegenerateStepCurve(expression); + return parameters.default === undefined ? expression : [ + 'case', + ['==', ['typeof', get], 'number'], + expression, + convertLiteral(parameters.default) + ]; + } + else if (type === 'exponential') { + const base = parameters.base !== undefined ? parameters.base : 1; + const expression = [ + getInterpolateOperator(parameters), + base === 1 ? ['linear'] : ['exponential', base], + ['number', get] + ]; + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], false); + } + return parameters.default === undefined ? expression : [ + 'case', + ['==', ['typeof', get], 'number'], + expression, + convertLiteral(parameters.default) + ]; + } + else { + throw new Error(`Unknown property function type ${type}`); + } +} +function convertZoomFunction(parameters, propertySpec, stops, input = ['zoom']) { + const type = getFunctionType(parameters, propertySpec); + let expression; + let isStep = false; + if (type === 'interval') { + expression = ['step', input]; + isStep = true; + } + else if (type === 'exponential') { + const base = parameters.base !== undefined ? parameters.base : 1; + expression = [getInterpolateOperator(parameters), base === 1 ? ['linear'] : ['exponential', base], input]; + } + else { + throw new Error(`Unknown zoom function type "${type}"`); + } + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], isStep); + } + fixupDegenerateStepCurve(expression); + return expression; +} +function fixupDegenerateStepCurve(expression) { + // degenerate step curve (i.e. a constant function): add a noop stop + if (expression[0] === 'step' && expression.length === 3) { + expression.push(0); + expression.push(expression[3]); + } +} +function appendStopPair(curve, input, output, isStep) { + // Skip duplicate stop values. They were not validated for functions, but they are for expressions. + // https://github.com/mapbox/mapbox-gl-js/issues/4107 + if (curve.length > 3 && input === curve[curve.length - 2]) { + return; + } + // step curves don't get the first input value, as it is redundant. + if (!(isStep && curve.length === 2)) { + curve.push(input); + } + curve.push(output); +} +function getFunctionType(parameters, propertySpec) { + if (parameters.type) { + return parameters.type; + } + else { + return propertySpec.expression.interpolated ? 'exponential' : 'interval'; + } +} +// "String with {name} token" => ["concat", "String with ", ["get", "name"], " token"] +function convertTokenString(s) { + const result = ['concat']; + const re = /{([^{}]+)}/g; + let pos = 0; + for (let match = re.exec(s); match !== null; match = re.exec(s)) { + const literal = s.slice(pos, re.lastIndex - match[0].length); + pos = re.lastIndex; + if (literal.length > 0) + result.push(literal); + result.push(['get', match[1]]); + } + if (result.length === 1) { + return s; + } + if (pos < s.length) { + result.push(s.slice(pos)); + } + else if (result.length === 2) { + return ['to-string', result[1]]; + } + return result; +} + +function getPropertyReference(propertyName) { + for (let i = 0; i < v8Spec.layout.length; i++) { + for (const key in v8Spec[v8Spec.layout[i]]) { + if (key === propertyName) + return v8Spec[v8Spec.layout[i]][key]; + } + } + for (let i = 0; i < v8Spec.paint.length; i++) { + for (const key in v8Spec[v8Spec.paint[i]]) { + if (key === propertyName) + return v8Spec[v8Spec.paint[i]][key]; + } + } + return null; +} +function eachSource(style, callback) { + for (const k in style.sources) { + callback(style.sources[k]); + } +} +function eachLayer(style, callback) { + for (const layer of style.layers) { + callback(layer); + } +} +function eachProperty(style, options, callback) { + function inner(layer, propertyType) { + const properties = layer[propertyType]; + if (!properties) + return; + Object.keys(properties).forEach((key) => { + callback({ + path: [layer.id, propertyType, key], + key, + value: properties[key], + reference: getPropertyReference(key), + set(x) { + properties[key] = x; + } + }); + }); + } + eachLayer(style, (layer) => { + if (options.paint) { + inner(layer, 'paint'); + } + if (options.layout) { + inner(layer, 'layout'); + } + }); +} + +function stringify$1(obj) { + const type = typeof obj; + if (type === 'number' || type === 'boolean' || type === 'string' || obj === undefined || obj === null) + return JSON.stringify(obj); + if (Array.isArray(obj)) { + let str = '['; + for (const val of obj) { + str += `${stringify$1(val)},`; + } + return `${str}]`; + } + const keys = Object.keys(obj).sort(); + let str = '{'; + for (let i = 0; i < keys.length; i++) { + str += `${JSON.stringify(keys[i])}:${stringify$1(obj[keys[i]])},`; + } + return `${str}}`; +} +function getKey(layer) { + let key = ''; + for (const k of refProperties) { + key += `/${stringify$1(layer[k])}`; + } + return key; +} +/** + * Given an array of layers, return an array of arrays of layers where all + * layers in each group have identical layout-affecting properties. These + * are the properties that were formerly used by explicit `ref` mechanism + * for layers: 'type', 'source', 'source-layer', 'minzoom', 'maxzoom', + * 'filter', and 'layout'. + * + * The input is not modified. The output layers are references to the + * input layers. + * + * @private + * @param {Array} layers + * @param {Object} [cachedKeys] - an object to keep already calculated keys. + * @returns {Array>} + */ +function groupByLayout(layers, cachedKeys) { + const groups = {}; + for (let i = 0; i < layers.length; i++) { + const k = (cachedKeys && cachedKeys[layers[i].id]) || getKey(layers[i]); + // update the cache if there is one + if (cachedKeys) + cachedKeys[layers[i].id] = k; + let group = groups[k]; + if (!group) { + group = groups[k] = []; + } + group.push(layers[i]); + } + const result = []; + for (const k in groups) { + result.push(groups[k]); + } + return result; +} + +function emptyStyle() { + const style = {}; + const version = v8Spec['$version']; + for (const styleKey in v8Spec['$root']) { + const spec = v8Spec['$root'][styleKey]; + if (spec.required) { + let value = null; + if (styleKey === 'version') { + value = version; + } + else { + if (spec.type === 'array') { + value = []; + } + else { + value = {}; + } + } + if (value != null) { + style[styleKey] = value; + } + } + } + return style; +} + +function validateConstants(options) { + const key = options.key; + const constants = options.value; + if (constants) { + return [new ValidationError(key, constants, 'constants have been deprecated as of v8')]; + } + else { + return []; + } +} + +// Turn jsonlint-lines-primitives objects into primitive objects +function unbundle(value) { + if (value instanceof Number || value instanceof String || value instanceof Boolean) { + return value.valueOf(); + } + else { + return value; + } +} +function deepUnbundle(value) { + if (Array.isArray(value)) { + return value.map(deepUnbundle); + } + else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) { + const unbundledValue = {}; + for (const key in value) { + unbundledValue[key] = deepUnbundle(value[key]); + } + return unbundledValue; + } + return unbundle(value); +} + +function validateObject(options) { + const key = options.key; + const object = options.value; + const elementSpecs = options.valueSpec || {}; + const elementValidators = options.objectElementValidators || {}; + const style = options.style; + const styleSpec = options.styleSpec; + const validateSpec = options.validateSpec; + let errors = []; + const type = getType(object); + if (type !== 'object') { + return [new ValidationError(key, object, `object expected, ${type} found`)]; + } + for (const objectKey in object) { + const elementSpecKey = objectKey.split('.')[0]; // treat 'paint.*' as 'paint' + const elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*']; + let validateElement; + if (elementValidators[elementSpecKey]) { + validateElement = elementValidators[elementSpecKey]; + } + else if (elementSpecs[elementSpecKey]) { + validateElement = validateSpec; + } + else if (elementValidators['*']) { + validateElement = elementValidators['*']; + } + else if (elementSpecs['*']) { + validateElement = validateSpec; + } + else { + errors.push(new ValidationError(key, object[objectKey], `unknown property "${objectKey}"`)); + continue; + } + errors = errors.concat(validateElement({ + key: (key ? `${key}.` : key) + objectKey, + value: object[objectKey], + valueSpec: elementSpec, + style, + styleSpec, + object, + objectKey, + validateSpec, + }, object)); + } + for (const elementSpecKey in elementSpecs) { + // Don't check `required` when there's a custom validator for that property. + if (elementValidators[elementSpecKey]) { + continue; + } + if (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey]['default'] === undefined && object[elementSpecKey] === undefined) { + errors.push(new ValidationError(key, object, `missing required property "${elementSpecKey}"`)); + } + } + return errors; +} + +function validateArray(options) { + const array = options.value; + const arraySpec = options.valueSpec; + const validateSpec = options.validateSpec; + const style = options.style; + const styleSpec = options.styleSpec; + const key = options.key; + const validateArrayElement = options.arrayElementValidator || validateSpec; + if (getType(array) !== 'array') { + return [new ValidationError(key, array, `array expected, ${getType(array)} found`)]; + } + if (arraySpec.length && array.length !== arraySpec.length) { + return [new ValidationError(key, array, `array length ${arraySpec.length} expected, length ${array.length} found`)]; + } + if (arraySpec['min-length'] && array.length < arraySpec['min-length']) { + return [new ValidationError(key, array, `array length at least ${arraySpec['min-length']} expected, length ${array.length} found`)]; + } + let arrayElementSpec = { + 'type': arraySpec.value, + 'values': arraySpec.values + }; + if (styleSpec.$version < 7) { + arrayElementSpec['function'] = arraySpec.function; + } + if (getType(arraySpec.value) === 'object') { + arrayElementSpec = arraySpec.value; + } + let errors = []; + for (let i = 0; i < array.length; i++) { + errors = errors.concat(validateArrayElement({ + array, + arrayIndex: i, + value: array[i], + valueSpec: arrayElementSpec, + validateSpec: options.validateSpec, + style, + styleSpec, + key: `${key}[${i}]` + })); + } + return errors; +} + +function validateNumber(options) { + const key = options.key; + const value = options.value; + const valueSpec = options.valueSpec; + let type = getType(value); + // eslint-disable-next-line no-self-compare + if (type === 'number' && value !== value) { + type = 'NaN'; + } + if (type !== 'number') { + return [new ValidationError(key, value, `number expected, ${type} found`)]; + } + if ('minimum' in valueSpec && value < valueSpec.minimum) { + return [new ValidationError(key, value, `${value} is less than the minimum value ${valueSpec.minimum}`)]; + } + if ('maximum' in valueSpec && value > valueSpec.maximum) { + return [new ValidationError(key, value, `${value} is greater than the maximum value ${valueSpec.maximum}`)]; + } + return []; +} + +function validateFunction(options) { + const functionValueSpec = options.valueSpec; + const functionType = unbundle(options.value.type); + let stopKeyType; + let stopDomainValues = {}; + let previousStopDomainValue; + let previousStopDomainZoom; + const isZoomFunction = functionType !== 'categorical' && options.value.property === undefined; + const isPropertyFunction = !isZoomFunction; + const isZoomAndPropertyFunction = getType(options.value.stops) === 'array' && + getType(options.value.stops[0]) === 'array' && + getType(options.value.stops[0][0]) === 'object'; + const errors = validateObject({ + key: options.key, + value: options.value, + valueSpec: options.styleSpec.function, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + stops: validateFunctionStops, + default: validateFunctionDefault + } + }); + if (functionType === 'identity' && isZoomFunction) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "property"')); + } + if (functionType !== 'identity' && !options.value.stops) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "stops"')); + } + if (functionType === 'exponential' && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'exponential functions not supported')); + } + if (options.styleSpec.$version >= 8) { + if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'property functions not supported')); + } + else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported')); + } + } + if ((functionType === 'categorical' || isZoomAndPropertyFunction) && options.value.property === undefined) { + errors.push(new ValidationError(options.key, options.value, '"property" property is required')); + } + return errors; + function validateFunctionStops(options) { + if (functionType === 'identity') { + return [new ValidationError(options.key, options.value, 'identity function may not have a "stops" property')]; + } + let errors = []; + const value = options.value; + errors = errors.concat(validateArray({ + key: options.key, + value, + valueSpec: options.valueSpec, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec, + arrayElementValidator: validateFunctionStop + })); + if (getType(value) === 'array' && value.length === 0) { + errors.push(new ValidationError(options.key, value, 'array must have at least one stop')); + } + return errors; + } + function validateFunctionStop(options) { + let errors = []; + const value = options.value; + const key = options.key; + if (getType(value) !== 'array') { + return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; + } + if (value.length !== 2) { + return [new ValidationError(key, value, `array length 2 expected, length ${value.length} found`)]; + } + if (isZoomAndPropertyFunction) { + if (getType(value[0]) !== 'object') { + return [new ValidationError(key, value, `object expected, ${getType(value[0])} found`)]; + } + if (value[0].zoom === undefined) { + return [new ValidationError(key, value, 'object stop key must have zoom')]; + } + if (value[0].value === undefined) { + return [new ValidationError(key, value, 'object stop key must have value')]; + } + if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) { + return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')]; + } + if (unbundle(value[0].zoom) !== previousStopDomainZoom) { + previousStopDomainZoom = unbundle(value[0].zoom); + previousStopDomainValue = undefined; + stopDomainValues = {}; + } + errors = errors.concat(validateObject({ + key: `${key}[0]`, + value: value[0], + valueSpec: { zoom: {} }, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { zoom: validateNumber, value: validateStopDomainValue } + })); + } + else { + errors = errors.concat(validateStopDomainValue({ + key: `${key}[0]`, + value: value[0], + valueSpec: {}, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec + }, value)); + } + if (isExpression(deepUnbundle(value[1]))) { + return errors.concat([new ValidationError(`${key}[1]`, value[1], 'expressions are not allowed in function stops.')]); + } + return errors.concat(options.validateSpec({ + key: `${key}[1]`, + value: value[1], + valueSpec: functionValueSpec, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec + })); + } + function validateStopDomainValue(options, stop) { + const type = getType(options.value); + const value = unbundle(options.value); + const reportValue = options.value !== null ? options.value : stop; + if (!stopKeyType) { + stopKeyType = type; + } + else if (type !== stopKeyType) { + return [new ValidationError(options.key, reportValue, `${type} stop domain type must match previous stop domain type ${stopKeyType}`)]; + } + if (type !== 'number' && type !== 'string' && type !== 'boolean') { + return [new ValidationError(options.key, reportValue, 'stop domain value must be a number, string, or boolean')]; + } + if (type !== 'number' && functionType !== 'categorical') { + let message = `number expected, ${type} found`; + if (supportsPropertyExpression(functionValueSpec) && functionType === undefined) { + message += '\nIf you intended to use a categorical function, specify `"type": "categorical"`.'; + } + return [new ValidationError(options.key, reportValue, message)]; + } + if (functionType === 'categorical' && type === 'number' && (!isFinite(value) || Math.floor(value) !== value)) { + return [new ValidationError(options.key, reportValue, `integer expected, found ${value}`)]; + } + if (functionType !== 'categorical' && type === 'number' && previousStopDomainValue !== undefined && value < previousStopDomainValue) { + return [new ValidationError(options.key, reportValue, 'stop domain values must appear in ascending order')]; + } + else { + previousStopDomainValue = value; + } + if (functionType === 'categorical' && value in stopDomainValues) { + return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')]; + } + else { + stopDomainValues[value] = true; + } + return []; + } + function validateFunctionDefault(options) { + return options.validateSpec({ + key: options.key, + value: options.value, + valueSpec: functionValueSpec, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec + }); + } +} + +function validateExpression(options) { + const expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec); + if (expression.result === 'error') { + return expression.value.map((error) => { + return new ValidationError(`${options.key}${error.key}`, options.value, error.message); + }); + } + const expressionObj = expression.value.expression || expression.value._styleExpression.expression; + if (options.expressionContext === 'property' && (options.propertyKey === 'text-font') && + !expressionObj.outputDefined()) { + return [new ValidationError(options.key, options.value, `Invalid data expression for "${options.propertyKey}". Output values must be contained as literals within the expression.`)]; + } + if (options.expressionContext === 'property' && options.propertyType === 'layout' && + (!isStateConstant(expressionObj))) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with layout properties.')]; + } + if (options.expressionContext === 'filter' && !isStateConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with filters.')]; + } + if (options.expressionContext && options.expressionContext.indexOf('cluster') === 0) { + if (!isGlobalPropertyConstant(expressionObj, ['zoom', 'feature-state'])) { + return [new ValidationError(options.key, options.value, '"zoom" and "feature-state" expressions are not supported with cluster properties.')]; + } + if (options.expressionContext === 'cluster-initial' && !isFeatureConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')]; + } + } + return []; +} + +function validateBoolean(options) { + const value = options.value; + const key = options.key; + const type = getType(value); + if (type !== 'boolean') { + return [new ValidationError(key, value, `boolean expected, ${type} found`)]; + } + return []; +} + +function validateColor(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + if (type !== 'string') { + return [new ValidationError(key, value, `color expected, ${type} found`)]; + } + if (!Color.parse(String(value))) { // cast String object to string primitive + return [new ValidationError(key, value, `color expected, "${value}" found`)]; + } + return []; +} + +function validateEnum(options) { + const key = options.key; + const value = options.value; + const valueSpec = options.valueSpec; + const errors = []; + if (Array.isArray(valueSpec.values)) { // <=v7 + if (valueSpec.values.indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, `expected one of [${valueSpec.values.join(', ')}], ${JSON.stringify(value)} found`)); + } + } + else { // >=v8 + if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, `expected one of [${Object.keys(valueSpec.values).join(', ')}], ${JSON.stringify(value)} found`)); + } + } + return errors; +} + +function validateFilter$1(options) { + if (isExpressionFilter(deepUnbundle(options.value))) { + return validateExpression(extendBy({}, options, { + expressionContext: 'filter', + valueSpec: { value: 'boolean' } + })); + } + else { + return validateNonExpressionFilter(options); + } +} +function validateNonExpressionFilter(options) { + const value = options.value; + const key = options.key; + if (getType(value) !== 'array') { + return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; + } + const styleSpec = options.styleSpec; + let type; + let errors = []; + if (value.length < 1) { + return [new ValidationError(key, value, 'filter array must have at least 1 element')]; + } + errors = errors.concat(validateEnum({ + key: `${key}[0]`, + value: value[0], + valueSpec: styleSpec.filter_operator, + style: options.style, + styleSpec: options.styleSpec + })); + switch (unbundle(value[0])) { + case '<': + case '<=': + case '>': + case '>=': + if (value.length >= 2 && unbundle(value[1]) === '$type') { + errors.push(new ValidationError(key, value, `"$type" cannot be use with operator "${value[0]}"`)); + } + /* falls through */ + case '==': + case '!=': + if (value.length !== 3) { + errors.push(new ValidationError(key, value, `filter array for operator "${value[0]}" must have 3 elements`)); + } + /* falls through */ + case 'in': + case '!in': + if (value.length >= 2) { + type = getType(value[1]); + if (type !== 'string') { + errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); + } + } + for (let i = 2; i < value.length; i++) { + type = getType(value[i]); + if (unbundle(value[1]) === '$type') { + errors = errors.concat(validateEnum({ + key: `${key}[${i}]`, + value: value[i], + valueSpec: styleSpec.geometry_type, + style: options.style, + styleSpec: options.styleSpec + })); + } + else if (type !== 'string' && type !== 'number' && type !== 'boolean') { + errors.push(new ValidationError(`${key}[${i}]`, value[i], `string, number, or boolean expected, ${type} found`)); + } + } + break; + case 'any': + case 'all': + case 'none': + for (let i = 1; i < value.length; i++) { + errors = errors.concat(validateNonExpressionFilter({ + key: `${key}[${i}]`, + value: value[i], + style: options.style, + styleSpec: options.styleSpec + })); + } + break; + case 'has': + case '!has': + type = getType(value[1]); + if (value.length !== 2) { + errors.push(new ValidationError(key, value, `filter array for "${value[0]}" operator must have 2 elements`)); + } + else if (type !== 'string') { + errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); + } + break; + } + return errors; +} + +function validateProperty(options, propertyType) { + const key = options.key; + const validateSpec = options.validateSpec; + const style = options.style; + const styleSpec = options.styleSpec; + const value = options.value; + const propertyKey = options.objectKey; + const layerSpec = styleSpec[`${propertyType}_${options.layerType}`]; + if (!layerSpec) + return []; + const transitionMatch = propertyKey.match(/^(.*)-transition$/); + if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) { + return validateSpec({ + key, + value, + valueSpec: styleSpec.transition, + style, + styleSpec + }); + } + const valueSpec = options.valueSpec || layerSpec[propertyKey]; + if (!valueSpec) { + return [new ValidationError(key, value, `unknown property "${propertyKey}"`)]; + } + let tokenMatch; + if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) { + return [new ValidationError(key, value, `"${propertyKey}" does not support interpolation syntax\n` + + `Use an identity property function instead: \`{ "type": "identity", "property": ${JSON.stringify(tokenMatch[1])} }\`.`)]; + } + const errors = []; + if (options.layerType === 'symbol') { + if (propertyKey === 'text-field' && style && !style.glyphs) { + errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property')); + } + if (propertyKey === 'text-font' && isFunction$1(deepUnbundle(value)) && unbundle(value.type) === 'identity') { + errors.push(new ValidationError(key, value, '"text-font" does not support identity functions')); + } + } + return errors.concat(validateSpec({ + key: options.key, + value, + valueSpec, + style, + styleSpec, + expressionContext: 'property', + propertyType, + propertyKey + })); +} + +function validatePaintProperty$1(options) { + return validateProperty(options, 'paint'); +} + +function validateLayoutProperty$1(options) { + return validateProperty(options, 'layout'); +} + +function validateLayer(options) { + let errors = []; + const layer = options.value; + const key = options.key; + const style = options.style; + const styleSpec = options.styleSpec; + if (!layer.type && !layer.ref) { + errors.push(new ValidationError(key, layer, 'either "type" or "ref" is required')); + } + let type = unbundle(layer.type); + const ref = unbundle(layer.ref); + if (layer.id) { + const layerId = unbundle(layer.id); + for (let i = 0; i < options.arrayIndex; i++) { + const otherLayer = style.layers[i]; + if (unbundle(otherLayer.id) === layerId) { + errors.push(new ValidationError(key, layer.id, `duplicate layer id "${layer.id}", previously used at line ${otherLayer.id.__line__}`)); + } + } + } + if ('ref' in layer) { + ['type', 'source', 'source-layer', 'filter', 'layout'].forEach((p) => { + if (p in layer) { + errors.push(new ValidationError(key, layer[p], `"${p}" is prohibited for ref layers`)); + } + }); + let parent; + style.layers.forEach((layer) => { + if (unbundle(layer.id) === ref) + parent = layer; + }); + if (!parent) { + errors.push(new ValidationError(key, layer.ref, `ref layer "${ref}" not found`)); + } + else if (parent.ref) { + errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer')); + } + else { + type = unbundle(parent.type); + } + } + else if (type !== 'background') { + if (!layer.source) { + errors.push(new ValidationError(key, layer, 'missing required property "source"')); + } + else { + const source = style.sources && style.sources[layer.source]; + const sourceType = source && unbundle(source.type); + if (!source) { + errors.push(new ValidationError(key, layer.source, `source "${layer.source}" not found`)); + } + else if (sourceType === 'vector' && type === 'raster') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a raster source`)); + } + else if (sourceType !== 'raster-dem' && type === 'hillshade') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a raster-dem source`)); + } + else if (sourceType === 'raster' && type !== 'raster') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a vector source`)); + } + else if (sourceType === 'vector' && !layer['source-layer']) { + errors.push(new ValidationError(key, layer, `layer "${layer.id}" must specify a "source-layer"`)); + } + else if (sourceType === 'raster-dem' && type !== 'hillshade') { + errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \'hillshade\'.')); + } + else if (type === 'line' && layer.paint && layer.paint['line-gradient'] && + (sourceType !== 'geojson' || !source.lineMetrics)) { + errors.push(new ValidationError(key, layer, `layer "${layer.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)); + } + } + } + errors = errors.concat(validateObject({ + key, + value: layer, + valueSpec: styleSpec.layer, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + objectElementValidators: { + '*'() { + return []; + }, + // We don't want to enforce the spec's `"requires": true` for backward compatibility with refs; + // the actual requirement is validated above. See https://github.com/mapbox/mapbox-gl-js/issues/5772. + type() { + return options.validateSpec({ + key: `${key}.type`, + value: layer.type, + valueSpec: styleSpec.layer.type, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + object: layer, + objectKey: 'type' + }); + }, + filter: validateFilter$1, + layout(options) { + return validateObject({ + layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + objectElementValidators: { + '*'(options) { + return validateLayoutProperty$1(extendBy({ layerType: type }, options)); + } + } + }); + }, + paint(options) { + return validateObject({ + layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + objectElementValidators: { + '*'(options) { + return validatePaintProperty$1(extendBy({ layerType: type }, options)); + } + } + }); + } + } + })); + return errors; +} + +function validateString(options) { + const value = options.value; + const key = options.key; + const type = getType(value); + if (type !== 'string') { + return [new ValidationError(key, value, `string expected, ${type} found`)]; + } + return []; +} + +function validateRasterDEMSource(options) { + var _a; + const sourceName = (_a = options.sourceName) !== null && _a !== void 0 ? _a : ''; + const rasterDEM = options.value; + const styleSpec = options.styleSpec; + const rasterDEMSpec = styleSpec.source_raster_dem; + const style = options.style; + let errors = []; + const rootType = getType(rasterDEM); + if (rasterDEM === undefined) { + return errors; + } + else if (rootType !== 'object') { + errors.push(new ValidationError('source_raster_dem', rasterDEM, `object expected, ${rootType} found`)); + return errors; + } + const encoding = unbundle(rasterDEM.encoding); + const isCustomEncoding = encoding === 'custom'; + const customEncodingKeys = ['redFactor', 'greenFactor', 'blueFactor', 'baseShift']; + const encodingName = options.value.encoding ? `"${options.value.encoding}"` : 'Default'; + for (const key in rasterDEM) { + if (!isCustomEncoding && customEncodingKeys.includes(key)) { + errors.push(new ValidationError(key, rasterDEM[key], `In "${sourceName}": "${key}" is only valid when "encoding" is set to "custom". ${encodingName} encoding found`)); + } + else if (rasterDEMSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: rasterDEM[key], + valueSpec: rasterDEMSpec[key], + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else { + errors.push(new ValidationError(key, rasterDEM[key], `unknown property "${key}"`)); + } + } + return errors; +} + +const objectElementValidators = { + promoteId: validatePromoteId +}; +function validateSource$1(options) { + const value = options.value; + const key = options.key; + const styleSpec = options.styleSpec; + const style = options.style; + const validateSpec = options.validateSpec; + if (!value.type) { + return [new ValidationError(key, value, '"type" is required')]; + } + const type = unbundle(value.type); + let errors; + switch (type) { + case 'vector': + case 'raster': + errors = validateObject({ + key, + value, + valueSpec: styleSpec[`source_${type.replace('-', '_')}`], + style: options.style, + styleSpec, + objectElementValidators, + validateSpec, + }); + return errors; + case 'raster-dem': + errors = validateRasterDEMSource({ + sourceName: key, + value, + style: options.style, + styleSpec, + validateSpec, + }); + return errors; + case 'geojson': + errors = validateObject({ + key, + value, + valueSpec: styleSpec.source_geojson, + style, + styleSpec, + validateSpec, + objectElementValidators + }); + if (value.cluster) { + for (const prop in value.clusterProperties) { + const [operator, mapExpr] = value.clusterProperties[prop]; + const reduceExpr = typeof operator === 'string' ? [operator, ['accumulated'], ['get', prop]] : operator; + errors.push(...validateExpression({ + key: `${key}.${prop}.map`, + value: mapExpr, + validateSpec, + expressionContext: 'cluster-map' + })); + errors.push(...validateExpression({ + key: `${key}.${prop}.reduce`, + value: reduceExpr, + validateSpec, + expressionContext: 'cluster-reduce' + })); + } + } + return errors; + case 'video': + return validateObject({ + key, + value, + valueSpec: styleSpec.source_video, + style, + validateSpec, + styleSpec + }); + case 'image': + return validateObject({ + key, + value, + valueSpec: styleSpec.source_image, + style, + validateSpec, + styleSpec + }); + case 'canvas': + return [new ValidationError(key, null, 'Please use runtime APIs to add canvas sources, rather than including them in stylesheets.', 'source.canvas')]; + default: + return validateEnum({ + key: `${key}.type`, + value: value.type, + valueSpec: { values: ['vector', 'raster', 'raster-dem', 'geojson', 'video', 'image'] }, + style, + validateSpec, + styleSpec + }); + } +} +function validatePromoteId({ key, value }) { + if (getType(value) === 'string') { + return validateString({ key, value }); + } + else { + const errors = []; + for (const prop in value) { + errors.push(...validateString({ key: `${key}.${prop}`, value: value[prop] })); + } + return errors; + } +} + +function validateLight$1(options) { + const light = options.value; + const styleSpec = options.styleSpec; + const lightSpec = styleSpec.light; + const style = options.style; + let errors = []; + const rootType = getType(light); + if (light === undefined) { + return errors; + } + else if (rootType !== 'object') { + errors = errors.concat([new ValidationError('light', light, `object expected, ${rootType} found`)]); + return errors; + } + for (const key in light) { + const transitionMatch = key.match(/^(.*)-transition$/); + if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) { + errors = errors.concat(options.validateSpec({ + key, + value: light[key], + valueSpec: styleSpec.transition, + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else if (lightSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: light[key], + valueSpec: lightSpec[key], + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, light[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +function validateSky$1(options) { + const sky = options.value; + const styleSpec = options.styleSpec; + const skySpec = styleSpec.sky; + const style = options.style; + const rootType = getType(sky); + if (sky === undefined) { + return []; + } + else if (rootType !== 'object') { + return [new ValidationError('sky', sky, `object expected, ${rootType} found`)]; + } + let errors = []; + for (const key in sky) { + if (skySpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: sky[key], + valueSpec: skySpec[key], + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, sky[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +function validateTerrain$1(options) { + const terrain = options.value; + const styleSpec = options.styleSpec; + const terrainSpec = styleSpec.terrain; + const style = options.style; + let errors = []; + const rootType = getType(terrain); + if (terrain === undefined) { + return errors; + } + else if (rootType !== 'object') { + errors = errors.concat([new ValidationError('terrain', terrain, `object expected, ${rootType} found`)]); + return errors; + } + for (const key in terrain) { + if (terrainSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: terrain[key], + valueSpec: terrainSpec[key], + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, terrain[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +function validateFormatted(options) { + if (validateString(options).length === 0) { + return []; + } + return validateExpression(options); +} + +function validateImage(options) { + if (validateString(options).length === 0) { + return []; + } + return validateExpression(options); +} + +function validatePadding(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + if (type === 'array') { + if (value.length < 1 || value.length > 4) { + return [new ValidationError(key, value, `padding requires 1 to 4 values; ${value.length} values found`)]; + } + const arrayElementSpec = { + type: 'number' + }; + let errors = []; + for (let i = 0; i < value.length; i++) { + errors = errors.concat(options.validateSpec({ + key: `${key}[${i}]`, + value: value[i], + validateSpec: options.validateSpec, + valueSpec: arrayElementSpec + })); + } + return errors; + } + else { + return validateNumber({ + key, + value, + valueSpec: {} + }); + } +} + +function validateVariableAnchorOffsetCollection(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + const styleSpec = options.styleSpec; + if (type !== 'array' || value.length < 1 || value.length % 2 !== 0) { + return [new ValidationError(key, value, 'variableAnchorOffsetCollection requires a non-empty array of even length')]; + } + let errors = []; + for (let i = 0; i < value.length; i += 2) { + // Elements in even positions should be values from text-anchor enum + errors = errors.concat(validateEnum({ + key: `${key}[${i}]`, + value: value[i], + valueSpec: styleSpec['layout_symbol']['text-anchor'] + })); + // Elements in odd positions should be points (2-element numeric arrays) + errors = errors.concat(validateArray({ + key: `${key}[${i + 1}]`, + value: value[i + 1], + valueSpec: { + length: 2, + value: 'number' + }, + validateSpec: options.validateSpec, + style: options.style, + styleSpec + })); + } + return errors; +} + +function validateSprite(options) { + let errors = []; + const sprite = options.value; + const key = options.key; + if (!Array.isArray(sprite)) { + return validateString({ + key, + value: sprite + }); + } + else { + const allSpriteIds = []; + const allSpriteURLs = []; + for (const i in sprite) { + if (sprite[i].id && allSpriteIds.includes(sprite[i].id)) + errors.push(new ValidationError(key, sprite, `all the sprites' ids must be unique, but ${sprite[i].id} is duplicated`)); + allSpriteIds.push(sprite[i].id); + if (sprite[i].url && allSpriteURLs.includes(sprite[i].url)) + errors.push(new ValidationError(key, sprite, `all the sprites' URLs must be unique, but ${sprite[i].url} is duplicated`)); + allSpriteURLs.push(sprite[i].url); + const pairSpec = { + id: { + type: 'string', + required: true, + }, + url: { + type: 'string', + required: true, + } + }; + errors = errors.concat(validateObject({ + key: `${key}[${i}]`, + value: sprite[i], + valueSpec: pairSpec, + validateSpec: options.validateSpec, + })); + } + return errors; + } +} + +function validateProjection(options) { + const projection = options.value; + const styleSpec = options.styleSpec; + const projectionSpec = styleSpec.projection; + const style = options.style; + const rootType = getType(projection); + if (projection === undefined) { + return []; + } + else if (rootType !== 'object') { + return [new ValidationError('projection', projection, `object expected, ${rootType} found`)]; + } + let errors = []; + for (const key in projection) { + if (projectionSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: projection[key], + valueSpec: projectionSpec[key], + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, projection[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +const VALIDATORS = { + '*'() { + return []; + }, + 'array': validateArray, + 'boolean': validateBoolean, + 'number': validateNumber, + 'color': validateColor, + 'constants': validateConstants, + 'enum': validateEnum, + 'filter': validateFilter$1, + 'function': validateFunction, + 'layer': validateLayer, + 'object': validateObject, + 'source': validateSource$1, + 'light': validateLight$1, + 'sky': validateSky$1, + 'terrain': validateTerrain$1, + 'projection': validateProjection, + 'string': validateString, + 'formatted': validateFormatted, + 'resolvedImage': validateImage, + 'padding': validatePadding, + 'variableAnchorOffsetCollection': validateVariableAnchorOffsetCollection, + 'sprite': validateSprite, +}; +/** + * Main recursive validation function used internally. + * You should use `validateStyleMin` in the browser or `validateStyle` in node env. + * @param options - the options object + * @param options.key - string representing location of validation in style tree. Used only + * for more informative error reporting. + * @param options.value - current value from style being evaluated. May be anything from a + * high level object that needs to be descended into deeper or a simple + * scalar value. + * @param options.valueSpec - current spec being evaluated. Tracks value. + * @param options.styleSpec - current full spec being evaluated. + * @param options.validateSpec - the validate function itself + * @param options.style - the style object + * @param options.objectElementValidators - optional object of functions that will be called + * @returns an array of errors, or an empty array if no errors are found. + */ +function validate(options) { + const value = options.value; + const valueSpec = options.valueSpec; + const styleSpec = options.styleSpec; + options.validateSpec = validate; + if (valueSpec.expression && isFunction$1(unbundle(value))) { + return validateFunction(options); + } + else if (valueSpec.expression && isExpression(deepUnbundle(value))) { + return validateExpression(options); + } + else if (valueSpec.type && VALIDATORS[valueSpec.type]) { + return VALIDATORS[valueSpec.type](options); + } + else { + const valid = validateObject(extendBy({}, options, { + valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec + })); + return valid; + } +} + +function validateGlyphsUrl(options) { + const value = options.value; + const key = options.key; + const errors = validateString(options); + if (errors.length) + return errors; + if (value.indexOf('{fontstack}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{fontstack}" token')); + } + if (value.indexOf('{range}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{range}" token')); + } + return errors; +} + +/** + * Validate a MapLibre style against the style specification. + * Use this when running in the browser. + * + * @param style - The style to be validated. + * @param styleSpec - The style specification to validate against. + * If omitted, the latest style spec is used. + * @returns an array of errors, or an empty array if no errors are found. + * @example + * const validate = require('@maplibre/maplibre-gl-style-spec/').validateStyleMin; + * const errors = validate(style); + */ +function validateStyleMin(style, styleSpec = v8Spec) { + let errors = []; + errors = errors.concat(validate({ + key: '', + value: style, + valueSpec: styleSpec.$root, + styleSpec, + style, + validateSpec: validate, + objectElementValidators: { + glyphs: validateGlyphsUrl, + '*'() { + return []; + } + } + })); + if (style['constants']) { + errors = errors.concat(validateConstants({ + key: 'constants', + value: style['constants'], + style, + styleSpec, + validateSpec: validate, + })); + } + return sortErrors(errors); +} +validateStyleMin.source = wrapCleanErrors(injectValidateSpec(validateSource$1)); +validateStyleMin.sprite = wrapCleanErrors(injectValidateSpec(validateSprite)); +validateStyleMin.glyphs = wrapCleanErrors(injectValidateSpec(validateGlyphsUrl)); +validateStyleMin.light = wrapCleanErrors(injectValidateSpec(validateLight$1)); +validateStyleMin.sky = wrapCleanErrors(injectValidateSpec(validateSky$1)); +validateStyleMin.terrain = wrapCleanErrors(injectValidateSpec(validateTerrain$1)); +validateStyleMin.layer = wrapCleanErrors(injectValidateSpec(validateLayer)); +validateStyleMin.filter = wrapCleanErrors(injectValidateSpec(validateFilter$1)); +validateStyleMin.paintProperty = wrapCleanErrors(injectValidateSpec(validatePaintProperty$1)); +validateStyleMin.layoutProperty = wrapCleanErrors(injectValidateSpec(validateLayoutProperty$1)); +function injectValidateSpec(validator) { + return function (options) { + return validator({ + ...options, + validateSpec: validate, + }); + }; +} +function sortErrors(errors) { + return [].concat(errors).sort((a, b) => { + return a.line - b.line; + }); +} +function wrapCleanErrors(inner) { + return function (...args) { + return sortErrors(inner.apply(this, args)); + }; +} + +// Note: This regex matches even invalid JSON strings, but since we’re +// working on the output of `JSON.stringify` we know that only valid strings +// are present (unless the user supplied a weird `options.indent` but in +// that case we don’t care since the output would be invalid anyway). +const stringOrChar = /("(?:[^\\"]|\\.)*")|[:,]/g; + +function stringify(passedObj, options = {}) { + const indent = JSON.stringify( + [1], + undefined, + options.indent === undefined ? 2 : options.indent + ).slice(2, -3); + + const maxLength = + indent === "" + ? Infinity + : options.maxLength === undefined + ? 80 + : options.maxLength; + + let { replacer } = options; + + return (function _stringify(obj, currentIndent, reserved) { + if (obj && typeof obj.toJSON === "function") { + obj = obj.toJSON(); + } + + const string = JSON.stringify(obj, replacer); + + if (string === undefined) { + return string; + } + + const length = maxLength - currentIndent.length - reserved; + + if (string.length <= length) { + const prettified = string.replace( + stringOrChar, + (match, stringLiteral) => { + return stringLiteral || `${match} `; + } + ); + if (prettified.length <= length) { + return prettified; + } + } + + if (replacer != null) { + obj = JSON.parse(string); + replacer = undefined; + } + + if (typeof obj === "object" && obj !== null) { + const nextIndent = currentIndent + indent; + const items = []; + let index = 0; + let start; + let end; + + if (Array.isArray(obj)) { + start = "["; + end = "]"; + const { length } = obj; + for (; index < length; index++) { + items.push( + _stringify(obj[index], nextIndent, index === length - 1 ? 0 : 1) || + "null" + ); + } + } else { + start = "{"; + end = "}"; + const keys = Object.keys(obj); + const { length } = keys; + for (; index < length; index++) { + const key = keys[index]; + const keyPart = `${JSON.stringify(key)}: `; + const value = _stringify( + obj[key], + nextIndent, + keyPart.length + (index === length - 1 ? 0 : 1) + ); + if (value !== undefined) { + items.push(keyPart + value); + } + } + } + + if (items.length > 0) { + return [start, indent + items.join(`,\n${nextIndent}`), end].join( + `\n${currentIndent}` + ); + } + } + + return string; + })(passedObj, "", 0); +} + +function sortKeysBy(obj, reference) { + const result = {}; + for (const key in reference) { + if (obj[key] !== undefined) { + result[key] = obj[key]; + } + } + for (const key in obj) { + if (result[key] === undefined) { + result[key] = obj[key]; + } + } + return result; +} +/** + * Format a MapLibre Style. Returns a stringified style with its keys + * sorted in the same order as the reference style. + * + * The optional `space` argument is passed to + * [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) + * to generate formatted output. + * + * If `space` is unspecified, a default of `2` spaces will be used. + * + * @private + * @param {Object} style a MapLibre Style + * @param {number} [space] space argument to pass to `JSON.stringify` + * @returns {string} stringified formatted JSON + * @example + * var fs = require('fs'); + * var format = require('maplibre-gl-style-spec').format; + * var style = fs.readFileSync('./source.json', 'utf8'); + * fs.writeFileSync('./dest.json', format(style)); + * fs.writeFileSync('./dest.min.json', format(style, 0)); + */ +function format(style, space = 2) { + style = sortKeysBy(style, v8Spec.$root); + if (style.layers) { + style.layers = style.layers.map((layer) => sortKeysBy(layer, v8Spec.layer)); + } + return stringify(style, { indent: space }); +} + +function eachLayout(layer, callback) { + for (const k in layer) { + if (k.indexOf('layout') === 0) { + callback(layer[k], k); + } + } +} +function eachPaint(layer, callback) { + for (const k in layer) { + if (k.indexOf('paint') === 0) { + callback(layer[k], k); + } + } +} +function resolveConstant(style, value) { + if (typeof value === 'string' && value[0] === '@') { + return resolveConstant(style, style.constants[value]); + } + else { + return value; + } +} +function isFunction(value) { + return Array.isArray(value.stops); +} +function renameProperty(obj, from, to) { + obj[to] = obj[from]; + delete obj[from]; +} +function migrateV8(style) { + style.version = 8; + // Rename properties, reverse coordinates in source and layers + eachSource(style, (source) => { + if (source.type === 'video' && source['url'] !== undefined) { + renameProperty(source, 'url', 'urls'); + } + if (source.type === 'video') { + source.coordinates.forEach((coord) => { + return coord.reverse(); + }); + } + }); + eachLayer(style, (layer) => { + eachLayout(layer, (layout) => { + if (layout['symbol-min-distance'] !== undefined) { + renameProperty(layout, 'symbol-min-distance', 'symbol-spacing'); + } + }); + eachPaint(layer, (paint) => { + if (paint['background-image'] !== undefined) { + renameProperty(paint, 'background-image', 'background-pattern'); + } + if (paint['line-image'] !== undefined) { + renameProperty(paint, 'line-image', 'line-pattern'); + } + if (paint['fill-image'] !== undefined) { + renameProperty(paint, 'fill-image', 'fill-pattern'); + } + }); + }); + // Inline Constants + eachProperty(style, { paint: true, layout: true }, (property) => { + const value = resolveConstant(style, property.value); + if (isFunction(value)) { + value.stops.forEach((stop) => { + stop[1] = resolveConstant(style, stop[1]); + }); + } + property.set(value); + }); + delete style['constants']; + eachLayer(style, (layer) => { + // get rid of text-max-size, icon-max-size + // turn text-size, icon-size into layout properties + // https://github.com/mapbox/mapbox-gl-style-spec/issues/255 + eachLayout(layer, (layout) => { + delete layout['text-max-size']; + delete layout['icon-max-size']; + }); + eachPaint(layer, (paint) => { + if (paint['text-size']) { + if (!layer.layout) + layer.layout = {}; + layer.layout['text-size'] = paint['text-size']; + delete paint['text-size']; + } + if (paint['icon-size']) { + if (!layer.layout) + layer.layout = {}; + layer.layout['icon-size'] = paint['icon-size']; + delete paint['icon-size']; + } + }); + }); + function migrateFontStack(font) { + function splitAndTrim(string) { + return string.split(',').map((s) => { + return s.trim(); + }); + } + if (Array.isArray(font)) { + // Assume it's a previously migrated font-array. + return font; + } + else if (typeof font === 'string') { + return splitAndTrim(font); + } + else if (typeof font === 'object') { + font.stops.forEach((stop) => { + stop[1] = splitAndTrim(stop[1]); + }); + return font; + } + else { + throw new Error('unexpected font value'); + } + } + eachLayer(style, (layer) => { + eachLayout(layer, (layout) => { + if (layout['text-font']) { + layout['text-font'] = migrateFontStack(layout['text-font']); + } + }); + }); + // Reverse order of symbol layers. This is an imperfect migration. + // + // The order of a symbol layer in the layers list affects two things: + // - how it is drawn relative to other layers (like oneway arrows below bridges) + // - the placement priority compared to other layers + // + // It's impossible to reverse the placement priority without breaking the draw order + // in some cases. This migration only reverses the order of symbol layers that + // are above all other types of layers. + // + // Symbol layers that are at the top of the map preserve their priority. + // Symbol layers that are below another type (line, fill) of layer preserve their draw order. + let firstSymbolLayer = 0; + for (let i = style.layers.length - 1; i >= 0; i--) { + const layer = style.layers[i]; + if (layer.type !== 'symbol') { + firstSymbolLayer = i + 1; + break; + } + } + const symbolLayers = style.layers.splice(firstSymbolLayer); + symbolLayers.reverse(); + style.layers = style.layers.concat(symbolLayers); + return style; +} + +/** + * Migrate the given style object in place to use expressions. Specifically, + * this will convert (a) "stop" functions, and (b) legacy filters to their + * expression equivalents. + * @param style The style object to migrate. + * @returns The migrated style object. + */ +function expressions(style) { + const converted = []; + eachLayer(style, (layer) => { + if (layer.filter) { + layer.filter = convertFilter(layer.filter); + } + }); + eachProperty(style, { paint: true, layout: true }, ({ path, value, reference, set }) => { + if (isExpression(value)) + return; + if (typeof value === 'object' && !Array.isArray(value)) { + set(convertFunction(value, reference)); + converted.push(path.join('.')); + } + else if (reference.tokens && typeof value === 'string') { + set(convertTokenString(value)); + } + }); + return style; +} + +/** + * Migrate color style values to supported format. + * + * @param colorToMigrate Color value to migrate, could be a string or an expression. + * @returns Color style value in supported format. + */ +function migrateColors(colorToMigrate) { + return JSON.parse(migrateHslColors(JSON.stringify(colorToMigrate))); +} +/** + * Created to migrate from colors supported by the former CSS color parsing + * library `csscolorparser` but not compliant with the CSS Color specification, + * like `hsl(900, 0.15, 90%)`. + * + * @param colorToMigrate Serialized color style value. + * @returns A serialized color style value in which all non-standard hsl color values + * have been converted to a format that complies with the CSS Color specification. + * + * @example + * migrateHslColors('"hsl(900, 0.15, 90%)"'); // returns '"hsl(900, 15%, 90%)"' + * migrateHslColors('"hsla(900, .15, .9)"'); // returns '"hsl(900, 15%, 90%)"' + * migrateHslColors('"hsl(900, 15%, 90%)"'); // returns '"hsl(900, 15%, 90%)"' - no changes + */ +function migrateHslColors(colorToMigrate) { + return colorToMigrate.replace(/"hsla?\((.+?)\)"/gi, (match, hslArgs) => { + const argsMatch = hslArgs.match(/^(.+?)\s*,\s*(.+?)\s*,\s*(.+?)(?:\s*,\s*(.+))?$/i); + if (argsMatch) { + let [h, s, l, a] = argsMatch.slice(1); + [s, l] = [s, l].map(v => v.endsWith('%') ? v : `${parseFloat(v) * 100}%`); + return `"hsl${typeof a === 'string' ? 'a' : ''}(${[h, s, l, a].filter(Boolean).join(',')})"`; + } + return match; + }); +} + +/** + * Migrate a Mapbox/MapLibre GL Style to the latest version. + * + * @param style - a MapLibre Style + * @returns a migrated style + * @example + * const fs = require('fs'); + * csont migrate = require('@maplibre/maplibre-gl-style-spec').migrate; + * const style = fs.readFileSync('./style.json', 'utf8'); + * fs.writeFileSync('./style.json', JSON.stringify(migrate(style))); + */ +function migrate(style) { + let migrated = false; + if (style.version === 7) { + style = migrateV8(style); + migrated = true; + } + if (style.version === 8) { + migrated = !!expressions(style); + migrated = true; + } + eachProperty(style, { paint: true, layout: true }, ({ value, reference, set }) => { + if (reference.type === 'color') { + set(migrateColors(value)); + } + }); + if (!migrated) { + throw new Error(`Cannot migrate from ${style.version}`); + } + return style; +} + +const v8 = v8Spec; +const expression = { + StyleExpression, + StylePropertyFunction, + ZoomConstantExpression, + ZoomDependentExpression, + createExpression, + createPropertyExpression, + isExpression, + isExpressionFilter, + isZoomExpression, + normalizePropertyExpression, +}; +const styleFunction = { + convertFunction, + createFunction, + isFunction: isFunction$1 +}; +const visit = { eachLayer, eachProperty, eachSource }; + +const validateStyle = validateStyleMin; +const validateSource = validateStyle.source; +const validateLight = validateStyle.light; +const validateSky = validateStyle.sky; +const validateTerrain = validateStyle.terrain; +const validateFilter = validateStyle.filter; +const validatePaintProperty = validateStyle.paintProperty; +const validateLayoutProperty = validateStyle.layoutProperty; +function emitValidationErrors$1(emitter, errors) { + let hasErrors = false; + if (errors && errors.length) { + for (const error of errors) { + emitter.fire(new ErrorEvent(new Error(error.message))); + hasErrors = true; + } + } + return hasErrors; +} + +/* +This file was copied from https://github.com/mapbox/grid-index and was +migrated from JavaScript to TypeScript. + +Copyright (c) 2016, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +*/ +const NUM_PARAMS = 3; +class TransferableGridIndex { + constructor(extent, n, padding) { + const cells = this.cells = []; + if (extent instanceof ArrayBuffer) { + this.arrayBuffer = extent; + const array = new Int32Array(this.arrayBuffer); + extent = array[0]; + n = array[1]; + padding = array[2]; + this.d = n + 2 * padding; + for (let k = 0; k < this.d * this.d; k++) { + const start = array[NUM_PARAMS + k]; + const end = array[NUM_PARAMS + k + 1]; + cells.push(start === end ? null : array.subarray(start, end)); + } + const keysOffset = array[NUM_PARAMS + cells.length]; + const bboxesOffset = array[NUM_PARAMS + cells.length + 1]; + this.keys = array.subarray(keysOffset, bboxesOffset); + this.bboxes = array.subarray(bboxesOffset); + this.insert = this._insertReadonly; + } + else { + this.d = n + 2 * padding; + for (let i = 0; i < this.d * this.d; i++) { + cells.push([]); + } + this.keys = []; + this.bboxes = []; + } + this.n = n; + this.extent = extent; + this.padding = padding; + this.scale = n / extent; + this.uid = 0; + const p = (padding / n) * extent; + this.min = -p; + this.max = extent + p; + } + insert(key, x1, y1, x2, y2) { + this._forEachCell(x1, y1, x2, y2, this._insertCell, this.uid++, undefined, undefined); + this.keys.push(key); + this.bboxes.push(x1); + this.bboxes.push(y1); + this.bboxes.push(x2); + this.bboxes.push(y2); + } + _insertReadonly() { + throw new Error('Cannot insert into a GridIndex created from an ArrayBuffer.'); + } + _insertCell(x1, y1, x2, y2, cellIndex, uid) { + this.cells[cellIndex].push(uid); + } + query(x1, y1, x2, y2, intersectionTest) { + const min = this.min; + const max = this.max; + if (x1 <= min && y1 <= min && max <= x2 && max <= y2 && !intersectionTest) { + // We use `Array#slice` because `this.keys` may be a `Int32Array` and + // some browsers (Safari and IE) do not support `TypedArray#slice` + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice#Browser_compatibility + return Array.prototype.slice.call(this.keys); + } + else { + const result = []; + const seenUids = {}; + this._forEachCell(x1, y1, x2, y2, this._queryCell, result, seenUids, intersectionTest); + return result; + } + } + _queryCell(x1, y1, x2, y2, cellIndex, result, seenUids, intersectionTest) { + const cell = this.cells[cellIndex]; + if (cell !== null) { + const keys = this.keys; + const bboxes = this.bboxes; + for (let u = 0; u < cell.length; u++) { + const uid = cell[u]; + if (seenUids[uid] === undefined) { + const offset = uid * 4; + if (intersectionTest ? + intersectionTest(bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) : + ((x1 <= bboxes[offset + 2]) && + (y1 <= bboxes[offset + 3]) && + (x2 >= bboxes[offset + 0]) && + (y2 >= bboxes[offset + 1]))) { + seenUids[uid] = true; + result.push(keys[uid]); + } + else { + seenUids[uid] = false; + } + } + } + } + } + _forEachCell(x1, y1, x2, y2, fn, arg1, arg2, intersectionTest) { + const cx1 = this._convertToCellCoord(x1); + const cy1 = this._convertToCellCoord(y1); + const cx2 = this._convertToCellCoord(x2); + const cy2 = this._convertToCellCoord(y2); + for (let x = cx1; x <= cx2; x++) { + for (let y = cy1; y <= cy2; y++) { + const cellIndex = this.d * y + x; + if (intersectionTest && !intersectionTest(this._convertFromCellCoord(x), this._convertFromCellCoord(y), this._convertFromCellCoord(x + 1), this._convertFromCellCoord(y + 1))) + continue; + if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, intersectionTest)) + return; + } + } + } + _convertFromCellCoord(x) { + return (x - this.padding) / this.scale; + } + _convertToCellCoord(x) { + return Math.max(0, Math.min(this.d - 1, Math.floor(x * this.scale) + this.padding)); + } + toArrayBuffer() { + if (this.arrayBuffer) + return this.arrayBuffer; + const cells = this.cells; + const metadataLength = NUM_PARAMS + this.cells.length + 1 + 1; + let totalCellLength = 0; + for (let i = 0; i < this.cells.length; i++) { + totalCellLength += this.cells[i].length; + } + const array = new Int32Array(metadataLength + totalCellLength + this.keys.length + this.bboxes.length); + array[0] = this.extent; + array[1] = this.n; + array[2] = this.padding; + let offset = metadataLength; + for (let k = 0; k < cells.length; k++) { + const cell = cells[k]; + array[NUM_PARAMS + k] = offset; + array.set(cell, offset); + offset += cell.length; + } + array[NUM_PARAMS + cells.length] = offset; + array.set(this.keys, offset); + offset += this.keys.length; + array[NUM_PARAMS + cells.length + 1] = offset; + array.set(this.bboxes, offset); + offset += this.bboxes.length; + return array.buffer; + } + static serialize(grid, transferables) { + const buffer = grid.toArrayBuffer(); + if (transferables) { + transferables.push(buffer); + } + return { buffer }; + } + static deserialize(serialized) { + return new TransferableGridIndex(serialized.buffer); + } +} + +const registry = {}; +/** + * Register the given class as serializable. + * + * @param options - the registration options + */ +function register(name, klass, options = {}) { + if (registry[name]) + throw new Error(`${name} is already registered.`); + Object.defineProperty(klass, '_classRegistryKey', { + value: name, + writeable: false + }); + registry[name] = { + klass, + omit: options.omit || [], + shallow: options.shallow || [] + }; +} +register('Object', Object); +register('TransferableGridIndex', TransferableGridIndex); +register('Color', Color); +register('Error', Error); +register('AJAXError', AJAXError); +register('ResolvedImage', ResolvedImage); +register('StylePropertyFunction', StylePropertyFunction); +register('StyleExpression', StyleExpression, { omit: ['_evaluator'] }); +register('ZoomDependentExpression', ZoomDependentExpression); +register('ZoomConstantExpression', ZoomConstantExpression); +register('CompoundExpression', CompoundExpression, { omit: ['_evaluate'] }); +for (const name in expressions$1) { + if (expressions$1[name]._classRegistryKey) + continue; + register(`Expression_${name}`, expressions$1[name]); +} +function isArrayBuffer(value) { + return value && typeof ArrayBuffer !== 'undefined' && + (value instanceof ArrayBuffer || (value.constructor && value.constructor.name === 'ArrayBuffer')); +} +function getClassRegistryKey(input) { + const klass = input.constructor; + return input.$name || klass._classRegistryKey; +} +function isRegistered(input) { + if (input === null || typeof input !== 'object') { + return false; + } + const classRegistryKey = getClassRegistryKey(input); + if (classRegistryKey && classRegistryKey !== 'Object') { + return true; + } + return false; +} +function isSerializeHandledByBuiltin(input) { + return (!isRegistered(input) && (input === null || + input === undefined || + typeof input === 'boolean' || + typeof input === 'number' || + typeof input === 'string' || + input instanceof Boolean || + input instanceof Number || + input instanceof String || + input instanceof Date || + input instanceof RegExp || + input instanceof Blob || + input instanceof Error || + isArrayBuffer(input) || + isImageBitmap(input) || + ArrayBuffer.isView(input) || + input instanceof ImageData)); +} +/** + * Serialize the given object for transfer to or from a web worker. + * + * For non-builtin types, recursively serialize each property (possibly + * omitting certain properties - see register()), and package the result along + * with the constructor's `name` so that the appropriate constructor can be + * looked up in `deserialize()`. + * + * If a `transferables` array is provided, add any transferable objects (i.e., + * any ArrayBuffers or ArrayBuffer views) to the list. (If a copy is needed, + * this should happen in the client code, before using serialize().) + */ +function serialize(input, transferables) { + if (isSerializeHandledByBuiltin(input)) { + if (isArrayBuffer(input) || isImageBitmap(input)) { + if (transferables) { + transferables.push(input); + } + } + if (ArrayBuffer.isView(input)) { + const view = input; + if (transferables) { + transferables.push(view.buffer); + } + } + if (input instanceof ImageData) { + if (transferables) { + transferables.push(input.data.buffer); + } + } + return input; + } + if (Array.isArray(input)) { + const serialized = []; + for (const item of input) { + serialized.push(serialize(item, transferables)); + } + return serialized; + } + if (typeof input !== 'object') { + throw new Error(`can't serialize object of type ${typeof input}`); + } + const classRegistryKey = getClassRegistryKey(input); + if (!classRegistryKey) { + throw new Error(`can't serialize object of unregistered class ${input.constructor.name}`); + } + if (!registry[classRegistryKey]) + throw new Error(`${classRegistryKey} is not registered.`); + const { klass } = registry[classRegistryKey]; + const properties = klass.serialize ? + // (Temporary workaround) allow a class to provide static + // `serialize()` and `deserialize()` methods to bypass the generic + // approach. + // This temporary workaround lets us use the generic serialization + // approach for objects whose members include instances of dynamic + // StructArray types. Once we refactor StructArray to be static, + // we can remove this complexity. + klass.serialize(input, transferables) : {}; + if (!klass.serialize) { + for (const key in input) { + if (!input.hasOwnProperty(key)) + continue; // eslint-disable-line no-prototype-builtins + if (registry[classRegistryKey].omit.indexOf(key) >= 0) + continue; + const property = input[key]; + properties[key] = registry[classRegistryKey].shallow.indexOf(key) >= 0 ? + property : + serialize(property, transferables); + } + if (input instanceof Error) { + properties.message = input.message; + } + } + else { + if (transferables && properties === transferables[transferables.length - 1]) { + throw new Error('statically serialized object won\'t survive transfer of $name property'); + } + } + if (properties.$name) { + throw new Error('$name property is reserved for worker serialization logic.'); + } + if (classRegistryKey !== 'Object') { + properties.$name = classRegistryKey; + } + return properties; +} +function deserialize$1(input) { + if (isSerializeHandledByBuiltin(input)) { + return input; + } + if (Array.isArray(input)) { + return input.map(deserialize$1); + } + if (typeof input !== 'object') { + throw new Error(`can't deserialize object of type ${typeof input}`); + } + const classRegistryKey = getClassRegistryKey(input) || 'Object'; + if (!registry[classRegistryKey]) { + throw new Error(`can't deserialize unregistered class ${classRegistryKey}`); + } + const { klass } = registry[classRegistryKey]; + if (!klass) { + throw new Error(`can't deserialize unregistered class ${classRegistryKey}`); + } + if (klass.deserialize) { + return klass.deserialize(input); + } + const result = Object.create(klass.prototype); + for (const key of Object.keys(input)) { + if (key === '$name') + continue; + const value = input[key]; + result[key] = registry[classRegistryKey].shallow.indexOf(key) >= 0 ? value : deserialize$1(value); + } + return result; +} + +class ZoomHistory { + constructor() { + this.first = true; + } + update(z, now) { + const floorZ = Math.floor(z); + if (this.first) { + this.first = false; + this.lastIntegerZoom = floorZ; + this.lastIntegerZoomTime = 0; + this.lastZoom = z; + this.lastFloorZoom = floorZ; + return true; + } + if (this.lastFloorZoom > floorZ) { + this.lastIntegerZoom = floorZ + 1; + this.lastIntegerZoomTime = now; + } + else if (this.lastFloorZoom < floorZ) { + this.lastIntegerZoom = floorZ; + this.lastIntegerZoomTime = now; + } + if (z !== this.lastZoom) { + this.lastZoom = z; + this.lastFloorZoom = floorZ; + return true; + } + return false; + } +} + +// The following table comes from . +// Keep it synchronized with . +const unicodeBlockLookup = { + // 'Basic Latin': (char) => char >= 0x0000 && char <= 0x007F, + 'Latin-1 Supplement': (char) => char >= 0x0080 && char <= 0x00FF, + // 'Latin Extended-A': (char) => char >= 0x0100 && char <= 0x017F, + // 'Latin Extended-B': (char) => char >= 0x0180 && char <= 0x024F, + // 'IPA Extensions': (char) => char >= 0x0250 && char <= 0x02AF, + // 'Spacing Modifier Letters': (char) => char >= 0x02B0 && char <= 0x02FF, + // 'Combining Diacritical Marks': (char) => char >= 0x0300 && char <= 0x036F, + // 'Greek and Coptic': (char) => char >= 0x0370 && char <= 0x03FF, + // 'Cyrillic': (char) => char >= 0x0400 && char <= 0x04FF, + // 'Cyrillic Supplement': (char) => char >= 0x0500 && char <= 0x052F, + // 'Armenian': (char) => char >= 0x0530 && char <= 0x058F, + //'Hebrew': (char) => char >= 0x0590 && char <= 0x05FF, + // 'Arabic': (char) => char >= 0x0600 && char <= 0x06FF, + //'Syriac': (char) => char >= 0x0700 && char <= 0x074F, + // 'Arabic Supplement': (char) => char >= 0x0750 && char <= 0x077F, + // 'Thaana': (char) => char >= 0x0780 && char <= 0x07BF, + // 'NKo': (char) => char >= 0x07C0 && char <= 0x07FF, + // 'Samaritan': (char) => char >= 0x0800 && char <= 0x083F, + // 'Mandaic': (char) => char >= 0x0840 && char <= 0x085F, + // 'Syriac Supplement': (char) => char >= 0x0860 && char <= 0x086F, + // 'Arabic Extended-B': (char) => char >= 0x0870 && char <= 0x089F, + // 'Arabic Extended-A': (char) => char >= 0x08A0 && char <= 0x08FF, + // 'Devanagari': (char) => char >= 0x0900 && char <= 0x097F, + // 'Bengali': (char) => char >= 0x0980 && char <= 0x09FF, + // 'Gurmukhi': (char) => char >= 0x0A00 && char <= 0x0A7F, + // 'Gujarati': (char) => char >= 0x0A80 && char <= 0x0AFF, + // 'Oriya': (char) => char >= 0x0B00 && char <= 0x0B7F, + // 'Tamil': (char) => char >= 0x0B80 && char <= 0x0BFF, + // 'Telugu': (char) => char >= 0x0C00 && char <= 0x0C7F, + // 'Kannada': (char) => char >= 0x0C80 && char <= 0x0CFF, + // 'Malayalam': (char) => char >= 0x0D00 && char <= 0x0D7F, + // 'Sinhala': (char) => char >= 0x0D80 && char <= 0x0DFF, + // 'Thai': (char) => char >= 0x0E00 && char <= 0x0E7F, + // 'Lao': (char) => char >= 0x0E80 && char <= 0x0EFF, + // 'Tibetan': (char) => char >= 0x0F00 && char <= 0x0FFF, + // 'Myanmar': (char) => char >= 0x1000 && char <= 0x109F, + // 'Georgian': (char) => char >= 0x10A0 && char <= 0x10FF, + 'Hangul Jamo': (char) => char >= 0x1100 && char <= 0x11FF, + // 'Ethiopic': (char) => char >= 0x1200 && char <= 0x137F, + // 'Ethiopic Supplement': (char) => char >= 0x1380 && char <= 0x139F, + // 'Cherokee': (char) => char >= 0x13A0 && char <= 0x13FF, + // 'Unified Canadian Aboriginal Syllabics': (char) => char >= 0x1400 && char <= 0x167F, + // 'Ogham': (char) => char >= 0x1680 && char <= 0x169F, + // 'Runic': (char) => char >= 0x16A0 && char <= 0x16FF, + // 'Tagalog': (char) => char >= 0x1700 && char <= 0x171F, + // 'Hanunoo': (char) => char >= 0x1720 && char <= 0x173F, + // 'Buhid': (char) => char >= 0x1740 && char <= 0x175F, + // 'Tagbanwa': (char) => char >= 0x1760 && char <= 0x177F, + 'Khmer': (char) => char >= 0x1780 && char <= 0x17FF, + // 'Mongolian': (char) => char >= 0x1800 && char <= 0x18AF, + // 'Unified Canadian Aboriginal Syllabics Extended': (char) => char >= 0x18B0 && char <= 0x18FF, + // 'Limbu': (char) => char >= 0x1900 && char <= 0x194F, + // 'Tai Le': (char) => char >= 0x1950 && char <= 0x197F, + // 'New Tai Lue': (char) => char >= 0x1980 && char <= 0x19DF, + // 'Khmer Symbols': (char) => char >= 0x19E0 && char <= 0x19FF, + // 'Buginese': (char) => char >= 0x1A00 && char <= 0x1A1F, + // 'Tai Tham': (char) => char >= 0x1A20 && char <= 0x1AAF, + // 'Combining Diacritical Marks Extended': (char) => char >= 0x1AB0 && char <= 0x1AFF, + // 'Balinese': (char) => char >= 0x1B00 && char <= 0x1B7F, + // 'Sundanese': (char) => char >= 0x1B80 && char <= 0x1BBF, + // 'Batak': (char) => char >= 0x1BC0 && char <= 0x1BFF, + // 'Lepcha': (char) => char >= 0x1C00 && char <= 0x1C4F, + // 'Ol Chiki': (char) => char >= 0x1C50 && char <= 0x1C7F, + // 'Cyrillic Extended-C': (char) => char >= 0x1C80 && char <= 0x1C8F, + // 'Georgian Extended': (char) => char >= 0x1C90 && char <= 0x1CBF, + // 'Sundanese Supplement': (char) => char >= 0x1CC0 && char <= 0x1CCF, + // 'Vedic Extensions': (char) => char >= 0x1CD0 && char <= 0x1CFF, + // 'Phonetic Extensions': (char) => char >= 0x1D00 && char <= 0x1D7F, + // 'Phonetic Extensions Supplement': (char) => char >= 0x1D80 && char <= 0x1DBF, + // 'Combining Diacritical Marks Supplement': (char) => char >= 0x1DC0 && char <= 0x1DFF, + // 'Latin Extended Additional': (char) => char >= 0x1E00 && char <= 0x1EFF, + // 'Greek Extended': (char) => char >= 0x1F00 && char <= 0x1FFF, + 'General Punctuation': (char) => char >= 0x2000 && char <= 0x206F, + // 'Superscripts and Subscripts': (char) => char >= 0x2070 && char <= 0x209F, + // 'Currency Symbols': (char) => char >= 0x20A0 && char <= 0x20CF, + // 'Combining Diacritical Marks for Symbols': (char) => char >= 0x20D0 && char <= 0x20FF, + 'Letterlike Symbols': (char) => char >= 0x2100 && char <= 0x214F, + 'Number Forms': (char) => char >= 0x2150 && char <= 0x218F, + // 'Arrows': (char) => char >= 0x2190 && char <= 0x21FF, + // 'Mathematical Operators': (char) => char >= 0x2200 && char <= 0x22FF, + 'Miscellaneous Technical': (char) => char >= 0x2300 && char <= 0x23FF, + 'Control Pictures': (char) => char >= 0x2400 && char <= 0x243F, + 'Optical Character Recognition': (char) => char >= 0x2440 && char <= 0x245F, + 'Enclosed Alphanumerics': (char) => char >= 0x2460 && char <= 0x24FF, + // 'Box Drawing': (char) => char >= 0x2500 && char <= 0x257F, + // 'Block Elements': (char) => char >= 0x2580 && char <= 0x259F, + 'Geometric Shapes': (char) => char >= 0x25A0 && char <= 0x25FF, + 'Miscellaneous Symbols': (char) => char >= 0x2600 && char <= 0x26FF, + // 'Dingbats': (char) => char >= 0x2700 && char <= 0x27BF, + // 'Miscellaneous Mathematical Symbols-A': (char) => char >= 0x27C0 && char <= 0x27EF, + // 'Supplemental Arrows-A': (char) => char >= 0x27F0 && char <= 0x27FF, + // 'Braille Patterns': (char) => char >= 0x2800 && char <= 0x28FF, + // 'Supplemental Arrows-B': (char) => char >= 0x2900 && char <= 0x297F, + // 'Miscellaneous Mathematical Symbols-B': (char) => char >= 0x2980 && char <= 0x29FF, + // 'Supplemental Mathematical Operators': (char) => char >= 0x2A00 && char <= 0x2AFF, + 'Miscellaneous Symbols and Arrows': (char) => char >= 0x2B00 && char <= 0x2BFF, + // 'Glagolitic': (char) => char >= 0x2C00 && char <= 0x2C5F, + // 'Latin Extended-C': (char) => char >= 0x2C60 && char <= 0x2C7F, + // 'Coptic': (char) => char >= 0x2C80 && char <= 0x2CFF, + // 'Georgian Supplement': (char) => char >= 0x2D00 && char <= 0x2D2F, + // 'Tifinagh': (char) => char >= 0x2D30 && char <= 0x2D7F, + // 'Ethiopic Extended': (char) => char >= 0x2D80 && char <= 0x2DDF, + // 'Cyrillic Extended-A': (char) => char >= 0x2DE0 && char <= 0x2DFF, + // 'Supplemental Punctuation': (char) => char >= 0x2E00 && char <= 0x2E7F, + // 'CJK Radicals Supplement': (char) => char >= 0x2E80 && char <= 0x2EFF, + // 'Kangxi Radicals': (char) => char >= 0x2F00 && char <= 0x2FDF, + 'Ideographic Description Characters': (char) => char >= 0x2FF0 && char <= 0x2FFF, + 'CJK Symbols and Punctuation': (char) => char >= 0x3000 && char <= 0x303F, + // 'Hiragana': (char) => char >= 0x3040 && char <= 0x309F, + 'Katakana': (char) => char >= 0x30A0 && char <= 0x30FF, + // 'Bopomofo': (char) => char >= 0x3100 && char <= 0x312F, + // 'Hangul Compatibility Jamo': (char) => char >= 0x3130 && char <= 0x318F, + 'Kanbun': (char) => char >= 0x3190 && char <= 0x319F, + // 'Bopomofo Extended': (char) => char >= 0x31A0 && char <= 0x31BF, + 'CJK Strokes': (char) => char >= 0x31C0 && char <= 0x31EF, + // 'Katakana Phonetic Extensions': (char) => char >= 0x31F0 && char <= 0x31FF, + 'Enclosed CJK Letters and Months': (char) => char >= 0x3200 && char <= 0x32FF, + 'CJK Compatibility': (char) => char >= 0x3300 && char <= 0x33FF, + // 'CJK Unified Ideographs Extension A': (char) => char >= 0x3400 && char <= 0x4DBF, + 'Yijing Hexagram Symbols': (char) => char >= 0x4DC0 && char <= 0x4DFF, + // 'CJK Unified Ideographs': (char) => char >= 0x4E00 && char <= 0x9FFF, + // 'Yi Syllables': (char) => char >= 0xA000 && char <= 0xA48F, + // 'Yi Radicals': (char) => char >= 0xA490 && char <= 0xA4CF, + // 'Lisu': (char) => char >= 0xA4D0 && char <= 0xA4FF, + // 'Vai': (char) => char >= 0xA500 && char <= 0xA63F, + // 'Cyrillic Extended-B': (char) => char >= 0xA640 && char <= 0xA69F, + // 'Bamum': (char) => char >= 0xA6A0 && char <= 0xA6FF, + // 'Modifier Tone Letters': (char) => char >= 0xA700 && char <= 0xA71F, + // 'Latin Extended-D': (char) => char >= 0xA720 && char <= 0xA7FF, + // 'Syloti Nagri': (char) => char >= 0xA800 && char <= 0xA82F, + // 'Common Indic Number Forms': (char) => char >= 0xA830 && char <= 0xA83F, + // 'Phags-pa': (char) => char >= 0xA840 && char <= 0xA87F, + // 'Saurashtra': (char) => char >= 0xA880 && char <= 0xA8DF, + // 'Devanagari Extended': (char) => char >= 0xA8E0 && char <= 0xA8FF, + // 'Kayah Li': (char) => char >= 0xA900 && char <= 0xA92F, + // 'Rejang': (char) => char >= 0xA930 && char <= 0xA95F, + // 'Hangul Jamo Extended-A': (char) => char >= 0xA960 && char <= 0xA97F, + // 'Javanese': (char) => char >= 0xA980 && char <= 0xA9DF, + // 'Myanmar Extended-B': (char) => char >= 0xA9E0 && char <= 0xA9FF, + // 'Cham': (char) => char >= 0xAA00 && char <= 0xAA5F, + // 'Myanmar Extended-A': (char) => char >= 0xAA60 && char <= 0xAA7F, + // 'Tai Viet': (char) => char >= 0xAA80 && char <= 0xAADF, + // 'Meetei Mayek Extensions': (char) => char >= 0xAAE0 && char <= 0xAAFF, + // 'Ethiopic Extended-A': (char) => char >= 0xAB00 && char <= 0xAB2F, + // 'Latin Extended-E': (char) => char >= 0xAB30 && char <= 0xAB6F, + // 'Cherokee Supplement': (char) => char >= 0xAB70 && char <= 0xABBF, + // 'Meetei Mayek': (char) => char >= 0xABC0 && char <= 0xABFF, + // 'Hangul Syllables': (char) => char >= 0xAC00 && char <= 0xD7AF, + // 'Hangul Jamo Extended-B': (char) => char >= 0xD7B0 && char <= 0xD7FF, + // 'High Surrogates': (char) => char >= 0xD800 && char <= 0xDB7F, + // 'High Private Use Surrogates': (char) => char >= 0xDB80 && char <= 0xDBFF, + // 'Low Surrogates': (char) => char >= 0xDC00 && char <= 0xDFFF, + 'Private Use Area': (char) => char >= 0xE000 && char <= 0xF8FF, + // 'CJK Compatibility Ideographs': (char) => char >= 0xF900 && char <= 0xFAFF, + // 'Alphabetic Presentation Forms': (char) => char >= 0xFB00 && char <= 0xFB4F, + // 'Arabic Presentation Forms-A': (char) => char >= 0xFB50 && char <= 0xFDFF, + // 'Variation Selectors': (char) => char >= 0xFE00 && char <= 0xFE0F, + 'Vertical Forms': (char) => char >= 0xFE10 && char <= 0xFE1F, + // 'Combining Half Marks': (char) => char >= 0xFE20 && char <= 0xFE2F, + 'CJK Compatibility Forms': (char) => char >= 0xFE30 && char <= 0xFE4F, + 'Small Form Variants': (char) => char >= 0xFE50 && char <= 0xFE6F, + // 'Arabic Presentation Forms-B': (char) => char >= 0xFE70 && char <= 0xFEFF, + 'Halfwidth and Fullwidth Forms': (char) => char >= 0xFF00 && char <= 0xFFEF + // 'Specials': (char) => char >= 0xFFF0 && char <= 0xFFFF, + // 'Linear B Syllabary': (char) => char >= 0x10000 && char <= 0x1007F, + // 'Linear B Ideograms': (char) => char >= 0x10080 && char <= 0x100FF, + // 'Aegean Numbers': (char) => char >= 0x10100 && char <= 0x1013F, + // 'Ancient Greek Numbers': (char) => char >= 0x10140 && char <= 0x1018F, + // 'Ancient Symbols': (char) => char >= 0x10190 && char <= 0x101CF, + // 'Phaistos Disc': (char) => char >= 0x101D0 && char <= 0x101FF, + // 'Lycian': (char) => char >= 0x10280 && char <= 0x1029F, + // 'Carian': (char) => char >= 0x102A0 && char <= 0x102DF, + // 'Coptic Epact Numbers': (char) => char >= 0x102E0 && char <= 0x102FF, + // 'Old Italic': (char) => char >= 0x10300 && char <= 0x1032F, + // 'Gothic': (char) => char >= 0x10330 && char <= 0x1034F, + // 'Old Permic': (char) => char >= 0x10350 && char <= 0x1037F, + // 'Ugaritic': (char) => char >= 0x10380 && char <= 0x1039F, + // 'Old Persian': (char) => char >= 0x103A0 && char <= 0x103DF, + // 'Deseret': (char) => char >= 0x10400 && char <= 0x1044F, + // 'Shavian': (char) => char >= 0x10450 && char <= 0x1047F, + // 'Osmanya': (char) => char >= 0x10480 && char <= 0x104AF, + // 'Osage': (char) => char >= 0x104B0 && char <= 0x104FF, + // 'Elbasan': (char) => char >= 0x10500 && char <= 0x1052F, + // 'Caucasian Albanian': (char) => char >= 0x10530 && char <= 0x1056F, + // 'Vithkuqi': (char) => char >= 0x10570 && char <= 0x105BF, + // 'Todhri': (char) => char >= 0x105C0 && char <= 0x105FF, + // 'Linear A': (char) => char >= 0x10600 && char <= 0x1077F, + // 'Latin Extended-F': (char) => char >= 0x10780 && char <= 0x107BF, + // 'Cypriot Syllabary': (char) => char >= 0x10800 && char <= 0x1083F, + // 'Imperial Aramaic': (char) => char >= 0x10840 && char <= 0x1085F, + // 'Palmyrene': (char) => char >= 0x10860 && char <= 0x1087F, + // 'Nabataean': (char) => char >= 0x10880 && char <= 0x108AF, + // 'Hatran': (char) => char >= 0x108E0 && char <= 0x108FF, + // 'Phoenician': (char) => char >= 0x10900 && char <= 0x1091F, + // 'Lydian': (char) => char >= 0x10920 && char <= 0x1093F, + // 'Meroitic Hieroglyphs': (char) => char >= 0x10980 && char <= 0x1099F, + // 'Meroitic Cursive': (char) => char >= 0x109A0 && char <= 0x109FF, + // 'Kharoshthi': (char) => char >= 0x10A00 && char <= 0x10A5F, + // 'Old South Arabian': (char) => char >= 0x10A60 && char <= 0x10A7F, + // 'Old North Arabian': (char) => char >= 0x10A80 && char <= 0x10A9F, + // 'Manichaean': (char) => char >= 0x10AC0 && char <= 0x10AFF, + // 'Avestan': (char) => char >= 0x10B00 && char <= 0x10B3F, + // 'Inscriptional Parthian': (char) => char >= 0x10B40 && char <= 0x10B5F, + // 'Inscriptional Pahlavi': (char) => char >= 0x10B60 && char <= 0x10B7F, + // 'Psalter Pahlavi': (char) => char >= 0x10B80 && char <= 0x10BAF, + // 'Old Turkic': (char) => char >= 0x10C00 && char <= 0x10C4F, + // 'Old Hungarian': (char) => char >= 0x10C80 && char <= 0x10CFF, + // 'Hanifi Rohingya': (char) => char >= 0x10D00 && char <= 0x10D3F, + // 'Garay': (char) => char >= 0x10D40 && char <= 0x10D8F, + // 'Rumi Numeral Symbols': (char) => char >= 0x10E60 && char <= 0x10E7F, + // 'Yezidi': (char) => char >= 0x10E80 && char <= 0x10EBF, + // 'Arabic Extended-C': (char) => char >= 0x10EC0 && char <= 0x10EFF, + // 'Old Sogdian': (char) => char >= 0x10F00 && char <= 0x10F2F, + // 'Sogdian': (char) => char >= 0x10F30 && char <= 0x10F6F, + // 'Old Uyghur': (char) => char >= 0x10F70 && char <= 0x10FAF, + // 'Chorasmian': (char) => char >= 0x10FB0 && char <= 0x10FDF, + // 'Elymaic': (char) => char >= 0x10FE0 && char <= 0x10FFF, + // 'Brahmi': (char) => char >= 0x11000 && char <= 0x1107F, + // 'Kaithi': (char) => char >= 0x11080 && char <= 0x110CF, + // 'Sora Sompeng': (char) => char >= 0x110D0 && char <= 0x110FF, + // 'Chakma': (char) => char >= 0x11100 && char <= 0x1114F, + // 'Mahajani': (char) => char >= 0x11150 && char <= 0x1117F, + // 'Sharada': (char) => char >= 0x11180 && char <= 0x111DF, + // 'Sinhala Archaic Numbers': (char) => char >= 0x111E0 && char <= 0x111FF, + // 'Khojki': (char) => char >= 0x11200 && char <= 0x1124F, + // 'Multani': (char) => char >= 0x11280 && char <= 0x112AF, + // 'Khudawadi': (char) => char >= 0x112B0 && char <= 0x112FF, + // 'Grantha': (char) => char >= 0x11300 && char <= 0x1137F, + // 'Tulu-Tigalari': (char) => char >= 0x11380 && char <= 0x113FF, + // 'Newa': (char) => char >= 0x11400 && char <= 0x1147F, + // 'Tirhuta': (char) => char >= 0x11480 && char <= 0x114DF, + // 'Siddham': (char) => char >= 0x11580 && char <= 0x115FF, + // 'Modi': (char) => char >= 0x11600 && char <= 0x1165F, + // 'Mongolian Supplement': (char) => char >= 0x11660 && char <= 0x1167F, + // 'Takri': (char) => char >= 0x11680 && char <= 0x116CF, + // 'Myanmar Extended-C': (char) => char >= 0x116D0 && char <= 0x116FF, + // 'Ahom': (char) => char >= 0x11700 && char <= 0x1174F, + // 'Dogra': (char) => char >= 0x11800 && char <= 0x1184F, + // 'Warang Citi': (char) => char >= 0x118A0 && char <= 0x118FF, + // 'Dives Akuru': (char) => char >= 0x11900 && char <= 0x1195F, + // 'Nandinagari': (char) => char >= 0x119A0 && char <= 0x119FF, + // 'Zanabazar Square': (char) => char >= 0x11A00 && char <= 0x11A4F, + // 'Soyombo': (char) => char >= 0x11A50 && char <= 0x11AAF, + // 'Unified Canadian Aboriginal Syllabics Extended-A': (char) => char >= 0x11AB0 && char <= 0x11ABF, + // 'Pau Cin Hau': (char) => char >= 0x11AC0 && char <= 0x11AFF, + // 'Devanagari Extended-A': (char) => char >= 0x11B00 && char <= 0x11B5F, + // 'Sunuwar': (char) => char >= 0x11BC0 && char <= 0x11BFF, + // 'Bhaiksuki': (char) => char >= 0x11C00 && char <= 0x11C6F, + // 'Marchen': (char) => char >= 0x11C70 && char <= 0x11CBF, + // 'Masaram Gondi': (char) => char >= 0x11D00 && char <= 0x11D5F, + // 'Gunjala Gondi': (char) => char >= 0x11D60 && char <= 0x11DAF, + // 'Makasar': (char) => char >= 0x11EE0 && char <= 0x11EFF, + // 'Kawi': (char) => char >= 0x11F00 && char <= 0x11F5F, + // 'Lisu Supplement': (char) => char >= 0x11FB0 && char <= 0x11FBF, + // 'Tamil Supplement': (char) => char >= 0x11FC0 && char <= 0x11FFF, + // 'Cuneiform': (char) => char >= 0x12000 && char <= 0x123FF, + // 'Cuneiform Numbers and Punctuation': (char) => char >= 0x12400 && char <= 0x1247F, + // 'Early Dynastic Cuneiform': (char) => char >= 0x12480 && char <= 0x1254F, + // 'Cypro-Minoan': (char) => char >= 0x12F90 && char <= 0x12FFF, + // 'Egyptian Hieroglyphs': (char) => char >= 0x13000 && char <= 0x1342F, + // 'Egyptian Hieroglyph Format Controls': (char) => char >= 0x13430 && char <= 0x1345F, + // 'Egyptian Hieroglyphs Extended-A': (char) => char >= 0x13460 && char <= 0x143FF, + // 'Anatolian Hieroglyphs': (char) => char >= 0x14400 && char <= 0x1467F, + // 'Gurung Khema': (char) => char >= 0x16100 && char <= 0x1613F, + // 'Bamum Supplement': (char) => char >= 0x16800 && char <= 0x16A3F, + // 'Mro': (char) => char >= 0x16A40 && char <= 0x16A6F, + // 'Tangsa': (char) => char >= 0x16A70 && char <= 0x16ACF, + // 'Bassa Vah': (char) => char >= 0x16AD0 && char <= 0x16AFF, + // 'Pahawh Hmong': (char) => char >= 0x16B00 && char <= 0x16B8F, + // 'Kirat Rai': (char) => char >= 0x16D40 && char <= 0x16D7F, + // 'Medefaidrin': (char) => char >= 0x16E40 && char <= 0x16E9F, + // 'Miao': (char) => char >= 0x16F00 && char <= 0x16F9F, + // 'Ideographic Symbols and Punctuation': (char) => char >= 0x16FE0 && char <= 0x16FFF, + // 'Tangut': (char) => char >= 0x17000 && char <= 0x187FF, + // 'Tangut Components': (char) => char >= 0x18800 && char <= 0x18AFF, + // 'Khitan Small Script': (char) => char >= 0x18B00 && char <= 0x18CFF, + // 'Tangut Supplement': (char) => char >= 0x18D00 && char <= 0x18D7F, + // 'Kana Extended-B': (char) => char >= 0x1AFF0 && char <= 0x1AFFF, + // 'Kana Supplement': (char) => char >= 0x1B000 && char <= 0x1B0FF, + // 'Kana Extended-A': (char) => char >= 0x1B100 && char <= 0x1B12F, + // 'Small Kana Extension': (char) => char >= 0x1B130 && char <= 0x1B16F, + // 'Nushu': (char) => char >= 0x1B170 && char <= 0x1B2FF, + // 'Duployan': (char) => char >= 0x1BC00 && char <= 0x1BC9F, + // 'Shorthand Format Controls': (char) => char >= 0x1BCA0 && char <= 0x1BCAF, + // 'Symbols for Legacy Computing Supplement': (char) => char >= 0x1CC00 && char <= 0x1CEBF, + // 'Znamenny Musical Notation': (char) => char >= 0x1CF00 && char <= 0x1CFCF, + // 'Byzantine Musical Symbols': (char) => char >= 0x1D000 && char <= 0x1D0FF, + // 'Musical Symbols': (char) => char >= 0x1D100 && char <= 0x1D1FF, + // 'Ancient Greek Musical Notation': (char) => char >= 0x1D200 && char <= 0x1D24F, + // 'Kaktovik Numerals': (char) => char >= 0x1D2C0 && char <= 0x1D2DF, + // 'Mayan Numerals': (char) => char >= 0x1D2E0 && char <= 0x1D2FF, + // 'Tai Xuan Jing Symbols': (char) => char >= 0x1D300 && char <= 0x1D35F, + // 'Counting Rod Numerals': (char) => char >= 0x1D360 && char <= 0x1D37F, + // 'Mathematical Alphanumeric Symbols': (char) => char >= 0x1D400 && char <= 0x1D7FF, + // 'Sutton SignWriting': (char) => char >= 0x1D800 && char <= 0x1DAAF, + // 'Latin Extended-G': (char) => char >= 0x1DF00 && char <= 0x1DFFF, + // 'Glagolitic Supplement': (char) => char >= 0x1E000 && char <= 0x1E02F, + // 'Cyrillic Extended-D': (char) => char >= 0x1E030 && char <= 0x1E08F, + // 'Nyiakeng Puachue Hmong': (char) => char >= 0x1E100 && char <= 0x1E14F, + // 'Toto': (char) => char >= 0x1E290 && char <= 0x1E2BF, + // 'Wancho': (char) => char >= 0x1E2C0 && char <= 0x1E2FF, + // 'Nag Mundari': (char) => char >= 0x1E4D0 && char <= 0x1E4FF, + // 'Ol Onal': (char) => char >= 0x1E5D0 && char <= 0x1E5FF, + // 'Ethiopic Extended-B': (char) => char >= 0x1E7E0 && char <= 0x1E7FF, + // 'Mende Kikakui': (char) => char >= 0x1E800 && char <= 0x1E8DF, + // 'Adlam': (char) => char >= 0x1E900 && char <= 0x1E95F, + // 'Indic Siyaq Numbers': (char) => char >= 0x1EC70 && char <= 0x1ECBF, + // 'Ottoman Siyaq Numbers': (char) => char >= 0x1ED00 && char <= 0x1ED4F, + // 'Arabic Mathematical Alphabetic Symbols': (char) => char >= 0x1EE00 && char <= 0x1EEFF, + // 'Mahjong Tiles': (char) => char >= 0x1F000 && char <= 0x1F02F, + // 'Domino Tiles': (char) => char >= 0x1F030 && char <= 0x1F09F, + // 'Playing Cards': (char) => char >= 0x1F0A0 && char <= 0x1F0FF, + // 'Enclosed Alphanumeric Supplement': (char) => char >= 0x1F100 && char <= 0x1F1FF, + // 'Enclosed Ideographic Supplement': (char) => char >= 0x1F200 && char <= 0x1F2FF, + // 'Miscellaneous Symbols and Pictographs': (char) => char >= 0x1F300 && char <= 0x1F5FF, + // 'Emoticons': (char) => char >= 0x1F600 && char <= 0x1F64F, + // 'Ornamental Dingbats': (char) => char >= 0x1F650 && char <= 0x1F67F, + // 'Transport and Map Symbols': (char) => char >= 0x1F680 && char <= 0x1F6FF, + // 'Alchemical Symbols': (char) => char >= 0x1F700 && char <= 0x1F77F, + // 'Geometric Shapes Extended': (char) => char >= 0x1F780 && char <= 0x1F7FF, + // 'Supplemental Arrows-C': (char) => char >= 0x1F800 && char <= 0x1F8FF, + // 'Supplemental Symbols and Pictographs': (char) => char >= 0x1F900 && char <= 0x1F9FF, + // 'Chess Symbols': (char) => char >= 0x1FA00 && char <= 0x1FA6F, + // 'Symbols and Pictographs Extended-A': (char) => char >= 0x1FA70 && char <= 0x1FAFF, + // 'Symbols for Legacy Computing': (char) => char >= 0x1FB00 && char <= 0x1FBFF, + // 'CJK Unified Ideographs Extension B': (char) => char >= 0x20000 && char <= 0x2A6DF, + // 'CJK Unified Ideographs Extension C': (char) => char >= 0x2A700 && char <= 0x2B73F, + // 'CJK Unified Ideographs Extension D': (char) => char >= 0x2B740 && char <= 0x2B81F, + // 'CJK Unified Ideographs Extension E': (char) => char >= 0x2B820 && char <= 0x2CEAF, + // 'CJK Unified Ideographs Extension F': (char) => char >= 0x2CEB0 && char <= 0x2EBEF, + // 'CJK Unified Ideographs Extension I': (char) => char >= 0x2EBF0 && char <= 0x2EE5F, + // 'CJK Unified Ideographs Extension G': (char) => char >= 0x30000 && char <= 0x3134F, + // 'CJK Unified Ideographs Extension H': (char) => char >= 0x31350 && char <= 0x323AF, + // 'CJK Compatibility Ideographs Supplement': (char) => char >= 0x2F800 && char <= 0x2FA1F, + // 'Tags': (char) => char >= 0xE0000 && char <= 0xE007F, + // 'Variation Selectors Supplement': (char) => char >= 0xE0100 && char <= 0xE01EF, + // 'Supplementary Private Use Area-A': (char) => char >= 0xF0000 && char <= 0xFFFFF, + // 'Supplementary Private Use Area-B': (char) => char >= 0x100000 && char <= 0x10FFFF, +}; + +/* eslint-disable new-cap */ +function allowsIdeographicBreaking(chars) { + for (const char of chars) { + if (!charAllowsIdeographicBreaking(char.charCodeAt(0))) + return false; + } + return true; +} +function allowsVerticalWritingMode(chars) { + for (const char of chars) { + if (charHasUprightVerticalOrientation(char.charCodeAt(0))) + return true; + } + return false; +} +function allowsLetterSpacing(chars) { + for (const char of chars) { + if (!charAllowsLetterSpacing(char.charCodeAt(0))) + return false; + } + return true; +} +/** + * Returns a regular expression matching the given script codes, excluding any + * code that the execution environment lacks support for in regular expressions. + */ +function sanitizedRegExpFromScriptCodes(scriptCodes) { + const supportedPropertyEscapes = scriptCodes.map(code => { + try { + return new RegExp(`\\p{sc=${code}}`, 'u').source; + } + catch (e) { + return null; + } + }).filter(pe => pe); + return new RegExp(supportedPropertyEscapes.join('|'), 'u'); +} +/** + * ISO 15924 script codes of scripts that disallow letter spacing as of Unicode + * 16.0.0. + * + * In general, cursive scripts are incompatible with letter spacing. + */ +const cursiveScriptCodes = [ + 'Arab', // Arabic + 'Dupl', // Duployan + 'Mong', // Mongolian + 'Ougr', // Old Uyghur + 'Syrc', // Syriac +]; +const cursiveScriptRegExp = sanitizedRegExpFromScriptCodes(cursiveScriptCodes); +function charAllowsLetterSpacing(char) { + return !cursiveScriptRegExp.test(String.fromCodePoint(char)); +} +/** + * ISO 15924 script codes of scripts that allow ideographic line breaking beyond + * the CJKV scripts that are considered ideographic in Unicode 16.0.0. + */ +const ideographicBreakingScriptCodes = [ + 'Bopo', // Bopomofo + 'Hani', // Han + 'Hira', // Hiragana + 'Kana', // Katakana + 'Kits', // Khitan Small Script + 'Nshu', // Nushu + 'Tang', // Tangut + 'Yiii', // Yi +]; +const ideographicBreakingRegExp = sanitizedRegExpFromScriptCodes(ideographicBreakingScriptCodes); +function charAllowsIdeographicBreaking(char) { + // Return early for characters outside all ideographic ranges. + if (char < 0x2E80) + return false; + if (unicodeBlockLookup['CJK Compatibility Forms'](char)) + return true; + if (unicodeBlockLookup['CJK Compatibility'](char)) + return true; + if (unicodeBlockLookup['CJK Strokes'](char)) + return true; + if (unicodeBlockLookup['CJK Symbols and Punctuation'](char)) + return true; + if (unicodeBlockLookup['Enclosed CJK Letters and Months'](char)) + return true; + if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) + return true; + if (unicodeBlockLookup['Ideographic Description Characters'](char)) + return true; + if (unicodeBlockLookup['Vertical Forms'](char)) + return true; + return ideographicBreakingRegExp.test(String.fromCodePoint(char)); +} +// The following logic comes from +// . +// Keep it synchronized with +// . +// The data file denotes with “U” or “Tu” any codepoint that may be drawn +// upright in vertical text but does not distinguish between upright and +// “neutral” characters. +// Blocks in the Unicode supplementary planes are excluded from this module due +// to . +/** + * Returns true if the given Unicode codepoint identifies a character with + * upright orientation. + * + * A character has upright orientation if it is drawn upright (unrotated) + * whether the line is oriented horizontally or vertically, even if both + * adjacent characters can be rotated. For example, a Chinese character is + * always drawn upright. An uprightly oriented character causes an adjacent + * “neutral” character to be drawn upright as well. + */ +function charHasUprightVerticalOrientation(char) { + if (char === 0x02EA /* modifier letter yin departing tone mark */ || + char === 0x02EB /* modifier letter yang departing tone mark */) { + return true; + } + // Return early for characters outside all ranges whose characters remain + // upright in vertical writing mode. + if (char < 0x1100) + return false; + if (unicodeBlockLookup['CJK Compatibility Forms'](char)) { + if (!((char >= 0xFE49 /* dashed overline */ && char <= 0xFE4F) /* wavy low line */)) { + return true; + } + } + if (unicodeBlockLookup['CJK Compatibility'](char)) + return true; + if (unicodeBlockLookup['CJK Strokes'](char)) + return true; + if (unicodeBlockLookup['CJK Symbols and Punctuation'](char)) { + if (!((char >= 0x3008 /* left angle bracket */ && char <= 0x3011) /* right black lenticular bracket */) && + !((char >= 0x3014 /* left tortoise shell bracket */ && char <= 0x301F) /* low double prime quotation mark */) && + char !== 0x3030 /* wavy dash */) { + return true; + } + } + if (unicodeBlockLookup['Enclosed CJK Letters and Months'](char)) + return true; + if (unicodeBlockLookup['Ideographic Description Characters'](char)) + return true; + if (unicodeBlockLookup['Kanbun'](char)) + return true; + if (unicodeBlockLookup['Katakana'](char)) { + if (char !== 0x30FC /* katakana-hiragana prolonged sound mark */) { + return true; + } + } + if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) { + if (char !== 0xFF08 /* fullwidth left parenthesis */ && + char !== 0xFF09 /* fullwidth right parenthesis */ && + char !== 0xFF0D /* fullwidth hyphen-minus */ && + !((char >= 0xFF1A /* fullwidth colon */ && char <= 0xFF1E) /* fullwidth greater-than sign */) && + char !== 0xFF3B /* fullwidth left square bracket */ && + char !== 0xFF3D /* fullwidth right square bracket */ && + char !== 0xFF3F /* fullwidth low line */ && + !(char >= 0xFF5B /* fullwidth left curly bracket */ && char <= 0xFFDF) && + char !== 0xFFE3 /* fullwidth macron */ && + !(char >= 0xFFE8 /* halfwidth forms light vertical */ && char <= 0xFFEF)) { + return true; + } + } + if (unicodeBlockLookup['Small Form Variants'](char)) { + if (!((char >= 0xFE58 /* small em dash */ && char <= 0xFE5E) /* small right tortoise shell bracket */) && + !((char >= 0xFE63 /* small hyphen-minus */ && char <= 0xFE66) /* small equals sign */)) { + return true; + } + } + if (unicodeBlockLookup['Vertical Forms'](char)) + return true; + if (unicodeBlockLookup['Yijing Hexagram Symbols'](char)) + return true; + if ( /* Canadian Aboriginal *//\p{sc=Cans}/u.test(String.fromCodePoint(char))) + return true; + if ( /* Hangul *//\p{sc=Hang}/u.test(String.fromCodePoint(char))) + return true; + if (ideographicBreakingRegExp.test(String.fromCodePoint(char))) + return true; + return false; +} +/** + * Returns true if the given Unicode codepoint identifies a character with + * neutral orientation. + * + * A character has neutral orientation if it may be drawn rotated or unrotated + * when the line is oriented vertically, depending on the orientation of the + * adjacent characters. For example, along a vertically oriented line, the vulgar + * fraction ½ is drawn upright among Chinese characters but rotated among Latin + * letters. A neutrally oriented character does not influence whether an + * adjacent character is drawn upright or rotated. + */ +function charHasNeutralVerticalOrientation(char) { + if (unicodeBlockLookup['Latin-1 Supplement'](char)) { + if (char === 0x00A7 /* section sign */ || + char === 0x00A9 /* copyright sign */ || + char === 0x00AE /* registered sign */ || + char === 0x00B1 /* plus-minus sign */ || + char === 0x00BC /* vulgar fraction one quarter */ || + char === 0x00BD /* vulgar fraction one half */ || + char === 0x00BE /* vulgar fraction three quarters */ || + char === 0x00D7 /* multiplication sign */ || + char === 0x00F7 /* division sign */) { + return true; + } + } + if (unicodeBlockLookup['General Punctuation'](char)) { + if (char === 0x2016 /* double vertical line */ || + char === 0x2020 /* dagger */ || + char === 0x2021 /* double dagger */ || + char === 0x2030 /* per mille sign */ || + char === 0x2031 /* per ten thousand sign */ || + char === 0x203B /* reference mark */ || + char === 0x203C /* double exclamation mark */ || + char === 0x2042 /* asterism */ || + char === 0x2047 /* double question mark */ || + char === 0x2048 /* question exclamation mark */ || + char === 0x2049 /* exclamation question mark */ || + char === 0x2051 /* two asterisks aligned vertically */) { + return true; + } + } + if (unicodeBlockLookup['Letterlike Symbols'](char)) + return true; + if (unicodeBlockLookup['Number Forms'](char)) + return true; + if (unicodeBlockLookup['Miscellaneous Technical'](char)) { + if ((char >= 0x2300 /* diameter sign */ && char <= 0x2307 /* wavy line */) || + (char >= 0x230C /* bottom right crop */ && char <= 0x231F /* bottom right corner */) || + (char >= 0x2324 /* up arrowhead between two horizontal bars */ && char <= 0x2328 /* keyboard */) || + char === 0x232B /* erase to the left */ || + (char >= 0x237D /* shouldered open box */ && char <= 0x239A /* clear screen symbol */) || + (char >= 0x23BE /* dentistry symbol light vertical and top right */ && char <= 0x23CD /* square foot */) || + char === 0x23CF /* eject symbol */ || + (char >= 0x23D1 /* metrical breve */ && char <= 0x23DB /* fuse */) || + (char >= 0x23E2 /* white trapezium */ && char <= 0x23FF)) { + return true; + } + } + if (unicodeBlockLookup['Control Pictures'](char) && char !== 0x2423 /* open box */) + return true; + if (unicodeBlockLookup['Optical Character Recognition'](char)) + return true; + if (unicodeBlockLookup['Enclosed Alphanumerics'](char)) + return true; + if (unicodeBlockLookup['Geometric Shapes'](char)) + return true; + if (unicodeBlockLookup['Miscellaneous Symbols'](char)) { + if (!((char >= 0x261A /* black left pointing index */ && char <= 0x261F) /* white down pointing index */)) { + return true; + } + } + if (unicodeBlockLookup['Miscellaneous Symbols and Arrows'](char)) { + if ((char >= 0x2B12 /* square with top half black */ && char <= 0x2B2F /* white vertical ellipse */) || + (char >= 0x2B50 /* white medium star */ && char <= 0x2B59 /* heavy circled saltire */) || + (char >= 0x2BB8 /* upwards white arrow from bar with horizontal bar */ && char <= 0x2BEB)) { + return true; + } + } + if (unicodeBlockLookup['CJK Symbols and Punctuation'](char)) + return true; + if (unicodeBlockLookup['Katakana'](char)) + return true; + if (unicodeBlockLookup['Private Use Area'](char)) + return true; + if (unicodeBlockLookup['CJK Compatibility Forms'](char)) + return true; + if (unicodeBlockLookup['Small Form Variants'](char)) + return true; + if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) + return true; + if (char === 0x221E /* infinity */ || + char === 0x2234 /* therefore */ || + char === 0x2235 /* because */ || + (char >= 0x2700 /* black safety scissors */ && char <= 0x2767 /* rotated floral heart bullet */) || + (char >= 0x2776 /* dingbat negative circled digit one */ && char <= 0x2793 /* dingbat negative circled sans-serif number ten */) || + char === 0xFFFC /* object replacement character */ || + char === 0xFFFD /* replacement character */) { + return true; + } + return false; +} +/** + * Returns true if the given Unicode codepoint identifies a character with + * rotated orientation. + * + * A character has rotated orientation if it is drawn rotated when the line is + * oriented vertically, even if both adjacent characters are upright. For + * example, a Latin letter is drawn rotated along a vertical line. A rotated + * character causes an adjacent “neutral” character to be drawn rotated as well. + */ +function charHasRotatedVerticalOrientation(char) { + return !(charHasUprightVerticalOrientation(char) || + charHasNeutralVerticalOrientation(char)); +} +function charInComplexShapingScript(char) { + return /\p{sc=Arab}/u.test(String.fromCodePoint(char)); +} +/** + * ISO 15924 script codes of scripts that are primarily written horizontally + * right-to-left according to Unicode 16.0.0. + */ +const rtlScriptCodes = [ + 'Adlm', // Adlam + 'Arab', // Arabic + 'Armi', // Imperial Aramaic + 'Avst', // Avestan + 'Chrs', // Chorasmian + 'Cprt', // Cypriot + 'Egyp', // Egyptian Hieroglyphs + 'Elym', // Elymaic + 'Gara', // Garay + 'Hatr', // Hatran + 'Hebr', // Hebrew + 'Hung', // Old Hungarian + 'Khar', // Kharoshthi + 'Lydi', // Lydian + 'Mand', // Mandaic + 'Mani', // Manichaean + 'Mend', // Mende Kikakui + 'Merc', // Meroitic Cursive + 'Mero', // Meroitic Hieroglyphs + 'Narb', // Old North Arabian + 'Nbat', // Nabataean + 'Nkoo', // NKo + 'Orkh', // Old Turkic + 'Palm', // Palmyrene + 'Phli', // Inscriptional Pahlavi + 'Phlp', // Psalter Pahlavi + 'Phnx', // Phoenician + 'Prti', // Inscriptional Parthian + 'Rohg', // Hanifi Rohingya + 'Samr', // Samaritan + 'Sarb', // Old South Arabian + 'Sogo', // Old Sogdian + 'Syrc', // Syriac + 'Thaa', // Thaana + 'Todr', // Todhri + 'Yezi', // Yezidi +]; +const rtlScriptRegExp = sanitizedRegExpFromScriptCodes(rtlScriptCodes); +function charInRTLScript(char) { + return rtlScriptRegExp.test(String.fromCodePoint(char)); +} +function charInSupportedScript(char, canRenderRTL) { + // This is a rough heuristic: whether we "can render" a script + // actually depends on the properties of the font being used + // and whether differences from the ideal rendering are considered + // semantically significant. + // Even in Latin script, we "can't render" combinations such as the fi + // ligature, but we don't consider that semantically significant. + if (!canRenderRTL && charInRTLScript(char)) { + return false; + } + if ((char >= 0x0900 && char <= 0x0DFF) || + // Main blocks for Indic scripts and Sinhala + (char >= 0x0F00 && char <= 0x109F) || + // Main blocks for Tibetan and Myanmar + unicodeBlockLookup['Khmer'](char)) { + // These blocks cover common scripts that require + // complex text shaping, based on unicode script metadata: + // https://www.unicode.org/repos/cldr/trunk/common/properties/scriptMetadata.txt + // where "Web Rank <= 32" "Shaping Required = YES" + return false; + } + return true; +} +function stringContainsRTLText(chars) { + for (const char of chars) { + if (charInRTLScript(char.charCodeAt(0))) { + return true; + } + } + return false; +} +function isStringInSupportedScript(chars, canRenderRTL) { + for (const char of chars) { + if (!charInSupportedScript(char.charCodeAt(0), canRenderRTL)) { + return false; + } + } + return true; +} + +class RTLWorkerPlugin { + constructor() { + this.applyArabicShaping = null; + this.processBidirectionalText = null; + this.processStyledBidirectionalText = null; + this.pluginStatus = 'unavailable'; + this.pluginURL = null; + } + setState(state) { + this.pluginStatus = state.pluginStatus; + this.pluginURL = state.pluginURL; + } + getState() { + return { + pluginStatus: this.pluginStatus, + pluginURL: this.pluginURL + }; + } + setMethods(rtlTextPlugin) { + this.applyArabicShaping = rtlTextPlugin.applyArabicShaping; + this.processBidirectionalText = rtlTextPlugin.processBidirectionalText; + this.processStyledBidirectionalText = rtlTextPlugin.processStyledBidirectionalText; + } + isParsed() { + return this.applyArabicShaping != null && + this.processBidirectionalText != null && + this.processStyledBidirectionalText != null; + } + getPluginURL() { + return this.pluginURL; + } + getRTLTextPluginStatus() { + return this.pluginStatus; + } +} +const rtlWorkerPlugin = new RTLWorkerPlugin(); + +/** + * @internal + * A parameter that can be evaluated to a value + */ +class EvaluationParameters { + // "options" may also be another EvaluationParameters to copy, see CrossFadedProperty.possiblyEvaluate + constructor(zoom, options) { + this.zoom = zoom; + if (options) { + this.now = options.now; + this.fadeDuration = options.fadeDuration; + this.zoomHistory = options.zoomHistory; + this.transition = options.transition; + } + else { + this.now = 0; + this.fadeDuration = 0; + this.zoomHistory = new ZoomHistory(); + this.transition = {}; + } + } + isSupportedScript(str) { + return isStringInSupportedScript(str, rtlWorkerPlugin.getRTLTextPluginStatus() === 'loaded'); + } + crossFadingFactor() { + if (this.fadeDuration === 0) { + return 1; + } + else { + return Math.min((this.now - this.zoomHistory.lastIntegerZoomTime) / this.fadeDuration, 1); + } + } + getCrossfadeParameters() { + const z = this.zoom; + const fraction = z - Math.floor(z); + const t = this.crossFadingFactor(); + return z > this.zoomHistory.lastIntegerZoom ? + { fromScale: 2, toScale: 1, t: fraction + (1 - fraction) * t } : + { fromScale: 0.5, toScale: 1, t: 1 - (1 - t) * fraction }; + } +} + +/** + * @internal + * `PropertyValue` represents the value part of a property key-value unit. It's used to represent both + * paint and layout property values, and regardless of whether or not their property supports data-driven + * expressions. + * + * `PropertyValue` stores the raw input value as seen in a style or a runtime styling API call, i.e. one of the + * following: + * + * * A constant value of the type appropriate for the property + * * A function which produces a value of that type (but functions are quasi-deprecated in favor of expressions) + * * An expression which produces a value of that type + * * "undefined"/"not present", in which case the property is assumed to take on its default value. + * + * In addition to storing the original input value, `PropertyValue` also stores a normalized representation, + * effectively treating functions as if they are expressions, and constant or default values as if they are + * (constant) expressions. + */ +class PropertyValue { + constructor(property, value) { + this.property = property; + this.value = value; + this.expression = normalizePropertyExpression(value === undefined ? property.specification.default : value, property.specification); + } + isDataDriven() { + return this.expression.kind === 'source' || this.expression.kind === 'composite'; + } + possiblyEvaluate(parameters, canonical, availableImages) { + return this.property.possiblyEvaluate(this, parameters, canonical, availableImages); + } +} +/** + * @internal + * Paint properties are _transitionable_: they can change in a fluid manner, interpolating or cross-fading between + * old and new value. The duration of the transition, and the delay before it begins, is configurable. + * + * `TransitionablePropertyValue` is a compositional class that stores both the property value and that transition + * configuration. + * + * A `TransitionablePropertyValue` can calculate the next step in the evaluation chain for paint property values: + * `TransitioningPropertyValue`. + */ +class TransitionablePropertyValue { + constructor(property) { + this.property = property; + this.value = new PropertyValue(property, undefined); + } + transitioned(parameters, prior) { + return new TransitioningPropertyValue(this.property, this.value, prior, extend({}, parameters.transition, this.transition), parameters.now); + } + untransitioned() { + return new TransitioningPropertyValue(this.property, this.value, null, {}, 0); + } +} +/** + * @internal + * `Transitionable` stores a map of all (property name, `TransitionablePropertyValue`) pairs for paint properties of a + * given layer type. It can calculate the `TransitioningPropertyValue`s for all of them at once, producing a + * `Transitioning` instance for the same set of properties. + */ +class Transitionable { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultTransitionablePropertyValues); + } + getValue(name) { + return clone$9(this._values[name].value.value); + } + setValue(name, value) { + if (!Object.prototype.hasOwnProperty.call(this._values, name)) { + this._values[name] = new TransitionablePropertyValue(this._values[name].property); + } + // Note that we do not _remove_ an own property in the case where a value is being reset + // to the default: the transition might still be non-default. + this._values[name].value = new PropertyValue(this._values[name].property, value === null ? undefined : clone$9(value)); + } + getTransition(name) { + return clone$9(this._values[name].transition); + } + setTransition(name, value) { + if (!Object.prototype.hasOwnProperty.call(this._values, name)) { + this._values[name] = new TransitionablePropertyValue(this._values[name].property); + } + this._values[name].transition = clone$9(value) || undefined; + } + serialize() { + const result = {}; + for (const property of Object.keys(this._values)) { + const value = this.getValue(property); + if (value !== undefined) { + result[property] = value; + } + const transition = this.getTransition(property); + if (transition !== undefined) { + result[`${property}-transition`] = transition; + } + } + return result; + } + transitioned(parameters, prior) { + const result = new Transitioning(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].transitioned(parameters, prior._values[property]); + } + return result; + } + untransitioned() { + const result = new Transitioning(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].untransitioned(); + } + return result; + } +} +/** + * @internal + * `TransitioningPropertyValue` implements the first of two intermediate steps in the evaluation chain of a paint + * property value. In this step, transitions between old and new values are handled: as long as the transition is in + * progress, `TransitioningPropertyValue` maintains a reference to the prior value, and interpolates between it and + * the new value based on the current time and the configured transition duration and delay. The product is the next + * step in the evaluation chain: the "possibly evaluated" result type `R`. See below for more on this concept. + */ +class TransitioningPropertyValue { + constructor(property, value, prior, transition, now) { + this.property = property; + this.value = value; + this.begin = now + transition.delay || 0; + this.end = this.begin + transition.duration || 0; + if (property.specification.transition && (transition.delay || transition.duration)) { + this.prior = prior; + } + } + possiblyEvaluate(parameters, canonical, availableImages) { + const now = parameters.now || 0; + const finalValue = this.value.possiblyEvaluate(parameters, canonical, availableImages); + const prior = this.prior; + if (!prior) { + // No prior value. + return finalValue; + } + else if (now > this.end) { + // Transition from prior value is now complete. + this.prior = null; + return finalValue; + } + else if (this.value.isDataDriven()) { + // Transitions to data-driven properties are not supported. + // We snap immediately to the data-driven value so that, when we perform layout, + // we see the data-driven function and can use it to populate vertex buffers. + this.prior = null; + return finalValue; + } + else if (now < this.begin) { + // Transition hasn't started yet. + return prior.possiblyEvaluate(parameters, canonical, availableImages); + } + else { + // Interpolate between recursively-calculated prior value and final. + const t = (now - this.begin) / (this.end - this.begin); + return this.property.interpolate(prior.possiblyEvaluate(parameters, canonical, availableImages), finalValue, easeCubicInOut(t)); + } + } +} +/** + * @internal + * `Transitioning` stores a map of all (property name, `TransitioningPropertyValue`) pairs for paint properties of a + * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a + * `PossiblyEvaluated` instance for the same set of properties. + */ +class Transitioning { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultTransitioningPropertyValues); + } + possiblyEvaluate(parameters, canonical, availableImages) { + const result = new PossiblyEvaluated(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages); + } + return result; + } + hasTransition() { + for (const property of Object.keys(this._values)) { + if (this._values[property].prior) { + return true; + } + } + return false; + } +} +// ------- Layout ------- +/** + * Because layout properties are not transitionable, they have a simpler representation and evaluation chain than + * paint properties: `PropertyValue`s are possibly evaluated, producing possibly evaluated values, which are then + * fully evaluated. + * + * `Layout` stores a map of all (property name, `PropertyValue`) pairs for layout properties of a + * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a + * `PossiblyEvaluated` instance for the same set of properties. + */ +class Layout { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultPropertyValues); + } + hasValue(name) { + return this._values[name].value !== undefined; + } + getValue(name) { + return clone$9(this._values[name].value); + } + setValue(name, value) { + this._values[name] = new PropertyValue(this._values[name].property, value === null ? undefined : clone$9(value)); + } + serialize() { + const result = {}; + for (const property of Object.keys(this._values)) { + const value = this.getValue(property); + if (value !== undefined) { + result[property] = value; + } + } + return result; + } + possiblyEvaluate(parameters, canonical, availableImages) { + const result = new PossiblyEvaluated(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages); + } + return result; + } +} +/** + * @internal + * `PossiblyEvaluatedPropertyValue` is used for data-driven paint and layout property values. It holds a + * `PossiblyEvaluatedValue` and the `GlobalProperties` that were used to generate it. You're not allowed to supply + * a different set of `GlobalProperties` when performing the final evaluation because they would be ignored in the + * case where the input value was a constant or camera function. + */ +class PossiblyEvaluatedPropertyValue { + constructor(property, value, parameters) { + this.property = property; + this.value = value; + this.parameters = parameters; + } + isConstant() { + return this.value.kind === 'constant'; + } + constantOr(value) { + if (this.value.kind === 'constant') { + return this.value.value; + } + else { + return value; + } + } + evaluate(feature, featureState, canonical, availableImages) { + return this.property.evaluate(this.value, this.parameters, feature, featureState, canonical, availableImages); + } +} +/** + * @internal + * `PossiblyEvaluated` stores a map of all (property name, `R`) pairs for paint or layout properties of a + * given layer type. + */ +class PossiblyEvaluated { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultPossiblyEvaluatedValues); + } + get(name) { + return this._values[name]; + } +} +/** + * @internal + * An implementation of `Property` for properties that do not permit data-driven (source or composite) expressions. + * This restriction allows us to declare statically that the result of possibly evaluating this kind of property + * is in fact always the scalar type `T`, and can be used without further evaluating the value on a per-feature basis. + */ +class DataConstantProperty { + constructor(specification) { + this.specification = specification; + } + possiblyEvaluate(value, parameters) { + if (value.isDataDriven()) + throw new Error('Value should not be data driven'); + return value.expression.evaluate(parameters); + } + interpolate(a, b, t) { + const interpolationType = this.specification.type; + const interpolationFn = interpolate[interpolationType]; + if (interpolationFn) { + return interpolationFn(a, b, t); + } + else { + return a; + } + } +} +/** + * @internal + * An implementation of `Property` for properties that permit data-driven (source or composite) expressions. + * The result of possibly evaluating this kind of property is `PossiblyEvaluatedPropertyValue`; obtaining + * a scalar value `T` requires further evaluation on a per-feature basis. + */ +class DataDrivenProperty { + constructor(specification, overrides) { + this.specification = specification; + this.overrides = overrides; + } + possiblyEvaluate(value, parameters, canonical, availableImages) { + if (value.expression.kind === 'constant' || value.expression.kind === 'camera') { + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: value.expression.evaluate(parameters, null, {}, canonical, availableImages) }, parameters); + } + else { + return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters); + } + } + interpolate(a, b, t) { + // If either possibly-evaluated value is non-constant, give up: we aren't able to interpolate data-driven values. + if (a.value.kind !== 'constant' || b.value.kind !== 'constant') { + return a; + } + // Special case hack solely for fill-outline-color. The undefined value is subsequently handled in + // FillStyleLayer#recalculate, which sets fill-outline-color to the fill-color value if the former + // is a PossiblyEvaluatedPropertyValue containing a constant undefined value. In addition to the + // return value here, the other source of a PossiblyEvaluatedPropertyValue containing a constant + // undefined value is the "default value" for fill-outline-color held in + // `Properties#defaultPossiblyEvaluatedValues`, which serves as the prototype of + // `PossiblyEvaluated#_values`. + if (a.value.value === undefined || b.value.value === undefined) { + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: undefined }, a.parameters); + } + const interpolationType = this.specification.type; + const interpolationFn = interpolate[interpolationType]; + if (interpolationFn) { + const interpolatedValue = interpolationFn(a.value.value, b.value.value, t); + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: interpolatedValue }, a.parameters); + } + else { + return a; + } + } + evaluate(value, parameters, feature, featureState, canonical, availableImages) { + if (value.kind === 'constant') { + return value.value; + } + else { + return value.evaluate(parameters, feature, featureState, canonical, availableImages); + } + } +} +/** + * @internal + * An implementation of `Property` for data driven `line-pattern` which are transitioned by cross-fading + * rather than interpolation. + */ +class CrossFadedDataDrivenProperty extends DataDrivenProperty { + possiblyEvaluate(value, parameters, canonical, availableImages) { + if (value.value === undefined) { + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: undefined }, parameters); + } + else if (value.expression.kind === 'constant') { + const evaluatedValue = value.expression.evaluate(parameters, null, {}, canonical, availableImages); + const isImageExpression = value.property.specification.type === 'resolvedImage'; + const constantValue = isImageExpression && typeof evaluatedValue !== 'string' ? evaluatedValue.name : evaluatedValue; + const constant = this._calculate(constantValue, constantValue, constantValue, parameters); + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: constant }, parameters); + } + else if (value.expression.kind === 'camera') { + const cameraVal = this._calculate(value.expression.evaluate({ zoom: parameters.zoom - 1.0 }), value.expression.evaluate({ zoom: parameters.zoom }), value.expression.evaluate({ zoom: parameters.zoom + 1.0 }), parameters); + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: cameraVal }, parameters); + } + else { + // source or composite expression + return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters); + } + } + evaluate(value, globals, feature, featureState, canonical, availableImages) { + if (value.kind === 'source') { + const constant = value.evaluate(globals, feature, featureState, canonical, availableImages); + return this._calculate(constant, constant, constant, globals); + } + else if (value.kind === 'composite') { + return this._calculate(value.evaluate({ zoom: Math.floor(globals.zoom) - 1.0 }, feature, featureState), value.evaluate({ zoom: Math.floor(globals.zoom) }, feature, featureState), value.evaluate({ zoom: Math.floor(globals.zoom) + 1.0 }, feature, featureState), globals); + } + else { + return value.value; + } + } + _calculate(min, mid, max, parameters) { + const z = parameters.zoom; + return z > parameters.zoomHistory.lastIntegerZoom ? { from: min, to: mid } : { from: max, to: mid }; + } + interpolate(a) { + return a; + } +} +/** + * @internal + * An implementation of `Property` for `*-pattern` and `line-dasharray`, which are transitioned by cross-fading + * rather than interpolation. + */ +class CrossFadedProperty { + constructor(specification) { + this.specification = specification; + } + possiblyEvaluate(value, parameters, canonical, availableImages) { + if (value.value === undefined) { + return undefined; + } + else if (value.expression.kind === 'constant') { + const constant = value.expression.evaluate(parameters, null, {}, canonical, availableImages); + return this._calculate(constant, constant, constant, parameters); + } + else { + return this._calculate(value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom - 1.0), parameters)), value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom), parameters)), value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom + 1.0), parameters)), parameters); + } + } + _calculate(min, mid, max, parameters) { + const z = parameters.zoom; + return z > parameters.zoomHistory.lastIntegerZoom ? { from: min, to: mid } : { from: max, to: mid }; + } + interpolate(a) { + return a; + } +} +/** + * @internal + * An implementation of `Property` for `heatmap-color` and `line-gradient`. Interpolation is a no-op, and + * evaluation returns a boolean value in order to indicate its presence, but the real + * evaluation happens in StyleLayer classes. + */ +class ColorRampProperty { + constructor(specification) { + this.specification = specification; + } + possiblyEvaluate(value, parameters, canonical, availableImages) { + return !!value.expression.evaluate(parameters, null, {}, canonical, availableImages); + } + interpolate() { return false; } +} +/** + * @internal + * `Properties` holds objects containing default values for the layout or paint property set of a given + * layer type. These objects are immutable, and they are used as the prototypes for the `_values` members of + * `Transitionable`, `Transitioning`, `Layout`, and `PossiblyEvaluated`. This allows these classes to avoid + * doing work in the common case where a property has no explicit value set and should be considered to take + * on the default value: using `for (const property of Object.keys(this._values))`, they can iterate over + * only the _own_ properties of `_values`, skipping repeated calculation of transitions and possible/final + * evaluations for defaults, the result of which will always be the same. + */ +class Properties { + constructor(properties) { + this.properties = properties; + this.defaultPropertyValues = {}; + this.defaultTransitionablePropertyValues = {}; + this.defaultTransitioningPropertyValues = {}; + this.defaultPossiblyEvaluatedValues = {}; + this.overridableProperties = []; + for (const property in properties) { + const prop = properties[property]; + if (prop.specification.overridable) { + this.overridableProperties.push(property); + } + const defaultPropertyValue = this.defaultPropertyValues[property] = + new PropertyValue(prop, undefined); + const defaultTransitionablePropertyValue = this.defaultTransitionablePropertyValues[property] = + new TransitionablePropertyValue(prop); + this.defaultTransitioningPropertyValues[property] = + defaultTransitionablePropertyValue.untransitioned(); + this.defaultPossiblyEvaluatedValues[property] = + defaultPropertyValue.possiblyEvaluate({}); + } + } +} +register('DataDrivenProperty', DataDrivenProperty); +register('DataConstantProperty', DataConstantProperty); +register('CrossFadedDataDrivenProperty', CrossFadedDataDrivenProperty); +register('CrossFadedProperty', CrossFadedProperty); +register('ColorRampProperty', ColorRampProperty); + +const TRANSITION_SUFFIX$2 = '-transition'; +/** + * A base class for style layers + */ +class StyleLayer extends Evented { + constructor(layer, properties) { + super(); + this.id = layer.id; + this.type = layer.type; + this._featureFilter = { filter: () => true, needGeometry: false }; + if (layer.type === 'custom') + return; + layer = layer; + this.metadata = layer.metadata; + this.minzoom = layer.minzoom; + this.maxzoom = layer.maxzoom; + if (layer.type !== 'background') { + this.source = layer.source; + this.sourceLayer = layer['source-layer']; + this.filter = layer.filter; + } + if (properties.layout) { + this._unevaluatedLayout = new Layout(properties.layout); + } + if (properties.paint) { + this._transitionablePaint = new Transitionable(properties.paint); + for (const property in layer.paint) { + this.setPaintProperty(property, layer.paint[property], { validate: false }); + } + for (const property in layer.layout) { + this.setLayoutProperty(property, layer.layout[property], { validate: false }); + } + this._transitioningPaint = this._transitionablePaint.untransitioned(); + //$FlowFixMe + this.paint = new PossiblyEvaluated(properties.paint); + } + } + getCrossfadeParameters() { + return this._crossfadeParameters; + } + getLayoutProperty(name) { + if (name === 'visibility') { + return this.visibility; + } + return this._unevaluatedLayout.getValue(name); + } + setLayoutProperty(name, value, options = {}) { + if (value !== null && value !== undefined) { + const key = `layers.${this.id}.layout.${name}`; + if (this._validate(validateLayoutProperty, key, name, value, options)) { + return; + } + } + if (name === 'visibility') { + this.visibility = value; + return; + } + this._unevaluatedLayout.setValue(name, value); + } + getPaintProperty(name) { + if (name.endsWith(TRANSITION_SUFFIX$2)) { + return this._transitionablePaint.getTransition(name.slice(0, -TRANSITION_SUFFIX$2.length)); + } + else { + return this._transitionablePaint.getValue(name); + } + } + setPaintProperty(name, value, options = {}) { + if (value !== null && value !== undefined) { + const key = `layers.${this.id}.paint.${name}`; + if (this._validate(validatePaintProperty, key, name, value, options)) { + return false; + } + } + if (name.endsWith(TRANSITION_SUFFIX$2)) { + this._transitionablePaint.setTransition(name.slice(0, -TRANSITION_SUFFIX$2.length), value || undefined); + return false; + } + else { + const transitionable = this._transitionablePaint._values[name]; + const isCrossFadedProperty = transitionable.property.specification['property-type'] === 'cross-faded-data-driven'; + const wasDataDriven = transitionable.value.isDataDriven(); + const oldValue = transitionable.value; + this._transitionablePaint.setValue(name, value); + this._handleSpecialPaintPropertyUpdate(name); + const newValue = this._transitionablePaint._values[name].value; + const isDataDriven = newValue.isDataDriven(); + // if a cross-faded value is changed, we need to make sure the new icons get added to each tile's iconAtlas + // so a call to _updateLayer is necessary, and we return true from this function so it gets called in + // Style#setPaintProperty + return isDataDriven || wasDataDriven || isCrossFadedProperty || this._handleOverridablePaintPropertyUpdate(name, oldValue, newValue); + } + } + _handleSpecialPaintPropertyUpdate(_) { + // No-op; can be overridden by derived classes. + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) { + // No-op; can be overridden by derived classes. + return false; + } + isHidden(zoom) { + if (this.minzoom && zoom < this.minzoom) + return true; + if (this.maxzoom && zoom >= this.maxzoom) + return true; + return this.visibility === 'none'; + } + updateTransitions(parameters) { + this._transitioningPaint = this._transitionablePaint.transitioned(parameters, this._transitioningPaint); + } + hasTransition() { + return this._transitioningPaint.hasTransition(); + } + recalculate(parameters, availableImages) { + if (parameters.getCrossfadeParameters) { + this._crossfadeParameters = parameters.getCrossfadeParameters(); + } + if (this._unevaluatedLayout) { + this.layout = this._unevaluatedLayout.possiblyEvaluate(parameters, undefined, availableImages); + } + this.paint = this._transitioningPaint.possiblyEvaluate(parameters, undefined, availableImages); + } + serialize() { + const output = { + 'id': this.id, + 'type': this.type, + 'source': this.source, + 'source-layer': this.sourceLayer, + 'metadata': this.metadata, + 'minzoom': this.minzoom, + 'maxzoom': this.maxzoom, + 'filter': this.filter, + 'layout': this._unevaluatedLayout && this._unevaluatedLayout.serialize(), + 'paint': this._transitionablePaint && this._transitionablePaint.serialize() + }; + if (this.visibility) { + output.layout = output.layout || {}; + output.layout.visibility = this.visibility; + } + return filterObject(output, (value, key) => { + return value !== undefined && + !(key === 'layout' && !Object.keys(value).length) && + !(key === 'paint' && !Object.keys(value).length); + }); + } + _validate(validate, key, name, value, options = {}) { + if (options && options.validate === false) { + return false; + } + return emitValidationErrors$1(this, validate.call(validateStyle, { + key, + layerType: this.type, + objectKey: name, + value, + styleSpec: v8Spec, + // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407 + style: { glyphs: true, sprite: true } + })); + } + is3D() { + return false; + } + isTileClipped() { + return false; + } + hasOffscreenPass() { + return false; + } + resize() { + // noop + } + isStateDependent() { + for (const property in this.paint._values) { + const value = this.paint.get(property); + if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) { + continue; + } + if ((value.value.kind === 'source' || value.value.kind === 'composite') && + value.value.isStateDependent) { + return true; + } + } + return false; + } +} + +// Note: all "sizes" are measured in bytes +/** + * @internal + * A view type size + */ +const viewTypes = { + 'Int8': Int8Array, + 'Uint8': Uint8Array, + 'Int16': Int16Array, + 'Uint16': Uint16Array, + 'Int32': Int32Array, + 'Uint32': Uint32Array, + 'Float32': Float32Array +}; +/** @internal */ +class Struct { + /** + * @param structArray - The StructArray the struct is stored in + * @param index - The index of the struct in the StructArray. + */ + constructor(structArray, index) { + this._structArray = structArray; + this._pos1 = index * this.size; + this._pos2 = this._pos1 / 2; + this._pos4 = this._pos1 / 4; + this._pos8 = this._pos1 / 8; + } +} +const DEFAULT_CAPACITY = 128; +const RESIZE_MULTIPLIER = 5; +/** + * @internal + * `StructArray` provides an abstraction over `ArrayBuffer` and `TypedArray` + * making it behave like an array of typed structs. + * + * Conceptually, a StructArray is comprised of elements, i.e., instances of its + * associated struct type. Each particular struct type, together with an + * alignment size, determines the memory layout of a StructArray whose elements + * are of that type. Thus, for each such layout that we need, we have + * a corresponding StructArrayLayout class, inheriting from StructArray and + * implementing `emplaceBack()` and `_refreshViews()`. + * + * In some cases, where we need to access particular elements of a StructArray, + * we implement a more specific subclass that inherits from one of the + * StructArrayLayouts and adds a `get(i): T` accessor that returns a structured + * object whose properties are proxies into the underlying memory space for the + * i-th element. This affords the convenience of working with (seemingly) plain + * Javascript objects without the overhead of serializing/deserializing them + * into ArrayBuffers for efficient web worker transfer. + */ +class StructArray { + constructor() { + this.isTransferred = false; + this.capacity = -1; + this.resize(0); + } + /** + * Serialize a StructArray instance. Serializes both the raw data and the + * metadata needed to reconstruct the StructArray base class during + * deserialization. + */ + static serialize(array, transferables) { + array._trim(); + if (transferables) { + array.isTransferred = true; + transferables.push(array.arrayBuffer); + } + return { + length: array.length, + arrayBuffer: array.arrayBuffer, + }; + } + static deserialize(input) { + const structArray = Object.create(this.prototype); + structArray.arrayBuffer = input.arrayBuffer; + structArray.length = input.length; + structArray.capacity = input.arrayBuffer.byteLength / structArray.bytesPerElement; + structArray._refreshViews(); + return structArray; + } + /** + * Resize the array to discard unused capacity. + */ + _trim() { + if (this.length !== this.capacity) { + this.capacity = this.length; + this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement); + this._refreshViews(); + } + } + /** + * Resets the length of the array to 0 without de-allocating capacity. + */ + clear() { + this.length = 0; + } + /** + * Resize the array. + * If `n` is greater than the current length then additional elements with undefined values are added. + * If `n` is less than the current length then the array will be reduced to the first `n` elements. + * @param n - The new size of the array. + */ + resize(n) { + this.reserve(n); + this.length = n; + } + /** + * Indicate a planned increase in size, so that any necessary allocation may + * be done once, ahead of time. + * @param n - The expected size of the array. + */ + reserve(n) { + if (n > this.capacity) { + this.capacity = Math.max(n, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY); + this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement); + const oldUint8Array = this.uint8; + this._refreshViews(); + if (oldUint8Array) + this.uint8.set(oldUint8Array); + } + } + /** + * Create TypedArray views for the current ArrayBuffer. + */ + _refreshViews() { + throw new Error('_refreshViews() must be implemented by each concrete StructArray layout'); + } +} +/** + * Given a list of member fields, create a full StructArrayLayout, in + * particular calculating the correct byte offset for each field. This data + * is used at build time to generate StructArrayLayout_*#emplaceBack() and + * other accessors, and at runtime for binding vertex buffer attributes. + */ +function createLayout(members, alignment = 1) { + let offset = 0; + let maxSize = 0; + const layoutMembers = members.map((member) => { + const typeSize = sizeOf(member.type); + const memberOffset = offset = align$1(offset, Math.max(alignment, typeSize)); + const components = member.components || 1; + maxSize = Math.max(maxSize, typeSize); + offset += typeSize * components; + return { + name: member.name, + type: member.type, + components, + offset: memberOffset, + }; + }); + const size = align$1(offset, Math.max(maxSize, alignment)); + return { + members: layoutMembers, + size, + alignment + }; +} +function sizeOf(type) { + return viewTypes[type].BYTES_PER_ELEMENT; +} +function align$1(offset, size) { + return Math.ceil(offset / size) * size; +} + +// This file is generated. Edit build/generate-struct-arrays.ts, then run `npm run codegen`. +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * + */ +class StructArrayLayout2i4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1); + } + emplace(i, v0, v1) { + const o2 = i * 2; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + return i; + } +} +StructArrayLayout2i4.prototype.bytesPerElement = 4; +register('StructArrayLayout2i4', StructArrayLayout2i4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[3] + * + */ +class StructArrayLayout3i6 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o2 = i * 3; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + return i; + } +} +StructArrayLayout3i6.prototype.bytesPerElement = 6; +register('StructArrayLayout3i6', StructArrayLayout3i6); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[4] + * + */ +class StructArrayLayout4i8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3); + } + emplace(i, v0, v1, v2, v3) { + const o2 = i * 4; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + return i; + } +} +StructArrayLayout4i8.prototype.bytesPerElement = 8; +register('StructArrayLayout4i8', StructArrayLayout4i8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Int16[4] + * + */ +class StructArrayLayout2i4i12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o2 = i * 6; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + return i; + } +} +StructArrayLayout2i4i12.prototype.bytesPerElement = 12; +register('StructArrayLayout2i4i12', StructArrayLayout2i4i12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Uint8[4] + * + */ +class StructArrayLayout2i4ub8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o2 = i * 4; + const o1 = i * 8; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.uint8[o1 + 4] = v2; + this.uint8[o1 + 5] = v3; + this.uint8[o1 + 6] = v4; + this.uint8[o1 + 7] = v5; + return i; + } +} +StructArrayLayout2i4ub8.prototype.bytesPerElement = 8; +register('StructArrayLayout2i4ub8', StructArrayLayout2i4ub8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[2] + * + */ +class StructArrayLayout2f8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1); + } + emplace(i, v0, v1) { + const o4 = i * 2; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + return i; + } +} +StructArrayLayout2f8.prototype.bytesPerElement = 8; +register('StructArrayLayout2f8', StructArrayLayout2f8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[10] + * + */ +class StructArrayLayout10ui20 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) { + const o2 = i * 10; + this.uint16[o2 + 0] = v0; + this.uint16[o2 + 1] = v1; + this.uint16[o2 + 2] = v2; + this.uint16[o2 + 3] = v3; + this.uint16[o2 + 4] = v4; + this.uint16[o2 + 5] = v5; + this.uint16[o2 + 6] = v6; + this.uint16[o2 + 7] = v7; + this.uint16[o2 + 8] = v8; + this.uint16[o2 + 9] = v9; + return i; + } +} +StructArrayLayout10ui20.prototype.bytesPerElement = 20; +register('StructArrayLayout10ui20', StructArrayLayout10ui20); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[4] + * [8] - Uint16[4] + * [16] - Int16[4] + * + */ +class StructArrayLayout4i4ui4i24 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) { + const o2 = i * 12; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.uint16[o2 + 4] = v4; + this.uint16[o2 + 5] = v5; + this.uint16[o2 + 6] = v6; + this.uint16[o2 + 7] = v7; + this.int16[o2 + 8] = v8; + this.int16[o2 + 9] = v9; + this.int16[o2 + 10] = v10; + this.int16[o2 + 11] = v11; + return i; + } +} +StructArrayLayout4i4ui4i24.prototype.bytesPerElement = 24; +register('StructArrayLayout4i4ui4i24', StructArrayLayout4i4ui4i24); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[3] + * + */ +class StructArrayLayout3f12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o4 = i * 3; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + return i; + } +} +StructArrayLayout3f12.prototype.bytesPerElement = 12; +register('StructArrayLayout3f12', StructArrayLayout3f12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint32[1] + * + */ +class StructArrayLayout1ul4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + } + emplaceBack(v0) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0); + } + emplace(i, v0) { + const o4 = i * 1; + this.uint32[o4 + 0] = v0; + return i; + } +} +StructArrayLayout1ul4.prototype.bytesPerElement = 4; +register('StructArrayLayout1ul4', StructArrayLayout1ul4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[6] + * [12] - Uint32[1] + * [16] - Uint16[2] + * + */ +class StructArrayLayout6i1ul2ui20 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8) { + const o2 = i * 10; + const o4 = i * 5; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + this.uint32[o4 + 3] = v6; + this.uint16[o2 + 8] = v7; + this.uint16[o2 + 9] = v8; + return i; + } +} +StructArrayLayout6i1ul2ui20.prototype.bytesPerElement = 20; +register('StructArrayLayout6i1ul2ui20', StructArrayLayout6i1ul2ui20); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Int16[2] + * [8] - Int16[2] + * + */ +class StructArrayLayout2i2i2i12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o2 = i * 6; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + return i; + } +} +StructArrayLayout2i2i2i12.prototype.bytesPerElement = 12; +register('StructArrayLayout2i2i2i12', StructArrayLayout2i2i2i12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[2] + * [8] - Float32[1] + * [12] - Int16[2] + * + */ +class StructArrayLayout2f1f2i16 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4); + } + emplace(i, v0, v1, v2, v3, v4) { + const o4 = i * 4; + const o2 = i * 8; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + this.int16[o2 + 6] = v3; + this.int16[o2 + 7] = v4; + return i; + } +} +StructArrayLayout2f1f2i16.prototype.bytesPerElement = 16; +register('StructArrayLayout2f1f2i16', StructArrayLayout2f1f2i16); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint8[2] + * [4] - Float32[2] + * [12] - Int16[2] + * + */ +class StructArrayLayout2ub2f2i16 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o1 = i * 16; + const o4 = i * 4; + const o2 = i * 8; + this.uint8[o1 + 0] = v0; + this.uint8[o1 + 1] = v1; + this.float32[o4 + 1] = v2; + this.float32[o4 + 2] = v3; + this.int16[o2 + 6] = v4; + this.int16[o2 + 7] = v5; + return i; + } +} +StructArrayLayout2ub2f2i16.prototype.bytesPerElement = 16; +register('StructArrayLayout2ub2f2i16', StructArrayLayout2ub2f2i16); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[3] + * + */ +class StructArrayLayout3ui6 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o2 = i * 3; + this.uint16[o2 + 0] = v0; + this.uint16[o2 + 1] = v1; + this.uint16[o2 + 2] = v2; + return i; + } +} +StructArrayLayout3ui6.prototype.bytesPerElement = 6; +register('StructArrayLayout3ui6', StructArrayLayout3ui6); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Uint16[2] + * [8] - Uint32[3] + * [20] - Uint16[3] + * [28] - Float32[2] + * [36] - Uint8[3] + * [40] - Uint32[1] + * [44] - Int16[1] + * + */ +class StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) { + const o2 = i * 24; + const o4 = i * 12; + const o1 = i * 48; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.uint16[o2 + 2] = v2; + this.uint16[o2 + 3] = v3; + this.uint32[o4 + 2] = v4; + this.uint32[o4 + 3] = v5; + this.uint32[o4 + 4] = v6; + this.uint16[o2 + 10] = v7; + this.uint16[o2 + 11] = v8; + this.uint16[o2 + 12] = v9; + this.float32[o4 + 7] = v10; + this.float32[o4 + 8] = v11; + this.uint8[o1 + 36] = v12; + this.uint8[o1 + 37] = v13; + this.uint8[o1 + 38] = v14; + this.uint32[o4 + 10] = v15; + this.int16[o2 + 22] = v16; + return i; + } +} +StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48.prototype.bytesPerElement = 48; +register('StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48', StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[8] + * [16] - Uint16[15] + * [48] - Uint32[1] + * [52] - Float32[2] + * [60] - Uint16[2] + * + */ +class StructArrayLayout8i15ui1ul2f2ui64 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(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) { + const i = this.length; + this.resize(i + 1); + 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); + } + 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) { + const o2 = i * 32; + const o4 = i * 16; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + this.int16[o2 + 6] = v6; + this.int16[o2 + 7] = v7; + this.uint16[o2 + 8] = v8; + this.uint16[o2 + 9] = v9; + this.uint16[o2 + 10] = v10; + this.uint16[o2 + 11] = v11; + this.uint16[o2 + 12] = v12; + this.uint16[o2 + 13] = v13; + this.uint16[o2 + 14] = v14; + this.uint16[o2 + 15] = v15; + this.uint16[o2 + 16] = v16; + this.uint16[o2 + 17] = v17; + this.uint16[o2 + 18] = v18; + this.uint16[o2 + 19] = v19; + this.uint16[o2 + 20] = v20; + this.uint16[o2 + 21] = v21; + this.uint16[o2 + 22] = v22; + this.uint32[o4 + 12] = v23; + this.float32[o4 + 13] = v24; + this.float32[o4 + 14] = v25; + this.uint16[o2 + 30] = v26; + this.uint16[o2 + 31] = v27; + return i; + } +} +StructArrayLayout8i15ui1ul2f2ui64.prototype.bytesPerElement = 64; +register('StructArrayLayout8i15ui1ul2f2ui64', StructArrayLayout8i15ui1ul2f2ui64); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[1] + * + */ +class StructArrayLayout1f4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0); + } + emplace(i, v0) { + const o4 = i * 1; + this.float32[o4 + 0] = v0; + return i; + } +} +StructArrayLayout1f4.prototype.bytesPerElement = 4; +register('StructArrayLayout1f4', StructArrayLayout1f4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[1] + * [4] - Float32[2] + * + */ +class StructArrayLayout1ui2f12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o2 = i * 6; + const o4 = i * 3; + this.uint16[o2 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + return i; + } +} +StructArrayLayout1ui2f12.prototype.bytesPerElement = 12; +register('StructArrayLayout1ui2f12', StructArrayLayout1ui2f12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint32[1] + * [4] - Uint16[2] + * + */ +class StructArrayLayout1ul2ui8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o4 = i * 2; + const o2 = i * 4; + this.uint32[o4 + 0] = v0; + this.uint16[o2 + 2] = v1; + this.uint16[o2 + 3] = v2; + return i; + } +} +StructArrayLayout1ul2ui8.prototype.bytesPerElement = 8; +register('StructArrayLayout1ul2ui8', StructArrayLayout1ul2ui8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[2] + * + */ +class StructArrayLayout2ui4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1); + } + emplace(i, v0, v1) { + const o2 = i * 2; + this.uint16[o2 + 0] = v0; + this.uint16[o2 + 1] = v1; + return i; + } +} +StructArrayLayout2ui4.prototype.bytesPerElement = 4; +register('StructArrayLayout2ui4', StructArrayLayout2ui4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[1] + * + */ +class StructArrayLayout1ui2 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0); + } + emplace(i, v0) { + const o2 = i * 1; + this.uint16[o2 + 0] = v0; + return i; + } +} +StructArrayLayout1ui2.prototype.bytesPerElement = 2; +register('StructArrayLayout1ui2', StructArrayLayout1ui2); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[4] + * + */ +class StructArrayLayout4f16 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3); + } + emplace(i, v0, v1, v2, v3) { + const o4 = i * 4; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + this.float32[o4 + 3] = v3; + return i; + } +} +StructArrayLayout4f16.prototype.bytesPerElement = 16; +register('StructArrayLayout4f16', StructArrayLayout4f16); +/** @internal */ +class CollisionBoxStruct extends Struct { + get anchorPointX() { return this._structArray.int16[this._pos2 + 0]; } + get anchorPointY() { return this._structArray.int16[this._pos2 + 1]; } + get x1() { return this._structArray.int16[this._pos2 + 2]; } + get y1() { return this._structArray.int16[this._pos2 + 3]; } + get x2() { return this._structArray.int16[this._pos2 + 4]; } + get y2() { return this._structArray.int16[this._pos2 + 5]; } + get featureIndex() { return this._structArray.uint32[this._pos4 + 3]; } + get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 8]; } + get bucketIndex() { return this._structArray.uint16[this._pos2 + 9]; } + get anchorPoint() { return new Point$2(this.anchorPointX, this.anchorPointY); } +} +CollisionBoxStruct.prototype.size = 20; +/** @internal */ +class CollisionBoxArray extends StructArrayLayout6i1ul2ui20 { + /** + * Return the CollisionBoxStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new CollisionBoxStruct(this, index); + } +} +register('CollisionBoxArray', CollisionBoxArray); +/** @internal */ +class PlacedSymbolStruct extends Struct { + get anchorX() { return this._structArray.int16[this._pos2 + 0]; } + get anchorY() { return this._structArray.int16[this._pos2 + 1]; } + get glyphStartIndex() { return this._structArray.uint16[this._pos2 + 2]; } + get numGlyphs() { return this._structArray.uint16[this._pos2 + 3]; } + get vertexStartIndex() { return this._structArray.uint32[this._pos4 + 2]; } + get lineStartIndex() { return this._structArray.uint32[this._pos4 + 3]; } + get lineLength() { return this._structArray.uint32[this._pos4 + 4]; } + get segment() { return this._structArray.uint16[this._pos2 + 10]; } + get lowerSize() { return this._structArray.uint16[this._pos2 + 11]; } + get upperSize() { return this._structArray.uint16[this._pos2 + 12]; } + get lineOffsetX() { return this._structArray.float32[this._pos4 + 7]; } + get lineOffsetY() { return this._structArray.float32[this._pos4 + 8]; } + get writingMode() { return this._structArray.uint8[this._pos1 + 36]; } + get placedOrientation() { return this._structArray.uint8[this._pos1 + 37]; } + set placedOrientation(x) { this._structArray.uint8[this._pos1 + 37] = x; } + get hidden() { return this._structArray.uint8[this._pos1 + 38]; } + set hidden(x) { this._structArray.uint8[this._pos1 + 38] = x; } + get crossTileID() { return this._structArray.uint32[this._pos4 + 10]; } + set crossTileID(x) { this._structArray.uint32[this._pos4 + 10] = x; } + get associatedIconIndex() { return this._structArray.int16[this._pos2 + 22]; } +} +PlacedSymbolStruct.prototype.size = 48; +/** @internal */ +class PlacedSymbolArray extends StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 { + /** + * Return the PlacedSymbolStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new PlacedSymbolStruct(this, index); + } +} +register('PlacedSymbolArray', PlacedSymbolArray); +/** @internal */ +class SymbolInstanceStruct extends Struct { + get anchorX() { return this._structArray.int16[this._pos2 + 0]; } + get anchorY() { return this._structArray.int16[this._pos2 + 1]; } + get rightJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 2]; } + get centerJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 3]; } + get leftJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 4]; } + get verticalPlacedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 5]; } + get placedIconSymbolIndex() { return this._structArray.int16[this._pos2 + 6]; } + get verticalPlacedIconSymbolIndex() { return this._structArray.int16[this._pos2 + 7]; } + get key() { return this._structArray.uint16[this._pos2 + 8]; } + get textBoxStartIndex() { return this._structArray.uint16[this._pos2 + 9]; } + get textBoxEndIndex() { return this._structArray.uint16[this._pos2 + 10]; } + get verticalTextBoxStartIndex() { return this._structArray.uint16[this._pos2 + 11]; } + get verticalTextBoxEndIndex() { return this._structArray.uint16[this._pos2 + 12]; } + get iconBoxStartIndex() { return this._structArray.uint16[this._pos2 + 13]; } + get iconBoxEndIndex() { return this._structArray.uint16[this._pos2 + 14]; } + get verticalIconBoxStartIndex() { return this._structArray.uint16[this._pos2 + 15]; } + get verticalIconBoxEndIndex() { return this._structArray.uint16[this._pos2 + 16]; } + get featureIndex() { return this._structArray.uint16[this._pos2 + 17]; } + get numHorizontalGlyphVertices() { return this._structArray.uint16[this._pos2 + 18]; } + get numVerticalGlyphVertices() { return this._structArray.uint16[this._pos2 + 19]; } + get numIconVertices() { return this._structArray.uint16[this._pos2 + 20]; } + get numVerticalIconVertices() { return this._structArray.uint16[this._pos2 + 21]; } + get useRuntimeCollisionCircles() { return this._structArray.uint16[this._pos2 + 22]; } + get crossTileID() { return this._structArray.uint32[this._pos4 + 12]; } + set crossTileID(x) { this._structArray.uint32[this._pos4 + 12] = x; } + get textBoxScale() { return this._structArray.float32[this._pos4 + 13]; } + get collisionCircleDiameter() { return this._structArray.float32[this._pos4 + 14]; } + get textAnchorOffsetStartIndex() { return this._structArray.uint16[this._pos2 + 30]; } + get textAnchorOffsetEndIndex() { return this._structArray.uint16[this._pos2 + 31]; } +} +SymbolInstanceStruct.prototype.size = 64; +/** @internal */ +class SymbolInstanceArray extends StructArrayLayout8i15ui1ul2f2ui64 { + /** + * Return the SymbolInstanceStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new SymbolInstanceStruct(this, index); + } +} +register('SymbolInstanceArray', SymbolInstanceArray); +/** @internal */ +class GlyphOffsetArray extends StructArrayLayout1f4 { + getoffsetX(index) { return this.float32[index * 1 + 0]; } +} +register('GlyphOffsetArray', GlyphOffsetArray); +/** @internal */ +class SymbolLineVertexArray extends StructArrayLayout3i6 { + getx(index) { return this.int16[index * 3 + 0]; } + gety(index) { return this.int16[index * 3 + 1]; } + gettileUnitDistanceFromAnchor(index) { return this.int16[index * 3 + 2]; } +} +register('SymbolLineVertexArray', SymbolLineVertexArray); +/** @internal */ +class TextAnchorOffsetStruct extends Struct { + get textAnchor() { return this._structArray.uint16[this._pos2 + 0]; } + get textOffset0() { return this._structArray.float32[this._pos4 + 1]; } + get textOffset1() { return this._structArray.float32[this._pos4 + 2]; } +} +TextAnchorOffsetStruct.prototype.size = 12; +/** @internal */ +class TextAnchorOffsetArray extends StructArrayLayout1ui2f12 { + /** + * Return the TextAnchorOffsetStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new TextAnchorOffsetStruct(this, index); + } +} +register('TextAnchorOffsetArray', TextAnchorOffsetArray); +/** @internal */ +class FeatureIndexStruct extends Struct { + get featureIndex() { return this._structArray.uint32[this._pos4 + 0]; } + get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 2]; } + get bucketIndex() { return this._structArray.uint16[this._pos2 + 3]; } +} +FeatureIndexStruct.prototype.size = 8; +/** @internal */ +class FeatureIndexArray extends StructArrayLayout1ul2ui8 { + /** + * Return the FeatureIndexStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new FeatureIndexStruct(this, index); + } +} +register('FeatureIndexArray', FeatureIndexArray); +class PosArray extends StructArrayLayout2i4 { +} +class Pos3dArray extends StructArrayLayout3i6 { +} +class RasterBoundsArray extends StructArrayLayout4i8 { +} +class CircleLayoutArray extends StructArrayLayout2i4 { +} +class FillLayoutArray extends StructArrayLayout2i4 { +} +class FillExtrusionLayoutArray extends StructArrayLayout2i4i12 { +} +class HeatmapLayoutArray extends StructArrayLayout2i4 { +} +class LineLayoutArray extends StructArrayLayout2i4ub8 { +} +class LineExtLayoutArray extends StructArrayLayout2f8 { +} +class PatternLayoutArray extends StructArrayLayout10ui20 { +} +class SymbolLayoutArray extends StructArrayLayout4i4ui4i24 { +} +class SymbolDynamicLayoutArray extends StructArrayLayout3f12 { +} +class SymbolOpacityArray extends StructArrayLayout1ul4 { +} +class CollisionBoxLayoutArray extends StructArrayLayout2i2i2i12 { +} +class CollisionCircleLayoutArray extends StructArrayLayout2f1f2i16 { +} +class CollisionVertexArray extends StructArrayLayout2ub2f2i16 { +} +class QuadTriangleArray extends StructArrayLayout3ui6 { +} +class TriangleIndexArray extends StructArrayLayout3ui6 { +} +class LineIndexArray extends StructArrayLayout2ui4 { +} +class LineStripIndexArray extends StructArrayLayout1ui2 { +} + +const layout$6 = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' } +], 4); +const { members: members$4, size: size$4, alignment: alignment$4 } = layout$6; + +/** + * @internal + * Used for calculations on vector segments + */ +class SegmentVector { + constructor(segments = []) { + this.segments = segments; + } + prepareSegment(numVertices, layoutVertexArray, indexArray, sortKey) { + let segment = this.segments[this.segments.length - 1]; + if (numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) + warnOnce(`Max vertices per segment is ${SegmentVector.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${numVertices}`); + if (!segment || segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH || segment.sortKey !== sortKey) { + segment = { + vertexOffset: layoutVertexArray.length, + primitiveOffset: indexArray.length, + vertexLength: 0, + primitiveLength: 0 + }; + if (sortKey !== undefined) + segment.sortKey = sortKey; + this.segments.push(segment); + } + return segment; + } + get() { + return this.segments; + } + destroy() { + for (const segment of this.segments) { + for (const k in segment.vaos) { + segment.vaos[k].destroy(); + } + } + } + static simpleSegment(vertexOffset, primitiveOffset, vertexLength, primitiveLength) { + return new SegmentVector([{ + vertexOffset, + primitiveOffset, + vertexLength, + primitiveLength, + vaos: {}, + sortKey: 0 + }]); + } +} +/** + * The maximum size of a vertex array. This limit is imposed by WebGL's 16 bit + * addressing of vertex buffers. + */ +SegmentVector.MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1; +register('SegmentVector', SegmentVector); + +/** + * Packs two numbers, interpreted as 8-bit unsigned integers, into a single + * float. Unpack them in the shader using the `unpack_float()` function, + * defined in _prelude.vertex.glsl + */ +function packUint8ToFloat(a, b) { + // coerce a and b to 8-bit ints + a = clamp$1(Math.floor(a), 0, 255); + b = clamp$1(Math.floor(b), 0, 255); + return 256 * a + b; +} + +const patternAttributes = createLayout([ + // [tl.x, tl.y, br.x, br.y] + { name: 'a_pattern_from', components: 4, type: 'Uint16' }, + { name: 'a_pattern_to', components: 4, type: 'Uint16' }, + { name: 'a_pixel_ratio_from', components: 1, type: 'Uint16' }, + { name: 'a_pixel_ratio_to', components: 1, type: 'Uint16' }, +]); + +var murmurhashJs$1 = {exports: {}}; + +var murmurhash3_gc$2 = {exports: {}}; + +/** + * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} key ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ +var murmurhash3_gc = murmurhash3_gc$2.exports; + +(function (module) { + function murmurhash3_32_gc(key, seed) { + var remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i; + + remainder = key.length & 3; // key.length % 4 + bytes = key.length - remainder; + h1 = seed; + c1 = 0xcc9e2d51; + c2 = 0x1b873593; + i = 0; + + while (i < bytes) { + k1 = + ((key.charCodeAt(i) & 0xff)) | + ((key.charCodeAt(++i) & 0xff) << 8) | + ((key.charCodeAt(++i) & 0xff) << 16) | + ((key.charCodeAt(++i) & 0xff) << 24); + ++i; + + k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff; + + h1 ^= k1; + h1 = (h1 << 13) | (h1 >>> 19); + h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff; + h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16)); + } + + k1 = 0; + + switch (remainder) { + case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; + case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; + case 1: k1 ^= (key.charCodeAt(i) & 0xff); + + k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; + h1 ^= k1; + } + + h1 ^= key.length; + + h1 ^= h1 >>> 16; + h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; + h1 ^= h1 >>> 13; + h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff; + h1 ^= h1 >>> 16; + + return h1 >>> 0; + } + + if('object' !== "undefined") { + module.exports = murmurhash3_32_gc; + } +} (murmurhash3_gc$2)); + +var murmurhash3_gcExports = murmurhash3_gc$2.exports; +var murmurhash3_gc$1 = /*@__PURE__*/getDefaultExportFromCjs$1(murmurhash3_gcExports); + +var murmurhash2_gc$2 = {exports: {}}; + +/** + * JS Implementation of MurmurHash2 + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} str ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ +var murmurhash2_gc = murmurhash2_gc$2.exports; + +(function (module) { + function murmurhash2_32_gc(str, seed) { + var + l = str.length, + h = seed ^ l, + i = 0, + k; + + while (l >= 4) { + k = + ((str.charCodeAt(i) & 0xff)) | + ((str.charCodeAt(++i) & 0xff) << 8) | + ((str.charCodeAt(++i) & 0xff) << 16) | + ((str.charCodeAt(++i) & 0xff) << 24); + + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + k ^= k >>> 24; + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; + + l -= 4; + ++i; + } + + switch (l) { + case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; + case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; + case 1: h ^= (str.charCodeAt(i) & 0xff); + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + } + + h ^= h >>> 13; + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + h ^= h >>> 15; + + return h >>> 0; + } + + if('object' !== undefined) { + module.exports = murmurhash2_32_gc; + } +} (murmurhash2_gc$2)); + +var murmurhash2_gcExports = murmurhash2_gc$2.exports; +var murmurhash2_gc$1 = /*@__PURE__*/getDefaultExportFromCjs$1(murmurhash2_gcExports); + +var murmurhashJs = murmurhashJs$1.exports; + +var murmur3 = murmurhash3_gcExports; +var murmur2 = murmurhash2_gcExports; + +murmurhashJs$1.exports = murmur3; +var murmur3_1 = murmurhashJs$1.exports.murmur3 = murmur3; +var murmur2_1 = murmurhashJs$1.exports.murmur2 = murmur2; + +var murmurhashJsExports = murmurhashJs$1.exports; +var murmur3$1 = /*@__PURE__*/getDefaultExportFromCjs$1(murmurhashJsExports); + +// A transferable data structure that maps feature ids to their indices and buffer offsets +class FeaturePositionMap { + constructor() { + this.ids = []; + this.positions = []; + this.indexed = false; + } + add(id, index, start, end) { + this.ids.push(getNumericId(id)); + this.positions.push(index, start, end); + } + getPositions(id) { + if (!this.indexed) + throw new Error('Trying to get index, but feature positions are not indexed'); + const intId = getNumericId(id); + // binary search for the first occurrence of id in this.ids; + // relies on ids/positions being sorted by id, which happens in serialization + let i = 0; + let j = this.ids.length - 1; + while (i < j) { + const m = (i + j) >> 1; + if (this.ids[m] >= intId) { + j = m; + } + else { + i = m + 1; + } + } + const positions = []; + while (this.ids[i] === intId) { + const index = this.positions[3 * i]; + const start = this.positions[3 * i + 1]; + const end = this.positions[3 * i + 2]; + positions.push({ index, start, end }); + i++; + } + return positions; + } + static serialize(map, transferables) { + const ids = new Float64Array(map.ids); + const positions = new Uint32Array(map.positions); + sort$1(ids, positions, 0, ids.length - 1); + if (transferables) { + transferables.push(ids.buffer, positions.buffer); + } + return { ids, positions }; + } + static deserialize(obj) { + const map = new FeaturePositionMap(); + // after transferring, we only use these arrays statically (no pushes), + // so TypedArray vs Array distinction that flow points out doesn't matter + map.ids = obj.ids; + map.positions = obj.positions; + map.indexed = true; + return map; + } +} +function getNumericId(value) { + const numValue = +value; + if (!isNaN(numValue) && numValue <= Number.MAX_SAFE_INTEGER) { + return numValue; + } + return murmur3$1(String(value)); +} +// custom quicksort that sorts ids, indices and offsets together (by ids) +// uses Hoare partitioning & manual tail call optimization to avoid worst case scenarios +function sort$1(ids, positions, left, right) { + while (left < right) { + const pivot = ids[(left + right) >> 1]; + let i = left - 1; + let j = right + 1; + while (true) { + do + i++; + while (ids[i] < pivot); + do + j--; + while (ids[j] > pivot); + if (i >= j) + break; + swap$1(ids, i, j); + swap$1(positions, 3 * i, 3 * j); + swap$1(positions, 3 * i + 1, 3 * j + 1); + swap$1(positions, 3 * i + 2, 3 * j + 2); + } + if (j - left < right - j) { + sort$1(ids, positions, left, j); + left = j + 1; + } + else { + sort$1(ids, positions, j + 1, right); + right = j; + } + } +} +function swap$1(arr, i, j) { + const tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} +register('FeaturePositionMap', FeaturePositionMap); + +/** + * @internal + * A base uniform abstract class + */ +class Uniform { + constructor(context, location) { + this.gl = context.gl; + this.location = location; + } +} +class Uniform1i extends Uniform { + constructor(context, location) { + super(context, location); + this.current = 0; + } + set(v) { + if (this.current !== v) { + this.current = v; + this.gl.uniform1i(this.location, v); + } + } +} +class Uniform1f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = 0; + } + set(v) { + if (this.current !== v) { + this.current = v; + this.gl.uniform1f(this.location, v); + } + } +} +class Uniform2f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = [0, 0]; + } + set(v) { + if (v[0] !== this.current[0] || v[1] !== this.current[1]) { + this.current = v; + this.gl.uniform2f(this.location, v[0], v[1]); + } + } +} +class Uniform3f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = [0, 0, 0]; + } + set(v) { + if (v[0] !== this.current[0] || v[1] !== this.current[1] || v[2] !== this.current[2]) { + this.current = v; + this.gl.uniform3f(this.location, v[0], v[1], v[2]); + } + } +} +class Uniform4f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = [0, 0, 0, 0]; + } + set(v) { + if (v[0] !== this.current[0] || v[1] !== this.current[1] || + v[2] !== this.current[2] || v[3] !== this.current[3]) { + this.current = v; + this.gl.uniform4f(this.location, v[0], v[1], v[2], v[3]); + } + } +} +class UniformColor extends Uniform { + constructor(context, location) { + super(context, location); + this.current = Color.transparent; + } + set(v) { + if (v.r !== this.current.r || v.g !== this.current.g || + v.b !== this.current.b || v.a !== this.current.a) { + this.current = v; + this.gl.uniform4f(this.location, v.r, v.g, v.b, v.a); + } + } +} +const emptyMat4 = new Float32Array(16); +class UniformMatrix4f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = emptyMat4; + } + set(v) { + // The vast majority of matrix comparisons that will trip this set + // happen at i=12 or i=0, so we check those first to avoid lots of + // unnecessary iteration: + if (v[12] !== this.current[12] || v[0] !== this.current[0]) { + this.current = v; + this.gl.uniformMatrix4fv(this.location, false, v); + return; + } + for (let i = 1; i < 16; i++) { + if (v[i] !== this.current[i]) { + this.current = v; + this.gl.uniformMatrix4fv(this.location, false, v); + break; + } + } + } +} + +function packColor(color) { + return [ + packUint8ToFloat(255 * color.r, 255 * color.g), + packUint8ToFloat(255 * color.b, 255 * color.a) + ]; +} +class ConstantBinder { + constructor(value, names, type) { + this.value = value; + this.uniformNames = names.map(name => `u_${name}`); + this.type = type; + } + setUniform(uniform, globals, currentValue) { + uniform.set(currentValue.constantOr(this.value)); + } + getBinding(context, location, _) { + return (this.type === 'color') ? + new UniformColor(context, location) : + new Uniform1f(context, location); + } +} +class CrossFadedConstantBinder { + constructor(value, names) { + this.uniformNames = names.map(name => `u_${name}`); + this.patternFrom = null; + this.patternTo = null; + this.pixelRatioFrom = 1.0; + this.pixelRatioTo = 1.0; + } + setConstantPatternPositions(posTo, posFrom) { + this.pixelRatioFrom = posFrom.pixelRatio; + this.pixelRatioTo = posTo.pixelRatio; + this.patternFrom = posFrom.tlbr; + this.patternTo = posTo.tlbr; + } + setUniform(uniform, globals, currentValue, uniformName) { + const pos = uniformName === 'u_pattern_to' ? this.patternTo : + uniformName === 'u_pattern_from' ? this.patternFrom : + uniformName === 'u_pixel_ratio_to' ? this.pixelRatioTo : + uniformName === 'u_pixel_ratio_from' ? this.pixelRatioFrom : null; + if (pos) + uniform.set(pos); + } + getBinding(context, location, name) { + return name.substr(0, 9) === 'u_pattern' ? + new Uniform4f(context, location) : + new Uniform1f(context, location); + } +} +class SourceExpressionBinder { + constructor(expression, names, type, PaintVertexArray) { + this.expression = expression; + this.type = type; + this.maxValue = 0; + this.paintVertexAttributes = names.map((name) => ({ + name: `a_${name}`, + type: 'Float32', + components: type === 'color' ? 2 : 1, + offset: 0 + })); + this.paintVertexArray = new PaintVertexArray(); + } + populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection) { + const start = this.paintVertexArray.length; + const value = this.expression.evaluate(new EvaluationParameters(0), feature, {}, canonical, [], formattedSection); + this.paintVertexArray.resize(newLength); + this._setPaintValue(start, newLength, value); + } + updatePaintArray(start, end, feature, featureState) { + const value = this.expression.evaluate({ zoom: 0 }, feature, featureState); + this._setPaintValue(start, end, value); + } + _setPaintValue(start, end, value) { + if (this.type === 'color') { + const color = packColor(value); + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, color[0], color[1]); + } + } + else { + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, value); + } + this.maxValue = Math.max(this.maxValue, Math.abs(value)); + } + } + upload(context) { + if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) { + if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) { + this.paintVertexBuffer.updateData(this.paintVertexArray); + } + else { + this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent); + } + } + } + destroy() { + if (this.paintVertexBuffer) { + this.paintVertexBuffer.destroy(); + } + } +} +class CompositeExpressionBinder { + constructor(expression, names, type, useIntegerZoom, zoom, PaintVertexArray) { + this.expression = expression; + this.uniformNames = names.map(name => `u_${name}_t`); + this.type = type; + this.useIntegerZoom = useIntegerZoom; + this.zoom = zoom; + this.maxValue = 0; + this.paintVertexAttributes = names.map((name) => ({ + name: `a_${name}`, + type: 'Float32', + components: type === 'color' ? 4 : 2, + offset: 0 + })); + this.paintVertexArray = new PaintVertexArray(); + } + populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection) { + const min = this.expression.evaluate(new EvaluationParameters(this.zoom), feature, {}, canonical, [], formattedSection); + const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1), feature, {}, canonical, [], formattedSection); + const start = this.paintVertexArray.length; + this.paintVertexArray.resize(newLength); + this._setPaintValue(start, newLength, min, max); + } + updatePaintArray(start, end, feature, featureState) { + const min = this.expression.evaluate({ zoom: this.zoom }, feature, featureState); + const max = this.expression.evaluate({ zoom: this.zoom + 1 }, feature, featureState); + this._setPaintValue(start, end, min, max); + } + _setPaintValue(start, end, min, max) { + if (this.type === 'color') { + const minColor = packColor(min); + const maxColor = packColor(max); + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, minColor[0], minColor[1], maxColor[0], maxColor[1]); + } + } + else { + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, min, max); + } + this.maxValue = Math.max(this.maxValue, Math.abs(min), Math.abs(max)); + } + } + upload(context) { + if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) { + if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) { + this.paintVertexBuffer.updateData(this.paintVertexArray); + } + else { + this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent); + } + } + } + destroy() { + if (this.paintVertexBuffer) { + this.paintVertexBuffer.destroy(); + } + } + setUniform(uniform, globals) { + const currentZoom = this.useIntegerZoom ? Math.floor(globals.zoom) : globals.zoom; + const factor = clamp$1(this.expression.interpolationFactor(currentZoom, this.zoom, this.zoom + 1), 0, 1); + uniform.set(factor); + } + getBinding(context, location, _) { + return new Uniform1f(context, location); + } +} +class CrossFadedCompositeBinder { + constructor(expression, type, useIntegerZoom, zoom, PaintVertexArray, layerId) { + this.expression = expression; + this.type = type; + this.useIntegerZoom = useIntegerZoom; + this.zoom = zoom; + this.layerId = layerId; + this.zoomInPaintVertexArray = new PaintVertexArray(); + this.zoomOutPaintVertexArray = new PaintVertexArray(); + } + populatePaintArray(length, feature, imagePositions) { + const start = this.zoomInPaintVertexArray.length; + this.zoomInPaintVertexArray.resize(length); + this.zoomOutPaintVertexArray.resize(length); + this._setPaintValues(start, length, feature.patterns && feature.patterns[this.layerId], imagePositions); + } + updatePaintArray(start, end, feature, featureState, imagePositions) { + this._setPaintValues(start, end, feature.patterns && feature.patterns[this.layerId], imagePositions); + } + _setPaintValues(start, end, patterns, positions) { + if (!positions || !patterns) + return; + const { min, mid, max } = patterns; + const imageMin = positions[min]; + const imageMid = positions[mid]; + const imageMax = positions[max]; + if (!imageMin || !imageMid || !imageMax) + return; + // We populate two paint arrays because, for cross-faded properties, we don't know which direction + // we're cross-fading to at layout time. In order to keep vertex attributes to a minimum and not pass + // unnecessary vertex data to the shaders, we determine which to upload at draw time. + for (let i = start; i < end; i++) { + this.zoomInPaintVertexArray.emplace(i, imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1], imageMin.tl[0], imageMin.tl[1], imageMin.br[0], imageMin.br[1], imageMid.pixelRatio, imageMin.pixelRatio); + this.zoomOutPaintVertexArray.emplace(i, imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1], imageMax.tl[0], imageMax.tl[1], imageMax.br[0], imageMax.br[1], imageMid.pixelRatio, imageMax.pixelRatio); + } + } + upload(context) { + if (this.zoomInPaintVertexArray && this.zoomInPaintVertexArray.arrayBuffer && this.zoomOutPaintVertexArray && this.zoomOutPaintVertexArray.arrayBuffer) { + this.zoomInPaintVertexBuffer = context.createVertexBuffer(this.zoomInPaintVertexArray, patternAttributes.members, this.expression.isStateDependent); + this.zoomOutPaintVertexBuffer = context.createVertexBuffer(this.zoomOutPaintVertexArray, patternAttributes.members, this.expression.isStateDependent); + } + } + destroy() { + if (this.zoomOutPaintVertexBuffer) + this.zoomOutPaintVertexBuffer.destroy(); + if (this.zoomInPaintVertexBuffer) + this.zoomInPaintVertexBuffer.destroy(); + } +} +/** + * @internal + * ProgramConfiguration contains the logic for binding style layer properties and tile + * layer feature data into GL program uniforms and vertex attributes. + * + * Non-data-driven property values are bound to shader uniforms. Data-driven property + * values are bound to vertex attributes. In order to support a uniform GLSL syntax over + * both, [Mapbox GL Shaders](https://github.com/mapbox/mapbox-gl-shaders) defines a `#pragma` + * abstraction, which ProgramConfiguration is responsible for implementing. At runtime, + * it examines the attributes of a particular layer, combines this with fixed knowledge + * about how layers of the particular type are implemented, and determines which uniforms + * and vertex attributes will be required. It can then substitute the appropriate text + * into the shader source code, create and link a program, and bind the uniforms and + * vertex attributes in preparation for drawing. + * + * When a vector tile is parsed, this same configuration information is used to + * populate the attribute buffers needed for data-driven styling using the zoom + * level and feature property data. + */ +class ProgramConfiguration { + constructor(layer, zoom, filterProperties) { + this.binders = {}; + this._buffers = []; + const keys = []; + for (const property in layer.paint._values) { + if (!filterProperties(property)) + continue; + const value = layer.paint.get(property); + if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) { + continue; + } + const names = paintAttributeNames(property, layer.type); + const expression = value.value; + const type = value.property.specification.type; + const useIntegerZoom = value.property.useIntegerZoom; + const propType = value.property.specification['property-type']; + const isCrossFaded = propType === 'cross-faded' || propType === 'cross-faded-data-driven'; + if (expression.kind === 'constant') { + this.binders[property] = isCrossFaded ? + new CrossFadedConstantBinder(expression.value, names) : + new ConstantBinder(expression.value, names, type); + keys.push(`/u_${property}`); + } + else if (expression.kind === 'source' || isCrossFaded) { + const StructArrayLayout = layoutType(property, type, 'source'); + this.binders[property] = isCrossFaded ? + new CrossFadedCompositeBinder(expression, type, useIntegerZoom, zoom, StructArrayLayout, layer.id) : + new SourceExpressionBinder(expression, names, type, StructArrayLayout); + keys.push(`/a_${property}`); + } + else { + const StructArrayLayout = layoutType(property, type, 'composite'); + this.binders[property] = new CompositeExpressionBinder(expression, names, type, useIntegerZoom, zoom, StructArrayLayout); + keys.push(`/z_${property}`); + } + } + this.cacheKey = keys.sort().join(''); + } + getMaxValue(property) { + const binder = this.binders[property]; + return binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder ? binder.maxValue : 0; + } + populatePaintArrays(newLength, feature, imagePositions, canonical, formattedSection) { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) + binder.populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection); + } + } + setConstantPatternPositions(posTo, posFrom) { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof CrossFadedConstantBinder) + binder.setConstantPatternPositions(posTo, posFrom); + } + } + updatePaintArrays(featureStates, featureMap, vtLayer, layer, imagePositions) { + let dirty = false; + for (const id in featureStates) { + const positions = featureMap.getPositions(id); + for (const pos of positions) { + const feature = vtLayer.feature(pos.index); + for (const property in this.binders) { + const binder = this.binders[property]; + if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || + binder instanceof CrossFadedCompositeBinder) && binder.expression.isStateDependent === true) { + //AHM: Remove after https://github.com/mapbox/mapbox-gl-js/issues/6255 + const value = layer.paint.get(property); + binder.expression = value.value; + binder.updatePaintArray(pos.start, pos.end, feature, featureStates[id], imagePositions); + dirty = true; + } + } + } + } + return dirty; + } + defines() { + const result = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder) { + result.push(...binder.uniformNames.map(name => `#define HAS_UNIFORM_${name}`)); + } + } + return result; + } + getBinderAttributes() { + const result = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) { + for (let i = 0; i < binder.paintVertexAttributes.length; i++) { + result.push(binder.paintVertexAttributes[i].name); + } + } + else if (binder instanceof CrossFadedCompositeBinder) { + for (let i = 0; i < patternAttributes.members.length; i++) { + result.push(patternAttributes.members[i].name); + } + } + } + return result; + } + getBinderUniforms() { + const uniforms = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) { + for (const uniformName of binder.uniformNames) { + uniforms.push(uniformName); + } + } + } + return uniforms; + } + getPaintVertexBuffers() { + return this._buffers; + } + getUniforms(context, locations) { + const uniforms = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) { + for (const name of binder.uniformNames) { + if (locations[name]) { + const binding = binder.getBinding(context, locations[name], name); + uniforms.push({ name, property, binding }); + } + } + } + } + return uniforms; + } + setUniforms(context, binderUniforms, properties, globals) { + // Uniform state bindings are owned by the Program, but we set them + // from within the ProgramConfiguration's binder members. + for (const { name, property, binding } of binderUniforms) { + this.binders[property].setUniform(binding, globals, properties.get(property), name); + } + } + updatePaintBuffers(crossfade) { + this._buffers = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (crossfade && binder instanceof CrossFadedCompositeBinder) { + const patternVertexBuffer = crossfade.fromScale === 2 ? binder.zoomInPaintVertexBuffer : binder.zoomOutPaintVertexBuffer; + if (patternVertexBuffer) + this._buffers.push(patternVertexBuffer); + } + else if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) && binder.paintVertexBuffer) { + this._buffers.push(binder.paintVertexBuffer); + } + } + } + upload(context) { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) + binder.upload(context); + } + this.updatePaintBuffers(); + } + destroy() { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) + binder.destroy(); + } + } +} +class ProgramConfigurationSet { + constructor(layers, zoom, filterProperties = () => true) { + this.programConfigurations = {}; + for (const layer of layers) { + this.programConfigurations[layer.id] = new ProgramConfiguration(layer, zoom, filterProperties); + } + this.needsUpload = false; + this._featureMap = new FeaturePositionMap(); + this._bufferOffset = 0; + } + populatePaintArrays(length, feature, index, imagePositions, canonical, formattedSection) { + for (const key in this.programConfigurations) { + this.programConfigurations[key].populatePaintArrays(length, feature, imagePositions, canonical, formattedSection); + } + if (feature.id !== undefined) { + this._featureMap.add(feature.id, index, this._bufferOffset, length); + } + this._bufferOffset = length; + this.needsUpload = true; + } + updatePaintArrays(featureStates, vtLayer, layers, imagePositions) { + for (const layer of layers) { + this.needsUpload = this.programConfigurations[layer.id].updatePaintArrays(featureStates, this._featureMap, vtLayer, layer, imagePositions) || this.needsUpload; + } + } + get(layerId) { + return this.programConfigurations[layerId]; + } + upload(context) { + if (!this.needsUpload) + return; + for (const layerId in this.programConfigurations) { + this.programConfigurations[layerId].upload(context); + } + this.needsUpload = false; + } + destroy() { + for (const layerId in this.programConfigurations) { + this.programConfigurations[layerId].destroy(); + } + } +} +function paintAttributeNames(property, type) { + const attributeNameExceptions = { + 'text-opacity': ['opacity'], + 'icon-opacity': ['opacity'], + 'text-color': ['fill_color'], + 'icon-color': ['fill_color'], + 'text-halo-color': ['halo_color'], + 'icon-halo-color': ['halo_color'], + 'text-halo-blur': ['halo_blur'], + 'icon-halo-blur': ['halo_blur'], + 'text-halo-width': ['halo_width'], + 'icon-halo-width': ['halo_width'], + 'line-gap-width': ['gapwidth'], + 'line-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'], + 'fill-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'], + 'fill-extrusion-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'], + }; + return attributeNameExceptions[property] || [property.replace(`${type}-`, '').replace(/-/g, '_')]; +} +function getLayoutException(property) { + const propertyExceptions = { + 'line-pattern': { + 'source': PatternLayoutArray, + 'composite': PatternLayoutArray + }, + 'fill-pattern': { + 'source': PatternLayoutArray, + 'composite': PatternLayoutArray + }, + 'fill-extrusion-pattern': { + 'source': PatternLayoutArray, + 'composite': PatternLayoutArray + } + }; + return propertyExceptions[property]; +} +function layoutType(property, type, binderType) { + const defaultLayouts = { + 'color': { + 'source': StructArrayLayout2f8, + 'composite': StructArrayLayout4f16 + }, + 'number': { + 'source': StructArrayLayout1f4, + 'composite': StructArrayLayout2f8 + } + }; + const layoutException = getLayoutException(property); + return layoutException && layoutException[binderType] || defaultLayouts[type][binderType]; +} +register('ConstantBinder', ConstantBinder); +register('CrossFadedConstantBinder', CrossFadedConstantBinder); +register('SourceExpressionBinder', SourceExpressionBinder); +register('CrossFadedCompositeBinder', CrossFadedCompositeBinder); +register('CompositeExpressionBinder', CompositeExpressionBinder); +register('ProgramConfiguration', ProgramConfiguration, { omit: ['_buffers'] }); +register('ProgramConfigurationSet', ProgramConfigurationSet); + +/** + * The maximum value of a coordinate in the internal tile coordinate system. Coordinates of + * all source features normalized to this extent upon load. + * + * The value is a consequence of the following: + * + * * Vertex buffer store positions as signed 16 bit integers. + * * One bit is lost for signedness to support tile buffers. + * * One bit is lost because the line vertex buffer used to pack 1 bit of other data into the int. + * * One bit is lost to support features extending past the extent on the right edge of the tile. + * * This leaves us with 2^13 = 8192 + */ +const EXTENT = 8192; + +// These bounds define the minimum and maximum supported coordinate values. +// While visible coordinates are within [0, EXTENT], tiles may theoretically +// contain coordinates within [-Infinity, Infinity]. Our range is limited by the +// number of bits used to represent the coordinate. +const BITS = 15; +const MAX = Math.pow(2, BITS - 1) - 1; +const MIN = -MAX - 1; +/** + * Loads a geometry from a VectorTileFeature and scales it to the common extent + * used internally. + * @param feature - the vector tile feature to load + */ +function loadGeometry(feature) { + const scale = EXTENT / feature.extent; + const geometry = feature.loadGeometry(); + for (let r = 0; r < geometry.length; r++) { + const ring = geometry[r]; + for (let p = 0; p < ring.length; p++) { + const point = ring[p]; + // round here because mapbox-gl-native uses integers to represent + // points and we need to do the same to avoid renering differences. + const x = Math.round(point.x * scale); + const y = Math.round(point.y * scale); + point.x = clamp$1(x, MIN, MAX); + point.y = clamp$1(y, MIN, MAX); + if (x < point.x || x > point.x + 1 || y < point.y || y > point.y + 1) { + // warn when exceeding allowed extent except for the 1-px-off case + // https://github.com/mapbox/mapbox-gl-js/issues/8992 + warnOnce('Geometry exceeds allowed extent, reduce your vector tile buffer size'); + } + } + } + return geometry; +} + +/** + * Construct a new feature based on a VectorTileFeature for expression evaluation, the geometry of which + * will be loaded based on necessity. + * @param feature - the feature to evaluate + * @param needGeometry - if set to true this will load the geometry + */ +function toEvaluationFeature(feature, needGeometry) { + return { type: feature.type, + id: feature.id, + properties: feature.properties, + geometry: needGeometry ? loadGeometry(feature) : [] }; +} + +function addCircleVertex(layoutVertexArray, x, y, extrudeX, extrudeY) { + layoutVertexArray.emplaceBack((x * 2) + ((extrudeX + 1) / 2), (y * 2) + ((extrudeY + 1) / 2)); +} +/** + * @internal + * Circles are represented by two triangles. + * + * Each corner has a pos that is the center of the circle and an extrusion + * vector that is where it points. + */ +class CircleBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.layoutVertexArray = new CircleLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.segments = new SegmentVector(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + const styleLayer = this.layers[0]; + const bucketFeatures = []; + let circleSortKey = null; + let sortFeaturesByKey = false; + // Heatmap layers are handled in this bucket and have no evaluated properties, so we check our access + if (styleLayer.type === 'circle') { + circleSortKey = styleLayer.layout.get('circle-sort-key'); + sortFeaturesByKey = !circleSortKey.isConstant(); + } + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const sortKey = sortFeaturesByKey ? + circleSortKey.evaluate(evaluationFeature, {}, canonical) : + undefined; + const bucketFeature = { + id, + properties: feature.properties, + type: feature.type, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + patterns: {}, + sortKey + }; + bucketFeatures.push(bucketFeature); + } + if (sortFeaturesByKey) { + bucketFeatures.sort((a, b) => a.sortKey - b.sortKey); + } + for (const bucketFeature of bucketFeatures) { + const { geometry, index, sourceLayerIndex } = bucketFeature; + const feature = features[index].feature; + this.addFeature(bucketFeature, geometry, index, canonical); + options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + isEmpty() { + return this.layoutVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$4); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + } + addFeature(feature, geometry, index, canonical) { + for (const ring of geometry) { + for (const point of ring) { + const x = point.x; + const y = point.y; + // Do not include points that are outside the tile boundaries. + if (x < 0 || x >= EXTENT || y < 0 || y >= EXTENT) + continue; + // this geometry will be of the Point type, and we'll derive + // two triangles from it. + // + // ┌─────────┐ + // │ 3 2 │ + // │ │ + // │ 0 1 │ + // └─────────┘ + const segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray, feature.sortKey); + const index = segment.vertexLength; + addCircleVertex(this.layoutVertexArray, x, y, -1, -1); + addCircleVertex(this.layoutVertexArray, x, y, 1, -1); + addCircleVertex(this.layoutVertexArray, x, y, 1, 1); + addCircleVertex(this.layoutVertexArray, x, y, -1, 1); + this.indexArray.emplaceBack(index, index + 1, index + 2); + this.indexArray.emplaceBack(index, index + 3, index + 2); + segment.vertexLength += 4; + segment.primitiveLength += 2; + } + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, {}, canonical); + } +} +register('CircleBucket', CircleBucket, { omit: ['layers'] }); + +function polygonIntersectsPolygon(polygonA, polygonB) { + for (let i = 0; i < polygonA.length; i++) { + if (polygonContainsPoint(polygonB, polygonA[i])) + return true; + } + for (let i = 0; i < polygonB.length; i++) { + if (polygonContainsPoint(polygonA, polygonB[i])) + return true; + } + if (lineIntersectsLine(polygonA, polygonB)) + return true; + return false; +} +function polygonIntersectsBufferedPoint(polygon, point, radius) { + if (polygonContainsPoint(polygon, point)) + return true; + if (pointIntersectsBufferedLine(point, polygon, radius)) + return true; + return false; +} +function polygonIntersectsMultiPolygon(polygon, multiPolygon) { + if (polygon.length === 1) { + return multiPolygonContainsPoint(multiPolygon, polygon[0]); + } + for (let m = 0; m < multiPolygon.length; m++) { + const ring = multiPolygon[m]; + for (let n = 0; n < ring.length; n++) { + if (polygonContainsPoint(polygon, ring[n])) + return true; + } + } + for (let i = 0; i < polygon.length; i++) { + if (multiPolygonContainsPoint(multiPolygon, polygon[i])) + return true; + } + for (let k = 0; k < multiPolygon.length; k++) { + if (lineIntersectsLine(polygon, multiPolygon[k])) + return true; + } + return false; +} +function polygonIntersectsBufferedMultiLine(polygon, multiLine, radius) { + for (let i = 0; i < multiLine.length; i++) { + const line = multiLine[i]; + if (polygon.length >= 3) { + for (let k = 0; k < line.length; k++) { + if (polygonContainsPoint(polygon, line[k])) + return true; + } + } + if (lineIntersectsBufferedLine(polygon, line, radius)) + return true; + } + return false; +} +function lineIntersectsBufferedLine(lineA, lineB, radius) { + if (lineA.length > 1) { + if (lineIntersectsLine(lineA, lineB)) + return true; + // Check whether any point in either line is within radius of the other line + for (let j = 0; j < lineB.length; j++) { + if (pointIntersectsBufferedLine(lineB[j], lineA, radius)) + return true; + } + } + for (let k = 0; k < lineA.length; k++) { + if (pointIntersectsBufferedLine(lineA[k], lineB, radius)) + return true; + } + return false; +} +function lineIntersectsLine(lineA, lineB) { + if (lineA.length === 0 || lineB.length === 0) + return false; + for (let i = 0; i < lineA.length - 1; i++) { + const a0 = lineA[i]; + const a1 = lineA[i + 1]; + for (let j = 0; j < lineB.length - 1; j++) { + const b0 = lineB[j]; + const b1 = lineB[j + 1]; + if (lineSegmentIntersectsLineSegment(a0, a1, b0, b1)) + return true; + } + } + return false; +} +function lineSegmentIntersectsLineSegment(a0, a1, b0, b1) { + return isCounterClockwise(a0, b0, b1) !== isCounterClockwise(a1, b0, b1) && + isCounterClockwise(a0, a1, b0) !== isCounterClockwise(a0, a1, b1); +} +function pointIntersectsBufferedLine(p, line, radius) { + const radiusSquared = radius * radius; + if (line.length === 1) + return p.distSqr(line[0]) < radiusSquared; + for (let i = 1; i < line.length; i++) { + // Find line segments that have a distance <= radius^2 to p + // In that case, we treat the line as "containing point p". + const v = line[i - 1], w = line[i]; + if (distToSegmentSquared(p, v, w) < radiusSquared) + return true; + } + return false; +} +// Code from https://stackoverflow.com/a/1501725/331379. +function distToSegmentSquared(p, v, w) { + const l2 = v.distSqr(w); + if (l2 === 0) + return p.distSqr(v); + const t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2; + if (t < 0) + return p.distSqr(v); + if (t > 1) + return p.distSqr(w); + return p.distSqr(w.sub(v)._mult(t)._add(v)); +} +// point in polygon ray casting algorithm +function multiPolygonContainsPoint(rings, p) { + let c = false, ring, p1, p2; + for (let k = 0; k < rings.length; k++) { + ring = rings[k]; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + 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)) { + c = !c; + } + } + } + return c; +} +function polygonContainsPoint(ring, p) { + let c = false; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const p1 = ring[i]; + const p2 = ring[j]; + 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)) { + c = !c; + } + } + return c; +} +function polygonIntersectsBox(ring, boxX1, boxY1, boxX2, boxY2) { + for (const p of ring) { + if (boxX1 <= p.x && + boxY1 <= p.y && + boxX2 >= p.x && + boxY2 >= p.y) + return true; + } + const corners = [ + new Point$2(boxX1, boxY1), + new Point$2(boxX1, boxY2), + new Point$2(boxX2, boxY2), + new Point$2(boxX2, boxY1) + ]; + if (ring.length > 2) { + for (const corner of corners) { + if (polygonContainsPoint(ring, corner)) + return true; + } + } + for (let i = 0; i < ring.length - 1; i++) { + const p1 = ring[i]; + const p2 = ring[i + 1]; + if (edgeIntersectsBox(p1, p2, corners)) + return true; + } + return false; +} +function edgeIntersectsBox(e1, e2, corners) { + const tl = corners[0]; + const br = corners[2]; + // the edge and box do not intersect in either the x or y dimensions + if (((e1.x < tl.x) && (e2.x < tl.x)) || + ((e1.x > br.x) && (e2.x > br.x)) || + ((e1.y < tl.y) && (e2.y < tl.y)) || + ((e1.y > br.y) && (e2.y > br.y))) + return false; + // check if all corners of the box are on the same side of the edge + const dir = isCounterClockwise(e1, e2, corners[0]); + return dir !== isCounterClockwise(e1, e2, corners[1]) || + dir !== isCounterClockwise(e1, e2, corners[2]) || + dir !== isCounterClockwise(e1, e2, corners[3]); +} + +function getMaximumPaintValue(property, layer, bucket) { + const value = layer.paint.get(property).value; + if (value.kind === 'constant') { + return value.value; + } + else { + return bucket.programConfigurations.get(layer.id).getMaxValue(property); + } +} +function translateDistance(translate) { + return Math.sqrt(translate[0] * translate[0] + translate[1] * translate[1]); +} +function translate$4(queryGeometry, translate, translateAnchor, bearing, pixelsToTileUnits) { + if (!translate[0] && !translate[1]) { + return queryGeometry; + } + const pt = Point$2.convert(translate)._mult(pixelsToTileUnits); + if (translateAnchor === 'viewport') { + pt._rotate(-bearing); + } + const translated = []; + for (let i = 0; i < queryGeometry.length; i++) { + const point = queryGeometry[i]; + translated.push(point.sub(pt)); + } + return translated; +} +function offsetLine(rings, offset) { + const newRings = []; + for (let ringIndex = 0; ringIndex < rings.length; ringIndex++) { + const ring = rings[ringIndex]; + const newRing = []; + for (let index = 0; index < ring.length; index++) { + const a = ring[index - 1]; + const b = ring[index]; + const c = ring[index + 1]; + const aToB = index === 0 ? new Point$2(0, 0) : b.sub(a)._unit()._perp(); + const bToC = index === ring.length - 1 ? new Point$2(0, 0) : c.sub(b)._unit()._perp(); + const extrude = aToB._add(bToC)._unit(); + const cosHalfAngle = extrude.x * bToC.x + extrude.y * bToC.y; + if (cosHalfAngle !== 0) { + extrude._mult(1 / cosHalfAngle); + } + newRing.push(extrude._mult(offset)._add(b)); + } + newRings.push(newRing); + } + return newRings; +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout$5; +const getLayout$3 = () => layout$5 = layout$5 || new Properties({ + "circle-sort-key": new DataDrivenProperty(v8Spec["layout_circle"]["circle-sort-key"]), +}); +let paint$8; +const getPaint$8 = () => paint$8 = paint$8 || new Properties({ + "circle-radius": new DataDrivenProperty(v8Spec["paint_circle"]["circle-radius"]), + "circle-color": new DataDrivenProperty(v8Spec["paint_circle"]["circle-color"]), + "circle-blur": new DataDrivenProperty(v8Spec["paint_circle"]["circle-blur"]), + "circle-opacity": new DataDrivenProperty(v8Spec["paint_circle"]["circle-opacity"]), + "circle-translate": new DataConstantProperty(v8Spec["paint_circle"]["circle-translate"]), + "circle-translate-anchor": new DataConstantProperty(v8Spec["paint_circle"]["circle-translate-anchor"]), + "circle-pitch-scale": new DataConstantProperty(v8Spec["paint_circle"]["circle-pitch-scale"]), + "circle-pitch-alignment": new DataConstantProperty(v8Spec["paint_circle"]["circle-pitch-alignment"]), + "circle-stroke-width": new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-width"]), + "circle-stroke-color": new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-color"]), + "circle-stroke-opacity": new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-opacity"]), +}); +var properties$9 = ({ get paint() { return getPaint$8(); }, get layout() { return getLayout$3(); } }); + +/** + * Common utilities + * @module glMatrix + */ +// Configuration Constants +var EPSILON = 0.000001; +var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; +var RANDOM = Math.random; +/** + * Sets the type of array used when creating new vectors and matrices + * + * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array + */ + +function setMatrixArrayType(type) { + ARRAY_TYPE = type; +} +var degree = Math.PI / 180; +/** + * Convert Degree To Radian + * + * @param {Number} a Angle in Degrees + */ + +function toRadian(a) { + return a * degree; +} +/** + * Tests whether or not the arguments have approximately the same value, within an absolute + * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less + * than or equal to 1.0, and a relative tolerance is used for larger values) + * + * @param {Number} a The first number to test. + * @param {Number} b The second number to test. + * @returns {Boolean} True if the numbers are approximately equal, false otherwise. + */ + +function equals$a(a, b) { + return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b)); +} +if (!Math.hypot) Math.hypot = function () { + var y = 0, + i = arguments.length; + + while (i--) { + y += arguments[i] * arguments[i]; + } + + return Math.sqrt(y); +}; + +var common = /*#__PURE__*/Object.freeze({ +__proto__: null, +get ARRAY_TYPE () { return ARRAY_TYPE; }, +EPSILON: EPSILON, +RANDOM: RANDOM, +equals: equals$a, +setMatrixArrayType: setMatrixArrayType, +toRadian: toRadian +}); + +/** + * 2x2 Matrix + * @module mat2 + */ + +/** + * Creates a new identity mat2 + * + * @returns {mat2} a new 2x2 matrix + */ + +function create$9() { + var out = new ARRAY_TYPE(4); + + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + } + + out[0] = 1; + out[3] = 1; + return out; +} +/** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param {ReadonlyMat2} a matrix to clone + * @returns {mat2} a new 2x2 matrix + */ + +function clone$8(a) { + var out = new ARRAY_TYPE(4); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +} +/** + * Copy the values from one mat2 to another + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the source matrix + * @returns {mat2} out + */ + +function copy$8(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +} +/** + * Set a mat2 to the identity matrix + * + * @param {mat2} out the receiving matrix + * @returns {mat2} out + */ + +function identity$5(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +} +/** + * Create a new mat2 with the given values + * + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m10 Component in column 1, row 0 position (index 2) + * @param {Number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out A new 2x2 matrix + */ + +function fromValues$8(m00, m01, m10, m11) { + var out = new ARRAY_TYPE(4); + out[0] = m00; + out[1] = m01; + out[2] = m10; + out[3] = m11; + return out; +} +/** + * Set the components of a mat2 to the given values + * + * @param {mat2} out the receiving matrix + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m10 Component in column 1, row 0 position (index 2) + * @param {Number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out + */ + +function set$8(out, m00, m01, m10, m11) { + out[0] = m00; + out[1] = m01; + out[2] = m10; + out[3] = m11; + return out; +} +/** + * Transpose the values of a mat2 + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the source matrix + * @returns {mat2} out + */ + +function transpose$2(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache + // some values + if (out === a) { + var a1 = a[1]; + out[1] = a[2]; + out[2] = a1; + } else { + out[0] = a[0]; + out[1] = a[2]; + out[2] = a[1]; + out[3] = a[3]; + } + + return out; +} +/** + * Inverts a mat2 + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the source matrix + * @returns {mat2} out + */ + +function invert$5(out, a) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; // Calculate the determinant + + var det = a0 * a3 - a2 * a1; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = a3 * det; + out[1] = -a1 * det; + out[2] = -a2 * det; + out[3] = a0 * det; + return out; +} +/** + * Calculates the adjugate of a mat2 + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the source matrix + * @returns {mat2} out + */ + +function adjoint$2(out, a) { + // Caching this value is nessecary if out == a + var a0 = a[0]; + out[0] = a[3]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = a0; + return out; +} +/** + * Calculates the determinant of a mat2 + * + * @param {ReadonlyMat2} a the source matrix + * @returns {Number} determinant of a + */ + +function determinant$3(a) { + return a[0] * a[3] - a[2] * a[1]; +} +/** + * Multiplies two mat2's + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the first operand + * @param {ReadonlyMat2} b the second operand + * @returns {mat2} out + */ + +function multiply$8(out, a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + out[0] = a0 * b0 + a2 * b1; + out[1] = a1 * b0 + a3 * b1; + out[2] = a0 * b2 + a2 * b3; + out[3] = a1 * b2 + a3 * b3; + return out; +} +/** + * Rotates a mat2 by the given angle + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + +function rotate$4(out, a, rad) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var s = Math.sin(rad); + var c = Math.cos(rad); + out[0] = a0 * c + a2 * s; + out[1] = a1 * c + a3 * s; + out[2] = a0 * -s + a2 * c; + out[3] = a1 * -s + a3 * c; + return out; +} +/** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the matrix to rotate + * @param {ReadonlyVec2} v the vec2 to scale the matrix by + * @returns {mat2} out + **/ + +function scale$8(out, a, v) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var v0 = v[0], + v1 = v[1]; + out[0] = a0 * v0; + out[1] = a1 * v0; + out[2] = a2 * v1; + out[3] = a3 * v1; + return out; +} +/** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.rotate(dest, dest, rad); + * + * @param {mat2} out mat2 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + +function fromRotation$4(out, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + out[0] = c; + out[1] = s; + out[2] = -s; + out[3] = c; + return out; +} +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.scale(dest, dest, vec); + * + * @param {mat2} out mat2 receiving operation result + * @param {ReadonlyVec2} v Scaling vector + * @returns {mat2} out + */ + +function fromScaling$3(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = v[1]; + return out; +} +/** + * Returns a string representation of a mat2 + * + * @param {ReadonlyMat2} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ + +function str$8(a) { + return "mat2(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ")"; +} +/** + * Returns Frobenius norm of a mat2 + * + * @param {ReadonlyMat2} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ + +function frob$3(a) { + return Math.hypot(a[0], a[1], a[2], a[3]); +} +/** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param {ReadonlyMat2} L the lower triangular matrix + * @param {ReadonlyMat2} D the diagonal matrix + * @param {ReadonlyMat2} U the upper triangular matrix + * @param {ReadonlyMat2} a the input matrix to factorize + */ + +function LDU(L, D, U, a) { + L[2] = a[2] / a[0]; + U[0] = a[0]; + U[1] = a[1]; + U[3] = a[3] - L[2] * U[1]; + return [L, D, U]; +} +/** + * Adds two mat2's + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the first operand + * @param {ReadonlyMat2} b the second operand + * @returns {mat2} out + */ + +function add$8(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + return out; +} +/** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the first operand + * @param {ReadonlyMat2} b the second operand + * @returns {mat2} out + */ + +function subtract$6(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + return out; +} +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyMat2} a The first matrix. + * @param {ReadonlyMat2} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function exactEquals$8(a, b) { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3]; +} +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {ReadonlyMat2} a The first matrix. + * @param {ReadonlyMat2} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function equals$9(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)); +} +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat2} out + */ + +function multiplyScalar$3(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + return out; +} +/** + * Adds two mat2's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2} out the receiving vector + * @param {ReadonlyMat2} a the first operand + * @param {ReadonlyMat2} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat2} out + */ + +function multiplyScalarAndAdd$3(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + return out; +} +/** + * Alias for {@link mat2.multiply} + * @function + */ + +var mul$8 = multiply$8; +/** + * Alias for {@link mat2.subtract} + * @function + */ + +var sub$6 = subtract$6; + +var mat2 = /*#__PURE__*/Object.freeze({ +__proto__: null, +LDU: LDU, +add: add$8, +adjoint: adjoint$2, +clone: clone$8, +copy: copy$8, +create: create$9, +determinant: determinant$3, +equals: equals$9, +exactEquals: exactEquals$8, +frob: frob$3, +fromRotation: fromRotation$4, +fromScaling: fromScaling$3, +fromValues: fromValues$8, +identity: identity$5, +invert: invert$5, +mul: mul$8, +multiply: multiply$8, +multiplyScalar: multiplyScalar$3, +multiplyScalarAndAdd: multiplyScalarAndAdd$3, +rotate: rotate$4, +scale: scale$8, +set: set$8, +str: str$8, +sub: sub$6, +subtract: subtract$6, +transpose: transpose$2 +}); + +/** + * 2x3 Matrix + * @module mat2d + * @description + * A mat2d contains six elements defined as: + *
+ * [a, b,
+ *  c, d,
+ *  tx, ty]
+ * 
+ * This is a short form for the 3x3 matrix: + *
+ * [a, b, 0,
+ *  c, d, 0,
+ *  tx, ty, 1]
+ * 
+ * The last column is ignored so the array is shorter and operations are faster. + */ + +/** + * Creates a new identity mat2d + * + * @returns {mat2d} a new 2x3 matrix + */ + +function create$8() { + var out = new ARRAY_TYPE(6); + + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + out[4] = 0; + out[5] = 0; + } + + out[0] = 1; + out[3] = 1; + return out; +} +/** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param {ReadonlyMat2d} a matrix to clone + * @returns {mat2d} a new 2x3 matrix + */ + +function clone$7(a) { + var out = new ARRAY_TYPE(6); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + return out; +} +/** + * Copy the values from one mat2d to another + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the source matrix + * @returns {mat2d} out + */ + +function copy$7(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + return out; +} +/** + * Set a mat2d to the identity matrix + * + * @param {mat2d} out the receiving matrix + * @returns {mat2d} out + */ + +function identity$4(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = 0; + out[5] = 0; + return out; +} +/** + * Create a new mat2d with the given values + * + * @param {Number} a Component A (index 0) + * @param {Number} b Component B (index 1) + * @param {Number} c Component C (index 2) + * @param {Number} d Component D (index 3) + * @param {Number} tx Component TX (index 4) + * @param {Number} ty Component TY (index 5) + * @returns {mat2d} A new mat2d + */ + +function fromValues$7(a, b, c, d, tx, ty) { + var out = new ARRAY_TYPE(6); + out[0] = a; + out[1] = b; + out[2] = c; + out[3] = d; + out[4] = tx; + out[5] = ty; + return out; +} +/** + * Set the components of a mat2d to the given values + * + * @param {mat2d} out the receiving matrix + * @param {Number} a Component A (index 0) + * @param {Number} b Component B (index 1) + * @param {Number} c Component C (index 2) + * @param {Number} d Component D (index 3) + * @param {Number} tx Component TX (index 4) + * @param {Number} ty Component TY (index 5) + * @returns {mat2d} out + */ + +function set$7(out, a, b, c, d, tx, ty) { + out[0] = a; + out[1] = b; + out[2] = c; + out[3] = d; + out[4] = tx; + out[5] = ty; + return out; +} +/** + * Inverts a mat2d + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the source matrix + * @returns {mat2d} out + */ + +function invert$4(out, a) { + var aa = a[0], + ab = a[1], + ac = a[2], + ad = a[3]; + var atx = a[4], + aty = a[5]; + var det = aa * ad - ab * ac; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = ad * det; + out[1] = -ab * det; + out[2] = -ac * det; + out[3] = aa * det; + out[4] = (ac * aty - ad * atx) * det; + out[5] = (ab * atx - aa * aty) * det; + return out; +} +/** + * Calculates the determinant of a mat2d + * + * @param {ReadonlyMat2d} a the source matrix + * @returns {Number} determinant of a + */ + +function determinant$2(a) { + return a[0] * a[3] - a[1] * a[2]; +} +/** + * Multiplies two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the first operand + * @param {ReadonlyMat2d} b the second operand + * @returns {mat2d} out + */ + +function multiply$7(out, a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5]; + out[0] = a0 * b0 + a2 * b1; + out[1] = a1 * b0 + a3 * b1; + out[2] = a0 * b2 + a2 * b3; + out[3] = a1 * b2 + a3 * b3; + out[4] = a0 * b4 + a2 * b5 + a4; + out[5] = a1 * b4 + a3 * b5 + a5; + return out; +} +/** + * Rotates a mat2d by the given angle + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + +function rotate$3(out, a, rad) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var s = Math.sin(rad); + var c = Math.cos(rad); + out[0] = a0 * c + a2 * s; + out[1] = a1 * c + a3 * s; + out[2] = a0 * -s + a2 * c; + out[3] = a1 * -s + a3 * c; + out[4] = a4; + out[5] = a5; + return out; +} +/** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to translate + * @param {ReadonlyVec2} v the vec2 to scale the matrix by + * @returns {mat2d} out + **/ + +function scale$7(out, a, v) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var v0 = v[0], + v1 = v[1]; + out[0] = a0 * v0; + out[1] = a1 * v0; + out[2] = a2 * v1; + out[3] = a3 * v1; + out[4] = a4; + out[5] = a5; + return out; +} +/** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to translate + * @param {ReadonlyVec2} v the vec2 to translate the matrix by + * @returns {mat2d} out + **/ + +function translate$3(out, a, v) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var v0 = v[0], + v1 = v[1]; + out[0] = a0; + out[1] = a1; + out[2] = a2; + out[3] = a3; + out[4] = a0 * v0 + a2 * v1 + a4; + out[5] = a1 * v0 + a3 * v1 + a5; + return out; +} +/** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.rotate(dest, dest, rad); + * + * @param {mat2d} out mat2d receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + +function fromRotation$3(out, rad) { + var s = Math.sin(rad), + c = Math.cos(rad); + out[0] = c; + out[1] = s; + out[2] = -s; + out[3] = c; + out[4] = 0; + out[5] = 0; + return out; +} +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.scale(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {ReadonlyVec2} v Scaling vector + * @returns {mat2d} out + */ + +function fromScaling$2(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = v[1]; + out[4] = 0; + out[5] = 0; + return out; +} +/** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.translate(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {ReadonlyVec2} v Translation vector + * @returns {mat2d} out + */ + +function fromTranslation$3(out, v) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = v[0]; + out[5] = v[1]; + return out; +} +/** + * Returns a string representation of a mat2d + * + * @param {ReadonlyMat2d} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ + +function str$7(a) { + return "mat2d(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ")"; +} +/** + * Returns Frobenius norm of a mat2d + * + * @param {ReadonlyMat2d} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ + +function frob$2(a) { + return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], 1); +} +/** + * Adds two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the first operand + * @param {ReadonlyMat2d} b the second operand + * @returns {mat2d} out + */ + +function add$7(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + out[4] = a[4] + b[4]; + out[5] = a[5] + b[5]; + return out; +} +/** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the first operand + * @param {ReadonlyMat2d} b the second operand + * @returns {mat2d} out + */ + +function subtract$5(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + out[4] = a[4] - b[4]; + out[5] = a[5] - b[5]; + return out; +} +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat2d} out + */ + +function multiplyScalar$2(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + out[4] = a[4] * b; + out[5] = a[5] * b; + return out; +} +/** + * Adds two mat2d's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2d} out the receiving vector + * @param {ReadonlyMat2d} a the first operand + * @param {ReadonlyMat2d} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat2d} out + */ + +function multiplyScalarAndAdd$2(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + out[4] = a[4] + b[4] * scale; + out[5] = a[5] + b[5] * scale; + return out; +} +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyMat2d} a The first matrix. + * @param {ReadonlyMat2d} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function exactEquals$7(a, b) { + 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]; +} +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {ReadonlyMat2d} a The first matrix. + * @param {ReadonlyMat2d} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function equals$8(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)); +} +/** + * Alias for {@link mat2d.multiply} + * @function + */ + +var mul$7 = multiply$7; +/** + * Alias for {@link mat2d.subtract} + * @function + */ + +var sub$5 = subtract$5; + +var mat2d = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$7, +clone: clone$7, +copy: copy$7, +create: create$8, +determinant: determinant$2, +equals: equals$8, +exactEquals: exactEquals$7, +frob: frob$2, +fromRotation: fromRotation$3, +fromScaling: fromScaling$2, +fromTranslation: fromTranslation$3, +fromValues: fromValues$7, +identity: identity$4, +invert: invert$4, +mul: mul$7, +multiply: multiply$7, +multiplyScalar: multiplyScalar$2, +multiplyScalarAndAdd: multiplyScalarAndAdd$2, +rotate: rotate$3, +scale: scale$7, +set: set$7, +str: str$7, +sub: sub$5, +subtract: subtract$5, +translate: translate$3 +}); + +/** + * 3x3 Matrix + * @module mat3 + */ + +/** + * Creates a new identity mat3 + * + * @returns {mat3} a new 3x3 matrix + */ + +function create$7() { + var out = new ARRAY_TYPE(9); + + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[5] = 0; + out[6] = 0; + out[7] = 0; + } + + out[0] = 1; + out[4] = 1; + out[8] = 1; + return out; +} +/** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {ReadonlyMat4} a the source 4x4 matrix + * @returns {mat3} out + */ + +function fromMat4$1(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[4]; + out[4] = a[5]; + out[5] = a[6]; + out[6] = a[8]; + out[7] = a[9]; + out[8] = a[10]; + return out; +} +/** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param {ReadonlyMat3} a matrix to clone + * @returns {mat3} a new 3x3 matrix + */ + +function clone$6(a) { + var out = new ARRAY_TYPE(9); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +} +/** + * Copy the values from one mat3 to another + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the source matrix + * @returns {mat3} out + */ + +function copy$6(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +} +/** + * Create a new mat3 with the given values + * + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m10 Component in column 1, row 0 position (index 3) + * @param {Number} m11 Component in column 1, row 1 position (index 4) + * @param {Number} m12 Component in column 1, row 2 position (index 5) + * @param {Number} m20 Component in column 2, row 0 position (index 6) + * @param {Number} m21 Component in column 2, row 1 position (index 7) + * @param {Number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} A new mat3 + */ + +function fromValues$6(m00, m01, m02, m10, m11, m12, m20, m21, m22) { + var out = new ARRAY_TYPE(9); + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m10; + out[4] = m11; + out[5] = m12; + out[6] = m20; + out[7] = m21; + out[8] = m22; + return out; +} +/** + * Set the components of a mat3 to the given values + * + * @param {mat3} out the receiving matrix + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m10 Component in column 1, row 0 position (index 3) + * @param {Number} m11 Component in column 1, row 1 position (index 4) + * @param {Number} m12 Component in column 1, row 2 position (index 5) + * @param {Number} m20 Component in column 2, row 0 position (index 6) + * @param {Number} m21 Component in column 2, row 1 position (index 7) + * @param {Number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} out + */ + +function set$6(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) { + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m10; + out[4] = m11; + out[5] = m12; + out[6] = m20; + out[7] = m21; + out[8] = m22; + return out; +} +/** + * Set a mat3 to the identity matrix + * + * @param {mat3} out the receiving matrix + * @returns {mat3} out + */ + +function identity$3(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 1; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +} +/** + * Transpose the values of a mat3 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the source matrix + * @returns {mat3} out + */ + +function transpose$1(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a[1], + a02 = a[2], + a12 = a[5]; + out[1] = a[3]; + out[2] = a[6]; + out[3] = a01; + out[5] = a[7]; + out[6] = a02; + out[7] = a12; + } else { + out[0] = a[0]; + out[1] = a[3]; + out[2] = a[6]; + out[3] = a[1]; + out[4] = a[4]; + out[5] = a[7]; + out[6] = a[2]; + out[7] = a[5]; + out[8] = a[8]; + } + + return out; +} +/** + * Inverts a mat3 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the source matrix + * @returns {mat3} out + */ + +function invert$3(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2]; + var a10 = a[3], + a11 = a[4], + a12 = a[5]; + var a20 = a[6], + a21 = a[7], + a22 = a[8]; + var b01 = a22 * a11 - a12 * a21; + var b11 = -a22 * a10 + a12 * a20; + var b21 = a21 * a10 - a11 * a20; // Calculate the determinant + + var det = a00 * b01 + a01 * b11 + a02 * b21; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = b01 * det; + out[1] = (-a22 * a01 + a02 * a21) * det; + out[2] = (a12 * a01 - a02 * a11) * det; + out[3] = b11 * det; + out[4] = (a22 * a00 - a02 * a20) * det; + out[5] = (-a12 * a00 + a02 * a10) * det; + out[6] = b21 * det; + out[7] = (-a21 * a00 + a01 * a20) * det; + out[8] = (a11 * a00 - a01 * a10) * det; + return out; +} +/** + * Calculates the adjugate of a mat3 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the source matrix + * @returns {mat3} out + */ + +function adjoint$1(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2]; + var a10 = a[3], + a11 = a[4], + a12 = a[5]; + var a20 = a[6], + a21 = a[7], + a22 = a[8]; + out[0] = a11 * a22 - a12 * a21; + out[1] = a02 * a21 - a01 * a22; + out[2] = a01 * a12 - a02 * a11; + out[3] = a12 * a20 - a10 * a22; + out[4] = a00 * a22 - a02 * a20; + out[5] = a02 * a10 - a00 * a12; + out[6] = a10 * a21 - a11 * a20; + out[7] = a01 * a20 - a00 * a21; + out[8] = a00 * a11 - a01 * a10; + return out; +} +/** + * Calculates the determinant of a mat3 + * + * @param {ReadonlyMat3} a the source matrix + * @returns {Number} determinant of a + */ + +function determinant$1(a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2]; + var a10 = a[3], + a11 = a[4], + a12 = a[5]; + var a20 = a[6], + a21 = a[7], + a22 = a[8]; + return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); +} +/** + * Multiplies two mat3's + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the first operand + * @param {ReadonlyMat3} b the second operand + * @returns {mat3} out + */ + +function multiply$6(out, a, b) { + var a00 = a[0], + a01 = a[1], + a02 = a[2]; + var a10 = a[3], + a11 = a[4], + a12 = a[5]; + var a20 = a[6], + a21 = a[7], + a22 = a[8]; + var b00 = b[0], + b01 = b[1], + b02 = b[2]; + var b10 = b[3], + b11 = b[4], + b12 = b[5]; + var b20 = b[6], + b21 = b[7], + b22 = b[8]; + out[0] = b00 * a00 + b01 * a10 + b02 * a20; + out[1] = b00 * a01 + b01 * a11 + b02 * a21; + out[2] = b00 * a02 + b01 * a12 + b02 * a22; + out[3] = b10 * a00 + b11 * a10 + b12 * a20; + out[4] = b10 * a01 + b11 * a11 + b12 * a21; + out[5] = b10 * a02 + b11 * a12 + b12 * a22; + out[6] = b20 * a00 + b21 * a10 + b22 * a20; + out[7] = b20 * a01 + b21 * a11 + b22 * a21; + out[8] = b20 * a02 + b21 * a12 + b22 * a22; + return out; +} +/** + * Translate a mat3 by the given vector + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the matrix to translate + * @param {ReadonlyVec2} v vector to translate by + * @returns {mat3} out + */ + +function translate$2(out, a, v) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a10 = a[3], + a11 = a[4], + a12 = a[5], + a20 = a[6], + a21 = a[7], + a22 = a[8], + x = v[0], + y = v[1]; + out[0] = a00; + out[1] = a01; + out[2] = a02; + out[3] = a10; + out[4] = a11; + out[5] = a12; + out[6] = x * a00 + y * a10 + a20; + out[7] = x * a01 + y * a11 + a21; + out[8] = x * a02 + y * a12 + a22; + return out; +} +/** + * Rotates a mat3 by the given angle + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + +function rotate$2(out, a, rad) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a10 = a[3], + a11 = a[4], + a12 = a[5], + a20 = a[6], + a21 = a[7], + a22 = a[8], + s = Math.sin(rad), + c = Math.cos(rad); + out[0] = c * a00 + s * a10; + out[1] = c * a01 + s * a11; + out[2] = c * a02 + s * a12; + out[3] = c * a10 - s * a00; + out[4] = c * a11 - s * a01; + out[5] = c * a12 - s * a02; + out[6] = a20; + out[7] = a21; + out[8] = a22; + return out; +} +/** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the matrix to rotate + * @param {ReadonlyVec2} v the vec2 to scale the matrix by + * @returns {mat3} out + **/ + +function scale$6(out, a, v) { + var x = v[0], + y = v[1]; + out[0] = x * a[0]; + out[1] = x * a[1]; + out[2] = x * a[2]; + out[3] = y * a[3]; + out[4] = y * a[4]; + out[5] = y * a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +} +/** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.translate(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {ReadonlyVec2} v Translation vector + * @returns {mat3} out + */ + +function fromTranslation$2(out, v) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 1; + out[5] = 0; + out[6] = v[0]; + out[7] = v[1]; + out[8] = 1; + return out; +} +/** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.rotate(dest, dest, rad); + * + * @param {mat3} out mat3 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + +function fromRotation$2(out, rad) { + var s = Math.sin(rad), + c = Math.cos(rad); + out[0] = c; + out[1] = s; + out[2] = 0; + out[3] = -s; + out[4] = c; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +} +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.scale(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {ReadonlyVec2} v Scaling vector + * @returns {mat3} out + */ + +function fromScaling$1(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = v[1]; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +} +/** + * Copies the values from a mat2d into a mat3 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to copy + * @returns {mat3} out + **/ + +function fromMat2d(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = 0; + out[3] = a[2]; + out[4] = a[3]; + out[5] = 0; + out[6] = a[4]; + out[7] = a[5]; + out[8] = 1; + return out; +} +/** + * Calculates a 3x3 matrix from the given quaternion + * + * @param {mat3} out mat3 receiving operation result + * @param {ReadonlyQuat} q Quaternion to create matrix from + * + * @returns {mat3} out + */ + +function fromQuat$1(out, q) { + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var yx = y * x2; + var yy = y * y2; + var zx = z * x2; + var zy = z * y2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + out[0] = 1 - yy - zz; + out[3] = yx - wz; + out[6] = zx + wy; + out[1] = yx + wz; + out[4] = 1 - xx - zz; + out[7] = zy - wx; + out[2] = zx - wy; + out[5] = zy + wx; + out[8] = 1 - xx - yy; + return out; +} +/** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param {mat3} out mat3 receiving operation result + * @param {ReadonlyMat4} a Mat4 to derive the normal matrix from + * + * @returns {mat3} out + */ + +function normalFromMat4(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; // Calculate the determinant + + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + return out; +} +/** + * Generates a 2D projection matrix with the given bounds + * + * @param {mat3} out mat3 frustum matrix will be written into + * @param {number} width Width of your gl context + * @param {number} height Height of gl context + * @returns {mat3} out + */ + +function projection(out, width, height) { + out[0] = 2 / width; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = -2 / height; + out[5] = 0; + out[6] = -1; + out[7] = 1; + out[8] = 1; + return out; +} +/** + * Returns a string representation of a mat3 + * + * @param {ReadonlyMat3} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ + +function str$6(a) { + return "mat3(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ", " + a[6] + ", " + a[7] + ", " + a[8] + ")"; +} +/** + * Returns Frobenius norm of a mat3 + * + * @param {ReadonlyMat3} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ + +function frob$1(a) { + return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]); +} +/** + * Adds two mat3's + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the first operand + * @param {ReadonlyMat3} b the second operand + * @returns {mat3} out + */ + +function add$6(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + out[4] = a[4] + b[4]; + out[5] = a[5] + b[5]; + out[6] = a[6] + b[6]; + out[7] = a[7] + b[7]; + out[8] = a[8] + b[8]; + return out; +} +/** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the first operand + * @param {ReadonlyMat3} b the second operand + * @returns {mat3} out + */ + +function subtract$4(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + out[4] = a[4] - b[4]; + out[5] = a[5] - b[5]; + out[6] = a[6] - b[6]; + out[7] = a[7] - b[7]; + out[8] = a[8] - b[8]; + return out; +} +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat3} out + */ + +function multiplyScalar$1(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + out[4] = a[4] * b; + out[5] = a[5] * b; + out[6] = a[6] * b; + out[7] = a[7] * b; + out[8] = a[8] * b; + return out; +} +/** + * Adds two mat3's after multiplying each element of the second operand by a scalar value. + * + * @param {mat3} out the receiving vector + * @param {ReadonlyMat3} a the first operand + * @param {ReadonlyMat3} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat3} out + */ + +function multiplyScalarAndAdd$1(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + out[4] = a[4] + b[4] * scale; + out[5] = a[5] + b[5] * scale; + out[6] = a[6] + b[6] * scale; + out[7] = a[7] + b[7] * scale; + out[8] = a[8] + b[8] * scale; + return out; +} +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyMat3} a The first matrix. + * @param {ReadonlyMat3} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function exactEquals$6(a, b) { + 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]; +} +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {ReadonlyMat3} a The first matrix. + * @param {ReadonlyMat3} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function equals$7(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5], + a6 = a[6], + a7 = a[7], + a8 = a[8]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)); +} +/** + * Alias for {@link mat3.multiply} + * @function + */ + +var mul$6 = multiply$6; +/** + * Alias for {@link mat3.subtract} + * @function + */ + +var sub$4 = subtract$4; + +var mat3 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$6, +adjoint: adjoint$1, +clone: clone$6, +copy: copy$6, +create: create$7, +determinant: determinant$1, +equals: equals$7, +exactEquals: exactEquals$6, +frob: frob$1, +fromMat2d: fromMat2d, +fromMat4: fromMat4$1, +fromQuat: fromQuat$1, +fromRotation: fromRotation$2, +fromScaling: fromScaling$1, +fromTranslation: fromTranslation$2, +fromValues: fromValues$6, +identity: identity$3, +invert: invert$3, +mul: mul$6, +multiply: multiply$6, +multiplyScalar: multiplyScalar$1, +multiplyScalarAndAdd: multiplyScalarAndAdd$1, +normalFromMat4: normalFromMat4, +projection: projection, +rotate: rotate$2, +scale: scale$6, +set: set$6, +str: str$6, +sub: sub$4, +subtract: subtract$4, +translate: translate$2, +transpose: transpose$1 +}); + +/** + * 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied. + * @module mat4 + */ + +/** + * Creates a new identity mat4 + * + * @returns {mat4} a new 4x4 matrix + */ + +function create$6() { + var out = new ARRAY_TYPE(16); + + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + } + + out[0] = 1; + out[5] = 1; + out[10] = 1; + out[15] = 1; + return out; +} +/** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param {ReadonlyMat4} a matrix to clone + * @returns {mat4} a new 4x4 matrix + */ + +function clone$5(a) { + var out = new ARRAY_TYPE(16); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +/** + * Copy the values from one mat4 to another + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function copy$5(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +/** + * Create a new mat4 with the given values + * + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m03 Component in column 0, row 3 position (index 3) + * @param {Number} m10 Component in column 1, row 0 position (index 4) + * @param {Number} m11 Component in column 1, row 1 position (index 5) + * @param {Number} m12 Component in column 1, row 2 position (index 6) + * @param {Number} m13 Component in column 1, row 3 position (index 7) + * @param {Number} m20 Component in column 2, row 0 position (index 8) + * @param {Number} m21 Component in column 2, row 1 position (index 9) + * @param {Number} m22 Component in column 2, row 2 position (index 10) + * @param {Number} m23 Component in column 2, row 3 position (index 11) + * @param {Number} m30 Component in column 3, row 0 position (index 12) + * @param {Number} m31 Component in column 3, row 1 position (index 13) + * @param {Number} m32 Component in column 3, row 2 position (index 14) + * @param {Number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} A new mat4 + */ + +function fromValues$5(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { + var out = new ARRAY_TYPE(16); + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m03; + out[4] = m10; + out[5] = m11; + out[6] = m12; + out[7] = m13; + out[8] = m20; + out[9] = m21; + out[10] = m22; + out[11] = m23; + out[12] = m30; + out[13] = m31; + out[14] = m32; + out[15] = m33; + return out; +} +/** + * Set the components of a mat4 to the given values + * + * @param {mat4} out the receiving matrix + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m03 Component in column 0, row 3 position (index 3) + * @param {Number} m10 Component in column 1, row 0 position (index 4) + * @param {Number} m11 Component in column 1, row 1 position (index 5) + * @param {Number} m12 Component in column 1, row 2 position (index 6) + * @param {Number} m13 Component in column 1, row 3 position (index 7) + * @param {Number} m20 Component in column 2, row 0 position (index 8) + * @param {Number} m21 Component in column 2, row 1 position (index 9) + * @param {Number} m22 Component in column 2, row 2 position (index 10) + * @param {Number} m23 Component in column 2, row 3 position (index 11) + * @param {Number} m30 Component in column 3, row 0 position (index 12) + * @param {Number} m31 Component in column 3, row 1 position (index 13) + * @param {Number} m32 Component in column 3, row 2 position (index 14) + * @param {Number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} out + */ + +function set$5(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m03; + out[4] = m10; + out[5] = m11; + out[6] = m12; + out[7] = m13; + out[8] = m20; + out[9] = m21; + out[10] = m22; + out[11] = m23; + out[12] = m30; + out[13] = m31; + out[14] = m32; + out[15] = m33; + return out; +} +/** + * Set a mat4 to the identity matrix + * + * @param {mat4} out the receiving matrix + * @returns {mat4} out + */ + +function identity$2(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Transpose the values of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function transpose(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a12 = a[6], + a13 = a[7]; + var a23 = a[11]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a01; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a02; + out[9] = a12; + out[11] = a[14]; + out[12] = a03; + out[13] = a13; + out[14] = a23; + } else { + out[0] = a[0]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a[1]; + out[5] = a[5]; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a[2]; + out[9] = a[6]; + out[10] = a[10]; + out[11] = a[14]; + out[12] = a[3]; + out[13] = a[7]; + out[14] = a[11]; + out[15] = a[15]; + } + + return out; +} +/** + * Inverts a mat4 + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function invert$2(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; // Calculate the determinant + + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + return out; +} +/** + * Calculates the adjugate of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function adjoint(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; + out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22); + out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); + out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12); + out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); + out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); + out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22); + out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); + out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12); + out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21); + out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); + out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11); + out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); + out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); + out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21); + out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); + out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11); + return out; +} +/** + * Calculates the determinant of a mat4 + * + * @param {ReadonlyMat4} a the source matrix + * @returns {Number} determinant of a + */ + +function determinant(a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; // Calculate the determinant + + return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; +} +/** + * Multiplies two mat4s + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the first operand + * @param {ReadonlyMat4} b the second operand + * @returns {mat4} out + */ + +function multiply$5(out, a, b) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; // Cache only the current line of the second matrix + + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[4]; + b1 = b[5]; + b2 = b[6]; + b3 = b[7]; + out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[8]; + b1 = b[9]; + b2 = b[10]; + b3 = b[11]; + out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[12]; + b1 = b[13]; + b2 = b[14]; + b3 = b[15]; + out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + return out; +} +/** + * Translate a mat4 by the given vector + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to translate + * @param {ReadonlyVec3} v vector to translate by + * @returns {mat4} out + */ + +function translate$1(out, a, v) { + var x = v[0], + y = v[1], + z = v[2]; + var a00, a01, a02, a03; + var a10, a11, a12, a13; + var a20, a21, a22, a23; + + if (a === out) { + out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + } else { + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; + out[0] = a00; + out[1] = a01; + out[2] = a02; + out[3] = a03; + out[4] = a10; + out[5] = a11; + out[6] = a12; + out[7] = a13; + out[8] = a20; + out[9] = a21; + out[10] = a22; + out[11] = a23; + out[12] = a00 * x + a10 * y + a20 * z + a[12]; + out[13] = a01 * x + a11 * y + a21 * z + a[13]; + out[14] = a02 * x + a12 * y + a22 * z + a[14]; + out[15] = a03 * x + a13 * y + a23 * z + a[15]; + } + + return out; +} +/** + * Scales the mat4 by the dimensions in the given vec3 not using vectorization + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to scale + * @param {ReadonlyVec3} v the vec3 to scale the matrix by + * @returns {mat4} out + **/ + +function scale$5(out, a, v) { + var x = v[0], + y = v[1], + z = v[2]; + out[0] = a[0] * x; + out[1] = a[1] * x; + out[2] = a[2] * x; + out[3] = a[3] * x; + out[4] = a[4] * y; + out[5] = a[5] * y; + out[6] = a[6] * y; + out[7] = a[7] * y; + out[8] = a[8] * z; + out[9] = a[9] * z; + out[10] = a[10] * z; + out[11] = a[11] * z; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +/** + * Rotates a mat4 by the given angle around the given axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @param {ReadonlyVec3} axis the axis to rotate around + * @returns {mat4} out + */ + +function rotate$1(out, a, rad, axis) { + var x = axis[0], + y = axis[1], + z = axis[2]; + var len = Math.hypot(x, y, z); + var s, c, t; + var a00, a01, a02, a03; + var a10, a11, a12, a13; + var a20, a21, a22, a23; + var b00, b01, b02; + var b10, b11, b12; + var b20, b21, b22; + + if (len < EPSILON) { + return null; + } + + len = 1 / len; + x *= len; + y *= len; + z *= len; + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; // Construct the elements of the rotation matrix + + b00 = x * x * t + c; + b01 = y * x * t + z * s; + b02 = z * x * t - y * s; + b10 = x * y * t - z * s; + b11 = y * y * t + c; + b12 = z * y * t + x * s; + b20 = x * z * t + y * s; + b21 = y * z * t - x * s; + b22 = z * z * t + c; // Perform rotation-specific matrix multiplication + + out[0] = a00 * b00 + a10 * b01 + a20 * b02; + out[1] = a01 * b00 + a11 * b01 + a21 * b02; + out[2] = a02 * b00 + a12 * b01 + a22 * b02; + out[3] = a03 * b00 + a13 * b01 + a23 * b02; + out[4] = a00 * b10 + a10 * b11 + a20 * b12; + out[5] = a01 * b10 + a11 * b11 + a21 * b12; + out[6] = a02 * b10 + a12 * b11 + a22 * b12; + out[7] = a03 * b10 + a13 * b11 + a23 * b12; + out[8] = a00 * b20 + a10 * b21 + a20 * b22; + out[9] = a01 * b20 + a11 * b21 + a21 * b22; + out[10] = a02 * b20 + a12 * b21 + a22 * b22; + out[11] = a03 * b20 + a13 * b21 + a23 * b22; + + if (a !== out) { + // If the source and destination differ, copy the unchanged last row + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + + return out; +} +/** + * Rotates a matrix by the given angle around the X axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function rotateX$3(out, a, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + if (a !== out) { + // If the source and destination differ, copy the unchanged rows + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } // Perform axis-specific matrix multiplication + + + out[4] = a10 * c + a20 * s; + out[5] = a11 * c + a21 * s; + out[6] = a12 * c + a22 * s; + out[7] = a13 * c + a23 * s; + out[8] = a20 * c - a10 * s; + out[9] = a21 * c - a11 * s; + out[10] = a22 * c - a12 * s; + out[11] = a23 * c - a13 * s; + return out; +} +/** + * Rotates a matrix by the given angle around the Y axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function rotateY$3(out, a, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + if (a !== out) { + // If the source and destination differ, copy the unchanged rows + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } // Perform axis-specific matrix multiplication + + + out[0] = a00 * c - a20 * s; + out[1] = a01 * c - a21 * s; + out[2] = a02 * c - a22 * s; + out[3] = a03 * c - a23 * s; + out[8] = a00 * s + a20 * c; + out[9] = a01 * s + a21 * c; + out[10] = a02 * s + a22 * c; + out[11] = a03 * s + a23 * c; + return out; +} +/** + * Rotates a matrix by the given angle around the Z axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function rotateZ$3(out, a, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + if (a !== out) { + // If the source and destination differ, copy the unchanged last row + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } // Perform axis-specific matrix multiplication + + + out[0] = a00 * c + a10 * s; + out[1] = a01 * c + a11 * s; + out[2] = a02 * c + a12 * s; + out[3] = a03 * c + a13 * s; + out[4] = a10 * c - a00 * s; + out[5] = a11 * c - a01 * s; + out[6] = a12 * c - a02 * s; + out[7] = a13 * c - a03 * s; + return out; +} +/** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {ReadonlyVec3} v Translation vector + * @returns {mat4} out + */ + +function fromTranslation$1(out, v) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; +} +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {ReadonlyVec3} v Scaling vector + * @returns {mat4} out + */ + +function fromScaling(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = v[1]; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = v[2]; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from a given angle around a given axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotate(dest, dest, rad, axis); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @param {ReadonlyVec3} axis the axis to rotate around + * @returns {mat4} out + */ + +function fromRotation$1(out, rad, axis) { + var x = axis[0], + y = axis[1], + z = axis[2]; + var len = Math.hypot(x, y, z); + var s, c, t; + + if (len < EPSILON) { + return null; + } + + len = 1 / len; + x *= len; + y *= len; + z *= len; + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; // Perform rotation-specific matrix multiplication + + out[0] = x * x * t + c; + out[1] = y * x * t + z * s; + out[2] = z * x * t - y * s; + out[3] = 0; + out[4] = x * y * t - z * s; + out[5] = y * y * t + c; + out[6] = z * y * t + x * s; + out[7] = 0; + out[8] = x * z * t + y * s; + out[9] = y * z * t - x * s; + out[10] = z * z * t + c; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from the given angle around the X axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateX(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function fromXRotation(out, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); // Perform axis-specific matrix multiplication + + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = c; + out[6] = s; + out[7] = 0; + out[8] = 0; + out[9] = -s; + out[10] = c; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from the given angle around the Y axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateY(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function fromYRotation(out, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); // Perform axis-specific matrix multiplication + + out[0] = c; + out[1] = 0; + out[2] = -s; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = s; + out[9] = 0; + out[10] = c; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from the given angle around the Z axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateZ(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function fromZRotation(out, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); // Perform axis-specific matrix multiplication + + out[0] = c; + out[1] = s; + out[2] = 0; + out[3] = 0; + out[4] = -s; + out[5] = c; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * let quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @param {ReadonlyVec3} v Translation vector + * @returns {mat4} out + */ + +function fromRotationTranslation$1(out, q, v) { + // Quaternion math + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; +} +/** + * Creates a new mat4 from a dual quat. + * + * @param {mat4} out Matrix + * @param {ReadonlyQuat2} a Dual Quaternion + * @returns {mat4} mat4 receiving operation result + */ + +function fromQuat2(out, a) { + var translation = new ARRAY_TYPE(3); + var bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3], + ax = a[4], + ay = a[5], + az = a[6], + aw = a[7]; + var magnitude = bx * bx + by * by + bz * bz + bw * bw; //Only scale if it makes sense + + if (magnitude > 0) { + translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude; + translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude; + translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude; + } else { + translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2; + translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2; + translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2; + } + + fromRotationTranslation$1(out, a, translation); + return out; +} +/** + * Returns the translation vector component of a transformation + * matrix. If a matrix is built with fromRotationTranslation, + * the returned vector will be the same as the translation vector + * originally supplied. + * @param {vec3} out Vector to receive translation component + * @param {ReadonlyMat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + +function getTranslation$1(out, mat) { + out[0] = mat[12]; + out[1] = mat[13]; + out[2] = mat[14]; + return out; +} +/** + * Returns the scaling factor component of a transformation + * matrix. If a matrix is built with fromRotationTranslationScale + * with a normalized Quaternion paramter, the returned vector will be + * the same as the scaling vector + * originally supplied. + * @param {vec3} out Vector to receive scaling factor component + * @param {ReadonlyMat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + +function getScaling(out, mat) { + var m11 = mat[0]; + var m12 = mat[1]; + var m13 = mat[2]; + var m21 = mat[4]; + var m22 = mat[5]; + var m23 = mat[6]; + var m31 = mat[8]; + var m32 = mat[9]; + var m33 = mat[10]; + out[0] = Math.hypot(m11, m12, m13); + out[1] = Math.hypot(m21, m22, m23); + out[2] = Math.hypot(m31, m32, m33); + return out; +} +/** + * Returns a quaternion representing the rotational component + * of a transformation matrix. If a matrix is built with + * fromRotationTranslation, the returned quaternion will be the + * same as the quaternion originally supplied. + * @param {quat} out Quaternion to receive the rotation component + * @param {ReadonlyMat4} mat Matrix to be decomposed (input) + * @return {quat} out + */ + +function getRotation(out, mat) { + var scaling = new ARRAY_TYPE(3); + getScaling(scaling, mat); + var is1 = 1 / scaling[0]; + var is2 = 1 / scaling[1]; + var is3 = 1 / scaling[2]; + var sm11 = mat[0] * is1; + var sm12 = mat[1] * is2; + var sm13 = mat[2] * is3; + var sm21 = mat[4] * is1; + var sm22 = mat[5] * is2; + var sm23 = mat[6] * is3; + var sm31 = mat[8] * is1; + var sm32 = mat[9] * is2; + var sm33 = mat[10] * is3; + var trace = sm11 + sm22 + sm33; + var S = 0; + + if (trace > 0) { + S = Math.sqrt(trace + 1.0) * 2; + out[3] = 0.25 * S; + out[0] = (sm23 - sm32) / S; + out[1] = (sm31 - sm13) / S; + out[2] = (sm12 - sm21) / S; + } else if (sm11 > sm22 && sm11 > sm33) { + S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2; + out[3] = (sm23 - sm32) / S; + out[0] = 0.25 * S; + out[1] = (sm12 + sm21) / S; + out[2] = (sm31 + sm13) / S; + } else if (sm22 > sm33) { + S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2; + out[3] = (sm31 - sm13) / S; + out[0] = (sm12 + sm21) / S; + out[1] = 0.25 * S; + out[2] = (sm23 + sm32) / S; + } else { + S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2; + out[3] = (sm12 - sm21) / S; + out[0] = (sm31 + sm13) / S; + out[1] = (sm23 + sm32) / S; + out[2] = 0.25 * S; + } + + return out; +} +/** + * Creates a matrix from a quaternion rotation, vector translation and vector scale + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * let quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @param {ReadonlyVec3} v Translation vector + * @param {ReadonlyVec3} s Scaling vector + * @returns {mat4} out + */ + +function fromRotationTranslationScale(out, q, v, s) { + // Quaternion math + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + var sx = s[0]; + var sy = s[1]; + var sz = s[2]; + out[0] = (1 - (yy + zz)) * sx; + out[1] = (xy + wz) * sx; + out[2] = (xz - wy) * sx; + out[3] = 0; + out[4] = (xy - wz) * sy; + out[5] = (1 - (xx + zz)) * sy; + out[6] = (yz + wx) * sy; + out[7] = 0; + out[8] = (xz + wy) * sz; + out[9] = (yz - wx) * sz; + out[10] = (1 - (xx + yy)) * sz; + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; +} +/** + * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * mat4.translate(dest, origin); + * let quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * mat4.translate(dest, negativeOrigin); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @param {ReadonlyVec3} v Translation vector + * @param {ReadonlyVec3} s Scaling vector + * @param {ReadonlyVec3} o The origin vector around which to scale and rotate + * @returns {mat4} out + */ + +function fromRotationTranslationScaleOrigin(out, q, v, s, o) { + // Quaternion math + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + var sx = s[0]; + var sy = s[1]; + var sz = s[2]; + var ox = o[0]; + var oy = o[1]; + var oz = o[2]; + var out0 = (1 - (yy + zz)) * sx; + var out1 = (xy + wz) * sx; + var out2 = (xz - wy) * sx; + var out4 = (xy - wz) * sy; + var out5 = (1 - (xx + zz)) * sy; + var out6 = (yz + wx) * sy; + var out8 = (xz + wy) * sz; + var out9 = (yz - wx) * sz; + var out10 = (1 - (xx + yy)) * sz; + out[0] = out0; + out[1] = out1; + out[2] = out2; + out[3] = 0; + out[4] = out4; + out[5] = out5; + out[6] = out6; + out[7] = 0; + out[8] = out8; + out[9] = out9; + out[10] = out10; + out[11] = 0; + out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz); + out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz); + out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz); + out[15] = 1; + return out; +} +/** + * Calculates a 4x4 matrix from the given quaternion + * + * @param {mat4} out mat4 receiving operation result + * @param {ReadonlyQuat} q Quaternion to create matrix from + * + * @returns {mat4} out + */ + +function fromQuat(out, q) { + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var yx = y * x2; + var yy = y * y2; + var zx = z * x2; + var zy = z * y2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + out[0] = 1 - yy - zz; + out[1] = yx + wz; + out[2] = zx - wy; + out[3] = 0; + out[4] = yx - wz; + out[5] = 1 - xx - zz; + out[6] = zy + wx; + out[7] = 0; + out[8] = zx + wy; + out[9] = zy - wx; + out[10] = 1 - xx - yy; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Generates a frustum matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Number} left Left bound of the frustum + * @param {Number} right Right bound of the frustum + * @param {Number} bottom Bottom bound of the frustum + * @param {Number} top Top bound of the frustum + * @param {Number} near Near bound of the frustum + * @param {Number} far Far bound of the frustum + * @returns {mat4} out + */ + +function frustum(out, left, right, bottom, top, near, far) { + var rl = 1 / (right - left); + var tb = 1 / (top - bottom); + var nf = 1 / (near - far); + out[0] = near * 2 * rl; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = near * 2 * tb; + out[6] = 0; + out[7] = 0; + out[8] = (right + left) * rl; + out[9] = (top + bottom) * tb; + out[10] = (far + near) * nf; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = far * near * 2 * nf; + out[15] = 0; + return out; +} +/** + * Generates a perspective projection matrix with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1], + * which matches WebGL/OpenGL's clip volume. + * Passing null/undefined/no value for far will generate infinite projection matrix. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} fovy Vertical field of view in radians + * @param {number} aspect Aspect ratio. typically viewport width/height + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum, can be null or Infinity + * @returns {mat4} out + */ + +function perspectiveNO(out, fovy, aspect, near, far) { + var f = 1.0 / Math.tan(fovy / 2), + nf; + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[15] = 0; + + if (far != null && far !== Infinity) { + nf = 1 / (near - far); + out[10] = (far + near) * nf; + out[14] = 2 * far * near * nf; + } else { + out[10] = -1; + out[14] = -2 * near; + } + + return out; +} +/** + * Alias for {@link mat4.perspectiveNO} + * @function + */ + +var perspective = perspectiveNO; +/** + * Generates a perspective projection matrix suitable for WebGPU with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1], + * which matches WebGPU/Vulkan/DirectX/Metal's clip volume. + * Passing null/undefined/no value for far will generate infinite projection matrix. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} fovy Vertical field of view in radians + * @param {number} aspect Aspect ratio. typically viewport width/height + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum, can be null or Infinity + * @returns {mat4} out + */ + +function perspectiveZO(out, fovy, aspect, near, far) { + var f = 1.0 / Math.tan(fovy / 2), + nf; + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[15] = 0; + + if (far != null && far !== Infinity) { + nf = 1 / (near - far); + out[10] = far * nf; + out[14] = far * near * nf; + } else { + out[10] = -1; + out[14] = -near; + } + + return out; +} +/** + * Generates a perspective projection matrix with the given field of view. + * This is primarily useful for generating projection matrices to be used + * with the still experiemental WebVR API. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + +function perspectiveFromFieldOfView(out, fov, near, far) { + var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0); + var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0); + var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0); + var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0); + var xScale = 2.0 / (leftTan + rightTan); + var yScale = 2.0 / (upTan + downTan); + out[0] = xScale; + out[1] = 0.0; + out[2] = 0.0; + out[3] = 0.0; + out[4] = 0.0; + out[5] = yScale; + out[6] = 0.0; + out[7] = 0.0; + out[8] = -((leftTan - rightTan) * xScale * 0.5); + out[9] = (upTan - downTan) * yScale * 0.5; + out[10] = far / (near - far); + out[11] = -1.0; + out[12] = 0.0; + out[13] = 0.0; + out[14] = far * near / (near - far); + out[15] = 0.0; + return out; +} +/** + * Generates a orthogonal projection matrix with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1], + * which matches WebGL/OpenGL's clip volume. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} left Left bound of the frustum + * @param {number} right Right bound of the frustum + * @param {number} bottom Bottom bound of the frustum + * @param {number} top Top bound of the frustum + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + +function orthoNO(out, left, right, bottom, top, near, far) { + var lr = 1 / (left - right); + var bt = 1 / (bottom - top); + var nf = 1 / (near - far); + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 2 * nf; + out[11] = 0; + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = (far + near) * nf; + out[15] = 1; + return out; +} +/** + * Alias for {@link mat4.orthoNO} + * @function + */ + +var ortho = orthoNO; +/** + * Generates a orthogonal projection matrix with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1], + * which matches WebGPU/Vulkan/DirectX/Metal's clip volume. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} left Left bound of the frustum + * @param {number} right Right bound of the frustum + * @param {number} bottom Bottom bound of the frustum + * @param {number} top Top bound of the frustum + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + +function orthoZO(out, left, right, bottom, top, near, far) { + var lr = 1 / (left - right); + var bt = 1 / (bottom - top); + var nf = 1 / (near - far); + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = nf; + out[11] = 0; + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = near * nf; + out[15] = 1; + return out; +} +/** + * Generates a look-at matrix with the given eye position, focal point, and up axis. + * If you want a matrix that actually makes an object look at another object, you should use targetTo instead. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {ReadonlyVec3} eye Position of the viewer + * @param {ReadonlyVec3} center Point the viewer is looking at + * @param {ReadonlyVec3} up vec3 pointing up + * @returns {mat4} out + */ + +function lookAt(out, eye, center, up) { + var x0, x1, x2, y0, y1, y2, z0, z1, z2, len; + var eyex = eye[0]; + var eyey = eye[1]; + var eyez = eye[2]; + var upx = up[0]; + var upy = up[1]; + var upz = up[2]; + var centerx = center[0]; + var centery = center[1]; + var centerz = center[2]; + + if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) { + return identity$2(out); + } + + z0 = eyex - centerx; + z1 = eyey - centery; + z2 = eyez - centerz; + len = 1 / Math.hypot(z0, z1, z2); + z0 *= len; + z1 *= len; + z2 *= len; + x0 = upy * z2 - upz * z1; + x1 = upz * z0 - upx * z2; + x2 = upx * z1 - upy * z0; + len = Math.hypot(x0, x1, x2); + + if (!len) { + x0 = 0; + x1 = 0; + x2 = 0; + } else { + len = 1 / len; + x0 *= len; + x1 *= len; + x2 *= len; + } + + y0 = z1 * x2 - z2 * x1; + y1 = z2 * x0 - z0 * x2; + y2 = z0 * x1 - z1 * x0; + len = Math.hypot(y0, y1, y2); + + if (!len) { + y0 = 0; + y1 = 0; + y2 = 0; + } else { + len = 1 / len; + y0 *= len; + y1 *= len; + y2 *= len; + } + + out[0] = x0; + out[1] = y0; + out[2] = z0; + out[3] = 0; + out[4] = x1; + out[5] = y1; + out[6] = z1; + out[7] = 0; + out[8] = x2; + out[9] = y2; + out[10] = z2; + out[11] = 0; + out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); + out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); + out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); + out[15] = 1; + return out; +} +/** + * Generates a matrix that makes something look at something else. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {ReadonlyVec3} eye Position of the viewer + * @param {ReadonlyVec3} center Point the viewer is looking at + * @param {ReadonlyVec3} up vec3 pointing up + * @returns {mat4} out + */ + +function targetTo(out, eye, target, up) { + var eyex = eye[0], + eyey = eye[1], + eyez = eye[2], + upx = up[0], + upy = up[1], + upz = up[2]; + var z0 = eyex - target[0], + z1 = eyey - target[1], + z2 = eyez - target[2]; + var len = z0 * z0 + z1 * z1 + z2 * z2; + + if (len > 0) { + len = 1 / Math.sqrt(len); + z0 *= len; + z1 *= len; + z2 *= len; + } + + var x0 = upy * z2 - upz * z1, + x1 = upz * z0 - upx * z2, + x2 = upx * z1 - upy * z0; + len = x0 * x0 + x1 * x1 + x2 * x2; + + if (len > 0) { + len = 1 / Math.sqrt(len); + x0 *= len; + x1 *= len; + x2 *= len; + } + + out[0] = x0; + out[1] = x1; + out[2] = x2; + out[3] = 0; + out[4] = z1 * x2 - z2 * x1; + out[5] = z2 * x0 - z0 * x2; + out[6] = z0 * x1 - z1 * x0; + out[7] = 0; + out[8] = z0; + out[9] = z1; + out[10] = z2; + out[11] = 0; + out[12] = eyex; + out[13] = eyey; + out[14] = eyez; + out[15] = 1; + return out; +} +/** + * Returns a string representation of a mat4 + * + * @param {ReadonlyMat4} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ + +function str$5(a) { + 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] + ")"; +} +/** + * Returns Frobenius norm of a mat4 + * + * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ + +function frob(a) { + 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]); +} +/** + * Adds two mat4's + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the first operand + * @param {ReadonlyMat4} b the second operand + * @returns {mat4} out + */ + +function add$5(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + out[4] = a[4] + b[4]; + out[5] = a[5] + b[5]; + out[6] = a[6] + b[6]; + out[7] = a[7] + b[7]; + out[8] = a[8] + b[8]; + out[9] = a[9] + b[9]; + out[10] = a[10] + b[10]; + out[11] = a[11] + b[11]; + out[12] = a[12] + b[12]; + out[13] = a[13] + b[13]; + out[14] = a[14] + b[14]; + out[15] = a[15] + b[15]; + return out; +} +/** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the first operand + * @param {ReadonlyMat4} b the second operand + * @returns {mat4} out + */ + +function subtract$3(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + out[4] = a[4] - b[4]; + out[5] = a[5] - b[5]; + out[6] = a[6] - b[6]; + out[7] = a[7] - b[7]; + out[8] = a[8] - b[8]; + out[9] = a[9] - b[9]; + out[10] = a[10] - b[10]; + out[11] = a[11] - b[11]; + out[12] = a[12] - b[12]; + out[13] = a[13] - b[13]; + out[14] = a[14] - b[14]; + out[15] = a[15] - b[15]; + return out; +} +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat4} out + */ + +function multiplyScalar(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + out[4] = a[4] * b; + out[5] = a[5] * b; + out[6] = a[6] * b; + out[7] = a[7] * b; + out[8] = a[8] * b; + out[9] = a[9] * b; + out[10] = a[10] * b; + out[11] = a[11] * b; + out[12] = a[12] * b; + out[13] = a[13] * b; + out[14] = a[14] * b; + out[15] = a[15] * b; + return out; +} +/** + * Adds two mat4's after multiplying each element of the second operand by a scalar value. + * + * @param {mat4} out the receiving vector + * @param {ReadonlyMat4} a the first operand + * @param {ReadonlyMat4} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat4} out + */ + +function multiplyScalarAndAdd(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + out[4] = a[4] + b[4] * scale; + out[5] = a[5] + b[5] * scale; + out[6] = a[6] + b[6] * scale; + out[7] = a[7] + b[7] * scale; + out[8] = a[8] + b[8] * scale; + out[9] = a[9] + b[9] * scale; + out[10] = a[10] + b[10] * scale; + out[11] = a[11] + b[11] * scale; + out[12] = a[12] + b[12] * scale; + out[13] = a[13] + b[13] * scale; + out[14] = a[14] + b[14] * scale; + out[15] = a[15] + b[15] * scale; + return out; +} +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyMat4} a The first matrix. + * @param {ReadonlyMat4} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function exactEquals$5(a, b) { + 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]; +} +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {ReadonlyMat4} a The first matrix. + * @param {ReadonlyMat4} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function equals$6(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var a4 = a[4], + a5 = a[5], + a6 = a[6], + a7 = a[7]; + var a8 = a[8], + a9 = a[9], + a10 = a[10], + a11 = a[11]; + var a12 = a[12], + a13 = a[13], + a14 = a[14], + a15 = a[15]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + var b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7]; + var b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11]; + var b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15)); +} +/** + * Alias for {@link mat4.multiply} + * @function + */ + +var mul$5 = multiply$5; +/** + * Alias for {@link mat4.subtract} + * @function + */ + +var sub$3 = subtract$3; + +var mat4 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$5, +adjoint: adjoint, +clone: clone$5, +copy: copy$5, +create: create$6, +determinant: determinant, +equals: equals$6, +exactEquals: exactEquals$5, +frob: frob, +fromQuat: fromQuat, +fromQuat2: fromQuat2, +fromRotation: fromRotation$1, +fromRotationTranslation: fromRotationTranslation$1, +fromRotationTranslationScale: fromRotationTranslationScale, +fromRotationTranslationScaleOrigin: fromRotationTranslationScaleOrigin, +fromScaling: fromScaling, +fromTranslation: fromTranslation$1, +fromValues: fromValues$5, +fromXRotation: fromXRotation, +fromYRotation: fromYRotation, +fromZRotation: fromZRotation, +frustum: frustum, +getRotation: getRotation, +getScaling: getScaling, +getTranslation: getTranslation$1, +identity: identity$2, +invert: invert$2, +lookAt: lookAt, +mul: mul$5, +multiply: multiply$5, +multiplyScalar: multiplyScalar, +multiplyScalarAndAdd: multiplyScalarAndAdd, +ortho: ortho, +orthoNO: orthoNO, +orthoZO: orthoZO, +perspective: perspective, +perspectiveFromFieldOfView: perspectiveFromFieldOfView, +perspectiveNO: perspectiveNO, +perspectiveZO: perspectiveZO, +rotate: rotate$1, +rotateX: rotateX$3, +rotateY: rotateY$3, +rotateZ: rotateZ$3, +scale: scale$5, +set: set$5, +str: str$5, +sub: sub$3, +subtract: subtract$3, +targetTo: targetTo, +translate: translate$1, +transpose: transpose +}); + +/** + * 3 Dimensional Vector + * @module vec3 + */ + +/** + * Creates a new, empty vec3 + * + * @returns {vec3} a new 3D vector + */ + +function create$5() { + var out = new ARRAY_TYPE(3); + + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + } + + return out; +} +/** + * Creates a new vec3 initialized with values from an existing vector + * + * @param {ReadonlyVec3} a vector to clone + * @returns {vec3} a new 3D vector + */ + +function clone$4(a) { + var out = new ARRAY_TYPE(3); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + return out; +} +/** + * Calculates the length of a vec3 + * + * @param {ReadonlyVec3} a vector to calculate length of + * @returns {Number} length of a + */ + +function length$4(a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + return Math.hypot(x, y, z); +} +/** + * Creates a new vec3 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @returns {vec3} a new 3D vector + */ + +function fromValues$4(x, y, z) { + var out = new ARRAY_TYPE(3); + out[0] = x; + out[1] = y; + out[2] = z; + return out; +} +/** + * Copy the values from one vec3 to another + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the source vector + * @returns {vec3} out + */ + +function copy$4(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + return out; +} +/** + * Set the components of a vec3 to the given values + * + * @param {vec3} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @returns {vec3} out + */ + +function set$4(out, x, y, z) { + out[0] = x; + out[1] = y; + out[2] = z; + return out; +} +/** + * Adds two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function add$4(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + return out; +} +/** + * Subtracts vector b from vector a + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function subtract$2(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + return out; +} +/** + * Multiplies two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function multiply$4(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + out[2] = a[2] * b[2]; + return out; +} +/** + * Divides two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function divide$2(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + out[2] = a[2] / b[2]; + return out; +} +/** + * Math.ceil the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to ceil + * @returns {vec3} out + */ + +function ceil$2(out, a) { + out[0] = Math.ceil(a[0]); + out[1] = Math.ceil(a[1]); + out[2] = Math.ceil(a[2]); + return out; +} +/** + * Math.floor the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to floor + * @returns {vec3} out + */ + +function floor$2(out, a) { + out[0] = Math.floor(a[0]); + out[1] = Math.floor(a[1]); + out[2] = Math.floor(a[2]); + return out; +} +/** + * Returns the minimum of two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function min$2(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + out[2] = Math.min(a[2], b[2]); + return out; +} +/** + * Returns the maximum of two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function max$2(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + out[2] = Math.max(a[2], b[2]); + return out; +} +/** + * Math.round the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to round + * @returns {vec3} out + */ + +function round$2(out, a) { + out[0] = Math.round(a[0]); + out[1] = Math.round(a[1]); + out[2] = Math.round(a[2]); + return out; +} +/** + * Scales a vec3 by a scalar number + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec3} out + */ + +function scale$4(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + return out; +} +/** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec3} out + */ + +function scaleAndAdd$2(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + return out; +} +/** + * Calculates the euclidian distance between two vec3's + * + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {Number} distance between a and b + */ + +function distance$2(a, b) { + var x = b[0] - a[0]; + var y = b[1] - a[1]; + var z = b[2] - a[2]; + return Math.hypot(x, y, z); +} +/** + * Calculates the squared euclidian distance between two vec3's + * + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {Number} squared distance between a and b + */ + +function squaredDistance$2(a, b) { + var x = b[0] - a[0]; + var y = b[1] - a[1]; + var z = b[2] - a[2]; + return x * x + y * y + z * z; +} +/** + * Calculates the squared length of a vec3 + * + * @param {ReadonlyVec3} a vector to calculate squared length of + * @returns {Number} squared length of a + */ + +function squaredLength$4(a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + return x * x + y * y + z * z; +} +/** + * Negates the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to negate + * @returns {vec3} out + */ + +function negate$2(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + return out; +} +/** + * Returns the inverse of the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to invert + * @returns {vec3} out + */ + +function inverse$2(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + out[2] = 1.0 / a[2]; + return out; +} +/** + * Normalize a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to normalize + * @returns {vec3} out + */ + +function normalize$4(out, a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + var len = x * x + y * y + z * z; + + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + } + + out[0] = a[0] * len; + out[1] = a[1] * len; + out[2] = a[2] * len; + return out; +} +/** + * Calculates the dot product of two vec3's + * + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {Number} dot product of a and b + */ + +function dot$5(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +} +/** + * Computes the cross product of two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function cross$2(out, a, b) { + var ax = a[0], + ay = a[1], + az = a[2]; + var bx = b[0], + by = b[1], + bz = b[2]; + out[0] = ay * bz - az * by; + out[1] = az * bx - ax * bz; + out[2] = ax * by - ay * bx; + return out; +} +/** + * Performs a linear interpolation between two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec3} out + */ + +function lerp$4(out, a, b, t) { + var ax = a[0]; + var ay = a[1]; + var az = a[2]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + out[2] = az + t * (b[2] - az); + return out; +} +/** + * Performs a hermite interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @param {ReadonlyVec3} c the third operand + * @param {ReadonlyVec3} d the fourth operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec3} out + */ + +function hermite(out, a, b, c, d, t) { + var factorTimes2 = t * t; + var factor1 = factorTimes2 * (2 * t - 3) + 1; + var factor2 = factorTimes2 * (t - 2) + t; + var factor3 = factorTimes2 * (t - 1); + var factor4 = factorTimes2 * (3 - 2 * t); + out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4; + out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4; + out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4; + return out; +} +/** + * Performs a bezier interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @param {ReadonlyVec3} c the third operand + * @param {ReadonlyVec3} d the fourth operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec3} out + */ + +function bezier(out, a, b, c, d, t) { + var inverseFactor = 1 - t; + var inverseFactorTimesTwo = inverseFactor * inverseFactor; + var factorTimes2 = t * t; + var factor1 = inverseFactorTimesTwo * inverseFactor; + var factor2 = 3 * t * inverseFactorTimesTwo; + var factor3 = 3 * factorTimes2 * inverseFactor; + var factor4 = factorTimes2 * t; + out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4; + out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4; + out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4; + return out; +} +/** + * Generates a random vector with the given scale + * + * @param {vec3} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec3} out + */ + +function random$3(out, scale) { + scale = scale || 1.0; + var r = RANDOM() * 2.0 * Math.PI; + var z = RANDOM() * 2.0 - 1.0; + var zScale = Math.sqrt(1.0 - z * z) * scale; + out[0] = Math.cos(r) * zScale; + out[1] = Math.sin(r) * zScale; + out[2] = z * scale; + return out; +} +/** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to transform + * @param {ReadonlyMat4} m matrix to transform with + * @returns {vec3} out + */ + +function transformMat4$2(out, a, m) { + var x = a[0], + y = a[1], + z = a[2]; + var w = m[3] * x + m[7] * y + m[11] * z + m[15]; + w = w || 1.0; + out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w; + out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w; + out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w; + return out; +} +/** + * Transforms the vec3 with a mat3. + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to transform + * @param {ReadonlyMat3} m the 3x3 matrix to transform with + * @returns {vec3} out + */ + +function transformMat3$1(out, a, m) { + var x = a[0], + y = a[1], + z = a[2]; + out[0] = x * m[0] + y * m[3] + z * m[6]; + out[1] = x * m[1] + y * m[4] + z * m[7]; + out[2] = x * m[2] + y * m[5] + z * m[8]; + return out; +} +/** + * Transforms the vec3 with a quat + * Can also be used for dual quaternions. (Multiply it with the real part) + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to transform + * @param {ReadonlyQuat} q quaternion to transform with + * @returns {vec3} out + */ + +function transformQuat$1(out, a, q) { + // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed + var qx = q[0], + qy = q[1], + qz = q[2], + qw = q[3]; + var x = a[0], + y = a[1], + z = a[2]; // var qvec = [qx, qy, qz]; + // var uv = vec3.cross([], qvec, a); + + var uvx = qy * z - qz * y, + uvy = qz * x - qx * z, + uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv); + + var uuvx = qy * uvz - qz * uvy, + uuvy = qz * uvx - qx * uvz, + uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w); + + var w2 = qw * 2; + uvx *= w2; + uvy *= w2; + uvz *= w2; // vec3.scale(uuv, uuv, 2); + + uuvx *= 2; + uuvy *= 2; + uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv)); + + out[0] = x + uvx + uuvx; + out[1] = y + uvy + uuvy; + out[2] = z + uvz + uuvz; + return out; +} +/** + * Rotate a 3D vector around the x-axis + * @param {vec3} out The receiving vec3 + * @param {ReadonlyVec3} a The vec3 point to rotate + * @param {ReadonlyVec3} b The origin of the rotation + * @param {Number} rad The angle of rotation in radians + * @returns {vec3} out + */ + +function rotateX$2(out, a, b, rad) { + var p = [], + r = []; //Translate point to the origin + + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; //perform rotation + + r[0] = p[0]; + r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad); + r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position + + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + return out; +} +/** + * Rotate a 3D vector around the y-axis + * @param {vec3} out The receiving vec3 + * @param {ReadonlyVec3} a The vec3 point to rotate + * @param {ReadonlyVec3} b The origin of the rotation + * @param {Number} rad The angle of rotation in radians + * @returns {vec3} out + */ + +function rotateY$2(out, a, b, rad) { + var p = [], + r = []; //Translate point to the origin + + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; //perform rotation + + r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad); + r[1] = p[1]; + r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position + + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + return out; +} +/** + * Rotate a 3D vector around the z-axis + * @param {vec3} out The receiving vec3 + * @param {ReadonlyVec3} a The vec3 point to rotate + * @param {ReadonlyVec3} b The origin of the rotation + * @param {Number} rad The angle of rotation in radians + * @returns {vec3} out + */ + +function rotateZ$2(out, a, b, rad) { + var p = [], + r = []; //Translate point to the origin + + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; //perform rotation + + r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad); + r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad); + r[2] = p[2]; //translate to correct position + + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + return out; +} +/** + * Get the angle between two 3D vectors + * @param {ReadonlyVec3} a The first operand + * @param {ReadonlyVec3} b The second operand + * @returns {Number} The angle in radians + */ + +function angle$1(a, b) { + var ax = a[0], + ay = a[1], + az = a[2], + bx = b[0], + by = b[1], + bz = b[2], + mag1 = Math.sqrt(ax * ax + ay * ay + az * az), + mag2 = Math.sqrt(bx * bx + by * by + bz * bz), + mag = mag1 * mag2, + cosine = mag && dot$5(a, b) / mag; + return Math.acos(Math.min(Math.max(cosine, -1), 1)); +} +/** + * Set the components of a vec3 to zero + * + * @param {vec3} out the receiving vector + * @returns {vec3} out + */ + +function zero$2(out) { + out[0] = 0.0; + out[1] = 0.0; + out[2] = 0.0; + return out; +} +/** + * Returns a string representation of a vector + * + * @param {ReadonlyVec3} a vector to represent as a string + * @returns {String} string representation of the vector + */ + +function str$4(a) { + return "vec3(" + a[0] + ", " + a[1] + ", " + a[2] + ")"; +} +/** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyVec3} a The first vector. + * @param {ReadonlyVec3} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function exactEquals$4(a, b) { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; +} +/** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {ReadonlyVec3} a The first vector. + * @param {ReadonlyVec3} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function equals$5(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2]; + var b0 = b[0], + b1 = b[1], + b2 = b[2]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)); +} +/** + * Alias for {@link vec3.subtract} + * @function + */ + +var sub$2 = subtract$2; +/** + * Alias for {@link vec3.multiply} + * @function + */ + +var mul$4 = multiply$4; +/** + * Alias for {@link vec3.divide} + * @function + */ + +var div$2 = divide$2; +/** + * Alias for {@link vec3.distance} + * @function + */ + +var dist$2 = distance$2; +/** + * Alias for {@link vec3.squaredDistance} + * @function + */ + +var sqrDist$2 = squaredDistance$2; +/** + * Alias for {@link vec3.length} + * @function + */ + +var len$4 = length$4; +/** + * Alias for {@link vec3.squaredLength} + * @function + */ + +var sqrLen$4 = squaredLength$4; +/** + * Perform some operation over an array of vec3s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ + +var forEach$2 = function () { + var vec = create$5(); + return function (a, stride, offset, count, fn, arg) { + var i, l; + + if (!stride) { + stride = 3; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min(count * stride + offset, a.length); + } else { + l = a.length; + } + + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + vec[2] = a[i + 2]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + a[i + 2] = vec[2]; + } + + return a; + }; +}(); + +var vec3 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$4, +angle: angle$1, +bezier: bezier, +ceil: ceil$2, +clone: clone$4, +copy: copy$4, +create: create$5, +cross: cross$2, +dist: dist$2, +distance: distance$2, +div: div$2, +divide: divide$2, +dot: dot$5, +equals: equals$5, +exactEquals: exactEquals$4, +floor: floor$2, +forEach: forEach$2, +fromValues: fromValues$4, +hermite: hermite, +inverse: inverse$2, +len: len$4, +length: length$4, +lerp: lerp$4, +max: max$2, +min: min$2, +mul: mul$4, +multiply: multiply$4, +negate: negate$2, +normalize: normalize$4, +random: random$3, +rotateX: rotateX$2, +rotateY: rotateY$2, +rotateZ: rotateZ$2, +round: round$2, +scale: scale$4, +scaleAndAdd: scaleAndAdd$2, +set: set$4, +sqrDist: sqrDist$2, +sqrLen: sqrLen$4, +squaredDistance: squaredDistance$2, +squaredLength: squaredLength$4, +str: str$4, +sub: sub$2, +subtract: subtract$2, +transformMat3: transformMat3$1, +transformMat4: transformMat4$2, +transformQuat: transformQuat$1, +zero: zero$2 +}); + +/** + * 4 Dimensional Vector + * @module vec4 + */ + +/** + * Creates a new, empty vec4 + * + * @returns {vec4} a new 4D vector + */ + +function create$4() { + var out = new ARRAY_TYPE(4); + + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 0; + } + + return out; +} +/** + * Creates a new vec4 initialized with values from an existing vector + * + * @param {ReadonlyVec4} a vector to clone + * @returns {vec4} a new 4D vector + */ + +function clone$3(a) { + var out = new ARRAY_TYPE(4); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +} +/** + * Creates a new vec4 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {vec4} a new 4D vector + */ + +function fromValues$3(x, y, z, w) { + var out = new ARRAY_TYPE(4); + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = w; + return out; +} +/** + * Copy the values from one vec4 to another + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the source vector + * @returns {vec4} out + */ + +function copy$3(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +} +/** + * Set the components of a vec4 to the given values + * + * @param {vec4} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {vec4} out + */ + +function set$3(out, x, y, z, w) { + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = w; + return out; +} +/** + * Adds two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function add$3(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + return out; +} +/** + * Subtracts vector b from vector a + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function subtract$1(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + return out; +} +/** + * Multiplies two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function multiply$3(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + out[2] = a[2] * b[2]; + out[3] = a[3] * b[3]; + return out; +} +/** + * Divides two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function divide$1(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + out[2] = a[2] / b[2]; + out[3] = a[3] / b[3]; + return out; +} +/** + * Math.ceil the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to ceil + * @returns {vec4} out + */ + +function ceil$1(out, a) { + out[0] = Math.ceil(a[0]); + out[1] = Math.ceil(a[1]); + out[2] = Math.ceil(a[2]); + out[3] = Math.ceil(a[3]); + return out; +} +/** + * Math.floor the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to floor + * @returns {vec4} out + */ + +function floor$1(out, a) { + out[0] = Math.floor(a[0]); + out[1] = Math.floor(a[1]); + out[2] = Math.floor(a[2]); + out[3] = Math.floor(a[3]); + return out; +} +/** + * Returns the minimum of two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function min$1(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + out[2] = Math.min(a[2], b[2]); + out[3] = Math.min(a[3], b[3]); + return out; +} +/** + * Returns the maximum of two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function max$1(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + out[2] = Math.max(a[2], b[2]); + out[3] = Math.max(a[3], b[3]); + return out; +} +/** + * Math.round the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to round + * @returns {vec4} out + */ + +function round$1(out, a) { + out[0] = Math.round(a[0]); + out[1] = Math.round(a[1]); + out[2] = Math.round(a[2]); + out[3] = Math.round(a[3]); + return out; +} +/** + * Scales a vec4 by a scalar number + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec4} out + */ + +function scale$3(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + return out; +} +/** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec4} out + */ + +function scaleAndAdd$1(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + return out; +} +/** + * Calculates the euclidian distance between two vec4's + * + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {Number} distance between a and b + */ + +function distance$1(a, b) { + var x = b[0] - a[0]; + var y = b[1] - a[1]; + var z = b[2] - a[2]; + var w = b[3] - a[3]; + return Math.hypot(x, y, z, w); +} +/** + * Calculates the squared euclidian distance between two vec4's + * + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {Number} squared distance between a and b + */ + +function squaredDistance$1(a, b) { + var x = b[0] - a[0]; + var y = b[1] - a[1]; + var z = b[2] - a[2]; + var w = b[3] - a[3]; + return x * x + y * y + z * z + w * w; +} +/** + * Calculates the length of a vec4 + * + * @param {ReadonlyVec4} a vector to calculate length of + * @returns {Number} length of a + */ + +function length$3(a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + var w = a[3]; + return Math.hypot(x, y, z, w); +} +/** + * Calculates the squared length of a vec4 + * + * @param {ReadonlyVec4} a vector to calculate squared length of + * @returns {Number} squared length of a + */ + +function squaredLength$3(a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + var w = a[3]; + return x * x + y * y + z * z + w * w; +} +/** + * Negates the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to negate + * @returns {vec4} out + */ + +function negate$1(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = -a[3]; + return out; +} +/** + * Returns the inverse of the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to invert + * @returns {vec4} out + */ + +function inverse$1(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + out[2] = 1.0 / a[2]; + out[3] = 1.0 / a[3]; + return out; +} +/** + * Normalize a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to normalize + * @returns {vec4} out + */ + +function normalize$3(out, a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + var w = a[3]; + var len = x * x + y * y + z * z + w * w; + + if (len > 0) { + len = 1 / Math.sqrt(len); + } + + out[0] = x * len; + out[1] = y * len; + out[2] = z * len; + out[3] = w * len; + return out; +} +/** + * Calculates the dot product of two vec4's + * + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {Number} dot product of a and b + */ + +function dot$4(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; +} +/** + * Returns the cross-product of three vectors in a 4-dimensional space + * + * @param {ReadonlyVec4} result the receiving vector + * @param {ReadonlyVec4} U the first vector + * @param {ReadonlyVec4} V the second vector + * @param {ReadonlyVec4} W the third vector + * @returns {vec4} result + */ + +function cross$1(out, u, v, w) { + var A = v[0] * w[1] - v[1] * w[0], + B = v[0] * w[2] - v[2] * w[0], + C = v[0] * w[3] - v[3] * w[0], + D = v[1] * w[2] - v[2] * w[1], + E = v[1] * w[3] - v[3] * w[1], + F = v[2] * w[3] - v[3] * w[2]; + var G = u[0]; + var H = u[1]; + var I = u[2]; + var J = u[3]; + out[0] = H * F - I * E + J * D; + out[1] = -(G * F) + I * C - J * B; + out[2] = G * E - H * C + J * A; + out[3] = -(G * D) + H * B - I * A; + return out; +} +/** + * Performs a linear interpolation between two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec4} out + */ + +function lerp$3(out, a, b, t) { + var ax = a[0]; + var ay = a[1]; + var az = a[2]; + var aw = a[3]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + out[2] = az + t * (b[2] - az); + out[3] = aw + t * (b[3] - aw); + return out; +} +/** + * Generates a random vector with the given scale + * + * @param {vec4} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec4} out + */ + +function random$2(out, scale) { + scale = scale || 1.0; // Marsaglia, George. Choosing a Point from the Surface of a + // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646. + // http://projecteuclid.org/euclid.aoms/1177692644; + + var v1, v2, v3, v4; + var s1, s2; + + do { + v1 = RANDOM() * 2 - 1; + v2 = RANDOM() * 2 - 1; + s1 = v1 * v1 + v2 * v2; + } while (s1 >= 1); + + do { + v3 = RANDOM() * 2 - 1; + v4 = RANDOM() * 2 - 1; + s2 = v3 * v3 + v4 * v4; + } while (s2 >= 1); + + var d = Math.sqrt((1 - s1) / s2); + out[0] = scale * v1; + out[1] = scale * v2; + out[2] = scale * v3 * d; + out[3] = scale * v4 * d; + return out; +} +/** + * Transforms the vec4 with a mat4. + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the vector to transform + * @param {ReadonlyMat4} m matrix to transform with + * @returns {vec4} out + */ + +function transformMat4$1(out, a, m) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w; + out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w; + out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w; + out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w; + return out; +} +/** + * Transforms the vec4 with a quat + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the vector to transform + * @param {ReadonlyQuat} q quaternion to transform with + * @returns {vec4} out + */ + +function transformQuat(out, a, q) { + var x = a[0], + y = a[1], + z = a[2]; + var qx = q[0], + qy = q[1], + qz = q[2], + qw = q[3]; // calculate quat * vec + + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; + var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat + + out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy; + out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz; + out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx; + out[3] = a[3]; + return out; +} +/** + * Set the components of a vec4 to zero + * + * @param {vec4} out the receiving vector + * @returns {vec4} out + */ + +function zero$1(out) { + out[0] = 0.0; + out[1] = 0.0; + out[2] = 0.0; + out[3] = 0.0; + return out; +} +/** + * Returns a string representation of a vector + * + * @param {ReadonlyVec4} a vector to represent as a string + * @returns {String} string representation of the vector + */ + +function str$3(a) { + return "vec4(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ")"; +} +/** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyVec4} a The first vector. + * @param {ReadonlyVec4} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function exactEquals$3(a, b) { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3]; +} +/** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {ReadonlyVec4} a The first vector. + * @param {ReadonlyVec4} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function equals$4(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)); +} +/** + * Alias for {@link vec4.subtract} + * @function + */ + +var sub$1 = subtract$1; +/** + * Alias for {@link vec4.multiply} + * @function + */ + +var mul$3 = multiply$3; +/** + * Alias for {@link vec4.divide} + * @function + */ + +var div$1 = divide$1; +/** + * Alias for {@link vec4.distance} + * @function + */ + +var dist$1 = distance$1; +/** + * Alias for {@link vec4.squaredDistance} + * @function + */ + +var sqrDist$1 = squaredDistance$1; +/** + * Alias for {@link vec4.length} + * @function + */ + +var len$3 = length$3; +/** + * Alias for {@link vec4.squaredLength} + * @function + */ + +var sqrLen$3 = squaredLength$3; +/** + * Perform some operation over an array of vec4s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ + +var forEach$1 = function () { + var vec = create$4(); + return function (a, stride, offset, count, fn, arg) { + var i, l; + + if (!stride) { + stride = 4; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min(count * stride + offset, a.length); + } else { + l = a.length; + } + + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + vec[2] = a[i + 2]; + vec[3] = a[i + 3]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + a[i + 2] = vec[2]; + a[i + 3] = vec[3]; + } + + return a; + }; +}(); + +var vec4 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$3, +ceil: ceil$1, +clone: clone$3, +copy: copy$3, +create: create$4, +cross: cross$1, +dist: dist$1, +distance: distance$1, +div: div$1, +divide: divide$1, +dot: dot$4, +equals: equals$4, +exactEquals: exactEquals$3, +floor: floor$1, +forEach: forEach$1, +fromValues: fromValues$3, +inverse: inverse$1, +len: len$3, +length: length$3, +lerp: lerp$3, +max: max$1, +min: min$1, +mul: mul$3, +multiply: multiply$3, +negate: negate$1, +normalize: normalize$3, +random: random$2, +round: round$1, +scale: scale$3, +scaleAndAdd: scaleAndAdd$1, +set: set$3, +sqrDist: sqrDist$1, +sqrLen: sqrLen$3, +squaredDistance: squaredDistance$1, +squaredLength: squaredLength$3, +str: str$3, +sub: sub$1, +subtract: subtract$1, +transformMat4: transformMat4$1, +transformQuat: transformQuat, +zero: zero$1 +}); + +/** + * Quaternion + * @module quat + */ + +/** + * Creates a new identity quat + * + * @returns {quat} a new quaternion + */ + +function create$3() { + var out = new ARRAY_TYPE(4); + + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + } + + out[3] = 1; + return out; +} +/** + * Set a quat to the identity quaternion + * + * @param {quat} out the receiving quaternion + * @returns {quat} out + */ + +function identity$1(out) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +} +/** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyVec3} axis the axis around which to rotate + * @param {Number} rad the angle in radians + * @returns {quat} out + **/ + +function setAxisAngle(out, axis, rad) { + rad = rad * 0.5; + var s = Math.sin(rad); + out[0] = s * axis[0]; + out[1] = s * axis[1]; + out[2] = s * axis[2]; + out[3] = Math.cos(rad); + return out; +} +/** + * Gets the rotation axis and angle for a given + * quaternion. If a quaternion is created with + * setAxisAngle, this method will return the same + * values as providied in the original parameter list + * OR functionally equivalent values. + * Example: The quaternion formed by axis [0, 0, 1] and + * angle -90 is the same as the quaternion formed by + * [0, 0, 1] and 270. This method favors the latter. + * @param {vec3} out_axis Vector receiving the axis of rotation + * @param {ReadonlyQuat} q Quaternion to be decomposed + * @return {Number} Angle, in radians, of the rotation + */ + +function getAxisAngle(out_axis, q) { + var rad = Math.acos(q[3]) * 2.0; + var s = Math.sin(rad / 2.0); + + if (s > EPSILON) { + out_axis[0] = q[0] / s; + out_axis[1] = q[1] / s; + out_axis[2] = q[2] / s; + } else { + // If s is zero, return any axis (no rotation - axis does not matter) + out_axis[0] = 1; + out_axis[1] = 0; + out_axis[2] = 0; + } + + return rad; +} +/** + * Gets the angular distance between two unit quaternions + * + * @param {ReadonlyQuat} a Origin unit quaternion + * @param {ReadonlyQuat} b Destination unit quaternion + * @return {Number} Angle, in radians, between the two quaternions + */ + +function getAngle(a, b) { + var dotproduct = dot$3(a, b); + return Math.acos(2 * dotproduct * dotproduct - 1); +} +/** + * Multiplies two quat's + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @returns {quat} out + */ + +function multiply$2(out, a, b) { + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var bx = b[0], + by = b[1], + bz = b[2], + bw = b[3]; + out[0] = ax * bw + aw * bx + ay * bz - az * by; + out[1] = ay * bw + aw * by + az * bx - ax * bz; + out[2] = az * bw + aw * bz + ax * by - ay * bx; + out[3] = aw * bw - ax * bx - ay * by - az * bz; + return out; +} +/** + * Rotates a quaternion by the given angle about the X axis + * + * @param {quat} out quat receiving operation result + * @param {ReadonlyQuat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ + +function rotateX$1(out, a, rad) { + rad *= 0.5; + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var bx = Math.sin(rad), + bw = Math.cos(rad); + out[0] = ax * bw + aw * bx; + out[1] = ay * bw + az * bx; + out[2] = az * bw - ay * bx; + out[3] = aw * bw - ax * bx; + return out; +} +/** + * Rotates a quaternion by the given angle about the Y axis + * + * @param {quat} out quat receiving operation result + * @param {ReadonlyQuat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ + +function rotateY$1(out, a, rad) { + rad *= 0.5; + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var by = Math.sin(rad), + bw = Math.cos(rad); + out[0] = ax * bw - az * by; + out[1] = ay * bw + aw * by; + out[2] = az * bw + ax * by; + out[3] = aw * bw - ay * by; + return out; +} +/** + * Rotates a quaternion by the given angle about the Z axis + * + * @param {quat} out quat receiving operation result + * @param {ReadonlyQuat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ + +function rotateZ$1(out, a, rad) { + rad *= 0.5; + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var bz = Math.sin(rad), + bw = Math.cos(rad); + out[0] = ax * bw + ay * bz; + out[1] = ay * bw - ax * bz; + out[2] = az * bw + aw * bz; + out[3] = aw * bw - az * bz; + return out; +} +/** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate W component of + * @returns {quat} out + */ + +function calculateW(out, a) { + var x = a[0], + y = a[1], + z = a[2]; + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z)); + return out; +} +/** + * Calculate the exponential of a unit quaternion. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate the exponential of + * @returns {quat} out + */ + +function exp(out, a) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + var r = Math.sqrt(x * x + y * y + z * z); + var et = Math.exp(w); + var s = r > 0 ? et * Math.sin(r) / r : 0; + out[0] = x * s; + out[1] = y * s; + out[2] = z * s; + out[3] = et * Math.cos(r); + return out; +} +/** + * Calculate the natural logarithm of a unit quaternion. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate the exponential of + * @returns {quat} out + */ + +function ln(out, a) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + var r = Math.sqrt(x * x + y * y + z * z); + var t = r > 0 ? Math.atan2(r, w) / r : 0; + out[0] = x * t; + out[1] = y * t; + out[2] = z * t; + out[3] = 0.5 * Math.log(x * x + y * y + z * z + w * w); + return out; +} +/** + * Calculate the scalar power of a unit quaternion. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate the exponential of + * @param {Number} b amount to scale the quaternion by + * @returns {quat} out + */ + +function pow(out, a, b) { + ln(out, a); + scale$2(out, out, b); + exp(out, out); + return out; +} +/** + * Performs a spherical linear interpolation between two quat + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {quat} out + */ + +function slerp(out, a, b, t) { + // benchmarks: + // http://jsperf.com/quaternion-slerp-implementations + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var bx = b[0], + by = b[1], + bz = b[2], + bw = b[3]; + var omega, cosom, sinom, scale0, scale1; // calc cosine + + cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary) + + if (cosom < 0.0) { + cosom = -cosom; + bx = -bx; + by = -by; + bz = -bz; + bw = -bw; + } // calculate coefficients + + + if (1.0 - cosom > EPSILON) { + // standard case (slerp) + omega = Math.acos(cosom); + sinom = Math.sin(omega); + scale0 = Math.sin((1.0 - t) * omega) / sinom; + scale1 = Math.sin(t * omega) / sinom; + } else { + // "from" and "to" quaternions are very close + // ... so we can do a linear interpolation + scale0 = 1.0 - t; + scale1 = t; + } // calculate final values + + + out[0] = scale0 * ax + scale1 * bx; + out[1] = scale0 * ay + scale1 * by; + out[2] = scale0 * az + scale1 * bz; + out[3] = scale0 * aw + scale1 * bw; + return out; +} +/** + * Generates a random unit quaternion + * + * @param {quat} out the receiving quaternion + * @returns {quat} out + */ + +function random$1(out) { + // Implementation of http://planning.cs.uiuc.edu/node198.html + // TODO: Calling random 3 times is probably not the fastest solution + var u1 = RANDOM(); + var u2 = RANDOM(); + var u3 = RANDOM(); + var sqrt1MinusU1 = Math.sqrt(1 - u1); + var sqrtU1 = Math.sqrt(u1); + out[0] = sqrt1MinusU1 * Math.sin(2.0 * Math.PI * u2); + out[1] = sqrt1MinusU1 * Math.cos(2.0 * Math.PI * u2); + out[2] = sqrtU1 * Math.sin(2.0 * Math.PI * u3); + out[3] = sqrtU1 * Math.cos(2.0 * Math.PI * u3); + return out; +} +/** + * Calculates the inverse of a quat + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate inverse of + * @returns {quat} out + */ + +function invert$1(out, a) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; + var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 + + out[0] = -a0 * invDot; + out[1] = -a1 * invDot; + out[2] = -a2 * invDot; + out[3] = a3 * invDot; + return out; +} +/** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate conjugate of + * @returns {quat} out + */ + +function conjugate$1(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = a[3]; + return out; +} +/** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyMat3} m rotation matrix + * @returns {quat} out + * @function + */ + +function fromMat3(out, m) { + // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes + // article "Quaternion Calculus and Fast Animation". + var fTrace = m[0] + m[4] + m[8]; + var fRoot; + + if (fTrace > 0.0) { + // |w| > 1/2, may as well choose w > 1/2 + fRoot = Math.sqrt(fTrace + 1.0); // 2w + + out[3] = 0.5 * fRoot; + fRoot = 0.5 / fRoot; // 1/(4w) + + out[0] = (m[5] - m[7]) * fRoot; + out[1] = (m[6] - m[2]) * fRoot; + out[2] = (m[1] - m[3]) * fRoot; + } else { + // |w| <= 1/2 + var i = 0; + if (m[4] > m[0]) i = 1; + if (m[8] > m[i * 3 + i]) i = 2; + var j = (i + 1) % 3; + var k = (i + 2) % 3; + fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0); + out[i] = 0.5 * fRoot; + fRoot = 0.5 / fRoot; + out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot; + out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot; + out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot; + } + + return out; +} +/** + * Creates a quaternion from the given euler angle x, y, z. + * + * @param {quat} out the receiving quaternion + * @param {x} Angle to rotate around X axis in degrees. + * @param {y} Angle to rotate around Y axis in degrees. + * @param {z} Angle to rotate around Z axis in degrees. + * @returns {quat} out + * @function + */ + +function fromEuler(out, x, y, z) { + var halfToRad = 0.5 * Math.PI / 180.0; + x *= halfToRad; + y *= halfToRad; + z *= halfToRad; + var sx = Math.sin(x); + var cx = Math.cos(x); + var sy = Math.sin(y); + var cy = Math.cos(y); + var sz = Math.sin(z); + var cz = Math.cos(z); + out[0] = sx * cy * cz - cx * sy * sz; + out[1] = cx * sy * cz + sx * cy * sz; + out[2] = cx * cy * sz - sx * sy * cz; + out[3] = cx * cy * cz + sx * sy * sz; + return out; +} +/** + * Returns a string representation of a quatenion + * + * @param {ReadonlyQuat} a vector to represent as a string + * @returns {String} string representation of the vector + */ + +function str$2(a) { + return "quat(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ")"; +} +/** + * Creates a new quat initialized with values from an existing quaternion + * + * @param {ReadonlyQuat} a quaternion to clone + * @returns {quat} a new quaternion + * @function + */ + +var clone$2 = clone$3; +/** + * Creates a new quat initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {quat} a new quaternion + * @function + */ + +var fromValues$2 = fromValues$3; +/** + * Copy the values from one quat to another + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the source quaternion + * @returns {quat} out + * @function + */ + +var copy$2 = copy$3; +/** + * Set the components of a quat to the given values + * + * @param {quat} out the receiving quaternion + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {quat} out + * @function + */ + +var set$2 = set$3; +/** + * Adds two quat's + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @returns {quat} out + * @function + */ + +var add$2 = add$3; +/** + * Alias for {@link quat.multiply} + * @function + */ + +var mul$2 = multiply$2; +/** + * Scales a quat by a scalar number + * + * @param {quat} out the receiving vector + * @param {ReadonlyQuat} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {quat} out + * @function + */ + +var scale$2 = scale$3; +/** + * Calculates the dot product of two quat's + * + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @returns {Number} dot product of a and b + * @function + */ + +var dot$3 = dot$4; +/** + * Performs a linear interpolation between two quat's + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {quat} out + * @function + */ + +var lerp$2 = lerp$3; +/** + * Calculates the length of a quat + * + * @param {ReadonlyQuat} a vector to calculate length of + * @returns {Number} length of a + */ + +var length$2 = length$3; +/** + * Alias for {@link quat.length} + * @function + */ + +var len$2 = length$2; +/** + * Calculates the squared length of a quat + * + * @param {ReadonlyQuat} a vector to calculate squared length of + * @returns {Number} squared length of a + * @function + */ + +var squaredLength$2 = squaredLength$3; +/** + * Alias for {@link quat.squaredLength} + * @function + */ + +var sqrLen$2 = squaredLength$2; +/** + * Normalize a quat + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quaternion to normalize + * @returns {quat} out + * @function + */ + +var normalize$2 = normalize$3; +/** + * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyQuat} a The first quaternion. + * @param {ReadonlyQuat} b The second quaternion. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +var exactEquals$2 = exactEquals$3; +/** + * Returns whether or not the quaternions have approximately the same elements in the same position. + * + * @param {ReadonlyQuat} a The first vector. + * @param {ReadonlyQuat} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +var equals$3 = equals$4; +/** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {ReadonlyVec3} a the initial vector + * @param {ReadonlyVec3} b the destination vector + * @returns {quat} out + */ + +var rotationTo = function () { + var tmpvec3 = create$5(); + var xUnitVec3 = fromValues$4(1, 0, 0); + var yUnitVec3 = fromValues$4(0, 1, 0); + return function (out, a, b) { + var dot = dot$5(a, b); + + if (dot < -0.999999) { + cross$2(tmpvec3, xUnitVec3, a); + if (len$4(tmpvec3) < 0.000001) cross$2(tmpvec3, yUnitVec3, a); + normalize$4(tmpvec3, tmpvec3); + setAxisAngle(out, tmpvec3, Math.PI); + return out; + } else if (dot > 0.999999) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; + } else { + cross$2(tmpvec3, a, b); + out[0] = tmpvec3[0]; + out[1] = tmpvec3[1]; + out[2] = tmpvec3[2]; + out[3] = 1 + dot; + return normalize$2(out, out); + } + }; +}(); +/** + * Performs a spherical linear interpolation with two control points + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @param {ReadonlyQuat} c the third operand + * @param {ReadonlyQuat} d the fourth operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {quat} out + */ + +var sqlerp = function () { + var temp1 = create$3(); + var temp2 = create$3(); + return function (out, a, b, c, d, t) { + slerp(temp1, a, d, t); + slerp(temp2, b, c, t); + slerp(out, temp1, temp2, 2 * t * (1 - t)); + return out; + }; +}(); +/** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {ReadonlyVec3} view the vector representing the viewing direction + * @param {ReadonlyVec3} right the vector representing the local "right" direction + * @param {ReadonlyVec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + +var setAxes = function () { + var matr = create$7(); + return function (out, view, right, up) { + matr[0] = right[0]; + matr[3] = right[1]; + matr[6] = right[2]; + matr[1] = up[0]; + matr[4] = up[1]; + matr[7] = up[2]; + matr[2] = -view[0]; + matr[5] = -view[1]; + matr[8] = -view[2]; + return normalize$2(out, fromMat3(out, matr)); + }; +}(); + +var quat = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$2, +calculateW: calculateW, +clone: clone$2, +conjugate: conjugate$1, +copy: copy$2, +create: create$3, +dot: dot$3, +equals: equals$3, +exactEquals: exactEquals$2, +exp: exp, +fromEuler: fromEuler, +fromMat3: fromMat3, +fromValues: fromValues$2, +getAngle: getAngle, +getAxisAngle: getAxisAngle, +identity: identity$1, +invert: invert$1, +len: len$2, +length: length$2, +lerp: lerp$2, +ln: ln, +mul: mul$2, +multiply: multiply$2, +normalize: normalize$2, +pow: pow, +random: random$1, +rotateX: rotateX$1, +rotateY: rotateY$1, +rotateZ: rotateZ$1, +rotationTo: rotationTo, +scale: scale$2, +set: set$2, +setAxes: setAxes, +setAxisAngle: setAxisAngle, +slerp: slerp, +sqlerp: sqlerp, +sqrLen: sqrLen$2, +squaredLength: squaredLength$2, +str: str$2 +}); + +/** + * Dual Quaternion
+ * Format: [real, dual]
+ * Quaternion format: XYZW
+ * Make sure to have normalized dual quaternions, otherwise the functions may not work as intended.
+ * @module quat2 + */ + +/** + * Creates a new identity dual quat + * + * @returns {quat2} a new dual quaternion [real -> rotation, dual -> translation] + */ + +function create$2() { + var dq = new ARRAY_TYPE(8); + + if (ARRAY_TYPE != Float32Array) { + dq[0] = 0; + dq[1] = 0; + dq[2] = 0; + dq[4] = 0; + dq[5] = 0; + dq[6] = 0; + dq[7] = 0; + } + + dq[3] = 1; + return dq; +} +/** + * Creates a new quat initialized with values from an existing quaternion + * + * @param {ReadonlyQuat2} a dual quaternion to clone + * @returns {quat2} new dual quaternion + * @function + */ + +function clone$1(a) { + var dq = new ARRAY_TYPE(8); + dq[0] = a[0]; + dq[1] = a[1]; + dq[2] = a[2]; + dq[3] = a[3]; + dq[4] = a[4]; + dq[5] = a[5]; + dq[6] = a[6]; + dq[7] = a[7]; + return dq; +} +/** + * Creates a new dual quat initialized with the given values + * + * @param {Number} x1 X component + * @param {Number} y1 Y component + * @param {Number} z1 Z component + * @param {Number} w1 W component + * @param {Number} x2 X component + * @param {Number} y2 Y component + * @param {Number} z2 Z component + * @param {Number} w2 W component + * @returns {quat2} new dual quaternion + * @function + */ + +function fromValues$1(x1, y1, z1, w1, x2, y2, z2, w2) { + var dq = new ARRAY_TYPE(8); + dq[0] = x1; + dq[1] = y1; + dq[2] = z1; + dq[3] = w1; + dq[4] = x2; + dq[5] = y2; + dq[6] = z2; + dq[7] = w2; + return dq; +} +/** + * Creates a new dual quat from the given values (quat and translation) + * + * @param {Number} x1 X component + * @param {Number} y1 Y component + * @param {Number} z1 Z component + * @param {Number} w1 W component + * @param {Number} x2 X component (translation) + * @param {Number} y2 Y component (translation) + * @param {Number} z2 Z component (translation) + * @returns {quat2} new dual quaternion + * @function + */ + +function fromRotationTranslationValues(x1, y1, z1, w1, x2, y2, z2) { + var dq = new ARRAY_TYPE(8); + dq[0] = x1; + dq[1] = y1; + dq[2] = z1; + dq[3] = w1; + var ax = x2 * 0.5, + ay = y2 * 0.5, + az = z2 * 0.5; + dq[4] = ax * w1 + ay * z1 - az * y1; + dq[5] = ay * w1 + az * x1 - ax * z1; + dq[6] = az * w1 + ax * y1 - ay * x1; + dq[7] = -ax * x1 - ay * y1 - az * z1; + return dq; +} +/** + * Creates a dual quat from a quaternion and a translation + * + * @param {ReadonlyQuat2} dual quaternion receiving operation result + * @param {ReadonlyQuat} q a normalized quaternion + * @param {ReadonlyVec3} t tranlation vector + * @returns {quat2} dual quaternion receiving operation result + * @function + */ + +function fromRotationTranslation(out, q, t) { + var ax = t[0] * 0.5, + ay = t[1] * 0.5, + az = t[2] * 0.5, + bx = q[0], + by = q[1], + bz = q[2], + bw = q[3]; + out[0] = bx; + out[1] = by; + out[2] = bz; + out[3] = bw; + out[4] = ax * bw + ay * bz - az * by; + out[5] = ay * bw + az * bx - ax * bz; + out[6] = az * bw + ax * by - ay * bx; + out[7] = -ax * bx - ay * by - az * bz; + return out; +} +/** + * Creates a dual quat from a translation + * + * @param {ReadonlyQuat2} dual quaternion receiving operation result + * @param {ReadonlyVec3} t translation vector + * @returns {quat2} dual quaternion receiving operation result + * @function + */ + +function fromTranslation(out, t) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = t[0] * 0.5; + out[5] = t[1] * 0.5; + out[6] = t[2] * 0.5; + out[7] = 0; + return out; +} +/** + * Creates a dual quat from a quaternion + * + * @param {ReadonlyQuat2} dual quaternion receiving operation result + * @param {ReadonlyQuat} q the quaternion + * @returns {quat2} dual quaternion receiving operation result + * @function + */ + +function fromRotation(out, q) { + out[0] = q[0]; + out[1] = q[1]; + out[2] = q[2]; + out[3] = q[3]; + out[4] = 0; + out[5] = 0; + out[6] = 0; + out[7] = 0; + return out; +} +/** + * Creates a new dual quat from a matrix (4x4) + * + * @param {quat2} out the dual quaternion + * @param {ReadonlyMat4} a the matrix + * @returns {quat2} dual quat receiving operation result + * @function + */ + +function fromMat4(out, a) { + //TODO Optimize this + var outer = create$3(); + getRotation(outer, a); + var t = new ARRAY_TYPE(3); + getTranslation$1(t, a); + fromRotationTranslation(out, outer, t); + return out; +} +/** + * Copy the values from one dual quat to another + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the source dual quaternion + * @returns {quat2} out + * @function + */ + +function copy$1(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + return out; +} +/** + * Set a dual quat to the identity dual quaternion + * + * @param {quat2} out the receiving quaternion + * @returns {quat2} out + */ + +function identity(out) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = 0; + out[5] = 0; + out[6] = 0; + out[7] = 0; + return out; +} +/** + * Set the components of a dual quat to the given values + * + * @param {quat2} out the receiving quaternion + * @param {Number} x1 X component + * @param {Number} y1 Y component + * @param {Number} z1 Z component + * @param {Number} w1 W component + * @param {Number} x2 X component + * @param {Number} y2 Y component + * @param {Number} z2 Z component + * @param {Number} w2 W component + * @returns {quat2} out + * @function + */ + +function set$1(out, x1, y1, z1, w1, x2, y2, z2, w2) { + out[0] = x1; + out[1] = y1; + out[2] = z1; + out[3] = w1; + out[4] = x2; + out[5] = y2; + out[6] = z2; + out[7] = w2; + return out; +} +/** + * Gets the real part of a dual quat + * @param {quat} out real part + * @param {ReadonlyQuat2} a Dual Quaternion + * @return {quat} real part + */ + +var getReal = copy$2; +/** + * Gets the dual part of a dual quat + * @param {quat} out dual part + * @param {ReadonlyQuat2} a Dual Quaternion + * @return {quat} dual part + */ + +function getDual(out, a) { + out[0] = a[4]; + out[1] = a[5]; + out[2] = a[6]; + out[3] = a[7]; + return out; +} +/** + * Set the real component of a dual quat to the given quaternion + * + * @param {quat2} out the receiving quaternion + * @param {ReadonlyQuat} q a quaternion representing the real part + * @returns {quat2} out + * @function + */ + +var setReal = copy$2; +/** + * Set the dual component of a dual quat to the given quaternion + * + * @param {quat2} out the receiving quaternion + * @param {ReadonlyQuat} q a quaternion representing the dual part + * @returns {quat2} out + * @function + */ + +function setDual(out, q) { + out[4] = q[0]; + out[5] = q[1]; + out[6] = q[2]; + out[7] = q[3]; + return out; +} +/** + * Gets the translation of a normalized dual quat + * @param {vec3} out translation + * @param {ReadonlyQuat2} a Dual Quaternion to be decomposed + * @return {vec3} translation + */ + +function getTranslation(out, a) { + var ax = a[4], + ay = a[5], + az = a[6], + aw = a[7], + bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3]; + out[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2; + out[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2; + out[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2; + return out; +} +/** + * Translates a dual quat by the given vector + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to translate + * @param {ReadonlyVec3} v vector to translate by + * @returns {quat2} out + */ + +function translate(out, a, v) { + var ax1 = a[0], + ay1 = a[1], + az1 = a[2], + aw1 = a[3], + bx1 = v[0] * 0.5, + by1 = v[1] * 0.5, + bz1 = v[2] * 0.5, + ax2 = a[4], + ay2 = a[5], + az2 = a[6], + aw2 = a[7]; + out[0] = ax1; + out[1] = ay1; + out[2] = az1; + out[3] = aw1; + out[4] = aw1 * bx1 + ay1 * bz1 - az1 * by1 + ax2; + out[5] = aw1 * by1 + az1 * bx1 - ax1 * bz1 + ay2; + out[6] = aw1 * bz1 + ax1 * by1 - ay1 * bx1 + az2; + out[7] = -ax1 * bx1 - ay1 * by1 - az1 * bz1 + aw2; + return out; +} +/** + * Rotates a dual quat around the X axis + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {number} rad how far should the rotation be + * @returns {quat2} out + */ + +function rotateX(out, a, rad) { + var bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3], + ax = a[4], + ay = a[5], + az = a[6], + aw = a[7], + ax1 = ax * bw + aw * bx + ay * bz - az * by, + ay1 = ay * bw + aw * by + az * bx - ax * bz, + az1 = az * bw + aw * bz + ax * by - ay * bx, + aw1 = aw * bw - ax * bx - ay * by - az * bz; + rotateX$1(out, a, rad); + bx = out[0]; + by = out[1]; + bz = out[2]; + bw = out[3]; + out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; + out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; + out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; + out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; + return out; +} +/** + * Rotates a dual quat around the Y axis + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {number} rad how far should the rotation be + * @returns {quat2} out + */ + +function rotateY(out, a, rad) { + var bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3], + ax = a[4], + ay = a[5], + az = a[6], + aw = a[7], + ax1 = ax * bw + aw * bx + ay * bz - az * by, + ay1 = ay * bw + aw * by + az * bx - ax * bz, + az1 = az * bw + aw * bz + ax * by - ay * bx, + aw1 = aw * bw - ax * bx - ay * by - az * bz; + rotateY$1(out, a, rad); + bx = out[0]; + by = out[1]; + bz = out[2]; + bw = out[3]; + out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; + out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; + out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; + out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; + return out; +} +/** + * Rotates a dual quat around the Z axis + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {number} rad how far should the rotation be + * @returns {quat2} out + */ + +function rotateZ(out, a, rad) { + var bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3], + ax = a[4], + ay = a[5], + az = a[6], + aw = a[7], + ax1 = ax * bw + aw * bx + ay * bz - az * by, + ay1 = ay * bw + aw * by + az * bx - ax * bz, + az1 = az * bw + aw * bz + ax * by - ay * bx, + aw1 = aw * bw - ax * bx - ay * by - az * bz; + rotateZ$1(out, a, rad); + bx = out[0]; + by = out[1]; + bz = out[2]; + bw = out[3]; + out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; + out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; + out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; + out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; + return out; +} +/** + * Rotates a dual quat by a given quaternion (a * q) + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {ReadonlyQuat} q quaternion to rotate by + * @returns {quat2} out + */ + +function rotateByQuatAppend(out, a, q) { + var qx = q[0], + qy = q[1], + qz = q[2], + qw = q[3], + ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + out[0] = ax * qw + aw * qx + ay * qz - az * qy; + out[1] = ay * qw + aw * qy + az * qx - ax * qz; + out[2] = az * qw + aw * qz + ax * qy - ay * qx; + out[3] = aw * qw - ax * qx - ay * qy - az * qz; + ax = a[4]; + ay = a[5]; + az = a[6]; + aw = a[7]; + out[4] = ax * qw + aw * qx + ay * qz - az * qy; + out[5] = ay * qw + aw * qy + az * qx - ax * qz; + out[6] = az * qw + aw * qz + ax * qy - ay * qx; + out[7] = aw * qw - ax * qx - ay * qy - az * qz; + return out; +} +/** + * Rotates a dual quat by a given quaternion (q * a) + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat} q quaternion to rotate by + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @returns {quat2} out + */ + +function rotateByQuatPrepend(out, q, a) { + var qx = q[0], + qy = q[1], + qz = q[2], + qw = q[3], + bx = a[0], + by = a[1], + bz = a[2], + bw = a[3]; + out[0] = qx * bw + qw * bx + qy * bz - qz * by; + out[1] = qy * bw + qw * by + qz * bx - qx * bz; + out[2] = qz * bw + qw * bz + qx * by - qy * bx; + out[3] = qw * bw - qx * bx - qy * by - qz * bz; + bx = a[4]; + by = a[5]; + bz = a[6]; + bw = a[7]; + out[4] = qx * bw + qw * bx + qy * bz - qz * by; + out[5] = qy * bw + qw * by + qz * bx - qx * bz; + out[6] = qz * bw + qw * bz + qx * by - qy * bx; + out[7] = qw * bw - qx * bx - qy * by - qz * bz; + return out; +} +/** + * Rotates a dual quat around a given axis. Does the normalisation automatically + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {ReadonlyVec3} axis the axis to rotate around + * @param {Number} rad how far the rotation should be + * @returns {quat2} out + */ + +function rotateAroundAxis(out, a, axis, rad) { + //Special case for rad = 0 + if (Math.abs(rad) < EPSILON) { + return copy$1(out, a); + } + + var axisLength = Math.hypot(axis[0], axis[1], axis[2]); + rad = rad * 0.5; + var s = Math.sin(rad); + var bx = s * axis[0] / axisLength; + var by = s * axis[1] / axisLength; + var bz = s * axis[2] / axisLength; + var bw = Math.cos(rad); + var ax1 = a[0], + ay1 = a[1], + az1 = a[2], + aw1 = a[3]; + out[0] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; + out[1] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; + out[2] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; + out[3] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; + var ax = a[4], + ay = a[5], + az = a[6], + aw = a[7]; + out[4] = ax * bw + aw * bx + ay * bz - az * by; + out[5] = ay * bw + aw * by + az * bx - ax * bz; + out[6] = az * bw + aw * bz + ax * by - ay * bx; + out[7] = aw * bw - ax * bx - ay * by - az * bz; + return out; +} +/** + * Adds two dual quat's + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the first operand + * @param {ReadonlyQuat2} b the second operand + * @returns {quat2} out + * @function + */ + +function add$1(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + out[4] = a[4] + b[4]; + out[5] = a[5] + b[5]; + out[6] = a[6] + b[6]; + out[7] = a[7] + b[7]; + return out; +} +/** + * Multiplies two dual quat's + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the first operand + * @param {ReadonlyQuat2} b the second operand + * @returns {quat2} out + */ + +function multiply$1(out, a, b) { + var ax0 = a[0], + ay0 = a[1], + az0 = a[2], + aw0 = a[3], + bx1 = b[4], + by1 = b[5], + bz1 = b[6], + bw1 = b[7], + ax1 = a[4], + ay1 = a[5], + az1 = a[6], + aw1 = a[7], + bx0 = b[0], + by0 = b[1], + bz0 = b[2], + bw0 = b[3]; + out[0] = ax0 * bw0 + aw0 * bx0 + ay0 * bz0 - az0 * by0; + out[1] = ay0 * bw0 + aw0 * by0 + az0 * bx0 - ax0 * bz0; + out[2] = az0 * bw0 + aw0 * bz0 + ax0 * by0 - ay0 * bx0; + out[3] = aw0 * bw0 - ax0 * bx0 - ay0 * by0 - az0 * bz0; + out[4] = ax0 * bw1 + aw0 * bx1 + ay0 * bz1 - az0 * by1 + ax1 * bw0 + aw1 * bx0 + ay1 * bz0 - az1 * by0; + out[5] = ay0 * bw1 + aw0 * by1 + az0 * bx1 - ax0 * bz1 + ay1 * bw0 + aw1 * by0 + az1 * bx0 - ax1 * bz0; + out[6] = az0 * bw1 + aw0 * bz1 + ax0 * by1 - ay0 * bx1 + az1 * bw0 + aw1 * bz0 + ax1 * by0 - ay1 * bx0; + out[7] = aw0 * bw1 - ax0 * bx1 - ay0 * by1 - az0 * bz1 + aw1 * bw0 - ax1 * bx0 - ay1 * by0 - az1 * bz0; + return out; +} +/** + * Alias for {@link quat2.multiply} + * @function + */ + +var mul$1 = multiply$1; +/** + * Scales a dual quat by a scalar number + * + * @param {quat2} out the receiving dual quat + * @param {ReadonlyQuat2} a the dual quat to scale + * @param {Number} b amount to scale the dual quat by + * @returns {quat2} out + * @function + */ + +function scale$1(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + out[4] = a[4] * b; + out[5] = a[5] * b; + out[6] = a[6] * b; + out[7] = a[7] * b; + return out; +} +/** + * Calculates the dot product of two dual quat's (The dot product of the real parts) + * + * @param {ReadonlyQuat2} a the first operand + * @param {ReadonlyQuat2} b the second operand + * @returns {Number} dot product of a and b + * @function + */ + +var dot$2 = dot$3; +/** + * Performs a linear interpolation between two dual quats's + * NOTE: The resulting dual quaternions won't always be normalized (The error is most noticeable when t = 0.5) + * + * @param {quat2} out the receiving dual quat + * @param {ReadonlyQuat2} a the first operand + * @param {ReadonlyQuat2} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {quat2} out + */ + +function lerp$1(out, a, b, t) { + var mt = 1 - t; + if (dot$2(a, b) < 0) t = -t; + out[0] = a[0] * mt + b[0] * t; + out[1] = a[1] * mt + b[1] * t; + out[2] = a[2] * mt + b[2] * t; + out[3] = a[3] * mt + b[3] * t; + out[4] = a[4] * mt + b[4] * t; + out[5] = a[5] * mt + b[5] * t; + out[6] = a[6] * mt + b[6] * t; + out[7] = a[7] * mt + b[7] * t; + return out; +} +/** + * Calculates the inverse of a dual quat. If they are normalized, conjugate is cheaper + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a dual quat to calculate inverse of + * @returns {quat2} out + */ + +function invert(out, a) { + var sqlen = squaredLength$1(a); + out[0] = -a[0] / sqlen; + out[1] = -a[1] / sqlen; + out[2] = -a[2] / sqlen; + out[3] = a[3] / sqlen; + out[4] = -a[4] / sqlen; + out[5] = -a[5] / sqlen; + out[6] = -a[6] / sqlen; + out[7] = a[7] / sqlen; + return out; +} +/** + * Calculates the conjugate of a dual quat + * If the dual quaternion is normalized, this function is faster than quat2.inverse and produces the same result. + * + * @param {quat2} out the receiving quaternion + * @param {ReadonlyQuat2} a quat to calculate conjugate of + * @returns {quat2} out + */ + +function conjugate(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = a[3]; + out[4] = -a[4]; + out[5] = -a[5]; + out[6] = -a[6]; + out[7] = a[7]; + return out; +} +/** + * Calculates the length of a dual quat + * + * @param {ReadonlyQuat2} a dual quat to calculate length of + * @returns {Number} length of a + * @function + */ + +var length$1 = length$2; +/** + * Alias for {@link quat2.length} + * @function + */ + +var len$1 = length$1; +/** + * Calculates the squared length of a dual quat + * + * @param {ReadonlyQuat2} a dual quat to calculate squared length of + * @returns {Number} squared length of a + * @function + */ + +var squaredLength$1 = squaredLength$2; +/** + * Alias for {@link quat2.squaredLength} + * @function + */ + +var sqrLen$1 = squaredLength$1; +/** + * Normalize a dual quat + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a dual quaternion to normalize + * @returns {quat2} out + * @function + */ + +function normalize$1(out, a) { + var magnitude = squaredLength$1(a); + + if (magnitude > 0) { + magnitude = Math.sqrt(magnitude); + var a0 = a[0] / magnitude; + var a1 = a[1] / magnitude; + var a2 = a[2] / magnitude; + var a3 = a[3] / magnitude; + var b0 = a[4]; + var b1 = a[5]; + var b2 = a[6]; + var b3 = a[7]; + var a_dot_b = a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3; + out[0] = a0; + out[1] = a1; + out[2] = a2; + out[3] = a3; + out[4] = (b0 - a0 * a_dot_b) / magnitude; + out[5] = (b1 - a1 * a_dot_b) / magnitude; + out[6] = (b2 - a2 * a_dot_b) / magnitude; + out[7] = (b3 - a3 * a_dot_b) / magnitude; + } + + return out; +} +/** + * Returns a string representation of a dual quatenion + * + * @param {ReadonlyQuat2} a dual quaternion to represent as a string + * @returns {String} string representation of the dual quat + */ + +function str$1(a) { + return "quat2(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ", " + a[6] + ", " + a[7] + ")"; +} +/** + * Returns whether or not the dual quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyQuat2} a the first dual quaternion. + * @param {ReadonlyQuat2} b the second dual quaternion. + * @returns {Boolean} true if the dual quaternions are equal, false otherwise. + */ + +function exactEquals$1(a, b) { + 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]; +} +/** + * Returns whether or not the dual quaternions have approximately the same elements in the same position. + * + * @param {ReadonlyQuat2} a the first dual quat. + * @param {ReadonlyQuat2} b the second dual quat. + * @returns {Boolean} true if the dual quats are equal, false otherwise. + */ + +function equals$2(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5], + a6 = a[6], + a7 = a[7]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)); +} + +var quat2 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$1, +clone: clone$1, +conjugate: conjugate, +copy: copy$1, +create: create$2, +dot: dot$2, +equals: equals$2, +exactEquals: exactEquals$1, +fromMat4: fromMat4, +fromRotation: fromRotation, +fromRotationTranslation: fromRotationTranslation, +fromRotationTranslationValues: fromRotationTranslationValues, +fromTranslation: fromTranslation, +fromValues: fromValues$1, +getDual: getDual, +getReal: getReal, +getTranslation: getTranslation, +identity: identity, +invert: invert, +len: len$1, +length: length$1, +lerp: lerp$1, +mul: mul$1, +multiply: multiply$1, +normalize: normalize$1, +rotateAroundAxis: rotateAroundAxis, +rotateByQuatAppend: rotateByQuatAppend, +rotateByQuatPrepend: rotateByQuatPrepend, +rotateX: rotateX, +rotateY: rotateY, +rotateZ: rotateZ, +scale: scale$1, +set: set$1, +setDual: setDual, +setReal: setReal, +sqrLen: sqrLen$1, +squaredLength: squaredLength$1, +str: str$1, +translate: translate +}); + +/** + * 2 Dimensional Vector + * @module vec2 + */ + +/** + * Creates a new, empty vec2 + * + * @returns {vec2} a new 2D vector + */ + +function create$1() { + var out = new ARRAY_TYPE(2); + + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + } + + return out; +} +/** + * Creates a new vec2 initialized with values from an existing vector + * + * @param {ReadonlyVec2} a vector to clone + * @returns {vec2} a new 2D vector + */ + +function clone(a) { + var out = new ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; +} +/** + * Creates a new vec2 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @returns {vec2} a new 2D vector + */ + +function fromValues(x, y) { + var out = new ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; +} +/** + * Copy the values from one vec2 to another + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the source vector + * @returns {vec2} out + */ + +function copy(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; +} +/** + * Set the components of a vec2 to the given values + * + * @param {vec2} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @returns {vec2} out + */ + +function set(out, x, y) { + out[0] = x; + out[1] = y; + return out; +} +/** + * Adds two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function add(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; +} +/** + * Subtracts vector b from vector a + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function subtract(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; +} +/** + * Multiplies two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function multiply(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; +} +/** + * Divides two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function divide(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; +} +/** + * Math.ceil the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to ceil + * @returns {vec2} out + */ + +function ceil(out, a) { + out[0] = Math.ceil(a[0]); + out[1] = Math.ceil(a[1]); + return out; +} +/** + * Math.floor the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to floor + * @returns {vec2} out + */ + +function floor(out, a) { + out[0] = Math.floor(a[0]); + out[1] = Math.floor(a[1]); + return out; +} +/** + * Returns the minimum of two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function min(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + return out; +} +/** + * Returns the maximum of two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function max(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + return out; +} +/** + * Math.round the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to round + * @returns {vec2} out + */ + +function round(out, a) { + out[0] = Math.round(a[0]); + out[1] = Math.round(a[1]); + return out; +} +/** + * Scales a vec2 by a scalar number + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec2} out + */ + +function scale(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; +} +/** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec2} out + */ + +function scaleAndAdd(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + return out; +} +/** + * Calculates the euclidian distance between two vec2's + * + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {Number} distance between a and b + */ + +function distance(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return Math.hypot(x, y); +} +/** + * Calculates the squared euclidian distance between two vec2's + * + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {Number} squared distance between a and b + */ + +function squaredDistance(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return x * x + y * y; +} +/** + * Calculates the length of a vec2 + * + * @param {ReadonlyVec2} a vector to calculate length of + * @returns {Number} length of a + */ + +function length(a) { + var x = a[0], + y = a[1]; + return Math.hypot(x, y); +} +/** + * Calculates the squared length of a vec2 + * + * @param {ReadonlyVec2} a vector to calculate squared length of + * @returns {Number} squared length of a + */ + +function squaredLength(a) { + var x = a[0], + y = a[1]; + return x * x + y * y; +} +/** + * Negates the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to negate + * @returns {vec2} out + */ + +function negate(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; +} +/** + * Returns the inverse of the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to invert + * @returns {vec2} out + */ + +function inverse(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + return out; +} +/** + * Normalize a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to normalize + * @returns {vec2} out + */ + +function normalize(out, a) { + var x = a[0], + y = a[1]; + var len = x * x + y * y; + + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + } + + out[0] = a[0] * len; + out[1] = a[1] * len; + return out; +} +/** + * Calculates the dot product of two vec2's + * + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {Number} dot product of a and b + */ + +function dot$1(a, b) { + return a[0] * b[0] + a[1] * b[1]; +} +/** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec3} out + */ + +function cross(out, a, b) { + var z = a[0] * b[1] - a[1] * b[0]; + out[0] = out[1] = 0; + out[2] = z; + return out; +} +/** + * Performs a linear interpolation between two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec2} out + */ + +function lerp(out, a, b, t) { + var ax = a[0], + ay = a[1]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + return out; +} +/** + * Generates a random vector with the given scale + * + * @param {vec2} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec2} out + */ + +function random(out, scale) { + scale = scale || 1.0; + var r = RANDOM() * 2.0 * Math.PI; + out[0] = Math.cos(r) * scale; + out[1] = Math.sin(r) * scale; + return out; +} +/** + * Transforms the vec2 with a mat2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to transform + * @param {ReadonlyMat2} m matrix to transform with + * @returns {vec2} out + */ + +function transformMat2(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[2] * y; + out[1] = m[1] * x + m[3] * y; + return out; +} +/** + * Transforms the vec2 with a mat2d + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to transform + * @param {ReadonlyMat2d} m matrix to transform with + * @returns {vec2} out + */ + +function transformMat2d(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[2] * y + m[4]; + out[1] = m[1] * x + m[3] * y + m[5]; + return out; +} +/** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to transform + * @param {ReadonlyMat3} m matrix to transform with + * @returns {vec2} out + */ + +function transformMat3(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[3] * y + m[6]; + out[1] = m[1] * x + m[4] * y + m[7]; + return out; +} +/** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to transform + * @param {ReadonlyMat4} m matrix to transform with + * @returns {vec2} out + */ + +function transformMat4(out, a, m) { + var x = a[0]; + var y = a[1]; + out[0] = m[0] * x + m[4] * y + m[12]; + out[1] = m[1] * x + m[5] * y + m[13]; + return out; +} +/** + * Rotate a 2D vector + * @param {vec2} out The receiving vec2 + * @param {ReadonlyVec2} a The vec2 point to rotate + * @param {ReadonlyVec2} b The origin of the rotation + * @param {Number} rad The angle of rotation in radians + * @returns {vec2} out + */ + +function rotate(out, a, b, rad) { + //Translate point to the origin + var p0 = a[0] - b[0], + p1 = a[1] - b[1], + sinC = Math.sin(rad), + cosC = Math.cos(rad); //perform rotation and translate to correct position + + out[0] = p0 * cosC - p1 * sinC + b[0]; + out[1] = p0 * sinC + p1 * cosC + b[1]; + return out; +} +/** + * Get the angle between two 2D vectors + * @param {ReadonlyVec2} a The first operand + * @param {ReadonlyVec2} b The second operand + * @returns {Number} The angle in radians + */ + +function angle(a, b) { + var x1 = a[0], + y1 = a[1], + x2 = b[0], + y2 = b[1], + // mag is the product of the magnitudes of a and b + mag = Math.sqrt(x1 * x1 + y1 * y1) * Math.sqrt(x2 * x2 + y2 * y2), + // mag &&.. short circuits if mag == 0 + cosine = mag && (x1 * x2 + y1 * y2) / mag; // Math.min(Math.max(cosine, -1), 1) clamps the cosine between -1 and 1 + + return Math.acos(Math.min(Math.max(cosine, -1), 1)); +} +/** + * Set the components of a vec2 to zero + * + * @param {vec2} out the receiving vector + * @returns {vec2} out + */ + +function zero(out) { + out[0] = 0.0; + out[1] = 0.0; + return out; +} +/** + * Returns a string representation of a vector + * + * @param {ReadonlyVec2} a vector to represent as a string + * @returns {String} string representation of the vector + */ + +function str(a) { + return "vec2(" + a[0] + ", " + a[1] + ")"; +} +/** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) + * + * @param {ReadonlyVec2} a The first vector. + * @param {ReadonlyVec2} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function exactEquals(a, b) { + return a[0] === b[0] && a[1] === b[1]; +} +/** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {ReadonlyVec2} a The first vector. + * @param {ReadonlyVec2} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function equals$1(a, b) { + var a0 = a[0], + a1 = a[1]; + var b0 = b[0], + b1 = b[1]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)); +} +/** + * Alias for {@link vec2.length} + * @function + */ + +var len = length; +/** + * Alias for {@link vec2.subtract} + * @function + */ + +var sub = subtract; +/** + * Alias for {@link vec2.multiply} + * @function + */ + +var mul = multiply; +/** + * Alias for {@link vec2.divide} + * @function + */ + +var div = divide; +/** + * Alias for {@link vec2.distance} + * @function + */ + +var dist = distance; +/** + * Alias for {@link vec2.squaredDistance} + * @function + */ + +var sqrDist = squaredDistance; +/** + * Alias for {@link vec2.squaredLength} + * @function + */ + +var sqrLen = squaredLength; +/** + * Perform some operation over an array of vec2s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ + +var forEach = function () { + var vec = create$1(); + return function (a, stride, offset, count, fn, arg) { + var i, l; + + if (!stride) { + stride = 2; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min(count * stride + offset, a.length); + } else { + l = a.length; + } + + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + } + + return a; + }; +}(); + +var vec2 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add, +angle: angle, +ceil: ceil, +clone: clone, +copy: copy, +create: create$1, +cross: cross, +dist: dist, +distance: distance, +div: div, +divide: divide, +dot: dot$1, +equals: equals$1, +exactEquals: exactEquals, +floor: floor, +forEach: forEach, +fromValues: fromValues, +inverse: inverse, +len: len, +length: length, +lerp: lerp, +max: max, +min: min, +mul: mul, +multiply: multiply, +negate: negate, +normalize: normalize, +random: random, +rotate: rotate, +round: round, +scale: scale, +scaleAndAdd: scaleAndAdd, +set: set, +sqrDist: sqrDist, +sqrLen: sqrLen, +squaredDistance: squaredDistance, +squaredLength: squaredLength, +str: str, +sub: sub, +subtract: subtract, +transformMat2: transformMat2, +transformMat2d: transformMat2d, +transformMat3: transformMat3, +transformMat4: transformMat4, +zero: zero +}); + +/** + * A style layer that defines a circle + */ +class CircleStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$9); + } + createBucket(parameters) { + return new CircleBucket(parameters); + } + queryRadius(bucket) { + const circleBucket = bucket; + return getMaximumPaintValue('circle-radius', this, circleBucket) + + getMaximumPaintValue('circle-stroke-width', this, circleBucket) + + translateDistance(this.paint.get('circle-translate')); + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits, pixelPosMatrix) { + const translatedPolygon = translate$4(queryGeometry, this.paint.get('circle-translate'), this.paint.get('circle-translate-anchor'), transform.angle, pixelsToTileUnits); + const radius = this.paint.get('circle-radius').evaluate(feature, featureState); + const stroke = this.paint.get('circle-stroke-width').evaluate(feature, featureState); + const size = radius + stroke; + // For pitch-alignment: map, compare feature geometry to query geometry in the plane of the tile + // // Otherwise, compare geometry in the plane of the viewport + // // A circle with fixed scaling relative to the viewport gets larger in tile space as it moves into the distance + // // A circle with fixed scaling relative to the map gets smaller in viewport space as it moves into the distance + const alignWithMap = this.paint.get('circle-pitch-alignment') === 'map'; + const transformedPolygon = alignWithMap ? translatedPolygon : projectQueryGeometry$1(translatedPolygon, pixelPosMatrix); + const transformedSize = alignWithMap ? size * pixelsToTileUnits : size; + for (const ring of geometry) { + for (const point of ring) { + const transformedPoint = alignWithMap ? point : projectPoint(point, pixelPosMatrix); + let adjustedSize = transformedSize; + const projectedCenter = transformMat4$1([], [point.x, point.y, 0, 1], pixelPosMatrix); + if (this.paint.get('circle-pitch-scale') === 'viewport' && this.paint.get('circle-pitch-alignment') === 'map') { + adjustedSize *= projectedCenter[3] / transform.cameraToCenterDistance; + } + else if (this.paint.get('circle-pitch-scale') === 'map' && this.paint.get('circle-pitch-alignment') === 'viewport') { + adjustedSize *= transform.cameraToCenterDistance / projectedCenter[3]; + } + if (polygonIntersectsBufferedPoint(transformedPolygon, transformedPoint, adjustedSize)) + return true; + } + } + return false; + } +} +function projectPoint(p, pixelPosMatrix) { + const point = transformMat4$1([], [p.x, p.y, 0, 1], pixelPosMatrix); + return new Point$2(point[0] / point[3], point[1] / point[3]); +} +function projectQueryGeometry$1(queryGeometry, pixelPosMatrix) { + return queryGeometry.map((p) => { + return projectPoint(p, pixelPosMatrix); + }); +} + +class HeatmapBucket extends CircleBucket { +} +register('HeatmapBucket', HeatmapBucket, { omit: ['layers'] }); + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$7; +const getPaint$7 = () => paint$7 = paint$7 || new Properties({ + "heatmap-radius": new DataDrivenProperty(v8Spec["paint_heatmap"]["heatmap-radius"]), + "heatmap-weight": new DataDrivenProperty(v8Spec["paint_heatmap"]["heatmap-weight"]), + "heatmap-intensity": new DataConstantProperty(v8Spec["paint_heatmap"]["heatmap-intensity"]), + "heatmap-color": new ColorRampProperty(v8Spec["paint_heatmap"]["heatmap-color"]), + "heatmap-opacity": new DataConstantProperty(v8Spec["paint_heatmap"]["heatmap-opacity"]), +}); +var properties$8 = ({ get paint() { return getPaint$7(); } }); + +function createImage(image, { width, height }, channels, data) { + if (!data) { + data = new Uint8Array(width * height * channels); + } + else if (data instanceof Uint8ClampedArray) { + data = new Uint8Array(data.buffer); + } + else if (data.length !== width * height * channels) { + throw new RangeError(`mismatched image size. expected: ${data.length} but got: ${width * height * channels}`); + } + image.width = width; + image.height = height; + image.data = data; + return image; +} +function resizeImage(image, { width, height }, channels) { + if (width === image.width && height === image.height) { + return; + } + const newImage = createImage({}, { width, height }, channels); + copyImage(image, newImage, { x: 0, y: 0 }, { x: 0, y: 0 }, { + width: Math.min(image.width, width), + height: Math.min(image.height, height) + }, channels); + image.width = width; + image.height = height; + image.data = newImage.data; +} +function copyImage(srcImg, dstImg, srcPt, dstPt, size, channels) { + if (size.width === 0 || size.height === 0) { + return dstImg; + } + if (size.width > srcImg.width || + size.height > srcImg.height || + srcPt.x > srcImg.width - size.width || + srcPt.y > srcImg.height - size.height) { + throw new RangeError('out of range source coordinates for image copy'); + } + if (size.width > dstImg.width || + size.height > dstImg.height || + dstPt.x > dstImg.width - size.width || + dstPt.y > dstImg.height - size.height) { + throw new RangeError('out of range destination coordinates for image copy'); + } + const srcData = srcImg.data; + const dstData = dstImg.data; + if (srcData === dstData) + throw new Error('srcData equals dstData, so image is already copied'); + for (let y = 0; y < size.height; y++) { + const srcOffset = ((srcPt.y + y) * srcImg.width + srcPt.x) * channels; + const dstOffset = ((dstPt.y + y) * dstImg.width + dstPt.x) * channels; + for (let i = 0; i < size.width * channels; i++) { + dstData[dstOffset + i] = srcData[srcOffset + i]; + } + } + return dstImg; +} +/** + * An image with alpha color value + */ +class AlphaImage { + constructor(size, data) { + createImage(this, size, 1, data); + } + resize(size) { + resizeImage(this, size, 1); + } + clone() { + return new AlphaImage({ width: this.width, height: this.height }, new Uint8Array(this.data)); + } + static copy(srcImg, dstImg, srcPt, dstPt, size) { + copyImage(srcImg, dstImg, srcPt, dstPt, size, 1); + } +} +/** + * An object to store image data not premultiplied, because ImageData is not premultiplied. + * UNPACK_PREMULTIPLY_ALPHA_WEBGL must be used when uploading to a texture. + */ +class RGBAImage { + constructor(size, data) { + createImage(this, size, 4, data); + } + resize(size) { + resizeImage(this, size, 4); + } + replace(data, copy) { + if (copy) { + this.data.set(data); + } + else if (data instanceof Uint8ClampedArray) { + this.data = new Uint8Array(data.buffer); + } + else { + this.data = data; + } + } + clone() { + return new RGBAImage({ width: this.width, height: this.height }, new Uint8Array(this.data)); + } + static copy(srcImg, dstImg, srcPt, dstPt, size) { + copyImage(srcImg, dstImg, srcPt, dstPt, size, 4); + } +} +register('AlphaImage', AlphaImage); +register('RGBAImage', RGBAImage); + +/** + * Given an expression that should evaluate to a color ramp, + * return a RGBA image representing that ramp expression. + */ +function renderColorRamp(params) { + const evaluationGlobals = {}; + const width = params.resolution || 256; + const height = params.clips ? params.clips.length : 1; + const image = params.image || new RGBAImage({ width, height }); + if (!isPowerOfTwo(width)) + throw new Error(`width is not a power of 2 - ${width}`); + const renderPixel = (stride, index, progress) => { + evaluationGlobals[params.evaluationKey] = progress; + const pxColor = params.expression.evaluate(evaluationGlobals); + // the colors are being unpremultiplied because Color uses + // premultiplied values, and the Texture class expects unpremultiplied ones + image.data[stride + index + 0] = Math.floor(pxColor.r * 255 / pxColor.a); + image.data[stride + index + 1] = Math.floor(pxColor.g * 255 / pxColor.a); + image.data[stride + index + 2] = Math.floor(pxColor.b * 255 / pxColor.a); + image.data[stride + index + 3] = Math.floor(pxColor.a * 255); + }; + if (!params.clips) { + for (let i = 0, j = 0; i < width; i++, j += 4) { + const progress = i / (width - 1); + renderPixel(0, j, progress); + } + } + else { + for (let clip = 0, stride = 0; clip < height; ++clip, stride += width * 4) { + for (let i = 0, j = 0; i < width; i++, j += 4) { + // Remap progress between clips + const progress = i / (width - 1); + const { start, end } = params.clips[clip]; + const evaluationProgress = start * (1 - progress) + end * progress; + renderPixel(stride, j, evaluationProgress); + } + } + } + return image; +} + +const HEATMAP_FULL_RENDER_FBO_KEY = 'big-fb'; +/** + * A style layer that defines a heatmap + */ +class HeatmapStyleLayer extends StyleLayer { + createBucket(options) { + return new HeatmapBucket(options); + } + constructor(layer) { + super(layer, properties$8); + this.heatmapFbos = new Map(); + // make sure color ramp texture is generated for default heatmap color too + this._updateColorRamp(); + } + _handleSpecialPaintPropertyUpdate(name) { + if (name === 'heatmap-color') { + this._updateColorRamp(); + } + } + _updateColorRamp() { + const expression = this._transitionablePaint._values['heatmap-color'].value.expression; + this.colorRamp = renderColorRamp({ + expression, + evaluationKey: 'heatmapDensity', + image: this.colorRamp + }); + this.colorRampTexture = null; + } + resize() { + if (this.heatmapFbos.has(HEATMAP_FULL_RENDER_FBO_KEY)) { + this.heatmapFbos.delete(HEATMAP_FULL_RENDER_FBO_KEY); + } + } + queryRadius() { + return 0; + } + queryIntersectsFeature() { + return false; + } + hasOffscreenPass() { + return this.paint.get('heatmap-opacity') !== 0 && this.visibility !== 'none'; + } +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$6; +const getPaint$6 = () => paint$6 = paint$6 || new Properties({ + "hillshade-illumination-direction": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-illumination-direction"]), + "hillshade-illumination-anchor": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-illumination-anchor"]), + "hillshade-exaggeration": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-exaggeration"]), + "hillshade-shadow-color": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-shadow-color"]), + "hillshade-highlight-color": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-highlight-color"]), + "hillshade-accent-color": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-accent-color"]), +}); +var properties$7 = ({ get paint() { return getPaint$6(); } }); + +class HillshadeStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$7); + } + hasOffscreenPass() { + return this.paint.get('hillshade-exaggeration') !== 0 && this.visibility !== 'none'; + } +} + +const layout$4 = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' } +], 4); +const { members: members$3, size: size$3, alignment: alignment$3 } = layout$4; + +function earcut(data, holeIndices, dim = 2) { + + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data.length; + let outerNode = linkedList(data, 0, outerLen, dim, true); + const triangles = []; + + if (!outerNode || outerNode.next === outerNode.prev) return triangles; + + let minX, minY, invSize; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = Infinity; + minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + + for (let i = dim; i < outerLen; i += dim) { + const x = data[i]; + const y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + let last; + + if (clockwise === (signedArea$1(data, start, end, dim) > 0)) { + for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); + } else { + for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + let p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + + let stop = ear; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + const prev = ear.prev; + const next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + triangles.push(prev.i, ear.i, next.i); // cut off the triangle + + removeNode(ear); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + const a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + let p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, invSize) { + const a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + // z-order range for the current triangle bbox; + const minZ = zOrder(x0, y0, minX, minY, invSize), + maxZ = zOrder(x1, y1, minX, minY, invSize); + + let p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles) { + let p = start; + do { + const a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i, p.i, b.i); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return filterPoints(p); +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + let a = start; + do { + let b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + let c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + const queue = []; + + for (let i = 0, len = holeIndices.length; i < len; i++) { + const start = holeIndices[i] * dim; + const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + const list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (let i = 0; i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + const bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + + const bridgeReverse = splitPolygon(bridge, hole); + + // filter collinear points around the cuts + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + let p = outerNode; + const hx = hole.x; + const hy = hole.y; + let qx = -Infinity; + let m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + const stop = m; + const mx = m.x; + const my = m.y; + let tanMin = Infinity; + + p = m; + + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if (locallyInside(p, hole) && + (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } while (p !== stop); + + return m; +} + +// whether sector in vertex m contains sector in vertex p in the same coordinates +function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, invSize) { + let p = start; + do { + if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + let numMerges; + let inSize = 1; + + do { + let p = list; + let e; + list = null; + let tail = null; + numMerges = 0; + + while (p) { + numMerges++; + let q = p; + let pSize = 0; + for (let i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + let qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + let p = start, + leftmost = start; + do { + if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && + (ax - px) * (by - py) >= (bx - px) * (ay - py) && + (bx - px) * (cy - py) >= (cx - px) * (by - py); +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges + (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors + equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + const o1 = sign(area(p1, q1, p2)); + const o2 = sign(area(p1, q1, q2)); + const o3 = sign(area(p2, q2, p1)); + const o4 = sign(area(p2, q2, q1)); + + if (o1 !== o2 && o3 !== o4) return true; // general case + + if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + + return false; +} + +// for collinear points p, q, r, check if point q lies on segment pr +function onSegment(p, q, r) { + 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); +} + +function sign(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + let p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + let p = a; + let inside = false; + const px = (a.x + b.x) / 2; + const py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + const a2 = createNode(a.i, a.x, a.y), + b2 = createNode(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + const p = createNode(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function createNode(i, x, y) { + return { + i, // vertex index in coordinates array + x, y, // vertex coordinates + prev: null, // previous and next vertex nodes in a polygon ring + next: null, + z: 0, // z-order curve value + prevZ: null, // previous and next nodes in z-order + nextZ: null, + steiner: false // indicates whether this is a steiner point + }; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +function deviation(data, holeIndices, dim, triangles) { + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + let polygonArea = Math.abs(signedArea$1(data, 0, outerLen, dim)); + if (hasHoles) { + for (let i = 0, len = holeIndices.length; i < len; i++) { + const start = holeIndices[i] * dim; + const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea$1(data, start, end, dim)); + } + } + + let trianglesArea = 0; + for (let i = 0; i < triangles.length; i += 3) { + const a = triangles[i] * dim; + const b = triangles[i + 1] * dim; + const c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +} + +function signedArea$1(data, start, end, dim) { + let sum = 0; + for (let i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +function flatten(data) { + const vertices = []; + const holes = []; + const dimensions = data[0][0].length; + let holeIndex = 0; + let prevLen = 0; + + for (const ring of data) { + for (const p of ring) { + for (let d = 0; d < dimensions; d++) vertices.push(p[d]); + } + if (prevLen) { + holeIndex += prevLen; + holes.push(holeIndex); + } + prevLen = ring.length; + } + return {vertices, holes, dimensions}; +} + +function hasPattern(type, layers, options) { + const patterns = options.patternDependencies; + let hasPattern = false; + for (const layer of layers) { + const patternProperty = layer.paint.get(`${type}-pattern`); + if (!patternProperty.isConstant()) { + hasPattern = true; + } + const constantPattern = patternProperty.constantOr(null); + if (constantPattern) { + hasPattern = true; + patterns[constantPattern.to] = true; + patterns[constantPattern.from] = true; + } + } + return hasPattern; +} +function addPatternDependencies(type, layers, patternFeature, zoom, options) { + const patterns = options.patternDependencies; + for (const layer of layers) { + const patternProperty = layer.paint.get(`${type}-pattern`); + const patternPropertyValue = patternProperty.value; + if (patternPropertyValue.kind !== 'constant') { + let min = patternPropertyValue.evaluate({ zoom: zoom - 1 }, patternFeature, {}, options.availableImages); + let mid = patternPropertyValue.evaluate({ zoom }, patternFeature, {}, options.availableImages); + let max = patternPropertyValue.evaluate({ zoom: zoom + 1 }, patternFeature, {}, options.availableImages); + min = min && min.name ? min.name : min; + mid = mid && mid.name ? mid.name : mid; + max = max && max.name ? max.name : max; + // add to patternDependencies + patterns[min] = true; + patterns[mid] = true; + patterns[max] = true; + // save for layout + patternFeature.patterns[layer.id] = { min, mid, max }; + } + } + return patternFeature; +} + +const EARCUT_MAX_RINGS$1 = 500; +class FillBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.patternFeatures = []; + this.layoutVertexArray = new FillLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.indexArray2 = new LineIndexArray(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.segments = new SegmentVector(); + this.segments2 = new SegmentVector(); + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + this.hasPattern = hasPattern('fill', this.layers, options); + const fillSortKey = this.layers[0].layout.get('fill-sort-key'); + const sortFeaturesByKey = !fillSortKey.isConstant(); + const bucketFeatures = []; + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const sortKey = sortFeaturesByKey ? + fillSortKey.evaluate(evaluationFeature, {}, canonical, options.availableImages) : + undefined; + const bucketFeature = { + id, + properties: feature.properties, + type: feature.type, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + patterns: {}, + sortKey + }; + bucketFeatures.push(bucketFeature); + } + if (sortFeaturesByKey) { + bucketFeatures.sort((a, b) => a.sortKey - b.sortKey); + } + for (const bucketFeature of bucketFeatures) { + const { geometry, index, sourceLayerIndex } = bucketFeature; + if (this.hasPattern) { + const patternFeature = addPatternDependencies('fill', this.layers, bucketFeature, this.zoom, options); + // pattern features are added only once the pattern is loaded into the image atlas + // so are stored during populate until later updated with positions by tile worker in addFeatures + this.patternFeatures.push(patternFeature); + } + else { + this.addFeature(bucketFeature, geometry, index, canonical, {}); + } + const feature = features[index].feature; + options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + addFeatures(options, canonical, imagePositions) { + for (const feature of this.patternFeatures) { + this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions); + } + } + isEmpty() { + return this.layoutVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$3); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + this.indexBuffer2 = context.createIndexBuffer(this.indexArray2); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.indexBuffer2.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + this.segments2.destroy(); + } + addFeature(feature, geometry, index, canonical, imagePositions) { + for (const polygon of classifyRings$1(geometry, EARCUT_MAX_RINGS$1)) { + let numVertices = 0; + for (const ring of polygon) { + numVertices += ring.length; + } + const triangleSegment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray); + const triangleIndex = triangleSegment.vertexLength; + const flattened = []; + const holeIndices = []; + for (const ring of polygon) { + if (ring.length === 0) { + continue; + } + if (ring !== polygon[0]) { + holeIndices.push(flattened.length / 2); + } + const lineSegment = this.segments2.prepareSegment(ring.length, this.layoutVertexArray, this.indexArray2); + const lineIndex = lineSegment.vertexLength; + this.layoutVertexArray.emplaceBack(ring[0].x, ring[0].y); + this.indexArray2.emplaceBack(lineIndex + ring.length - 1, lineIndex); + flattened.push(ring[0].x); + flattened.push(ring[0].y); + for (let i = 1; i < ring.length; i++) { + this.layoutVertexArray.emplaceBack(ring[i].x, ring[i].y); + this.indexArray2.emplaceBack(lineIndex + i - 1, lineIndex + i); + flattened.push(ring[i].x); + flattened.push(ring[i].y); + } + lineSegment.vertexLength += ring.length; + lineSegment.primitiveLength += ring.length; + } + const indices = earcut(flattened, holeIndices); + for (let i = 0; i < indices.length; i += 3) { + this.indexArray.emplaceBack(triangleIndex + indices[i], triangleIndex + indices[i + 1], triangleIndex + indices[i + 2]); + } + triangleSegment.vertexLength += numVertices; + triangleSegment.primitiveLength += indices.length / 3; + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical); + } +} +register('FillBucket', FillBucket, { omit: ['layers', 'patternFeatures'] }); + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout$3; +const getLayout$2 = () => layout$3 = layout$3 || new Properties({ + "fill-sort-key": new DataDrivenProperty(v8Spec["layout_fill"]["fill-sort-key"]), +}); +let paint$5; +const getPaint$5 = () => paint$5 = paint$5 || new Properties({ + "fill-antialias": new DataConstantProperty(v8Spec["paint_fill"]["fill-antialias"]), + "fill-opacity": new DataDrivenProperty(v8Spec["paint_fill"]["fill-opacity"]), + "fill-color": new DataDrivenProperty(v8Spec["paint_fill"]["fill-color"]), + "fill-outline-color": new DataDrivenProperty(v8Spec["paint_fill"]["fill-outline-color"]), + "fill-translate": new DataConstantProperty(v8Spec["paint_fill"]["fill-translate"]), + "fill-translate-anchor": new DataConstantProperty(v8Spec["paint_fill"]["fill-translate-anchor"]), + "fill-pattern": new CrossFadedDataDrivenProperty(v8Spec["paint_fill"]["fill-pattern"]), +}); +var properties$6 = ({ get paint() { return getPaint$5(); }, get layout() { return getLayout$2(); } }); + +class FillStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$6); + } + recalculate(parameters, availableImages) { + super.recalculate(parameters, availableImages); + const outlineColor = this.paint._values['fill-outline-color']; + if (outlineColor.value.kind === 'constant' && outlineColor.value.value === undefined) { + this.paint._values['fill-outline-color'] = this.paint._values['fill-color']; + } + } + createBucket(parameters) { + return new FillBucket(parameters); + } + queryRadius() { + return translateDistance(this.paint.get('fill-translate')); + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits) { + const translatedPolygon = translate$4(queryGeometry, this.paint.get('fill-translate'), this.paint.get('fill-translate-anchor'), transform.angle, pixelsToTileUnits); + return polygonIntersectsMultiPolygon(translatedPolygon, geometry); + } + isTileClipped() { + return true; + } +} + +const layout$2 = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' }, + { name: 'a_normal_ed', components: 4, type: 'Int16' }, +], 4); +const centroidAttributes = createLayout([ + { name: 'a_centroid', components: 2, type: 'Int16' } +], 4); +const { members: members$2, size: size$2, alignment: alignment$2 } = layout$2; + +var vectorTile = {}; + +'use strict'; + +var Point = pointGeometry; + +var vectortilefeature = VectorTileFeature$2; + +function VectorTileFeature$2(pbf, end, extent, keys, values) { + // Public + this.properties = {}; + this.extent = extent; + this.type = 0; + + // Private + this._pbf = pbf; + this._geometry = -1; + this._keys = keys; + this._values = values; + + pbf.readFields(readFeature, this, end); +} + +function readFeature(tag, feature, pbf) { + if (tag == 1) feature.id = pbf.readVarint(); + else if (tag == 2) readTag(pbf, feature); + else if (tag == 3) feature.type = pbf.readVarint(); + else if (tag == 4) feature._geometry = pbf.pos; +} + +function readTag(pbf, feature) { + var end = pbf.readVarint() + pbf.pos; + + while (pbf.pos < end) { + var key = feature._keys[pbf.readVarint()], + value = feature._values[pbf.readVarint()]; + feature.properties[key] = value; + } +} + +VectorTileFeature$2.types = ['Unknown', 'Point', 'LineString', 'Polygon']; + +VectorTileFeature$2.prototype.loadGeometry = function() { + var pbf = this._pbf; + pbf.pos = this._geometry; + + var end = pbf.readVarint() + pbf.pos, + cmd = 1, + length = 0, + x = 0, + y = 0, + lines = [], + line; + + while (pbf.pos < end) { + if (length <= 0) { + var cmdLen = pbf.readVarint(); + cmd = cmdLen & 0x7; + length = cmdLen >> 3; + } + + length--; + + if (cmd === 1 || cmd === 2) { + x += pbf.readSVarint(); + y += pbf.readSVarint(); + + if (cmd === 1) { // moveTo + if (line) lines.push(line); + line = []; + } + + line.push(new Point(x, y)); + + } else if (cmd === 7) { + + // Workaround for https://github.com/mapbox/mapnik-vector-tile/issues/90 + if (line) { + line.push(line[0].clone()); // closePolygon + } + + } else { + throw new Error('unknown command ' + cmd); + } + } + + if (line) lines.push(line); + + return lines; +}; + +VectorTileFeature$2.prototype.bbox = function() { + var pbf = this._pbf; + pbf.pos = this._geometry; + + var end = pbf.readVarint() + pbf.pos, + cmd = 1, + length = 0, + x = 0, + y = 0, + x1 = Infinity, + x2 = -Infinity, + y1 = Infinity, + y2 = -Infinity; + + while (pbf.pos < end) { + if (length <= 0) { + var cmdLen = pbf.readVarint(); + cmd = cmdLen & 0x7; + length = cmdLen >> 3; + } + + length--; + + if (cmd === 1 || cmd === 2) { + x += pbf.readSVarint(); + y += pbf.readSVarint(); + if (x < x1) x1 = x; + if (x > x2) x2 = x; + if (y < y1) y1 = y; + if (y > y2) y2 = y; + + } else if (cmd !== 7) { + throw new Error('unknown command ' + cmd); + } + } + + return [x1, y1, x2, y2]; +}; + +VectorTileFeature$2.prototype.toGeoJSON = function(x, y, z) { + var size = this.extent * Math.pow(2, z), + x0 = this.extent * x, + y0 = this.extent * y, + coords = this.loadGeometry(), + type = VectorTileFeature$2.types[this.type], + i, j; + + function project(line) { + for (var j = 0; j < line.length; j++) { + var p = line[j], y2 = 180 - (p.y + y0) * 360 / size; + line[j] = [ + (p.x + x0) * 360 / size - 180, + 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90 + ]; + } + } + + switch (this.type) { + case 1: + var points = []; + for (i = 0; i < coords.length; i++) { + points[i] = coords[i][0]; + } + coords = points; + project(coords); + break; + + case 2: + for (i = 0; i < coords.length; i++) { + project(coords[i]); + } + break; + + case 3: + coords = classifyRings(coords); + for (i = 0; i < coords.length; i++) { + for (j = 0; j < coords[i].length; j++) { + project(coords[i][j]); + } + } + break; + } + + if (coords.length === 1) { + coords = coords[0]; + } else { + type = 'Multi' + type; + } + + var result = { + type: "Feature", + geometry: { + type: type, + coordinates: coords + }, + properties: this.properties + }; + + if ('id' in this) { + result.id = this.id; + } + + return result; +}; + +// classifies an array of rings into polygons with outer rings and holes + +function classifyRings(rings) { + var len = rings.length; + + if (len <= 1) return [rings]; + + var polygons = [], + polygon, + ccw; + + for (var i = 0; i < len; i++) { + var area = signedArea(rings[i]); + if (area === 0) continue; + + if (ccw === undefined) ccw = area < 0; + + if (ccw === area < 0) { + if (polygon) polygons.push(polygon); + polygon = [rings[i]]; + + } else { + polygon.push(rings[i]); + } + } + if (polygon) polygons.push(polygon); + + return polygons; +} + +function signedArea(ring) { + var sum = 0; + for (var i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + return sum; +} + +var vectortilefeature$1 = /*@__PURE__*/getDefaultExportFromCjs$1(vectortilefeature); + +'use strict'; + +var VectorTileFeature$1 = vectortilefeature; + +var vectortilelayer = VectorTileLayer$2; + +function VectorTileLayer$2(pbf, end) { + // Public + this.version = 1; + this.name = null; + this.extent = 4096; + this.length = 0; + + // Private + this._pbf = pbf; + this._keys = []; + this._values = []; + this._features = []; + + pbf.readFields(readLayer, this, end); + + this.length = this._features.length; +} + +function readLayer(tag, layer, pbf) { + if (tag === 15) layer.version = pbf.readVarint(); + else if (tag === 1) layer.name = pbf.readString(); + else if (tag === 5) layer.extent = pbf.readVarint(); + else if (tag === 2) layer._features.push(pbf.pos); + else if (tag === 3) layer._keys.push(pbf.readString()); + else if (tag === 4) layer._values.push(readValueMessage(pbf)); +} + +function readValueMessage(pbf) { + var value = null, + end = pbf.readVarint() + pbf.pos; + + while (pbf.pos < end) { + var tag = pbf.readVarint() >> 3; + + value = tag === 1 ? pbf.readString() : + tag === 2 ? pbf.readFloat() : + tag === 3 ? pbf.readDouble() : + tag === 4 ? pbf.readVarint64() : + tag === 5 ? pbf.readVarint() : + tag === 6 ? pbf.readSVarint() : + tag === 7 ? pbf.readBoolean() : null; + } + + return value; +} + +// return feature `i` from this layer as a `VectorTileFeature` +VectorTileLayer$2.prototype.feature = function(i) { + if (i < 0 || i >= this._features.length) throw new Error('feature index out of bounds'); + + this._pbf.pos = this._features[i]; + + var end = this._pbf.readVarint() + this._pbf.pos; + return new VectorTileFeature$1(this._pbf, end, this.extent, this._keys, this._values); +}; + +var vectortilelayer$1 = /*@__PURE__*/getDefaultExportFromCjs$1(vectortilelayer); + +'use strict'; + +var VectorTileLayer$1 = vectortilelayer; + +var vectortile = VectorTile$1; + +function VectorTile$1(pbf, end) { + this.layers = pbf.readFields(readTile, {}, end); +} + +function readTile(tag, layers, pbf) { + if (tag === 3) { + var layer = new VectorTileLayer$1(pbf, pbf.readVarint() + pbf.pos); + if (layer.length) layers[layer.name] = layer; + } +} + +var vectortile$1 = /*@__PURE__*/getDefaultExportFromCjs$1(vectortile); + +var VectorTile = vectorTile.VectorTile = vectortile; +var VectorTileFeature = vectorTile.VectorTileFeature = vectortilefeature; +var VectorTileLayer = vectorTile.VectorTileLayer = vectortilelayer; + +const vectorTileFeatureTypes$2 = vectorTile.VectorTileFeature.types; +const EARCUT_MAX_RINGS = 500; +const FACTOR = Math.pow(2, 13); +function addVertex$1(vertexArray, x, y, nx, ny, nz, t, e) { + vertexArray.emplaceBack( + // a_pos + x, y, + // a_normal_ed: 3-component normal and 1-component edgedistance + Math.floor(nx * FACTOR) * 2 + t, ny * FACTOR * 2, nz * FACTOR * 2, + // edgedistance (used for wrapping patterns around extrusion sides) + Math.round(e)); +} +class FillExtrusionBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.layoutVertexArray = new FillExtrusionLayoutArray(); + this.centroidVertexArray = new PosArray(); + this.indexArray = new TriangleIndexArray(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.segments = new SegmentVector(); + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + this.features = []; + this.hasPattern = hasPattern('fill-extrusion', this.layers, options); + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const bucketFeature = { + id, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + properties: feature.properties, + type: feature.type, + patterns: {} + }; + if (this.hasPattern) { + this.features.push(addPatternDependencies('fill-extrusion', this.layers, bucketFeature, this.zoom, options)); + } + else { + this.addFeature(bucketFeature, bucketFeature.geometry, index, canonical, {}); + } + options.featureIndex.insert(feature, bucketFeature.geometry, index, sourceLayerIndex, this.index, true); + } + } + addFeatures(options, canonical, imagePositions) { + for (const feature of this.features) { + const { geometry } = feature; + this.addFeature(feature, geometry, feature.index, canonical, imagePositions); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + isEmpty() { + return this.layoutVertexArray.length === 0 && this.centroidVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$2); + this.centroidVertexBuffer = context.createVertexBuffer(this.centroidVertexArray, centroidAttributes.members, true); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + this.centroidVertexBuffer.destroy(); + } + addFeature(feature, geometry, index, canonical, imagePositions) { + for (const polygon of classifyRings$1(geometry, EARCUT_MAX_RINGS)) { + const centroid = { x: 0, y: 0, vertexCount: 0 }; + let numVertices = 0; + for (const ring of polygon) { + numVertices += ring.length; + } + let segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray); + for (const ring of polygon) { + if (ring.length === 0) { + continue; + } + if (isEntirelyOutside(ring)) { + continue; + } + let edgeDistance = 0; + for (let p = 0; p < ring.length; p++) { + const p1 = ring[p]; + if (p >= 1) { + const p2 = ring[p - 1]; + if (!isBoundaryEdge(p1, p2)) { + if (segment.vertexLength + 4 > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) { + segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray); + } + const perp = p1.sub(p2)._perp()._unit(); + const dist = p2.dist(p1); + if (edgeDistance + dist > 32768) + edgeDistance = 0; + addVertex$1(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 0, edgeDistance); + addVertex$1(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 1, edgeDistance); + centroid.x += 2 * p1.x; + centroid.y += 2 * p1.y; + centroid.vertexCount += 2; + edgeDistance += dist; + addVertex$1(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 0, edgeDistance); + addVertex$1(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 1, edgeDistance); + centroid.x += 2 * p2.x; + centroid.y += 2 * p2.y; + centroid.vertexCount += 2; + const bottomRight = segment.vertexLength; + // ┌──────┐ + // │ 0 1 │ Counter-clockwise winding order. + // │ │ Triangle 1: 0 => 2 => 1 + // │ 2 3 │ Triangle 2: 1 => 2 => 3 + // └──────┘ + this.indexArray.emplaceBack(bottomRight, bottomRight + 2, bottomRight + 1); + this.indexArray.emplaceBack(bottomRight + 1, bottomRight + 2, bottomRight + 3); + segment.vertexLength += 4; + segment.primitiveLength += 2; + } + } + } + } + if (segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) { + segment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray); + } + //Only triangulate and draw the area of the feature if it is a polygon + //Other feature types (e.g. LineString) do not have area, so triangulation is pointless / undefined + if (vectorTileFeatureTypes$2[feature.type] !== 'Polygon') + continue; + const flattened = []; + const holeIndices = []; + const triangleIndex = segment.vertexLength; + for (const ring of polygon) { + if (ring.length === 0) { + continue; + } + if (ring !== polygon[0]) { + holeIndices.push(flattened.length / 2); + } + for (let i = 0; i < ring.length; i++) { + const p = ring[i]; + addVertex$1(this.layoutVertexArray, p.x, p.y, 0, 0, 1, 1, 0); + centroid.x += p.x; + centroid.y += p.y; + centroid.vertexCount += 1; + flattened.push(p.x); + flattened.push(p.y); + } + } + const indices = earcut(flattened, holeIndices); + for (let j = 0; j < indices.length; j += 3) { + // Counter-clockwise winding order. + this.indexArray.emplaceBack(triangleIndex + indices[j], triangleIndex + indices[j + 2], triangleIndex + indices[j + 1]); + } + segment.primitiveLength += indices.length / 3; + segment.vertexLength += numVertices; + // remember polygon centroid to calculate elevation in GPU + for (let i = 0; i < centroid.vertexCount; i++) { + const averageX = Math.floor(centroid.x / centroid.vertexCount); + const averageY = Math.floor(centroid.y / centroid.vertexCount); + this.centroidVertexArray.emplaceBack(averageX, averageY); + } + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical); + } +} +register('FillExtrusionBucket', FillExtrusionBucket, { omit: ['layers', 'features'] }); +function isBoundaryEdge(p1, p2) { + return (p1.x === p2.x && (p1.x < 0 || p1.x > EXTENT)) || + (p1.y === p2.y && (p1.y < 0 || p1.y > EXTENT)); +} +function isEntirelyOutside(ring) { + return ring.every(p => p.x < 0) || + ring.every(p => p.x > EXTENT) || + ring.every(p => p.y < 0) || + ring.every(p => p.y > EXTENT); +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$4; +const getPaint$4 = () => paint$4 = paint$4 || new Properties({ + "fill-extrusion-opacity": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-opacity"]), + "fill-extrusion-color": new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-color"]), + "fill-extrusion-translate": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-translate"]), + "fill-extrusion-translate-anchor": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]), + "fill-extrusion-pattern": new CrossFadedDataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-pattern"]), + "fill-extrusion-height": new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-height"]), + "fill-extrusion-base": new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-base"]), + "fill-extrusion-vertical-gradient": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"]), +}); +var properties$5 = ({ get paint() { return getPaint$4(); } }); + +class Point3D extends Point$2 { +} +class FillExtrusionStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$5); + } + createBucket(parameters) { + return new FillExtrusionBucket(parameters); + } + queryRadius() { + return translateDistance(this.paint.get('fill-extrusion-translate')); + } + is3D() { + return true; + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits, pixelPosMatrix) { + const translatedPolygon = translate$4(queryGeometry, this.paint.get('fill-extrusion-translate'), this.paint.get('fill-extrusion-translate-anchor'), transform.angle, pixelsToTileUnits); + const height = this.paint.get('fill-extrusion-height').evaluate(feature, featureState); + const base = this.paint.get('fill-extrusion-base').evaluate(feature, featureState); + const projectedQueryGeometry = projectQueryGeometry(translatedPolygon, pixelPosMatrix, transform, 0); + const projected = projectExtrusion(geometry, base, height, pixelPosMatrix); + const projectedBase = projected[0]; + const projectedTop = projected[1]; + return checkIntersection(projectedBase, projectedTop, projectedQueryGeometry); + } +} +function dot(a, b) { + return a.x * b.x + a.y * b.y; +} +function getIntersectionDistance(projectedQueryGeometry, projectedFace) { + if (projectedQueryGeometry.length === 1) { + // For point queries calculate the z at which the point intersects the face + // using barycentric coordinates. + // Find the barycentric coordinates of the projected point within the first + // triangle of the face, using only the xy plane. It doesn't matter if the + // point is outside the first triangle because all the triangles in the face + // are in the same plane. + // + // Check whether points are coincident and use other points if they are. + let i = 0; + const a = projectedFace[i++]; + let b; + while (!b || a.equals(b)) { + b = projectedFace[i++]; + if (!b) + return Infinity; + } + // Loop until point `c` is not colinear with points `a` and `b`. + for (; i < projectedFace.length; i++) { + const c = projectedFace[i]; + const p = projectedQueryGeometry[0]; + const ab = b.sub(a); + const ac = c.sub(a); + const ap = p.sub(a); + const dotABAB = dot(ab, ab); + const dotABAC = dot(ab, ac); + const dotACAC = dot(ac, ac); + const dotAPAB = dot(ap, ab); + const dotAPAC = dot(ap, ac); + const denom = dotABAB * dotACAC - dotABAC * dotABAC; + const v = (dotACAC * dotAPAB - dotABAC * dotAPAC) / denom; + const w = (dotABAB * dotAPAC - dotABAC * dotAPAB) / denom; + const u = 1 - v - w; + // Use the barycentric weighting along with the original triangle z coordinates to get the point of intersection. + const distance = a.z * u + b.z * v + c.z * w; + if (isFinite(distance)) + return distance; + } + return Infinity; + } + else { + // The counts as closest is less clear when the query is a box. This + // returns the distance to the nearest point on the face, whether it is + // within the query or not. It could be more correct to return the + // distance to the closest point within the query box but this would be + // more complicated and expensive to calculate with little benefit. + let closestDistance = Infinity; + for (const p of projectedFace) { + closestDistance = Math.min(closestDistance, p.z); + } + return closestDistance; + } +} +function checkIntersection(projectedBase, projectedTop, projectedQueryGeometry) { + let closestDistance = Infinity; + if (polygonIntersectsMultiPolygon(projectedQueryGeometry, projectedTop)) { + closestDistance = getIntersectionDistance(projectedQueryGeometry, projectedTop[0]); + } + for (let r = 0; r < projectedTop.length; r++) { + const ringTop = projectedTop[r]; + const ringBase = projectedBase[r]; + for (let p = 0; p < ringTop.length - 1; p++) { + const topA = ringTop[p]; + const topB = ringTop[p + 1]; + const baseA = ringBase[p]; + const baseB = ringBase[p + 1]; + const face = [topA, topB, baseB, baseA, topA]; + if (polygonIntersectsPolygon(projectedQueryGeometry, face)) { + closestDistance = Math.min(closestDistance, getIntersectionDistance(projectedQueryGeometry, face)); + } + } + } + return closestDistance === Infinity ? false : closestDistance; +} +/* + * Project the geometry using matrix `m`. This is essentially doing + * `vec4.transformMat4([], [p.x, p.y, z, 1], m)` but the multiplication + * is inlined so that parts of the projection that are the same across + * different points can only be done once. This produced a measurable + * performance improvement. + */ +function projectExtrusion(geometry, zBase, zTop, m) { + const projectedBase = []; + const projectedTop = []; + const baseXZ = m[8] * zBase; + const baseYZ = m[9] * zBase; + const baseZZ = m[10] * zBase; + const baseWZ = m[11] * zBase; + const topXZ = m[8] * zTop; + const topYZ = m[9] * zTop; + const topZZ = m[10] * zTop; + const topWZ = m[11] * zTop; + for (const r of geometry) { + const ringBase = []; + const ringTop = []; + for (const p of r) { + const x = p.x; + const y = p.y; + const sX = m[0] * x + m[4] * y + m[12]; + const sY = m[1] * x + m[5] * y + m[13]; + const sZ = m[2] * x + m[6] * y + m[14]; + const sW = m[3] * x + m[7] * y + m[15]; + const baseX = sX + baseXZ; + const baseY = sY + baseYZ; + const baseZ = sZ + baseZZ; + const baseW = sW + baseWZ; + const topX = sX + topXZ; + const topY = sY + topYZ; + const topZ = sZ + topZZ; + const topW = sW + topWZ; + const b = new Point$2(baseX / baseW, baseY / baseW); + b.z = baseZ / baseW; + ringBase.push(b); + const t = new Point$2(topX / topW, topY / topW); + t.z = topZ / topW; + ringTop.push(t); + } + projectedBase.push(ringBase); + projectedTop.push(ringTop); + } + return [projectedBase, projectedTop]; +} +function projectQueryGeometry(queryGeometry, pixelPosMatrix, transform, z) { + const projectedQueryGeometry = []; + for (const p of queryGeometry) { + const v = [p.x, p.y, z, 1]; + transformMat4$1(v, v, pixelPosMatrix); + projectedQueryGeometry.push(new Point$2(v[0] / v[3], v[1] / v[3])); + } + return projectedQueryGeometry; +} + +const lineLayoutAttributes = createLayout([ + { name: 'a_pos_normal', components: 2, type: 'Int16' }, + { name: 'a_data', components: 4, type: 'Uint8' } +], 4); +const { members: members$1, size: size$1, alignment: alignment$1 } = lineLayoutAttributes; + +const lineLayoutAttributesExt = createLayout([ + { name: 'a_uv_x', components: 1, type: 'Float32' }, + { name: 'a_split_index', components: 1, type: 'Float32' }, +]); +const { members, size, alignment } = lineLayoutAttributesExt; + +const vectorTileFeatureTypes$1 = vectorTile.VectorTileFeature.types; +// NOTE ON EXTRUDE SCALE: +// scale the extrusion vector so that the normal length is this value. +// contains the "texture" normals (-1..1). this is distinct from the extrude +// normals for line joins, because the x-value remains 0 for the texture +// normal array, while the extrude normal actually moves the vertex to create +// the acute/bevelled line join. +const EXTRUDE_SCALE = 63; +/* + * Sharp corners cause dashed lines to tilt because the distance along the line + * is the same at both the inner and outer corners. To improve the appearance of + * dashed lines we add extra points near sharp corners so that a smaller part + * of the line is tilted. + * + * COS_HALF_SHARP_CORNER controls how sharp a corner has to be for us to add an + * extra vertex. The default is 75 degrees. + * + * The newly created vertices are placed SHARP_CORNER_OFFSET pixels from the corner. + */ +const COS_HALF_SHARP_CORNER = Math.cos(75 / 2 * (Math.PI / 180)); +const SHARP_CORNER_OFFSET = 15; +// Angle per triangle for approximating round line joins. +const DEG_PER_TRIANGLE = 20; +// The number of bits that is used to store the line distance in the buffer. +const LINE_DISTANCE_BUFFER_BITS = 15; +// We don't have enough bits for the line distance as we'd like to have, so +// use this value to scale the line distance (in tile units) down to a smaller +// value. This lets us store longer distances while sacrificing precision. +const LINE_DISTANCE_SCALE = 1 / 2; +// The maximum line distance, in tile units, that fits in the buffer. +const MAX_LINE_DISTANCE = Math.pow(2, LINE_DISTANCE_BUFFER_BITS - 1) / LINE_DISTANCE_SCALE; +/** + * @internal + * Line bucket class + */ +class LineBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.patternFeatures = []; + this.lineClipsArray = []; + this.gradients = {}; + this.layers.forEach(layer => { + this.gradients[layer.id] = {}; + }); + this.layoutVertexArray = new LineLayoutArray(); + this.layoutVertexArray2 = new LineExtLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.segments = new SegmentVector(); + this.maxLineLength = 0; + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + this.hasPattern = hasPattern('line', this.layers, options); + const lineSortKey = this.layers[0].layout.get('line-sort-key'); + const sortFeaturesByKey = !lineSortKey.isConstant(); + const bucketFeatures = []; + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const sortKey = sortFeaturesByKey ? + lineSortKey.evaluate(evaluationFeature, {}, canonical) : + undefined; + const bucketFeature = { + id, + properties: feature.properties, + type: feature.type, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + patterns: {}, + sortKey + }; + bucketFeatures.push(bucketFeature); + } + if (sortFeaturesByKey) { + bucketFeatures.sort((a, b) => { + return (a.sortKey) - (b.sortKey); + }); + } + for (const bucketFeature of bucketFeatures) { + const { geometry, index, sourceLayerIndex } = bucketFeature; + if (this.hasPattern) { + const patternBucketFeature = addPatternDependencies('line', this.layers, bucketFeature, this.zoom, options); + // pattern features are added only once the pattern is loaded into the image atlas + // so are stored during populate until later updated with positions by tile worker in addFeatures + this.patternFeatures.push(patternBucketFeature); + } + else { + this.addFeature(bucketFeature, geometry, index, canonical, {}); + } + const feature = features[index].feature; + options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + addFeatures(options, canonical, imagePositions) { + for (const feature of this.patternFeatures) { + this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions); + } + } + isEmpty() { + return this.layoutVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + if (this.layoutVertexArray2.length !== 0) { + this.layoutVertexBuffer2 = context.createVertexBuffer(this.layoutVertexArray2, members); + } + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$1); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + } + lineFeatureClips(feature) { + if (!!feature.properties && Object.prototype.hasOwnProperty.call(feature.properties, 'mapbox_clip_start') && Object.prototype.hasOwnProperty.call(feature.properties, 'mapbox_clip_end')) { + const start = +feature.properties['mapbox_clip_start']; + const end = +feature.properties['mapbox_clip_end']; + return { start, end }; + } + } + addFeature(feature, geometry, index, canonical, imagePositions) { + const layout = this.layers[0].layout; + const join = layout.get('line-join').evaluate(feature, {}); + const cap = layout.get('line-cap'); + const miterLimit = layout.get('line-miter-limit'); + const roundLimit = layout.get('line-round-limit'); + this.lineClips = this.lineFeatureClips(feature); + for (const line of geometry) { + this.addLine(line, feature, join, cap, miterLimit, roundLimit); + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical); + } + addLine(vertices, feature, join, cap, miterLimit, roundLimit) { + this.distance = 0; + this.scaledDistance = 0; + this.totalDistance = 0; + if (this.lineClips) { + this.lineClipsArray.push(this.lineClips); + // Calculate the total distance, in tile units, of this tiled line feature + for (let i = 0; i < vertices.length - 1; i++) { + this.totalDistance += vertices[i].dist(vertices[i + 1]); + } + this.updateScaledDistance(); + this.maxLineLength = Math.max(this.maxLineLength, this.totalDistance); + } + const isPolygon = vectorTileFeatureTypes$1[feature.type] === 'Polygon'; + // If the line has duplicate vertices at the ends, adjust start/length to remove them. + let len = vertices.length; + while (len >= 2 && vertices[len - 1].equals(vertices[len - 2])) { + len--; + } + let first = 0; + while (first < len - 1 && vertices[first].equals(vertices[first + 1])) { + first++; + } + // Ignore invalid geometry. + if (len < (isPolygon ? 3 : 2)) + return; + if (join === 'bevel') + miterLimit = 1.05; + const sharpCornerOffset = this.overscaling <= 16 ? + SHARP_CORNER_OFFSET * EXTENT / (512 * this.overscaling) : + 0; + // we could be more precise, but it would only save a negligible amount of space + const segment = this.segments.prepareSegment(len * 10, this.layoutVertexArray, this.indexArray); + let currentVertex; + let prevVertex; + let nextVertex; + let prevNormal; + let nextNormal; + // the last two vertices added + this.e1 = this.e2 = -1; + if (isPolygon) { + currentVertex = vertices[len - 2]; + nextNormal = vertices[first].sub(currentVertex)._unit()._perp(); + } + for (let i = first; i < len; i++) { + nextVertex = i === len - 1 ? + (isPolygon ? vertices[first + 1] : undefined) : // if it's a polygon, treat the last vertex like the first + vertices[i + 1]; // just the next vertex + // if two consecutive vertices exist, skip the current one + if (nextVertex && vertices[i].equals(nextVertex)) + continue; + if (nextNormal) + prevNormal = nextNormal; + if (currentVertex) + prevVertex = currentVertex; + currentVertex = vertices[i]; + // Calculate the normal towards the next vertex in this line. In case + // there is no next vertex, pretend that the line is continuing straight, + // meaning that we are just using the previous normal. + nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal; + // If we still don't have a previous normal, this is the beginning of a + // non-closed line, so we're doing a straight "join". + prevNormal = prevNormal || nextNormal; + // Determine the normal of the join extrusion. It is the angle bisector + // of the segments between the previous line and the next line. + // In the case of 180° angles, the prev and next normals cancel each other out: + // prevNormal + nextNormal = (0, 0), its magnitude is 0, so the unit vector would be + // undefined. In that case, we're keeping the joinNormal at (0, 0), so that the cosHalfAngle + // below will also become 0 and miterLength will become Infinity. + let joinNormal = prevNormal.add(nextNormal); + if (joinNormal.x !== 0 || joinNormal.y !== 0) { + joinNormal._unit(); + } + /* joinNormal prevNormal + * ↖ ↑ + * .________. prevVertex + * | + * nextNormal ← | currentVertex + * | + * nextVertex ! + * + */ + // calculate cosines of the angle (and its half) using dot product + const cosAngle = prevNormal.x * nextNormal.x + prevNormal.y * nextNormal.y; + const cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y; + // Calculate the length of the miter (the ratio of the miter to the width) + // as the inverse of cosine of the angle between next and join normals + const miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity; + // approximate angle from cosine + const approxAngle = 2 * Math.sqrt(2 - 2 * cosHalfAngle); + const isSharpCorner = cosHalfAngle < COS_HALF_SHARP_CORNER && prevVertex && nextVertex; + const lineTurnsLeft = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0; + if (isSharpCorner && i > first) { + const prevSegmentLength = currentVertex.dist(prevVertex); + if (prevSegmentLength > 2 * sharpCornerOffset) { + const newPrevVertex = currentVertex.sub(currentVertex.sub(prevVertex)._mult(sharpCornerOffset / prevSegmentLength)._round()); + this.updateDistance(prevVertex, newPrevVertex); + this.addCurrentVertex(newPrevVertex, prevNormal, 0, 0, segment); + prevVertex = newPrevVertex; + } + } + // The join if a middle vertex, otherwise the cap. + const middleVertex = prevVertex && nextVertex; + let currentJoin = middleVertex ? join : isPolygon ? 'butt' : cap; + if (middleVertex && currentJoin === 'round') { + if (miterLength < roundLimit) { + currentJoin = 'miter'; + } + else if (miterLength <= 2) { + currentJoin = 'fakeround'; + } + } + if (currentJoin === 'miter' && miterLength > miterLimit) { + currentJoin = 'bevel'; + } + if (currentJoin === 'bevel') { + // The maximum extrude length is 128 / 63 = 2 times the width of the line + // so if miterLength >= 2 we need to draw a different type of bevel here. + if (miterLength > 2) + currentJoin = 'flipbevel'; + // If the miterLength is really small and the line bevel wouldn't be visible, + // just draw a miter join to save a triangle. + if (miterLength < miterLimit) + currentJoin = 'miter'; + } + // Calculate how far along the line the currentVertex is + if (prevVertex) + this.updateDistance(prevVertex, currentVertex); + if (currentJoin === 'miter') { + joinNormal._mult(miterLength); + this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); + } + else if (currentJoin === 'flipbevel') { + // miter is too big, flip the direction to make a beveled join + if (miterLength > 100) { + // Almost parallel lines + joinNormal = nextNormal.mult(-1); + } + else { + const bevelLength = miterLength * prevNormal.add(nextNormal).mag() / prevNormal.sub(nextNormal).mag(); + joinNormal._perp()._mult(bevelLength * (lineTurnsLeft ? -1 : 1)); + } + this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); + this.addCurrentVertex(currentVertex, joinNormal.mult(-1), 0, 0, segment); + } + else if (currentJoin === 'bevel' || currentJoin === 'fakeround') { + const offset = -Math.sqrt(miterLength * miterLength - 1); + const offsetA = lineTurnsLeft ? offset : 0; + const offsetB = lineTurnsLeft ? 0 : offset; + // Close previous segment with a bevel + if (prevVertex) { + this.addCurrentVertex(currentVertex, prevNormal, offsetA, offsetB, segment); + } + if (currentJoin === 'fakeround') { + // The join angle is sharp enough that a round join would be visible. + // Bevel joins fill the gap between segments with a single pie slice triangle. + // Create a round join by adding multiple pie slices. The join isn't actually round, but + // it looks like it is at the sizes we render lines at. + // pick the number of triangles for approximating round join by based on the angle between normals + const n = Math.round((approxAngle * 180 / Math.PI) / DEG_PER_TRIANGLE); + for (let m = 1; m < n; m++) { + let t = m / n; + if (t !== 0.5) { + // approximate spherical interpolation https://observablehq.com/@mourner/approximating-geometric-slerp + const t2 = t - 0.5; + const A = 1.0904 + cosAngle * (-3.2452 + cosAngle * (3.55645 - cosAngle * 1.43519)); + const B = 0.848013 + cosAngle * (-1.06021 + cosAngle * 0.215638); + t = t + t * t2 * (t - 1) * (A * t2 * t2 + B); + } + const extrude = nextNormal.sub(prevNormal)._mult(t)._add(prevNormal)._unit()._mult(lineTurnsLeft ? -1 : 1); + this.addHalfVertex(currentVertex, extrude.x, extrude.y, false, lineTurnsLeft, 0, segment); + } + } + if (nextVertex) { + // Start next segment + this.addCurrentVertex(currentVertex, nextNormal, -offsetA, -offsetB, segment); + } + } + else if (currentJoin === 'butt') { + this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); // butt cap + } + else if (currentJoin === 'square') { + const offset = prevVertex ? 1 : -1; // closing or starting square cap + this.addCurrentVertex(currentVertex, joinNormal, offset, offset, segment); + } + else if (currentJoin === 'round') { + if (prevVertex) { + // Close previous segment with butt + this.addCurrentVertex(currentVertex, prevNormal, 0, 0, segment); + // Add round cap or linejoin at end of segment + this.addCurrentVertex(currentVertex, prevNormal, 1, 1, segment, true); + } + if (nextVertex) { + // Add round cap before first segment + this.addCurrentVertex(currentVertex, nextNormal, -1, -1, segment, true); + // Start next segment with a butt + this.addCurrentVertex(currentVertex, nextNormal, 0, 0, segment); + } + } + if (isSharpCorner && i < len - 1) { + const nextSegmentLength = currentVertex.dist(nextVertex); + if (nextSegmentLength > 2 * sharpCornerOffset) { + const newCurrentVertex = currentVertex.add(nextVertex.sub(currentVertex)._mult(sharpCornerOffset / nextSegmentLength)._round()); + this.updateDistance(currentVertex, newCurrentVertex); + this.addCurrentVertex(newCurrentVertex, nextNormal, 0, 0, segment); + currentVertex = newCurrentVertex; + } + } + } + } + /** + * Add two vertices to the buffers. + * + * @param p - the line vertex to add buffer vertices for + * @param normal - vertex normal + * @param endLeft - extrude to shift the left vertex along the line + * @param endRight - extrude to shift the left vertex along the line + * @param segment - the segment object to add the vertex to + * @param round - whether this is a round cap + */ + addCurrentVertex(p, normal, endLeft, endRight, segment, round = false) { + // left and right extrude vectors, perpendicularly shifted by endLeft/endRight + const leftX = normal.x + normal.y * endLeft; + const leftY = normal.y - normal.x * endLeft; + const rightX = -normal.x + normal.y * endRight; + const rightY = -normal.y - normal.x * endRight; + this.addHalfVertex(p, leftX, leftY, round, false, endLeft, segment); + this.addHalfVertex(p, rightX, rightY, round, true, -endRight, segment); + // There is a maximum "distance along the line" that we can store in the buffers. + // When we get close to the distance, reset it to zero and add the vertex again with + // a distance of zero. The max distance is determined by the number of bits we allocate + // to `linesofar`. + if (this.distance > MAX_LINE_DISTANCE / 2 && this.totalDistance === 0) { + this.distance = 0; + this.updateScaledDistance(); + this.addCurrentVertex(p, normal, endLeft, endRight, segment, round); + } + } + addHalfVertex({ x, y }, extrudeX, extrudeY, round, up, dir, segment) { + const totalDistance = this.lineClips ? this.scaledDistance * (MAX_LINE_DISTANCE - 1) : this.scaledDistance; + // scale down so that we can store longer distances while sacrificing precision. + const linesofarScaled = totalDistance * LINE_DISTANCE_SCALE; + this.layoutVertexArray.emplaceBack( + // a_pos_normal + // Encode round/up the least significant bits + (x << 1) + (round ? 1 : 0), (y << 1) + (up ? 1 : 0), + // a_data + // add 128 to store a byte in an unsigned byte + Math.round(EXTRUDE_SCALE * extrudeX) + 128, Math.round(EXTRUDE_SCALE * extrudeY) + 128, + // Encode the -1/0/1 direction value into the first two bits of .z of a_data. + // Combine it with the lower 6 bits of `linesofarScaled` (shifted by 2 bits to make + // room for the direction value). The upper 8 bits of `linesofarScaled` are placed in + // the `w` component. + ((dir === 0 ? 0 : (dir < 0 ? -1 : 1)) + 1) | ((linesofarScaled & 0x3F) << 2), linesofarScaled >> 6); + // Constructs a second vertex buffer with higher precision line progress + if (this.lineClips) { + const progressRealigned = this.scaledDistance - this.lineClips.start; + const endClipRealigned = this.lineClips.end - this.lineClips.start; + const uvX = progressRealigned / endClipRealigned; + this.layoutVertexArray2.emplaceBack(uvX, this.lineClipsArray.length); + } + const e = segment.vertexLength++; + if (this.e1 >= 0 && this.e2 >= 0) { + this.indexArray.emplaceBack(this.e1, this.e2, e); + segment.primitiveLength++; + } + if (up) { + this.e2 = e; + } + else { + this.e1 = e; + } + } + updateScaledDistance() { + // Knowing the ratio of the full linestring covered by this tiled feature, as well + // as the total distance (in tile units) of this tiled feature, and the distance + // (in tile units) of the current vertex, we can determine the relative distance + // of this vertex along the full linestring feature and scale it to [0, 2^15) + this.scaledDistance = this.lineClips ? + this.lineClips.start + (this.lineClips.end - this.lineClips.start) * this.distance / this.totalDistance : + this.distance; + } + updateDistance(prev, next) { + this.distance += prev.dist(next); + this.updateScaledDistance(); + } +} +register('LineBucket', LineBucket, { omit: ['layers', 'patternFeatures'] }); + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout$1; +const getLayout$1 = () => layout$1 = layout$1 || new Properties({ + "line-cap": new DataConstantProperty(v8Spec["layout_line"]["line-cap"]), + "line-join": new DataDrivenProperty(v8Spec["layout_line"]["line-join"]), + "line-miter-limit": new DataConstantProperty(v8Spec["layout_line"]["line-miter-limit"]), + "line-round-limit": new DataConstantProperty(v8Spec["layout_line"]["line-round-limit"]), + "line-sort-key": new DataDrivenProperty(v8Spec["layout_line"]["line-sort-key"]), +}); +let paint$3; +const getPaint$3 = () => paint$3 = paint$3 || new Properties({ + "line-opacity": new DataDrivenProperty(v8Spec["paint_line"]["line-opacity"]), + "line-color": new DataDrivenProperty(v8Spec["paint_line"]["line-color"]), + "line-translate": new DataConstantProperty(v8Spec["paint_line"]["line-translate"]), + "line-translate-anchor": new DataConstantProperty(v8Spec["paint_line"]["line-translate-anchor"]), + "line-width": new DataDrivenProperty(v8Spec["paint_line"]["line-width"]), + "line-gap-width": new DataDrivenProperty(v8Spec["paint_line"]["line-gap-width"]), + "line-offset": new DataDrivenProperty(v8Spec["paint_line"]["line-offset"]), + "line-blur": new DataDrivenProperty(v8Spec["paint_line"]["line-blur"]), + "line-dasharray": new CrossFadedProperty(v8Spec["paint_line"]["line-dasharray"]), + "line-pattern": new CrossFadedDataDrivenProperty(v8Spec["paint_line"]["line-pattern"]), + "line-gradient": new ColorRampProperty(v8Spec["paint_line"]["line-gradient"]), +}); +var properties$4 = ({ get paint() { return getPaint$3(); }, get layout() { return getLayout$1(); } }); + +class LineFloorwidthProperty extends DataDrivenProperty { + possiblyEvaluate(value, parameters) { + parameters = new EvaluationParameters(Math.floor(parameters.zoom), { + now: parameters.now, + fadeDuration: parameters.fadeDuration, + zoomHistory: parameters.zoomHistory, + transition: parameters.transition + }); + return super.possiblyEvaluate(value, parameters); + } + evaluate(value, globals, feature, featureState) { + globals = extend({}, globals, { zoom: Math.floor(globals.zoom) }); + return super.evaluate(value, globals, feature, featureState); + } +} +let lineFloorwidthProperty; +class LineStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$4); + this.gradientVersion = 0; + if (!lineFloorwidthProperty) { + lineFloorwidthProperty = + new LineFloorwidthProperty(properties$4.paint.properties['line-width'].specification); + lineFloorwidthProperty.useIntegerZoom = true; + } + } + _handleSpecialPaintPropertyUpdate(name) { + if (name === 'line-gradient') { + const expression = this.gradientExpression(); + if (isZoomExpression(expression)) { + this.stepInterpolant = expression._styleExpression.expression instanceof Step; + } + else { + this.stepInterpolant = false; + } + this.gradientVersion = (this.gradientVersion + 1) % Number.MAX_SAFE_INTEGER; + } + } + gradientExpression() { + return this._transitionablePaint._values['line-gradient'].value.expression; + } + recalculate(parameters, availableImages) { + super.recalculate(parameters, availableImages); + this.paint._values['line-floorwidth'] = + lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values['line-width'].value, parameters); + } + createBucket(parameters) { + return new LineBucket(parameters); + } + queryRadius(bucket) { + const lineBucket = bucket; + const width = getLineWidth(getMaximumPaintValue('line-width', this, lineBucket), getMaximumPaintValue('line-gap-width', this, lineBucket)); + const offset = getMaximumPaintValue('line-offset', this, lineBucket); + return width / 2 + Math.abs(offset) + translateDistance(this.paint.get('line-translate')); + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits) { + const translatedPolygon = translate$4(queryGeometry, this.paint.get('line-translate'), this.paint.get('line-translate-anchor'), transform.angle, pixelsToTileUnits); + const halfWidth = pixelsToTileUnits / 2 * getLineWidth(this.paint.get('line-width').evaluate(feature, featureState), this.paint.get('line-gap-width').evaluate(feature, featureState)); + const lineOffset = this.paint.get('line-offset').evaluate(feature, featureState); + if (lineOffset) { + geometry = offsetLine(geometry, lineOffset * pixelsToTileUnits); + } + return polygonIntersectsBufferedMultiLine(translatedPolygon, geometry, halfWidth); + } + isTileClipped() { + return true; + } +} +function getLineWidth(lineWidth, lineGapWidth) { + if (lineGapWidth > 0) { + return lineGapWidth + 2 * lineWidth; + } + else { + return lineWidth; + } +} + +const symbolLayoutAttributes = createLayout([ + { name: 'a_pos_offset', components: 4, type: 'Int16' }, + { name: 'a_data', components: 4, type: 'Uint16' }, + { name: 'a_pixeloffset', components: 4, type: 'Int16' } +], 4); +const dynamicLayoutAttributes = createLayout([ + { name: 'a_projected_pos', components: 3, type: 'Float32' } +], 4); +const placementOpacityAttributes = createLayout([ + { name: 'a_fade_opacity', components: 1, type: 'Uint32' } +], 4); +const collisionVertexAttributes = createLayout([ + { name: 'a_placed', components: 2, type: 'Uint8' }, + { name: 'a_shift', components: 2, type: 'Float32' }, + { name: 'a_box_real', components: 2, type: 'Int16' }, +]); +const collisionBox = createLayout([ + // the box is centered around the anchor point + { type: 'Int16', name: 'anchorPointX' }, + { type: 'Int16', name: 'anchorPointY' }, + // distances to the edges from the anchor + { type: 'Int16', name: 'x1' }, + { type: 'Int16', name: 'y1' }, + { type: 'Int16', name: 'x2' }, + { type: 'Int16', name: 'y2' }, + // the index of the feature in the original vectortile + { type: 'Uint32', name: 'featureIndex' }, + // the source layer the feature appears in + { type: 'Uint16', name: 'sourceLayerIndex' }, + // the bucket the feature appears in + { type: 'Uint16', name: 'bucketIndex' }, +]); +const collisionBoxLayout = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' }, + { name: 'a_anchor_pos', components: 2, type: 'Int16' }, + { name: 'a_extrude', components: 2, type: 'Int16' } +], 4); +const collisionCircleLayout = createLayout([ + { name: 'a_pos', components: 2, type: 'Float32' }, + { name: 'a_radius', components: 1, type: 'Float32' }, + { name: 'a_flags', components: 2, type: 'Int16' } +], 4); +const quadTriangle = createLayout([ + { name: 'triangle', components: 3, type: 'Uint16' }, +]); +const placement = createLayout([ + { type: 'Int16', name: 'anchorX' }, + { type: 'Int16', name: 'anchorY' }, + { type: 'Uint16', name: 'glyphStartIndex' }, + { type: 'Uint16', name: 'numGlyphs' }, + { type: 'Uint32', name: 'vertexStartIndex' }, + { type: 'Uint32', name: 'lineStartIndex' }, + { type: 'Uint32', name: 'lineLength' }, + { type: 'Uint16', name: 'segment' }, + { type: 'Uint16', name: 'lowerSize' }, + { type: 'Uint16', name: 'upperSize' }, + { type: 'Float32', name: 'lineOffsetX' }, + { type: 'Float32', name: 'lineOffsetY' }, + { type: 'Uint8', name: 'writingMode' }, + { type: 'Uint8', name: 'placedOrientation' }, + { type: 'Uint8', name: 'hidden' }, + { type: 'Uint32', name: 'crossTileID' }, + { type: 'Int16', name: 'associatedIconIndex' } +]); +const symbolInstance = createLayout([ + { type: 'Int16', name: 'anchorX' }, + { type: 'Int16', name: 'anchorY' }, + { type: 'Int16', name: 'rightJustifiedTextSymbolIndex' }, + { type: 'Int16', name: 'centerJustifiedTextSymbolIndex' }, + { type: 'Int16', name: 'leftJustifiedTextSymbolIndex' }, + { type: 'Int16', name: 'verticalPlacedTextSymbolIndex' }, + { type: 'Int16', name: 'placedIconSymbolIndex' }, + { type: 'Int16', name: 'verticalPlacedIconSymbolIndex' }, + { type: 'Uint16', name: 'key' }, + { type: 'Uint16', name: 'textBoxStartIndex' }, + { type: 'Uint16', name: 'textBoxEndIndex' }, + { type: 'Uint16', name: 'verticalTextBoxStartIndex' }, + { type: 'Uint16', name: 'verticalTextBoxEndIndex' }, + { type: 'Uint16', name: 'iconBoxStartIndex' }, + { type: 'Uint16', name: 'iconBoxEndIndex' }, + { type: 'Uint16', name: 'verticalIconBoxStartIndex' }, + { type: 'Uint16', name: 'verticalIconBoxEndIndex' }, + { type: 'Uint16', name: 'featureIndex' }, + { type: 'Uint16', name: 'numHorizontalGlyphVertices' }, + { type: 'Uint16', name: 'numVerticalGlyphVertices' }, + { type: 'Uint16', name: 'numIconVertices' }, + { type: 'Uint16', name: 'numVerticalIconVertices' }, + { type: 'Uint16', name: 'useRuntimeCollisionCircles' }, + { type: 'Uint32', name: 'crossTileID' }, + { type: 'Float32', name: 'textBoxScale' }, + { type: 'Float32', name: 'collisionCircleDiameter' }, + { type: 'Uint16', name: 'textAnchorOffsetStartIndex' }, + { type: 'Uint16', name: 'textAnchorOffsetEndIndex' } +]); +const glyphOffset = createLayout([ + { type: 'Float32', name: 'offsetX' } +]); +const lineVertex = createLayout([ + { type: 'Int16', name: 'x' }, + { type: 'Int16', name: 'y' }, + { type: 'Int16', name: 'tileUnitDistanceFromAnchor' } +]); +const textAnchorOffset = createLayout([ + { type: 'Uint16', name: 'textAnchor' }, + { type: 'Float32', components: 2, name: 'textOffset' } +]); + +function transformTextInternal(text, layer, feature) { + const transform = layer.layout.get('text-transform').evaluate(feature, {}); + if (transform === 'uppercase') { + text = text.toLocaleUpperCase(); + } + else if (transform === 'lowercase') { + text = text.toLocaleLowerCase(); + } + if (rtlWorkerPlugin.applyArabicShaping) { + text = rtlWorkerPlugin.applyArabicShaping(text); + } + return text; +} +function transformText(text, layer, feature) { + text.sections.forEach(section => { + section.text = transformTextInternal(section.text, layer, feature); + }); + return text; +} + +function mergeLines(features) { + const leftIndex = {}; + const rightIndex = {}; + const mergedFeatures = []; + let mergedIndex = 0; + function add(k) { + mergedFeatures.push(features[k]); + mergedIndex++; + } + function mergeFromRight(leftKey, rightKey, geom) { + const i = rightIndex[leftKey]; + delete rightIndex[leftKey]; + rightIndex[rightKey] = i; + mergedFeatures[i].geometry[0].pop(); + mergedFeatures[i].geometry[0] = mergedFeatures[i].geometry[0].concat(geom[0]); + return i; + } + function mergeFromLeft(leftKey, rightKey, geom) { + const i = leftIndex[rightKey]; + delete leftIndex[rightKey]; + leftIndex[leftKey] = i; + mergedFeatures[i].geometry[0].shift(); + mergedFeatures[i].geometry[0] = geom[0].concat(mergedFeatures[i].geometry[0]); + return i; + } + function getKey(text, geom, onRight) { + const point = onRight ? geom[0][geom[0].length - 1] : geom[0][0]; + return `${text}:${point.x}:${point.y}`; + } + for (let k = 0; k < features.length; k++) { + const feature = features[k]; + const geom = feature.geometry; + const text = feature.text ? feature.text.toString() : null; + if (!text) { + add(k); + continue; + } + const leftKey = getKey(text, geom), rightKey = getKey(text, geom, true); + if ((leftKey in rightIndex) && (rightKey in leftIndex) && (rightIndex[leftKey] !== leftIndex[rightKey])) { + // found lines with the same text adjacent to both ends of the current line, merge all three + const j = mergeFromLeft(leftKey, rightKey, geom); + const i = mergeFromRight(leftKey, rightKey, mergedFeatures[j].geometry); + delete leftIndex[leftKey]; + delete rightIndex[rightKey]; + rightIndex[getKey(text, mergedFeatures[i].geometry, true)] = i; + mergedFeatures[j].geometry = null; + } + else if (leftKey in rightIndex) { + // found mergeable line adjacent to the start of the current line, merge + mergeFromRight(leftKey, rightKey, geom); + } + else if (rightKey in leftIndex) { + // found mergeable line adjacent to the end of the current line, merge + mergeFromLeft(leftKey, rightKey, geom); + } + else { + // no adjacent lines, add as a new item + add(k); + leftIndex[leftKey] = mergedIndex - 1; + rightIndex[rightKey] = mergedIndex - 1; + } + } + return mergedFeatures.filter((f) => f.geometry); +} + +const verticalizedCharacterMap = { + '!': '︕', + '#': '#', + '$': '$', + '%': '%', + '&': '&', + '(': '︵', + ')': '︶', + '*': '*', + '+': '+', + ',': '︐', + '-': '︲', + '.': '・', + '/': '/', + ':': '︓', + ';': '︔', + '<': '︿', + '=': '=', + '>': '﹀', + '?': '︖', + '@': '@', + '[': '﹇', + '\\': '\', + ']': '﹈', + '^': '^', + '_': '︳', + '`': '`', + '{': '︷', + '|': '―', + '}': '︸', + '~': '~', + '¢': '¢', + '£': '£', + '¥': '¥', + '¦': '¦', + '¬': '¬', + '¯': ' ̄', + '–': '︲', + '—': '︱', + '‘': '﹃', + '’': '﹄', + '“': '﹁', + '”': '﹂', + '…': '︙', + '‧': '・', + '₩': '₩', + '、': '︑', + '。': '︒', + '〈': '︿', + '〉': '﹀', + '《': '︽', + '》': '︾', + '「': '﹁', + '」': '﹂', + '『': '﹃', + '』': '﹄', + '【': '︻', + '】': '︼', + '〔': '︹', + '〕': '︺', + '〖': '︗', + '〗': '︘', + '!': '︕', + '(': '︵', + ')': '︶', + ',': '︐', + '-': '︲', + '.': '・', + ':': '︓', + ';': '︔', + '<': '︿', + '>': '﹀', + '?': '︖', + '[': '﹇', + ']': '﹈', + '_': '︳', + '{': '︷', + '|': '―', + '}': '︸', + '⦅': '︵', + '⦆': '︶', + '。': '︒', + '「': '﹁', + '」': '﹂' +}; +function verticalizePunctuation(input) { + let output = ''; + for (let i = 0; i < input.length; i++) { + const nextCharCode = input.charCodeAt(i + 1) || null; + const prevCharCode = input.charCodeAt(i - 1) || null; + const canReplacePunctuation = ((!nextCharCode || !charHasRotatedVerticalOrientation(nextCharCode) || verticalizedCharacterMap[input[i + 1]]) && + (!prevCharCode || !charHasRotatedVerticalOrientation(prevCharCode) || verticalizedCharacterMap[input[i - 1]])); + if (canReplacePunctuation && verticalizedCharacterMap[input[i]]) { + output += verticalizedCharacterMap[input[i]]; + } + else { + output += input[i]; + } + } + return output; +} + +// ONE_EM constant used to go between "em" units used in style spec and "points" used internally for layout +var ONE_EM = 24; + +var ieee754$1 = {}; + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + +var read = ieee754$1.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = (nBytes * 8) - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +}; + +var write = ieee754$1.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = (nBytes * 8) - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +}; + +'use strict'; + +var pbf = Pbf; + +var ieee754 = ieee754$1; + +function Pbf(buf) { + this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0); + this.pos = 0; + this.type = 0; + this.length = this.buf.length; +} + +Pbf.Varint = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum +Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64 +Pbf.Bytes = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields +Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32 + +var SHIFT_LEFT_32 = (1 << 16) * (1 << 16), + SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32; + +// Threshold chosen based on both benchmarking and knowledge about browser string +// data structures (which currently switch structure types at 12 bytes or more) +var TEXT_DECODER_MIN_LENGTH = 12; +var utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8'); + +Pbf.prototype = { + + destroy: function() { + this.buf = null; + }, + + // === READING ================================================================= + + readFields: function(readField, result, end) { + end = end || this.length; + + while (this.pos < end) { + var val = this.readVarint(), + tag = val >> 3, + startPos = this.pos; + + this.type = val & 0x7; + readField(tag, result, this); + + if (this.pos === startPos) this.skip(val); + } + return result; + }, + + readMessage: function(readField, result) { + return this.readFields(readField, result, this.readVarint() + this.pos); + }, + + readFixed32: function() { + var val = readUInt32(this.buf, this.pos); + this.pos += 4; + return val; + }, + + readSFixed32: function() { + var val = readInt32(this.buf, this.pos); + this.pos += 4; + return val; + }, + + // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed) + + readFixed64: function() { + var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; + this.pos += 8; + return val; + }, + + readSFixed64: function() { + var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; + this.pos += 8; + return val; + }, + + readFloat: function() { + var val = ieee754.read(this.buf, this.pos, true, 23, 4); + this.pos += 4; + return val; + }, + + readDouble: function() { + var val = ieee754.read(this.buf, this.pos, true, 52, 8); + this.pos += 8; + return val; + }, + + readVarint: function(isSigned) { + var buf = this.buf, + val, b; + + b = buf[this.pos++]; val = b & 0x7f; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val; + b = buf[this.pos]; val |= (b & 0x0f) << 28; + + return readVarintRemainder(val, isSigned, this); + }, + + readVarint64: function() { // for compatibility with v2.0.1 + return this.readVarint(true); + }, + + readSVarint: function() { + var num = this.readVarint(); + return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding + }, + + readBoolean: function() { + return Boolean(this.readVarint()); + }, + + readString: function() { + var end = this.readVarint() + this.pos; + var pos = this.pos; + this.pos = end; + + if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) { + // longer strings are fast with the built-in browser TextDecoder API + return readUtf8TextDecoder(this.buf, pos, end); + } + // short strings are fast with our custom implementation + return readUtf8(this.buf, pos, end); + }, + + readBytes: function() { + var end = this.readVarint() + this.pos, + buffer = this.buf.subarray(this.pos, end); + this.pos = end; + return buffer; + }, + + // verbose for performance reasons; doesn't affect gzipped size + + readPackedVarint: function(arr, isSigned) { + if (this.type !== Pbf.Bytes) return arr.push(this.readVarint(isSigned)); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readVarint(isSigned)); + return arr; + }, + readPackedSVarint: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSVarint()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSVarint()); + return arr; + }, + readPackedBoolean: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readBoolean()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readBoolean()); + return arr; + }, + readPackedFloat: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFloat()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFloat()); + return arr; + }, + readPackedDouble: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readDouble()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readDouble()); + return arr; + }, + readPackedFixed32: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFixed32()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFixed32()); + return arr; + }, + readPackedSFixed32: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed32()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSFixed32()); + return arr; + }, + readPackedFixed64: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFixed64()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFixed64()); + return arr; + }, + readPackedSFixed64: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed64()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSFixed64()); + return arr; + }, + + skip: function(val) { + var type = val & 0x7; + if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {} + else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos; + else if (type === Pbf.Fixed32) this.pos += 4; + else if (type === Pbf.Fixed64) this.pos += 8; + else throw new Error('Unimplemented type: ' + type); + }, + + // === WRITING ================================================================= + + writeTag: function(tag, type) { + this.writeVarint((tag << 3) | type); + }, + + realloc: function(min) { + var length = this.length || 16; + + while (length < this.pos + min) length *= 2; + + if (length !== this.length) { + var buf = new Uint8Array(length); + buf.set(this.buf); + this.buf = buf; + this.length = length; + } + }, + + finish: function() { + this.length = this.pos; + this.pos = 0; + return this.buf.subarray(0, this.length); + }, + + writeFixed32: function(val) { + this.realloc(4); + writeInt32(this.buf, val, this.pos); + this.pos += 4; + }, + + writeSFixed32: function(val) { + this.realloc(4); + writeInt32(this.buf, val, this.pos); + this.pos += 4; + }, + + writeFixed64: function(val) { + this.realloc(8); + writeInt32(this.buf, val & -1, this.pos); + writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4); + this.pos += 8; + }, + + writeSFixed64: function(val) { + this.realloc(8); + writeInt32(this.buf, val & -1, this.pos); + writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4); + this.pos += 8; + }, + + writeVarint: function(val) { + val = +val || 0; + + if (val > 0xfffffff || val < 0) { + writeBigVarint(val, this); + return; + } + + this.realloc(4); + + this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = (val >>> 7) & 0x7f; + }, + + writeSVarint: function(val) { + this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2); + }, + + writeBoolean: function(val) { + this.writeVarint(Boolean(val)); + }, + + writeString: function(str) { + str = String(str); + this.realloc(str.length * 4); + + this.pos++; // reserve 1 byte for short string length + + var startPos = this.pos; + // write the string directly to the buffer and see how much was written + this.pos = writeUtf8(this.buf, str, this.pos); + var len = this.pos - startPos; + + if (len >= 0x80) makeRoomForExtraLength(startPos, len, this); + + // finally, write the message length in the reserved place and restore the position + this.pos = startPos - 1; + this.writeVarint(len); + this.pos += len; + }, + + writeFloat: function(val) { + this.realloc(4); + ieee754.write(this.buf, val, this.pos, true, 23, 4); + this.pos += 4; + }, + + writeDouble: function(val) { + this.realloc(8); + ieee754.write(this.buf, val, this.pos, true, 52, 8); + this.pos += 8; + }, + + writeBytes: function(buffer) { + var len = buffer.length; + this.writeVarint(len); + this.realloc(len); + for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i]; + }, + + writeRawMessage: function(fn, obj) { + this.pos++; // reserve 1 byte for short message length + + // write the message directly to the buffer and see how much was written + var startPos = this.pos; + fn(obj, this); + var len = this.pos - startPos; + + if (len >= 0x80) makeRoomForExtraLength(startPos, len, this); + + // finally, write the message length in the reserved place and restore the position + this.pos = startPos - 1; + this.writeVarint(len); + this.pos += len; + }, + + writeMessage: function(tag, fn, obj) { + this.writeTag(tag, Pbf.Bytes); + this.writeRawMessage(fn, obj); + }, + + writePackedVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedVarint, arr); }, + writePackedSVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSVarint, arr); }, + writePackedBoolean: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedBoolean, arr); }, + writePackedFloat: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFloat, arr); }, + writePackedDouble: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedDouble, arr); }, + writePackedFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed32, arr); }, + writePackedSFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr); }, + writePackedFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed64, arr); }, + writePackedSFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr); }, + + writeBytesField: function(tag, buffer) { + this.writeTag(tag, Pbf.Bytes); + this.writeBytes(buffer); + }, + writeFixed32Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeFixed32(val); + }, + writeSFixed32Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeSFixed32(val); + }, + writeFixed64Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeFixed64(val); + }, + writeSFixed64Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeSFixed64(val); + }, + writeVarintField: function(tag, val) { + this.writeTag(tag, Pbf.Varint); + this.writeVarint(val); + }, + writeSVarintField: function(tag, val) { + this.writeTag(tag, Pbf.Varint); + this.writeSVarint(val); + }, + writeStringField: function(tag, str) { + this.writeTag(tag, Pbf.Bytes); + this.writeString(str); + }, + writeFloatField: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeFloat(val); + }, + writeDoubleField: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeDouble(val); + }, + writeBooleanField: function(tag, val) { + this.writeVarintField(tag, Boolean(val)); + } +}; + +function readVarintRemainder(l, s, p) { + var buf = p.buf, + h, b; + + b = buf[p.pos++]; h = (b & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s); + + throw new Error('Expected varint not more than 10 bytes'); +} + +function readPackedEnd(pbf) { + return pbf.type === Pbf.Bytes ? + pbf.readVarint() + pbf.pos : pbf.pos + 1; +} + +function toNum(low, high, isSigned) { + if (isSigned) { + return high * 0x100000000 + (low >>> 0); + } + + return ((high >>> 0) * 0x100000000) + (low >>> 0); +} + +function writeBigVarint(val, pbf) { + var low, high; + + if (val >= 0) { + low = (val % 0x100000000) | 0; + high = (val / 0x100000000) | 0; + } else { + low = ~(-val % 0x100000000); + high = ~(-val / 0x100000000); + + if (low ^ 0xffffffff) { + low = (low + 1) | 0; + } else { + low = 0; + high = (high + 1) | 0; + } + } + + if (val >= 0x10000000000000000 || val < -0x10000000000000000) { + throw new Error('Given varint doesn\'t fit into 10 bytes'); + } + + pbf.realloc(10); + + writeBigVarintLow(low, high, pbf); + writeBigVarintHigh(high, pbf); +} + +function writeBigVarintLow(low, high, pbf) { + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos] = low & 0x7f; +} + +function writeBigVarintHigh(high, pbf) { + var lsb = (high & 0x07) << 4; + + pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f; +} + +function makeRoomForExtraLength(startPos, len, pbf) { + var extraLen = + len <= 0x3fff ? 1 : + len <= 0x1fffff ? 2 : + len <= 0xfffffff ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7)); + + // if 1 byte isn't enough for encoding message length, shift the data to the right + pbf.realloc(extraLen); + for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i]; +} + +function writePackedVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]); } +function writePackedSVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); } +function writePackedFloat(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); } +function writePackedDouble(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); } +function writePackedBoolean(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); } +function writePackedFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); } +function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); } +function writePackedFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); } +function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); } + +// Buffer code below from https://github.com/feross/buffer, MIT-licensed + +function readUInt32(buf, pos) { + return ((buf[pos]) | + (buf[pos + 1] << 8) | + (buf[pos + 2] << 16)) + + (buf[pos + 3] * 0x1000000); +} + +function writeInt32(buf, val, pos) { + buf[pos] = val; + buf[pos + 1] = (val >>> 8); + buf[pos + 2] = (val >>> 16); + buf[pos + 3] = (val >>> 24); +} + +function readInt32(buf, pos) { + return ((buf[pos]) | + (buf[pos + 1] << 8) | + (buf[pos + 2] << 16)) + + (buf[pos + 3] << 24); +} + +function readUtf8(buf, pos, end) { + var str = ''; + var i = pos; + + while (i < end) { + var b0 = buf[i]; + var c = null; // codepoint + var bytesPerSequence = + b0 > 0xEF ? 4 : + b0 > 0xDF ? 3 : + b0 > 0xBF ? 2 : 1; + + if (i + bytesPerSequence > end) break; + + var b1, b2, b3; + + if (bytesPerSequence === 1) { + if (b0 < 0x80) { + c = b0; + } + } else if (bytesPerSequence === 2) { + b1 = buf[i + 1]; + if ((b1 & 0xC0) === 0x80) { + c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F); + if (c <= 0x7F) { + c = null; + } + } + } else if (bytesPerSequence === 3) { + b1 = buf[i + 1]; + b2 = buf[i + 2]; + if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) { + c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F); + if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) { + c = null; + } + } + } else if (bytesPerSequence === 4) { + b1 = buf[i + 1]; + b2 = buf[i + 2]; + b3 = buf[i + 3]; + if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) { + c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F); + if (c <= 0xFFFF || c >= 0x110000) { + c = null; + } + } + } + + if (c === null) { + c = 0xFFFD; + bytesPerSequence = 1; + + } else if (c > 0xFFFF) { + c -= 0x10000; + str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800); + c = 0xDC00 | c & 0x3FF; + } + + str += String.fromCharCode(c); + i += bytesPerSequence; + } + + return str; +} + +function readUtf8TextDecoder(buf, pos, end) { + return utf8TextDecoder.decode(buf.subarray(pos, end)); +} + +function writeUtf8(buf, str, pos) { + for (var i = 0, c, lead; i < str.length; i++) { + c = str.charCodeAt(i); // code point + + if (c > 0xD7FF && c < 0xE000) { + if (lead) { + if (c < 0xDC00) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + lead = c; + continue; + } else { + c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000; + lead = null; + } + } else { + if (c > 0xDBFF || (i + 1 === str.length)) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + } else { + lead = c; + } + continue; + } + } else if (lead) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + lead = null; + } + + if (c < 0x80) { + buf[pos++] = c; + } else { + if (c < 0x800) { + buf[pos++] = c >> 0x6 | 0xC0; + } else { + if (c < 0x10000) { + buf[pos++] = c >> 0xC | 0xE0; + } else { + buf[pos++] = c >> 0x12 | 0xF0; + buf[pos++] = c >> 0xC & 0x3F | 0x80; + } + buf[pos++] = c >> 0x6 & 0x3F | 0x80; + } + buf[pos++] = c & 0x3F | 0x80; + } + } + return pos; +} + +var Protobuf = /*@__PURE__*/getDefaultExportFromCjs$1(pbf); + +const border$1 = 3; +function readFontstacks(tag, glyphs, pbf) { + if (tag === 1) { + pbf.readMessage(readFontstack, glyphs); + } +} +function readFontstack(tag, glyphs, pbf) { + if (tag === 3) { + const { id, bitmap, width, height, left, top, advance } = pbf.readMessage(readGlyph, {}); + glyphs.push({ + id, + bitmap: new AlphaImage({ + width: width + 2 * border$1, + height: height + 2 * border$1 + }, bitmap), + metrics: { width, height, left, top, advance } + }); + } +} +function readGlyph(tag, glyph, pbf) { + if (tag === 1) + glyph.id = pbf.readVarint(); + else if (tag === 2) + glyph.bitmap = pbf.readBytes(); + else if (tag === 3) + glyph.width = pbf.readVarint(); + else if (tag === 4) + glyph.height = pbf.readVarint(); + else if (tag === 5) + glyph.left = pbf.readSVarint(); + else if (tag === 6) + glyph.top = pbf.readSVarint(); + else if (tag === 7) + glyph.advance = pbf.readVarint(); +} +function parseGlyphPbf(data) { + return new Protobuf(data).readFields(readFontstacks, []); +} +const GLYPH_PBF_BORDER = border$1; + +function potpack(boxes) { + + // calculate total box area and maximum box width + let area = 0; + let maxWidth = 0; + + for (const box of boxes) { + area += box.w * box.h; + maxWidth = Math.max(maxWidth, box.w); + } + + // sort the boxes for insertion by height, descending + boxes.sort((a, b) => b.h - a.h); + + // aim for a squarish resulting container, + // slightly adjusted for sub-100% space utilization + const startWidth = Math.max(Math.ceil(Math.sqrt(area / 0.95)), maxWidth); + + // start with a single empty space, unbounded at the bottom + const spaces = [{x: 0, y: 0, w: startWidth, h: Infinity}]; + + let width = 0; + let height = 0; + + for (const box of boxes) { + // look through spaces backwards so that we check smaller spaces first + for (let i = spaces.length - 1; i >= 0; i--) { + const space = spaces[i]; + + // look for empty spaces that can accommodate the current box + if (box.w > space.w || box.h > space.h) continue; + + // found the space; add the box to its top-left corner + // |-------|-------| + // | box | | + // |_______| | + // | space | + // |_______________| + box.x = space.x; + box.y = space.y; + + height = Math.max(height, box.y + box.h); + width = Math.max(width, box.x + box.w); + + if (box.w === space.w && box.h === space.h) { + // space matches the box exactly; remove it + const last = spaces.pop(); + if (i < spaces.length) spaces[i] = last; + + } else if (box.h === space.h) { + // space matches the box height; update it accordingly + // |-------|---------------| + // | box | updated space | + // |_______|_______________| + space.x += box.w; + space.w -= box.w; + + } else if (box.w === space.w) { + // space matches the box width; update it accordingly + // |---------------| + // | box | + // |_______________| + // | updated space | + // |_______________| + space.y += box.h; + space.h -= box.h; + + } else { + // otherwise the box splits the space into two spaces + // |-------|-----------| + // | box | new space | + // |_______|___________| + // | updated space | + // |___________________| + spaces.push({ + x: space.x + box.w, + y: space.y, + w: space.w - box.w, + h: box.h + }); + space.y += box.h; + space.h -= box.h; + } + break; + } + } + + return { + w: width, // container width + h: height, // container height + fill: (area / (width * height)) || 0 // space utilization + }; +} + +/* eslint-disable key-spacing */ +const IMAGE_PADDING = 1; +class ImagePosition { + constructor(paddedRect, { pixelRatio, version, stretchX, stretchY, content, textFitWidth, textFitHeight }) { + this.paddedRect = paddedRect; + this.pixelRatio = pixelRatio; + this.stretchX = stretchX; + this.stretchY = stretchY; + this.content = content; + this.version = version; + this.textFitWidth = textFitWidth; + this.textFitHeight = textFitHeight; + } + get tl() { + return [ + this.paddedRect.x + IMAGE_PADDING, + this.paddedRect.y + IMAGE_PADDING + ]; + } + get br() { + return [ + this.paddedRect.x + this.paddedRect.w - IMAGE_PADDING, + this.paddedRect.y + this.paddedRect.h - IMAGE_PADDING + ]; + } + get tlbr() { + return this.tl.concat(this.br); + } + get displaySize() { + return [ + (this.paddedRect.w - IMAGE_PADDING * 2) / this.pixelRatio, + (this.paddedRect.h - IMAGE_PADDING * 2) / this.pixelRatio + ]; + } +} +/** + * A class holding all the images + */ +class ImageAtlas { + constructor(icons, patterns) { + const iconPositions = {}, patternPositions = {}; + this.haveRenderCallbacks = []; + const bins = []; + this.addImages(icons, iconPositions, bins); + this.addImages(patterns, patternPositions, bins); + const { w, h } = potpack(bins); + const image = new RGBAImage({ width: w || 1, height: h || 1 }); + for (const id in icons) { + const src = icons[id]; + const bin = iconPositions[id].paddedRect; + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x: bin.x + IMAGE_PADDING, y: bin.y + IMAGE_PADDING }, src.data); + } + for (const id in patterns) { + const src = patterns[id]; + const bin = patternPositions[id].paddedRect; + const x = bin.x + IMAGE_PADDING, y = bin.y + IMAGE_PADDING, w = src.data.width, h = src.data.height; + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x, y }, src.data); + // Add 1 pixel wrapped padding on each side of the image. + RGBAImage.copy(src.data, image, { x: 0, y: h - 1 }, { x, y: y - 1 }, { width: w, height: 1 }); // T + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x, y: y + h }, { width: w, height: 1 }); // B + RGBAImage.copy(src.data, image, { x: w - 1, y: 0 }, { x: x - 1, y }, { width: 1, height: h }); // L + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x: x + w, y }, { width: 1, height: h }); // R + } + this.image = image; + this.iconPositions = iconPositions; + this.patternPositions = patternPositions; + } + addImages(images, positions, bins) { + for (const id in images) { + const src = images[id]; + const bin = { + x: 0, + y: 0, + w: src.data.width + 2 * IMAGE_PADDING, + h: src.data.height + 2 * IMAGE_PADDING, + }; + bins.push(bin); + positions[id] = new ImagePosition(bin, src); + if (src.hasRenderCallback) { + this.haveRenderCallbacks.push(id); + } + } + } + patchUpdatedImages(imageManager, texture) { + imageManager.dispatchRenderCallbacks(this.haveRenderCallbacks); + for (const name in imageManager.updatedImages) { + this.patchUpdatedImage(this.iconPositions[name], imageManager.getImage(name), texture); + this.patchUpdatedImage(this.patternPositions[name], imageManager.getImage(name), texture); + } + } + patchUpdatedImage(position, image, texture) { + if (!position || !image) + return; + if (position.version === image.version) + return; + position.version = image.version; + const [x, y] = position.tl; + texture.update(image.data, undefined, { x, y }); + } +} +register('ImagePosition', ImagePosition); +register('ImageAtlas', ImageAtlas); + +var WritingMode; +(function (WritingMode) { + WritingMode[WritingMode["none"] = 0] = "none"; + WritingMode[WritingMode["horizontal"] = 1] = "horizontal"; + WritingMode[WritingMode["vertical"] = 2] = "vertical"; + WritingMode[WritingMode["horizontalOnly"] = 3] = "horizontalOnly"; +})(WritingMode || (WritingMode = {})); +const SHAPING_DEFAULT_OFFSET = -17; +function isEmpty(positionedLines) { + for (const line of positionedLines) { + if (line.positionedGlyphs.length !== 0) { + return false; + } + } + return true; +} +// Max number of images in label is 6401 U+E000–U+F8FF that covers +// Basic Multilingual Plane Unicode Private Use Area (PUA). +const PUAbegin = 0xE000; +const PUAend = 0xF8FF; +class SectionOptions { + constructor() { + this.scale = 1.0; + this.fontStack = ''; + this.imageName = null; + } + static forText(scale, fontStack) { + const textOptions = new SectionOptions(); + textOptions.scale = scale || 1; + textOptions.fontStack = fontStack; + return textOptions; + } + static forImage(imageName) { + const imageOptions = new SectionOptions(); + imageOptions.imageName = imageName; + return imageOptions; + } +} +class TaggedString { + constructor() { + this.text = ''; + this.sectionIndex = []; + this.sections = []; + this.imageSectionID = null; + } + static fromFeature(text, defaultFontStack) { + const result = new TaggedString(); + for (let i = 0; i < text.sections.length; i++) { + const section = text.sections[i]; + if (!section.image) { + result.addTextSection(section, defaultFontStack); + } + else { + result.addImageSection(section); + } + } + return result; + } + length() { + return this.text.length; + } + getSection(index) { + return this.sections[this.sectionIndex[index]]; + } + getSectionIndex(index) { + return this.sectionIndex[index]; + } + getCharCode(index) { + return this.text.charCodeAt(index); + } + verticalizePunctuation() { + this.text = verticalizePunctuation(this.text); + } + trim() { + let beginningWhitespace = 0; + for (let i = 0; i < this.text.length && whitespace[this.text.charCodeAt(i)]; i++) { + beginningWhitespace++; + } + let trailingWhitespace = this.text.length; + for (let i = this.text.length - 1; i >= 0 && i >= beginningWhitespace && whitespace[this.text.charCodeAt(i)]; i--) { + trailingWhitespace--; + } + this.text = this.text.substring(beginningWhitespace, trailingWhitespace); + this.sectionIndex = this.sectionIndex.slice(beginningWhitespace, trailingWhitespace); + } + substring(start, end) { + const substring = new TaggedString(); + substring.text = this.text.substring(start, end); + substring.sectionIndex = this.sectionIndex.slice(start, end); + substring.sections = this.sections; + return substring; + } + toString() { + return this.text; + } + getMaxScale() { + return this.sectionIndex.reduce((max, index) => Math.max(max, this.sections[index].scale), 0); + } + addTextSection(section, defaultFontStack) { + this.text += section.text; + this.sections.push(SectionOptions.forText(section.scale, section.fontStack || defaultFontStack)); + const index = this.sections.length - 1; + for (let i = 0; i < section.text.length; ++i) { + this.sectionIndex.push(index); + } + } + addImageSection(section) { + const imageName = section.image ? section.image.name : ''; + if (imageName.length === 0) { + warnOnce('Can\'t add FormattedSection with an empty image.'); + return; + } + const nextImageSectionCharCode = this.getNextImageSectionCharCode(); + if (!nextImageSectionCharCode) { + warnOnce(`Reached maximum number of images ${PUAend - PUAbegin + 2}`); + return; + } + this.text += String.fromCharCode(nextImageSectionCharCode); + this.sections.push(SectionOptions.forImage(imageName)); + this.sectionIndex.push(this.sections.length - 1); + } + getNextImageSectionCharCode() { + if (!this.imageSectionID) { + this.imageSectionID = PUAbegin; + return this.imageSectionID; + } + if (this.imageSectionID >= PUAend) + return null; + return ++this.imageSectionID; + } +} +function breakLines(input, lineBreakPoints) { + const lines = []; + const text = input.text; + let start = 0; + for (const lineBreak of lineBreakPoints) { + lines.push(input.substring(start, lineBreak)); + start = lineBreak; + } + if (start < text.length) { + lines.push(input.substring(start, text.length)); + } + return lines; +} +function shapeText(text, glyphMap, glyphPositions, imagePositions, defaultFontStack, maxWidth, lineHeight, textAnchor, textJustify, spacing, translate, writingMode, allowVerticalPlacement, layoutTextSize, layoutTextSizeThisZoom) { + const logicalInput = TaggedString.fromFeature(text, defaultFontStack); + if (writingMode === WritingMode.vertical) { + logicalInput.verticalizePunctuation(); + } + let lines; + const { processBidirectionalText, processStyledBidirectionalText } = rtlWorkerPlugin; + if (processBidirectionalText && logicalInput.sections.length === 1) { + // Bidi doesn't have to be style-aware + lines = []; + const untaggedLines = processBidirectionalText(logicalInput.toString(), determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + for (const line of untaggedLines) { + const taggedLine = new TaggedString(); + taggedLine.text = line; + taggedLine.sections = logicalInput.sections; + for (let i = 0; i < line.length; i++) { + taggedLine.sectionIndex.push(0); + } + lines.push(taggedLine); + } + } + else if (processStyledBidirectionalText) { + // Need version of mapbox-gl-rtl-text with style support for combining RTL text + // with formatting + lines = []; + const processedLines = processStyledBidirectionalText(logicalInput.text, logicalInput.sectionIndex, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + for (const line of processedLines) { + const taggedLine = new TaggedString(); + taggedLine.text = line[0]; + taggedLine.sectionIndex = line[1]; + taggedLine.sections = logicalInput.sections; + lines.push(taggedLine); + } + } + else { + lines = breakLines(logicalInput, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + } + const positionedLines = []; + const shaping = { + positionedLines, + text: logicalInput.toString(), + top: translate[1], + bottom: translate[1], + left: translate[0], + right: translate[0], + writingMode, + iconsInText: false, + verticalizable: false + }; + shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom); + if (isEmpty(positionedLines)) + return false; + return shaping; +} +// using computed properties due to https://github.com/facebook/flow/issues/380 +/* eslint no-useless-computed-key: 0 */ +const whitespace = { + [0x09]: true, // tab + [0x0a]: true, // newline + [0x0b]: true, // vertical tab + [0x0c]: true, // form feed + [0x0d]: true, // carriage return + [0x20]: true, // space +}; +const breakable = { + [0x0a]: true, // newline + [0x20]: true, // space + [0x26]: true, // ampersand + [0x29]: true, // right parenthesis + [0x2b]: true, // plus sign + [0x2d]: true, // hyphen-minus + [0x2f]: true, // solidus + [0xad]: true, // soft hyphen + [0xb7]: true, // middle dot + [0x200b]: true, // zero-width space + [0x2010]: true, // hyphen + [0x2013]: true, // en dash + [0x2027]: true // interpunct + // Many other characters may be reasonable breakpoints + // Consider "neutral orientation" characters at scriptDetection.charHasNeutralVerticalOrientation + // See https://github.com/mapbox/mapbox-gl-js/issues/3658 +}; +// Allow breaks depending on the following character +const breakableBefore = { + [0x28]: true, // left parenthesis +}; +function getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize) { + if (!section.imageName) { + const positions = glyphMap[section.fontStack]; + const glyph = positions && positions[codePoint]; + if (!glyph) + return 0; + return glyph.metrics.advance * section.scale + spacing; + } + else { + const imagePosition = imagePositions[section.imageName]; + if (!imagePosition) + return 0; + return imagePosition.displaySize[0] * section.scale * ONE_EM / layoutTextSize + spacing; + } +} +function determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) { + let totalWidth = 0; + for (let index = 0; index < logicalInput.length(); index++) { + const section = logicalInput.getSection(index); + totalWidth += getGlyphAdvance(logicalInput.getCharCode(index), section, glyphMap, imagePositions, spacing, layoutTextSize); + } + const lineCount = Math.max(1, Math.ceil(totalWidth / maxWidth)); + return totalWidth / lineCount; +} +function calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) { + const raggedness = Math.pow(lineWidth - targetWidth, 2); + if (isLastBreak) { + // Favor finals lines shorter than average over longer than average + if (lineWidth < targetWidth) { + return raggedness / 2; + } + else { + return raggedness * 2; + } + } + return raggedness + Math.abs(penalty) * penalty; +} +function calculatePenalty(codePoint, nextCodePoint, penalizableIdeographicBreak) { + let penalty = 0; + // Force break on newline + if (codePoint === 0x0a) { + penalty -= 10000; + } + // Penalize breaks between characters that allow ideographic breaking because + // they are less preferable than breaks at spaces (or zero width spaces). + if (penalizableIdeographicBreak) { + penalty += 150; + } + // Penalize open parenthesis at end of line + if (codePoint === 0x28 || codePoint === 0xff08) { + penalty += 50; + } + // Penalize close parenthesis at beginning of line + if (nextCodePoint === 0x29 || nextCodePoint === 0xff09) { + penalty += 50; + } + return penalty; +} +function evaluateBreak(breakIndex, breakX, targetWidth, potentialBreaks, penalty, isLastBreak) { + // We could skip evaluating breaks where the line length (breakX - priorBreak.x) > maxWidth + // ...but in fact we allow lines longer than maxWidth (if there's no break points) + // ...and when targetWidth and maxWidth are close, strictly enforcing maxWidth can give + // more lopsided results. + let bestPriorBreak = null; + let bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak); + for (const potentialBreak of potentialBreaks) { + const lineWidth = breakX - potentialBreak.x; + const breakBadness = calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness; + if (breakBadness <= bestBreakBadness) { + bestPriorBreak = potentialBreak; + bestBreakBadness = breakBadness; + } + } + return { + index: breakIndex, + x: breakX, + priorBreak: bestPriorBreak, + badness: bestBreakBadness + }; +} +function leastBadBreaks(lastLineBreak) { + if (!lastLineBreak) { + return []; + } + return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index); +} +function determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) { + if (!logicalInput) + return []; + const potentialLineBreaks = []; + const targetWidth = determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize); + const hasServerSuggestedBreakpoints = logicalInput.text.indexOf('\u200b') >= 0; + let currentX = 0; + for (let i = 0; i < logicalInput.length(); i++) { + const section = logicalInput.getSection(i); + const codePoint = logicalInput.getCharCode(i); + if (!whitespace[codePoint]) + currentX += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize); + // Ideographic characters, spaces, and word-breaking punctuation that often appear without + // surrounding spaces. + if ((i < logicalInput.length() - 1)) { + const ideographicBreak = charAllowsIdeographicBreaking(codePoint); + if (breakable[codePoint] || ideographicBreak || section.imageName || (i !== logicalInput.length() - 2 && breakableBefore[logicalInput.getCharCode(i + 1)])) { + potentialLineBreaks.push(evaluateBreak(i + 1, currentX, targetWidth, potentialLineBreaks, calculatePenalty(codePoint, logicalInput.getCharCode(i + 1), ideographicBreak && hasServerSuggestedBreakpoints), false)); + } + } + } + return leastBadBreaks(evaluateBreak(logicalInput.length(), currentX, targetWidth, potentialLineBreaks, 0, true)); +} +function getAnchorAlignment(anchor) { + let horizontalAlign = 0.5, verticalAlign = 0.5; + switch (anchor) { + case 'right': + case 'top-right': + case 'bottom-right': + horizontalAlign = 1; + break; + case 'left': + case 'top-left': + case 'bottom-left': + horizontalAlign = 0; + break; + } + switch (anchor) { + case 'bottom': + case 'bottom-right': + case 'bottom-left': + verticalAlign = 1; + break; + case 'top': + case 'top-right': + case 'top-left': + verticalAlign = 0; + break; + } + return { horizontalAlign, verticalAlign }; +} +function shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom) { + let x = 0; + let y = SHAPING_DEFAULT_OFFSET; + let maxLineLength = 0; + let maxLineHeight = 0; + const justify = textJustify === 'right' ? 1 : + textJustify === 'left' ? 0 : 0.5; + let lineIndex = 0; + for (const line of lines) { + line.trim(); + const lineMaxScale = line.getMaxScale(); + const maxLineOffset = (lineMaxScale - 1) * ONE_EM; + const positionedLine = { positionedGlyphs: [], lineOffset: 0 }; + shaping.positionedLines[lineIndex] = positionedLine; + const positionedGlyphs = positionedLine.positionedGlyphs; + let lineOffset = 0.0; + if (!line.length()) { + y += lineHeight; // Still need a line feed after empty line + ++lineIndex; + continue; + } + for (let i = 0; i < line.length(); i++) { + const section = line.getSection(i); + const sectionIndex = line.getSectionIndex(i); + const codePoint = line.getCharCode(i); + let baselineOffset = 0.0; + let metrics = null; + let rect = null; + let imageName = null; + let verticalAdvance = ONE_EM; + const vertical = !(writingMode === WritingMode.horizontal || + // Don't verticalize glyphs that have no upright orientation if vertical placement is disabled. + (!allowVerticalPlacement && !charHasUprightVerticalOrientation(codePoint)) || + // If vertical placement is enabled, don't verticalize glyphs that + // are from complex text layout script, or whitespaces. + (allowVerticalPlacement && (whitespace[codePoint] || charInComplexShapingScript(codePoint)))); + if (!section.imageName) { + const positions = glyphPositions[section.fontStack]; + const glyphPosition = positions && positions[codePoint]; + if (glyphPosition && glyphPosition.rect) { + rect = glyphPosition.rect; + metrics = glyphPosition.metrics; + } + else { + const glyphs = glyphMap[section.fontStack]; + const glyph = glyphs && glyphs[codePoint]; + if (!glyph) + continue; + metrics = glyph.metrics; + } + // We don't know the baseline, but since we're laying out + // at 24 points, we can calculate how much it will move when + // we scale up or down. + baselineOffset = (lineMaxScale - section.scale) * ONE_EM; + } + else { + const imagePosition = imagePositions[section.imageName]; + if (!imagePosition) + continue; + imageName = section.imageName; + shaping.iconsInText = shaping.iconsInText || true; + rect = imagePosition.paddedRect; + const size = imagePosition.displaySize; + // If needed, allow to set scale factor for an image using + // alias "image-scale" that could be alias for "font-scale" + // when FormattedSection is an image section. + section.scale = section.scale * ONE_EM / layoutTextSizeThisZoom; + metrics = { width: size[0], + height: size[1], + left: IMAGE_PADDING, + top: -GLYPH_PBF_BORDER, + advance: vertical ? size[1] : size[0] }; + // Difference between one EM and an image size. + // Aligns bottom of an image to a baseline level. + const imageOffset = ONE_EM - size[1] * section.scale; + baselineOffset = maxLineOffset + imageOffset; + verticalAdvance = metrics.advance; + // Difference between height of an image and one EM at max line scale. + // Pushes current line down if an image size is over 1 EM at max line scale. + const offset = vertical ? size[0] * section.scale - ONE_EM * lineMaxScale : + size[1] * section.scale - ONE_EM * lineMaxScale; + if (offset > 0 && offset > lineOffset) { + lineOffset = offset; + } + } + if (!vertical) { + positionedGlyphs.push({ glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect }); + x += metrics.advance * section.scale + spacing; + } + else { + shaping.verticalizable = true; + positionedGlyphs.push({ glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect }); + x += verticalAdvance * section.scale + spacing; + } + } + // Only justify if we placed at least one glyph + if (positionedGlyphs.length !== 0) { + const lineLength = x - spacing; + maxLineLength = Math.max(lineLength, maxLineLength); + justifyLine(positionedGlyphs, 0, positionedGlyphs.length - 1, justify, lineOffset); + } + x = 0; + const currentLineHeight = lineHeight * lineMaxScale + lineOffset; + positionedLine.lineOffset = Math.max(lineOffset, maxLineOffset); + y += currentLineHeight; + maxLineHeight = Math.max(currentLineHeight, maxLineHeight); + ++lineIndex; + } + // Calculate the bounding box and justify / align text block. + const height = y - SHAPING_DEFAULT_OFFSET; + const { horizontalAlign, verticalAlign } = getAnchorAlignment(textAnchor); + align(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, height, lines.length); + shaping.top += -verticalAlign * height; + shaping.bottom = shaping.top + height; + shaping.left += -horizontalAlign * maxLineLength; + shaping.right = shaping.left + maxLineLength; +} +// justify right = 1, left = 0, center = 0.5 +function justifyLine(positionedGlyphs, start, end, justify, lineOffset) { + if (!justify && !lineOffset) + return; + const lastPositionedGlyph = positionedGlyphs[end]; + const lastAdvance = lastPositionedGlyph.metrics.advance * lastPositionedGlyph.scale; + const lineIndent = (positionedGlyphs[end].x + lastAdvance) * justify; + for (let j = start; j <= end; j++) { + positionedGlyphs[j].x -= lineIndent; + positionedGlyphs[j].y += lineOffset; + } +} +function align(positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, blockHeight, lineCount) { + const shiftX = (justify - horizontalAlign) * maxLineLength; + let shiftY = 0; + if (maxLineHeight !== lineHeight) { + shiftY = -blockHeight * verticalAlign - SHAPING_DEFAULT_OFFSET; + } + else { + shiftY = (-verticalAlign * lineCount + 0.5) * lineHeight; + } + for (const line of positionedLines) { + for (const positionedGlyph of line.positionedGlyphs) { + positionedGlyph.x += shiftX; + positionedGlyph.y += shiftY; + } + } +} +function shapeIcon(image, iconOffset, iconAnchor) { + const { horizontalAlign, verticalAlign } = getAnchorAlignment(iconAnchor); + const dx = iconOffset[0]; + const dy = iconOffset[1]; + const x1 = dx - image.displaySize[0] * horizontalAlign; + const x2 = x1 + image.displaySize[0]; + const y1 = dy - image.displaySize[1] * verticalAlign; + const y2 = y1 + image.displaySize[1]; + return { image, top: y1, bottom: y2, left: x1, right: x2 }; +} +/** + * Called after a PositionedIcon has already been run through fitIconToText, + * but needs further adjustment to apply textFitWidth and textFitHeight. + * @param shapedIcon - The icon that will be adjusted. + * @returns Extents of the shapedIcon with text fit adjustments if necessary. + */ +function applyTextFit(shapedIcon) { + var _a, _b; + // Assume shapedIcon.image is set or this wouldn't be called. + // Size of the icon after it was adjusted using stretchX and Y + let iconLeft = shapedIcon.left; + let iconTop = shapedIcon.top; + let iconWidth = shapedIcon.right - iconLeft; + let iconHeight = shapedIcon.bottom - iconTop; + // Size of the original content area + const contentWidth = shapedIcon.image.content[2] - shapedIcon.image.content[0]; + const contentHeight = shapedIcon.image.content[3] - shapedIcon.image.content[1]; + const textFitWidth = (_a = shapedIcon.image.textFitWidth) !== null && _a !== void 0 ? _a : "stretchOrShrink" /* TextFit.stretchOrShrink */; + const textFitHeight = (_b = shapedIcon.image.textFitHeight) !== null && _b !== void 0 ? _b : "stretchOrShrink" /* TextFit.stretchOrShrink */; + const contentAspectRatio = contentWidth / contentHeight; + // Scale to the proportional axis first note that height takes precedence if + // both axes are set to proportional. + if (textFitHeight === "proportional" /* TextFit.proportional */) { + if ((textFitWidth === "stretchOnly" /* TextFit.stretchOnly */ && iconWidth / iconHeight < contentAspectRatio) || textFitWidth === "proportional" /* TextFit.proportional */) { + // Push the width of the icon back out to match the content aspect ratio + const newIconWidth = Math.ceil(iconHeight * contentAspectRatio); + iconLeft *= newIconWidth / iconWidth; + iconWidth = newIconWidth; + } + } + else if (textFitWidth === "proportional" /* TextFit.proportional */) { + if (textFitHeight === "stretchOnly" /* TextFit.stretchOnly */ && contentAspectRatio !== 0 && iconWidth / iconHeight > contentAspectRatio) { + // Push the height of the icon back out to match the content aspect ratio + const newIconHeight = Math.ceil(iconWidth / contentAspectRatio); + iconTop *= newIconHeight / iconHeight; + iconHeight = newIconHeight; + } + } + else { + // If neither textFitHeight nor textFitWidth are proportional then + // there is no effect since the content rectangle should be precisely + // matched to the content + } + return { x1: iconLeft, y1: iconTop, x2: iconLeft + iconWidth, y2: iconTop + iconHeight }; +} +function fitIconToText(shapedIcon, shapedText, textFit, padding, iconOffset, fontScale) { + const image = shapedIcon.image; + let collisionPadding; + if (image.content) { + const content = image.content; + const pixelRatio = image.pixelRatio || 1; + collisionPadding = [ + content[0] / pixelRatio, + content[1] / pixelRatio, + image.displaySize[0] - content[2] / pixelRatio, + image.displaySize[1] - content[3] / pixelRatio + ]; + } + // We don't respect the icon-anchor, because icon-text-fit is set. Instead, + // the icon will be centered on the text, then stretched in the given + // dimensions. + const textLeft = shapedText.left * fontScale; + const textRight = shapedText.right * fontScale; + let top, right, bottom, left; + if (textFit === 'width' || textFit === 'both') { + // Stretched horizontally to the text width + left = iconOffset[0] + textLeft - padding[3]; + right = iconOffset[0] + textRight + padding[1]; + } + else { + // Centered on the text + left = iconOffset[0] + (textLeft + textRight - image.displaySize[0]) / 2; + right = left + image.displaySize[0]; + } + const textTop = shapedText.top * fontScale; + const textBottom = shapedText.bottom * fontScale; + if (textFit === 'height' || textFit === 'both') { + // Stretched vertically to the text height + top = iconOffset[1] + textTop - padding[0]; + bottom = iconOffset[1] + textBottom + padding[2]; + } + else { + // Centered on the text + top = iconOffset[1] + (textTop + textBottom - image.displaySize[1]) / 2; + bottom = top + image.displaySize[1]; + } + return { image, top, right, bottom, left, collisionPadding }; +} + +const MAX_GLYPH_ICON_SIZE = 255; +const SIZE_PACK_FACTOR = 128; +const MAX_PACKED_SIZE = MAX_GLYPH_ICON_SIZE * SIZE_PACK_FACTOR; +// For {text,icon}-size, get the bucket-level data that will be needed by +// the painter to set symbol-size-related uniforms +function getSizeData(tileZoom, value) { + const { expression } = value; + if (expression.kind === 'constant') { + const layoutSize = expression.evaluate(new EvaluationParameters(tileZoom + 1)); + return { kind: 'constant', layoutSize }; + } + else if (expression.kind === 'source') { + return { kind: 'source' }; + } + else { + const { zoomStops, interpolationType } = expression; + // calculate covering zoom stops for zoom-dependent values + let lower = 0; + while (lower < zoomStops.length && zoomStops[lower] <= tileZoom) + lower++; + lower = Math.max(0, lower - 1); + let upper = lower; + while (upper < zoomStops.length && zoomStops[upper] < tileZoom + 1) + upper++; + upper = Math.min(zoomStops.length - 1, upper); + const minZoom = zoomStops[lower]; + const maxZoom = zoomStops[upper]; + // We'd like to be able to use CameraExpression or CompositeExpression in these + // return types rather than ExpressionSpecification, but the former are not + // transferrable across Web Worker boundaries. + if (expression.kind === 'composite') { + return { kind: 'composite', minZoom, maxZoom, interpolationType }; + } + // for camera functions, also save off the function values + // evaluated at the covering zoom levels + const minSize = expression.evaluate(new EvaluationParameters(minZoom)); + const maxSize = expression.evaluate(new EvaluationParameters(maxZoom)); + return { kind: 'camera', minZoom, maxZoom, minSize, maxSize, interpolationType }; + } +} +function evaluateSizeForFeature(sizeData, { uSize, uSizeT }, { lowerSize, upperSize }) { + if (sizeData.kind === 'source') { + return lowerSize / SIZE_PACK_FACTOR; + } + else if (sizeData.kind === 'composite') { + return interpolate.number(lowerSize / SIZE_PACK_FACTOR, upperSize / SIZE_PACK_FACTOR, uSizeT); + } + return uSize; +} +function evaluateSizeForZoom(sizeData, zoom) { + let uSizeT = 0; + let uSize = 0; + if (sizeData.kind === 'constant') { + uSize = sizeData.layoutSize; + } + else if (sizeData.kind !== 'source') { + const { interpolationType, minZoom, maxZoom } = sizeData; + // Even though we could get the exact value of the camera function + // at z = tr.zoom, we intentionally do not: instead, we interpolate + // between the camera function values at a pair of zoom stops covering + // [tileZoom, tileZoom + 1] in order to be consistent with this + // restriction on composite functions + const t = !interpolationType ? 0 : clamp$1(Interpolate.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1); + if (sizeData.kind === 'camera') { + uSize = interpolate.number(sizeData.minSize, sizeData.maxSize, t); + } + else { + uSizeT = t; + } + } + return { uSizeT, uSize }; +} + +function getOverlapMode(layout, overlapProp, allowOverlapProp) { + let result = 'never'; + const overlap = layout.get(overlapProp); + if (overlap) { + // if -overlap is set, use it + result = overlap; + } + else if (layout.get(allowOverlapProp)) { + // fall back to -allow-overlap, with false='never', true='always' + result = 'always'; + } + return result; +} + +const vectorTileFeatureTypes = vectorTile.VectorTileFeature.types; +// Opacity arrays are frequently updated but don't contain a lot of information, so we pack them +// tight. Each Uint32 is actually four duplicate Uint8s for the four corners of a glyph +// 7 bits are for the current opacity, and the lowest bit is the target opacity +// actually defined in symbol_attributes.js +// const placementOpacityAttributes = [ +// { name: 'a_fade_opacity', components: 1, type: 'Uint32' } +// ]; +const shaderOpacityAttributes = [ + { name: 'a_fade_opacity', components: 1, type: 'Uint8', offset: 0 } +]; +function addVertex(array, anchorX, anchorY, ox, oy, tx, ty, sizeVertex, isSDF, pixelOffsetX, pixelOffsetY, minFontScaleX, minFontScaleY) { + const aSizeX = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[0])) : 0; + const aSizeY = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[1])) : 0; + array.emplaceBack( + // a_pos_offset + anchorX, anchorY, Math.round(ox * 32), Math.round(oy * 32), + // a_data + tx, // x coordinate of symbol on glyph atlas texture + ty, // y coordinate of symbol on glyph atlas texture + (aSizeX << 1) + (isSDF ? 1 : 0), aSizeY, pixelOffsetX * 16, pixelOffsetY * 16, minFontScaleX * 256, minFontScaleY * 256); +} +function addDynamicAttributes(dynamicLayoutVertexArray, p, angle) { + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); +} +function containsRTLText(formattedText) { + for (const section of formattedText.sections) { + if (stringContainsRTLText(section.text)) { + return true; + } + } + return false; +} +class SymbolBuffers { + constructor(programConfigurations) { + this.layoutVertexArray = new SymbolLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.programConfigurations = programConfigurations; + this.segments = new SegmentVector(); + this.dynamicLayoutVertexArray = new SymbolDynamicLayoutArray(); + this.opacityVertexArray = new SymbolOpacityArray(); + this.hasVisibleVertices = false; + this.placedSymbolArray = new PlacedSymbolArray(); + } + isEmpty() { + return this.layoutVertexArray.length === 0 && + this.indexArray.length === 0 && + this.dynamicLayoutVertexArray.length === 0 && + this.opacityVertexArray.length === 0; + } + upload(context, dynamicIndexBuffer, upload, update) { + if (this.isEmpty()) { + return; + } + if (upload) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members); + this.indexBuffer = context.createIndexBuffer(this.indexArray, dynamicIndexBuffer); + this.dynamicLayoutVertexBuffer = context.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, true); + this.opacityVertexBuffer = context.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, true); + // This is a performance hack so that we can write to opacityVertexArray with uint32s + // even though the shaders read uint8s + this.opacityVertexBuffer.itemSize = 1; + } + if (upload || update) { + this.programConfigurations.upload(context); + } + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + this.dynamicLayoutVertexBuffer.destroy(); + this.opacityVertexBuffer.destroy(); + } +} +register('SymbolBuffers', SymbolBuffers); +class CollisionBuffers { + constructor(LayoutArray, layoutAttributes, IndexArray) { + this.layoutVertexArray = new LayoutArray(); + this.layoutAttributes = layoutAttributes; + this.indexArray = new IndexArray(); + this.segments = new SegmentVector(); + this.collisionVertexArray = new CollisionVertexArray(); + } + upload(context) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + this.collisionVertexBuffer = context.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, true); + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.segments.destroy(); + this.collisionVertexBuffer.destroy(); + } +} +register('CollisionBuffers', CollisionBuffers); +/** + * @internal + * Unlike other buckets, which simply implement #addFeature with type-specific + * logic for (essentially) triangulating feature geometries, SymbolBucket + * requires specialized behavior: + * + * 1. WorkerTile#parse(), the logical owner of the bucket creation process, + * calls SymbolBucket#populate(), which resolves text and icon tokens on + * each feature, adds each glyphs and symbols needed to the passed-in + * collections options.glyphDependencies and options.iconDependencies, and + * stores the feature data for use in subsequent step (this.features). + * + * 2. WorkerTile asynchronously requests from the main thread all of the glyphs + * and icons needed (by this bucket and any others). When glyphs and icons + * have been received, the WorkerTile creates a CollisionIndex and invokes: + * + * 3. performSymbolLayout(bucket, stacks, icons) perform texts shaping and + * layout on a Symbol Bucket. This step populates: + * `this.symbolInstances`: metadata on generated symbols + * `this.collisionBoxArray`: collision data for use by foreground + * `this.text`: SymbolBuffers for text symbols + * `this.icons`: SymbolBuffers for icons + * `this.iconCollisionBox`: Debug SymbolBuffers for icon collision boxes + * `this.textCollisionBox`: Debug SymbolBuffers for text collision boxes + * The results are sent to the foreground for rendering + * + * 4. placement.ts is run on the foreground, + * and uses the CollisionIndex along with current camera settings to determine + * which symbols can actually show on the map. Collided symbols are hidden + * using a dynamic "OpacityVertexArray". + */ +class SymbolBucket { + constructor(options) { + this.collisionBoxArray = options.collisionBoxArray; + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.pixelRatio = options.pixelRatio; + this.sourceLayerIndex = options.sourceLayerIndex; + this.hasPattern = false; + this.hasRTLText = false; + this.sortKeyRanges = []; + this.collisionCircleArray = []; + this.placementInvProjMatrix = identity$2([]); + this.placementViewportMatrix = identity$2([]); + const layer = this.layers[0]; + const unevaluatedLayoutValues = layer._unevaluatedLayout._values; + this.textSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['text-size']); + this.iconSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['icon-size']); + const layout = this.layers[0].layout; + const sortKey = layout.get('symbol-sort-key'); + const zOrder = layout.get('symbol-z-order'); + this.canOverlap = + getOverlapMode(layout, 'text-overlap', 'text-allow-overlap') !== 'never' || + getOverlapMode(layout, 'icon-overlap', 'icon-allow-overlap') !== 'never' || + layout.get('text-ignore-placement') || + layout.get('icon-ignore-placement'); + this.sortFeaturesByKey = zOrder !== 'viewport-y' && !sortKey.isConstant(); + const zOrderByViewportY = zOrder === 'viewport-y' || (zOrder === 'auto' && !this.sortFeaturesByKey); + this.sortFeaturesByY = zOrderByViewportY && this.canOverlap; + if (layout.get('symbol-placement') === 'point') { + this.writingModes = layout.get('text-writing-mode').map(wm => WritingMode[wm]); + } + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + this.sourceID = options.sourceID; + } + createArrays() { + this.text = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^text/.test(property))); + this.icon = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^icon/.test(property))); + this.glyphOffsetArray = new GlyphOffsetArray(); + this.lineVertexArray = new SymbolLineVertexArray(); + this.symbolInstances = new SymbolInstanceArray(); + this.textAnchorOffsets = new TextAnchorOffsetArray(); + } + calculateGlyphDependencies(text, stack, textAlongLine, allowVerticalPlacement, doesAllowVerticalWritingMode) { + for (let i = 0; i < text.length; i++) { + stack[text.charCodeAt(i)] = true; + if ((textAlongLine || allowVerticalPlacement) && doesAllowVerticalWritingMode) { + const verticalChar = verticalizedCharacterMap[text.charAt(i)]; + if (verticalChar) { + stack[verticalChar.charCodeAt(0)] = true; + } + } + } + } + populate(features, options, canonical) { + const layer = this.layers[0]; + const layout = layer.layout; + const textFont = layout.get('text-font'); + const textField = layout.get('text-field'); + const iconImage = layout.get('icon-image'); + const hasText = (textField.value.kind !== 'constant' || + (textField.value.value instanceof Formatted && !textField.value.value.isEmpty()) || + textField.value.value.toString().length > 0) && + (textFont.value.kind !== 'constant' || textFont.value.value.length > 0); + // we should always resolve the icon-image value if the property was defined in the style + // this allows us to fire the styleimagemissing event if image evaluation returns null + // the only way to distinguish between null returned from a coalesce statement with no valid images + // and null returned because icon-image wasn't defined is to check whether or not iconImage.parameters is an empty object + const hasIcon = iconImage.value.kind !== 'constant' || !!iconImage.value.value || Object.keys(iconImage.parameters).length > 0; + const symbolSortKey = layout.get('symbol-sort-key'); + this.features = []; + if (!hasText && !hasIcon) { + return; + } + const icons = options.iconDependencies; + const stacks = options.glyphDependencies; + const availableImages = options.availableImages; + const globalProperties = new EvaluationParameters(this.zoom); + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = layer._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) { + continue; + } + if (!needGeometry) + evaluationFeature.geometry = loadGeometry(feature); + let text; + if (hasText) { + // Expression evaluation will automatically coerce to Formatted + // but plain string token evaluation skips that pathway so do the + // conversion here. + const resolvedTokens = layer.getValueAndResolveTokens('text-field', evaluationFeature, canonical, availableImages); + const formattedText = Formatted.factory(resolvedTokens); + // on this instance: if hasRTLText is already true, all future calls to containsRTLText can be skipped. + const bucketHasRTLText = this.hasRTLText = (this.hasRTLText || containsRTLText(formattedText)); + if (!bucketHasRTLText || // non-rtl text so can proceed safely + rtlWorkerPlugin.getRTLTextPluginStatus() === 'unavailable' || // We don't intend to lazy-load the rtl text plugin, so proceed with incorrect shaping + bucketHasRTLText && rtlWorkerPlugin.isParsed() // Use the rtlText plugin to shape text + ) { + text = transformText(formattedText, layer, evaluationFeature); + } + } + let icon; + if (hasIcon) { + // Expression evaluation will automatically coerce to Image + // but plain string token evaluation skips that pathway so do the + // conversion here. + const resolvedTokens = layer.getValueAndResolveTokens('icon-image', evaluationFeature, canonical, availableImages); + if (resolvedTokens instanceof ResolvedImage) { + icon = resolvedTokens; + } + else { + icon = ResolvedImage.fromString(resolvedTokens); + } + } + if (!text && !icon) { + continue; + } + const sortKey = this.sortFeaturesByKey ? + symbolSortKey.evaluate(evaluationFeature, {}, canonical) : + undefined; + const symbolFeature = { + id, + text, + icon, + index, + sourceLayerIndex, + geometry: evaluationFeature.geometry, + properties: feature.properties, + type: vectorTileFeatureTypes[feature.type], + sortKey + }; + this.features.push(symbolFeature); + if (icon) { + icons[icon.name] = true; + } + if (text) { + const fontStack = textFont.evaluate(evaluationFeature, {}, canonical).join(','); + const textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point'; + this.allowVerticalPlacement = this.writingModes && this.writingModes.indexOf(WritingMode.vertical) >= 0; + for (const section of text.sections) { + if (!section.image) { + const doesAllowVerticalWritingMode = allowsVerticalWritingMode(text.toString()); + const sectionFont = section.fontStack || fontStack; + const sectionStack = stacks[sectionFont] = stacks[sectionFont] || {}; + this.calculateGlyphDependencies(section.text, sectionStack, textAlongLine, this.allowVerticalPlacement, doesAllowVerticalWritingMode); + } + else { + // Add section image to the list of dependencies. + icons[section.image.name] = true; + } + } + } + } + if (layout.get('symbol-placement') === 'line') { + // Merge adjacent lines with the same text to improve labelling. + // It's better to place labels on one long line than on many short segments. + this.features = mergeLines(this.features); + } + if (this.sortFeaturesByKey) { + this.features.sort((a, b) => { + // a.sortKey is always a number when sortFeaturesByKey is true + return a.sortKey - b.sortKey; + }); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.text.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions); + this.icon.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions); + } + isEmpty() { + // When the bucket encounters only rtl-text but the plugin isn't loaded, no symbol instances will be created. + // In order for the bucket to be serialized, and not discarded as an empty bucket both checks are necessary. + return this.symbolInstances.length === 0 && !this.hasRTLText; + } + uploadPending() { + return !this.uploaded || this.text.programConfigurations.needsUpload || this.icon.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded && this.hasDebugData()) { + this.textCollisionBox.upload(context); + this.iconCollisionBox.upload(context); + } + this.text.upload(context, this.sortFeaturesByY, !this.uploaded, this.text.programConfigurations.needsUpload); + this.icon.upload(context, this.sortFeaturesByY, !this.uploaded, this.icon.programConfigurations.needsUpload); + this.uploaded = true; + } + destroyDebugData() { + this.textCollisionBox.destroy(); + this.iconCollisionBox.destroy(); + } + destroy() { + this.text.destroy(); + this.icon.destroy(); + if (this.hasDebugData()) { + this.destroyDebugData(); + } + } + addToLineVertexArray(anchor, line) { + const lineStartIndex = this.lineVertexArray.length; + if (anchor.segment !== undefined) { + let sumForwardLength = anchor.dist(line[anchor.segment + 1]); + let sumBackwardLength = anchor.dist(line[anchor.segment]); + const vertices = {}; + for (let i = anchor.segment + 1; i < line.length; i++) { + vertices[i] = { x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumForwardLength }; + if (i < line.length - 1) { + sumForwardLength += line[i + 1].dist(line[i]); + } + } + for (let i = anchor.segment || 0; i >= 0; i--) { + vertices[i] = { x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumBackwardLength }; + if (i > 0) { + sumBackwardLength += line[i - 1].dist(line[i]); + } + } + for (let i = 0; i < line.length; i++) { + const vertex = vertices[i]; + this.lineVertexArray.emplaceBack(vertex.x, vertex.y, vertex.tileUnitDistanceFromAnchor); + } + } + return { + lineStartIndex, + lineLength: this.lineVertexArray.length - lineStartIndex + }; + } + addSymbols(arrays, quads, sizeVertex, lineOffset, alongLine, feature, writingMode, labelAnchor, lineStartIndex, lineLength, associatedIconIndex, canonical) { + const indexArray = arrays.indexArray; + const layoutVertexArray = arrays.layoutVertexArray; + const segment = arrays.segments.prepareSegment(4 * quads.length, layoutVertexArray, indexArray, this.canOverlap ? feature.sortKey : undefined); + const glyphOffsetArrayStart = this.glyphOffsetArray.length; + const vertexStartIndex = segment.vertexLength; + const angle = (this.allowVerticalPlacement && writingMode === WritingMode.vertical) ? Math.PI / 2 : 0; + const sections = feature.text && feature.text.sections; + for (let i = 0; i < quads.length; i++) { + const { tl, tr, bl, br, tex, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, glyphOffset, isSDF, sectionIndex } = quads[i]; + const index = segment.vertexLength; + const y = glyphOffset[1]; + addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY); + 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); + 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); + 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); + addDynamicAttributes(arrays.dynamicLayoutVertexArray, labelAnchor, angle); + indexArray.emplaceBack(index, index + 1, index + 2); + indexArray.emplaceBack(index + 1, index + 2, index + 3); + segment.vertexLength += 4; + segment.primitiveLength += 2; + this.glyphOffsetArray.emplaceBack(glyphOffset[0]); + if (i === quads.length - 1 || sectionIndex !== quads[i + 1].sectionIndex) { + arrays.programConfigurations.populatePaintArrays(layoutVertexArray.length, feature, feature.index, {}, canonical, sections && sections[sectionIndex]); + } + } + arrays.placedSymbolArray.emplaceBack(labelAnchor.x, labelAnchor.y, glyphOffsetArrayStart, this.glyphOffsetArray.length - glyphOffsetArrayStart, vertexStartIndex, lineStartIndex, lineLength, labelAnchor.segment, sizeVertex ? sizeVertex[0] : 0, sizeVertex ? sizeVertex[1] : 0, lineOffset[0], lineOffset[1], writingMode, + // placedOrientation is null initially; will be updated to horizontal(1)/vertical(2) if placed + 0, false, + // The crossTileID is only filled/used on the foreground for dynamic text anchors + 0, associatedIconIndex); + } + _addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, point, anchorX, anchorY, extrude) { + collisionVertexArray.emplaceBack(0, 0); + return layoutVertexArray.emplaceBack( + // pos + point.x, point.y, + // a_anchor_pos + anchorX, anchorY, + // extrude + Math.round(extrude.x), Math.round(extrude.y)); + } + addCollisionDebugVertices(x1, y1, x2, y2, arrays, boxAnchorPoint, symbolInstance) { + const segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray); + const index = segment.vertexLength; + const layoutVertexArray = arrays.layoutVertexArray; + const collisionVertexArray = arrays.collisionVertexArray; + const anchorX = symbolInstance.anchorX; + const anchorY = symbolInstance.anchorY; + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$2(x1, y1)); + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$2(x2, y1)); + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$2(x2, y2)); + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$2(x1, y2)); + segment.vertexLength += 4; + const indexArray = arrays.indexArray; + indexArray.emplaceBack(index, index + 1); + indexArray.emplaceBack(index + 1, index + 2); + indexArray.emplaceBack(index + 2, index + 3); + indexArray.emplaceBack(index + 3, index); + segment.primitiveLength += 4; + } + addDebugCollisionBoxes(startIndex, endIndex, symbolInstance, isText) { + for (let b = startIndex; b < endIndex; b++) { + const box = this.collisionBoxArray.get(b); + const x1 = box.x1; + const y1 = box.y1; + const x2 = box.x2; + const y2 = box.y2; + this.addCollisionDebugVertices(x1, y1, x2, y2, isText ? this.textCollisionBox : this.iconCollisionBox, box.anchorPoint, symbolInstance); + } + } + generateCollisionDebugBuffers() { + if (this.hasDebugData()) { + this.destroyDebugData(); + } + this.textCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray); + this.iconCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray); + for (let i = 0; i < this.symbolInstances.length; i++) { + const symbolInstance = this.symbolInstances.get(i); + this.addDebugCollisionBoxes(symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance, true); + this.addDebugCollisionBoxes(symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance, true); + this.addDebugCollisionBoxes(symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance, false); + this.addDebugCollisionBoxes(symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance, false); + } + } + // These flat arrays are meant to be quicker to iterate over than the source + // CollisionBoxArray + _deserializeCollisionBoxesForSymbol(collisionBoxArray, textStartIndex, textEndIndex, verticalTextStartIndex, verticalTextEndIndex, iconStartIndex, iconEndIndex, verticalIconStartIndex, verticalIconEndIndex) { + const collisionArrays = {}; + for (let k = textStartIndex; k < textEndIndex; k++) { + const box = collisionBoxArray.get(k); + collisionArrays.textBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.textFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + for (let k = verticalTextStartIndex; k < verticalTextEndIndex; k++) { + const box = collisionBoxArray.get(k); + collisionArrays.verticalTextBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.verticalTextFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + for (let k = iconStartIndex; k < iconEndIndex; k++) { + // An icon can only have one box now, so this indexing is a bit vestigial... + const box = collisionBoxArray.get(k); + collisionArrays.iconBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.iconFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + for (let k = verticalIconStartIndex; k < verticalIconEndIndex; k++) { + // An icon can only have one box now, so this indexing is a bit vestigial... + const box = collisionBoxArray.get(k); + collisionArrays.verticalIconBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.verticalIconFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + return collisionArrays; + } + deserializeCollisionBoxes(collisionBoxArray) { + this.collisionArrays = []; + for (let i = 0; i < this.symbolInstances.length; i++) { + const symbolInstance = this.symbolInstances.get(i); + this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(collisionBoxArray, symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex)); + } + } + hasTextData() { + return this.text.segments.get().length > 0; + } + hasIconData() { + return this.icon.segments.get().length > 0; + } + hasDebugData() { + return this.textCollisionBox && this.iconCollisionBox; + } + hasTextCollisionBoxData() { + return this.hasDebugData() && this.textCollisionBox.segments.get().length > 0; + } + hasIconCollisionBoxData() { + return this.hasDebugData() && this.iconCollisionBox.segments.get().length > 0; + } + addIndicesForPlacedSymbol(iconOrText, placedSymbolIndex) { + const placedSymbol = iconOrText.placedSymbolArray.get(placedSymbolIndex); + const endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4; + for (let vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) { + iconOrText.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2); + iconOrText.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3); + } + } + getSortedSymbolIndexes(angle) { + if (this.sortedAngle === angle && this.symbolInstanceIndexes !== undefined) { + return this.symbolInstanceIndexes; + } + const sin = Math.sin(angle); + const cos = Math.cos(angle); + const rotatedYs = []; + const featureIndexes = []; + const result = []; + for (let i = 0; i < this.symbolInstances.length; ++i) { + result.push(i); + const symbolInstance = this.symbolInstances.get(i); + rotatedYs.push(Math.round(sin * symbolInstance.anchorX + cos * symbolInstance.anchorY) | 0); + featureIndexes.push(symbolInstance.featureIndex); + } + result.sort((aIndex, bIndex) => { + return (rotatedYs[aIndex] - rotatedYs[bIndex]) || + (featureIndexes[bIndex] - featureIndexes[aIndex]); + }); + return result; + } + addToSortKeyRanges(symbolInstanceIndex, sortKey) { + const last = this.sortKeyRanges[this.sortKeyRanges.length - 1]; + if (last && last.sortKey === sortKey) { + last.symbolInstanceEnd = symbolInstanceIndex + 1; + } + else { + this.sortKeyRanges.push({ + sortKey, + symbolInstanceStart: symbolInstanceIndex, + symbolInstanceEnd: symbolInstanceIndex + 1 + }); + } + } + sortFeatures(angle) { + if (!this.sortFeaturesByY) + return; + if (this.sortedAngle === angle) + return; + // The current approach to sorting doesn't sort across segments so don't try. + // Sorting within segments separately seemed not to be worth the complexity. + if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1) + return; + // If the symbols are allowed to overlap sort them by their vertical screen position. + // The index array buffer is rewritten to reference the (unchanged) vertices in the + // sorted order. + // To avoid sorting the actual symbolInstance array we sort an array of indexes. + this.symbolInstanceIndexes = this.getSortedSymbolIndexes(angle); + this.sortedAngle = angle; + this.text.indexArray.clear(); + this.icon.indexArray.clear(); + this.featureSortOrder = []; + for (const i of this.symbolInstanceIndexes) { + const symbolInstance = this.symbolInstances.get(i); + this.featureSortOrder.push(symbolInstance.featureIndex); + [ + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.leftJustifiedTextSymbolIndex + ].forEach((index, i, array) => { + // Only add a given index the first time it shows up, + // to avoid duplicate opacity entries when multiple justifications + // share the same glyphs. + if (index >= 0 && array.indexOf(index) === i) { + this.addIndicesForPlacedSymbol(this.text, index); + } + }); + if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) { + this.addIndicesForPlacedSymbol(this.text, symbolInstance.verticalPlacedTextSymbolIndex); + } + if (symbolInstance.placedIconSymbolIndex >= 0) { + this.addIndicesForPlacedSymbol(this.icon, symbolInstance.placedIconSymbolIndex); + } + if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) { + this.addIndicesForPlacedSymbol(this.icon, symbolInstance.verticalPlacedIconSymbolIndex); + } + } + if (this.text.indexBuffer) + this.text.indexBuffer.updateData(this.text.indexArray); + if (this.icon.indexBuffer) + this.icon.indexBuffer.updateData(this.icon.indexArray); + } +} +register('SymbolBucket', SymbolBucket, { + omit: ['layers', 'collisionBoxArray', 'features', 'compareText'] +}); +// this constant is based on the size of StructArray indexes used in a symbol +// bucket--namely, glyphOffsetArrayStart +// eg the max valid UInt16 is 65,535 +// See https://github.com/mapbox/mapbox-gl-js/issues/2907 for motivation +// lineStartIndex and textBoxStartIndex could potentially be concerns +// but we expect there to be many fewer boxes/lines than glyphs +SymbolBucket.MAX_GLYPHS = 65535; +SymbolBucket.addDynamicAttributes = addDynamicAttributes; + +/** + * Replace tokens in a string template with values in an object + * + * @param properties - a key/value relationship between tokens and replacements + * @param text - the template string + * @returns the template with tokens replaced + */ +function resolveTokens(properties, text) { + return text.replace(/{([^{}]+)}/g, (match, key) => { + return properties && key in properties ? String(properties[key]) : ''; + }); +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout; +const getLayout = () => layout = layout || new Properties({ + "symbol-placement": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-placement"]), + "symbol-spacing": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-spacing"]), + "symbol-avoid-edges": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-avoid-edges"]), + "symbol-sort-key": new DataDrivenProperty(v8Spec["layout_symbol"]["symbol-sort-key"]), + "symbol-z-order": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-z-order"]), + "icon-allow-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["icon-allow-overlap"]), + "icon-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["icon-overlap"]), + "icon-ignore-placement": new DataConstantProperty(v8Spec["layout_symbol"]["icon-ignore-placement"]), + "icon-optional": new DataConstantProperty(v8Spec["layout_symbol"]["icon-optional"]), + "icon-rotation-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["icon-rotation-alignment"]), + "icon-size": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-size"]), + "icon-text-fit": new DataConstantProperty(v8Spec["layout_symbol"]["icon-text-fit"]), + "icon-text-fit-padding": new DataConstantProperty(v8Spec["layout_symbol"]["icon-text-fit-padding"]), + "icon-image": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-image"]), + "icon-rotate": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-rotate"]), + "icon-padding": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-padding"]), + "icon-keep-upright": new DataConstantProperty(v8Spec["layout_symbol"]["icon-keep-upright"]), + "icon-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-offset"]), + "icon-anchor": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-anchor"]), + "icon-pitch-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["icon-pitch-alignment"]), + "text-pitch-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["text-pitch-alignment"]), + "text-rotation-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["text-rotation-alignment"]), + "text-field": new DataDrivenProperty(v8Spec["layout_symbol"]["text-field"]), + "text-font": new DataDrivenProperty(v8Spec["layout_symbol"]["text-font"]), + "text-size": new DataDrivenProperty(v8Spec["layout_symbol"]["text-size"]), + "text-max-width": new DataDrivenProperty(v8Spec["layout_symbol"]["text-max-width"]), + "text-line-height": new DataConstantProperty(v8Spec["layout_symbol"]["text-line-height"]), + "text-letter-spacing": new DataDrivenProperty(v8Spec["layout_symbol"]["text-letter-spacing"]), + "text-justify": new DataDrivenProperty(v8Spec["layout_symbol"]["text-justify"]), + "text-radial-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["text-radial-offset"]), + "text-variable-anchor": new DataConstantProperty(v8Spec["layout_symbol"]["text-variable-anchor"]), + "text-variable-anchor-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["text-variable-anchor-offset"]), + "text-anchor": new DataDrivenProperty(v8Spec["layout_symbol"]["text-anchor"]), + "text-max-angle": new DataConstantProperty(v8Spec["layout_symbol"]["text-max-angle"]), + "text-writing-mode": new DataConstantProperty(v8Spec["layout_symbol"]["text-writing-mode"]), + "text-rotate": new DataDrivenProperty(v8Spec["layout_symbol"]["text-rotate"]), + "text-padding": new DataConstantProperty(v8Spec["layout_symbol"]["text-padding"]), + "text-keep-upright": new DataConstantProperty(v8Spec["layout_symbol"]["text-keep-upright"]), + "text-transform": new DataDrivenProperty(v8Spec["layout_symbol"]["text-transform"]), + "text-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["text-offset"]), + "text-allow-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["text-allow-overlap"]), + "text-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["text-overlap"]), + "text-ignore-placement": new DataConstantProperty(v8Spec["layout_symbol"]["text-ignore-placement"]), + "text-optional": new DataConstantProperty(v8Spec["layout_symbol"]["text-optional"]), +}); +let paint$2; +const getPaint$2 = () => paint$2 = paint$2 || new Properties({ + "icon-opacity": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-opacity"]), + "icon-color": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-color"]), + "icon-halo-color": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-color"]), + "icon-halo-width": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-width"]), + "icon-halo-blur": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-blur"]), + "icon-translate": new DataConstantProperty(v8Spec["paint_symbol"]["icon-translate"]), + "icon-translate-anchor": new DataConstantProperty(v8Spec["paint_symbol"]["icon-translate-anchor"]), + "text-opacity": new DataDrivenProperty(v8Spec["paint_symbol"]["text-opacity"]), + "text-color": new DataDrivenProperty(v8Spec["paint_symbol"]["text-color"], { runtimeType: ColorType, getOverride: (o) => o.textColor, hasOverride: (o) => !!o.textColor }), + "text-halo-color": new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-color"]), + "text-halo-width": new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-width"]), + "text-halo-blur": new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-blur"]), + "text-translate": new DataConstantProperty(v8Spec["paint_symbol"]["text-translate"]), + "text-translate-anchor": new DataConstantProperty(v8Spec["paint_symbol"]["text-translate-anchor"]), +}); +var properties$3 = ({ get paint() { return getPaint$2(); }, get layout() { return getLayout(); } }); + +// This is an internal expression class. It is only used in GL JS and +// has GL JS dependencies which can break the standalone style-spec module +class FormatSectionOverride { + constructor(defaultValue) { + if (defaultValue.property.overrides === undefined) + throw new Error('overrides must be provided to instantiate FormatSectionOverride class'); + this.type = defaultValue.property.overrides ? defaultValue.property.overrides.runtimeType : NullType; + this.defaultValue = defaultValue; + } + evaluate(ctx) { + if (ctx.formattedSection) { + const overrides = this.defaultValue.property.overrides; + if (overrides && overrides.hasOverride(ctx.formattedSection)) { + return overrides.getOverride(ctx.formattedSection); + } + } + if (ctx.feature && ctx.featureState) { + return this.defaultValue.evaluate(ctx.feature, ctx.featureState); + } + return this.defaultValue.property.specification.default; + } + eachChild(fn) { + if (!this.defaultValue.isConstant()) { + const expr = this.defaultValue.value; + fn(expr._styleExpression.expression); + } + } + // Cannot be statically evaluated, as the output depends on the evaluation context. + outputDefined() { + return false; + } + serialize() { + return null; + } +} +register('FormatSectionOverride', FormatSectionOverride, { omit: ['defaultValue'] }); + +class SymbolStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$3); + } + recalculate(parameters, availableImages) { + super.recalculate(parameters, availableImages); + if (this.layout.get('icon-rotation-alignment') === 'auto') { + if (this.layout.get('symbol-placement') !== 'point') { + this.layout._values['icon-rotation-alignment'] = 'map'; + } + else { + this.layout._values['icon-rotation-alignment'] = 'viewport'; + } + } + if (this.layout.get('text-rotation-alignment') === 'auto') { + if (this.layout.get('symbol-placement') !== 'point') { + this.layout._values['text-rotation-alignment'] = 'map'; + } + else { + this.layout._values['text-rotation-alignment'] = 'viewport'; + } + } + // If unspecified, `*-pitch-alignment` inherits `*-rotation-alignment` + if (this.layout.get('text-pitch-alignment') === 'auto') { + this.layout._values['text-pitch-alignment'] = this.layout.get('text-rotation-alignment') === 'map' ? 'map' : 'viewport'; + } + if (this.layout.get('icon-pitch-alignment') === 'auto') { + this.layout._values['icon-pitch-alignment'] = this.layout.get('icon-rotation-alignment'); + } + if (this.layout.get('symbol-placement') === 'point') { + const writingModes = this.layout.get('text-writing-mode'); + if (writingModes) { + // remove duplicates, preserving order + const deduped = []; + for (const m of writingModes) { + if (deduped.indexOf(m) < 0) + deduped.push(m); + } + this.layout._values['text-writing-mode'] = deduped; + } + else { + this.layout._values['text-writing-mode'] = ['horizontal']; + } + } + this._setPaintOverrides(); + } + getValueAndResolveTokens(name, feature, canonical, availableImages) { + const value = this.layout.get(name).evaluate(feature, {}, canonical, availableImages); + const unevaluated = this._unevaluatedLayout._values[name]; + if (!unevaluated.isDataDriven() && !isExpression(unevaluated.value) && value) { + return resolveTokens(feature.properties, value); + } + return value; + } + createBucket(parameters) { + return new SymbolBucket(parameters); + } + queryRadius() { + return 0; + } + queryIntersectsFeature() { + throw new Error('Should take a different path in FeatureIndex'); + } + _setPaintOverrides() { + for (const overridable of properties$3.paint.overridableProperties) { + if (!SymbolStyleLayer.hasPaintOverride(this.layout, overridable)) { + continue; + } + const overridden = this.paint.get(overridable); + const override = new FormatSectionOverride(overridden); + const styleExpression = new StyleExpression(override, overridden.property.specification); + let expression = null; + if (overridden.value.kind === 'constant' || overridden.value.kind === 'source') { + expression = new ZoomConstantExpression('source', styleExpression); + } + else { + expression = new ZoomDependentExpression('composite', styleExpression, overridden.value.zoomStops); + } + this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overridden.property, expression, overridden.parameters); + } + } + _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) { + if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) { + return false; + } + return SymbolStyleLayer.hasPaintOverride(this.layout, name); + } + static hasPaintOverride(layout, propertyName) { + const textField = layout.get('text-field'); + const property = properties$3.paint.properties[propertyName]; + let hasOverrides = false; + const checkSections = (sections) => { + for (const section of sections) { + if (property.overrides && property.overrides.hasOverride(section)) { + hasOverrides = true; + return; + } + } + }; + if (textField.value.kind === 'constant' && textField.value.value instanceof Formatted) { + checkSections(textField.value.value.sections); + } + else if (textField.value.kind === 'source') { + const checkExpression = (expression) => { + if (hasOverrides) + return; + if (expression instanceof Literal && typeOf(expression.value) === FormattedType) { + const formatted = expression.value; + checkSections(formatted.sections); + } + else if (expression instanceof FormatExpression) { + checkSections(expression.sections); + } + else { + expression.eachChild(checkExpression); + } + }; + const expr = textField.value; + if (expr._styleExpression) { + checkExpression(expr._styleExpression.expression); + } + } + return hasOverrides; + } +} +function getIconPadding(layout, feature, canonical, pixelRatio = 1) { + // Support text-padding in addition to icon-padding? Unclear how to apply asymmetric text-padding to the radius for collision circles. + const result = layout.get('icon-padding').evaluate(feature, {}, canonical); + const values = result && result.values; + return [ + values[0] * pixelRatio, + values[1] * pixelRatio, + values[2] * pixelRatio, + values[3] * pixelRatio, + ]; +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$1; +const getPaint$1 = () => paint$1 = paint$1 || new Properties({ + "background-color": new DataConstantProperty(v8Spec["paint_background"]["background-color"]), + "background-pattern": new CrossFadedProperty(v8Spec["paint_background"]["background-pattern"]), + "background-opacity": new DataConstantProperty(v8Spec["paint_background"]["background-opacity"]), +}); +var properties$2 = ({ get paint() { return getPaint$1(); } }); + +class BackgroundStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$2); + } +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint; +const getPaint = () => paint = paint || new Properties({ + "raster-opacity": new DataConstantProperty(v8Spec["paint_raster"]["raster-opacity"]), + "raster-hue-rotate": new DataConstantProperty(v8Spec["paint_raster"]["raster-hue-rotate"]), + "raster-brightness-min": new DataConstantProperty(v8Spec["paint_raster"]["raster-brightness-min"]), + "raster-brightness-max": new DataConstantProperty(v8Spec["paint_raster"]["raster-brightness-max"]), + "raster-saturation": new DataConstantProperty(v8Spec["paint_raster"]["raster-saturation"]), + "raster-contrast": new DataConstantProperty(v8Spec["paint_raster"]["raster-contrast"]), + "raster-resampling": new DataConstantProperty(v8Spec["paint_raster"]["raster-resampling"]), + "raster-fade-duration": new DataConstantProperty(v8Spec["paint_raster"]["raster-fade-duration"]), +}); +var properties$1 = ({ get paint() { return getPaint(); } }); + +class RasterStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$1); + } +} + +function validateCustomStyleLayer(layerObject) { + const errors = []; + const id = layerObject.id; + if (id === undefined) { + errors.push({ + message: `layers.${id}: missing required property "id"` + }); + } + if (layerObject.render === undefined) { + errors.push({ + message: `layers.${id}: missing required method "render"` + }); + } + if (layerObject.renderingMode && + layerObject.renderingMode !== '2d' && + layerObject.renderingMode !== '3d') { + errors.push({ + message: `layers.${id}: property "renderingMode" must be either "2d" or "3d"` + }); + } + return errors; +} +class CustomStyleLayer extends StyleLayer { + constructor(implementation) { + super(implementation, {}); + this.onAdd = (map) => { + if (this.implementation.onAdd) { + this.implementation.onAdd(map, map.painter.context.gl); + } + }; + this.onRemove = (map) => { + if (this.implementation.onRemove) { + this.implementation.onRemove(map, map.painter.context.gl); + } + }; + this.implementation = implementation; + } + is3D() { + return this.implementation.renderingMode === '3d'; + } + hasOffscreenPass() { + return this.implementation.prerender !== undefined; + } + recalculate() { } + updateTransitions() { } + hasTransition() { return false; } + serialize() { + throw new Error('Custom layers cannot be serialized'); + } +} + +function createStyleLayer(layer) { + if (layer.type === 'custom') { + return new CustomStyleLayer(layer); + } + switch (layer.type) { + case 'background': + return new BackgroundStyleLayer(layer); + case 'circle': + return new CircleStyleLayer(layer); + case 'fill': + return new FillStyleLayer(layer); + case 'fill-extrusion': + return new FillExtrusionStyleLayer(layer); + case 'heatmap': + return new HeatmapStyleLayer(layer); + case 'hillshade': + return new HillshadeStyleLayer(layer); + case 'line': + return new LineStyleLayer(layer); + case 'raster': + return new RasterStyleLayer(layer); + case 'symbol': + return new SymbolStyleLayer(layer); + } +} + +/** + * Takes a SpriteSpecification value and returns it in its array form. If `undefined` is passed as an input value, an + * empty array is returned. + * duplicated entries with identical id/url will be removed in returned array + * @param sprite - optional sprite to coerce + * @returns an empty array in case `undefined` is passed; id-url pairs otherwise + */ +function coerceSpriteToArray(sprite) { + const resultArray = []; + if (typeof sprite === 'string') { + resultArray.push({ id: 'default', url: sprite }); + } + else if (sprite && sprite.length > 0) { + const dedupArray = []; + for (const { id, url } of sprite) { + const key = `${id}${url}`; + if (dedupArray.indexOf(key) === -1) { + dedupArray.push(key); + resultArray.push({ id, url }); + } + } + } + return resultArray; +} + +function normalizeSpriteURL(url, format, extension) { + const split = url.split('?'); + split[0] += `${format}${extension}`; + return split.join('?'); +} +function loadSprite(originalSprite, requestManager, pixelRatio, abortController) { + return __awaiter(this, void 0, void 0, function* () { + const spriteArray = coerceSpriteToArray(originalSprite); + const format = pixelRatio > 1 ? '@2x' : ''; + const jsonsMap = {}; + const imagesMap = {}; + for (const { id, url } of spriteArray) { + const jsonRequestParameters = requestManager.transformRequest(normalizeSpriteURL(url, format, '.json'), "SpriteJSON" /* ResourceType.SpriteJSON */); + jsonsMap[id] = getJSON(jsonRequestParameters, abortController); + const imageRequestParameters = requestManager.transformRequest(normalizeSpriteURL(url, format, '.png'), "SpriteImage" /* ResourceType.SpriteImage */); + imagesMap[id] = ImageRequest.getImage(imageRequestParameters, abortController); + } + yield Promise.all([...Object.values(jsonsMap), ...Object.values(imagesMap)]); + return doOnceCompleted(jsonsMap, imagesMap); + }); +} +/** + * @param jsonsMap - JSON data map + * @param imagesMap - image data map + */ +function doOnceCompleted(jsonsMap, imagesMap) { + return __awaiter(this, void 0, void 0, function* () { + const result = {}; + for (const spriteName in jsonsMap) { + result[spriteName] = {}; + const context = browser.getImageCanvasContext((yield imagesMap[spriteName]).data); + const json = (yield jsonsMap[spriteName]).data; + for (const id in json) { + const { width, height, x, y, sdf, pixelRatio, stretchX, stretchY, content, textFitWidth, textFitHeight } = json[id]; + const spriteData = { width, height, x, y, context }; + result[spriteName][id] = { data: null, pixelRatio, sdf, stretchX, stretchY, content, textFitWidth, textFitHeight, spriteData }; + } + } + return result; + }); +} + +/** + * @internal + * A `Texture` GL related object + */ +class Texture { + constructor(context, image, format, options) { + this.context = context; + this.format = format; + this.texture = context.gl.createTexture(); + this.update(image, options); + } + update(image, options, position) { + const { width, height } = image; + const resize = (!this.size || this.size[0] !== width || this.size[1] !== height) && !position; + const { context } = this; + const { gl } = context; + this.useMipmap = Boolean(options && options.useMipmap); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + context.pixelStoreUnpackFlipY.set(false); + context.pixelStoreUnpack.set(1); + context.pixelStoreUnpackPremultiplyAlpha.set(this.format === gl.RGBA && (!options || options.premultiply !== false)); + if (resize) { + this.size = [width, height]; + if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || isImageBitmap(image)) { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, gl.UNSIGNED_BYTE, image); + } + else { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, gl.UNSIGNED_BYTE, image.data); + } + } + else { + const { x, y } = position || { x: 0, y: 0 }; + if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || isImageBitmap(image)) { + gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, gl.RGBA, gl.UNSIGNED_BYTE, image); + } + else { + gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, image.data); + } + } + if (this.useMipmap && this.isSizePowerOfTwo()) { + gl.generateMipmap(gl.TEXTURE_2D); + } + } + bind(filter, wrap, minFilter) { + const { context } = this; + const { gl } = context; + gl.bindTexture(gl.TEXTURE_2D, this.texture); + if (minFilter === gl.LINEAR_MIPMAP_NEAREST && !this.isSizePowerOfTwo()) { + minFilter = gl.LINEAR; + } + if (filter !== this.filter) { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter || filter); + this.filter = filter; + } + if (wrap !== this.wrap) { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap); + this.wrap = wrap; + } + } + isSizePowerOfTwo() { + return this.size[0] === this.size[1] && (Math.log(this.size[0]) / Math.LN2) % 1 === 0; + } + destroy() { + const { gl } = this.context; + gl.deleteTexture(this.texture); + this.texture = null; + } +} + +function renderStyleImage(image) { + const { userImage } = image; + if (userImage && userImage.render) { + const updated = userImage.render(); + if (updated) { + image.data.replace(new Uint8Array(userImage.data.buffer)); + return true; + } + } + return false; +} + +/* eslint-disable key-spacing */ +/** + * When copied into the atlas texture, image data is padded by one pixel on each side. Icon + * images are padded with fully transparent pixels, while pattern images are padded with a + * copy of the image data wrapped from the opposite side. In both cases, this ensures the + * correct behavior of GL_LINEAR texture sampling mode. + */ +const padding = 1; +/** + * ImageManager does three things: + * + * 1. Tracks requests for icon images from tile workers and sends responses when the requests are fulfilled. + * 2. Builds a texture atlas for pattern images. + * 3. Rerenders renderable images once per frame + * + * These are disparate responsibilities and should eventually be handled by different classes. When we implement + * data-driven support for `*-pattern`, we'll likely use per-bucket pattern atlases, and that would be a good time + * to refactor this. +*/ +class ImageManager extends Evented { + constructor() { + super(); + this.images = {}; + this.updatedImages = {}; + this.callbackDispatchedThisFrame = {}; + this.loaded = false; + this.requestors = []; + this.patterns = {}; + this.atlasImage = new RGBAImage({ width: 1, height: 1 }); + this.dirty = true; + } + isLoaded() { + return this.loaded; + } + setLoaded(loaded) { + if (this.loaded === loaded) { + return; + } + this.loaded = loaded; + if (loaded) { + for (const { ids, promiseResolve } of this.requestors) { + promiseResolve(this._getImagesForIds(ids)); + } + this.requestors = []; + } + } + getImage(id) { + const image = this.images[id]; + // Extract sprite image data on demand + if (image && !image.data && image.spriteData) { + const spriteData = image.spriteData; + image.data = new RGBAImage({ + width: spriteData.width, + height: spriteData.height + }, spriteData.context.getImageData(spriteData.x, spriteData.y, spriteData.width, spriteData.height).data); + image.spriteData = null; + } + return image; + } + addImage(id, image) { + if (this.images[id]) + throw new Error(`Image id ${id} already exist, use updateImage instead`); + if (this._validate(id, image)) { + this.images[id] = image; + } + } + _validate(id, image) { + let valid = true; + const data = image.data || image.spriteData; + if (!this._validateStretch(image.stretchX, data && data.width)) { + this.fire(new ErrorEvent(new Error(`Image "${id}" has invalid "stretchX" value`))); + valid = false; + } + if (!this._validateStretch(image.stretchY, data && data.height)) { + this.fire(new ErrorEvent(new Error(`Image "${id}" has invalid "stretchY" value`))); + valid = false; + } + if (!this._validateContent(image.content, image)) { + this.fire(new ErrorEvent(new Error(`Image "${id}" has invalid "content" value`))); + valid = false; + } + return valid; + } + _validateStretch(stretch, size) { + if (!stretch) + return true; + let last = 0; + for (const part of stretch) { + if (part[0] < last || part[1] < part[0] || size < part[1]) + return false; + last = part[1]; + } + return true; + } + _validateContent(content, image) { + if (!content) + return true; + if (content.length !== 4) + return false; + const spriteData = image.spriteData; + const width = (spriteData && spriteData.width) || image.data.width; + const height = (spriteData && spriteData.height) || image.data.height; + if (content[0] < 0 || width < content[0]) + return false; + if (content[1] < 0 || height < content[1]) + return false; + if (content[2] < 0 || width < content[2]) + return false; + if (content[3] < 0 || height < content[3]) + return false; + if (content[2] < content[0]) + return false; + if (content[3] < content[1]) + return false; + return true; + } + updateImage(id, image, validate = true) { + const oldImage = this.getImage(id); + if (validate && (oldImage.data.width !== image.data.width || oldImage.data.height !== image.data.height)) { + throw new Error(`size mismatch between old image (${oldImage.data.width}x${oldImage.data.height}) and new image (${image.data.width}x${image.data.height}).`); + } + image.version = oldImage.version + 1; + this.images[id] = image; + this.updatedImages[id] = true; + } + removeImage(id) { + const image = this.images[id]; + delete this.images[id]; + delete this.patterns[id]; + if (image.userImage && image.userImage.onRemove) { + image.userImage.onRemove(); + } + } + listImages() { + return Object.keys(this.images); + } + getImages(ids) { + return new Promise((resolve, _reject) => { + // If the sprite has been loaded, or if all the icon dependencies are already present + // (i.e. if they've been added via runtime styling), then notify the requestor immediately. + // Otherwise, delay notification until the sprite is loaded. At that point, if any of the + // dependencies are still unavailable, we'll just assume they are permanently missing. + let hasAllDependencies = true; + if (!this.isLoaded()) { + for (const id of ids) { + if (!this.images[id]) { + hasAllDependencies = false; + } + } + } + if (this.isLoaded() || hasAllDependencies) { + resolve(this._getImagesForIds(ids)); + } + else { + this.requestors.push({ ids, promiseResolve: resolve }); + } + }); + } + _getImagesForIds(ids) { + const response = {}; + for (const id of ids) { + let image = this.getImage(id); + if (!image) { + this.fire(new Event('styleimagemissing', { id })); + //Try to acquire image again in case styleimagemissing has populated it + image = this.getImage(id); + } + if (image) { + // Clone the image so that our own copy of its ArrayBuffer doesn't get transferred. + response[id] = { + data: image.data.clone(), + pixelRatio: image.pixelRatio, + sdf: image.sdf, + version: image.version, + stretchX: image.stretchX, + stretchY: image.stretchY, + content: image.content, + textFitWidth: image.textFitWidth, + textFitHeight: image.textFitHeight, + hasRenderCallback: Boolean(image.userImage && image.userImage.render) + }; + } + else { + 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.`); + } + } + return response; + } + // Pattern stuff + getPixelSize() { + const { width, height } = this.atlasImage; + return { width, height }; + } + getPattern(id) { + const pattern = this.patterns[id]; + const image = this.getImage(id); + if (!image) { + return null; + } + if (pattern && pattern.position.version === image.version) { + return pattern.position; + } + if (!pattern) { + const w = image.data.width + padding * 2; + const h = image.data.height + padding * 2; + const bin = { w, h, x: 0, y: 0 }; + const position = new ImagePosition(bin, image); + this.patterns[id] = { bin, position }; + } + else { + pattern.position.version = image.version; + } + this._updatePatternAtlas(); + return this.patterns[id].position; + } + bind(context) { + const gl = context.gl; + if (!this.atlasTexture) { + this.atlasTexture = new Texture(context, this.atlasImage, gl.RGBA); + } + else if (this.dirty) { + this.atlasTexture.update(this.atlasImage); + this.dirty = false; + } + this.atlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + } + _updatePatternAtlas() { + const bins = []; + for (const id in this.patterns) { + bins.push(this.patterns[id].bin); + } + const { w, h } = potpack(bins); + const dst = this.atlasImage; + dst.resize({ width: w || 1, height: h || 1 }); + for (const id in this.patterns) { + const { bin } = this.patterns[id]; + const x = bin.x + padding; + const y = bin.y + padding; + const src = this.getImage(id).data; + const w = src.width; + const h = src.height; + RGBAImage.copy(src, dst, { x: 0, y: 0 }, { x, y }, { width: w, height: h }); + // Add 1 pixel wrapped padding on each side of the image. + RGBAImage.copy(src, dst, { x: 0, y: h - 1 }, { x, y: y - 1 }, { width: w, height: 1 }); // T + RGBAImage.copy(src, dst, { x: 0, y: 0 }, { x, y: y + h }, { width: w, height: 1 }); // B + RGBAImage.copy(src, dst, { x: w - 1, y: 0 }, { x: x - 1, y }, { width: 1, height: h }); // L + RGBAImage.copy(src, dst, { x: 0, y: 0 }, { x: x + w, y }, { width: 1, height: h }); // R + } + this.dirty = true; + } + beginFrame() { + this.callbackDispatchedThisFrame = {}; + } + dispatchRenderCallbacks(ids) { + for (const id of ids) { + // the callback for the image was already dispatched for a different frame + if (this.callbackDispatchedThisFrame[id]) + continue; + this.callbackDispatchedThisFrame[id] = true; + const image = this.getImage(id); + if (!image) + warnOnce(`Image with ID: "${id}" was not found`); + const updated = renderStyleImage(image); + if (updated) { + this.updateImage(id, image); + } + } + } +} + +function loadGlyphRange(fontstack, range, urlTemplate, requestManager) { + return __awaiter(this, void 0, void 0, function* () { + const begin = range * 256; + const end = begin + 255; + const request = requestManager.transformRequest(urlTemplate.replace('{fontstack}', fontstack).replace('{range}', `${begin}-${end}`), "Glyphs" /* ResourceType.Glyphs */); + const response = yield getArrayBuffer(request, new AbortController()); + if (!response || !response.data) { + throw new Error(`Could not load glyph range. range: ${range}, ${begin}-${end}`); + } + const glyphs = {}; + for (const glyph of parseGlyphPbf(response.data)) { + glyphs[glyph.id] = glyph; + } + return glyphs; + }); +} + +const INF = 1e20; + +class TinySDF { + constructor({ + fontSize = 24, + buffer = 3, + radius = 8, + cutoff = 0.25, + fontFamily = 'sans-serif', + fontWeight = 'normal', + fontStyle = 'normal' + } = {}) { + this.buffer = buffer; + this.cutoff = cutoff; + this.radius = radius; + + // make the canvas size big enough to both have the specified buffer around the glyph + // for "halo", and account for some glyphs possibly being larger than their font size + const size = this.size = fontSize + buffer * 4; + + const canvas = this._createCanvas(size); + const ctx = this.ctx = canvas.getContext('2d', {willReadFrequently: true}); + ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`; + + ctx.textBaseline = 'alphabetic'; + ctx.textAlign = 'left'; // Necessary so that RTL text doesn't have different alignment + ctx.fillStyle = 'black'; + + // temporary arrays for the distance transform + this.gridOuter = new Float64Array(size * size); + this.gridInner = new Float64Array(size * size); + this.f = new Float64Array(size); + this.z = new Float64Array(size + 1); + this.v = new Uint16Array(size); + } + + _createCanvas(size) { + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = size; + return canvas; + } + + draw(char) { + const { + width: glyphAdvance, + actualBoundingBoxAscent, + actualBoundingBoxDescent, + actualBoundingBoxLeft, + actualBoundingBoxRight + } = this.ctx.measureText(char); + + // The integer/pixel part of the top alignment is encoded in metrics.glyphTop + // The remainder is implicitly encoded in the rasterization + const glyphTop = Math.ceil(actualBoundingBoxAscent); + const glyphLeft = 0; + + // If the glyph overflows the canvas size, it will be clipped at the bottom/right + const glyphWidth = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(actualBoundingBoxRight - actualBoundingBoxLeft))); + const glyphHeight = Math.min(this.size - this.buffer, glyphTop + Math.ceil(actualBoundingBoxDescent)); + + const width = glyphWidth + 2 * this.buffer; + const height = glyphHeight + 2 * this.buffer; + + const len = Math.max(width * height, 0); + const data = new Uint8ClampedArray(len); + const glyph = {data, width, height, glyphWidth, glyphHeight, glyphTop, glyphLeft, glyphAdvance}; + if (glyphWidth === 0 || glyphHeight === 0) return glyph; + + const {ctx, buffer, gridInner, gridOuter} = this; + ctx.clearRect(buffer, buffer, glyphWidth, glyphHeight); + ctx.fillText(char, buffer, buffer + glyphTop); + const imgData = ctx.getImageData(buffer, buffer, glyphWidth, glyphHeight); + + // Initialize grids outside the glyph range to alpha 0 + gridOuter.fill(INF, 0, len); + gridInner.fill(0, 0, len); + + for (let y = 0; y < glyphHeight; y++) { + for (let x = 0; x < glyphWidth; x++) { + const a = imgData.data[4 * (y * glyphWidth + x) + 3] / 255; // alpha value + if (a === 0) continue; // empty pixels + + const j = (y + buffer) * width + x + buffer; + + if (a === 1) { // fully drawn pixels + gridOuter[j] = 0; + gridInner[j] = INF; + + } else { // aliased pixels + const d = 0.5 - a; + gridOuter[j] = d > 0 ? d * d : 0; + gridInner[j] = d < 0 ? d * d : 0; + } + } + } + + edt(gridOuter, 0, 0, width, height, width, this.f, this.v, this.z); + edt(gridInner, buffer, buffer, glyphWidth, glyphHeight, width, this.f, this.v, this.z); + + for (let i = 0; i < len; i++) { + const d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]); + data[i] = Math.round(255 - 255 * (d / this.radius + this.cutoff)); + } + + return glyph; + } +} + +// 2D Euclidean squared distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf +function edt(data, x0, y0, width, height, gridSize, f, v, z) { + for (let x = x0; x < x0 + width; x++) edt1d(data, y0 * gridSize + x, gridSize, height, f, v, z); + for (let y = y0; y < y0 + height; y++) edt1d(data, y * gridSize + x0, 1, width, f, v, z); +} + +// 1D squared distance transform +function edt1d(grid, offset, stride, length, f, v, z) { + v[0] = 0; + z[0] = -INF; + z[1] = INF; + f[0] = grid[offset]; + + for (let q = 1, k = 0, s = 0; q < length; q++) { + f[q] = grid[offset + q * stride]; + const q2 = q * q; + do { + const r = v[k]; + s = (f[q] - f[r] + q2 - r * r) / (q - r) / 2; + } while (s <= z[k] && --k > -1); + + k++; + v[k] = q; + z[k] = s; + z[k + 1] = INF; + } + + for (let q = 0, k = 0; q < length; q++) { + while (z[k + 1] < q) k++; + const r = v[k]; + const qr = q - r; + grid[offset + q * stride] = f[r] + qr * qr; + } +} + +class GlyphManager { + constructor(requestManager, localIdeographFontFamily) { + this.requestManager = requestManager; + this.localIdeographFontFamily = localIdeographFontFamily; + this.entries = {}; + } + setURL(url) { + this.url = url; + } + getGlyphs(glyphs) { + return __awaiter(this, void 0, void 0, function* () { + const glyphsPromises = []; + for (const stack in glyphs) { + for (const id of glyphs[stack]) { + glyphsPromises.push(this._getAndCacheGlyphsPromise(stack, id)); + } + } + const updatedGlyphs = yield Promise.all(glyphsPromises); + const result = {}; + for (const { stack, id, glyph } of updatedGlyphs) { + if (!result[stack]) { + result[stack] = {}; + } + // Clone the glyph so that our own copy of its ArrayBuffer doesn't get transferred. + result[stack][id] = glyph && { + id: glyph.id, + bitmap: glyph.bitmap.clone(), + metrics: glyph.metrics + }; + } + return result; + }); + } + _getAndCacheGlyphsPromise(stack, id) { + return __awaiter(this, void 0, void 0, function* () { + let entry = this.entries[stack]; + if (!entry) { + entry = this.entries[stack] = { + glyphs: {}, + requests: {}, + ranges: {} + }; + } + let glyph = entry.glyphs[id]; + if (glyph !== undefined) { + return { stack, id, glyph }; + } + glyph = this._tinySDF(entry, stack, id); + if (glyph) { + entry.glyphs[id] = glyph; + return { stack, id, glyph }; + } + const range = Math.floor(id / 256); + if (range * 256 > 65535) { + throw new Error('glyphs > 65535 not supported'); + } + if (entry.ranges[range]) { + return { stack, id, glyph }; + } + if (!this.url) { + throw new Error('glyphsUrl is not set'); + } + if (!entry.requests[range]) { + const promise = GlyphManager.loadGlyphRange(stack, range, this.url, this.requestManager); + entry.requests[range] = promise; + } + const response = yield entry.requests[range]; + for (const id in response) { + if (!this._doesCharSupportLocalGlyph(+id)) { + entry.glyphs[+id] = response[+id]; + } + } + entry.ranges[range] = true; + return { stack, id, glyph: response[id] || null }; + }); + } + _doesCharSupportLocalGlyph(id) { + // The CJK Unified Ideographs blocks and Hangul Syllables blocks are + // spread across many glyph PBFs and are typically accessed very + // randomly. Preferring local rendering for these blocks reduces + // wasteful bandwidth consumption. For visual consistency within CJKV + // text, also include any other CJKV or siniform ideograph or hangul, + // hiragana, or katakana character. + return !!this.localIdeographFontFamily && + /\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(id)); + } + _tinySDF(entry, stack, id) { + const fontFamily = this.localIdeographFontFamily; + if (!fontFamily) { + return; + } + if (!this._doesCharSupportLocalGlyph(id)) { + return; + } + // Client-generated glyphs are rendered at 2x texture scale, + // because CJK glyphs are more detailed than others. + const textureScale = 2; + let tinySDF = entry.tinySDF; + if (!tinySDF) { + let fontWeight = '400'; + if (/bold/i.test(stack)) { + fontWeight = '900'; + } + else if (/medium/i.test(stack)) { + fontWeight = '500'; + } + else if (/light/i.test(stack)) { + fontWeight = '200'; + } + tinySDF = entry.tinySDF = new GlyphManager.TinySDF({ + fontSize: 24 * textureScale, + buffer: 3 * textureScale, + radius: 8 * textureScale, + cutoff: 0.25, + fontFamily, + fontWeight + }); + } + const char = tinySDF.draw(String.fromCharCode(id)); + /** + * TinySDF's "top" is the distance from the alphabetic baseline to the top of the glyph. + * Server-generated fonts specify "top" relative to an origin above the em box (the origin + * comes from FreeType, but I'm unclear on exactly how it's derived) + * ref: https://github.com/mapbox/sdf-glyph-foundry + * + * Server fonts don't yet include baseline information, so we can't line up exactly with them + * (and they don't line up with each other) + * ref: https://github.com/mapbox/node-fontnik/pull/160 + * + * To approximately align TinySDF glyphs with server-provided glyphs, we use this baseline adjustment + * factor calibrated to be in between DIN Pro and Arial Unicode (but closer to Arial Unicode) + */ + const topAdjustment = 27.5; + const leftAdjustment = 0.5; + return { + id, + bitmap: new AlphaImage({ width: char.width || 30 * textureScale, height: char.height || 30 * textureScale }, char.data), + metrics: { + width: char.glyphWidth / textureScale || 24, + height: char.glyphHeight / textureScale || 24, + left: (char.glyphLeft / textureScale + leftAdjustment) || 0, + top: char.glyphTop / textureScale - topAdjustment || -8, + advance: char.glyphAdvance / textureScale || 24, + isDoubleResolution: true + } + }; + } +} +// exposed as statics to enable stubbing in unit tests +GlyphManager.loadGlyphRange = loadGlyphRange; +GlyphManager.TinySDF = TinySDF; + +class LightPositionProperty { + constructor() { + this.specification = v8Spec.light.position; + } + possiblyEvaluate(value, parameters) { + return sphericalToCartesian(value.expression.evaluate(parameters)); + } + interpolate(a, b, t) { + return { + x: interpolate.number(a.x, b.x, t), + y: interpolate.number(a.y, b.y, t), + z: interpolate.number(a.z, b.z, t), + }; + } +} +const TRANSITION_SUFFIX$1 = '-transition'; +let lightProperties; +/* + * Represents the light used to light extruded features. + */ +class Light extends Evented { + constructor(lightOptions) { + super(); + lightProperties = lightProperties || new Properties({ + 'anchor': new DataConstantProperty(v8Spec.light.anchor), + 'position': new LightPositionProperty(), + 'color': new DataConstantProperty(v8Spec.light.color), + 'intensity': new DataConstantProperty(v8Spec.light.intensity), + }); + this._transitionable = new Transitionable(lightProperties); + this.setLight(lightOptions); + this._transitioning = this._transitionable.untransitioned(); + } + getLight() { + return this._transitionable.serialize(); + } + setLight(light, options = {}) { + if (this._validate(validateLight, light, options)) { + return; + } + for (const name in light) { + const value = light[name]; + if (name.endsWith(TRANSITION_SUFFIX$1)) { + this._transitionable.setTransition(name.slice(0, -TRANSITION_SUFFIX$1.length), value); + } + else { + this._transitionable.setValue(name, value); + } + } + } + updateTransitions(parameters) { + this._transitioning = this._transitionable.transitioned(parameters, this._transitioning); + } + hasTransition() { + return this._transitioning.hasTransition(); + } + recalculate(parameters) { + this.properties = this._transitioning.possiblyEvaluate(parameters); + } + _validate(validate, value, options) { + if (options && options.validate === false) { + return false; + } + return emitValidationErrors$1(this, validate.call(validateStyle, { + value, + // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407 + style: { glyphs: true, sprite: true }, + styleSpec: v8Spec + })); + } +} + +const properties = new Properties({ + 'sky-color': new DataConstantProperty(v8Spec.sky['sky-color']), + 'horizon-color': new DataConstantProperty(v8Spec.sky['horizon-color']), + 'fog-color': new DataConstantProperty(v8Spec.sky['fog-color']), + 'fog-ground-blend': new DataConstantProperty(v8Spec.sky['fog-ground-blend']), + 'horizon-fog-blend': new DataConstantProperty(v8Spec.sky['horizon-fog-blend']), + 'sky-horizon-blend': new DataConstantProperty(v8Spec.sky['sky-horizon-blend']), + 'atmosphere-blend': new DataConstantProperty(v8Spec.sky['atmosphere-blend']) +}); +const TRANSITION_SUFFIX = '-transition'; +class Sky extends Evented { + constructor(sky) { + super(); + this._transitionable = new Transitionable(properties); + this.setSky(sky); + this._transitioning = this._transitionable.untransitioned(); + this.recalculate(new EvaluationParameters(0)); + } + setSky(sky, options = {}) { + if (this._validate(validateSky, sky, options)) + return; + if (!sky) { + sky = { + 'sky-color': 'transparent', + 'horizon-color': 'transparent', + 'fog-color': 'transparent', + 'fog-ground-blend': 1, + 'atmosphere-blend': 0, + }; + } + for (const name in sky) { + const value = sky[name]; + if (name.endsWith(TRANSITION_SUFFIX)) { + this._transitionable.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), value); + } + else { + this._transitionable.setValue(name, value); + } + } + } + getSky() { + return this._transitionable.serialize(); + } + updateTransitions(parameters) { + this._transitioning = this._transitionable.transitioned(parameters, this._transitioning); + } + hasTransition() { + return this._transitioning.hasTransition(); + } + recalculate(parameters) { + this.properties = this._transitioning.possiblyEvaluate(parameters); + } + _validate(validate, value, options = {}) { + if ((options === null || options === void 0 ? void 0 : options.validate) === false) { + return false; + } + return emitValidationErrors$1(this, validate.call(validateStyle, extend({ + value, + // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407 + style: { glyphs: true, sprite: true }, + styleSpec: v8Spec + }))); + } + /** + * Currently fog is a very simple implementation, and should only used + * to create an atmosphere near the horizon. + * But because the fog is drawn from the far-clipping-plane to + * map-center, and because the fog does nothing know about the horizon, + * this method does a fadeout in respect of pitch. So, when the horizon + * gets out of view, which is at about pitch 70, this methods calculates + * the corresponding opacity values. Below pitch 60 the fog is completely + * invisible. + */ + calculateFogBlendOpacity(pitch) { + if (pitch < 60) + return 0; // disable + if (pitch < 70) + return (pitch - 60) / 10; // fade in + return 1; + } +} + +/** + * @internal + * A LineAtlas lets us reuse rendered dashed lines + * by writing many of them to a texture and then fetching their positions + * using {@link LineAtlas#getDash}. + * + * @param width - the width + * @param height - the height + */ +class LineAtlas { + constructor(width, height) { + this.width = width; + this.height = height; + this.nextRow = 0; + this.data = new Uint8Array(this.width * this.height); + this.dashEntry = {}; + } + /** + * Get or create a dash line pattern. + * + * @param dasharray - the key (represented by numbers) to get the dash texture + * @param round - whether to add circle caps in between dash segments + * @returns position of dash texture in {@link DashEntry} + */ + getDash(dasharray, round) { + const key = dasharray.join(',') + String(round); + if (!this.dashEntry[key]) { + this.dashEntry[key] = this.addDash(dasharray, round); + } + return this.dashEntry[key]; + } + getDashRanges(dasharray, lineAtlasWidth, stretch) { + // If dasharray has an odd length, both the first and last parts + // are dashes and should be joined seamlessly. + const oddDashArray = dasharray.length % 2 === 1; + const ranges = []; + let left = oddDashArray ? -dasharray[dasharray.length - 1] * stretch : 0; + let right = dasharray[0] * stretch; + let isDash = true; + ranges.push({ left, right, isDash, zeroLength: dasharray[0] === 0 }); + let currentDashLength = dasharray[0]; + for (let i = 1; i < dasharray.length; i++) { + isDash = !isDash; + const dashLength = dasharray[i]; + left = currentDashLength * stretch; + currentDashLength += dashLength; + right = currentDashLength * stretch; + ranges.push({ left, right, isDash, zeroLength: dashLength === 0 }); + } + return ranges; + } + addRoundDash(ranges, stretch, n) { + const halfStretch = stretch / 2; + for (let y = -n; y <= n; y++) { + const row = this.nextRow + n + y; + const index = this.width * row; + let currIndex = 0; + let range = ranges[currIndex]; + for (let x = 0; x < this.width; x++) { + if (x / range.right > 1) { + range = ranges[++currIndex]; + } + const distLeft = Math.abs(x - range.left); + const distRight = Math.abs(x - range.right); + const minDist = Math.min(distLeft, distRight); + let signedDistance; + const distMiddle = y / n * (halfStretch + 1); + if (range.isDash) { + const distEdge = halfStretch - Math.abs(distMiddle); + signedDistance = Math.sqrt(minDist * minDist + distEdge * distEdge); + } + else { + signedDistance = halfStretch - Math.sqrt(minDist * minDist + distMiddle * distMiddle); + } + this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128)); + } + } + } + addRegularDash(ranges) { + // Collapse any zero-length range + // Collapse neighbouring same-type parts into a single part + for (let i = ranges.length - 1; i >= 0; --i) { + const part = ranges[i]; + const next = ranges[i + 1]; + if (part.zeroLength) { + ranges.splice(i, 1); + } + else if (next && next.isDash === part.isDash) { + next.left = part.left; + ranges.splice(i, 1); + } + } + // Combine the first and last parts if possible + const first = ranges[0]; + const last = ranges[ranges.length - 1]; + if (first.isDash === last.isDash) { + first.left = last.left - this.width; + last.right = first.right + this.width; + } + const index = this.width * this.nextRow; + let currIndex = 0; + let range = ranges[currIndex]; + for (let x = 0; x < this.width; x++) { + if (x / range.right > 1) { + range = ranges[++currIndex]; + } + const distLeft = Math.abs(x - range.left); + const distRight = Math.abs(x - range.right); + const minDist = Math.min(distLeft, distRight); + const signedDistance = range.isDash ? minDist : -minDist; + this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128)); + } + } + addDash(dasharray, round) { + const n = round ? 7 : 0; + const height = 2 * n + 1; + if (this.nextRow + height > this.height) { + warnOnce('LineAtlas out of space'); + return null; + } + let length = 0; + for (let i = 0; i < dasharray.length; i++) { + length += dasharray[i]; + } + if (length !== 0) { + const stretch = this.width / length; + const ranges = this.getDashRanges(dasharray, this.width, stretch); + if (round) { + this.addRoundDash(ranges, stretch, n); + } + else { + this.addRegularDash(ranges); + } + } + const dashEntry = { + y: (this.nextRow + n + 0.5) / this.height, + height: 2 * n / this.height, + width: length + }; + this.nextRow += height; + this.dirty = true; + return dashEntry; + } + bind(context) { + const gl = context.gl; + if (!this.texture) { + this.texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, this.width, this.height, 0, gl.ALPHA, gl.UNSIGNED_BYTE, this.data); + } + else { + gl.bindTexture(gl.TEXTURE_2D, this.texture); + if (this.dirty) { + this.dirty = false; + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.width, this.height, gl.ALPHA, gl.UNSIGNED_BYTE, this.data); + } + } + } +} + +/** + * Invokes the wrapped function in a non-blocking way when trigger() is called. + * Invocation requests are ignored until the function was actually invoked. + */ +class ThrottledInvoker { + constructor(methodToThrottle) { + this._methodToThrottle = methodToThrottle; + this._triggered = false; + if (typeof MessageChannel !== 'undefined') { + this._channel = new MessageChannel(); + this._channel.port2.onmessage = () => { + this._triggered = false; + this._methodToThrottle(); + }; + } + } + trigger() { + if (this._triggered) { + return; + } + this._triggered = true; + if (this._channel) { + this._channel.port1.postMessage(true); + } + else { + setTimeout(() => { + this._triggered = false; + this._methodToThrottle(); + }, 0); + } + } + remove() { + delete this._channel; + this._methodToThrottle = () => { }; + } +} + +/** + * An implementation of the [Actor design pattern](https://en.wikipedia.org/wiki/Actor_model) + * that maintains the relationship between asynchronous tasks and the objects + * that spin them off - in this case, tasks like parsing parts of styles, + * owned by the styles + */ +class Actor { + /** + * @param target - The target + * @param mapId - A unique identifier for the Map instance using this Actor. + */ + constructor(target, mapId) { + this.target = target; + this.mapId = mapId; + this.resolveRejects = {}; + this.tasks = {}; + this.taskQueue = []; + this.abortControllers = {}; + this.messageHandlers = {}; + this.invoker = new ThrottledInvoker(() => this.process()); + this.subscription = subscribe(this.target, 'message', (message) => this.receive(message), false); + this.globalScope = isWorker(self) ? target : window; + } + registerMessageHandler(type, handler) { + this.messageHandlers[type] = handler; + } + /** + * Sends a message from a main-thread map to a Worker or from a Worker back to + * a main-thread map instance. + * @param message - the message to send + * @param abortController - an optional AbortController to abort the request + * @returns a promise that will be resolved with the response data + */ + sendAsync(message, abortController) { + return new Promise((resolve, reject) => { + // We're using a string ID instead of numbers because they are being used as object keys + // anyway, and thus stringified implicitly. We use random IDs because an actor may receive + // message from multiple other actors which could run in different execution context. A + // linearly increasing ID could produce collisions. + const id = Math.round((Math.random() * 1e18)).toString(36).substring(0, 10); + this.resolveRejects[id] = { + resolve, + reject + }; + if (abortController) { + abortController.signal.addEventListener('abort', () => { + delete this.resolveRejects[id]; + const cancelMessage = { + id, + type: '', + origin: location.origin, + targetMapId: message.targetMapId, + sourceMapId: this.mapId + }; + this.target.postMessage(cancelMessage); + // In case of abort the current behavior is to keep the promise pending. + }, { once: true }); + } + const buffers = []; + const messageToPost = Object.assign(Object.assign({}, message), { id, sourceMapId: this.mapId, origin: location.origin, data: serialize(message.data, buffers) }); + this.target.postMessage(messageToPost, { transfer: buffers }); + }); + } + receive(message) { + const data = message.data; + const id = data.id; + if (data.origin !== 'file://' && location.origin !== 'file://' && data.origin !== 'resource://android' && location.origin !== 'resource://android' && data.origin !== location.origin) { + return; + } + if (data.targetMapId && this.mapId !== data.targetMapId) { + return; + } + if (data.type === '') { + // Remove the original request from the queue. This is only possible if it + // hasn't been kicked off yet. The id will remain in the queue, but because + // there is no associated task, it will be dropped once it's time to execute it. + delete this.tasks[id]; + const abortController = this.abortControllers[id]; + delete this.abortControllers[id]; + if (abortController) { + abortController.abort(); + } + return; + } + if (isWorker(self) || data.mustQueue) { + // In workers, store the tasks that we need to process before actually processing them. This + // is necessary because we want to keep receiving messages, and in particular, + // messages. Some tasks may take a while in the worker thread, so before + // executing the next task in our queue, postMessage preempts this and + // messages can be processed. We're using a MessageChannel object to get throttle the + // process() flow to one at a time. + this.tasks[id] = data; + this.taskQueue.push(id); + this.invoker.trigger(); + return; + } + // In the main thread, process messages immediately so that other work does not slip in + // between getting partial data back from workers. + this.processTask(id, data); + } + process() { + if (this.taskQueue.length === 0) { + return; + } + const id = this.taskQueue.shift(); + const task = this.tasks[id]; + delete this.tasks[id]; + // Schedule another process call if we know there's more to process _before_ invoking the + // current task. This is necessary so that processing continues even if the current task + // doesn't execute successfully. + if (this.taskQueue.length > 0) { + this.invoker.trigger(); + } + if (!task) { + // If the task ID doesn't have associated task data anymore, it was canceled. + return; + } + this.processTask(id, task); + } + processTask(id, task) { + return __awaiter(this, void 0, void 0, function* () { + if (task.type === '') { + // The `completeTask` function in the counterpart actor has been called, and we are now + // resolving or rejecting the promise in the originating actor, if there is one. + const resolveReject = this.resolveRejects[id]; + delete this.resolveRejects[id]; + if (!resolveReject) { + // If we get a response, but don't have a resolve or reject, the request was canceled. + return; + } + if (task.error) { + resolveReject.reject(deserialize$1(task.error)); + } + else { + resolveReject.resolve(deserialize$1(task.data)); + } + return; + } + if (!this.messageHandlers[task.type]) { + this.completeTask(id, new Error(`Could not find a registered handler for ${task.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(', ')}`)); + return; + } + const params = deserialize$1(task.data); + const abortController = new AbortController(); + this.abortControllers[id] = abortController; + try { + const data = yield this.messageHandlers[task.type](task.sourceMapId, params, abortController); + this.completeTask(id, null, data); + } + catch (err) { + this.completeTask(id, err); + } + }); + } + completeTask(id, err, data) { + const buffers = []; + delete this.abortControllers[id]; + const responseMessage = { + id, + type: '', + sourceMapId: this.mapId, + origin: location.origin, + error: err ? serialize(err) : null, + data: serialize(data, buffers) + }; + this.target.postMessage(responseMessage, { transfer: buffers }); + } + remove() { + this.invoker.remove(); + this.subscription.unsubscribe(); + } +} + +function workerFactory() { + return new Worker(config.WORKER_URL); +} + +const PRELOAD_POOL_ID = 'maplibre_preloaded_worker_pool'; +/** + * Constructs a worker pool. + */ +class WorkerPool { + constructor() { + this.active = {}; + } + acquire(mapId) { + if (!this.workers) { + // Lazily look up the value of getWorkerCount so that + // client code has had a chance to set it. + this.workers = []; + while (this.workers.length < WorkerPool.workerCount) { + this.workers.push(workerFactory()); + } + } + this.active[mapId] = true; + return this.workers.slice(); + } + release(mapId) { + delete this.active[mapId]; + if (this.numActive() === 0) { + this.workers.forEach((w) => { + w.terminate(); + }); + this.workers = null; + } + } + isPreloaded() { + return !!this.active[PRELOAD_POOL_ID]; + } + numActive() { + return Object.keys(this.active).length; + } +} +// Based on results from A/B testing: https://github.com/maplibre/maplibre-gl-js/pull/2354 +const availableLogicalProcessors = Math.floor(browser.hardwareConcurrency / 2); +WorkerPool.workerCount = isSafari(globalThis) ? Math.max(Math.min(availableLogicalProcessors, 3), 1) : 1; + +let globalWorkerPool; +/** + * Creates (if necessary) and returns the single, global WorkerPool instance + * to be shared across each Map + */ +function getGlobalWorkerPool() { + if (!globalWorkerPool) { + globalWorkerPool = new WorkerPool(); + } + return globalWorkerPool; +} +/** + * Initializes resources like WebWorkers that can be shared across maps to lower load + * times in some situations. `setWorkerUrl()` and `setWorkerCount()`, if being + * used, must be set before `prewarm()` is called to have an effect. + * + * By default, the lifecycle of these resources is managed automatically, and they are + * lazily initialized when a Map is first created. By invoking `prewarm()`, these + * resources will be created ahead of time, and will not be cleared when the last Map + * is removed from the page. This allows them to be re-used by new Map instances that + * are created later. They can be manually cleared by calling + * `clearPrewarmedResources()`. This is only necessary if your web page remains + * active but stops using maps altogether. + * + * This is primarily useful when using GL-JS maps in a single page app, wherein a user + * would navigate between various views that can cause Map instances to constantly be + * created and destroyed. + * + * @example + * ```ts + * prewarm() + * ``` + */ +function prewarm() { + const workerPool = getGlobalWorkerPool(); + workerPool.acquire(PRELOAD_POOL_ID); +} +/** + * Clears up resources that have previously been created by `prewarm()`. + * Note that this is typically not necessary. You should only call this function + * if you expect the user of your app to not return to a Map view at any point + * in your application. + * + * @example + * ```ts + * clearPrewarmedResources() + * ``` + */ +function clearPrewarmedResources() { + const pool = globalWorkerPool; + if (pool) { + // Remove the pool only if all maps that referenced the preloaded global worker pool have been removed. + if (pool.isPreloaded() && pool.numActive() === 1) { + pool.release(PRELOAD_POOL_ID); + globalWorkerPool = null; + } + else { + 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()'); + } + } +} + +/** + * Responsible for sending messages from a {@link Source} to an associated + * {@link WorkerSource}. + */ +class Dispatcher { + constructor(workerPool, mapId) { + this.workerPool = workerPool; + this.actors = []; + this.currentActor = 0; + this.id = mapId; + const workers = this.workerPool.acquire(mapId); + for (let i = 0; i < workers.length; i++) { + const worker = workers[i]; + const actor = new Actor(worker, mapId); + actor.name = `Worker ${i}`; + this.actors.push(actor); + } + if (!this.actors.length) + throw new Error('No actors found'); + } + /** + * Broadcast a message to all Workers. + */ + broadcast(type, data) { + const promises = []; + for (const actor of this.actors) { + promises.push(actor.sendAsync({ type, data })); + } + return Promise.all(promises); + } + /** + * Acquires an actor to dispatch messages to. The actors are distributed in round-robin fashion. + * @returns An actor object backed by a web worker for processing messages. + */ + getActor() { + this.currentActor = (this.currentActor + 1) % this.actors.length; + return this.actors[this.currentActor]; + } + remove(mapRemoved = true) { + this.actors.forEach((actor) => { actor.remove(); }); + this.actors = []; + if (mapRemoved) + this.workerPool.release(this.id); + } + registerMessageHandler(type, handler) { + for (const actor of this.actors) { + actor.registerMessageHandler(type, handler); + } + } +} +let globalDispatcher; +function getGlobalDispatcher() { + if (!globalDispatcher) { + globalDispatcher = new Dispatcher(getGlobalWorkerPool(), GLOBAL_DISPATCHER_ID); + globalDispatcher.registerMessageHandler("GR" /* MessageType.getResource */, (_mapId, params, abortController) => { + return makeRequest(params, abortController); + }); + } + return globalDispatcher; +} + +/* + * Returns a matrix that can be used to convert from tile coordinates to viewport pixel coordinates. + */ +function getPixelPosMatrix(transform, tileID) { + const t = create$6(); + translate$1(t, t, [1, 1, 0]); + scale$5(t, t, [transform.width * 0.5, transform.height * 0.5, 1]); + return multiply$5(t, t, transform.calculatePosMatrix(tileID.toUnwrapped())); +} +function queryIncludes3DLayer(layers, styleLayers, sourceID) { + if (layers) { + for (const layerID of layers) { + const layer = styleLayers[layerID]; + if (layer && layer.source === sourceID && layer.type === 'fill-extrusion') { + return true; + } + } + } + else { + for (const key in styleLayers) { + const layer = styleLayers[key]; + if (layer.source === sourceID && layer.type === 'fill-extrusion') { + return true; + } + } + } + return false; +} +function queryRenderedFeatures(sourceCache, styleLayers, serializedLayers, queryGeometry, params, transform) { + const has3DLayer = queryIncludes3DLayer(params && params.layers, styleLayers, sourceCache.id); + const maxPitchScaleFactor = transform.maxPitchScaleFactor(); + const tilesIn = sourceCache.tilesIn(queryGeometry, maxPitchScaleFactor, has3DLayer); + tilesIn.sort(sortTilesIn); + const renderedFeatureLayers = []; + for (const tileIn of tilesIn) { + renderedFeatureLayers.push({ + wrappedTileID: tileIn.tileID.wrapped().key, + queryResults: tileIn.tile.queryRenderedFeatures(styleLayers, serializedLayers, sourceCache._state, tileIn.queryGeometry, tileIn.cameraQueryGeometry, tileIn.scale, params, transform, maxPitchScaleFactor, getPixelPosMatrix(sourceCache.transform, tileIn.tileID)) + }); + } + const result = mergeRenderedFeatureLayers(renderedFeatureLayers); + // Merge state from SourceCache into the results + for (const layerID in result) { + result[layerID].forEach((featureWrapper) => { + const feature = featureWrapper.feature; + const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id); + feature.source = feature.layer.source; + if (feature.layer['source-layer']) { + feature.sourceLayer = feature.layer['source-layer']; + } + feature.state = state; + }); + } + return result; +} +function queryRenderedSymbols(styleLayers, serializedLayers, sourceCaches, queryGeometry, params, collisionIndex, retainedQueryData) { + const result = {}; + const renderedSymbols = collisionIndex.queryRenderedSymbols(queryGeometry); + const bucketQueryData = []; + for (const bucketInstanceId of Object.keys(renderedSymbols).map(Number)) { + bucketQueryData.push(retainedQueryData[bucketInstanceId]); + } + bucketQueryData.sort(sortTilesIn); + for (const queryData of bucketQueryData) { + const bucketSymbols = queryData.featureIndex.lookupSymbolFeatures(renderedSymbols[queryData.bucketInstanceId], serializedLayers, queryData.bucketIndex, queryData.sourceLayerIndex, params.filter, params.layers, params.availableImages, styleLayers); + for (const layerID in bucketSymbols) { + const resultFeatures = result[layerID] = result[layerID] || []; + const layerSymbols = bucketSymbols[layerID]; + layerSymbols.sort((a, b) => { + // Match topDownFeatureComparator from FeatureIndex, but using + // most recent sorting of features from bucket.sortFeatures + const featureSortOrder = queryData.featureSortOrder; + if (featureSortOrder) { + // queryRenderedSymbols documentation says we'll return features in + // "top-to-bottom" rendering order (aka last-to-first). + // Actually there can be multiple symbol instances per feature, so + // we sort each feature based on the first matching symbol instance. + const sortedA = featureSortOrder.indexOf(a.featureIndex); + const sortedB = featureSortOrder.indexOf(b.featureIndex); + return sortedB - sortedA; + } + else { + // Bucket hasn't been re-sorted based on angle, so use the + // reverse of the order the features appeared in the data. + return b.featureIndex - a.featureIndex; + } + }); + for (const symbolFeature of layerSymbols) { + resultFeatures.push(symbolFeature); + } + } + } + // Merge state from SourceCache into the results + for (const layerName in result) { + result[layerName].forEach((featureWrapper) => { + const feature = featureWrapper.feature; + const layer = styleLayers[layerName]; + const sourceCache = sourceCaches[layer.source]; + const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id); + feature.source = feature.layer.source; + if (feature.layer['source-layer']) { + feature.sourceLayer = feature.layer['source-layer']; + } + feature.state = state; + }); + } + return result; +} +function querySourceFeatures(sourceCache, params) { + const tiles = sourceCache.getRenderableIds().map((id) => { + return sourceCache.getTileByID(id); + }); + const result = []; + const dataTiles = {}; + for (let i = 0; i < tiles.length; i++) { + const tile = tiles[i]; + const dataID = tile.tileID.canonical.key; + if (!dataTiles[dataID]) { + dataTiles[dataID] = true; + tile.querySourceFeatures(result, params); + } + } + return result; +} +function sortTilesIn(a, b) { + const idA = a.tileID; + const idB = b.tileID; + return (idA.overscaledZ - idB.overscaledZ) || (idA.canonical.y - idB.canonical.y) || (idA.wrap - idB.wrap) || (idA.canonical.x - idB.canonical.x); +} +function mergeRenderedFeatureLayers(tiles) { + // Merge results from all tiles, but if two tiles share the same + // wrapped ID, don't duplicate features between the two tiles + const result = {}; + const wrappedIDLayerMap = {}; + for (const tile of tiles) { + const queryResults = tile.queryResults; + const wrappedID = tile.wrappedTileID; + const wrappedIDLayers = wrappedIDLayerMap[wrappedID] = wrappedIDLayerMap[wrappedID] || {}; + for (const layerID in queryResults) { + const tileFeatures = queryResults[layerID]; + const wrappedIDFeatures = wrappedIDLayers[layerID] = wrappedIDLayers[layerID] || {}; + const resultFeatures = result[layerID] = result[layerID] || []; + for (const tileFeature of tileFeatures) { + if (!wrappedIDFeatures[tileFeature.featureIndex]) { + wrappedIDFeatures[tileFeature.featureIndex] = true; + resultFeatures.push(tileFeature); + } + } + } + } + return result; +} + +function loadTileJson(options, requestManager, abortController) { + return __awaiter(this, void 0, void 0, function* () { + let tileJSON = options; + if (options.url) { + const response = yield getJSON(requestManager.transformRequest(options.url, "Source" /* ResourceType.Source */), abortController); + tileJSON = response.data; + } + else { + yield browser.frameAsync(abortController); + } + if (!tileJSON) { + return null; + } + const result = pick( + // explicit source options take precedence over TileJSON + extend(tileJSON, options), ['tiles', 'minzoom', 'maxzoom', 'attribution', 'bounds', 'scheme', 'tileSize', 'encoding']); + if ('vector_layers' in tileJSON && tileJSON.vector_layers) { + result.vectorLayerIds = tileJSON.vector_layers.map((layer) => { return layer.id; }); + } + return result; + }); +} + +/* +* Approximate radius of the earth in meters. +* 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 +* 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 +*/ +const earthRadius = 6371008.8; +/** + * A `LngLat` object represents a given longitude and latitude coordinate, measured in degrees. + * These coordinates are based on the [WGS84 (EPSG:4326) standard](https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84). + * + * MapLibre GL JS uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match the + * [GeoJSON specification](https://tools.ietf.org/html/rfc7946). + * + * Note that any MapLibre GL JS method that accepts a `LngLat` object as an argument or option + * can also accept an `Array` of two numbers and will perform an implicit conversion. + * This flexible type is documented as {@link LngLatLike}. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let ll = new LngLat(-123.9749, 40.7736); + * ll.lng; // = -123.9749 + * ``` + * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/) + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Create a timeline animation](https://maplibre.org/maplibre-gl-js/docs/examples/timeline-animation/) + */ +class LngLat { + /** + * @param lng - Longitude, measured in degrees. + * @param lat - Latitude, measured in degrees. + */ + constructor(lng, lat) { + if (isNaN(lng) || isNaN(lat)) { + throw new Error(`Invalid LngLat object: (${lng}, ${lat})`); + } + this.lng = +lng; + this.lat = +lat; + if (this.lat > 90 || this.lat < -90) { + throw new Error('Invalid LngLat latitude value: must be between -90 and 90'); + } + } + /** + * Returns a new `LngLat` object whose longitude is wrapped to the range (-180, 180). + * + * @returns The wrapped `LngLat` object. + * @example + * ```ts + * let ll = new LngLat(286.0251, 40.7736); + * let wrapped = ll.wrap(); + * wrapped.lng; // = -73.9749 + * ``` + */ + wrap() { + return new LngLat(wrap(this.lng, -180, 180), this.lat); + } + /** + * Returns the coordinates represented as an array of two numbers. + * + * @returns The coordinates represented as an array of longitude and latitude. + * @example + * ```ts + * let ll = new LngLat(-73.9749, 40.7736); + * ll.toArray(); // = [-73.9749, 40.7736] + * ``` + */ + toArray() { + return [this.lng, this.lat]; + } + /** + * Returns the coordinates represent as a string. + * + * @returns The coordinates represented as a string of the format `'LngLat(lng, lat)'`. + * @example + * ```ts + * let ll = new LngLat(-73.9749, 40.7736); + * ll.toString(); // = "LngLat(-73.9749, 40.7736)" + * ``` + */ + toString() { + return `LngLat(${this.lng}, ${this.lat})`; + } + /** + * Returns the approximate distance between a pair of coordinates in meters + * Uses the Haversine Formula (from R.W. Sinnott, "Virtues of the Haversine", Sky and Telescope, vol. 68, no. 2, 1984, p. 159) + * + * @param lngLat - coordinates to compute the distance to + * @returns Distance in meters between the two coordinates. + * @example + * ```ts + * let new_york = new LngLat(-74.0060, 40.7128); + * let los_angeles = new LngLat(-118.2437, 34.0522); + * new_york.distanceTo(los_angeles); // = 3935751.690893987, "true distance" using a non-spherical approximation is ~3966km + * ``` + */ + distanceTo(lngLat) { + const rad = Math.PI / 180; + const lat1 = this.lat * rad; + const lat2 = lngLat.lat * rad; + const a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((lngLat.lng - this.lng) * rad); + const maxMeters = earthRadius * Math.acos(Math.min(a, 1)); + return maxMeters; + } + /** + * Converts an array of two numbers or an object with `lng` and `lat` or `lon` and `lat` properties + * to a `LngLat` object. + * + * If a `LngLat` object is passed in, the function returns it unchanged. + * + * @param input - An array of two numbers or object to convert, or a `LngLat` object to return. + * @returns A new `LngLat` object, if a conversion occurred, or the original `LngLat` object. + * @example + * ```ts + * let arr = [-73.9749, 40.7736]; + * let ll = LngLat.convert(arr); + * ll; // = LngLat {lng: -73.9749, lat: 40.7736} + * ``` + */ + static convert(input) { + if (input instanceof LngLat) { + return input; + } + if (Array.isArray(input) && (input.length === 2 || input.length === 3)) { + return new LngLat(Number(input[0]), Number(input[1])); + } + if (!Array.isArray(input) && typeof input === 'object' && input !== null) { + return new LngLat( + // flow can't refine this to have one of lng or lat, so we have to cast to any + Number('lng' in input ? input.lng : input.lon), Number(input.lat)); + } + throw new Error('`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]'); + } +} + +/** + * A `LngLatBounds` object represents a geographical bounding box, + * defined by its southwest and northeast points in longitude and latitude. + * + * If no arguments are provided to the constructor, a `null` bounding box is created. + * + * Note that any Mapbox GL method that accepts a `LngLatBounds` object as an argument or option + * can also accept an `Array` of two {@link LngLatLike} constructs and will perform an implicit conversion. + * This flexible type is documented as {@link LngLatBoundsLike}. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let sw = new LngLat(-73.9876, 40.7661); + * let ne = new LngLat(-73.9397, 40.8002); + * let llb = new LngLatBounds(sw, ne); + * ``` + */ +class LngLatBounds { + /** + * @param sw - The southwest corner of the bounding box. + * OR array of 4 numbers in the order of west, south, east, north + * OR array of 2 LngLatLike: [sw,ne] + * @param ne - The northeast corner of the bounding box. + * @example + * ```ts + * let sw = new LngLat(-73.9876, 40.7661); + * let ne = new LngLat(-73.9397, 40.8002); + * let llb = new LngLatBounds(sw, ne); + * ``` + * OR + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661, -73.9397, 40.8002]); + * ``` + * OR + * ```ts + * let llb = new LngLatBounds([sw, ne]); + * ``` + */ + constructor(sw, ne) { + if (!sw) { + // noop + } + else if (ne) { + this.setSouthWest(sw).setNorthEast(ne); + } + else if (Array.isArray(sw)) { + if (sw.length === 4) { + // 4 element array: west, south, east, north + this.setSouthWest([sw[0], sw[1]]).setNorthEast([sw[2], sw[3]]); + } + else { + this.setSouthWest(sw[0]).setNorthEast(sw[1]); + } + } + } + /** + * Set the northeast corner of the bounding box + * + * @param ne - a {@link LngLatLike} object describing the northeast corner of the bounding box. + */ + setNorthEast(ne) { + this._ne = ne instanceof LngLat ? new LngLat(ne.lng, ne.lat) : LngLat.convert(ne); + return this; + } + /** + * Set the southwest corner of the bounding box + * + * @param sw - a {@link LngLatLike} object describing the southwest corner of the bounding box. + */ + setSouthWest(sw) { + this._sw = sw instanceof LngLat ? new LngLat(sw.lng, sw.lat) : LngLat.convert(sw); + return this; + } + /** + * Extend the bounds to include a given LngLatLike or LngLatBoundsLike. + * + * @param obj - object to extend to + */ + extend(obj) { + const sw = this._sw, ne = this._ne; + let sw2, ne2; + if (obj instanceof LngLat) { + sw2 = obj; + ne2 = obj; + } + else if (obj instanceof LngLatBounds) { + sw2 = obj._sw; + ne2 = obj._ne; + if (!sw2 || !ne2) + return this; + } + else { + if (Array.isArray(obj)) { + if (obj.length === 4 || obj.every(Array.isArray)) { + const lngLatBoundsObj = obj; + return this.extend(LngLatBounds.convert(lngLatBoundsObj)); + } + else { + const lngLatObj = obj; + return this.extend(LngLat.convert(lngLatObj)); + } + } + else if (obj && ('lng' in obj || 'lon' in obj) && 'lat' in obj) { + return this.extend(LngLat.convert(obj)); + } + return this; + } + if (!sw && !ne) { + this._sw = new LngLat(sw2.lng, sw2.lat); + this._ne = new LngLat(ne2.lng, ne2.lat); + } + else { + sw.lng = Math.min(sw2.lng, sw.lng); + sw.lat = Math.min(sw2.lat, sw.lat); + ne.lng = Math.max(ne2.lng, ne.lng); + ne.lat = Math.max(ne2.lat, ne.lat); + } + return this; + } + /** + * Returns the geographical coordinate equidistant from the bounding box's corners. + * + * @returns The bounding box's center. + * @example + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]); + * llb.getCenter(); // = LngLat {lng: -73.96365, lat: 40.78315} + * ``` + */ + getCenter() { + return new LngLat((this._sw.lng + this._ne.lng) / 2, (this._sw.lat + this._ne.lat) / 2); + } + /** + * Returns the southwest corner of the bounding box. + * + * @returns The southwest corner of the bounding box. + */ + getSouthWest() { return this._sw; } + /** + * Returns the northeast corner of the bounding box. + * + * @returns The northeast corner of the bounding box. + */ + getNorthEast() { return this._ne; } + /** + * Returns the northwest corner of the bounding box. + * + * @returns The northwest corner of the bounding box. + */ + getNorthWest() { return new LngLat(this.getWest(), this.getNorth()); } + /** + * Returns the southeast corner of the bounding box. + * + * @returns The southeast corner of the bounding box. + */ + getSouthEast() { return new LngLat(this.getEast(), this.getSouth()); } + /** + * Returns the west edge of the bounding box. + * + * @returns The west edge of the bounding box. + */ + getWest() { return this._sw.lng; } + /** + * Returns the south edge of the bounding box. + * + * @returns The south edge of the bounding box. + */ + getSouth() { return this._sw.lat; } + /** + * Returns the east edge of the bounding box. + * + * @returns The east edge of the bounding box. + */ + getEast() { return this._ne.lng; } + /** + * Returns the north edge of the bounding box. + * + * @returns The north edge of the bounding box. + */ + getNorth() { return this._ne.lat; } + /** + * Returns the bounding box represented as an array. + * + * @returns The bounding box represented as an array, consisting of the + * southwest and northeast coordinates of the bounding represented as arrays of numbers. + * @example + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]); + * llb.toArray(); // = [[-73.9876, 40.7661], [-73.9397, 40.8002]] + * ``` + */ + toArray() { + return [this._sw.toArray(), this._ne.toArray()]; + } + /** + * Return the bounding box represented as a string. + * + * @returns The bounding box represents as a string of the format + * `'LngLatBounds(LngLat(lng, lat), LngLat(lng, lat))'`. + * @example + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]); + * llb.toString(); // = "LngLatBounds(LngLat(-73.9876, 40.7661), LngLat(-73.9397, 40.8002))" + * ``` + */ + toString() { + return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`; + } + /** + * Check if the bounding box is an empty/`null`-type box. + * + * @returns True if bounds have been defined, otherwise false. + */ + isEmpty() { + return !(this._sw && this._ne); + } + /** + * Check if the point is within the bounding box. + * + * @param lnglat - geographic point to check against. + * @returns `true` if the point is within the bounding box. + * @example + * ```ts + * let llb = new LngLatBounds( + * new LngLat(-73.9876, 40.7661), + * new LngLat(-73.9397, 40.8002) + * ); + * + * let ll = new LngLat(-73.9567, 40.7789); + * + * console.log(llb.contains(ll)); // = true + * ``` + */ + contains(lnglat) { + const { lng, lat } = LngLat.convert(lnglat); + const containsLatitude = this._sw.lat <= lat && lat <= this._ne.lat; + let containsLongitude = this._sw.lng <= lng && lng <= this._ne.lng; + if (this._sw.lng > this._ne.lng) { // wrapped coordinates + containsLongitude = this._sw.lng >= lng && lng >= this._ne.lng; + } + return containsLatitude && containsLongitude; + } + /** + * Converts an array to a `LngLatBounds` object. + * + * If a `LngLatBounds` object is passed in, the function returns it unchanged. + * + * Internally, the function calls `LngLat#convert` to convert arrays to `LngLat` values. + * + * @param input - An array of two coordinates to convert, or a `LngLatBounds` object to return. + * @returns A new `LngLatBounds` object, if a conversion occurred, or the original `LngLatBounds` object. + * @example + * ```ts + * let arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]]; + * let llb = LngLatBounds.convert(arr); // = LngLatBounds {_sw: LngLat {lng: -73.9876, lat: 40.7661}, _ne: LngLat {lng: -73.9397, lat: 40.8002}} + * ``` + */ + static convert(input) { + if (input instanceof LngLatBounds) + return input; + if (!input) + return input; + return new LngLatBounds(input); + } + /** + * Returns a `LngLatBounds` from the coordinates extended by a given `radius`. The returned `LngLatBounds` completely contains the `radius`. + * + * @param center - center coordinates of the new bounds. + * @param radius - Distance in meters from the coordinates to extend the bounds. + * @returns A new `LngLatBounds` object representing the coordinates extended by the `radius`. + * @example + * ```ts + * let center = new LngLat(-73.9749, 40.7736); + * LngLatBounds.fromLngLat(100).toArray(); // = [[-73.97501862141328, 40.77351016847229], [-73.97478137858673, 40.77368983152771]] + * ``` + */ + static fromLngLat(center, radius = 0) { + const earthCircumferenceInMetersAtEquator = 40075017; + const latAccuracy = 360 * radius / earthCircumferenceInMetersAtEquator, lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * center.lat); + return new LngLatBounds(new LngLat(center.lng - lngAccuracy, center.lat - latAccuracy), new LngLat(center.lng + lngAccuracy, center.lat + latAccuracy)); + } + /** + * Adjusts the given bounds to handle the case where the bounds cross the 180th meridian (antimeridian). + * + * @returns The adjusted LngLatBounds + * @example + * ```ts + * let bounds = new LngLatBounds([175.813127, -20.157768], [-178. 340903, -15.449124]); + * let adjustedBounds = bounds.adjustAntiMeridian(); + * // adjustedBounds will be: [[175.813127, -20.157768], [181.659097, -15.449124]] + * ``` + */ + adjustAntiMeridian() { + const sw = new LngLat(this._sw.lng, this._sw.lat); + const ne = new LngLat(this._ne.lng, this._ne.lat); + if (sw.lng > ne.lng) { + return new LngLatBounds(sw, new LngLat(ne.lng + 360, ne.lat)); + } + return new LngLatBounds(sw, ne); + } +} + +/* + * The average circumference of the world in meters. + */ +const earthCircumference = 2 * Math.PI * earthRadius; // meters +/* + * The circumference at a line of latitude in meters. + */ +function circumferenceAtLatitude(latitude) { + return earthCircumference * Math.cos(latitude * Math.PI / 180); +} +function mercatorXfromLng(lng) { + return (180 + lng) / 360; +} +function mercatorYfromLat(lat) { + return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360; +} +function mercatorZfromAltitude(altitude, lat) { + return altitude / circumferenceAtLatitude(lat); +} +function lngFromMercatorX(x) { + return x * 360 - 180; +} +function latFromMercatorY(y) { + const y2 = 180 - y * 360; + return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90; +} +function altitudeFromMercatorZ(z, y) { + return z * circumferenceAtLatitude(latFromMercatorY(y)); +} +/** + * Determine the Mercator scale factor for a given latitude, see + * https://en.wikipedia.org/wiki/Mercator_projection#Scale_factor + * + * At the equator the scale factor will be 1, which increases at higher latitudes. + * + * @param lat - Latitude + * @returns scale factor + */ +function mercatorScale(lat) { + return 1 / Math.cos(lat * Math.PI / 180); +} +/** + * A `MercatorCoordinate` object represents a projected three dimensional position. + * + * `MercatorCoordinate` uses the web mercator projection ([EPSG:3857](https://epsg.io/3857)) with slightly different units: + * + * - the size of 1 unit is the width of the projected world instead of the "mercator meter" + * - the origin of the coordinate space is at the north-west corner instead of the middle + * + * For example, `MercatorCoordinate(0, 0, 0)` is the north-west corner of the mercator world and + * `MercatorCoordinate(1, 1, 0)` is the south-east corner. If you are familiar with + * [vector tiles](https://github.com/mapbox/vector-tile-spec) it may be helpful to think + * of the coordinate space as the `0/0/0` tile with an extent of `1`. + * + * The `z` dimension of `MercatorCoordinate` is conformal. A cube in the mercator coordinate space would be rendered as a cube. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let nullIsland = new MercatorCoordinate(0.5, 0.5, 0); + * ``` + * @see [Add a custom style layer](https://maplibre.org/maplibre-gl-js/docs/examples/custom-style-layer/) + */ +class MercatorCoordinate { + /** + * @param x - The x component of the position. + * @param y - The y component of the position. + * @param z - The z component of the position. + */ + constructor(x, y, z = 0) { + this.x = +x; + this.y = +y; + this.z = +z; + } + /** + * Project a `LngLat` to a `MercatorCoordinate`. + * + * @param lngLatLike - The location to project. + * @param altitude - The altitude in meters of the position. + * @returns The projected mercator coordinate. + * @example + * ```ts + * let coord = MercatorCoordinate.fromLngLat({ lng: 0, lat: 0}, 0); + * coord; // MercatorCoordinate(0.5, 0.5, 0) + * ``` + */ + static fromLngLat(lngLatLike, altitude = 0) { + const lngLat = LngLat.convert(lngLatLike); + return new MercatorCoordinate(mercatorXfromLng(lngLat.lng), mercatorYfromLat(lngLat.lat), mercatorZfromAltitude(altitude, lngLat.lat)); + } + /** + * Returns the `LngLat` for the coordinate. + * + * @returns The `LngLat` object. + * @example + * ```ts + * let coord = new MercatorCoordinate(0.5, 0.5, 0); + * let lngLat = coord.toLngLat(); // LngLat(0, 0) + * ``` + */ + toLngLat() { + return new LngLat(lngFromMercatorX(this.x), latFromMercatorY(this.y)); + } + /** + * Returns the altitude in meters of the coordinate. + * + * @returns The altitude in meters. + * @example + * ```ts + * let coord = new MercatorCoordinate(0, 0, 0.02); + * coord.toAltitude(); // 6914.281956295339 + * ``` + */ + toAltitude() { + return altitudeFromMercatorZ(this.z, this.y); + } + /** + * Returns the distance of 1 meter in `MercatorCoordinate` units at this latitude. + * + * For coordinates in real world units using meters, this naturally provides the scale + * to transform into `MercatorCoordinate`s. + * + * @returns Distance of 1 meter in `MercatorCoordinate` units. + */ + meterInMercatorCoordinateUnits() { + // 1 meter / circumference at equator in meters * Mercator projection scale factor at this latitude + return 1 / earthCircumference * mercatorScale(latFromMercatorY(this.y)); + } +} + +class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + } + validateBounds(bounds) { + // make sure the bounds property contains valid longitude and latitudes + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [Math.max(-180, bounds[0]), Math.max(-90, bounds[1]), Math.min(180, bounds[2]), Math.min(90, bounds[3])]; + } + contains(tileID) { + const worldSize = Math.pow(2, tileID.z); + const level = { + minX: Math.floor(mercatorXfromLng(this.bounds.getWest()) * worldSize), + minY: Math.floor(mercatorYfromLat(this.bounds.getNorth()) * worldSize), + maxX: Math.ceil(mercatorXfromLng(this.bounds.getEast()) * worldSize), + maxY: Math.ceil(mercatorYfromLat(this.bounds.getSouth()) * worldSize) + }; + const hit = tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY; + return hit; + } +} + +/** + * A source containing vector tiles in [Mapbox Vector Tile format](https://docs.mapbox.com/vector-tiles/reference/). + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'vector', + * url: 'https://demotiles.maplibre.org/tiles/tiles.json' + * }); + * ``` + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'vector', + * tiles: ['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt'], + * minzoom: 6, + * maxzoom: 14 + * }); + * ``` + * + * @example + * ```ts + * map.getSource('some id').setUrl("https://demotiles.maplibre.org/tiles/tiles.json"); + * ``` + * + * @example + * ```ts + * map.getSource('some id').setTiles(['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt']); + * ``` + * @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/vector-source/) + */ +class VectorTileSource extends Evented { + constructor(id, options, dispatcher, eventedParent) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.type = 'vector'; + this.minzoom = 0; + this.maxzoom = 22; + this.scheme = 'xyz'; + this.tileSize = 512; + this.reparseOverscaled = true; + this.isTileClipped = true; + this._loaded = false; + extend(this, pick(options, ['url', 'scheme', 'tileSize', 'promoteId'])); + this._options = extend({ type: 'vector' }, options); + this._collectResourceTiming = options.collectResourceTiming; + if (this.tileSize !== 512) { + throw new Error('vector tile sources must have a tileSize of 512'); + } + this.setEventedParent(eventedParent); + } + load() { + return __awaiter(this, void 0, void 0, function* () { + this._loaded = false; + this.fire(new Event('dataloading', { dataType: 'source' })); + this._tileJSONRequest = new AbortController(); + try { + const tileJSON = yield loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest); + this._tileJSONRequest = null; + this._loaded = true; + this.map.style.sourceCaches[this.id].clearTiles(); + if (tileJSON) { + extend(this, tileJSON); + if (tileJSON.bounds) + this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom); + // `content` is included here to prevent a race condition where `Style#_updateSources` is called + // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives + // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088 + this.fire(new Event('data', { dataType: 'source', sourceDataType: 'metadata' })); + this.fire(new Event('data', { dataType: 'source', sourceDataType: 'content' })); + } + } + catch (err) { + this._tileJSONRequest = null; + this.fire(new ErrorEvent(err)); + } + }); + } + loaded() { + return this._loaded; + } + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + onAdd(map) { + this.map = map; + this.load(); + } + setSourceProperty(callback) { + if (this._tileJSONRequest) { + this._tileJSONRequest.abort(); + } + callback(); + this.load(); + } + /** + * Sets the source `tiles` property and re-renders the map. + * + * @param tiles - An array of one or more tile source URLs, as in the TileJSON spec. + */ + setTiles(tiles) { + this.setSourceProperty(() => { + this._options.tiles = tiles; + }); + return this; + } + /** + * Sets the source `url` property and re-renders the map. + * + * @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`. + */ + setUrl(url) { + this.setSourceProperty(() => { + this.url = url; + this._options.url = url; + }); + return this; + } + onRemove() { + if (this._tileJSONRequest) { + this._tileJSONRequest.abort(); + this._tileJSONRequest = null; + } + } + serialize() { + return extend({}, this._options); + } + loadTile(tile) { + return __awaiter(this, void 0, void 0, function* () { + const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme); + const params = { + request: this.map._requestManager.transformRequest(url, "Tile" /* ResourceType.Tile */), + uid: tile.uid, + tileID: tile.tileID, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: this.type, + source: this.id, + pixelRatio: this.map.getPixelRatio(), + showCollisionBoxes: this.map.showCollisionBoxes, + promoteId: this.promoteId + }; + params.request.collectResourceTiming = this._collectResourceTiming; + let messageType = "RT" /* MessageType.reloadTile */; + if (!tile.actor || tile.state === 'expired') { + tile.actor = this.dispatcher.getActor(); + messageType = "LT" /* MessageType.loadTile */; + } + else if (tile.state === 'loading') { + return new Promise((resolve, reject) => { + tile.reloadPromise = { resolve, reject }; + }); + } + tile.abortController = new AbortController(); + try { + const data = yield tile.actor.sendAsync({ type: messageType, data: params }, tile.abortController); + delete tile.abortController; + if (tile.aborted) { + return; + } + this._afterTileLoadWorkerResponse(tile, data); + } + catch (err) { + delete tile.abortController; + if (tile.aborted) { + return; + } + if (err && err.status !== 404) { + throw err; + } + this._afterTileLoadWorkerResponse(tile, null); + } + }); + } + _afterTileLoadWorkerResponse(tile, data) { + if (data && data.resourceTiming) { + tile.resourceTiming = data.resourceTiming; + } + if (data && this.map._refreshExpiredTiles) { + tile.setExpiryData(data); + } + tile.loadVectorData(data, this.map.painter); + if (tile.reloadPromise) { + const reloadPromise = tile.reloadPromise; + tile.reloadPromise = null; + this.loadTile(tile).then(reloadPromise.resolve).catch(reloadPromise.reject); + } + } + abortTile(tile) { + return __awaiter(this, void 0, void 0, function* () { + if (tile.abortController) { + tile.abortController.abort(); + delete tile.abortController; + } + if (tile.actor) { + yield tile.actor.sendAsync({ + type: "AT" /* MessageType.abortTile */, + data: { uid: tile.uid, type: this.type, source: this.id } + }); + } + }); + } + unloadTile(tile) { + return __awaiter(this, void 0, void 0, function* () { + tile.unloadVectorData(); + if (tile.actor) { + yield tile.actor.sendAsync({ + type: "RMT" /* MessageType.removeTile */, + data: { + uid: tile.uid, + type: this.type, + source: this.id + } + }); + } + }); + } + hasTransition() { + return false; + } +} + +/** + * A source containing raster tiles (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * map.addSource('raster-source', { + * 'type': 'raster', + * 'tiles': ['https://tiles.stadiamaps.com/tiles/stamen_watercolor/{z}/{x}/{y}.jpg'], + * 'tileSize': 256, + * }); + * ``` + * + * @example + * ```ts + * map.addSource('wms-test-source', { + * 'type': 'raster', + * // use the tiles option to specify a WMS tile source URL + * 'tiles': [ + * 'https://img.nj.gov/imagerywms/Natural2015?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&transparent=true&width=256&height=256&layers=Natural2015' + * ], + * 'tileSize': 256 + * }); + * ``` + * @see [Add a raster tile source](https://maplibre.org/maplibre-gl-js/docs/examples/map-tiles/) + * @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/wms/) + * @see [Display a satellite map](https://maplibre.org/maplibre-gl-js/docs/examples/satellite-map/) + */ +class RasterTileSource extends Evented { + constructor(id, options, dispatcher, eventedParent) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.setEventedParent(eventedParent); + this.type = 'raster'; + this.minzoom = 0; + this.maxzoom = 22; + this.roundZoom = true; + this.scheme = 'xyz'; + this.tileSize = 512; + this._loaded = false; + this._options = extend({ type: 'raster' }, options); + extend(this, pick(options, ['url', 'scheme', 'tileSize'])); + } + load() { + return __awaiter(this, void 0, void 0, function* () { + this._loaded = false; + this.fire(new Event('dataloading', { dataType: 'source' })); + this._tileJSONRequest = new AbortController(); + try { + const tileJSON = yield loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest); + this._tileJSONRequest = null; + this._loaded = true; + if (tileJSON) { + extend(this, tileJSON); + if (tileJSON.bounds) + this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom); + // `content` is included here to prevent a race condition where `Style#_updateSources` is called + // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives + // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088 + this.fire(new Event('data', { dataType: 'source', sourceDataType: 'metadata' })); + this.fire(new Event('data', { dataType: 'source', sourceDataType: 'content' })); + } + } + catch (err) { + this._tileJSONRequest = null; + this.fire(new ErrorEvent(err)); + } + }); + } + loaded() { + return this._loaded; + } + onAdd(map) { + this.map = map; + this.load(); + } + onRemove() { + if (this._tileJSONRequest) { + this._tileJSONRequest.abort(); + this._tileJSONRequest = null; + } + } + setSourceProperty(callback) { + if (this._tileJSONRequest) { + this._tileJSONRequest.abort(); + this._tileJSONRequest = null; + } + callback(); + this.load(); + } + /** + * Sets the source `tiles` property and re-renders the map. + * + * @param tiles - An array of one or more tile source URLs, as in the raster tiles spec (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) + */ + setTiles(tiles) { + this.setSourceProperty(() => { + this._options.tiles = tiles; + }); + return this; + } + /** + * Sets the source `url` property and re-renders the map. + * + * @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`. + */ + setUrl(url) { + this.setSourceProperty(() => { + this.url = url; + this._options.url = url; + }); + return this; + } + serialize() { + return extend({}, this._options); + } + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + loadTile(tile) { + return __awaiter(this, void 0, void 0, function* () { + const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme); + tile.abortController = new AbortController(); + try { + const response = yield ImageRequest.getImage(this.map._requestManager.transformRequest(url, "Tile" /* ResourceType.Tile */), tile.abortController, this.map._refreshExpiredTiles); + delete tile.abortController; + if (tile.aborted) { + tile.state = 'unloaded'; + return; + } + if (response && response.data) { + if (this.map._refreshExpiredTiles && response.cacheControl && response.expires) { + tile.setExpiryData({ cacheControl: response.cacheControl, expires: response.expires }); + } + const context = this.map.painter.context; + const gl = context.gl; + const img = response.data; + tile.texture = this.map.painter.getTileTexture(img.width); + if (tile.texture) { + tile.texture.update(img, { useMipmap: true }); + } + else { + tile.texture = new Texture(context, img, gl.RGBA, { useMipmap: true }); + tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST); + } + tile.state = 'loaded'; + } + } + catch (err) { + delete tile.abortController; + if (tile.aborted) { + tile.state = 'unloaded'; + } + else if (err) { + tile.state = 'errored'; + throw err; + } + } + }); + } + abortTile(tile) { + return __awaiter(this, void 0, void 0, function* () { + if (tile.abortController) { + tile.abortController.abort(); + delete tile.abortController; + } + }); + } + unloadTile(tile) { + return __awaiter(this, void 0, void 0, function* () { + if (tile.texture) { + this.map.painter.saveTileTexture(tile.texture); + } + }); + } + hasTransition() { + return false; + } +} + +/** + * getURL + * + * @param {String} baseUrl Base url of the WMS server + * @param {String} layer Layer name + * @param {Number} x Tile coordinate x + * @param {Number} y Tile coordinate y + * @param {Number} z Tile zoom + * @param {Object} [options] + * @param {String} [options.format='image/png'] + * @param {String} [options.service='WMS'] + * @param {String} [options.version='1.1.1'] + * @param {String} [options.request='GetMap'] + * @param {String} [options.srs='EPSG:3857'] + * @param {Number} [options.width='256'] + * @param {Number} [options.height='256'] + * @returns {String} url + * @example + * var baseUrl = 'http://geodata.state.nj.us/imagerywms/Natural2015'; + * var layer = 'Natural2015'; + * var url = whoots.getURL(baseUrl, layer, 154308, 197167, 19); + */ +function getURL(baseUrl, layer, x, y, z, options) { + options = options || {}; + + var url = baseUrl + '?' + [ + 'bbox=' + getTileBBox(x, y, z), + 'format=' + (options.format || 'image/png'), + 'service=' + (options.service || 'WMS'), + 'version=' + (options.version || '1.1.1'), + 'request=' + (options.request || 'GetMap'), + 'srs=' + (options.srs || 'EPSG:3857'), + 'width=' + (options.width || 256), + 'height=' + (options.height || 256), + 'layers=' + layer + ].join('&'); + + return url; +} + + +/** + * getTileBBox + * + * @param {Number} x Tile coordinate x + * @param {Number} y Tile coordinate y + * @param {Number} z Tile zoom + * @returns {String} String of the bounding box + */ +function getTileBBox(x, y, z) { + // for Google/OSM tile scheme we need to alter the y + y = (Math.pow(2, z) - y - 1); + + var min = getMercCoords(x * 256, y * 256, z), + max = getMercCoords((x + 1) * 256, (y + 1) * 256, z); + + return min[0] + ',' + min[1] + ',' + max[0] + ',' + max[1]; +} + + +/** + * getMercCoords + * + * @param {Number} x Pixel coordinate x + * @param {Number} y Pixel coordinate y + * @param {Number} z Tile zoom + * @returns {Array} [x, y] + */ +function getMercCoords(x, y, z) { + var resolution = (2 * Math.PI * 6378137 / 256) / Math.pow(2, z), + merc_x = (x * resolution - 2 * Math.PI * 6378137 / 2.0), + merc_y = (y * resolution - 2 * Math.PI * 6378137 / 2.0); + + return [merc_x, merc_y]; +} + +/** + * Returns true if a given tile zoom (Z), X, and Y are in the bounds of the world. + * Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive). + * X and Y bounds are 0 (inclusive) to their respective zoom-dependent maxima (exclusive). + * + * @param zoom - the tile zoom (Z) + * @param x - the tile X + * @param y - the tile Y + * @returns `true` if a given tile zoom, X, and Y are in the bounds of the world. + */ +function isInBoundsForTileZoomXY(zoom, x, y) { + return !(zoom < MIN_TILE_ZOOM || + zoom > MAX_TILE_ZOOM || + y < 0 || + y >= Math.pow(2, zoom) || + x < 0 || + x >= Math.pow(2, zoom)); +} +/** + * Returns true if a given zoom and `LngLat` are in the bounds of the world. + * Does not wrap `LngLat` when checking if in bounds. + * Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive). + * `LngLat` bounds are the mercator world's north-west corner (inclusive) to its south-east corner (exclusive). + * + * @param zoom - the tile zoom (Z) + * @param LngLat - the `LngLat` object containing the longitude and latitude + * @returns `true` if a given zoom and `LngLat` are in the bounds of the world. + */ +function isInBoundsForZoomLngLat(zoom, lnglat) { + const { x, y } = MercatorCoordinate.fromLngLat(lnglat); + return !(zoom < MIN_TILE_ZOOM || + zoom > MAX_TILE_ZOOM || + y < 0 || + y >= 1 || + x < 0 || + x >= 1); +} + +/** + * A canonical way to define a tile ID + */ +class CanonicalTileID { + constructor(z, x, y) { + if (!isInBoundsForTileZoomXY(z, x, y)) { + throw new Error(`x=${x}, y=${y}, z=${z} outside of bounds. 0<=x<${Math.pow(2, z)}, 0<=y<${Math.pow(2, z)} ${MIN_TILE_ZOOM}<=z<=${MAX_TILE_ZOOM} `); + } + this.z = z; + this.x = x; + this.y = y; + this.key = calculateKey(0, z, z, x, y); + } + equals(id) { + return this.z === id.z && this.x === id.x && this.y === id.y; + } + // given a list of urls, choose a url template and return a tile URL + url(urls, pixelRatio, scheme) { + const bbox = getTileBBox(this.x, this.y, this.z); + const quadkey = getQuadkey(this.z, this.x, this.y); + return urls[(this.x + this.y) % urls.length] + .replace(/{prefix}/g, (this.x % 16).toString(16) + (this.y % 16).toString(16)) + .replace(/{z}/g, String(this.z)) + .replace(/{x}/g, String(this.x)) + .replace(/{y}/g, String(scheme === 'tms' ? (Math.pow(2, this.z) - this.y - 1) : this.y)) + .replace(/{ratio}/g, pixelRatio > 1 ? '@2x' : '') + .replace(/{quadkey}/g, quadkey) + .replace(/{bbox-epsg-3857}/g, bbox); + } + isChildOf(parent) { + const dz = this.z - parent.z; + return dz > 0 && parent.x === (this.x >> dz) && parent.y === (this.y >> dz); + } + getTilePoint(coord) { + const tilesAtZoom = Math.pow(2, this.z); + return new Point$2((coord.x * tilesAtZoom - this.x) * EXTENT, (coord.y * tilesAtZoom - this.y) * EXTENT); + } + toString() { + return `${this.z}/${this.x}/${this.y}`; + } +} +/** + * @internal + * An unwrapped tile identifier + */ +class UnwrappedTileID { + constructor(wrap, canonical) { + this.wrap = wrap; + this.canonical = canonical; + this.key = calculateKey(wrap, canonical.z, canonical.z, canonical.x, canonical.y); + } +} +/** + * An overscaled tile identifier + */ +class OverscaledTileID { + constructor(overscaledZ, wrap, z, x, y) { + if (overscaledZ < z) + throw new Error(`overscaledZ should be >= z; overscaledZ = ${overscaledZ}; z = ${z}`); + this.overscaledZ = overscaledZ; + this.wrap = wrap; + this.canonical = new CanonicalTileID(z, +x, +y); + this.key = calculateKey(wrap, overscaledZ, z, x, y); + } + clone() { + return new OverscaledTileID(this.overscaledZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } + equals(id) { + return this.overscaledZ === id.overscaledZ && this.wrap === id.wrap && this.canonical.equals(id.canonical); + } + scaledTo(targetZ) { + if (targetZ > this.overscaledZ) + throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`); + const zDifference = this.canonical.z - targetZ; + if (targetZ > this.canonical.z) { + return new OverscaledTileID(targetZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } + else { + return new OverscaledTileID(targetZ, this.wrap, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference); + } + } + /* + * calculateScaledKey is an optimization: + * when withWrap == true, implements the same as this.scaledTo(z).key, + * when withWrap == false, implements the same as this.scaledTo(z).wrapped().key. + */ + calculateScaledKey(targetZ, withWrap) { + if (targetZ > this.overscaledZ) + throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`); + const zDifference = this.canonical.z - targetZ; + if (targetZ > this.canonical.z) { + return calculateKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y); + } + else { + return calculateKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference); + } + } + isChildOf(parent) { + if (parent.wrap !== this.wrap) { + // We can't be a child if we're in a different world copy + return false; + } + const zDifference = this.canonical.z - parent.canonical.z; + // We're first testing for z == 0, to avoid a 32 bit shift, which is undefined. + return parent.overscaledZ === 0 || (parent.overscaledZ < this.overscaledZ && + parent.canonical.x === (this.canonical.x >> zDifference) && + parent.canonical.y === (this.canonical.y >> zDifference)); + } + children(sourceMaxZoom) { + if (this.overscaledZ >= sourceMaxZoom) { + // return a single tile coord representing a an overscaled tile + return [new OverscaledTileID(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)]; + } + const z = this.canonical.z + 1; + const x = this.canonical.x * 2; + const y = this.canonical.y * 2; + return [ + new OverscaledTileID(z, this.wrap, z, x, y), + new OverscaledTileID(z, this.wrap, z, x + 1, y), + new OverscaledTileID(z, this.wrap, z, x, y + 1), + new OverscaledTileID(z, this.wrap, z, x + 1, y + 1) + ]; + } + isLessThan(rhs) { + if (this.wrap < rhs.wrap) + return true; + if (this.wrap > rhs.wrap) + return false; + if (this.overscaledZ < rhs.overscaledZ) + return true; + if (this.overscaledZ > rhs.overscaledZ) + return false; + if (this.canonical.x < rhs.canonical.x) + return true; + if (this.canonical.x > rhs.canonical.x) + return false; + if (this.canonical.y < rhs.canonical.y) + return true; + return false; + } + wrapped() { + return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y); + } + unwrapTo(wrap) { + return new OverscaledTileID(this.overscaledZ, wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } + overscaleFactor() { + return Math.pow(2, this.overscaledZ - this.canonical.z); + } + toUnwrapped() { + return new UnwrappedTileID(this.wrap, this.canonical); + } + toString() { + return `${this.overscaledZ}/${this.canonical.x}/${this.canonical.y}`; + } + getTilePoint(coord) { + return this.canonical.getTilePoint(new MercatorCoordinate(coord.x - this.wrap, coord.y)); + } +} +function calculateKey(wrap, overscaledZ, z, x, y) { + wrap *= 2; + if (wrap < 0) + wrap = wrap * -1 - 1; + const dim = 1 << z; + return (dim * dim * wrap + dim * y + x).toString(36) + z.toString(36) + overscaledZ.toString(36); +} +function getQuadkey(z, x, y) { + let quadkey = '', mask; + for (let i = z; i > 0; i--) { + mask = 1 << (i - 1); + quadkey += ((x & mask ? 1 : 0) + (y & mask ? 2 : 0)); + } + return quadkey; +} +register('CanonicalTileID', CanonicalTileID); +register('OverscaledTileID', OverscaledTileID, { omit: ['posMatrix'] }); + +/** + * DEMData is a data structure for decoding, backfilling, and storing elevation data for processing in the hillshade shaders + * data can be populated either from a pngraw image tile or from serialized data sent back from a worker. When data is initially + * loaded from a image tile, we decode the pixel values using the appropriate decoding formula, but we store the + * elevation data as an Int32 value. we add 65536 (2^16) to eliminate negative values and enable the use of + * integer overflow when creating the texture used in the hillshadePrepare step. + * + * DEMData also handles the backfilling of data from a tile's neighboring tiles. This is necessary because we use a pixel's 8 + * surrounding pixel values to compute the slope at that pixel, and we cannot accurately calculate the slope at pixels on a + * tile's edge without backfilling from neighboring tiles. + */ +class DEMData { + /** + * Constructs a `DEMData` object + * @param uid - the tile's unique id + * @param data - RGBAImage data has uniform 1px padding on all sides: square tile edge size defines stride + // and dim is calculated as stride - 2. + * @param encoding - the encoding type of the data + * @param redFactor - the red channel factor used to unpack the data, used for `custom` encoding only + * @param greenFactor - the green channel factor used to unpack the data, used for `custom` encoding only + * @param blueFactor - the blue channel factor used to unpack the data, used for `custom` encoding only + * @param baseShift - the base shift used to unpack the data, used for `custom` encoding only + */ + constructor(uid, data, encoding, redFactor = 1.0, greenFactor = 1.0, blueFactor = 1.0, baseShift = 0.0) { + this.uid = uid; + if (data.height !== data.width) + throw new RangeError('DEM tiles must be square'); + if (encoding && !['mapbox', 'terrarium', 'custom'].includes(encoding)) { + warnOnce(`"${encoding}" is not a valid encoding type. Valid types include "mapbox", "terrarium" and "custom".`); + return; + } + this.stride = data.height; + const dim = this.dim = data.height - 2; + this.data = new Uint32Array(data.data.buffer); + switch (encoding) { + case 'terrarium': + // unpacking formula for mapzen terrarium: + // https://aws.amazon.com/public-datasets/terrain/ + this.redFactor = 256.0; + this.greenFactor = 1.0; + this.blueFactor = 1.0 / 256.0; + this.baseShift = 32768.0; + break; + case 'custom': + this.redFactor = redFactor; + this.greenFactor = greenFactor; + this.blueFactor = blueFactor; + this.baseShift = baseShift; + break; + case 'mapbox': + default: + // unpacking formula for mapbox.terrain-rgb: + // https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb + this.redFactor = 6553.6; + this.greenFactor = 25.6; + this.blueFactor = 0.1; + this.baseShift = 10000.0; + break; + } + // in order to avoid flashing seams between tiles, here we are initially populating a 1px border of pixels around the image + // with the data of the nearest pixel from the image. this data is eventually replaced when the tile's neighboring + // tiles are loaded and the accurate data can be backfilled using DEMData#backfillBorder + for (let x = 0; x < dim; x++) { + // left vertical border + this.data[this._idx(-1, x)] = this.data[this._idx(0, x)]; + // right vertical border + this.data[this._idx(dim, x)] = this.data[this._idx(dim - 1, x)]; + // left horizontal border + this.data[this._idx(x, -1)] = this.data[this._idx(x, 0)]; + // right horizontal border + this.data[this._idx(x, dim)] = this.data[this._idx(x, dim - 1)]; + } + // corners + this.data[this._idx(-1, -1)] = this.data[this._idx(0, 0)]; + this.data[this._idx(dim, -1)] = this.data[this._idx(dim - 1, 0)]; + this.data[this._idx(-1, dim)] = this.data[this._idx(0, dim - 1)]; + this.data[this._idx(dim, dim)] = this.data[this._idx(dim - 1, dim - 1)]; + // calculate min/max values + this.min = Number.MAX_SAFE_INTEGER; + this.max = Number.MIN_SAFE_INTEGER; + for (let x = 0; x < dim; x++) { + for (let y = 0; y < dim; y++) { + const ele = this.get(x, y); + if (ele > this.max) + this.max = ele; + if (ele < this.min) + this.min = ele; + } + } + } + get(x, y) { + const pixels = new Uint8Array(this.data.buffer); + const index = this._idx(x, y) * 4; + return this.unpack(pixels[index], pixels[index + 1], pixels[index + 2]); + } + getUnpackVector() { + return [this.redFactor, this.greenFactor, this.blueFactor, this.baseShift]; + } + _idx(x, y) { + if (x < -1 || x >= this.dim + 1 || y < -1 || y >= this.dim + 1) + throw new RangeError('out of range source coordinates for DEM data'); + return (y + 1) * this.stride + (x + 1); + } + unpack(r, g, b) { + return (r * this.redFactor + g * this.greenFactor + b * this.blueFactor - this.baseShift); + } + getPixels() { + return new RGBAImage({ width: this.stride, height: this.stride }, new Uint8Array(this.data.buffer)); + } + backfillBorder(borderTile, dx, dy) { + if (this.dim !== borderTile.dim) + throw new Error('dem dimension mismatch'); + let xMin = dx * this.dim, xMax = dx * this.dim + this.dim, yMin = dy * this.dim, yMax = dy * this.dim + this.dim; + switch (dx) { + case -1: + xMin = xMax - 1; + break; + case 1: + xMax = xMin + 1; + break; + } + switch (dy) { + case -1: + yMin = yMax - 1; + break; + case 1: + yMax = yMin + 1; + break; + } + const ox = -dx * this.dim; + const oy = -dy * this.dim; + for (let y = yMin; y < yMax; y++) { + for (let x = xMin; x < xMax; x++) { + this.data[this._idx(x, y)] = borderTile.data[this._idx(x + ox, y + oy)]; + } + } + } +} +register('DEMData', DEMData); + +/** + * A source containing raster DEM tiles (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.) + * This source can be used to show hillshading and 3D terrain + * + * @group Sources + * + * @example + * ```ts + * map.addSource('raster-dem-source', { + * type: 'raster-dem', + * url: 'https://demotiles.maplibre.org/terrain-tiles/tiles.json', + * tileSize: 256 + * }); + * ``` + * @see [3D Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/3d-terrain/) + */ +class RasterDEMTileSource extends RasterTileSource { + constructor(id, options, dispatcher, eventedParent) { + super(id, options, dispatcher, eventedParent); + this.type = 'raster-dem'; + this.maxzoom = 22; + this._options = extend({ type: 'raster-dem' }, options); + this.encoding = options.encoding || 'mapbox'; + this.redFactor = options.redFactor; + this.greenFactor = options.greenFactor; + this.blueFactor = options.blueFactor; + this.baseShift = options.baseShift; + } + loadTile(tile) { + return __awaiter(this, void 0, void 0, function* () { + const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme); + const request = this.map._requestManager.transformRequest(url, "Tile" /* ResourceType.Tile */); + tile.neighboringTiles = this._getNeighboringTiles(tile.tileID); + tile.abortController = new AbortController(); + try { + const response = yield ImageRequest.getImage(request, tile.abortController, this.map._refreshExpiredTiles); + delete tile.abortController; + if (tile.aborted) { + tile.state = 'unloaded'; + return; + } + if (response && response.data) { + const img = response.data; + if (this.map._refreshExpiredTiles && response.cacheControl && response.expires) { + tile.setExpiryData({ cacheControl: response.cacheControl, expires: response.expires }); + } + const transfer = isImageBitmap(img) && offscreenCanvasSupported(); + const rawImageData = transfer ? img : yield this.readImageNow(img); + const params = { + type: this.type, + uid: tile.uid, + source: this.id, + rawImageData, + encoding: this.encoding, + redFactor: this.redFactor, + greenFactor: this.greenFactor, + blueFactor: this.blueFactor, + baseShift: this.baseShift + }; + if (!tile.actor || tile.state === 'expired') { + tile.actor = this.dispatcher.getActor(); + /* eslint-disable require-atomic-updates */ + const data = yield tile.actor.sendAsync({ type: "LDT" /* MessageType.loadDEMTile */, data: params }); + tile.dem = data; + tile.needsHillshadePrepare = true; + tile.needsTerrainPrepare = true; + tile.state = 'loaded'; + /* eslint-enable require-atomic-updates */ + } + } + } + catch (err) { + delete tile.abortController; + if (tile.aborted) { + tile.state = 'unloaded'; + } + else if (err) { + tile.state = 'errored'; + throw err; + } + } + }); + } + readImageNow(img) { + return __awaiter(this, void 0, void 0, function* () { + if (typeof VideoFrame !== 'undefined' && isOffscreenCanvasDistorted()) { + const width = img.width + 2; + const height = img.height + 2; + try { + return new RGBAImage({ width, height }, yield readImageUsingVideoFrame(img, -1, -1, width, height)); + } + catch (e) { + // fall-back to browser canvas decoding + } + } + return browser.getImageData(img, 1); + }); + } + _getNeighboringTiles(tileID) { + const canonical = tileID.canonical; + const dim = Math.pow(2, canonical.z); + const px = (canonical.x - 1 + dim) % dim; + const pxw = canonical.x === 0 ? tileID.wrap - 1 : tileID.wrap; + const nx = (canonical.x + 1 + dim) % dim; + const nxw = canonical.x + 1 === dim ? tileID.wrap + 1 : tileID.wrap; + const neighboringTiles = {}; + // add adjacent tiles + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y).key] = { backfilled: false }; + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y).key] = { backfilled: false }; + // Add upper neighboringTiles + if (canonical.y > 0) { + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y - 1).key] = { backfilled: false }; + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y - 1).key] = { backfilled: false }; + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y - 1).key] = { backfilled: false }; + } + // Add lower neighboringTiles + if (canonical.y + 1 < dim) { + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y + 1).key] = { backfilled: false }; + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y + 1).key] = { backfilled: false }; + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y + 1).key] = { backfilled: false }; + } + return neighboringTiles; + } + unloadTile(tile) { + return __awaiter(this, void 0, void 0, function* () { + if (tile.demTexture) + this.map.painter.saveTileTexture(tile.demTexture); + if (tile.fbo) { + tile.fbo.destroy(); + delete tile.fbo; + } + if (tile.dem) + delete tile.dem; + delete tile.neighboringTiles; + tile.state = 'unloaded'; + if (tile.actor) { + yield tile.actor.sendAsync({ type: "RDT" /* MessageType.removeDEMTile */, data: { type: this.type, uid: tile.uid, source: this.id } }); + } + }); + } +} + +/** + * A source containing GeoJSON. + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-geojson) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'geojson', + * data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson' + * }); + * ``` + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'geojson', + * data: { + * "type": "FeatureCollection", + * "features": [{ + * "type": "Feature", + * "properties": {}, + * "geometry": { + * "type": "Point", + * "coordinates": [ + * -76.53063297271729, + * 39.18174077994108 + * ] + * } + * }] + * } + * }); + * ``` + * + * @example + * ```ts + * map.getSource('some id').setData({ + * "type": "FeatureCollection", + * "features": [{ + * "type": "Feature", + * "properties": { "name": "Null Island" }, + * "geometry": { + * "type": "Point", + * "coordinates": [ 0, 0 ] + * } + * }] + * }); + * ``` + * @see [Draw GeoJSON points](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-markers/) + * @see [Add a GeoJSON line](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-line/) + * @see [Create a heatmap from points](https://maplibre.org/maplibre-gl-js/docs/examples/heatmap-layer/) + * @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/cluster/) + */ +class GeoJSONSource extends Evented { + /** @internal */ + constructor(id, options, dispatcher, eventedParent) { + super(); + this.id = id; + // `type` is a property rather than a constant to make it easy for 3rd + // parties to use GeoJSONSource to build their own source types. + this.type = 'geojson'; + this.minzoom = 0; + this.maxzoom = 18; + this.tileSize = 512; + this.isTileClipped = true; + this.reparseOverscaled = true; + this._removed = false; + this._pendingLoads = 0; + this.actor = dispatcher.getActor(); + this.setEventedParent(eventedParent); + this._data = options.data; + this._options = extend({}, options); + this._collectResourceTiming = options.collectResourceTiming; + if (options.maxzoom !== undefined) + this.maxzoom = options.maxzoom; + if (options.type) + this.type = options.type; + if (options.attribution) + this.attribution = options.attribution; + this.promoteId = options.promoteId; + const scale = EXTENT / this.tileSize; + if (options.clusterMaxZoom !== undefined && this.maxzoom <= options.clusterMaxZoom) { + warnOnce(`The maxzoom value "${this.maxzoom}" is expected to be greater than the clusterMaxZoom value "${options.clusterMaxZoom}".`); + } + // sent to the worker, along with `url: ...` or `data: literal geojson`, + // so that it can load/parse/index the geojson data + // extending with `options.workerOptions` helps to make it easy for + // third-party sources to hack/reuse GeoJSONSource. + this.workerOptions = extend({ + source: this.id, + cluster: options.cluster || false, + geojsonVtOptions: { + buffer: (options.buffer !== undefined ? options.buffer : 128) * scale, + tolerance: (options.tolerance !== undefined ? options.tolerance : 0.375) * scale, + extent: EXTENT, + maxZoom: this.maxzoom, + lineMetrics: options.lineMetrics || false, + generateId: options.generateId || false + }, + superclusterOptions: { + maxZoom: options.clusterMaxZoom !== undefined ? options.clusterMaxZoom : this.maxzoom - 1, + minPoints: Math.max(2, options.clusterMinPoints || 2), + extent: EXTENT, + radius: (options.clusterRadius || 50) * scale, + log: false, + generateId: options.generateId || false + }, + clusterProperties: options.clusterProperties, + filter: options.filter + }, options.workerOptions); + // send the promoteId to the worker to have more flexible updates, but only if it is a string + if (typeof this.promoteId === 'string') { + this.workerOptions.promoteId = this.promoteId; + } + } + load() { + return __awaiter(this, void 0, void 0, function* () { + yield this._updateWorkerData(); + }); + } + onAdd(map) { + this.map = map; + this.load(); + } + /** + * Sets the GeoJSON data and re-renders the map. + * + * @param data - A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files. + */ + setData(data) { + this._data = data; + this._updateWorkerData(); + return this; + } + /** + * Updates the source's GeoJSON, and re-renders the map. + * + * For sources with lots of features, this method can be used to make updates more quickly. + * + * This approach requires unique IDs for every feature in the source. The IDs can either be specified on the feature, + * or by using the promoteId option to specify which property should be used as the ID. + * + * It is an error to call updateData on a source that did not have unique IDs for each of its features already. + * + * Updates are applied on a best-effort basis, updating an ID that does not exist will not result in an error. + * + * @param diff - The changes that need to be applied. + */ + updateData(diff) { + this._updateWorkerData(diff); + return this; + } + /** + * Allows to get the source's actual GeoJSON data. + * + * @returns a promise which resolves to the source's actual GeoJSON data + */ + getData() { + return __awaiter(this, void 0, void 0, function* () { + const options = extend({ type: this.type }, this.workerOptions); + return this.actor.sendAsync({ type: "GD" /* MessageType.getData */, data: options }); + }); + } + /** + * To disable/enable clustering on the source options + * @param options - The options to set + * @example + * ```ts + * map.getSource('some id').setClusterOptions({cluster: false}); + * map.getSource('some id').setClusterOptions({cluster: false, clusterRadius: 50, clusterMaxZoom: 14}); + * ``` + */ + setClusterOptions(options) { + this.workerOptions.cluster = options.cluster; + if (options) { + if (options.clusterRadius !== undefined) + this.workerOptions.superclusterOptions.radius = options.clusterRadius; + if (options.clusterMaxZoom !== undefined) + this.workerOptions.superclusterOptions.maxZoom = options.clusterMaxZoom; + } + this._updateWorkerData(); + return this; + } + /** + * For clustered sources, fetches the zoom at which the given cluster expands. + * + * @param clusterId - The value of the cluster's `cluster_id` property. + * @returns a promise that is resolved with the zoom number + */ + getClusterExpansionZoom(clusterId) { + return this.actor.sendAsync({ type: "GCEZ" /* MessageType.getClusterExpansionZoom */, data: { type: this.type, clusterId, source: this.id } }); + } + /** + * For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features). + * + * @param clusterId - The value of the cluster's `cluster_id` property. + * @returns a promise that is resolved when the features are retrieved + */ + getClusterChildren(clusterId) { + return this.actor.sendAsync({ type: "GCC" /* MessageType.getClusterChildren */, data: { type: this.type, clusterId, source: this.id } }); + } + /** + * For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features). + * + * @param clusterId - The value of the cluster's `cluster_id` property. + * @param limit - The maximum number of features to return. + * @param offset - The number of features to skip (e.g. for pagination). + * @returns a promise that is resolved when the features are retrieved + * @example + * Retrieve cluster leaves on click + * ```ts + * map.on('click', 'clusters', (e) => { + * let features = map.queryRenderedFeatures(e.point, { + * layers: ['clusters'] + * }); + * + * let clusterId = features[0].properties.cluster_id; + * let pointCount = features[0].properties.point_count; + * let clusterSource = map.getSource('clusters'); + * + * const features = await clusterSource.getClusterLeaves(clusterId, pointCount); + * // Print cluster leaves in the console + * console.log('Cluster leaves:', features); + * }); + * ``` + */ + getClusterLeaves(clusterId, limit, offset) { + return this.actor.sendAsync({ type: "GCL" /* MessageType.getClusterLeaves */, data: { + type: this.type, + source: this.id, + clusterId, + limit, + offset + } }); + } + /** + * Responsible for invoking WorkerSource's geojson.loadData target, which + * handles loading the geojson data and preparing to serve it up as tiles, + * using geojson-vt or supercluster as appropriate. + * @param diff - the diff object + */ + _updateWorkerData(diff) { + return __awaiter(this, void 0, void 0, function* () { + const options = extend({ type: this.type }, this.workerOptions); + if (diff) { + options.dataDiff = diff; + } + else if (typeof this._data === 'string') { + options.request = this.map._requestManager.transformRequest(browser.resolveURL(this._data), "Source" /* ResourceType.Source */); + options.request.collectResourceTiming = this._collectResourceTiming; + } + else { + options.data = JSON.stringify(this._data); + } + this._pendingLoads++; + this.fire(new Event('dataloading', { dataType: 'source' })); + try { + const result = yield this.actor.sendAsync({ type: "LD" /* MessageType.loadData */, data: options }); + this._pendingLoads--; + if (this._removed || result.abandoned) { + this.fire(new Event('dataabort', { dataType: 'source' })); + return; + } + let resourceTiming = null; + if (result.resourceTiming && result.resourceTiming[this.id]) { + resourceTiming = result.resourceTiming[this.id].slice(0); + } + const data = { dataType: 'source' }; + if (this._collectResourceTiming && resourceTiming && resourceTiming.length > 0) { + extend(data, { resourceTiming }); + } + // although GeoJSON sources contain no metadata, we fire this event to let the SourceCache + // know its ok to start requesting tiles. + this.fire(new Event('data', Object.assign(Object.assign({}, data), { sourceDataType: 'metadata' }))); + this.fire(new Event('data', Object.assign(Object.assign({}, data), { sourceDataType: 'content' }))); + } + catch (err) { + this._pendingLoads--; + if (this._removed) { + this.fire(new Event('dataabort', { dataType: 'source' })); + return; + } + this.fire(new ErrorEvent(err)); + } + }); + } + loaded() { + return this._pendingLoads === 0; + } + loadTile(tile) { + return __awaiter(this, void 0, void 0, function* () { + const message = !tile.actor ? "LT" /* MessageType.loadTile */ : "RT" /* MessageType.reloadTile */; + tile.actor = this.actor; + const params = { + type: this.type, + uid: tile.uid, + tileID: tile.tileID, + zoom: tile.tileID.overscaledZ, + maxZoom: this.maxzoom, + tileSize: this.tileSize, + source: this.id, + pixelRatio: this.map.getPixelRatio(), + showCollisionBoxes: this.map.showCollisionBoxes, + promoteId: this.promoteId + }; + tile.abortController = new AbortController(); + const data = yield this.actor.sendAsync({ type: message, data: params }, tile.abortController); + delete tile.abortController; + tile.unloadVectorData(); + if (!tile.aborted) { + tile.loadVectorData(data, this.map.painter, message === "RT" /* MessageType.reloadTile */); + } + }); + } + abortTile(tile) { + return __awaiter(this, void 0, void 0, function* () { + if (tile.abortController) { + tile.abortController.abort(); + delete tile.abortController; + } + tile.aborted = true; + }); + } + unloadTile(tile) { + return __awaiter(this, void 0, void 0, function* () { + tile.unloadVectorData(); + yield this.actor.sendAsync({ type: "RMT" /* MessageType.removeTile */, data: { uid: tile.uid, type: this.type, source: this.id } }); + }); + } + onRemove() { + this._removed = true; + this.actor.sendAsync({ type: "RS" /* MessageType.removeSource */, data: { type: this.type, source: this.id } }); + } + serialize() { + return extend({}, this._options, { + type: this.type, + data: this._data + }); + } + hasTransition() { + return false; + } +} + +var rasterBoundsAttributes = createLayout([ + { name: 'a_pos', type: 'Int16', components: 2 }, + { name: 'a_texture_pos', type: 'Int16', components: 2 } +]); + +/** + * A data source containing an image. + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-image) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * // add to map + * map.addSource('some id', { + * type: 'image', + * url: 'https://www.maplibre.org/images/foo.png', + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update coordinates + * let mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * // update url and coordinates simultaneously + * mySource.updateImage({ + * url: 'https://www.maplibre.org/images/bar.png', + * coordinates: [ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ] + * }) + * + * map.removeSource('some id'); // remove + * ``` + */ +class ImageSource extends Evented { + /** @internal */ + constructor(id, options, dispatcher, eventedParent) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.coordinates = options.coordinates; + this.type = 'image'; + this.minzoom = 0; + this.maxzoom = 22; + this.tileSize = 512; + this.tiles = {}; + this._loaded = false; + this.setEventedParent(eventedParent); + this.options = options; + } + load(newCoordinates) { + return __awaiter(this, void 0, void 0, function* () { + this._loaded = false; + this.fire(new Event('dataloading', { dataType: 'source' })); + this.url = this.options.url; + this._request = new AbortController(); + try { + const image = yield ImageRequest.getImage(this.map._requestManager.transformRequest(this.url, "Image" /* ResourceType.Image */), this._request); + this._request = null; + this._loaded = true; + if (image && image.data) { + this.image = image.data; + if (newCoordinates) { + this.coordinates = newCoordinates; + } + this._finishLoading(); + } + } + catch (err) { + this._request = null; + this._loaded = true; + this.fire(new ErrorEvent(err)); + } + }); + } + loaded() { + return this._loaded; + } + /** + * Updates the image URL and, optionally, the coordinates. To avoid having the image flash after changing, + * set the `raster-fade-duration` paint property on the raster layer to 0. + * + * @param options - The options object. + */ + updateImage(options) { + if (!options.url) { + return this; + } + if (this._request) { + this._request.abort(); + this._request = null; + } + this.options.url = options.url; + this.load(options.coordinates).finally(() => { this.texture = null; }); + return this; + } + _finishLoading() { + if (this.map) { + this.setCoordinates(this.coordinates); + this.fire(new Event('data', { dataType: 'source', sourceDataType: 'metadata' })); + } + } + onAdd(map) { + this.map = map; + this.load(); + } + onRemove() { + if (this._request) { + this._request.abort(); + this._request = null; + } + } + /** + * Sets the image's coordinates and re-renders the map. + * + * @param coordinates - Four geographical coordinates, + * represented as arrays of longitude and latitude numbers, which define the corners of the image. + * The coordinates start at the top left corner of the image and proceed in clockwise order. + * They do not have to represent a rectangle. + */ + setCoordinates(coordinates) { + this.coordinates = coordinates; + // Calculate which mercator tile is suitable for rendering the video in + // and create a buffer with the corner coordinates. These coordinates + // may be outside the tile, because raster tiles aren't clipped when rendering. + // transform the geo coordinates into (zoom 0) tile space coordinates + const cornerCoords = coordinates.map(MercatorCoordinate.fromLngLat); + // Compute the coordinates of the tile we'll use to hold this image's + // render data + this.tileID = getCoordinatesCenterTileID(cornerCoords); + // Constrain min/max zoom to our tile's zoom level in order to force + // SourceCache to request this tile (no matter what the map's zoom + // level) + this.minzoom = this.maxzoom = this.tileID.z; + // Transform the corner coordinates into the coordinate space of our + // tile. + const tileCoords = cornerCoords.map((coord) => this.tileID.getTilePoint(coord)._round()); + this._boundsArray = new RasterBoundsArray(); + this._boundsArray.emplaceBack(tileCoords[0].x, tileCoords[0].y, 0, 0); + this._boundsArray.emplaceBack(tileCoords[1].x, tileCoords[1].y, EXTENT, 0); + this._boundsArray.emplaceBack(tileCoords[3].x, tileCoords[3].y, 0, EXTENT); + this._boundsArray.emplaceBack(tileCoords[2].x, tileCoords[2].y, EXTENT, EXTENT); + if (this.boundsBuffer) { + this.boundsBuffer.destroy(); + delete this.boundsBuffer; + } + this.fire(new Event('data', { dataType: 'source', sourceDataType: 'content' })); + return this; + } + prepare() { + if (Object.keys(this.tiles).length === 0 || !this.image) { + return; + } + const context = this.map.painter.context; + const gl = context.gl; + if (!this.boundsBuffer) { + this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members); + } + if (!this.boundsSegments) { + this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2); + } + if (!this.texture) { + this.texture = new Texture(context, this.image, gl.RGBA); + this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + } + let newTilesLoaded = false; + for (const w in this.tiles) { + const tile = this.tiles[w]; + if (tile.state !== 'loaded') { + tile.state = 'loaded'; + tile.texture = this.texture; + newTilesLoaded = true; + } + } + if (newTilesLoaded) { + this.fire(new Event('data', { dataType: 'source', sourceDataType: 'idle', sourceId: this.id })); + } + } + loadTile(tile) { + return __awaiter(this, void 0, void 0, function* () { + // We have a single tile -- whose coordinates are this.tileID -- that + // covers the image we want to render. If that's the one being + // requested, set it up with the image; otherwise, mark the tile as + // `errored` to indicate that we have no data for it. + // If the world wraps, we may have multiple "wrapped" copies of the + // single tile. + if (this.tileID && this.tileID.equals(tile.tileID.canonical)) { + this.tiles[String(tile.tileID.wrap)] = tile; + tile.buckets = {}; + } + else { + tile.state = 'errored'; + } + }); + } + serialize() { + return { + type: 'image', + url: this.options.url, + coordinates: this.coordinates + }; + } + hasTransition() { + return false; + } +} +/** + * Given a list of coordinates, get their center as a coordinate. + * + * @returns centerpoint + * @internal + */ +function getCoordinatesCenterTileID(coords) { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const coord of coords) { + minX = Math.min(minX, coord.x); + minY = Math.min(minY, coord.y); + maxX = Math.max(maxX, coord.x); + maxY = Math.max(maxY, coord.y); + } + const dx = maxX - minX; + const dy = maxY - minY; + const dMax = Math.max(dx, dy); + const zoom = Math.max(0, Math.floor(-Math.log(dMax) / Math.LN2)); + const tilesAtZoom = Math.pow(2, zoom); + return new CanonicalTileID(zoom, Math.floor((minX + maxX) / 2 * tilesAtZoom), Math.floor((minY + maxY) / 2 * tilesAtZoom)); +} + +/** + * A data source containing video. + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-video) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * // add to map + * map.addSource('some id', { + * type: 'video', + * url: [ + * 'https://www.mapbox.com/blog/assets/baltimore-smoke.mp4', + * 'https://www.mapbox.com/blog/assets/baltimore-smoke.webm' + * ], + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update + * let mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * map.removeSource('some id'); // remove + * ``` + * @see [Add a video](https://maplibre.org/maplibre-gl-js/docs/examples/video-on-a-map/) + * + * Note that when rendered as a raster layer, the layer's `raster-fade-duration` property will cause the video to fade in. + * This happens when playback is started, paused and resumed, or when the video's coordinates are updated. To avoid this behavior, + * set the layer's `raster-fade-duration` property to `0`. + */ +class VideoSource extends ImageSource { + constructor(id, options, dispatcher, eventedParent) { + super(id, options, dispatcher, eventedParent); + this.roundZoom = true; + this.type = 'video'; + this.options = options; + } + load() { + return __awaiter(this, void 0, void 0, function* () { + this._loaded = false; + const options = this.options; + this.urls = []; + for (const url of options.urls) { + this.urls.push(this.map._requestManager.transformRequest(url, "Source" /* ResourceType.Source */).url); + } + try { + const video = yield getVideo(this.urls); + this._loaded = true; + if (!video) { + return; + } + this.video = video; + this.video.loop = true; + // Start repainting when video starts playing. hasTransition() will then return + // true to trigger additional frames as long as the videos continues playing. + this.video.addEventListener('playing', () => { + this.map.triggerRepaint(); + }); + if (this.map) { + this.video.play(); + } + this._finishLoading(); + } + catch (err) { + this.fire(new ErrorEvent(err)); + } + }); + } + /** + * Pauses the video. + */ + pause() { + if (this.video) { + this.video.pause(); + } + } + /** + * Plays the video. + */ + play() { + if (this.video) { + this.video.play(); + } + } + /** + * Sets playback to a timestamp, in seconds. + */ + seek(seconds) { + if (this.video) { + const seekableRange = this.video.seekable; + if (seconds < seekableRange.start(0) || seconds > seekableRange.end(0)) { + 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.`))); + } + else + this.video.currentTime = seconds; + } + } + /** + * Returns the HTML `video` element. + * + * @returns The HTML `video` element. + */ + getVideo() { + return this.video; + } + onAdd(map) { + if (this.map) + return; + this.map = map; + this.load(); + if (this.video) { + this.video.play(); + this.setCoordinates(this.coordinates); + } + } + /** + * Sets the video's coordinates and re-renders the map. + */ + prepare() { + if (Object.keys(this.tiles).length === 0 || this.video.readyState < 2) { + return; // not enough data for current position + } + const context = this.map.painter.context; + const gl = context.gl; + if (!this.boundsBuffer) { + this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members); + } + if (!this.boundsSegments) { + this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2); + } + if (!this.texture) { + this.texture = new Texture(context, this.video, gl.RGBA); + this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + } + else if (!this.video.paused) { + this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.video); + } + let newTilesLoaded = false; + for (const w in this.tiles) { + const tile = this.tiles[w]; + if (tile.state !== 'loaded') { + tile.state = 'loaded'; + tile.texture = this.texture; + newTilesLoaded = true; + } + } + if (newTilesLoaded) { + this.fire(new Event('data', { dataType: 'source', sourceDataType: 'idle', sourceId: this.id })); + } + } + serialize() { + return { + type: 'video', + urls: this.urls, + coordinates: this.coordinates + }; + } + hasTransition() { + return this.video && !this.video.paused; + } +} + +/** + * A data source containing the contents of an HTML canvas. See {@link CanvasSourceSpecification} for detailed documentation of options. + * + * @group Sources + * + * @example + * ```ts + * // add to map + * map.addSource('some id', { + * type: 'canvas', + * canvas: 'idOfMyHTMLCanvas', + * animate: true, + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update + * let mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * map.removeSource('some id'); // remove + * ``` + */ +class CanvasSource extends ImageSource { + /** @internal */ + constructor(id, options, dispatcher, eventedParent) { + super(id, options, dispatcher, eventedParent); + // We build in some validation here, since canvas sources aren't included in the style spec: + if (!options.coordinates) { + this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'missing required property "coordinates"'))); + } + else if (!Array.isArray(options.coordinates) || options.coordinates.length !== 4 || + options.coordinates.some(c => !Array.isArray(c) || c.length !== 2 || c.some(l => typeof l !== 'number'))) { + this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, '"coordinates" property must be an array of 4 longitude/latitude array pairs'))); + } + if (options.animate && typeof options.animate !== 'boolean') { + this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'optional "animate" property must be a boolean value'))); + } + if (!options.canvas) { + this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'missing required property "canvas"'))); + } + else if (typeof options.canvas !== 'string' && !(options.canvas instanceof HTMLCanvasElement)) { + 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'))); + } + this.options = options; + this.animate = options.animate !== undefined ? options.animate : true; + } + load() { + return __awaiter(this, void 0, void 0, function* () { + this._loaded = true; + if (!this.canvas) { + this.canvas = (this.options.canvas instanceof HTMLCanvasElement) ? + this.options.canvas : + document.getElementById(this.options.canvas); + // cast to HTMLCanvasElement in else of ternary + // should we do a safety check and throw if it's not actually HTMLCanvasElement? + } + this.width = this.canvas.width; + this.height = this.canvas.height; + if (this._hasInvalidDimensions()) { + this.fire(new ErrorEvent(new Error('Canvas dimensions cannot be less than or equal to zero.'))); + return; + } + this.play = function () { + this._playing = true; + this.map.triggerRepaint(); + }; + this.pause = function () { + if (this._playing) { + this.prepare(); + this._playing = false; + } + }; + this._finishLoading(); + }); + } + /** + * Returns the HTML `canvas` element. + * + * @returns The HTML `canvas` element. + */ + getCanvas() { + return this.canvas; + } + onAdd(map) { + this.map = map; + this.load(); + if (this.canvas) { + if (this.animate) + this.play(); + } + } + onRemove() { + this.pause(); + } + prepare() { + let resize = false; + if (this.canvas.width !== this.width) { + this.width = this.canvas.width; + resize = true; + } + if (this.canvas.height !== this.height) { + this.height = this.canvas.height; + resize = true; + } + if (this._hasInvalidDimensions()) + return; + if (Object.keys(this.tiles).length === 0) + return; // not enough data for current position + const context = this.map.painter.context; + const gl = context.gl; + if (!this.boundsBuffer) { + this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members); + } + if (!this.boundsSegments) { + this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2); + } + if (!this.texture) { + this.texture = new Texture(context, this.canvas, gl.RGBA, { premultiply: true }); + } + else if (resize || this._playing) { + this.texture.update(this.canvas, { premultiply: true }); + } + let newTilesLoaded = false; + for (const w in this.tiles) { + const tile = this.tiles[w]; + if (tile.state !== 'loaded') { + tile.state = 'loaded'; + tile.texture = this.texture; + newTilesLoaded = true; + } + } + if (newTilesLoaded) { + this.fire(new Event('data', { dataType: 'source', sourceDataType: 'idle', sourceId: this.id })); + } + } + serialize() { + return { + type: 'canvas', + coordinates: this.coordinates + }; + } + hasTransition() { + return this._playing; + } + _hasInvalidDimensions() { + for (const x of [this.canvas.width, this.canvas.height]) { + if (isNaN(x) || x <= 0) + return true; + } + return false; + } +} + +const registeredSources = {}; +/** + * Creates a tiled data source instance given an options object. + * + * @param id - The id for the source. Must not be used by any existing source. + * @param specification - Source options, specific to the source type (except for `options.type`, which is always required). + * @param source - A source definition object compliant with + * [`maplibre-gl-style-spec`](https://maplibre.org/maplibre-style-spec/#sources) or, for a third-party source type, + * with that type's requirements. + * @param dispatcher - A {@link Dispatcher} instance, which can be used to send messages to the workers. + * @returns a newly created source + */ +const create = (id, specification, dispatcher, eventedParent) => { + const Class = getSourceType(specification.type); + const source = new Class(id, specification, dispatcher, eventedParent); + if (source.id !== id) { + throw new Error(`Expected Source id to be ${id} instead of ${source.id}`); + } + return source; +}; +const getSourceType = (name) => { + switch (name) { + case 'geojson': + return GeoJSONSource; + case 'image': + return ImageSource; + case 'raster': + return RasterTileSource; + case 'raster-dem': + return RasterDEMTileSource; + case 'vector': + return VectorTileSource; + case 'video': + return VideoSource; + case 'canvas': + return CanvasSource; + } + return registeredSources[name]; +}; +const setSourceType = (name, type) => { + registeredSources[name] = type; +}; +/** + * Adds a custom source type, making it available for use with {@link Map#addSource}. + * @param name - The name of the source type; source definition objects use this name in the `{type: ...}` field. + * @param SourceType - A {@link SourceClass} - which is a constructor for the `Source` interface. + * @returns a promise that is resolved when the source type is ready or rejected with an error. + */ +const addSourceType = (name, SourceType) => __awaiter(void 0, void 0, void 0, function* () { + if (getSourceType(name)) { + throw new Error(`A source type called "${name}" already exists.`); + } + setSourceType(name, SourceType); +}); + +function deserialize(input, style) { + const output = {}; + // Guard against the case where the map's style has been set to null while + // this bucket has been parsing. + if (!style) + return output; + for (const bucket of input) { + const layers = bucket.layerIds + .map((id) => style.getLayer(id)) + .filter(Boolean); + if (layers.length === 0) { + continue; + } + // look up StyleLayer objects from layer ids (since we don't + // want to waste time serializing/copying them from the worker) + bucket.layers = layers; + if (bucket.stateDependentLayerIds) { + bucket.stateDependentLayers = bucket.stateDependentLayerIds.map((lId) => layers.filter((l) => l.id === lId)[0]); + } + for (const layer of layers) { + output[layer.id] = bucket; + } + } + return output; +} + +class DictionaryCoder { + constructor(strings) { + this._stringToNumber = {}; + this._numberToString = []; + for (let i = 0; i < strings.length; i++) { + const string = strings[i]; + this._stringToNumber[string] = i; + this._numberToString[i] = string; + } + } + encode(string) { + return this._stringToNumber[string]; + } + decode(n) { + if (n >= this._numberToString.length) + throw new Error(`Out of bounds. Index requested n=${n} can't be >= this._numberToString.length ${this._numberToString.length}`); + return this._numberToString[n]; + } +} + +/** + * A geojson feature + */ +class GeoJSONFeature { + constructor(vectorTileFeature, z, x, y, id) { + this.type = 'Feature'; + this._vectorTileFeature = vectorTileFeature; + vectorTileFeature._z = z; + vectorTileFeature._x = x; + vectorTileFeature._y = y; + this.properties = vectorTileFeature.properties; + this.id = id; + } + get geometry() { + if (this._geometry === undefined) { + this._geometry = this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x, this._vectorTileFeature._y, this._vectorTileFeature._z).geometry; + } + return this._geometry; + } + set geometry(g) { + this._geometry = g; + } + toJSON() { + const json = { + geometry: this.geometry + }; + for (const i in this) { + if (i === '_geometry' || i === '_vectorTileFeature') + continue; + json[i] = (this)[i]; + } + return json; + } +} + +/** + * An in memory index class to allow fast interaction with features + */ +class FeatureIndex { + constructor(tileID, promoteId) { + this.tileID = tileID; + this.x = tileID.canonical.x; + this.y = tileID.canonical.y; + this.z = tileID.canonical.z; + this.grid = new TransferableGridIndex(EXTENT, 16, 0); + this.grid3D = new TransferableGridIndex(EXTENT, 16, 0); + this.featureIndexArray = new FeatureIndexArray(); + this.promoteId = promoteId; + } + insert(feature, geometry, featureIndex, sourceLayerIndex, bucketIndex, is3D) { + const key = this.featureIndexArray.length; + this.featureIndexArray.emplaceBack(featureIndex, sourceLayerIndex, bucketIndex); + const grid = is3D ? this.grid3D : this.grid; + for (let r = 0; r < geometry.length; r++) { + const ring = geometry[r]; + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + for (let i = 0; i < ring.length; i++) { + const p = ring[i]; + bbox[0] = Math.min(bbox[0], p.x); + bbox[1] = Math.min(bbox[1], p.y); + bbox[2] = Math.max(bbox[2], p.x); + bbox[3] = Math.max(bbox[3], p.y); + } + if (bbox[0] < EXTENT && + bbox[1] < EXTENT && + bbox[2] >= 0 && + bbox[3] >= 0) { + grid.insert(key, bbox[0], bbox[1], bbox[2], bbox[3]); + } + } + } + loadVTLayers() { + if (!this.vtLayers) { + this.vtLayers = new vectorTile.VectorTile(new Protobuf(this.rawTileData)).layers; + this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : ['_geojsonTileLayer']); + } + return this.vtLayers; + } + // Finds non-symbol features in this tile at a particular position. + query(args, styleLayers, serializedLayers, sourceFeatureState) { + this.loadVTLayers(); + const params = args.params || {}, pixelsToTileUnits = EXTENT / args.tileSize / args.scale, filter = createFilter(params.filter); + const queryGeometry = args.queryGeometry; + const queryPadding = args.queryPadding * pixelsToTileUnits; + const bounds = getBounds(queryGeometry); + const matching = this.grid.query(bounds.minX - queryPadding, bounds.minY - queryPadding, bounds.maxX + queryPadding, bounds.maxY + queryPadding); + const cameraBounds = getBounds(args.cameraQueryGeometry); + const matching3D = this.grid3D.query(cameraBounds.minX - queryPadding, cameraBounds.minY - queryPadding, cameraBounds.maxX + queryPadding, cameraBounds.maxY + queryPadding, (bx1, by1, bx2, by2) => { + return polygonIntersectsBox(args.cameraQueryGeometry, bx1 - queryPadding, by1 - queryPadding, bx2 + queryPadding, by2 + queryPadding); + }); + for (const key of matching3D) { + matching.push(key); + } + matching.sort(topDownFeatureComparator); + const result = {}; + let previousIndex; + for (let k = 0; k < matching.length; k++) { + const index = matching[k]; + // don't check the same feature more than once + if (index === previousIndex) + continue; + previousIndex = index; + const match = this.featureIndexArray.get(index); + let featureGeometry = null; + this.loadMatchingFeature(result, match.bucketIndex, match.sourceLayerIndex, match.featureIndex, filter, params.layers, params.availableImages, styleLayers, serializedLayers, sourceFeatureState, (feature, styleLayer, featureState) => { + if (!featureGeometry) { + featureGeometry = loadGeometry(feature); + } + return styleLayer.queryIntersectsFeature(queryGeometry, feature, featureState, featureGeometry, this.z, args.transform, pixelsToTileUnits, args.pixelPosMatrix); + }); + } + return result; + } + loadMatchingFeature(result, bucketIndex, sourceLayerIndex, featureIndex, filter, filterLayerIDs, availableImages, styleLayers, serializedLayers, sourceFeatureState, intersectionTest) { + const layerIDs = this.bucketLayerIDs[bucketIndex]; + if (filterLayerIDs && !arraysIntersect(filterLayerIDs, layerIDs)) + return; + const sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex); + const sourceLayer = this.vtLayers[sourceLayerName]; + const feature = sourceLayer.feature(featureIndex); + if (filter.needGeometry) { + const evaluationFeature = toEvaluationFeature(feature, true); + if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) { + return; + } + } + else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) { + return; + } + const id = this.getId(feature, sourceLayerName); + for (let l = 0; l < layerIDs.length; l++) { + const layerID = layerIDs[l]; + if (filterLayerIDs && filterLayerIDs.indexOf(layerID) < 0) { + continue; + } + const styleLayer = styleLayers[layerID]; + if (!styleLayer) + continue; + let featureState = {}; + if (id && sourceFeatureState) { + // `feature-state` expression evaluation requires feature state to be available + featureState = sourceFeatureState.getState(styleLayer.sourceLayer || '_geojsonTileLayer', id); + } + const serializedLayer = extend({}, serializedLayers[layerID]); + serializedLayer.paint = evaluateProperties(serializedLayer.paint, styleLayer.paint, feature, featureState, availableImages); + serializedLayer.layout = evaluateProperties(serializedLayer.layout, styleLayer.layout, feature, featureState, availableImages); + const intersectionZ = !intersectionTest || intersectionTest(feature, styleLayer, featureState); + if (!intersectionZ) { + // Only applied for non-symbol features + continue; + } + const geojsonFeature = new GeoJSONFeature(feature, this.z, this.x, this.y, id); + geojsonFeature.layer = serializedLayer; + let layerResult = result[layerID]; + if (layerResult === undefined) { + layerResult = result[layerID] = []; + } + layerResult.push({ featureIndex, feature: geojsonFeature, intersectionZ }); + } + } + // Given a set of symbol indexes that have already been looked up, + // return a matching set of GeoJSONFeatures + lookupSymbolFeatures(symbolFeatureIndexes, serializedLayers, bucketIndex, sourceLayerIndex, filterSpec, filterLayerIDs, availableImages, styleLayers) { + const result = {}; + this.loadVTLayers(); + const filter = createFilter(filterSpec); + for (const symbolFeatureIndex of symbolFeatureIndexes) { + this.loadMatchingFeature(result, bucketIndex, sourceLayerIndex, symbolFeatureIndex, filter, filterLayerIDs, availableImages, styleLayers, serializedLayers); + } + return result; + } + hasLayer(id) { + for (const layerIDs of this.bucketLayerIDs) { + for (const layerID of layerIDs) { + if (id === layerID) + return true; + } + } + return false; + } + getId(feature, sourceLayerId) { + let id = feature.id; + if (this.promoteId) { + const propName = typeof this.promoteId === 'string' ? this.promoteId : this.promoteId[sourceLayerId]; + id = feature.properties[propName]; + if (typeof id === 'boolean') + id = Number(id); + } + return id; + } +} +register('FeatureIndex', FeatureIndex, { omit: ['rawTileData', 'sourceLayerCoder'] }); +function evaluateProperties(serializedProperties, styleLayerProperties, feature, featureState, availableImages) { + return mapObject(serializedProperties, (property, key) => { + const prop = styleLayerProperties instanceof PossiblyEvaluated ? styleLayerProperties.get(key) : null; + return prop && prop.evaluate ? prop.evaluate(feature, featureState, availableImages) : prop; + }); +} +function getBounds(geometry) { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const p of geometry) { + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + return { minX, minY, maxX, maxY }; +} +function topDownFeatureComparator(a, b) { + return b - a; +} + +const RTLPluginLoadedEventName = 'RTLPluginLoaded'; + +class RTLMainThreadPlugin extends Evented { + constructor() { + super(...arguments); + this.status = 'unavailable'; + this.url = null; + this.dispatcher = getGlobalDispatcher(); + } + /** Sync RTL plugin state by broadcasting a message to the worker */ + _syncState(statusToSend) { + this.status = statusToSend; + return this.dispatcher.broadcast("SRPS" /* MessageType.syncRTLPluginState */, { pluginStatus: statusToSend, pluginURL: this.url }) + .catch((e) => { + this.status = 'error'; + throw e; + }); + } + /** This one is exposed to outside */ + getRTLTextPluginStatus() { + return this.status; + } + clearRTLTextPlugin() { + this.status = 'unavailable'; + this.url = null; + } + setRTLTextPlugin(url_1) { + return __awaiter(this, arguments, void 0, function* (url, deferred = false) { + if (this.url) { + // error + throw new Error('setRTLTextPlugin cannot be called multiple times.'); + } + this.url = browser.resolveURL(url); + if (!this.url) { + throw new Error(`requested url ${url} is invalid`); + } + if (this.status === 'unavailable') { + // from initial state: + if (deferred) { + this.status = 'deferred'; + // fire and forget: in this case it does not need wait for the broadcasting result + // it is important to sync the deferred status once because + // symbol_bucket will be checking it in worker + this._syncState(this.status); + } + else { + return this._requestImport(); + } + } + else if (this.status === 'requested') { + return this._requestImport(); + } + }); + } + /** Send a message to worker which will import the RTL plugin script */ + _requestImport() { + return __awaiter(this, void 0, void 0, function* () { + // all errors/exceptions will be handled by _syncState + yield this._syncState('loading'); + this.status = 'loaded'; + this.fire(new Event(RTLPluginLoadedEventName)); + }); + } + /** Start a lazy loading process of RTL plugin */ + lazyLoad() { + if (this.status === 'unavailable') { + this.status = 'requested'; + } + else if (this.status === 'deferred') { + this._requestImport(); + } + } +} +let rtlMainThreadPlugin = null; +function rtlMainThreadPluginFactory() { + if (!rtlMainThreadPlugin) { + rtlMainThreadPlugin = new RTLMainThreadPlugin(); + } + return rtlMainThreadPlugin; +} + +const CLOCK_SKEW_RETRY_TIMEOUT = 30000; +/** + * A tile object is the combination of a Coordinate, which defines + * its place, as well as a unique ID and data tracking for its content + */ +class Tile { + /** + * @param tileID - the tile ID + * @param size - The tile size + */ + constructor(tileID, size) { + this.timeAdded = 0; + this.fadeEndTime = 0; + this.tileID = tileID; + this.uid = uniqueId(); + this.uses = 0; + this.tileSize = size; + this.buckets = {}; + this.expirationTime = null; + this.queryPadding = 0; + this.hasSymbolBuckets = false; + this.hasRTLText = false; + this.dependencies = {}; + this.rtt = []; + this.rttCoords = {}; + // Counts the number of times a response was already expired when + // received. We're using this to add a delay when making a new request + // so we don't have to keep retrying immediately in case of a server + // serving expired tiles. + this.expiredRequestCount = 0; + this.state = 'loading'; + } + registerFadeDuration(duration) { + const fadeEndTime = duration + this.timeAdded; + if (fadeEndTime < this.fadeEndTime) { + return; + } + this.fadeEndTime = fadeEndTime; + } + wasRequested() { + return this.state === 'errored' || this.state === 'loaded' || this.state === 'reloading'; + } + clearTextures(painter) { + if (this.demTexture) + painter.saveTileTexture(this.demTexture); + this.demTexture = null; + } + /** + * Given a data object with a 'buffers' property, load it into + * this tile's elementGroups and buffers properties and set loaded + * to true. If the data is null, like in the case of an empty + * GeoJSON tile, no-op but still set loaded to true. + * @param data - The data from the worker + * @param painter - the painter + * @param justReloaded - `true` to just reload + */ + loadVectorData(data, painter, justReloaded) { + if (this.hasData()) { + this.unloadVectorData(); + } + this.state = 'loaded'; + // empty GeoJSON tile + if (!data) { + this.collisionBoxArray = new CollisionBoxArray(); + return; + } + if (data.featureIndex) { + this.latestFeatureIndex = data.featureIndex; + if (data.rawTileData) { + // Only vector tiles have rawTileData, and they won't update it for + // 'reloadTile' + this.latestRawTileData = data.rawTileData; + this.latestFeatureIndex.rawTileData = data.rawTileData; + } + else if (this.latestRawTileData) { + // If rawTileData hasn't updated, hold onto a pointer to the last + // one we received + this.latestFeatureIndex.rawTileData = this.latestRawTileData; + } + } + this.collisionBoxArray = data.collisionBoxArray; + this.buckets = deserialize(data.buckets, painter.style); + this.hasSymbolBuckets = false; + for (const id in this.buckets) { + const bucket = this.buckets[id]; + if (bucket instanceof SymbolBucket) { + this.hasSymbolBuckets = true; + if (justReloaded) { + bucket.justReloaded = true; + } + else { + break; + } + } + } + this.hasRTLText = false; + if (this.hasSymbolBuckets) { + for (const id in this.buckets) { + const bucket = this.buckets[id]; + if (bucket instanceof SymbolBucket) { + if (bucket.hasRTLText) { + this.hasRTLText = true; + rtlMainThreadPluginFactory().lazyLoad(); + break; + } + } + } + } + this.queryPadding = 0; + for (const id in this.buckets) { + const bucket = this.buckets[id]; + this.queryPadding = Math.max(this.queryPadding, painter.style.getLayer(id).queryRadius(bucket)); + } + if (data.imageAtlas) { + this.imageAtlas = data.imageAtlas; + } + if (data.imageBackgroundsAtlas) { + this.imageBackgroundsAtlas = data.imageBackgroundsAtlas; + } + if (data.glyphAtlasImage) { + this.glyphAtlasImage = data.glyphAtlasImage; + } + } + /** + * Release any data or WebGL resources referenced by this tile. + */ + unloadVectorData() { + for (const id in this.buckets) { + this.buckets[id].destroy(); + } + this.buckets = {}; + if (this.imageAtlasTexture) { + this.imageAtlasTexture.destroy(); + } + if (this.imageBackgroundsAtlasTexture) { + this.imageBackgroundsAtlasTexture.destroy(); + } + if (this.imageAtlas) { + this.imageAtlas = null; + } + if (this.imageBackgroundsAtlas) { + this.imageBackgroundsAtlas = null; + } + if (this.glyphAtlasTexture) { + this.glyphAtlasTexture.destroy(); + } + this.latestFeatureIndex = null; + this.state = 'unloaded'; + } + getBucket(layer) { + return this.buckets[layer.id]; + } + upload(context) { + for (const id in this.buckets) { + const bucket = this.buckets[id]; + if (bucket.uploadPending()) { + bucket.upload(context); + } + } + const gl = context.gl; + if (this.imageAtlas && !this.imageAtlas.uploaded) { + this.imageAtlasTexture = new Texture(context, this.imageAtlas.image, gl.RGBA); + this.imageAtlas.uploaded = true; + } + if (this.imageBackgroundsAtlas && !this.imageBackgroundsAtlas.uploaded) { + this.imageBackgroundsAtlasTexture = new Texture(context, this.imageBackgroundsAtlas.image, gl.RGBA); + this.imageBackgroundsAtlas.uploaded = true; + } + if (this.glyphAtlasImage) { + this.glyphAtlasTexture = new Texture(context, this.glyphAtlasImage, gl.ALPHA); + this.glyphAtlasImage = null; + } + } + prepare(imageManager) { + if (this.imageAtlas) { + this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture); + } + if (this.imageBackgroundsAtlas) { + this.imageBackgroundsAtlas.patchUpdatedImages(imageManager, this.imageBackgroundsAtlasTexture); + } + } + // Queries non-symbol features rendered for this tile. + // Symbol features are queried globally + queryRenderedFeatures(layers, serializedLayers, sourceFeatureState, queryGeometry, cameraQueryGeometry, scale, params, transform, maxPitchScaleFactor, pixelPosMatrix) { + if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData) + return {}; + return this.latestFeatureIndex.query({ + queryGeometry, + cameraQueryGeometry, + scale, + tileSize: this.tileSize, + pixelPosMatrix, + transform, + params, + queryPadding: this.queryPadding * maxPitchScaleFactor + }, layers, serializedLayers, sourceFeatureState); + } + querySourceFeatures(result, params) { + const featureIndex = this.latestFeatureIndex; + if (!featureIndex || !featureIndex.rawTileData) + return; + const vtLayers = featureIndex.loadVTLayers(); + const sourceLayer = params && params.sourceLayer ? params.sourceLayer : ''; + const layer = vtLayers._geojsonTileLayer || vtLayers[sourceLayer]; + if (!layer) + return; + const filter = createFilter(params && params.filter); + const { z, x, y } = this.tileID.canonical; + const coord = { z, x, y }; + for (let i = 0; i < layer.length; i++) { + const feature = layer.feature(i); + if (filter.needGeometry) { + const evaluationFeature = toEvaluationFeature(feature, true); + if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) + continue; + } + else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) { + continue; + } + const id = featureIndex.getId(feature, sourceLayer); + const geojsonFeature = new GeoJSONFeature(feature, z, x, y, id); + geojsonFeature.tile = coord; + result.push(geojsonFeature); + } + } + hasData() { + return this.state === 'loaded' || this.state === 'reloading' || this.state === 'expired'; + } + patternsLoaded() { + return this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length; + } + setExpiryData(data) { + const prior = this.expirationTime; + if (data.cacheControl) { + const parsedCC = parseCacheControl(data.cacheControl); + if (parsedCC['max-age']) + this.expirationTime = Date.now() + parsedCC['max-age'] * 1000; + } + else if (data.expires) { + this.expirationTime = new Date(data.expires).getTime(); + } + if (this.expirationTime) { + const now = Date.now(); + let isExpired = false; + if (this.expirationTime > now) { + isExpired = false; + } + else if (!prior) { + isExpired = true; + } + else if (this.expirationTime < prior) { + // Expiring date is going backwards: + // fall back to exponential backoff + isExpired = true; + } + else { + const delta = this.expirationTime - prior; + if (!delta) { + // Server is serving the same expired resource over and over: fall + // back to exponential backoff. + isExpired = true; + } + else { + // Assume that either the client or the server clock is wrong and + // try to interpolate a valid expiration date (from the client POV) + // observing a minimum timeout. + this.expirationTime = now + Math.max(delta, CLOCK_SKEW_RETRY_TIMEOUT); + } + } + if (isExpired) { + this.expiredRequestCount++; + this.state = 'expired'; + } + else { + this.expiredRequestCount = 0; + } + } + } + getExpiryTimeout() { + if (this.expirationTime) { + if (this.expiredRequestCount) { + return 1000 * (1 << Math.min(this.expiredRequestCount - 1, 31)); + } + else { + // Max value for `setTimeout` implementations is a 32 bit integer; cap this accordingly + return Math.min(this.expirationTime - new Date().getTime(), Math.pow(2, 31) - 1); + } + } + } + setFeatureState(states, painter) { + if (!this.latestFeatureIndex || + !this.latestFeatureIndex.rawTileData || + Object.keys(states).length === 0) { + return; + } + const vtLayers = this.latestFeatureIndex.loadVTLayers(); + for (const id in this.buckets) { + if (!painter.style.hasLayer(id)) + continue; + const bucket = this.buckets[id]; + // Buckets are grouped by common source-layer + const sourceLayerId = bucket.layers[0]['sourceLayer'] || '_geojsonTileLayer'; + const sourceLayer = vtLayers[sourceLayerId]; + const sourceLayerStates = states[sourceLayerId]; + if (!sourceLayer || !sourceLayerStates || Object.keys(sourceLayerStates).length === 0) + continue; + bucket.update(sourceLayerStates, sourceLayer, this.imageAtlas && this.imageAtlas.patternPositions || {}); + const layer = painter && painter.style && painter.style.getLayer(id); + if (layer) { + this.queryPadding = Math.max(this.queryPadding, layer.queryRadius(bucket)); + } + } + } + holdingForFade() { + return this.symbolFadeHoldUntil !== undefined; + } + symbolFadeFinished() { + return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < browser.now(); + } + clearFadeHold() { + this.symbolFadeHoldUntil = undefined; + } + setHoldDuration(duration) { + this.symbolFadeHoldUntil = browser.now() + duration; + } + setDependencies(namespace, dependencies) { + const index = {}; + for (const dep of dependencies) { + index[dep] = true; + } + this.dependencies[namespace] = index; + } + hasDependency(namespaces, keys) { + for (const namespace of namespaces) { + const dependencies = this.dependencies[namespace]; + if (dependencies) { + for (const key of keys) { + if (dependencies[key]) { + return true; + } + } + } + } + return false; + } +} + +/** + * @internal + * A [least-recently-used cache](https://en.wikipedia.org/wiki/Cache_algorithms) + * with hash lookup made possible by keeping a list of keys in parallel to + * an array of dictionary of values + */ +class TileCache { + /** + * @param max - number of permitted values + * @param onRemove - callback called with items when they expire + */ + constructor(max, onRemove) { + this.max = max; + this.onRemove = onRemove; + this.reset(); + } + /** + * Clear the cache + * + * @returns this cache + */ + reset() { + for (const key in this.data) { + for (const removedData of this.data[key]) { + if (removedData.timeout) + clearTimeout(removedData.timeout); + this.onRemove(removedData.value); + } + } + this.data = {}; + this.order = []; + return this; + } + /** + * Add a key, value combination to the cache, trimming its size if this pushes + * it over max length. + * + * @param tileID - lookup key for the item + * @param data - tile data + * + * @returns this cache + */ + add(tileID, data, expiryTimeout) { + const key = tileID.wrapped().key; + if (this.data[key] === undefined) { + this.data[key] = []; + } + const dataWrapper = { + value: data, + timeout: undefined + }; + if (expiryTimeout !== undefined) { + dataWrapper.timeout = setTimeout(() => { + this.remove(tileID, dataWrapper); + }, expiryTimeout); + } + this.data[key].push(dataWrapper); + this.order.push(key); + if (this.order.length > this.max) { + const removedData = this._getAndRemoveByKey(this.order[0]); + if (removedData) + this.onRemove(removedData); + } + return this; + } + /** + * Determine whether the value attached to `key` is present + * + * @param tileID - the key to be looked-up + * @returns whether the cache has this value + */ + has(tileID) { + return tileID.wrapped().key in this.data; + } + /** + * Get the value attached to a specific key and remove data from cache. + * If the key is not found, returns `null` + * + * @param tileID - the key to look up + * @returns the tile data, or null if it isn't found + */ + getAndRemove(tileID) { + if (!this.has(tileID)) { + return null; + } + return this._getAndRemoveByKey(tileID.wrapped().key); + } + /* + * Get and remove the value with the specified key. + */ + _getAndRemoveByKey(key) { + const data = this.data[key].shift(); + if (data.timeout) + clearTimeout(data.timeout); + if (this.data[key].length === 0) { + delete this.data[key]; + } + this.order.splice(this.order.indexOf(key), 1); + return data.value; + } + /* + * Get the value with the specified (wrapped tile) key. + */ + getByKey(key) { + const data = this.data[key]; + return data ? data[0].value : null; + } + /** + * Get the value attached to a specific key without removing data + * from the cache. If the key is not found, returns `null` + * + * @param tileID - the key to look up + * @returns the tile data, or null if it isn't found + */ + get(tileID) { + if (!this.has(tileID)) { + return null; + } + const data = this.data[tileID.wrapped().key][0]; + return data.value; + } + /** + * Remove a key/value combination from the cache. + * + * @param tileID - the key for the pair to delete + * @param value - If a value is provided, remove that exact version of the value. + * @returns this cache + */ + remove(tileID, value) { + if (!this.has(tileID)) { + return this; + } + const key = tileID.wrapped().key; + const dataIndex = value === undefined ? 0 : this.data[key].indexOf(value); + const data = this.data[key][dataIndex]; + this.data[key].splice(dataIndex, 1); + if (data.timeout) + clearTimeout(data.timeout); + if (this.data[key].length === 0) { + delete this.data[key]; + } + this.onRemove(data.value); + this.order.splice(this.order.indexOf(key), 1); + return this; + } + /** + * Change the max size of the cache. + * + * @param max - the max size of the cache + * @returns this cache + */ + setMaxSize(max) { + this.max = max; + while (this.order.length > this.max) { + const removedData = this._getAndRemoveByKey(this.order[0]); + if (removedData) + this.onRemove(removedData); + } + return this; + } + /** + * Remove entries that do not pass a filter function. Used for removing + * stale tiles from the cache. + * + * @param filterFn - Determines whether the tile is filtered. If the supplied function returns false, the tile will be filtered out. + */ + filter(filterFn) { + const removed = []; + for (const key in this.data) { + for (const entry of this.data[key]) { + if (!filterFn(entry.value)) { + removed.push(entry); + } + } + } + for (const r of removed) { + this.remove(r.value.tileID, r); + } + } +} + +/** + * @internal + * SourceFeatureState manages the state and pending changes + * to features in a source, separated by source layer. + * stateChanges and deletedStates batch all changes to the tile (updates and removes, respectively) + * between coalesce() events. addFeatureState() and removeFeatureState() also update their counterpart's + * list of changes, such that coalesce() can apply the proper state changes while agnostic to the order of operations. + * In deletedStates, all null's denote complete removal of state at that scope +*/ +class SourceFeatureState { + constructor() { + this.state = {}; + this.stateChanges = {}; + this.deletedStates = {}; + } + updateState(sourceLayer, featureId, newState) { + const feature = String(featureId); + this.stateChanges[sourceLayer] = this.stateChanges[sourceLayer] || {}; + this.stateChanges[sourceLayer][feature] = this.stateChanges[sourceLayer][feature] || {}; + extend(this.stateChanges[sourceLayer][feature], newState); + if (this.deletedStates[sourceLayer] === null) { + this.deletedStates[sourceLayer] = {}; + for (const ft in this.state[sourceLayer]) { + if (ft !== feature) + this.deletedStates[sourceLayer][ft] = null; + } + } + else { + const featureDeletionQueued = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] === null; + if (featureDeletionQueued) { + this.deletedStates[sourceLayer][feature] = {}; + for (const prop in this.state[sourceLayer][feature]) { + if (!newState[prop]) + this.deletedStates[sourceLayer][feature][prop] = null; + } + } + else { + for (const key in newState) { + const deletionInQueue = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] && this.deletedStates[sourceLayer][feature][key] === null; + if (deletionInQueue) + delete this.deletedStates[sourceLayer][feature][key]; + } + } + } + } + removeFeatureState(sourceLayer, featureId, key) { + const sourceLayerDeleted = this.deletedStates[sourceLayer] === null; + if (sourceLayerDeleted) + return; + const feature = String(featureId); + this.deletedStates[sourceLayer] = this.deletedStates[sourceLayer] || {}; + if (key && featureId !== undefined) { + if (this.deletedStates[sourceLayer][feature] !== null) { + this.deletedStates[sourceLayer][feature] = this.deletedStates[sourceLayer][feature] || {}; + this.deletedStates[sourceLayer][feature][key] = null; + } + } + else if (featureId !== undefined) { + const updateInQueue = this.stateChanges[sourceLayer] && this.stateChanges[sourceLayer][feature]; + if (updateInQueue) { + this.deletedStates[sourceLayer][feature] = {}; + for (key in this.stateChanges[sourceLayer][feature]) + this.deletedStates[sourceLayer][feature][key] = null; + } + else { + this.deletedStates[sourceLayer][feature] = null; + } + } + else { + this.deletedStates[sourceLayer] = null; + } + } + getState(sourceLayer, featureId) { + const feature = String(featureId); + const base = this.state[sourceLayer] || {}; + const changes = this.stateChanges[sourceLayer] || {}; + const reconciledState = extend({}, base[feature], changes[feature]); + //return empty object if the whole source layer is awaiting deletion + if (this.deletedStates[sourceLayer] === null) + return {}; + else if (this.deletedStates[sourceLayer]) { + const featureDeletions = this.deletedStates[sourceLayer][featureId]; + if (featureDeletions === null) + return {}; + for (const prop in featureDeletions) + delete reconciledState[prop]; + } + return reconciledState; + } + initializeTileState(tile, painter) { + tile.setFeatureState(this.state, painter); + } + coalesceChanges(tiles, painter) { + //track changes with full state objects, but only for features that got modified + const featuresChanged = {}; + for (const sourceLayer in this.stateChanges) { + this.state[sourceLayer] = this.state[sourceLayer] || {}; + const layerStates = {}; + for (const feature in this.stateChanges[sourceLayer]) { + if (!this.state[sourceLayer][feature]) + this.state[sourceLayer][feature] = {}; + extend(this.state[sourceLayer][feature], this.stateChanges[sourceLayer][feature]); + layerStates[feature] = this.state[sourceLayer][feature]; + } + featuresChanged[sourceLayer] = layerStates; + } + for (const sourceLayer in this.deletedStates) { + this.state[sourceLayer] = this.state[sourceLayer] || {}; + const layerStates = {}; + if (this.deletedStates[sourceLayer] === null) { + for (const ft in this.state[sourceLayer]) { + layerStates[ft] = {}; + this.state[sourceLayer][ft] = {}; + } + } + else { + for (const feature in this.deletedStates[sourceLayer]) { + const deleteWholeFeatureState = this.deletedStates[sourceLayer][feature] === null; + if (deleteWholeFeatureState) + this.state[sourceLayer][feature] = {}; + else { + for (const key of Object.keys(this.deletedStates[sourceLayer][feature])) { + delete this.state[sourceLayer][feature][key]; + } + } + layerStates[feature] = this.state[sourceLayer][feature]; + } + } + featuresChanged[sourceLayer] = featuresChanged[sourceLayer] || {}; + extend(featuresChanged[sourceLayer], layerStates); + } + this.stateChanges = {}; + this.deletedStates = {}; + if (Object.keys(featuresChanged).length === 0) + return; + for (const id in tiles) { + const tile = tiles[id]; + tile.setFeatureState(featuresChanged, painter); + } + } +} + +/** + * @internal + * `SourceCache` is responsible for + * + * - creating an instance of `Source` + * - forwarding events from `Source` + * - caching tiles loaded from an instance of `Source` + * - loading the tiles needed to render a given viewport + * - unloading the cached tiles not needed to render a given viewport + */ +class SourceCache extends Evented { + constructor(id, options, dispatcher) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.on('data', (e) => this._dataHandler(e)); + this.on('dataloading', () => { + this._sourceErrored = false; + }); + this.on('error', () => { + // Only set _sourceErrored if the source does not have pending loads. + this._sourceErrored = this._source.loaded(); + }); + this._source = create(id, options, dispatcher, this); + this._tiles = {}; + this._cache = new TileCache(0, (tile) => this._unloadTile(tile)); + this._timers = {}; + this._cacheTimers = {}; + this._maxTileCacheSize = null; + this._maxTileCacheZoomLevels = null; + this._loadedParentTiles = {}; + this._coveredTiles = {}; + this._state = new SourceFeatureState(); + this._didEmitContent = false; + this._updated = false; + } + onAdd(map) { + this.map = map; + this._maxTileCacheSize = map ? map._maxTileCacheSize : null; + this._maxTileCacheZoomLevels = map ? map._maxTileCacheZoomLevels : null; + if (this._source && this._source.onAdd) { + this._source.onAdd(map); + } + } + onRemove(map) { + this.clearTiles(); + if (this._source && this._source.onRemove) { + this._source.onRemove(map); + } + } + /** + * Return true if no tile data is pending, tiles will not change unless + * an additional API call is received. + */ + loaded() { + if (this._sourceErrored) { + return true; + } + if (!this._sourceLoaded) { + return false; + } + if (!this._source.loaded()) { + return false; + } + if ((this.used !== undefined || this.usedForTerrain !== undefined) && !this.used && !this.usedForTerrain) { + return true; + } + // do not consider as loaded if the update hasn't been called yet (we do not know if we will have any tiles to fetch) + if (!this._updated) { + return false; + } + for (const t in this._tiles) { + const tile = this._tiles[t]; + if (tile.state !== 'loaded' && tile.state !== 'errored') + return false; + } + return true; + } + getSource() { + return this._source; + } + pause() { + this._paused = true; + } + resume() { + if (!this._paused) + return; + const shouldReload = this._shouldReloadOnResume; + this._paused = false; + this._shouldReloadOnResume = false; + if (shouldReload) + this.reload(); + if (this.transform) + this.update(this.transform, this.terrain); + } + _loadTile(tile, id, state) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield this._source.loadTile(tile); + this._tileLoaded(tile, id, state); + } + catch (err) { + tile.state = 'errored'; + if (err.status !== 404) { + this._source.fire(new ErrorEvent(err, { tile })); + } + else { + // continue to try loading parent/children tiles if a tile doesn't exist (404) + this.update(this.transform, this.terrain); + } + } + }); + } + _unloadTile(tile) { + if (this._source.unloadTile) + this._source.unloadTile(tile); + } + _abortTile(tile) { + if (this._source.abortTile) + this._source.abortTile(tile); + this._source.fire(new Event('dataabort', { tile, coord: tile.tileID, dataType: 'source' })); + } + serialize() { + return this._source.serialize(); + } + prepare(context) { + if (this._source.prepare) { + this._source.prepare(); + } + this._state.coalesceChanges(this._tiles, this.map ? this.map.painter : null); + for (const i in this._tiles) { + const tile = this._tiles[i]; + tile.upload(context); + tile.prepare(this.map.style.imageManager); + } + } + /** + * Return all tile ids ordered with z-order, and cast to numbers + */ + getIds() { + return Object.values(this._tiles).map((tile) => tile.tileID).sort(compareTileId).map(id => id.key); + } + getRenderableIds(symbolLayer) { + const renderables = []; + for (const id in this._tiles) { + if (this._isIdRenderable(id, symbolLayer)) + renderables.push(this._tiles[id]); + } + if (symbolLayer) { + return renderables.sort((a_, b_) => { + const a = a_.tileID; + const b = b_.tileID; + const rotatedA = (new Point$2(a.canonical.x, a.canonical.y))._rotate(this.transform.angle); + const rotatedB = (new Point$2(b.canonical.x, b.canonical.y))._rotate(this.transform.angle); + return a.overscaledZ - b.overscaledZ || rotatedB.y - rotatedA.y || rotatedB.x - rotatedA.x; + }).map(tile => tile.tileID.key); + } + return renderables.map(tile => tile.tileID).sort(compareTileId).map(id => id.key); + } + hasRenderableParent(tileID) { + const parentTile = this.findLoadedParent(tileID, 0); + if (parentTile) { + return this._isIdRenderable(parentTile.tileID.key); + } + return false; + } + _isIdRenderable(id, symbolLayer) { + return this._tiles[id] && this._tiles[id].hasData() && + !this._coveredTiles[id] && (symbolLayer || !this._tiles[id].holdingForFade()); + } + reload() { + if (this._paused) { + this._shouldReloadOnResume = true; + return; + } + this._cache.reset(); + for (const i in this._tiles) { + if (this._tiles[i].state !== 'errored') + this._reloadTile(i, 'reloading'); + } + } + _reloadTile(id, state) { + return __awaiter(this, void 0, void 0, function* () { + const tile = this._tiles[id]; + // this potentially does not address all underlying + // issues https://github.com/mapbox/mapbox-gl-js/issues/4252 + // - hard to tell without repro steps + if (!tile) + return; + // The difference between "loading" tiles and "reloading" or "expired" + // tiles is that "reloading"/"expired" tiles are "renderable". + // Therefore, a "loading" tile cannot become a "reloading" tile without + // first becoming a "loaded" tile. + if (tile.state !== 'loading') { + tile.state = state; + } + yield this._loadTile(tile, id, state); + }); + } + _tileLoaded(tile, id, previousState) { + tile.timeAdded = browser.now(); + if (previousState === 'expired') + tile.refreshedUponExpiration = true; + this._setTileReloadTimer(id, tile); + if (this.getSource().type === 'raster-dem' && tile.dem) + this._backfillDEM(tile); + this._state.initializeTileState(tile, this.map ? this.map.painter : null); + if (!tile.aborted) { + this._source.fire(new Event('data', { dataType: 'source', tile, coord: tile.tileID })); + } + } + /** + * For raster terrain source, backfill DEM to eliminate visible tile boundaries + */ + _backfillDEM(tile) { + const renderables = this.getRenderableIds(); + for (let i = 0; i < renderables.length; i++) { + const borderId = renderables[i]; + if (tile.neighboringTiles && tile.neighboringTiles[borderId]) { + const borderTile = this.getTileByID(borderId); + fillBorder(tile, borderTile); + fillBorder(borderTile, tile); + } + } + function fillBorder(tile, borderTile) { + tile.needsHillshadePrepare = true; + tile.needsTerrainPrepare = true; + let dx = borderTile.tileID.canonical.x - tile.tileID.canonical.x; + const dy = borderTile.tileID.canonical.y - tile.tileID.canonical.y; + const dim = Math.pow(2, tile.tileID.canonical.z); + const borderId = borderTile.tileID.key; + if (dx === 0 && dy === 0) + return; + if (Math.abs(dy) > 1) { + return; + } + if (Math.abs(dx) > 1) { + // Adjust the delta coordinate for world wraparound. + if (Math.abs(dx + dim) === 1) { + dx += dim; + } + else if (Math.abs(dx - dim) === 1) { + dx -= dim; + } + } + if (!borderTile.dem || !tile.dem) + return; + tile.dem.backfillBorder(borderTile.dem, dx, dy); + if (tile.neighboringTiles && tile.neighboringTiles[borderId]) + tile.neighboringTiles[borderId].backfilled = true; + } + } + /** + * Get a specific tile by TileID + */ + getTile(tileID) { + return this.getTileByID(tileID.key); + } + /** + * Get a specific tile by id + */ + getTileByID(id) { + return this._tiles[id]; + } + /** + * For a given set of tiles, retain children that are loaded and have a zoom + * between `zoom` (exclusive) and `maxCoveringZoom` (inclusive) + */ + _retainLoadedChildren(idealTiles, zoom, maxCoveringZoom, retain) { + for (const id in this._tiles) { + let tile = this._tiles[id]; + // only consider renderable tiles up to maxCoveringZoom + if (retain[id] || + !tile.hasData() || + tile.tileID.overscaledZ <= zoom || + tile.tileID.overscaledZ > maxCoveringZoom) + continue; + // loop through parents and retain the topmost loaded one if found + let topmostLoadedID = tile.tileID; + while (tile && tile.tileID.overscaledZ > zoom + 1) { + const parentID = tile.tileID.scaledTo(tile.tileID.overscaledZ - 1); + tile = this._tiles[parentID.key]; + if (tile && tile.hasData()) { + topmostLoadedID = parentID; + } + } + // loop through ancestors of the topmost loaded child to see if there's one that needed it + let tileID = topmostLoadedID; + while (tileID.overscaledZ > zoom) { + tileID = tileID.scaledTo(tileID.overscaledZ - 1); + if (idealTiles[tileID.key]) { + // found a parent that needed a loaded child; retain that child + retain[topmostLoadedID.key] = topmostLoadedID; + break; + } + } + } + } + /** + * Find a loaded parent of the given tile (up to minCoveringZoom) + */ + findLoadedParent(tileID, minCoveringZoom) { + if (tileID.key in this._loadedParentTiles) { + const parent = this._loadedParentTiles[tileID.key]; + if (parent && parent.tileID.overscaledZ >= minCoveringZoom) { + return parent; + } + else { + return null; + } + } + for (let z = tileID.overscaledZ - 1; z >= minCoveringZoom; z--) { + const parentTileID = tileID.scaledTo(z); + const tile = this._getLoadedTile(parentTileID); + if (tile) { + return tile; + } + } + } + /** + * Find a loaded sibling of the given tile + */ + findLoadedSibling(tileID) { + // If a tile with this ID already exists, return it + return this._getLoadedTile(tileID); + } + _getLoadedTile(tileID) { + const tile = this._tiles[tileID.key]; + if (tile && tile.hasData()) { + return tile; + } + // TileCache ignores wrap in lookup. + const cachedTile = this._cache.getByKey(tileID.wrapped().key); + return cachedTile; + } + /** + * Resizes the tile cache based on the current viewport's size + * or the maxTileCacheSize option passed during map creation + * + * Larger viewports use more tiles and need larger caches. Larger viewports + * are more likely to be found on devices with more memory and on pages where + * the map is more important. + */ + updateCacheSize(transform) { + const widthInTiles = Math.ceil(transform.width / this._source.tileSize) + 1; + const heightInTiles = Math.ceil(transform.height / this._source.tileSize) + 1; + const approxTilesInView = widthInTiles * heightInTiles; + const commonZoomRange = this._maxTileCacheZoomLevels === null ? + config.MAX_TILE_CACHE_ZOOM_LEVELS : this._maxTileCacheZoomLevels; + const viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange); + const maxSize = typeof this._maxTileCacheSize === 'number' ? + Math.min(this._maxTileCacheSize, viewDependentMaxSize) : viewDependentMaxSize; + this._cache.setMaxSize(maxSize); + } + handleWrapJump(lng) { + // On top of the regular z/x/y values, TileIDs have a `wrap` value that specify + // which cppy of the world the tile belongs to. For example, at `lng: 10` you + // might render z/x/y/0 while at `lng: 370` you would render z/x/y/1. + // + // When lng values get wrapped (going from `lng: 370` to `long: 10`) you expect + // to see the same thing on the screen (370 degrees and 10 degrees is the same + // place in the world) but all the TileIDs will have different wrap values. + // + // In order to make this transition seamless, we calculate the rounded difference of + // "worlds" between the last frame and the current frame. If the map panned by + // a world, then we can assign all the tiles new TileIDs with updated wrap values. + // For example, assign z/x/y/1 a new id: z/x/y/0. It is the same tile, just rendered + // in a different position. + // + // This enables us to reuse the tiles at more ideal locations and prevent flickering. + const prevLng = this._prevLng === undefined ? lng : this._prevLng; + const lngDifference = lng - prevLng; + const worldDifference = lngDifference / 360; + const wrapDelta = Math.round(worldDifference); + this._prevLng = lng; + if (wrapDelta) { + const tiles = {}; + for (const key in this._tiles) { + const tile = this._tiles[key]; + tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta); + tiles[tile.tileID.key] = tile; + } + this._tiles = tiles; + // Reset tile reload timers + for (const id in this._timers) { + clearTimeout(this._timers[id]); + delete this._timers[id]; + } + for (const id in this._tiles) { + const tile = this._tiles[id]; + this._setTileReloadTimer(id, tile); + } + } + } + _updateCoveredAndRetainedTiles(retain, minCoveringZoom, maxCoveringZoom, zoom, idealTileIDs, terrain) { + const tilesForFading = {}; + const fadingTiles = {}; + const ids = Object.keys(retain); + const now = browser.now(); + for (const id of ids) { + const tileID = retain[id]; + const tile = this._tiles[id]; + // when fadeEndTime is 0, the tile is created but registerFadeDuration + // has not been called, therefore must be kept in fadingTiles dictionary + // for next round of rendering + if (!tile || (tile.fadeEndTime !== 0 && tile.fadeEndTime <= now)) { + continue; + } + // if the tile is loaded but still fading in, find parents to cross-fade with it + const parentTile = this.findLoadedParent(tileID, minCoveringZoom); + const siblingTile = this.findLoadedSibling(tileID); + const fadeTileRef = parentTile || siblingTile || null; + if (fadeTileRef) { + this._addTile(fadeTileRef.tileID); + tilesForFading[fadeTileRef.tileID.key] = fadeTileRef.tileID; + } + fadingTiles[id] = tileID; + } + // for tiles that are still fading in, also find children to cross-fade with + this._retainLoadedChildren(fadingTiles, zoom, maxCoveringZoom, retain); + for (const id in tilesForFading) { + if (!retain[id]) { + // If a tile is only needed for fading, mark it as covered so that it isn't rendered on it's own. + this._coveredTiles[id] = true; + retain[id] = tilesForFading[id]; + } + } + // disable fading logic in terrain3D mode to avoid rendering two tiles on the same place + if (terrain) { + const idealRasterTileIDs = {}; + const missingTileIDs = {}; + for (const tileID of idealTileIDs) { + if (this._tiles[tileID.key].hasData()) + idealRasterTileIDs[tileID.key] = tileID; + else + missingTileIDs[tileID.key] = tileID; + } + // search for a complete set of children for each missing tile + for (const key in missingTileIDs) { + const children = missingTileIDs[key].children(this._source.maxzoom); + if (this._tiles[children[0].key] && this._tiles[children[1].key] && this._tiles[children[2].key] && this._tiles[children[3].key]) { + idealRasterTileIDs[children[0].key] = retain[children[0].key] = children[0]; + idealRasterTileIDs[children[1].key] = retain[children[1].key] = children[1]; + idealRasterTileIDs[children[2].key] = retain[children[2].key] = children[2]; + idealRasterTileIDs[children[3].key] = retain[children[3].key] = children[3]; + delete missingTileIDs[key]; + } + } + // search for parent or sibling for each missing tile + for (const key in missingTileIDs) { + const tileID = missingTileIDs[key]; + const parentTile = this.findLoadedParent(tileID, this._source.minzoom); + const siblingTile = this.findLoadedSibling(tileID); + const fadeTileRef = parentTile || siblingTile || null; + if (fadeTileRef) { + idealRasterTileIDs[fadeTileRef.tileID.key] = retain[fadeTileRef.tileID.key] = fadeTileRef.tileID; + // remove idealTiles which would be rendered twice + for (const key in idealRasterTileIDs) { + if (idealRasterTileIDs[key].isChildOf(fadeTileRef.tileID)) + delete idealRasterTileIDs[key]; + } + } + } + // cover all tiles which are not needed + for (const key in this._tiles) { + if (!idealRasterTileIDs[key]) + this._coveredTiles[key] = true; + } + } + } + /** + * Removes tiles that are outside the viewport and adds new tiles that + * are inside the viewport. + */ + update(transform, terrain) { + if (!this._sourceLoaded || this._paused) { + return; + } + this.transform = transform; + this.terrain = terrain; + this.updateCacheSize(transform); + this.handleWrapJump(this.transform.center.lng); + // Covered is a list of retained tiles who's areas are fully covered by other, + // better, retained tiles. They are not drawn separately. + this._coveredTiles = {}; + let idealTileIDs; + if (!this.used && !this.usedForTerrain) { + idealTileIDs = []; + } + else if (this._source.tileID) { + idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID) + .map((unwrapped) => new OverscaledTileID(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y)); + } + else { + idealTileIDs = transform.coveringTiles({ + tileSize: this.usedForTerrain ? this.tileSize : this._source.tileSize, + minzoom: this._source.minzoom, + maxzoom: this._source.maxzoom, + roundZoom: this.usedForTerrain ? false : this._source.roundZoom, + reparseOverscaled: this._source.reparseOverscaled, + terrain + }); + if (this._source.hasTile) { + idealTileIDs = idealTileIDs.filter((coord) => this._source.hasTile(coord)); + } + } + // Determine the overzooming/underzooming amounts. + const zoom = transform.coveringZoomLevel(this._source); + const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom); + const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom); + // When sourcecache is used for terrain also load parent tiles to avoid flickering when zooming out + if (this.usedForTerrain) { + const parents = {}; + for (const tileID of idealTileIDs) { + if (tileID.canonical.z > this._source.minzoom) { + const parent = tileID.scaledTo(tileID.canonical.z - 1); + parents[parent.key] = parent; + // load very low zoom to calculate tile visibility in transform.coveringTiles and high zoomlevels correct + const parent2 = tileID.scaledTo(Math.max(this._source.minzoom, Math.min(tileID.canonical.z, 5))); + parents[parent2.key] = parent2; + } + } + idealTileIDs = idealTileIDs.concat(Object.values(parents)); + } + const noPendingDataEmissions = idealTileIDs.length === 0 && !this._updated && this._didEmitContent; + this._updated = true; + // if we won't have any tiles to fetch and content is already emitted + // there will be no more data emissions, so we need to emit the event with isSourceLoaded = true + if (noPendingDataEmissions) { + this.fire(new Event('data', { sourceDataType: 'idle', dataType: 'source', sourceId: this.id })); + } + // Retain is a list of tiles that we shouldn't delete, even if they are not + // the most ideal tile for the current viewport. This may include tiles like + // parent or child tiles that are *already* loaded. + const retain = this._updateRetainedTiles(idealTileIDs, zoom); + if (isRasterType(this._source.type)) { + this._updateCoveredAndRetainedTiles(retain, minCoveringZoom, maxCoveringZoom, zoom, idealTileIDs, terrain); + } + for (const retainedId in retain) { + // Make sure retained tiles always clear any existing fade holds + // so that if they're removed again their fade timer starts fresh. + this._tiles[retainedId].clearFadeHold(); + } + // Remove the tiles we don't need anymore. + const remove = keysDifference(this._tiles, retain); + for (const tileID of remove) { + const tile = this._tiles[tileID]; + if (tile.hasSymbolBuckets && !tile.holdingForFade()) { + tile.setHoldDuration(this.map._fadeDuration); + } + else if (!tile.hasSymbolBuckets || tile.symbolFadeFinished()) { + this._removeTile(tileID); + } + } + // Construct caches of loaded parents & siblings + this._updateLoadedParentTileCache(); + this._updateLoadedSiblingTileCache(); + } + releaseSymbolFadeTiles() { + for (const id in this._tiles) { + if (this._tiles[id].holdingForFade()) { + this._removeTile(id); + } + } + } + _updateRetainedTiles(idealTileIDs, zoom) { + var _a; + const retain = {}; + const checked = {}; + const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom); + const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom); + const missingTiles = {}; + for (const tileID of idealTileIDs) { + const tile = this._addTile(tileID); + // retain the tile even if it's not loaded because it's an ideal tile. + retain[tileID.key] = tileID; + if (tile.hasData()) + continue; + if (zoom < this._source.maxzoom) { + // save missing tiles that potentially have loaded children + missingTiles[tileID.key] = tileID; + } + } + // retain any loaded children of ideal tiles up to maxCoveringZoom + this._retainLoadedChildren(missingTiles, zoom, maxCoveringZoom, retain); + for (const tileID of idealTileIDs) { + let tile = this._tiles[tileID.key]; + if (tile.hasData()) + continue; + // The tile we require is not yet loaded or does not exist; + // Attempt to find children that fully cover it. + if (zoom + 1 > this._source.maxzoom) { + // We're looking for an overzoomed child tile. + const childCoord = tileID.children(this._source.maxzoom)[0]; + const childTile = this.getTile(childCoord); + if (!!childTile && childTile.hasData()) { + retain[childCoord.key] = childCoord; + continue; // tile is covered by overzoomed child + } + } + else { + // check if all 4 immediate children are loaded (i.e. the missing ideal tile is covered) + const children = tileID.children(this._source.maxzoom); + if (retain[children[0].key] && + retain[children[1].key] && + retain[children[2].key] && + retain[children[3].key]) + continue; // tile is covered by children + } + // We couldn't find child tiles that entirely cover the ideal tile; look for parents now. + // As we ascend up the tile pyramid of the ideal tile, we check whether the parent + // tile has been previously requested (and errored because we only loop over tiles with no data) + // in order to determine if we need to request its parent. + let parentWasRequested = tile.wasRequested(); + for (let overscaledZ = tileID.overscaledZ - 1; overscaledZ >= minCoveringZoom; --overscaledZ) { + const parentId = tileID.scaledTo(overscaledZ); + // Break parent tile ascent if this route has been previously checked by another child. + if (checked[parentId.key]) + break; + checked[parentId.key] = true; + tile = this.getTile(parentId); + if (!tile && parentWasRequested) { + tile = this._addTile(parentId); + } + if (tile) { + const hasData = tile.hasData(); + if (hasData || !((_a = this.map) === null || _a === void 0 ? void 0 : _a.cancelPendingTileRequestsWhileZooming) || parentWasRequested) { + retain[parentId.key] = parentId; + } + // Save the current values, since they're the parent of the next iteration + // of the parent tile ascent loop. + parentWasRequested = tile.wasRequested(); + if (hasData) + break; + } + } + } + return retain; + } + _updateLoadedParentTileCache() { + this._loadedParentTiles = {}; + for (const tileKey in this._tiles) { + const path = []; + let parentTile; + let currentId = this._tiles[tileKey].tileID; + // Find the closest loaded ancestor by traversing the tile tree towards the root and + // caching results along the way + while (currentId.overscaledZ > 0) { + // Do we have a cached result from previous traversals? + if (currentId.key in this._loadedParentTiles) { + parentTile = this._loadedParentTiles[currentId.key]; + break; + } + path.push(currentId.key); + // Is the parent loaded? + const parentId = currentId.scaledTo(currentId.overscaledZ - 1); + parentTile = this._getLoadedTile(parentId); + if (parentTile) { + break; + } + currentId = parentId; + } + // Cache the result of this traversal to all newly visited tiles + for (const key of path) { + this._loadedParentTiles[key] = parentTile; + } + } + } + /** + * Update the cache of loaded sibling tiles + * + * Sibling tiles are tiles that share the same zoom level and + * x/y position but have different wrap values + * Maintaining sibling tile cache allows fading from old to new tiles + * of the same position and zoom level + */ + _updateLoadedSiblingTileCache() { + this._loadedSiblingTiles = {}; + for (const tileKey in this._tiles) { + const currentId = this._tiles[tileKey].tileID; + const siblingTile = this._getLoadedTile(currentId); + this._loadedSiblingTiles[currentId.key] = siblingTile; + } + } + /** + * Add a tile, given its coordinate, to the pyramid. + */ + _addTile(tileID) { + let tile = this._tiles[tileID.key]; + if (tile) + return tile; + tile = this._cache.getAndRemove(tileID); + if (tile) { + this._setTileReloadTimer(tileID.key, tile); + // set the tileID because the cached tile could have had a different wrap value + tile.tileID = tileID; + this._state.initializeTileState(tile, this.map ? this.map.painter : null); + if (this._cacheTimers[tileID.key]) { + clearTimeout(this._cacheTimers[tileID.key]); + delete this._cacheTimers[tileID.key]; + this._setTileReloadTimer(tileID.key, tile); + } + } + const cached = tile; + if (!tile) { + tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor()); + this._loadTile(tile, tileID.key, tile.state); + } + tile.uses++; + this._tiles[tileID.key] = tile; + if (!cached) { + this._source.fire(new Event('dataloading', { tile, coord: tile.tileID, dataType: 'source' })); + } + return tile; + } + _setTileReloadTimer(id, tile) { + if (id in this._timers) { + clearTimeout(this._timers[id]); + delete this._timers[id]; + } + const expiryTimeout = tile.getExpiryTimeout(); + if (expiryTimeout) { + this._timers[id] = setTimeout(() => { + this._reloadTile(id, 'expired'); + delete this._timers[id]; + }, expiryTimeout); + } + } + /** + * Remove a tile, given its id, from the pyramid + */ + _removeTile(id) { + const tile = this._tiles[id]; + if (!tile) + return; + tile.uses--; + delete this._tiles[id]; + if (this._timers[id]) { + clearTimeout(this._timers[id]); + delete this._timers[id]; + } + if (tile.uses > 0) + return; + if (tile.hasData() && tile.state !== 'reloading') { + this._cache.add(tile.tileID, tile, tile.getExpiryTimeout()); + } + else { + tile.aborted = true; + this._abortTile(tile); + this._unloadTile(tile); + } + } + /** @internal */ + _dataHandler(e) { + const eventSourceDataType = e.sourceDataType; + if (e.dataType === 'source' && eventSourceDataType === 'metadata') { + this._sourceLoaded = true; + } + // for sources with mutable data, this event fires when the underlying data + // to a source is changed. (i.e. GeoJSONSource#setData and ImageSource#serCoordinates) + if (this._sourceLoaded && !this._paused && e.dataType === 'source' && eventSourceDataType === 'content') { + this.reload(); + if (this.transform) { + this.update(this.transform, this.terrain); + } + this._didEmitContent = true; + } + } + /** + * Remove all tiles from this pyramid + */ + clearTiles() { + this._shouldReloadOnResume = false; + this._paused = false; + for (const id in this._tiles) + this._removeTile(id); + this._cache.reset(); + } + /** + * Search through our current tiles and attempt to find the tiles that + * cover the given bounds. + * @param pointQueryGeometry - coordinates of the corners of bounding rectangle + * @returns result items have `{tile, minX, maxX, minY, maxY}`, where min/max bounding values are the given bounds transformed in into the coordinate space of this tile. + */ + tilesIn(pointQueryGeometry, maxPitchScaleFactor, has3DLayer) { + const tileResults = []; + const transform = this.transform; + if (!transform) + return tileResults; + const cameraPointQueryGeometry = has3DLayer ? + transform.getCameraQueryGeometry(pointQueryGeometry) : + pointQueryGeometry; + const queryGeometry = pointQueryGeometry.map((p) => transform.pointCoordinate(p, this.terrain)); + const cameraQueryGeometry = cameraPointQueryGeometry.map((p) => transform.pointCoordinate(p, this.terrain)); + const ids = this.getIds(); + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const p of cameraQueryGeometry) { + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + for (let i = 0; i < ids.length; i++) { + const tile = this._tiles[ids[i]]; + if (tile.holdingForFade()) { + // Tiles held for fading are covered by tiles that are closer to ideal + continue; + } + const tileID = tile.tileID; + const scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ); + const queryPadding = maxPitchScaleFactor * tile.queryPadding * EXTENT / tile.tileSize / scale; + const tileSpaceBounds = [ + tileID.getTilePoint(new MercatorCoordinate(minX, minY)), + tileID.getTilePoint(new MercatorCoordinate(maxX, maxY)) + ]; + if (tileSpaceBounds[0].x - queryPadding < EXTENT && tileSpaceBounds[0].y - queryPadding < EXTENT && + tileSpaceBounds[1].x + queryPadding >= 0 && tileSpaceBounds[1].y + queryPadding >= 0) { + const tileSpaceQueryGeometry = queryGeometry.map((c) => tileID.getTilePoint(c)); + const tileSpaceCameraQueryGeometry = cameraQueryGeometry.map((c) => tileID.getTilePoint(c)); + tileResults.push({ + tile, + tileID, + queryGeometry: tileSpaceQueryGeometry, + cameraQueryGeometry: tileSpaceCameraQueryGeometry, + scale + }); + } + } + return tileResults; + } + getVisibleCoordinates(symbolLayer) { + const coords = this.getRenderableIds(symbolLayer).map((id) => this._tiles[id].tileID); + for (const coord of coords) { + coord.posMatrix = this.transform.calculatePosMatrix(coord.toUnwrapped()); + } + return coords; + } + hasTransition() { + if (this._source.hasTransition()) { + return true; + } + if (isRasterType(this._source.type)) { + const now = browser.now(); + for (const id in this._tiles) { + const tile = this._tiles[id]; + if (tile.fadeEndTime >= now) { + return true; + } + } + } + return false; + } + /** + * Set the value of a particular state for a feature + */ + setFeatureState(sourceLayer, featureId, state) { + sourceLayer = sourceLayer || '_geojsonTileLayer'; + this._state.updateState(sourceLayer, featureId, state); + } + /** + * Resets the value of a particular state key for a feature + */ + removeFeatureState(sourceLayer, featureId, key) { + sourceLayer = sourceLayer || '_geojsonTileLayer'; + this._state.removeFeatureState(sourceLayer, featureId, key); + } + /** + * Get the entire state object for a feature + */ + getFeatureState(sourceLayer, featureId) { + sourceLayer = sourceLayer || '_geojsonTileLayer'; + return this._state.getState(sourceLayer, featureId); + } + /** + * Sets the set of keys that the tile depends on. This allows tiles to + * be reloaded when their dependencies change. + */ + setDependencies(tileKey, namespace, dependencies) { + const tile = this._tiles[tileKey]; + if (tile) { + tile.setDependencies(namespace, dependencies); + } + } + /** + * Reloads all tiles that depend on the given keys. + */ + reloadTilesForDependencies(namespaces, keys) { + for (const id in this._tiles) { + const tile = this._tiles[id]; + if (tile.hasDependency(namespaces, keys)) { + this._reloadTile(id, 'reloading'); + } + } + this._cache.filter(tile => !tile.hasDependency(namespaces, keys)); + } +} +SourceCache.maxOverzooming = 10; +SourceCache.maxUnderzooming = 3; +function compareTileId(a, b) { + // Different copies of the world are sorted based on their distance to the center. + // Wrap values are converted to unsigned distances by reserving odd number for copies + // with negative wrap and even numbers for copies with positive wrap. + const aWrap = Math.abs(a.wrap * 2) - +(a.wrap < 0); + const bWrap = Math.abs(b.wrap * 2) - +(b.wrap < 0); + return a.overscaledZ - b.overscaledZ || bWrap - aWrap || b.canonical.y - a.canonical.y || b.canonical.x - a.canonical.x; +} +function isRasterType(type) { + return type === 'raster' || type === 'image' || type === 'video'; +} + +/** + * Returns the part of a multiline that intersects with the provided rectangular box. + * + * @param lines - the lines to check + * @param x1 - the left edge of the box + * @param y1 - the top edge of the box + * @param x2 - the right edge of the box + * @param y2 - the bottom edge of the box + * @returns lines + */ +function clipLine(lines, x1, y1, x2, y2) { + const clippedLines = []; + for (let l = 0; l < lines.length; l++) { + const line = lines[l]; + let clippedLine; + for (let i = 0; i < line.length - 1; i++) { + let p0 = line[i]; + let p1 = line[i + 1]; + if (p0.x < x1 && p1.x < x1) { + continue; + } + else if (p0.x < x1) { + p0 = new Point$2(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); + } + else if (p1.x < x1) { + p1 = new Point$2(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); + } + if (p0.y < y1 && p1.y < y1) { + continue; + } + else if (p0.y < y1) { + p0 = new Point$2(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); + } + else if (p1.y < y1) { + p1 = new Point$2(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); + } + if (p0.x >= x2 && p1.x >= x2) { + continue; + } + else if (p0.x >= x2) { + p0 = new Point$2(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); + } + else if (p1.x >= x2) { + p1 = new Point$2(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); + } + if (p0.y >= y2 && p1.y >= y2) { + continue; + } + else if (p0.y >= y2) { + p0 = new Point$2(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); + } + else if (p1.y >= y2) { + p1 = new Point$2(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); + } + if (!clippedLine || !p0.equals(clippedLine[clippedLine.length - 1])) { + clippedLine = [p0]; + clippedLines.push(clippedLine); + } + clippedLine.push(p1); + } + } + return clippedLines; +} + +class PathInterpolator { + constructor(points_, padding_) { + this.reset(points_, padding_); + } + reset(points_, padding_) { + this.points = points_ || []; + // Compute cumulative distance from first point to every other point in the segment. + // Last entry in the array is total length of the path + this._distances = [0.0]; + for (let i = 1; i < this.points.length; i++) { + this._distances[i] = this._distances[i - 1] + this.points[i].dist(this.points[i - 1]); + } + this.length = this._distances[this._distances.length - 1]; + this.padding = Math.min(padding_ || 0, this.length * 0.5); + this.paddedLength = this.length - this.padding * 2.0; + } + lerp(t) { + if (this.points.length === 1) { + return this.points[0]; + } + t = clamp$1(t, 0, 1); + // Find the correct segment [p0, p1] where p0 <= x < p1 + let currentIndex = 1; + let distOfCurrentIdx = this._distances[currentIndex]; + const distToTarget = t * this.paddedLength + this.padding; + while (distOfCurrentIdx < distToTarget && currentIndex < this._distances.length) { + distOfCurrentIdx = this._distances[++currentIndex]; + } + // Interpolate between the two points of the segment + const idxOfPrevPoint = currentIndex - 1; + const distOfPrevIdx = this._distances[idxOfPrevPoint]; + const segmentLength = distOfCurrentIdx - distOfPrevIdx; + const segmentT = segmentLength > 0 ? (distToTarget - distOfPrevIdx) / segmentLength : 0; + return this.points[idxOfPrevPoint].mult(1.0 - segmentT).add(this.points[currentIndex].mult(segmentT)); + } +} + +function overlapAllowed(overlapA, overlapB) { + let allowed = true; + if (overlapA === 'always') { + // symbol A using 'always' overlap - allowed to overlap anything. + } + else if (overlapA === 'never' || overlapB === 'never') { + // symbol A using 'never' overlap - can't overlap anything + // symbol A using 'cooperative' overlap - can overlap 'always' or 'cooperative' symbol; can't overlap 'never' + allowed = false; + } + return allowed; +} +/** + * @internal + * GridIndex is a data structure for testing the intersection of + * circles and rectangles in a 2d plane. + * It is optimized for rapid insertion and querying. + * GridIndex splits the plane into a set of "cells" and keeps track + * of which geometries intersect with each cell. At query time, + * full geometry comparisons are only done for items that share + * at least one cell. As long as the geometries are relatively + * uniformly distributed across the plane, this greatly reduces + * the number of comparisons necessary. + */ +class GridIndex { + constructor(width, height, cellSize) { + const boxCells = this.boxCells = []; + const circleCells = this.circleCells = []; + // More cells -> fewer geometries to check per cell, but items tend + // to be split across more cells. + // Sweet spot allows most small items to fit in one cell + this.xCellCount = Math.ceil(width / cellSize); + this.yCellCount = Math.ceil(height / cellSize); + for (let i = 0; i < this.xCellCount * this.yCellCount; i++) { + boxCells.push([]); + circleCells.push([]); + } + this.circleKeys = []; + this.boxKeys = []; + this.bboxes = []; + this.circles = []; + this.width = width; + this.height = height; + this.xScale = this.xCellCount / width; + this.yScale = this.yCellCount / height; + this.boxUid = 0; + this.circleUid = 0; + } + keysLength() { + return this.boxKeys.length + this.circleKeys.length; + } + insert(key, x1, y1, x2, y2) { + this._forEachCell(x1, y1, x2, y2, this._insertBoxCell, this.boxUid++); + this.boxKeys.push(key); + this.bboxes.push(x1); + this.bboxes.push(y1); + this.bboxes.push(x2); + this.bboxes.push(y2); + } + insertCircle(key, x, y, radius) { + // Insert circle into grid for all cells in the circumscribing square + // It's more than necessary (by a factor of 4/PI), but fast to insert + this._forEachCell(x - radius, y - radius, x + radius, y + radius, this._insertCircleCell, this.circleUid++); + this.circleKeys.push(key); + this.circles.push(x); + this.circles.push(y); + this.circles.push(radius); + } + _insertBoxCell(x1, y1, x2, y2, cellIndex, uid) { + this.boxCells[cellIndex].push(uid); + } + _insertCircleCell(x1, y1, x2, y2, cellIndex, uid) { + this.circleCells[cellIndex].push(uid); + } + _query(x1, y1, x2, y2, hitTest, overlapMode, predicate) { + if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) { + return []; + } + const result = []; + if (x1 <= 0 && y1 <= 0 && this.width <= x2 && this.height <= y2) { + if (hitTest) { + // Covers the entire grid, so collides with everything + return [{ + key: null, + x1, + y1, + x2, + y2 + }]; + } + for (let boxUid = 0; boxUid < this.boxKeys.length; boxUid++) { + result.push({ + key: this.boxKeys[boxUid], + x1: this.bboxes[boxUid * 4], + y1: this.bboxes[boxUid * 4 + 1], + x2: this.bboxes[boxUid * 4 + 2], + y2: this.bboxes[boxUid * 4 + 3] + }); + } + for (let circleUid = 0; circleUid < this.circleKeys.length; circleUid++) { + const x = this.circles[circleUid * 3]; + const y = this.circles[circleUid * 3 + 1]; + const radius = this.circles[circleUid * 3 + 2]; + result.push({ + key: this.circleKeys[circleUid], + x1: x - radius, + y1: y - radius, + x2: x + radius, + y2: y + radius + }); + } + } + else { + const queryArgs = { + hitTest, + overlapMode, + seenUids: { box: {}, circle: {} } + }; + this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate); + } + return result; + } + query(x1, y1, x2, y2) { + return this._query(x1, y1, x2, y2, false, null); + } + hitTest(x1, y1, x2, y2, overlapMode, predicate) { + return this._query(x1, y1, x2, y2, true, overlapMode, predicate).length > 0; + } + hitTestCircle(x, y, radius, overlapMode, predicate) { + // Insert circle into grid for all cells in the circumscribing square + // It's more than necessary (by a factor of 4/PI), but fast to insert + const x1 = x - radius; + const x2 = x + radius; + const y1 = y - radius; + const y2 = y + radius; + if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) { + return false; + } + // Box query early exits if the bounding box is larger than the grid, but we don't do + // the equivalent calculation for circle queries because early exit is less likely + // and the calculation is more expensive + const result = []; + const queryArgs = { + hitTest: true, + overlapMode, + circle: { x, y, radius }, + seenUids: { box: {}, circle: {} } + }; + this._forEachCell(x1, y1, x2, y2, this._queryCellCircle, result, queryArgs, predicate); + return result.length > 0; + } + _queryCell(x1, y1, x2, y2, cellIndex, result, queryArgs, predicate) { + const { seenUids, hitTest, overlapMode } = queryArgs; + const boxCell = this.boxCells[cellIndex]; + if (boxCell !== null) { + const bboxes = this.bboxes; + for (const boxUid of boxCell) { + if (!seenUids.box[boxUid]) { + seenUids.box[boxUid] = true; + const offset = boxUid * 4; + const key = this.boxKeys[boxUid]; + if ((x1 <= bboxes[offset + 2]) && + (y1 <= bboxes[offset + 3]) && + (x2 >= bboxes[offset + 0]) && + (y2 >= bboxes[offset + 1]) && + (!predicate || predicate(key))) { + if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) { + result.push({ + key, + x1: bboxes[offset], + y1: bboxes[offset + 1], + x2: bboxes[offset + 2], + y2: bboxes[offset + 3] + }); + if (hitTest) { + // true return value stops the query after first match + return true; + } + } + } + } + } + } + const circleCell = this.circleCells[cellIndex]; + if (circleCell !== null) { + const circles = this.circles; + for (const circleUid of circleCell) { + if (!seenUids.circle[circleUid]) { + seenUids.circle[circleUid] = true; + const offset = circleUid * 3; + const key = this.circleKeys[circleUid]; + if (this._circleAndRectCollide(circles[offset], circles[offset + 1], circles[offset + 2], x1, y1, x2, y2) && + (!predicate || predicate(key))) { + if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) { + const x = circles[offset]; + const y = circles[offset + 1]; + const radius = circles[offset + 2]; + result.push({ + key, + x1: x - radius, + y1: y - radius, + x2: x + radius, + y2: y + radius + }); + if (hitTest) { + // true return value stops the query after first match + return true; + } + } + } + } + } + } + // false return to continue query + return false; + } + _queryCellCircle(x1, y1, x2, y2, cellIndex, result, queryArgs, predicate) { + const { circle, seenUids, overlapMode } = queryArgs; + const boxCell = this.boxCells[cellIndex]; + if (boxCell !== null) { + const bboxes = this.bboxes; + for (const boxUid of boxCell) { + if (!seenUids.box[boxUid]) { + seenUids.box[boxUid] = true; + const offset = boxUid * 4; + const key = this.boxKeys[boxUid]; + if (this._circleAndRectCollide(circle.x, circle.y, circle.radius, bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) && + (!predicate || predicate(key)) && + !overlapAllowed(overlapMode, key.overlapMode)) { + result.push(true); + return true; + } + } + } + } + const circleCell = this.circleCells[cellIndex]; + if (circleCell !== null) { + const circles = this.circles; + for (const circleUid of circleCell) { + if (!seenUids.circle[circleUid]) { + seenUids.circle[circleUid] = true; + const offset = circleUid * 3; + const key = this.circleKeys[circleUid]; + if (this._circlesCollide(circles[offset], circles[offset + 1], circles[offset + 2], circle.x, circle.y, circle.radius) && + (!predicate || predicate(key)) && + !overlapAllowed(overlapMode, key.overlapMode)) { + result.push(true); + return true; + } + } + } + } + } + _forEachCell(x1, y1, x2, y2, fn, arg1, arg2, predicate) { + const cx1 = this._convertToXCellCoord(x1); + const cy1 = this._convertToYCellCoord(y1); + const cx2 = this._convertToXCellCoord(x2); + const cy2 = this._convertToYCellCoord(y2); + for (let x = cx1; x <= cx2; x++) { + for (let y = cy1; y <= cy2; y++) { + const cellIndex = this.xCellCount * y + x; + if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, predicate)) + return; + } + } + } + _convertToXCellCoord(x) { + return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(x * this.xScale))); + } + _convertToYCellCoord(y) { + return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(y * this.yScale))); + } + _circlesCollide(x1, y1, r1, x2, y2, r2) { + const dx = x2 - x1; + const dy = y2 - y1; + const bothRadii = r1 + r2; + return (bothRadii * bothRadii) > (dx * dx + dy * dy); + } + _circleAndRectCollide(circleX, circleY, radius, x1, y1, x2, y2) { + const halfRectWidth = (x2 - x1) / 2; + const distX = Math.abs(circleX - (x1 + halfRectWidth)); + if (distX > (halfRectWidth + radius)) { + return false; + } + const halfRectHeight = (y2 - y1) / 2; + const distY = Math.abs(circleY - (y1 + halfRectHeight)); + if (distY > (halfRectHeight + radius)) { + return false; + } + if (distX <= halfRectWidth || distY <= halfRectHeight) { + return true; + } + const dx = distX - halfRectWidth; + const dy = distY - halfRectHeight; + return (dx * dx + dy * dy <= (radius * radius)); + } +} + +/* + * # Overview of coordinate spaces + * + * ## Tile coordinate spaces + * Each label has an anchor. Some labels have corresponding line geometries. + * The points for both anchors and lines are stored in tile units. Each tile has it's own + * coordinate space going from (0, 0) at the top left to (EXTENT, EXTENT) at the bottom right. + * + * ## Clip space (GL coordinate space) + * At the end of everything, the vertex shader needs to produce a position in clip space, + * which is (-1, 1) at the top left and (1, -1) in the bottom right. + * In the depth buffer, values are between 0 (near plane) to 1 (far plane). + * + * ## Map pixel coordinate spaces + * Each tile has a pixel coordinate space. It's just the tile units scaled so that one unit is + * whatever counts as 1 pixel at the current zoom. + * This space is used for pitch-alignment=map, rotation-alignment=map + * + * ## Rotated map pixel coordinate spaces + * Like the above, but rotated so axis of the space are aligned with the viewport instead of the tile. + * This space is used for pitch-alignment=map, rotation-alignment=viewport + * + * ## Viewport pixel coordinate space + * (0, 0) is at the top left of the canvas and (pixelWidth, pixelHeight) is at the bottom right corner + * of the canvas. This space is used for pitch-alignment=viewport + * + * + * # Vertex projection + * It goes roughly like this: + * 1. project the anchor and line from tile units into the correct label coordinate space + * - map pixel space pitch-alignment=map rotation-alignment=map + * - rotated map pixel space pitch-alignment=map rotation-alignment=viewport + * - viewport pixel space pitch-alignment=viewport rotation-alignment=* + * 2. if the label follows a line, find the point along the line that is the correct distance from the anchor. + * 3. add the glyph's corner offset to the point from step 3 + * 4. convert from the label coordinate space to clip space + * + * For horizontal labels we want to do step 1 in the shader for performance reasons (no cpu work). + * This is what `u_label_plane_matrix` is used for. + * For labels aligned with lines we have to steps 1 and 2 on the cpu since we need access to the line geometry. + * This is what `updateLineLabels(...)` does. + * Since the conversion is handled on the cpu we just set `u_label_plane_matrix` to an identity matrix. + * + * Steps 3 and 4 are done in the shaders for all labels. + */ +/* + * Returns a matrix for converting from tile units to the correct label coordinate space. + */ +function getLabelPlaneMatrix(posMatrix, pitchWithMap, rotateWithMap, transform, pixelsToTileUnits) { + const m = create$6(); + if (pitchWithMap) { + scale$5(m, m, [1 / pixelsToTileUnits, 1 / pixelsToTileUnits, 1]); + if (!rotateWithMap) { + rotateZ$3(m, m, transform.angle); + } + } + else { + multiply$5(m, transform.labelPlaneMatrix, posMatrix); + } + return m; +} +/* + * Returns a matrix for converting from the correct label coordinate space to clip space. + */ +function getGlCoordMatrix(posMatrix, pitchWithMap, rotateWithMap, transform, pixelsToTileUnits) { + if (pitchWithMap) { + const m = clone$5(posMatrix); + scale$5(m, m, [pixelsToTileUnits, pixelsToTileUnits, 1]); + if (!rotateWithMap) { + rotateZ$3(m, m, -transform.angle); + } + return m; + } + else { + return transform.glCoordMatrix; + } +} +function project(x, y, matrix, getElevation) { + let pos; + if (getElevation) { // slow because of handle z-index + pos = [x, y, getElevation(x, y), 1]; + transformMat4$1(pos, pos, matrix); + } + else { // fast because of ignore z-index + pos = [x, y, 0, 1]; + xyTransformMat4(pos, pos, matrix); + } + const w = pos[3]; + return { + point: new Point$2(pos[0] / w, pos[1] / w), + signedDistanceFromCamera: w, + isOccluded: false + }; +} +function getPerspectiveRatio(cameraToCenterDistance, signedDistanceFromCamera) { + return 0.5 + 0.5 * (cameraToCenterDistance / signedDistanceFromCamera); +} +function isVisible(p, clippingBuffer) { + const inPaddedViewport = (p.x >= -clippingBuffer[0] && + p.x <= clippingBuffer[0] && + p.y >= -clippingBuffer[1] && + p.y <= clippingBuffer[1]); + return inPaddedViewport; +} +/* + * Update the `dynamicLayoutVertexBuffer` for the buffer with the correct glyph positions for the current map view. + * This is only run on labels that are aligned with lines. Horizontal labels are handled entirely in the shader. + */ +function updateLineLabels(bucket, posMatrix, painter, isText, labelPlaneMatrix, glCoordMatrix, pitchWithMap, keepUpright, rotateToLine, projection, unwrappedTileID, viewportWidth, viewportHeight, translation, getElevation) { + const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData; + const partiallyEvaluatedSize = evaluateSizeForZoom(sizeData, painter.transform.zoom); + const clippingBuffer = [256 / painter.width * 2 + 1, 256 / painter.height * 2 + 1]; + const dynamicLayoutVertexArray = isText ? + bucket.text.dynamicLayoutVertexArray : + bucket.icon.dynamicLayoutVertexArray; + dynamicLayoutVertexArray.clear(); + const lineVertexArray = bucket.lineVertexArray; + const placedSymbols = isText ? bucket.text.placedSymbolArray : bucket.icon.placedSymbolArray; + const aspectRatio = painter.transform.width / painter.transform.height; + let useVertical = false; + for (let s = 0; s < placedSymbols.length; s++) { + const symbol = placedSymbols.get(s); + // Don't do calculations for vertical glyphs unless the previous symbol was horizontal + // and we determined that vertical glyphs were necessary. + // Also don't do calculations for symbols that are collided and fully faded out + if (symbol.hidden || symbol.writingMode === WritingMode.vertical && !useVertical) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + continue; + } + // Awkward... but we're counting on the paired "vertical" symbol coming immediately after its horizontal counterpart + useVertical = false; + const anchorPos = project(symbol.anchorX, symbol.anchorY, posMatrix, getElevation); + // Don't bother calculating the correct point for invisible labels. + if (!isVisible(anchorPos.point, clippingBuffer)) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + continue; + } + const cameraToAnchorDistance = anchorPos.signedDistanceFromCamera; + const perspectiveRatio = getPerspectiveRatio(painter.transform.cameraToCenterDistance, cameraToAnchorDistance); + const fontSize = evaluateSizeForFeature(sizeData, partiallyEvaluatedSize, symbol); + const pitchScaledFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio; + const tileAnchorPoint = new Point$2(symbol.anchorX, symbol.anchorY); + const projectionCache = { projections: {}, offsets: {}, cachedAnchorPoint: undefined, anyProjectionOccluded: false }; + const projectionContext = { + getElevation, + labelPlaneMatrix, + lineVertexArray, + pitchWithMap, + projectionCache, + projection, + tileAnchorPoint, + unwrappedTileID, + width: viewportWidth, + height: viewportHeight, + translation + }; + const placeUnflipped = placeGlyphsAlongLine(projectionContext, symbol, pitchScaledFontSize, false /*unflipped*/, keepUpright, posMatrix, glCoordMatrix, bucket.glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine); + useVertical = placeUnflipped.useVertical; + if (placeUnflipped.notEnoughRoom || useVertical || + (placeUnflipped.needsFlipping && + placeGlyphsAlongLine(projectionContext, symbol, pitchScaledFontSize, true /*flipped*/, keepUpright, posMatrix, glCoordMatrix, bucket.glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine).notEnoughRoom)) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + } + } + if (isText) { + bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray); + } + else { + bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray); + } +} +/* + * Place the first and last glyph of a line label, projected to the label plane. + * This function is called both during collision detection (to determine the label's size) + * and during line label rendering (to make sure the label fits on the line geometry with + * the current camera position, which may differ from the position used during collision detection). + * + * Calling this function has the effect of populating the "projectionCache" with all projected + * vertex locations the label will need, making future calls to placeGlyphAlongLine (for all the + * intermediate glyphs) much cheaper. + * + * Returns null if the label can't fit on the geometry + */ +function placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, symbol, rotateToLine, projectionContext) { + const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs; + const lineStartIndex = symbol.lineStartIndex; + const lineEndIndex = symbol.lineStartIndex + symbol.lineLength; + const firstGlyphOffset = glyphOffsetArray.getoffsetX(symbol.glyphStartIndex); + const lastGlyphOffset = glyphOffsetArray.getoffsetX(glyphEndIndex - 1); + const firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, lineOffsetX, lineOffsetY, flip, symbol.segment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine); + if (!firstPlacedGlyph) + return null; + const lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, symbol.segment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine); + if (!lastPlacedGlyph) + return null; + if (projectionContext.projectionCache.anyProjectionOccluded) { + return null; + } + return { first: firstPlacedGlyph, last: lastPlacedGlyph }; +} +function requiresOrientationChange(writingMode, firstPoint, lastPoint, aspectRatio) { + if (writingMode === WritingMode.horizontal) { + // On top of choosing whether to flip, choose whether to render this version of the glyphs or the alternate + // vertical glyphs. We can't just filter out vertical glyphs in the horizontal range because the horizontal + // and vertical versions can have slightly different projections which could lead to angles where both or + // neither showed. + const rise = Math.abs(lastPoint.y - firstPoint.y); + const run = Math.abs(lastPoint.x - firstPoint.x) * aspectRatio; + if (rise > run) { + return { useVertical: true }; + } + } + if (writingMode === WritingMode.vertical ? firstPoint.y < lastPoint.y : firstPoint.x > lastPoint.x) { + // Includes "horizontalOnly" case for labels without vertical glyphs + return { needsFlipping: true }; + } + return null; +} +/* +* Place first and last glyph along the line projected to label plane, and if they fit +* iterate through all the intermediate glyphs, calculating their label plane positions +* from the projected line. +* +* Finally, add resulting glyph position calculations to dynamicLayoutVertexArray for +* upload to the GPU +*/ +function placeGlyphsAlongLine(projectionContext, symbol, fontSize, flip, keepUpright, posMatrix, glCoordMatrix, glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine) { + const fontScale = fontSize / 24; + const lineOffsetX = symbol.lineOffsetX * fontScale; + const lineOffsetY = symbol.lineOffsetY * fontScale; + let placedGlyphs; + if (symbol.numGlyphs > 1) { + const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs; + const lineStartIndex = symbol.lineStartIndex; + const lineEndIndex = symbol.lineStartIndex + symbol.lineLength; + // Place the first and the last glyph in the label first, so we can figure out + // the overall orientation of the label and determine whether it needs to be flipped in keepUpright mode + const firstAndLastGlyph = placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, symbol, rotateToLine, projectionContext); + if (!firstAndLastGlyph) { + return { notEnoughRoom: true }; + } + const firstPoint = project(firstAndLastGlyph.first.point.x, firstAndLastGlyph.first.point.y, glCoordMatrix, projectionContext.getElevation).point; + const lastPoint = project(firstAndLastGlyph.last.point.x, firstAndLastGlyph.last.point.y, glCoordMatrix, projectionContext.getElevation).point; + if (keepUpright && !flip) { + const orientationChange = requiresOrientationChange(symbol.writingMode, firstPoint, lastPoint, aspectRatio); + if (orientationChange) { + return orientationChange; + } + } + placedGlyphs = [firstAndLastGlyph.first]; + for (let glyphIndex = symbol.glyphStartIndex + 1; glyphIndex < glyphEndIndex - 1; glyphIndex++) { + // Since first and last glyph fit on the line, we're sure that the rest of the glyphs can be placed + placedGlyphs.push(placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphIndex), lineOffsetX, lineOffsetY, flip, symbol.segment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine)); + } + placedGlyphs.push(firstAndLastGlyph.last); + } + else { + // Only a single glyph to place + // So, determine whether to flip based on projected angle of the line segment it's on + if (keepUpright && !flip) { + const a = project(projectionContext.tileAnchorPoint.x, projectionContext.tileAnchorPoint.y, posMatrix, projectionContext.getElevation).point; + const tileVertexIndex = (symbol.lineStartIndex + symbol.segment + 1); + const tileSegmentEnd = new Point$2(projectionContext.lineVertexArray.getx(tileVertexIndex), projectionContext.lineVertexArray.gety(tileVertexIndex)); + const projectedVertex = project(tileSegmentEnd.x, tileSegmentEnd.y, posMatrix, projectionContext.getElevation); + // We know the anchor will be in the viewport, but the end of the line segment may be + // behind the plane of the camera, in which case we can use a point at any arbitrary (closer) + // point on the segment. + const b = (projectedVertex.signedDistanceFromCamera > 0) ? + projectedVertex.point : + projectTruncatedLineSegmentToLabelPlane(projectionContext.tileAnchorPoint, tileSegmentEnd, a, 1, posMatrix, projectionContext); + const orientationChange = requiresOrientationChange(symbol.writingMode, a, b, aspectRatio); + if (orientationChange) { + return orientationChange; + } + } + const singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(symbol.glyphStartIndex), lineOffsetX, lineOffsetY, flip, symbol.segment, symbol.lineStartIndex, symbol.lineStartIndex + symbol.lineLength, projectionContext, rotateToLine); + if (!singleGlyph || projectionContext.projectionCache.anyProjectionOccluded) + return { notEnoughRoom: true }; + placedGlyphs = [singleGlyph]; + } + for (const glyph of placedGlyphs) { + addDynamicAttributes(dynamicLayoutVertexArray, glyph.point, glyph.angle); + } + return {}; +} +/** + * Takes a line and direction from `previousTilePoint` to `currentTilePoint`, + * projects it to *label plane*, + * and returns a projected point along this projected line that is `minimumLength` distance away from `previousProjectedPoint`. + * @param previousTilePoint - Line start point, in tile coordinates. + * @param currentTilePoint - Line end point, in tile coordinates. + * @param previousProjectedPoint - Projection of `previousTilePoint` into *label plane*. + * @param minimumLength - Distance in the projected space along the line for the returned point. + * @param projectionMatrix - Matrix to use during projection. + * @param projectionContext - Projection context, used only for terrain's `getElevation`. + */ +function projectTruncatedLineSegmentToLabelPlane(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionMatrix, projectionContext) { + return _projectTruncatedLineSegment(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionMatrix, projectionContext); +} +/** + * Takes a line and direction from `previousTilePoint` to `currentTilePoint`, + * projects it to *viewport*, + * and returns a projected point along this projected line that is `minimumLength` distance away from `previousProjectedPoint`. + * @param previousTilePoint - Line start point, in tile coordinates. + * @param currentTilePoint - Line end point, in tile coordinates. + * @param previousProjectedPoint - Projection of `previousTilePoint` into *viewport*. + * @param minimumLength - Distance in the projected space along the line for the returned point. + * @param projectionContext - Projection context, used for terrain's `getElevation`, and either the `labelPlaneMatrix` or the map's special projection (mostly for globe). + */ +function projectTruncatedLineSegmentToViewport(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionContext) { + return _projectTruncatedLineSegment(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, undefined, projectionContext); +} +/** + * Do not use directly, use {@link projectTruncatedLineSegmentToLabelPlane} or {@link projectTruncatedLineSegmentToViewport} instead, + * depending on the target space. + * + * Projects a "virtual" vertex along a line segment. + * If `projectionMatrix` is not undefined, does a simple projection using this matrix. + * Otherwise, either projects to label plane using the `labelPlaneMatrix` + * or projects to viewport using the special map projection (mostly for globe) by calling {@link projectTileCoordinatesToViewport}. + */ +function _projectTruncatedLineSegment(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionMatrix, projectionContext) { + // We are assuming "previousTilePoint" won't project to a point within one unit of the camera plane + // If it did, that would mean our label extended all the way out from within the viewport to a (very distant) + // point near the plane of the camera. We wouldn't be able to render the label anyway once it crossed the + // plane of the camera. + const unitVertexToBeProjected = previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit()); + const projectedUnitVertex = projectionMatrix !== undefined ? + project(unitVertexToBeProjected.x, unitVertexToBeProjected.y, projectionMatrix, projectionContext.getElevation).point : + projectTileCoordinatesToViewport(unitVertexToBeProjected.x, unitVertexToBeProjected.y, projectionContext).point; + const projectedUnitSegment = previousProjectedPoint.sub(projectedUnitVertex); + return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength / projectedUnitSegment.mag())); +} +/** + * Transform a vertex from tile coordinates to label plane coordinates + * @param index - index of vertex to project + * @param projectionContext - necessary data to project a vertex + * @returns the vertex projected to the label plane + */ +function projectLineVertexToViewport(index, projectionContext, syntheticVertexArgs) { + const cache = projectionContext.projectionCache; + if (cache.projections[index]) { + return cache.projections[index]; + } + const currentVertex = new Point$2(projectionContext.lineVertexArray.getx(index), projectionContext.lineVertexArray.gety(index)); + const projection = projectTileCoordinatesToViewport(currentVertex.x, currentVertex.y, projectionContext); + if (projection.signedDistanceFromCamera > 0) { + cache.projections[index] = projection.point; + cache.anyProjectionOccluded = cache.anyProjectionOccluded || projection.isOccluded; + return projection.point; + } + // The vertex is behind the plane of the camera, so we can't project it + // Instead, we'll create a vertex along the line that's far enough to include the glyph + const previousLineVertexIndex = index - syntheticVertexArgs.direction; + const previousTilePoint = syntheticVertexArgs.distanceFromAnchor === 0 ? + projectionContext.tileAnchorPoint : + new Point$2(projectionContext.lineVertexArray.getx(previousLineVertexIndex), projectionContext.lineVertexArray.gety(previousLineVertexIndex)); + // Don't cache because the new vertex might not be far enough out for future glyphs on the same segment + const minimumLength = syntheticVertexArgs.absOffsetX - syntheticVertexArgs.distanceFromAnchor + 1; + return projectTruncatedLineSegmentToViewport(previousTilePoint, currentVertex, syntheticVertexArgs.previousVertex, minimumLength, projectionContext); +} +function projectTileCoordinatesToViewport(x, y, projectionContext) { + const translatedX = x + projectionContext.translation[0]; + const translatedY = y + projectionContext.translation[1]; + let projection; + if (!projectionContext.pitchWithMap && projectionContext.projection.useSpecialProjectionForSymbols) { + projection = projectionContext.projection.projectTileCoordinates(translatedX, translatedY, projectionContext.unwrappedTileID, projectionContext.getElevation); + projection.point.x = (projection.point.x * 0.5 + 0.5) * projectionContext.width; + projection.point.y = (-projection.point.y * 0.5 + 0.5) * projectionContext.height; + } + else { + projection = project(translatedX, translatedY, projectionContext.labelPlaneMatrix, projectionContext.getElevation); + projection.isOccluded = false; + } + return projection; +} +/** + * Calculate the normal vector for a line segment + * @param segmentVector - will be mutated as a tiny optimization + * @param offset - magnitude of resulting vector + * @param direction - direction of line traversal + * @returns a normal vector from the segment, with magnitude equal to offset amount + */ +function transformToOffsetNormal(segmentVector, offset, direction) { + return segmentVector._unit()._perp()._mult(offset * direction); +} +/** + * Construct offset line segments for the current segment and the next segment, then extend/shrink + * the segments until they intersect. If the segments are parallel, then they will touch with no modification. + * + * @param index - Index of the current vertex + * @param prevToCurrentOffsetNormal - Normal vector of the line segment from the previous vertex to the current vertex + * @param currentVertex - Current (non-offset) vertex projected to the label plane + * @param lineStartIndex - Beginning index for the line this label is on + * @param lineEndIndex - End index for the line this label is on + * @param offsetPreviousVertex - The previous vertex projected to the label plane, and then offset along the previous segments normal + * @param lineOffsetY - Magnitude of the offset + * @param projectionContext - Necessary data for tile-to-label-plane projection + * @returns The point at which the current and next line segments intersect, once offset and extended/shrunk to their meeting point + */ +function findOffsetIntersectionPoint(index, prevToCurrentOffsetNormal, currentVertex, lineStartIndex, lineEndIndex, offsetPreviousVertex, lineOffsetY, projectionContext, syntheticVertexArgs) { + if (projectionContext.projectionCache.offsets[index]) { + return projectionContext.projectionCache.offsets[index]; + } + const offsetCurrentVertex = currentVertex.add(prevToCurrentOffsetNormal); + if (index + syntheticVertexArgs.direction < lineStartIndex || index + syntheticVertexArgs.direction >= lineEndIndex) { + // This is the end of the line, no intersection to calculate + projectionContext.projectionCache.offsets[index] = offsetCurrentVertex; + return offsetCurrentVertex; + } + // Offset the vertices for the next segment + const nextVertex = projectLineVertexToViewport(index + syntheticVertexArgs.direction, projectionContext, syntheticVertexArgs); + const currentToNextOffsetNormal = transformToOffsetNormal(nextVertex.sub(currentVertex), lineOffsetY, syntheticVertexArgs.direction); + const offsetNextSegmentBegin = currentVertex.add(currentToNextOffsetNormal); + const offsetNextSegmentEnd = nextVertex.add(currentToNextOffsetNormal); + // find the intersection of these two lines + // if the lines are parallel, offsetCurrent/offsetNextBegin will touch + projectionContext.projectionCache.offsets[index] = findLineIntersection(offsetPreviousVertex, offsetCurrentVertex, offsetNextSegmentBegin, offsetNextSegmentEnd) || offsetCurrentVertex; + return projectionContext.projectionCache.offsets[index]; +} +/* + * Place a single glyph along its line, projected into the label plane, by iterating outward + * from the anchor point until the distance traversed in the label plane equals the glyph's + * offsetX. Returns null if the glyph can't fit on the line geometry. + */ +function placeGlyphAlongLine(offsetX, lineOffsetX, lineOffsetY, flip, anchorSegment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine) { + const combinedOffsetX = flip ? + offsetX - lineOffsetX : + offsetX + lineOffsetX; + let direction = combinedOffsetX > 0 ? 1 : -1; + let angle = 0; + if (flip) { + // The label needs to be flipped to keep text upright. + // Iterate in the reverse direction. + direction *= -1; + angle = Math.PI; + } + if (direction < 0) + angle += Math.PI; + let currentIndex = direction > 0 ? + lineStartIndex + anchorSegment : + lineStartIndex + anchorSegment + 1; + // Project anchor point to proper label plane and cache it + let anchorPoint; + if (projectionContext.projectionCache.cachedAnchorPoint) { + anchorPoint = projectionContext.projectionCache.cachedAnchorPoint; + } + else { + anchorPoint = projectTileCoordinatesToViewport(projectionContext.tileAnchorPoint.x, projectionContext.tileAnchorPoint.y, projectionContext).point; + projectionContext.projectionCache.cachedAnchorPoint = anchorPoint; + } + let currentVertex = anchorPoint; + let previousVertex = anchorPoint; + // offsetPrev and intersectionPoint are analogous to previousVertex and currentVertex + // but if there's a line offset they are calculated in parallel as projection happens + let offsetIntersectionPoint; + let offsetPreviousVertex; + let distanceFromAnchor = 0; + let currentSegmentDistance = 0; + const absOffsetX = Math.abs(combinedOffsetX); + const pathVertices = []; + let currentLineSegment; + while (distanceFromAnchor + currentSegmentDistance <= absOffsetX) { + currentIndex += direction; + // offset does not fit on the projected line + if (currentIndex < lineStartIndex || currentIndex >= lineEndIndex) + return null; + // accumulate values from last iteration + distanceFromAnchor += currentSegmentDistance; + previousVertex = currentVertex; + offsetPreviousVertex = offsetIntersectionPoint; + const syntheticVertexArgs = { + absOffsetX, + direction, + distanceFromAnchor, + previousVertex + }; + // find next vertex in viewport space + currentVertex = projectLineVertexToViewport(currentIndex, projectionContext, syntheticVertexArgs); + if (lineOffsetY === 0) { + // Store vertices for collision detection and update current segment geometry + pathVertices.push(previousVertex); + currentLineSegment = currentVertex.sub(previousVertex); + } + else { + // Calculate the offset for this section + let prevToCurrentOffsetNormal; + const prevToCurrent = currentVertex.sub(previousVertex); + if (prevToCurrent.mag() === 0) { + // We are starting with our anchor point directly on the vertex, so look one vertex ahead + // to calculate a normal + const nextVertex = projectLineVertexToViewport(currentIndex + direction, projectionContext, syntheticVertexArgs); + prevToCurrentOffsetNormal = transformToOffsetNormal(nextVertex.sub(currentVertex), lineOffsetY, direction); + } + else { + prevToCurrentOffsetNormal = transformToOffsetNormal(prevToCurrent, lineOffsetY, direction); + } + // Initialize offsetPrev on our first iteration, after that it will be pre-calculated + if (!offsetPreviousVertex) + offsetPreviousVertex = previousVertex.add(prevToCurrentOffsetNormal); + offsetIntersectionPoint = findOffsetIntersectionPoint(currentIndex, prevToCurrentOffsetNormal, currentVertex, lineStartIndex, lineEndIndex, offsetPreviousVertex, lineOffsetY, projectionContext, syntheticVertexArgs); + pathVertices.push(offsetPreviousVertex); + currentLineSegment = offsetIntersectionPoint.sub(offsetPreviousVertex); + } + currentSegmentDistance = currentLineSegment.mag(); + } + // The point is on the current segment. Interpolate to find it. + const segmentInterpolationT = (absOffsetX - distanceFromAnchor) / currentSegmentDistance; + const p = currentLineSegment._mult(segmentInterpolationT)._add(offsetPreviousVertex || previousVertex); + const segmentAngle = angle + Math.atan2(currentVertex.y - previousVertex.y, currentVertex.x - previousVertex.x); + pathVertices.push(p); + return { + point: p, + angle: rotateToLine ? segmentAngle : 0.0, + path: pathVertices + }; +} +const hiddenGlyphAttributes = new Float32Array([-Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0]); +// Hide them by moving them offscreen. We still need to add them to the buffer +// because the dynamic buffer is paired with a static buffer that doesn't get updated. +function hideGlyphs(num, dynamicLayoutVertexArray) { + for (let i = 0; i < num; i++) { + const offset = dynamicLayoutVertexArray.length; + dynamicLayoutVertexArray.resize(offset + 4); + // Since all hidden glyphs have the same attributes, we can build up the array faster with a single call to Float32Array.set + // for each set of four vertices, instead of calling addDynamicAttributes for each vertex. + dynamicLayoutVertexArray.float32.set(hiddenGlyphAttributes, offset * 3); + } +} +// For line label layout, we're not using z output and our w input is always 1 +// This custom matrix transformation ignores those components to make projection faster +function xyTransformMat4(out, a, m) { + const x = a[0], y = a[1]; + out[0] = m[0] * x + m[4] * y + m[12]; + out[1] = m[1] * x + m[5] * y + m[13]; + out[3] = m[3] * x + m[7] * y + m[15]; + return out; +} + +// When a symbol crosses the edge that causes it to be included in +// collision detection, it will cause changes in the symbols around +// it. This constant specifies how many pixels to pad the edge of +// the viewport for collision detection so that the bulk of the changes +// occur offscreen. Making this constant greater increases label +// stability, but it's expensive. +const viewportPadding = 100; +/** + * @internal + * A collision index used to prevent symbols from overlapping. It keep tracks of + * where previous symbols have been placed and is used to check if a new + * symbol overlaps with any previously added symbols. + * + * There are two steps to insertion: first placeCollisionBox/Circles checks if + * there's room for a symbol, then insertCollisionBox/Circles actually puts the + * symbol in the index. The two step process allows paired symbols to be inserted + * together even if they overlap. + */ +class CollisionIndex { + constructor(transform, projection, grid = new GridIndex(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25), ignoredGrid = new GridIndex(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25)) { + this.transform = transform; + this.mapProjection = projection; + this.grid = grid; + this.ignoredGrid = ignoredGrid; + this.pitchFactor = Math.cos(transform._pitch) * transform.cameraToCenterDistance; + this.screenRightBoundary = transform.width + viewportPadding; + this.screenBottomBoundary = transform.height + viewportPadding; + this.gridRightBoundary = transform.width + 2 * viewportPadding; + this.gridBottomBoundary = transform.height + 2 * viewportPadding; + this.perspectiveRatioCutoff = 0.6; + } + placeCollisionBox(collisionBox, overlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translation, collisionGroupPredicate, getElevation, shift) { + const x = collisionBox.anchorPointX + translation[0]; + const y = collisionBox.anchorPointY + translation[1]; + const projectedPoint = this.projectAndGetPerspectiveRatio(posMatrix, x, y, unwrappedTileID, getElevation); + const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio; + let projectedBox; + if (!pitchWithMap && !rotateWithMap) { + // Fast path for common symbols + const pointX = projectedPoint.point.x + (shift ? shift.x * tileToViewport : 0); + const pointY = projectedPoint.point.y + (shift ? shift.y * tileToViewport : 0); + projectedBox = { + allPointsOccluded: false, + box: [ + pointX + collisionBox.x1 * tileToViewport, + pointY + collisionBox.y1 * tileToViewport, + pointX + collisionBox.x2 * tileToViewport, + pointY + collisionBox.y2 * tileToViewport, + ] + }; + } + else { + projectedBox = this._projectCollisionBox(collisionBox, tileToViewport, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translation, projectedPoint, getElevation, shift); + } + const [tlX, tlY, brX, brY] = projectedBox.box; + const projectionOccluded = this.mapProjection.useSpecialProjectionForSymbols ? (pitchWithMap ? projectedBox.allPointsOccluded : this.mapProjection.isOccluded(x, y, unwrappedTileID)) : false; + if (projectionOccluded || projectedPoint.perspectiveRatio < this.perspectiveRatioCutoff || !this.isInsideGrid(tlX, tlY, brX, brY) || + (overlapMode !== 'always' && this.grid.hitTest(tlX, tlY, brX, brY, overlapMode, collisionGroupPredicate))) { + return { + box: [tlX, tlY, brX, brY], + placeable: false, + offscreen: false + }; + } + return { + box: [tlX, tlY, brX, brY], + placeable: true, + offscreen: this.isOffscreen(tlX, tlY, brX, brY) + }; + } + placeCollisionCircles(overlapMode, symbol, lineVertexArray, glyphOffsetArray, fontSize, posMatrix, unwrappedTileID, labelPlaneMatrix, labelToScreenMatrix, showCollisionCircles, pitchWithMap, collisionGroupPredicate, circlePixelDiameter, textPixelPadding, translation, getElevation) { + const placedCollisionCircles = []; + const tileUnitAnchorPoint = new Point$2(symbol.anchorX, symbol.anchorY); + const perspectiveRatio = this.getPerspectiveRatio(posMatrix, tileUnitAnchorPoint.x, tileUnitAnchorPoint.y, unwrappedTileID, getElevation); + const labelPlaneFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio; + const labelPlaneFontScale = labelPlaneFontSize / ONE_EM; + const projectionCache = { projections: {}, offsets: {}, cachedAnchorPoint: undefined, anyProjectionOccluded: false }; + const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale; + const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale; + const projectionContext = { + getElevation, + labelPlaneMatrix, + lineVertexArray, + pitchWithMap, + projectionCache, + projection: this.mapProjection, + tileAnchorPoint: tileUnitAnchorPoint, + unwrappedTileID, + width: this.transform.width, + height: this.transform.height, + translation + }; + const firstAndLastGlyph = placeFirstAndLastGlyph(labelPlaneFontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, + /*flip*/ false, symbol, false, projectionContext); + let collisionDetected = false; + let inGrid = false; + let entirelyOffscreen = true; + if (firstAndLastGlyph) { + const radius = circlePixelDiameter * 0.5 * perspectiveRatio + textPixelPadding; + const screenPlaneMin = new Point$2(-viewportPadding, -viewportPadding); + const screenPlaneMax = new Point$2(this.screenRightBoundary, this.screenBottomBoundary); + const interpolator = new PathInterpolator(); + // Construct a projected path from projected line vertices. Anchor points are ignored and removed + const first = firstAndLastGlyph.first; + const last = firstAndLastGlyph.last; + let projectedPath = []; + for (let i = first.path.length - 1; i >= 1; i--) { + projectedPath.push(first.path[i]); + } + for (let i = 1; i < last.path.length; i++) { + projectedPath.push(last.path[i]); + } + // Tolerate a slightly longer distance than one diameter between two adjacent circles + const circleDist = radius * 2.5; + // The path might need to be converted into screen space if a pitched map is used as the label space + if (labelToScreenMatrix) { + const screenSpacePath = this.projectPathToScreenSpace(projectedPath, projectionContext, labelToScreenMatrix); + // Do not try to place collision circles if even one of the points is behind the camera. + // This is a plausible scenario with big camera pitch angles + if (screenSpacePath.some(point => point.signedDistanceFromCamera <= 0)) { + projectedPath = []; + } + else { + projectedPath = screenSpacePath.map(p => p.point); + } + } + let segments = []; + if (projectedPath.length > 0) { + // Quickly check if the path is fully inside or outside of the padded collision region. + // For overlapping paths we'll only create collision circles for the visible segments + const minPoint = projectedPath[0].clone(); + const maxPoint = projectedPath[0].clone(); + for (let i = 1; i < projectedPath.length; i++) { + minPoint.x = Math.min(minPoint.x, projectedPath[i].x); + minPoint.y = Math.min(minPoint.y, projectedPath[i].y); + maxPoint.x = Math.max(maxPoint.x, projectedPath[i].x); + maxPoint.y = Math.max(maxPoint.y, projectedPath[i].y); + } + if (minPoint.x >= screenPlaneMin.x && maxPoint.x <= screenPlaneMax.x && + minPoint.y >= screenPlaneMin.y && maxPoint.y <= screenPlaneMax.y) { + // Quad fully visible + segments = [projectedPath]; + } + else if (maxPoint.x < screenPlaneMin.x || minPoint.x > screenPlaneMax.x || + maxPoint.y < screenPlaneMin.y || minPoint.y > screenPlaneMax.y) { + // Not visible + segments = []; + } + else { + segments = clipLine([projectedPath], screenPlaneMin.x, screenPlaneMin.y, screenPlaneMax.x, screenPlaneMax.y); + } + } + for (const seg of segments) { + // interpolate positions for collision circles. Add a small padding to both ends of the segment + interpolator.reset(seg, radius * 0.25); + let numCircles = 0; + if (interpolator.length <= 0.5 * radius) { + numCircles = 1; + } + else { + numCircles = Math.ceil(interpolator.paddedLength / circleDist) + 1; + } + for (let i = 0; i < numCircles; i++) { + const t = i / Math.max(numCircles - 1, 1); + const circlePosition = interpolator.lerp(t); + // add viewport padding to the position and perform initial collision check + const centerX = circlePosition.x + viewportPadding; + const centerY = circlePosition.y + viewportPadding; + placedCollisionCircles.push(centerX, centerY, radius, 0); + const x1 = centerX - radius; + const y1 = centerY - radius; + const x2 = centerX + radius; + const y2 = centerY + radius; + entirelyOffscreen = entirelyOffscreen && this.isOffscreen(x1, y1, x2, y2); + inGrid = inGrid || this.isInsideGrid(x1, y1, x2, y2); + if (overlapMode !== 'always' && this.grid.hitTestCircle(centerX, centerY, radius, overlapMode, collisionGroupPredicate)) { + // Don't early exit if we're showing the debug circles because we still want to calculate + // which circles are in use + collisionDetected = true; + if (!showCollisionCircles) { + return { + circles: [], + offscreen: false, + collisionDetected + }; + } + } + } + } + } + return { + circles: ((!showCollisionCircles && collisionDetected) || !inGrid || perspectiveRatio < this.perspectiveRatioCutoff) ? [] : placedCollisionCircles, + offscreen: entirelyOffscreen, + collisionDetected + }; + } + projectPathToScreenSpace(projectedPath, projectionContext, labelToScreenMatrix) { + return projectedPath.map(p => project(p.x, p.y, labelToScreenMatrix, projectionContext.getElevation)); + } + /** + * Because the geometries in the CollisionIndex are an approximation of the shape of + * symbols on the map, we use the CollisionIndex to look up the symbol part of + * `queryRenderedFeatures`. + */ + queryRenderedSymbols(viewportQueryGeometry) { + if (viewportQueryGeometry.length === 0 || (this.grid.keysLength() === 0 && this.ignoredGrid.keysLength() === 0)) { + return {}; + } + const query = []; + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const point of viewportQueryGeometry) { + const gridPoint = new Point$2(point.x + viewportPadding, point.y + viewportPadding); + minX = Math.min(minX, gridPoint.x); + minY = Math.min(minY, gridPoint.y); + maxX = Math.max(maxX, gridPoint.x); + maxY = Math.max(maxY, gridPoint.y); + query.push(gridPoint); + } + const features = this.grid.query(minX, minY, maxX, maxY) + .concat(this.ignoredGrid.query(minX, minY, maxX, maxY)); + const seenFeatures = {}; + const result = {}; + for (const feature of features) { + const featureKey = feature.key; + // Skip already seen features. + if (seenFeatures[featureKey.bucketInstanceId] === undefined) { + seenFeatures[featureKey.bucketInstanceId] = {}; + } + if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) { + continue; + } + // Check if query intersects with the feature box + // "Collision Circles" for line labels are treated as boxes here + // Since there's no actual collision taking place, the circle vs. square + // distinction doesn't matter as much, and box geometry is easier + // to work with. + const bbox = [ + new Point$2(feature.x1, feature.y1), + new Point$2(feature.x2, feature.y1), + new Point$2(feature.x2, feature.y2), + new Point$2(feature.x1, feature.y2) + ]; + if (!polygonIntersectsPolygon(query, bbox)) { + continue; + } + seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true; + if (result[featureKey.bucketInstanceId] === undefined) { + result[featureKey.bucketInstanceId] = []; + } + result[featureKey.bucketInstanceId].push(featureKey.featureIndex); + } + return result; + } + insertCollisionBox(collisionBox, overlapMode, ignorePlacement, bucketInstanceId, featureIndex, collisionGroupID) { + const grid = ignorePlacement ? this.ignoredGrid : this.grid; + const key = { bucketInstanceId, featureIndex, collisionGroupID, overlapMode }; + grid.insert(key, collisionBox[0], collisionBox[1], collisionBox[2], collisionBox[3]); + } + insertCollisionCircles(collisionCircles, overlapMode, ignorePlacement, bucketInstanceId, featureIndex, collisionGroupID) { + const grid = ignorePlacement ? this.ignoredGrid : this.grid; + const key = { bucketInstanceId, featureIndex, collisionGroupID, overlapMode }; + for (let k = 0; k < collisionCircles.length; k += 4) { + grid.insertCircle(key, collisionCircles[k], collisionCircles[k + 1], collisionCircles[k + 2]); + } + } + projectAndGetPerspectiveRatio(posMatrix, x, y, _unwrappedTileID, getElevation) { + // The code here is duplicated from "projection.ts" for performance. + // Code here is subject to change once globe is merged. + let pos; + if (getElevation) { // slow because of handle z-index + pos = [x, y, getElevation(x, y), 1]; + transformMat4$1(pos, pos, posMatrix); + } + else { // fast because of ignore z-index + pos = [x, y, 0, 1]; + xyTransformMat4(pos, pos, posMatrix); + } + const w = pos[3]; + return { + point: new Point$2((((pos[0] / w + 1) / 2) * this.transform.width) + viewportPadding, (((-pos[1] / w + 1) / 2) * this.transform.height) + viewportPadding), + // See perspective ratio comment in symbol_sdf.vertex + // We're doing collision detection in viewport space so we need + // to scale down boxes in the distance + perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / w), + isOccluded: false, + signedDistanceFromCamera: w + }; + } + getPerspectiveRatio(posMatrix, x, y, unwrappedTileID, getElevation) { + // We don't care about the actual projected point, just its W component. + const projected = this.mapProjection.useSpecialProjectionForSymbols ? + this.mapProjection.projectTileCoordinates(x, y, unwrappedTileID, getElevation) : + project(x, y, posMatrix, getElevation); + return 0.5 + 0.5 * (this.transform.cameraToCenterDistance / projected.signedDistanceFromCamera); + } + isOffscreen(x1, y1, x2, y2) { + return x2 < viewportPadding || x1 >= this.screenRightBoundary || y2 < viewportPadding || y1 > this.screenBottomBoundary; + } + isInsideGrid(x1, y1, x2, y2) { + return x2 >= 0 && x1 < this.gridRightBoundary && y2 >= 0 && y1 < this.gridBottomBoundary; + } + /* + * Returns a matrix for transforming collision shapes to viewport coordinate space. + * Use this function to render e.g. collision circles on the screen. + * example transformation: clipPos = glCoordMatrix * viewportMatrix * circle_pos + */ + getViewportMatrix() { + const m = identity$2([]); + translate$1(m, m, [-viewportPadding, -viewportPadding, 0.0]); + return m; + } + /** + * Applies all layout+paint properties of the given box in order to find as good approximation of its screen-space bounding box as possible. + */ + _projectCollisionBox(collisionBox, tileToViewport, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translation, projectedPoint, getElevation, shift) { + // These vectors are valid both for screen space viewport-rotation-aligned texts and for pitch-align: map texts that are map-rotation-aligned. + let vecEast = new Point$2(1, 0); + let vecSouth = new Point$2(0, 1); + const translatedAnchor = new Point$2(collisionBox.anchorPointX + translation[0], collisionBox.anchorPointY + translation[1]); + if (rotateWithMap && !pitchWithMap) { + // Handles screen space texts that are always aligned east-west. + const projectedEast = this.projectAndGetPerspectiveRatio(posMatrix, translatedAnchor.x + 1, translatedAnchor.y, unwrappedTileID, getElevation).point; + const toEast = projectedEast.sub(projectedPoint.point).unit(); + const angle = Math.atan(toEast.y / toEast.x) + (toEast.x < 0 ? Math.PI : 0); + const sin = Math.sin(angle); + const cos = Math.cos(angle); + vecEast = new Point$2(cos, sin); + vecSouth = new Point$2(-sin, cos); + } + else if (!rotateWithMap && pitchWithMap) { + // Handles pitch-align: map texts that are always aligned with the viewport's X axis. + const angle = -this.transform.angle; + const sin = Math.sin(angle); + const cos = Math.cos(angle); + vecEast = new Point$2(cos, sin); + vecSouth = new Point$2(-sin, cos); + } + // Configuration for screen space offsets + let basePoint = projectedPoint.point; + let distanceMultiplier = tileToViewport; + if (pitchWithMap) { + // Configuration for tile space (map-pitch-aligned) offsets + basePoint = translatedAnchor; + const zoomFraction = this.transform.zoom - Math.floor(this.transform.zoom); + distanceMultiplier = Math.pow(2, -zoomFraction); + distanceMultiplier *= this.mapProjection.getPitchedTextCorrection(this.transform, translatedAnchor, unwrappedTileID); + // This next correction can't be applied when variable anchors are in use. + if (!shift) { + // Shader applies a perspective size correction, we need to apply the same correction. + // For non-pitchWithMap texts, this is handled above by multiplying `textPixelRatio` with `projectedPoint.perspectiveRatio`, + // which is equivalent to the non-pitchWithMap branch of the GLSL code. + // Here, we compute and apply the pitchWithMap branch. + // See the computation of `perspective_ratio` in the symbol vertex shaders for the GLSL code. + const distanceRatio = projectedPoint.signedDistanceFromCamera / this.transform.cameraToCenterDistance; + const perspectiveRatio = clamp$1(0.5 + 0.5 * distanceRatio, 0.0, 4.0); // Same clamp as what is used in the shader. + distanceMultiplier *= perspectiveRatio; + } + } + if (shift) { + // Variable anchors are in use + basePoint = basePoint.add(vecEast.mult(shift.x * distanceMultiplier)).add(vecSouth.mult(shift.y * distanceMultiplier)); + } + const offsetXmin = collisionBox.x1 * distanceMultiplier; + const offsetXmax = collisionBox.x2 * distanceMultiplier; + const offsetXhalf = (offsetXmin + offsetXmax) / 2; + const offsetYmin = collisionBox.y1 * distanceMultiplier; + const offsetYmax = collisionBox.y2 * distanceMultiplier; + const offsetYhalf = (offsetYmin + offsetYmax) / 2; + // 0--1--2 + // | | + // 7 3 + // | | + // 6--5--4 + const offsetsArray = [ + { offsetX: offsetXmin, offsetY: offsetYmin }, + { offsetX: offsetXhalf, offsetY: offsetYmin }, + { offsetX: offsetXmax, offsetY: offsetYmin }, + { offsetX: offsetXmax, offsetY: offsetYhalf }, + { offsetX: offsetXmax, offsetY: offsetYmax }, + { offsetX: offsetXhalf, offsetY: offsetYmax }, + { offsetX: offsetXmin, offsetY: offsetYmax }, + { offsetX: offsetXmin, offsetY: offsetYhalf } + ]; + let points = []; + for (const { offsetX, offsetY } of offsetsArray) { + points.push(new Point$2(basePoint.x + vecEast.x * offsetX + vecSouth.x * offsetY, basePoint.y + vecEast.y * offsetX + vecSouth.y * offsetY)); + } + // Is any point of the collision shape visible on the globe (on beyond horizon)? + let anyPointVisible = false; + if (pitchWithMap) { + const projected = points.map(p => this.projectAndGetPerspectiveRatio(posMatrix, p.x, p.y, unwrappedTileID, getElevation)); + // Is at least one of the projected points NOT behind the horizon? + anyPointVisible = projected.some(p => !p.isOccluded); + points = projected.map(p => p.point); + } + else { + // Labels that are not pitchWithMap cannot ever hide behind the horizon. + anyPointVisible = true; + } + return { + box: getAABB(points), + allPointsOccluded: !anyPointVisible + }; + } +} + +class Anchor extends Point$2 { + constructor(x, y, angle, segment) { + super(x, y); + this.angle = angle; + if (segment !== undefined) { + this.segment = segment; + } + } + clone() { + return new Anchor(this.x, this.y, this.angle, this.segment); + } +} +register('Anchor', Anchor); + +/** + * Labels placed around really sharp angles aren't readable. Check if any + * part of the potential label has a combined angle that is too big. + * + * @param line - The line to check + * @param anchor - The point on the line around which the label is anchored. + * @param labelLength - The length of the label in geometry units. + * @param windowSize - The check fails if the combined angles within a part of the line that is `windowSize` long is too big. + * @param maxAngle - The maximum combined angle that any window along the label is allowed to have. + * + * @returns whether the label should be placed + */ +function checkMaxAngle(line, anchor, labelLength, windowSize, maxAngle) { + // horizontal labels and labels with length 0 always pass + if (anchor.segment === undefined || labelLength === 0) + return true; + let p = anchor; + let index = anchor.segment + 1; + let anchorDistance = 0; + // move backwards along the line to the first segment the label appears on + while (anchorDistance > -labelLength / 2) { + index--; + // there isn't enough room for the label after the beginning of the line + if (index < 0) + return false; + anchorDistance -= line[index].dist(p); + p = line[index]; + } + anchorDistance += line[index].dist(line[index + 1]); + index++; + // store recent corners and their total angle difference + const recentCorners = []; + let recentAngleDelta = 0; + // move forwards by the length of the label and check angles along the way + while (anchorDistance < labelLength / 2) { + const prev = line[index - 1]; + const current = line[index]; + const next = line[index + 1]; + // there isn't enough room for the label before the end of the line + if (!next) + return false; + let angleDelta = prev.angleTo(current) - current.angleTo(next); + // restrict angle to -pi..pi range + angleDelta = Math.abs(((angleDelta + 3 * Math.PI) % (Math.PI * 2)) - Math.PI); + recentCorners.push({ + distance: anchorDistance, + angleDelta + }); + recentAngleDelta += angleDelta; + // remove corners that are far enough away from the list of recent anchors + while (anchorDistance - recentCorners[0].distance > windowSize) { + recentAngleDelta -= recentCorners.shift().angleDelta; + } + // the sum of angles within the window area exceeds the maximum allowed value. check fails. + if (recentAngleDelta > maxAngle) + return false; + index++; + anchorDistance += current.dist(next); + } + // no part of the line had an angle greater than the maximum allowed. check passes. + return true; +} + +function getLineLength(line) { + let lineLength = 0; + for (let k = 0; k < line.length - 1; k++) { + lineLength += line[k].dist(line[k + 1]); + } + return lineLength; +} +function getAngleWindowSize(shapedText, glyphSize, boxScale) { + return shapedText ? + 3 / 5 * glyphSize * boxScale : + 0; +} +function getShapedLabelLength(shapedText, shapedIcon) { + return Math.max(shapedText ? shapedText.right - shapedText.left : 0, shapedIcon ? shapedIcon.right - shapedIcon.left : 0); +} +function getCenterAnchor(line, maxAngle, shapedText, shapedIcon, glyphSize, boxScale) { + const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); + const labelLength = getShapedLabelLength(shapedText, shapedIcon) * boxScale; + let prevDistance = 0; + const centerDistance = getLineLength(line) / 2; + for (let i = 0; i < line.length - 1; i++) { + const a = line[i], b = line[i + 1]; + const segmentDistance = a.dist(b); + if (prevDistance + segmentDistance > centerDistance) { + // The center is on this segment + const t = (centerDistance - prevDistance) / segmentDistance, x = interpolate.number(a.x, b.x, t), y = interpolate.number(a.y, b.y, t); + const anchor = new Anchor(x, y, b.angleTo(a), i); + anchor._round(); + if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { + return anchor; + } + else { + return; + } + } + prevDistance += segmentDistance; + } +} +function getAnchors(line, spacing, maxAngle, shapedText, shapedIcon, glyphSize, boxScale, overscaling, tileExtent) { + // Resample a line to get anchor points for labels and check that each + // potential label passes text-max-angle check and has enough room to fit + // on the line. + const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); + const shapedLabelLength = getShapedLabelLength(shapedText, shapedIcon); + const labelLength = shapedLabelLength * boxScale; + // Is the line continued from outside the tile boundary? + const isLineContinued = line[0].x === 0 || line[0].x === tileExtent || line[0].y === 0 || line[0].y === tileExtent; + // Is the label long, relative to the spacing? + // If so, adjust the spacing so there is always a minimum space of `spacing / 4` between label edges. + if (spacing - labelLength < spacing / 4) { + spacing = labelLength + spacing / 4; + } + // Offset the first anchor by: + // Either half the label length plus a fixed extra offset if the line is not continued + // Or half the spacing if the line is continued. + // For non-continued lines, add a bit of fixed extra offset to avoid collisions at T intersections. + const fixedExtraOffset = glyphSize * 2; + const offset = !isLineContinued ? + ((shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling) % spacing : + (spacing / 2 * overscaling) % spacing; + return resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, false, tileExtent); +} +function resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, placeAtMiddle, tileExtent) { + const halfLabelLength = labelLength / 2; + const lineLength = getLineLength(line); + let distance = 0, markedDistance = offset - spacing; + let anchors = []; + for (let i = 0; i < line.length - 1; i++) { + const a = line[i], b = line[i + 1]; + const segmentDist = a.dist(b), angle = b.angleTo(a); + while (markedDistance + spacing < distance + segmentDist) { + markedDistance += spacing; + const t = (markedDistance - distance) / segmentDist, x = interpolate.number(a.x, b.x, t), y = interpolate.number(a.y, b.y, t); + // Check that the point is within the tile boundaries and that + // the label would fit before the beginning and end of the line + // if placed at this point. + if (x >= 0 && x < tileExtent && y >= 0 && y < tileExtent && + markedDistance - halfLabelLength >= 0 && + markedDistance + halfLabelLength <= lineLength) { + const anchor = new Anchor(x, y, angle, i); + anchor._round(); + if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { + anchors.push(anchor); + } + } + } + distance += segmentDist; + } + if (!placeAtMiddle && !anchors.length && !isLineContinued) { + // The first attempt at finding anchors at which labels can be placed failed. + // Try again, but this time just try placing one anchor at the middle of the line. + // This has the most effect for short lines in overscaled tiles, since the + // initial offset used in overscaled tiles is calculated to align labels with positions in + // parent tiles instead of placing the label as close to the beginning as possible. + anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, true, tileExtent); + } + return anchors; +} + +// If you have a 10px icon that isn't perfectly aligned to the pixel grid it will cover 11 actual +// pixels. The quad needs to be padded to account for this, otherwise they'll look slightly clipped +// on one edge in some cases. +const border = IMAGE_PADDING; +/** + * Create the quads used for rendering an icon. + */ +function getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit) { + const quads = []; + const image = shapedIcon.image; + const pixelRatio = image.pixelRatio; + const imageWidth = image.paddedRect.w - 2 * border; + const imageHeight = image.paddedRect.h - 2 * border; + let icon = { + x1: shapedIcon.left, + y1: shapedIcon.top, + x2: shapedIcon.right, + y2: shapedIcon.bottom + }; + const stretchX = image.stretchX || [[0, imageWidth]]; + const stretchY = image.stretchY || [[0, imageHeight]]; + const reduceRanges = (sum, range) => sum + range[1] - range[0]; + const stretchWidth = stretchX.reduce(reduceRanges, 0); + const stretchHeight = stretchY.reduce(reduceRanges, 0); + const fixedWidth = imageWidth - stretchWidth; + const fixedHeight = imageHeight - stretchHeight; + let stretchOffsetX = 0; + let stretchContentWidth = stretchWidth; + let stretchOffsetY = 0; + let stretchContentHeight = stretchHeight; + let fixedOffsetX = 0; + let fixedContentWidth = fixedWidth; + let fixedOffsetY = 0; + let fixedContentHeight = fixedHeight; + if (image.content && hasIconTextFit) { + const content = image.content; + const contentWidth = content[2] - content[0]; + const contentHeight = content[3] - content[1]; + // Constrict content area to fit target aspect ratio + if (image.textFitWidth || image.textFitHeight) { + icon = applyTextFit(shapedIcon); + } + stretchOffsetX = sumWithinRange(stretchX, 0, content[0]); + stretchOffsetY = sumWithinRange(stretchY, 0, content[1]); + stretchContentWidth = sumWithinRange(stretchX, content[0], content[2]); + stretchContentHeight = sumWithinRange(stretchY, content[1], content[3]); + fixedOffsetX = content[0] - stretchOffsetX; + fixedOffsetY = content[1] - stretchOffsetY; + fixedContentWidth = contentWidth - stretchContentWidth; + fixedContentHeight = contentHeight - stretchContentHeight; + } + const iconLeft = icon.x1; + const iconTop = icon.y1; + const iconWidth = icon.x2 - iconLeft; + const iconHeight = icon.y2 - iconTop; + const makeBox = (left, top, right, bottom) => { + const leftEm = getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, iconLeft); + const leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth); + const topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, iconTop); + const topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight); + const rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, iconLeft); + const rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth); + const bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, iconTop); + const bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight); + const tl = new Point$2(leftEm, topEm); + const tr = new Point$2(rightEm, topEm); + const br = new Point$2(rightEm, bottomEm); + const bl = new Point$2(leftEm, bottomEm); + const pixelOffsetTL = new Point$2(leftPx / pixelRatio, topPx / pixelRatio); + const pixelOffsetBR = new Point$2(rightPx / pixelRatio, bottomPx / pixelRatio); + const angle = iconRotate * Math.PI / 180; + if (angle) { + const sin = Math.sin(angle), cos = Math.cos(angle), matrix = [cos, -sin, sin, cos]; + tl._matMult(matrix); + tr._matMult(matrix); + bl._matMult(matrix); + br._matMult(matrix); + } + const x1 = left.stretch + left.fixed; + const x2 = right.stretch + right.fixed; + const y1 = top.stretch + top.fixed; + const y2 = bottom.stretch + bottom.fixed; + const subRect = { + x: image.paddedRect.x + border + x1, + y: image.paddedRect.y + border + y1, + w: x2 - x1, + h: y2 - y1 + }; + const minFontScaleX = fixedContentWidth / pixelRatio / iconWidth; + const minFontScaleY = fixedContentHeight / pixelRatio / iconHeight; + // Icon quad is padded, so texture coordinates also need to be padded. + return { tl, tr, bl, br, tex: subRect, writingMode: undefined, glyphOffset: [0, 0], sectionIndex: 0, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, isSDF: isSDFIcon }; + }; + if (!hasIconTextFit || (!image.stretchX && !image.stretchY)) { + quads.push(makeBox({ fixed: 0, stretch: -1 }, { fixed: 0, stretch: -1 }, { fixed: 0, stretch: imageWidth + 1 }, { fixed: 0, stretch: imageHeight + 1 })); + } + else { + const xCuts = stretchZonesToCuts(stretchX, fixedWidth, stretchWidth); + const yCuts = stretchZonesToCuts(stretchY, fixedHeight, stretchHeight); + for (let xi = 0; xi < xCuts.length - 1; xi++) { + const x1 = xCuts[xi]; + const x2 = xCuts[xi + 1]; + for (let yi = 0; yi < yCuts.length - 1; yi++) { + const y1 = yCuts[yi]; + const y2 = yCuts[yi + 1]; + quads.push(makeBox(x1, y1, x2, y2)); + } + } + } + return quads; +} +function sumWithinRange(ranges, min, max) { + let sum = 0; + for (const range of ranges) { + sum += Math.max(min, Math.min(max, range[1])) - Math.max(min, Math.min(max, range[0])); + } + return sum; +} +function stretchZonesToCuts(stretchZones, fixedSize, stretchSize) { + const cuts = [{ fixed: -border, stretch: 0 }]; + for (const [c1, c2] of stretchZones) { + const last = cuts[cuts.length - 1]; + cuts.push({ + fixed: c1 - last.stretch, + stretch: last.stretch + }); + cuts.push({ + fixed: c1 - last.stretch, + stretch: last.stretch + (c2 - c1) + }); + } + cuts.push({ + fixed: fixedSize + border, + stretch: stretchSize + }); + return cuts; +} +function getEmOffset(stretchOffset, stretchSize, iconSize, iconOffset) { + return stretchOffset / stretchSize * iconSize + iconOffset; +} +function getPxOffset(fixedOffset, fixedSize, stretchOffset, stretchSize) { + return fixedOffset - fixedSize * stretchOffset / stretchSize; +} +/** + * Create the quads used for rendering a text label. + */ +function getGlyphQuads(anchor, shaping, textOffset, layer, alongLine, feature, imageMap, allowVerticalPlacement) { + const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}) * Math.PI / 180; + const quads = []; + for (const line of shaping.positionedLines) { + for (const positionedGlyph of line.positionedGlyphs) { + if (!positionedGlyph.rect) + continue; + const textureRect = positionedGlyph.rect || {}; + // The rects have an additional buffer that is not included in their size. + const glyphPadding = 1.0; + let rectBuffer = GLYPH_PBF_BORDER + glyphPadding; + let isSDF = true; + let pixelRatio = 1.0; + let lineOffset = 0.0; + const rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical; + const halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2; + // Align images and scaled glyphs in the middle of a vertical line. + if (allowVerticalPlacement && shaping.verticalizable) { + const scaledGlyphOffset = (positionedGlyph.scale - 1) * ONE_EM; + const imageOffset = (ONE_EM - positionedGlyph.metrics.width * positionedGlyph.scale) / 2; + lineOffset = line.lineOffset / 2 - (positionedGlyph.imageName ? -imageOffset : scaledGlyphOffset); + } + if (positionedGlyph.imageName) { + const image = imageMap[positionedGlyph.imageName]; + isSDF = image.sdf; + pixelRatio = image.pixelRatio; + rectBuffer = IMAGE_PADDING / pixelRatio; + } + const glyphOffset = alongLine ? + [positionedGlyph.x + halfAdvance, positionedGlyph.y] : + [0, 0]; + let builtInOffset = alongLine ? + [0, 0] : + [positionedGlyph.x + halfAdvance + textOffset[0], positionedGlyph.y + textOffset[1] - lineOffset]; + let verticalizedLabelOffset = [0, 0]; + if (rotateVerticalGlyph) { + // Vertical POI labels that are rotated 90deg CW and whose glyphs must preserve upright orientation + // need to be rotated 90deg CCW. After a quad is rotated, it is translated to the original built-in offset. + verticalizedLabelOffset = builtInOffset; + builtInOffset = [0, 0]; + } + const textureScale = positionedGlyph.metrics.isDoubleResolution ? 2 : 1; + const x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0]; + const y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1]; + const x2 = x1 + textureRect.w / textureScale * positionedGlyph.scale / pixelRatio; + const y2 = y1 + textureRect.h / textureScale * positionedGlyph.scale / pixelRatio; + const tl = new Point$2(x1, y1); + const tr = new Point$2(x2, y1); + const bl = new Point$2(x1, y2); + const br = new Point$2(x2, y2); + if (rotateVerticalGlyph) { + // Vertical-supporting glyphs are laid out in 24x24 point boxes (1 square em) + // In horizontal orientation, the y values for glyphs are below the midline + // and we use a "yOffset" of -17 to pull them up to the middle. + // By rotating counter-clockwise around the point at the center of the left + // edge of a 24x24 layout box centered below the midline, we align the center + // of the glyphs with the horizontal midline, so the yOffset is no longer + // necessary, but we also pull the glyph to the left along the x axis. + // The y coordinate includes baseline yOffset, thus needs to be accounted + // for when glyph is rotated and translated. + const center = new Point$2(-halfAdvance, halfAdvance - SHAPING_DEFAULT_OFFSET); + const verticalRotation = -Math.PI / 2; + // xHalfWidthOffsetCorrection is a difference between full-width and half-width + // advance, should be 0 for full-width glyphs and will pull up half-width glyphs. + const xHalfWidthOffsetCorrection = ONE_EM / 2 - halfAdvance; + const yImageOffsetCorrection = positionedGlyph.imageName ? xHalfWidthOffsetCorrection : 0.0; + const halfWidthOffsetCorrection = new Point$2(5 - SHAPING_DEFAULT_OFFSET - xHalfWidthOffsetCorrection, -yImageOffsetCorrection); + const verticalOffsetCorrection = new Point$2(...verticalizedLabelOffset); + tl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + tr._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + bl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + br._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + } + if (textRotate) { + const sin = Math.sin(textRotate), cos = Math.cos(textRotate), matrix = [cos, -sin, sin, cos]; + tl._matMult(matrix); + tr._matMult(matrix); + bl._matMult(matrix); + br._matMult(matrix); + } + const pixelOffsetTL = new Point$2(0, 0); + const pixelOffsetBR = new Point$2(0, 0); + const minFontScaleX = 0; + const minFontScaleY = 0; + quads.push({ tl, tr, bl, br, tex: textureRect, writingMode: shaping.writingMode, glyphOffset, sectionIndex: positionedGlyph.sectionIndex, isSDF, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY }); + } + } + return quads; +} + +/** + * A CollisionFeature represents the area of the tile covered by a single label. + * It is used with CollisionIndex to check if the label overlaps with any + * previous labels. A CollisionFeature is mostly just a set of CollisionBox + * objects. + */ +class CollisionFeature { + /** + * Create a CollisionFeature, adding its collision box data to the given collisionBoxArray in the process. + * For line aligned labels a collision circle diameter is computed instead. + * + * @param anchor - The point along the line around which the label is anchored. + * @param shaped - The text or icon shaping results. + * @param boxScale - A magic number used to convert from glyph metrics units to geometry units. + * @param padding - The amount of padding to add around the label edges. + * @param alignLine - Whether the label is aligned with the line or the viewport. + */ + constructor(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaped, boxScale, padding, alignLine, rotate) { + var _a; + this.boxStartIndex = collisionBoxArray.length; + if (alignLine) { + // Compute height of the shape in glyph metrics and apply collision padding. + // Note that the pixel based 'text-padding' is applied at runtime + let top = shaped.top; + let bottom = shaped.bottom; + const collisionPadding = shaped.collisionPadding; + if (collisionPadding) { + top -= collisionPadding[1]; + bottom += collisionPadding[3]; + } + let height = bottom - top; + if (height > 0) { + // set minimum box height to avoid very many small labels + height = Math.max(10, height); + this.circleDiameter = height; + } + } + else { + const icon = ((_a = shaped.image) === null || _a === void 0 ? void 0 : _a.content) && (shaped.image.textFitWidth || shaped.image.textFitHeight) ? + applyTextFit(shaped) : + { + x1: shaped.left, + y1: shaped.top, + x2: shaped.right, + y2: shaped.bottom + }; + // margin is in CSS order: [top, right, bottom, left] + icon.y1 = icon.y1 * boxScale - padding[0]; + icon.y2 = icon.y2 * boxScale + padding[2]; + icon.x1 = icon.x1 * boxScale - padding[3]; + icon.x2 = icon.x2 * boxScale + padding[1]; + const collisionPadding = shaped.collisionPadding; + if (collisionPadding) { + icon.x1 -= collisionPadding[0] * boxScale; + icon.y1 -= collisionPadding[1] * boxScale; + icon.x2 += collisionPadding[2] * boxScale; + icon.y2 += collisionPadding[3] * boxScale; + } + if (rotate) { + // Account for *-rotate in point collision boxes + // See https://github.com/mapbox/mapbox-gl-js/issues/6075 + // Doesn't account for icon-text-fit + const tl = new Point$2(icon.x1, icon.y1); + const tr = new Point$2(icon.x2, icon.y1); + const bl = new Point$2(icon.x1, icon.y2); + const br = new Point$2(icon.x2, icon.y2); + const rotateRadians = rotate * Math.PI / 180; + tl._rotate(rotateRadians); + tr._rotate(rotateRadians); + bl._rotate(rotateRadians); + br._rotate(rotateRadians); + // Collision features require an "on-axis" geometry, + // so take the envelope of the rotated geometry + // (may be quite large for wide labels rotated 45 degrees) + icon.x1 = Math.min(tl.x, tr.x, bl.x, br.x); + icon.x2 = Math.max(tl.x, tr.x, bl.x, br.x); + icon.y1 = Math.min(tl.y, tr.y, bl.y, br.y); + icon.y2 = Math.max(tl.y, tr.y, bl.y, br.y); + } + collisionBoxArray.emplaceBack(anchor.x, anchor.y, icon.x1, icon.y1, icon.x2, icon.y2, featureIndex, sourceLayerIndex, bucketIndex); + } + this.boxEndIndex = collisionBoxArray.length; + } +} + +class TinyQueue { + constructor(data = [], compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) { + this.data = data; + this.length = this.data.length; + this.compare = compare; + + if (this.length > 0) { + for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i); + } + } + + push(item) { + this.data.push(item); + this._up(this.length++); + } + + pop() { + if (this.length === 0) return undefined; + + const top = this.data[0]; + const bottom = this.data.pop(); + + if (--this.length > 0) { + this.data[0] = bottom; + this._down(0); + } + + return top; + } + + peek() { + return this.data[0]; + } + + _up(pos) { + const {data, compare} = this; + const item = data[pos]; + + while (pos > 0) { + const parent = (pos - 1) >> 1; + const current = data[parent]; + if (compare(item, current) >= 0) break; + data[pos] = current; + pos = parent; + } + + data[pos] = item; + } + + _down(pos) { + const {data, compare} = this; + const halfLength = this.length >> 1; + const item = data[pos]; + + while (pos < halfLength) { + let bestChild = (pos << 1) + 1; // initially it is the left child + const right = bestChild + 1; + + if (right < this.length && compare(data[right], data[bestChild]) < 0) { + bestChild = right; + } + if (compare(data[bestChild], item) >= 0) break; + + data[pos] = data[bestChild]; + pos = bestChild; + } + + data[pos] = item; + } +} + +/** + * Finds an approximation of a polygon's Pole Of Inaccessibility https://en.wikipedia.org/wiki/Pole_of_inaccessibility + * This is a copy of https://github.com/mapbox/polylabel adapted to use Points + * + * @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 + * @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 + * @param debug - Print some statistics to the console during execution + * @returns Pole of Inaccessibility. + */ +function findPoleOfInaccessibility(polygonRings, precision = 1, debug = false) { + // find the bounding box of the outer ring + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + const outerRing = polygonRings[0]; + for (let i = 0; i < outerRing.length; i++) { + const p = outerRing[i]; + if (!i || p.x < minX) + minX = p.x; + if (!i || p.y < minY) + minY = p.y; + if (!i || p.x > maxX) + maxX = p.x; + if (!i || p.y > maxY) + maxY = p.y; + } + const width = maxX - minX; + const height = maxY - minY; + const cellSize = Math.min(width, height); + let h = cellSize / 2; + // a priority queue of cells in order of their "potential" (max distance to polygon) + const cellQueue = new TinyQueue([], compareMax); + if (cellSize === 0) + return new Point$2(minX, minY); + // cover polygon with initial cells + for (let x = minX; x < maxX; x += cellSize) { + for (let y = minY; y < maxY; y += cellSize) { + cellQueue.push(new Cell(x + h, y + h, h, polygonRings)); + } + } + // take centroid as the first best guess + let bestCell = getCentroidCell(polygonRings); + let numProbes = cellQueue.length; + while (cellQueue.length) { + // pick the most promising cell from the queue + const cell = cellQueue.pop(); + // update the best cell if we found a better one + if (cell.d > bestCell.d || !bestCell.d) { + bestCell = cell; + if (debug) + console.log('found best %d after %d probes', Math.round(1e4 * cell.d) / 1e4, numProbes); + } + // do not drill down further if there's no chance of a better solution + if (cell.max - bestCell.d <= precision) + continue; + // split the cell into four cells + h = cell.h / 2; + cellQueue.push(new Cell(cell.p.x - h, cell.p.y - h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x + h, cell.p.y - h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x - h, cell.p.y + h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x + h, cell.p.y + h, h, polygonRings)); + numProbes += 4; + } + if (debug) { + console.log(`num probes: ${numProbes}`); + console.log(`best distance: ${bestCell.d}`); + } + return bestCell.p; +} +function compareMax(a, b) { + return b.max - a.max; +} +function Cell(x, y, h, polygon) { + this.p = new Point$2(x, y); + this.h = h; // half the cell size + this.d = pointToPolygonDist(this.p, polygon); // distance from cell center to polygon + this.max = this.d + this.h * Math.SQRT2; // max distance to polygon within a cell +} +// signed distance from point to polygon outline (negative if point is outside) +function pointToPolygonDist(p, polygon) { + let inside = false; + let minDistSq = Infinity; + for (let k = 0; k < polygon.length; k++) { + const ring = polygon[k]; + for (let i = 0, len = ring.length, j = len - 1; i < len; j = i++) { + const a = ring[i]; + const b = ring[j]; + if ((a.y > p.y !== b.y > p.y) && + (p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x)) + inside = !inside; + minDistSq = Math.min(minDistSq, distToSegmentSquared(p, a, b)); + } + } + return (inside ? 1 : -1) * Math.sqrt(minDistSq); +} +// get polygon centroid +function getCentroidCell(polygon) { + let area = 0; + let x = 0; + let y = 0; + const points = polygon[0]; + for (let i = 0, len = points.length, j = len - 1; i < len; j = i++) { + const a = points[i]; + const b = points[j]; + const f = a.x * b.y - b.x * a.y; + x += (a.x + b.x) * f; + y += (a.y + b.y) * f; + area += f * 3; + } + return new Cell(x / area, y / area, 0, polygon); +} + +var TextAnchorEnum; +(function (TextAnchorEnum) { + TextAnchorEnum[TextAnchorEnum["center"] = 1] = "center"; + TextAnchorEnum[TextAnchorEnum["left"] = 2] = "left"; + TextAnchorEnum[TextAnchorEnum["right"] = 3] = "right"; + TextAnchorEnum[TextAnchorEnum["top"] = 4] = "top"; + TextAnchorEnum[TextAnchorEnum["bottom"] = 5] = "bottom"; + TextAnchorEnum[TextAnchorEnum["top-left"] = 6] = "top-left"; + TextAnchorEnum[TextAnchorEnum["top-right"] = 7] = "top-right"; + TextAnchorEnum[TextAnchorEnum["bottom-left"] = 8] = "bottom-left"; + TextAnchorEnum[TextAnchorEnum["bottom-right"] = 9] = "bottom-right"; +})(TextAnchorEnum || (TextAnchorEnum = {})); +// The radial offset is to the edge of the text box +// In the horizontal direction, the edge of the text box is where glyphs start +// But in the vertical direction, the glyphs appear to "start" at the baseline +// We don't actually load baseline data, but we assume an offset of ONE_EM - 17 +// (see "yOffset" in shaping.js) +const baselineOffset = 7; +const INVALID_TEXT_OFFSET = Number.POSITIVE_INFINITY; +function evaluateVariableOffset(anchor, offset) { + function fromRadialOffset(anchor, radialOffset) { + let x = 0, y = 0; + if (radialOffset < 0) + radialOffset = 0; // Ignore negative offset. + // solve for r where r^2 + r^2 = radialOffset^2 + const hypotenuse = radialOffset / Math.SQRT2; + switch (anchor) { + case 'top-right': + case 'top-left': + y = hypotenuse - baselineOffset; + break; + case 'bottom-right': + case 'bottom-left': + y = -hypotenuse + baselineOffset; + break; + case 'bottom': + y = -radialOffset + baselineOffset; + break; + case 'top': + y = radialOffset - baselineOffset; + break; + } + switch (anchor) { + case 'top-right': + case 'bottom-right': + x = -hypotenuse; + break; + case 'top-left': + case 'bottom-left': + x = hypotenuse; + break; + case 'left': + x = radialOffset; + break; + case 'right': + x = -radialOffset; + break; + } + return [x, y]; + } + function fromTextOffset(anchor, offsetX, offsetY) { + let x = 0, y = 0; + // Use absolute offset values. + offsetX = Math.abs(offsetX); + offsetY = Math.abs(offsetY); + switch (anchor) { + case 'top-right': + case 'top-left': + case 'top': + y = offsetY - baselineOffset; + break; + case 'bottom-right': + case 'bottom-left': + case 'bottom': + y = -offsetY + baselineOffset; + break; + } + switch (anchor) { + case 'top-right': + case 'bottom-right': + case 'right': + x = -offsetX; + break; + case 'top-left': + case 'bottom-left': + case 'left': + x = offsetX; + break; + } + return [x, y]; + } + return (offset[1] !== INVALID_TEXT_OFFSET) ? fromTextOffset(anchor, offset[0], offset[1]) : fromRadialOffset(anchor, offset[0]); +} +// Helper to support both text-variable-anchor and text-variable-anchor-offset. Offset values converted from EMs to PXs +function getTextVariableAnchorOffset(layer, feature, canonical) { + var _a; + const layout = layer.layout; + // If style specifies text-variable-anchor-offset, just return it + const variableAnchorOffset = (_a = layout.get('text-variable-anchor-offset')) === null || _a === void 0 ? void 0 : _a.evaluate(feature, {}, canonical); + if (variableAnchorOffset) { + const sourceValues = variableAnchorOffset.values; + const destValues = []; + // Convert offsets from EM to PX, and apply baseline shift + for (let i = 0; i < sourceValues.length; i += 2) { + const anchor = destValues[i] = sourceValues[i]; + const offset = sourceValues[i + 1].map(t => t * ONE_EM); + if (anchor.startsWith('top')) { + offset[1] -= baselineOffset; + } + else if (anchor.startsWith('bottom')) { + offset[1] += baselineOffset; + } + destValues[i + 1] = offset; + } + return new VariableAnchorOffsetCollection(destValues); + } + // If style specifies text-variable-anchor, convert to the new format + const variableAnchor = layout.get('text-variable-anchor'); + if (variableAnchor) { + let textOffset; + const unevaluatedLayout = layer._unevaluatedLayout; + // The style spec says don't use `text-offset` and `text-radial-offset` together + // but doesn't actually specify what happens if you use both. We go with the radial offset. + if (unevaluatedLayout.getValue('text-radial-offset') !== undefined) { + textOffset = [layout.get('text-radial-offset').evaluate(feature, {}, canonical) * ONE_EM, INVALID_TEXT_OFFSET]; + } + else { + textOffset = layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM); + } + const anchorOffsets = []; + for (const anchor of variableAnchor) { + anchorOffsets.push(anchor, evaluateVariableOffset(anchor, textOffset)); + } + return new VariableAnchorOffsetCollection(anchorOffsets); + } + return null; +} + +function performSymbolLayout(args) { + args.bucket.createArrays(); + const tileSize = 512 * args.bucket.overscaling; + args.bucket.tilePixelRatio = EXTENT / tileSize; + args.bucket.compareText = {}; + args.bucket.iconsNeedLinear = false; + const layer = args.bucket.layers[0]; + const layout = layer.layout; + const unevaluatedLayoutValues = layer._unevaluatedLayout._values; + const sizes = { + // Filled in below, if *SizeData.kind is 'composite' + // compositeIconSizes: undefined, + // compositeTextSizes: undefined, + layoutIconSize: unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical), + layoutTextSize: unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical), + textMaxSize: unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(18)) + }; + if (args.bucket.textSizeData.kind === 'composite') { + const { minZoom, maxZoom } = args.bucket.textSizeData; + sizes.compositeTextSizes = [ + unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical), + unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical) + ]; + } + if (args.bucket.iconSizeData.kind === 'composite') { + const { minZoom, maxZoom } = args.bucket.iconSizeData; + sizes.compositeIconSizes = [ + unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical), + unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical) + ]; + } + const lineHeight = layout.get('text-line-height') * ONE_EM; + const textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point'; + const keepUpright = layout.get('text-keep-upright'); + const textSize = layout.get('text-size'); + for (const feature of args.bucket.features) { + const fontstack = layout.get('text-font').evaluate(feature, {}, args.canonical).join(','); + const layoutTextSizeThisZoom = textSize.evaluate(feature, {}, args.canonical); + const layoutTextSize = sizes.layoutTextSize.evaluate(feature, {}, args.canonical); + const layoutIconSize = sizes.layoutIconSize.evaluate(feature, {}, args.canonical); + const shapedTextOrientations = { + horizontal: {}, + vertical: undefined + }; + const text = feature.text; + let textOffset = [0, 0]; + if (text) { + const unformattedText = text.toString(); + const spacing = layout.get('text-letter-spacing').evaluate(feature, {}, args.canonical) * ONE_EM; + const spacingIfAllowed = allowsLetterSpacing(unformattedText) ? spacing : 0; + const textAnchor = layout.get('text-anchor').evaluate(feature, {}, args.canonical); + const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, args.canonical); + if (!variableAnchorOffset) { + const radialOffset = layout.get('text-radial-offset').evaluate(feature, {}, args.canonical); + // Layers with variable anchors use the `text-radial-offset` property and the [x, y] offset vector + // is calculated at placement time instead of layout time + if (radialOffset) { + // The style spec says don't use `text-offset` and `text-radial-offset` together + // but doesn't actually specify what happens if you use both. We go with the radial offset. + textOffset = evaluateVariableOffset(textAnchor, [radialOffset * ONE_EM, INVALID_TEXT_OFFSET]); + } + else { + textOffset = layout.get('text-offset').evaluate(feature, {}, args.canonical).map(t => t * ONE_EM); + } + } + let textJustify = textAlongLine ? + 'center' : + layout.get('text-justify').evaluate(feature, {}, args.canonical); + const symbolPlacement = layout.get('symbol-placement'); + const maxWidth = symbolPlacement === 'point' ? + layout.get('text-max-width').evaluate(feature, {}, args.canonical) * ONE_EM : + Infinity; + const addVerticalShapingForPointLabelIfNeeded = () => { + if (args.bucket.allowVerticalPlacement && allowsVerticalWritingMode(unformattedText)) { + // Vertical POI label placement is meant to be used for scripts that support vertical + // writing mode, thus, default left justification is used. If Latin + // scripts would need to be supported, this should take into account other justifications. + shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, 'left', spacingIfAllowed, textOffset, WritingMode.vertical, true, layoutTextSize, layoutTextSizeThisZoom); + } + }; + // If this layer uses text-variable-anchor, generate shapings for all justification possibilities. + if (!textAlongLine && variableAnchorOffset) { + const justifications = new Set(); + if (textJustify === 'auto') { + for (let i = 0; i < variableAnchorOffset.values.length; i += 2) { + justifications.add(getAnchorJustification(variableAnchorOffset.values[i])); + } + } + else { + justifications.add(textJustify); + } + let singleLine = false; + for (const justification of justifications) { + if (shapedTextOrientations.horizontal[justification]) + continue; + if (singleLine) { + // If the shaping for the first justification was only a single line, we + // can re-use it for the other justifications + shapedTextOrientations.horizontal[justification] = shapedTextOrientations.horizontal[0]; + } + else { + // If using text-variable-anchor for the layer, we use a center anchor for all shapings and apply + // the offsets for the anchor in the placement step. + const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, 'center', justification, spacingIfAllowed, textOffset, WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom); + if (shaping) { + shapedTextOrientations.horizontal[justification] = shaping; + singleLine = shaping.positionedLines.length === 1; + } + } + } + addVerticalShapingForPointLabelIfNeeded(); + } + else { + if (textJustify === 'auto') { + textJustify = getAnchorJustification(textAnchor); + } + // Horizontal point or line label. + const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom); + if (shaping) + shapedTextOrientations.horizontal[textJustify] = shaping; + // Vertical point label (if allowVerticalPlacement is enabled). + addVerticalShapingForPointLabelIfNeeded(); + // Verticalized line label. + if (allowsVerticalWritingMode(unformattedText) && textAlongLine && keepUpright) { + shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, WritingMode.vertical, false, layoutTextSize, layoutTextSizeThisZoom); + } + } + } + let shapedIcon; + let isSDFIcon = false; + if (feature.icon && feature.icon.name) { + const image = args.imageMap[feature.icon.name]; + if (image) { + shapedIcon = shapeIcon(args.imagePositions[feature.icon.name], layout.get('icon-offset').evaluate(feature, {}, args.canonical), layout.get('icon-anchor').evaluate(feature, {}, args.canonical)); + // null/undefined SDF property treated same as default (false) + isSDFIcon = !!image.sdf; + if (args.bucket.sdfIcons === undefined) { + args.bucket.sdfIcons = isSDFIcon; + } + else if (args.bucket.sdfIcons !== isSDFIcon) { + warnOnce('Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer'); + } + if (image.pixelRatio !== args.bucket.pixelRatio) { + args.bucket.iconsNeedLinear = true; + } + else if (layout.get('icon-rotate').constantOr(1) !== 0) { + args.bucket.iconsNeedLinear = true; + } + } + } + const shapedText = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical; + args.bucket.iconsInText = shapedText ? shapedText.iconsInText : false; + if (shapedText || shapedIcon) { + addFeature(args.bucket, feature, shapedTextOrientations, shapedIcon, args.imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, args.canonical); + } + } + if (args.showCollisionBoxes) { + args.bucket.generateCollisionDebugBuffers(); + } +} +// Choose the justification that matches the direction of the TextAnchor +function getAnchorJustification(anchor) { + switch (anchor) { + case 'right': + case 'top-right': + case 'bottom-right': + return 'right'; + case 'left': + case 'top-left': + case 'bottom-left': + return 'left'; + } + return 'center'; +} +/** + * Given a feature and its shaped text and icon data, add a 'symbol + * instance' for each _possible_ placement of the symbol feature. + * (At render timePlaceSymbols#place() selects which of these instances to + * show or hide based on collisions with symbols in other layers.) + */ +function addFeature(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, canonical) { + // To reduce the number of labels that jump around when zooming we need + // to use a text-size value that is the same for all zoom levels. + // bucket calculates text-size at a high zoom level so that all tiles can + // use the same value when calculating anchor positions. + let textMaxSize = sizes.textMaxSize.evaluate(feature, {}); + if (textMaxSize === undefined) { + textMaxSize = layoutTextSize; + } + const layout = bucket.layers[0].layout; + const iconOffset = layout.get('icon-offset').evaluate(feature, {}, canonical); + const defaultHorizontalShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal); + const glyphSize = 24, fontScale = layoutTextSize / glyphSize, textBoxScale = bucket.tilePixelRatio * fontScale, textMaxBoxScale = bucket.tilePixelRatio * textMaxSize / glyphSize, iconBoxScale = bucket.tilePixelRatio * layoutIconSize, symbolMinDistance = bucket.tilePixelRatio * layout.get('symbol-spacing'), textPadding = layout.get('text-padding') * bucket.tilePixelRatio, iconPadding = getIconPadding(layout, feature, canonical, bucket.tilePixelRatio), textMaxAngle = layout.get('text-max-angle') / 180 * Math.PI, textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point', iconAlongLine = layout.get('icon-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point', symbolPlacement = layout.get('symbol-placement'), textRepeatDistance = symbolMinDistance / 2; + const iconTextFit = layout.get('icon-text-fit'); + let verticallyShapedIcon; + // Adjust shaped icon size when icon-text-fit is used. + if (shapedIcon && iconTextFit !== 'none') { + if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) { + verticallyShapedIcon = fitIconToText(shapedIcon, shapedTextOrientations.vertical, iconTextFit, layout.get('icon-text-fit-padding'), iconOffset, fontScale); + } + if (defaultHorizontalShaping) { + shapedIcon = fitIconToText(shapedIcon, defaultHorizontalShaping, iconTextFit, layout.get('icon-text-fit-padding'), iconOffset, fontScale); + } + } + const addSymbolAtAnchor = (line, anchor) => { + if (anchor.x < 0 || anchor.x >= EXTENT || anchor.y < 0 || anchor.y >= EXTENT) { + // Symbol layers are drawn across tile boundaries, We filter out symbols + // outside our tile boundaries (which may be included in vector tile buffers) + // to prevent double-drawing symbols. + return; + } + addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, bucket.layers[0], bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex, bucket.index, textBoxScale, [textPadding, textPadding, textPadding, textPadding], textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, canonical, layoutTextSize); + }; + if (symbolPlacement === 'line') { + for (const line of clipLine(feature.geometry, 0, 0, EXTENT, EXTENT)) { + const anchors = getAnchors(line, symbolMinDistance, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale, bucket.overscaling, EXTENT); + for (const anchor of anchors) { + const shapedText = defaultHorizontalShaping; + if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) { + addSymbolAtAnchor(line, anchor); + } + } + } + } + else if (symbolPlacement === 'line-center') { + // No clipping, multiple lines per feature are allowed + // "lines" with only one point are ignored as in clipLines + for (const line of feature.geometry) { + if (line.length > 1) { + const anchor = getCenterAnchor(line, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale); + if (anchor) { + addSymbolAtAnchor(line, anchor); + } + } + } + } + else if (feature.type === 'Polygon') { + for (const polygon of classifyRings$1(feature.geometry, 0)) { + // 16 here represents 2 pixels + const poi = findPoleOfInaccessibility(polygon, 16); + addSymbolAtAnchor(polygon[0], new Anchor(poi.x, poi.y, 0)); + } + } + else if (feature.type === 'LineString') { + // https://github.com/mapbox/mapbox-gl-js/issues/3808 + for (const line of feature.geometry) { + addSymbolAtAnchor(line, new Anchor(line[0].x, line[0].y, 0)); + } + } + else if (feature.type === 'Point') { + for (const points of feature.geometry) { + for (const point of points) { + addSymbolAtAnchor([point], new Anchor(point.x, point.y, 0)); + } + } + } +} +function addTextVariableAnchorOffsets(textAnchorOffsets, variableAnchorOffset) { + const startIndex = textAnchorOffsets.length; + const values = variableAnchorOffset === null || variableAnchorOffset === void 0 ? void 0 : variableAnchorOffset.values; + if ((values === null || values === void 0 ? void 0 : values.length) > 0) { + for (let i = 0; i < values.length; i += 2) { + const anchor = TextAnchorEnum[values[i]]; + const offset = values[i + 1]; + textAnchorOffsets.emplaceBack(anchor, offset[0], offset[1]); + } + } + return [startIndex, textAnchorOffsets.length]; +} +function addTextVertices(bucket, anchor, shapedText, imageMap, layer, textAlongLine, feature, textOffset, lineArray, writingMode, placementTypes, placedTextSymbolIndices, placedIconIndex, sizes, canonical) { + const glyphQuads = getGlyphQuads(anchor, shapedText, textOffset, layer, textAlongLine, feature, imageMap, bucket.allowVerticalPlacement); + const sizeData = bucket.textSizeData; + let textSizeData = null; + if (sizeData.kind === 'source') { + textSizeData = [ + SIZE_PACK_FACTOR * layer.layout.get('text-size').evaluate(feature, {}) + ]; + if (textSizeData[0] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`); + } + } + else if (sizeData.kind === 'composite') { + textSizeData = [ + SIZE_PACK_FACTOR * sizes.compositeTextSizes[0].evaluate(feature, {}, canonical), + SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical) + ]; + if (textSizeData[0] > MAX_PACKED_SIZE || textSizeData[1] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`); + } + } + bucket.addSymbols(bucket.text, glyphQuads, textSizeData, textOffset, textAlongLine, feature, writingMode, anchor, lineArray.lineStartIndex, lineArray.lineLength, placedIconIndex, canonical); + // The placedSymbolArray is used at render time in drawTileSymbols + // These indices allow access to the array at collision detection time + for (const placementType of placementTypes) { + placedTextSymbolIndices[placementType] = bucket.text.placedSymbolArray.length - 1; + } + return glyphQuads.length * 4; +} +function getDefaultHorizontalShaping(horizontalShaping) { + // We don't care which shaping we get because this is used for collision purposes + // and all the justifications have the same collision box + for (const justification in horizontalShaping) { + return horizontalShaping[justification]; + } + return null; +} +/** + * Add a single label & icon placement. + */ +function addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, layer, collisionBoxArray, featureIndex, sourceLayerIndex, bucketIndex, textBoxScale, textPadding, textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, canonical, layoutTextSize) { + const lineArray = bucket.addToLineVertexArray(anchor, line); + let textCollisionFeature, iconCollisionFeature, verticalTextCollisionFeature, verticalIconCollisionFeature; + let numIconVertices = 0; + let numVerticalIconVertices = 0; + let numHorizontalGlyphVertices = 0; + let numVerticalGlyphVertices = 0; + let placedIconSymbolIndex = -1; + let verticalPlacedIconSymbolIndex = -1; + const placedTextSymbolIndices = {}; + let key = murmur3$1(''); + if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) { + const textRotation = layer.layout.get('text-rotate').evaluate(feature, {}, canonical); + const verticalTextRotation = textRotation + 90.0; + const verticalShaping = shapedTextOrientations.vertical; + verticalTextCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textBoxScale, textPadding, textAlongLine, verticalTextRotation); + if (verticallyShapedIcon) { + verticalIconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconBoxScale, iconPadding, textAlongLine, verticalTextRotation); + } + } + //Place icon first, so text can have a reference to its index in the placed symbol array. + //Text symbols can lazily shift at render-time because of variable anchor placement. + //If the style specifies an `icon-text-fit` then the icon would have to shift along with it. + // For more info check `updateVariableAnchors` in `draw_symbol.js` . + if (shapedIcon) { + const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {}); + const hasIconTextFit = layer.layout.get('icon-text-fit') !== 'none'; + const iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit); + const verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit) : undefined; + iconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconBoxScale, iconPadding, /*align boxes to line*/ false, iconRotate); + numIconVertices = iconQuads.length * 4; + const sizeData = bucket.iconSizeData; + let iconSizeData = null; + if (sizeData.kind === 'source') { + iconSizeData = [ + SIZE_PACK_FACTOR * layer.layout.get('icon-size').evaluate(feature, {}) + ]; + if (iconSizeData[0] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`); + } + } + else if (sizeData.kind === 'composite') { + iconSizeData = [ + SIZE_PACK_FACTOR * sizes.compositeIconSizes[0].evaluate(feature, {}, canonical), + SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical) + ]; + if (iconSizeData[0] > MAX_PACKED_SIZE || iconSizeData[1] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`); + } + } + bucket.addSymbols(bucket.icon, iconQuads, iconSizeData, iconOffset, iconAlongLine, feature, WritingMode.none, anchor, lineArray.lineStartIndex, lineArray.lineLength, + // The icon itself does not have an associated symbol since the text isn't placed yet + -1, canonical); + placedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; + if (verticalIconQuads) { + numVerticalIconVertices = verticalIconQuads.length * 4; + bucket.addSymbols(bucket.icon, verticalIconQuads, iconSizeData, iconOffset, iconAlongLine, feature, WritingMode.vertical, anchor, lineArray.lineStartIndex, lineArray.lineLength, + // The icon itself does not have an associated symbol since the text isn't placed yet + -1, canonical); + verticalPlacedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; + } + } + const justifications = Object.keys(shapedTextOrientations.horizontal); + for (const justification of justifications) { + const shaping = shapedTextOrientations.horizontal[justification]; + if (!textCollisionFeature) { + key = murmur3$1(shaping.text); + const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}, canonical); + // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature + // We're counting on all versions having similar dimensions + textCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textBoxScale, textPadding, textAlongLine, textRotate); + } + const singleLine = shaping.positionedLines.length === 1; + numHorizontalGlyphVertices += addTextVertices(bucket, anchor, shaping, imageMap, layer, textAlongLine, feature, textOffset, lineArray, shapedTextOrientations.vertical ? WritingMode.horizontal : WritingMode.horizontalOnly, singleLine ? justifications : [justification], placedTextSymbolIndices, placedIconSymbolIndex, sizes, canonical); + if (singleLine) { + break; + } + } + if (shapedTextOrientations.vertical) { + numVerticalGlyphVertices += addTextVertices(bucket, anchor, shapedTextOrientations.vertical, imageMap, layer, textAlongLine, feature, textOffset, lineArray, WritingMode.vertical, ['vertical'], placedTextSymbolIndices, verticalPlacedIconSymbolIndex, sizes, canonical); + } + const textBoxStartIndex = textCollisionFeature ? textCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const textBoxEndIndex = textCollisionFeature ? textCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + const verticalTextBoxStartIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const verticalTextBoxEndIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + const iconBoxStartIndex = iconCollisionFeature ? iconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const iconBoxEndIndex = iconCollisionFeature ? iconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + const verticalIconBoxStartIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const verticalIconBoxEndIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + // Check if runtime collision circles should be used for any of the collision features. + // It is enough to choose the tallest feature shape as circles are always placed on a line. + // All measurements are in glyph metrics and later converted into pixels using proper font size "layoutTextSize" + let collisionCircleDiameter = -1; + const getCollisionCircleHeight = (feature, prevHeight) => { + if (feature && feature.circleDiameter) + return Math.max(feature.circleDiameter, prevHeight); + return prevHeight; + }; + collisionCircleDiameter = getCollisionCircleHeight(textCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(verticalTextCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(iconCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(verticalIconCollisionFeature, collisionCircleDiameter); + const useRuntimeCollisionCircles = (collisionCircleDiameter > -1) ? 1 : 0; + // Convert circle collision height into pixels + if (useRuntimeCollisionCircles) + collisionCircleDiameter *= layoutTextSize / ONE_EM; + if (bucket.glyphOffsetArray.length >= SymbolBucket.MAX_GLYPHS) + warnOnce('Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907'); + if (feature.sortKey !== undefined) { + bucket.addToSortKeyRanges(bucket.symbolInstances.length, feature.sortKey); + } + const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, canonical); + const [textAnchorOffsetStartIndex, textAnchorOffsetEndIndex] = addTextVariableAnchorOffsets(bucket.textAnchorOffsets, variableAnchorOffset); + bucket.symbolInstances.emplaceBack(anchor.x, anchor.y, placedTextSymbolIndices.right >= 0 ? placedTextSymbolIndices.right : -1, placedTextSymbolIndices.center >= 0 ? placedTextSymbolIndices.center : -1, placedTextSymbolIndices.left >= 0 ? placedTextSymbolIndices.left : -1, placedTextSymbolIndices.vertical || -1, placedIconSymbolIndex, verticalPlacedIconSymbolIndex, key, textBoxStartIndex, textBoxEndIndex, verticalTextBoxStartIndex, verticalTextBoxEndIndex, iconBoxStartIndex, iconBoxEndIndex, verticalIconBoxStartIndex, verticalIconBoxEndIndex, featureIndex, numHorizontalGlyphVertices, numVerticalGlyphVertices, numIconVertices, numVerticalIconVertices, useRuntimeCollisionCircles, 0, textBoxScale, collisionCircleDiameter, textAnchorOffsetStartIndex, textAnchorOffsetEndIndex); +} +function anchorIsTooClose(bucket, text, repeatDistance, anchor) { + const compareText = bucket.compareText; + if (!(text in compareText)) { + compareText[text] = []; + } + else { + const otherAnchors = compareText[text]; + for (let k = otherAnchors.length - 1; k >= 0; k--) { + if (anchor.dist(otherAnchors[k]) < repeatDistance) { + // If it's within repeatDistance of one anchor, stop looking + return true; + } + } + } + // If anchor is not within repeatDistance of any other anchor, add to array + compareText[text].push(anchor); + return false; +} + +/** + * Converts a pixel value at a the given zoom level to tile units. + * + * The shaders mostly calculate everything in tile units so style + * properties need to be converted from pixels to tile units using this. + * + * For example, a translation by 30 pixels at zoom 6.5 will be a + * translation by pixelsToTileUnits(30, 6.5) tile units. + * + * @returns value in tile units + */ +function pixelsToTileUnits(tile, pixelValue, z) { + return pixelValue * (EXTENT / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ))); +} + +class OpacityState { + constructor(prevState, increment, placed, skipFade) { + if (prevState) { + this.opacity = Math.max(0, Math.min(1, prevState.opacity + (prevState.placed ? increment : -increment))); + } + else { + this.opacity = (skipFade && placed) ? 1 : 0; + } + this.placed = placed; + } + isHidden() { + return this.opacity === 0 && !this.placed; + } +} +class JointOpacityState { + constructor(prevState, increment, placedText, placedIcon, skipFade) { + this.text = new OpacityState(prevState ? prevState.text : null, increment, placedText, skipFade); + this.icon = new OpacityState(prevState ? prevState.icon : null, increment, placedIcon, skipFade); + } + isHidden() { + return this.text.isHidden() && this.icon.isHidden(); + } +} +class JointPlacement { + constructor(text, icon, skipFade) { + this.text = text; + this.icon = icon; + this.skipFade = skipFade; + } +} +class CollisionCircleArray { + constructor() { + this.invProjMatrix = create$6(); + this.viewportMatrix = create$6(); + this.circles = []; + } +} +class RetainedQueryData { + constructor(bucketInstanceId, featureIndex, sourceLayerIndex, bucketIndex, tileID) { + this.bucketInstanceId = bucketInstanceId; + this.featureIndex = featureIndex; + this.sourceLayerIndex = sourceLayerIndex; + this.bucketIndex = bucketIndex; + this.tileID = tileID; + } +} +class CollisionGroups { + constructor(crossSourceCollisions) { + this.crossSourceCollisions = crossSourceCollisions; + this.maxGroupID = 0; + this.collisionGroups = {}; + } + get(sourceID) { + // The predicate/groupID mechanism allows for arbitrary grouping, + // but the current interface defines one source == one group when + // crossSourceCollisions == true. + if (!this.crossSourceCollisions) { + if (!this.collisionGroups[sourceID]) { + const nextGroupID = ++this.maxGroupID; + this.collisionGroups[sourceID] = { + ID: nextGroupID, + predicate: (key) => { + return key.collisionGroupID === nextGroupID; + } + }; + } + return this.collisionGroups[sourceID]; + } + else { + return { ID: 0, predicate: null }; + } + } +} +function calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale) { + const { horizontalAlign, verticalAlign } = getAnchorAlignment(anchor); + const shiftX = -(horizontalAlign - 0.5) * width; + const shiftY = -(verticalAlign - 0.5) * height; + return new Point$2(shiftX + textOffset[0] * textBoxScale, shiftY + textOffset[1] * textBoxScale); +} +class Placement { + constructor(transform, projection, terrain, fadeDuration, crossSourceCollisions, prevPlacement) { + this.transform = transform.clone(); + this.terrain = terrain; + this.collisionIndex = new CollisionIndex(this.transform, projection); + this.placements = {}; + this.opacities = {}; + this.variableOffsets = {}; + this.stale = false; + this.commitTime = 0; + this.fadeDuration = fadeDuration; + this.retainedQueryData = {}; + this.collisionGroups = new CollisionGroups(crossSourceCollisions); + this.collisionCircleArrays = {}; + this.collisionBoxArrays = new Map(); + this.prevPlacement = prevPlacement; + if (prevPlacement) { + prevPlacement.prevPlacement = undefined; // Only hold on to one placement back + } + this.placedOrientations = {}; + } + _getTerrainElevationFunc(tileID) { + const terrain = this.terrain; + return terrain ? (x, y) => terrain.getElevation(tileID, x, y) : null; + } + getBucketParts(results, styleLayer, tile, sortAcrossTiles) { + const symbolBucket = tile.getBucket(styleLayer); + const bucketFeatureIndex = tile.latestFeatureIndex; + if (!symbolBucket || !bucketFeatureIndex || styleLayer.id !== symbolBucket.layerIds[0]) + return; + const collisionBoxArray = tile.collisionBoxArray; + const layout = symbolBucket.layers[0].layout; + const paint = symbolBucket.layers[0].paint; + const scale = Math.pow(2, this.transform.zoom - tile.tileID.overscaledZ); + const textPixelRatio = tile.tileSize / EXTENT; + const unwrappedTileID = tile.tileID.toUnwrapped(); + const posMatrix = this.transform.calculatePosMatrix(unwrappedTileID); + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pixelsToTiles = pixelsToTileUnits(tile, 1, this.transform.zoom); + const translationText = this.collisionIndex.mapProjection.translatePosition(this.transform, tile, paint.get('text-translate'), paint.get('text-translate-anchor')); + const translationIcon = this.collisionIndex.mapProjection.translatePosition(this.transform, tile, paint.get('icon-translate'), paint.get('icon-translate-anchor')); + const textLabelPlaneMatrix = getLabelPlaneMatrix(posMatrix, pitchWithMap, rotateWithMap, this.transform, pixelsToTiles); + let labelToScreenMatrix = null; + if (pitchWithMap) { + const glMatrix = getGlCoordMatrix(posMatrix, pitchWithMap, rotateWithMap, this.transform, pixelsToTiles); + labelToScreenMatrix = multiply$5([], this.transform.labelPlaneMatrix, glMatrix); + } + // As long as this placement lives, we have to hold onto this bucket's + // matching FeatureIndex/data for querying purposes + this.retainedQueryData[symbolBucket.bucketInstanceId] = new RetainedQueryData(symbolBucket.bucketInstanceId, bucketFeatureIndex, symbolBucket.sourceLayerIndex, symbolBucket.index, tile.tileID); + const parameters = { + bucket: symbolBucket, + layout, + translationText, + translationIcon, + posMatrix, + unwrappedTileID, + textLabelPlaneMatrix, + labelToScreenMatrix, + scale, + textPixelRatio, + holdingForFade: tile.holdingForFade(), + collisionBoxArray, + partiallyEvaluatedTextSize: evaluateSizeForZoom(symbolBucket.textSizeData, this.transform.zoom), + collisionGroup: this.collisionGroups.get(symbolBucket.sourceID) + }; + if (sortAcrossTiles) { + for (const range of symbolBucket.sortKeyRanges) { + const { sortKey, symbolInstanceStart, symbolInstanceEnd } = range; + results.push({ sortKey, symbolInstanceStart, symbolInstanceEnd, parameters }); + } + } + else { + results.push({ + symbolInstanceStart: 0, + symbolInstanceEnd: symbolBucket.symbolInstances.length, + parameters + }); + } + } + attemptAnchorPlacement(textAnchorOffset, textBox, width, height, textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix, unwrappedTileID, collisionGroup, textOverlapMode, symbolInstance, bucket, orientation, translationText, translationIcon, iconBox, getElevation) { + const anchor = TextAnchorEnum[textAnchorOffset.textAnchor]; + const textOffset = [textAnchorOffset.textOffset0, textAnchorOffset.textOffset1]; + const shift = calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale); + const placedGlyphBoxes = this.collisionIndex.placeCollisionBox(textBox, textOverlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation, shift); + if (iconBox) { + const placedIconBoxes = this.collisionIndex.placeCollisionBox(iconBox, textOverlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationIcon, collisionGroup.predicate, getElevation, shift); + if (!placedIconBoxes.placeable) + return; + } + if (placedGlyphBoxes.placeable) { + let prevAnchor; + // If this label was placed in the previous placement, record the anchor position + // to allow us to animate the transition + if (this.prevPlacement && + this.prevPlacement.variableOffsets[symbolInstance.crossTileID] && + this.prevPlacement.placements[symbolInstance.crossTileID] && + this.prevPlacement.placements[symbolInstance.crossTileID].text) { + prevAnchor = this.prevPlacement.variableOffsets[symbolInstance.crossTileID].anchor; + } + if (symbolInstance.crossTileID === 0) + throw new Error('symbolInstance.crossTileID can\'t be 0'); + this.variableOffsets[symbolInstance.crossTileID] = { + textOffset, + width, + height, + anchor, + textBoxScale, + prevAnchor + }; + this.markUsedJustification(bucket, anchor, symbolInstance, orientation); + if (bucket.allowVerticalPlacement) { + this.markUsedOrientation(bucket, orientation, symbolInstance); + this.placedOrientations[symbolInstance.crossTileID] = orientation; + } + return { shift, placedGlyphBoxes }; + } + } + placeLayerBucketPart(bucketPart, seenCrossTileIDs, showCollisionBoxes) { + const { bucket, layout, translationText, translationIcon, posMatrix, unwrappedTileID, textLabelPlaneMatrix, labelToScreenMatrix, textPixelRatio, holdingForFade, collisionBoxArray, partiallyEvaluatedTextSize, collisionGroup } = bucketPart.parameters; + const textOptional = layout.get('text-optional'); + const iconOptional = layout.get('icon-optional'); + const textOverlapMode = getOverlapMode(layout, 'text-overlap', 'text-allow-overlap'); + const textAlwaysOverlap = textOverlapMode === 'always'; + const iconOverlapMode = getOverlapMode(layout, 'icon-overlap', 'icon-allow-overlap'); + const iconAlwaysOverlap = iconOverlapMode === 'always'; + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const hasIconTextFit = layout.get('icon-text-fit') !== 'none'; + const zOrderByViewportY = layout.get('symbol-z-order') === 'viewport-y'; + // This logic is similar to the "defaultOpacityState" logic below in updateBucketOpacities + // If we know a symbol is always supposed to show, force it to be marked visible even if + // it wasn't placed into the collision index (because some or all of it was outside the range + // of the collision grid). + // There is a subtle edge case here we're accepting: + // Symbol A has text-allow-overlap: true, icon-allow-overlap: true, icon-optional: false + // A's icon is outside the grid, so doesn't get placed + // A's text would be inside grid, but doesn't get placed because of icon-optional: false + // We still show A because of the allow-overlap settings. + // Symbol B has allow-overlap: false, and gets placed where A's text would be + // On panning in, there is a short period when Symbol B and Symbol A will overlap + // This is the reverse of our normal policy of "fade in on pan", but should look like any other + // collision and hopefully not be too noticeable. + // See https://github.com/mapbox/mapbox-gl-js/issues/7172 + const alwaysShowText = textAlwaysOverlap && (iconAlwaysOverlap || !bucket.hasIconData() || iconOptional); + const alwaysShowIcon = iconAlwaysOverlap && (textAlwaysOverlap || !bucket.hasTextData() || textOptional); + if (!bucket.collisionArrays && collisionBoxArray) { + bucket.deserializeCollisionBoxes(collisionBoxArray); + } + const tileID = this.retainedQueryData[bucket.bucketInstanceId].tileID; + const getElevation = this._getTerrainElevationFunc(tileID); + const placeSymbol = (symbolInstance, collisionArrays, symbolIndex) => { + var _a, _b; + if (seenCrossTileIDs[symbolInstance.crossTileID]) + return; + if (holdingForFade) { + // Mark all symbols from this tile as "not placed", but don't add to seenCrossTileIDs, because we don't + // know yet if we have a duplicate in a parent tile that _should_ be placed. + this.placements[symbolInstance.crossTileID] = new JointPlacement(false, false, false); + return; + } + let placeText = false; + let placeIcon = false; + let offscreen = true; + let shift = null; + let placed = { box: null, placeable: false, offscreen: null }; + let placedVerticalText = { box: null, placeable: false, offscreen: null }; + let placedGlyphBoxes = null; + let placedGlyphCircles = null; + let placedIconBoxes = null; + let textFeatureIndex = 0; + let verticalTextFeatureIndex = 0; + let iconFeatureIndex = 0; + if (collisionArrays.textFeatureIndex) { + textFeatureIndex = collisionArrays.textFeatureIndex; + } + else if (symbolInstance.useRuntimeCollisionCircles) { + textFeatureIndex = symbolInstance.featureIndex; + } + if (collisionArrays.verticalTextFeatureIndex) { + verticalTextFeatureIndex = collisionArrays.verticalTextFeatureIndex; + } + const textBox = collisionArrays.textBox; + if (textBox) { + const updatePreviousOrientationIfNotPlaced = (isPlaced) => { + let previousOrientation = WritingMode.horizontal; + if (bucket.allowVerticalPlacement && !isPlaced && this.prevPlacement) { + const prevPlacedOrientation = this.prevPlacement.placedOrientations[symbolInstance.crossTileID]; + if (prevPlacedOrientation) { + this.placedOrientations[symbolInstance.crossTileID] = prevPlacedOrientation; + previousOrientation = prevPlacedOrientation; + this.markUsedOrientation(bucket, previousOrientation, symbolInstance); + } + } + return previousOrientation; + }; + const placeTextForPlacementModes = (placeHorizontalFn, placeVerticalFn) => { + if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && collisionArrays.verticalTextBox) { + for (const placementMode of bucket.writingModes) { + if (placementMode === WritingMode.vertical) { + placed = placeVerticalFn(); + placedVerticalText = placed; + } + else { + placed = placeHorizontalFn(); + } + if (placed && placed.placeable) + break; + } + } + else { + placed = placeHorizontalFn(); + } + }; + const textAnchorOffsetStart = symbolInstance.textAnchorOffsetStartIndex; + const textAnchorOffsetEnd = symbolInstance.textAnchorOffsetEndIndex; + // If start+end indices match, text-variable-anchor is not in play. + if (textAnchorOffsetEnd === textAnchorOffsetStart) { + const placeBox = (collisionTextBox, orientation) => { + const placedFeature = this.collisionIndex.placeCollisionBox(collisionTextBox, textOverlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation); + if (placedFeature && placedFeature.placeable) { + this.markUsedOrientation(bucket, orientation, symbolInstance); + this.placedOrientations[symbolInstance.crossTileID] = orientation; + } + return placedFeature; + }; + const placeHorizontal = () => { + return placeBox(textBox, WritingMode.horizontal); + }; + const placeVertical = () => { + const verticalTextBox = collisionArrays.verticalTextBox; + if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) { + return placeBox(verticalTextBox, WritingMode.vertical); + } + return { box: null, offscreen: null }; + }; + placeTextForPlacementModes(placeHorizontal, placeVertical); + updatePreviousOrientationIfNotPlaced(placed && placed.placeable); + } + else { + // If this symbol was in the last placement, prefer placement using same anchor, if it's still available + let prevAnchor = TextAnchorEnum[(_b = (_a = this.prevPlacement) === null || _a === void 0 ? void 0 : _a.variableOffsets[symbolInstance.crossTileID]) === null || _b === void 0 ? void 0 : _b.anchor]; + const placeBoxForVariableAnchors = (collisionTextBox, collisionIconBox, orientation) => { + const width = collisionTextBox.x2 - collisionTextBox.x1; + const height = collisionTextBox.y2 - collisionTextBox.y1; + const textBoxScale = symbolInstance.textBoxScale; + const variableIconBox = hasIconTextFit && (iconOverlapMode === 'never') ? collisionIconBox : null; + let placedBox = null; + let placementPasses = (textOverlapMode === 'never') ? 1 : 2; + let overlapMode = 'never'; + if (prevAnchor) { + placementPasses++; + } + for (let pass = 0; pass < placementPasses; pass++) { + for (let i = textAnchorOffsetStart; i < textAnchorOffsetEnd; i++) { + const textAnchorOffset = bucket.textAnchorOffsets.get(i); + if (prevAnchor && textAnchorOffset.textAnchor !== prevAnchor) { + continue; + } + const result = this.attemptAnchorPlacement(textAnchorOffset, collisionTextBox, width, height, textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix, unwrappedTileID, collisionGroup, overlapMode, symbolInstance, bucket, orientation, translationText, translationIcon, variableIconBox, getElevation); + if (result) { + placedBox = result.placedGlyphBoxes; + if (placedBox && placedBox.placeable) { + placeText = true; + shift = result.shift; + return placedBox; + } + } + } + if (prevAnchor) { + prevAnchor = null; + } + else { + overlapMode = textOverlapMode; + } + } + if (showCollisionBoxes && !placedBox) { + // No box was successfully placed + // Generate bounds for a fake centered box, so that we can at least display something for collision debug. + const placedFakeGlyphBox = this.collisionIndex.placeCollisionBox(textBox, 'always', // Skips expensive collision check with already placed boxes + textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation, new Point$2(0, 0)); + placedBox = { + box: placedFakeGlyphBox.box, + offscreen: false, + placeable: false + }; + } + return placedBox; + }; + const placeHorizontal = () => { + return placeBoxForVariableAnchors(textBox, collisionArrays.iconBox, WritingMode.horizontal); + }; + const placeVertical = () => { + const verticalTextBox = collisionArrays.verticalTextBox; + const wasPlaced = placed && placed.placeable; + if (bucket.allowVerticalPlacement && !wasPlaced && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) { + return placeBoxForVariableAnchors(verticalTextBox, collisionArrays.verticalIconBox, WritingMode.vertical); + } + return { box: null, occluded: true, offscreen: null }; + }; + placeTextForPlacementModes(placeHorizontal, placeVertical); + if (placed) { + placeText = placed.placeable; + offscreen = placed.offscreen; + } + const prevOrientation = updatePreviousOrientationIfNotPlaced(placed && placed.placeable); + // If we didn't get placed, we still need to copy our position from the last placement for + // fade animations + if (!placeText && this.prevPlacement) { + const prevOffset = this.prevPlacement.variableOffsets[symbolInstance.crossTileID]; + if (prevOffset) { + this.variableOffsets[symbolInstance.crossTileID] = prevOffset; + this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, prevOrientation); + } + } + } + } + placedGlyphBoxes = placed; + placeText = placedGlyphBoxes && placedGlyphBoxes.placeable; + offscreen = placedGlyphBoxes && placedGlyphBoxes.offscreen; + if (symbolInstance.useRuntimeCollisionCircles) { + const placedSymbol = bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex); + const fontSize = evaluateSizeForFeature(bucket.textSizeData, partiallyEvaluatedTextSize, placedSymbol); + const textPixelPadding = layout.get('text-padding'); + const circlePixelDiameter = symbolInstance.collisionCircleDiameter; + placedGlyphCircles = this.collisionIndex.placeCollisionCircles(textOverlapMode, placedSymbol, bucket.lineVertexArray, bucket.glyphOffsetArray, fontSize, posMatrix, unwrappedTileID, textLabelPlaneMatrix, labelToScreenMatrix, showCollisionBoxes, pitchWithMap, collisionGroup.predicate, circlePixelDiameter, textPixelPadding, translationText, getElevation); + if (placedGlyphCircles.circles.length && placedGlyphCircles.collisionDetected && !showCollisionBoxes) { + warnOnce('Collisions detected, but collision boxes are not shown'); + } + // If text-overlap is set to 'always', force "placedCircles" to true + // In theory there should always be at least one circle placed + // in this case, but for now quirks in text-anchor + // and text-offset may prevent that from being true. + placeText = textAlwaysOverlap || (placedGlyphCircles.circles.length > 0 && !placedGlyphCircles.collisionDetected); + offscreen = offscreen && placedGlyphCircles.offscreen; + } + if (collisionArrays.iconFeatureIndex) { + iconFeatureIndex = collisionArrays.iconFeatureIndex; + } + if (collisionArrays.iconBox) { + const placeIconFeature = iconBox => { + return this.collisionIndex.placeCollisionBox(iconBox, iconOverlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationIcon, collisionGroup.predicate, getElevation, (hasIconTextFit && shift) ? shift : undefined); + }; + if (placedVerticalText && placedVerticalText.placeable && collisionArrays.verticalIconBox) { + placedIconBoxes = placeIconFeature(collisionArrays.verticalIconBox); + placeIcon = placedIconBoxes.placeable; + } + else { + placedIconBoxes = placeIconFeature(collisionArrays.iconBox); + placeIcon = placedIconBoxes.placeable; + } + offscreen = offscreen && placedIconBoxes.offscreen; + } + const iconWithoutText = textOptional || + (symbolInstance.numHorizontalGlyphVertices === 0 && symbolInstance.numVerticalGlyphVertices === 0); + const textWithoutIcon = iconOptional || symbolInstance.numIconVertices === 0; + // Combine the scales for icons and text. + if (!iconWithoutText && !textWithoutIcon) { + placeIcon = placeText = placeIcon && placeText; + } + else if (!textWithoutIcon) { + placeText = placeIcon && placeText; + } + else if (!iconWithoutText) { + placeIcon = placeIcon && placeText; + } + const hasTextBox = placeText && placedGlyphBoxes.placeable; + const hasIconBox = placeIcon && placedIconBoxes.placeable; + if (hasTextBox) { + if (placedVerticalText && placedVerticalText.placeable && verticalTextFeatureIndex) { + this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, textOverlapMode, layout.get('text-ignore-placement'), bucket.bucketInstanceId, verticalTextFeatureIndex, collisionGroup.ID); + } + else { + this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, textOverlapMode, layout.get('text-ignore-placement'), bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID); + } + } + if (hasIconBox) { + this.collisionIndex.insertCollisionBox(placedIconBoxes.box, iconOverlapMode, layout.get('icon-ignore-placement'), bucket.bucketInstanceId, iconFeatureIndex, collisionGroup.ID); + } + if (placedGlyphCircles) { + if (placeText) { + this.collisionIndex.insertCollisionCircles(placedGlyphCircles.circles, textOverlapMode, layout.get('text-ignore-placement'), bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID); + } + } + if (showCollisionBoxes) { + this.storeCollisionData(bucket.bucketInstanceId, symbolIndex, collisionArrays, placedGlyphBoxes, placedIconBoxes, placedGlyphCircles); + } + if (symbolInstance.crossTileID === 0) + throw new Error('symbolInstance.crossTileID can\'t be 0'); + if (bucket.bucketInstanceId === 0) + throw new Error('bucket.bucketInstanceId can\'t be 0'); + this.placements[symbolInstance.crossTileID] = new JointPlacement(placeText || alwaysShowText, placeIcon || alwaysShowIcon, offscreen || bucket.justReloaded); + seenCrossTileIDs[symbolInstance.crossTileID] = true; + }; + if (zOrderByViewportY) { + if (bucketPart.symbolInstanceStart !== 0) + throw new Error('bucket.bucketInstanceId should be 0'); + const symbolIndexes = bucket.getSortedSymbolIndexes(this.transform.angle); + for (let i = symbolIndexes.length - 1; i >= 0; --i) { + const symbolIndex = symbolIndexes[i]; + placeSymbol(bucket.symbolInstances.get(symbolIndex), bucket.collisionArrays[symbolIndex], symbolIndex); + } + } + else { + for (let i = bucketPart.symbolInstanceStart; i < bucketPart.symbolInstanceEnd; i++) { + placeSymbol(bucket.symbolInstances.get(i), bucket.collisionArrays[i], i); + } + } + if (showCollisionBoxes && bucket.bucketInstanceId in this.collisionCircleArrays) { + const circleArray = this.collisionCircleArrays[bucket.bucketInstanceId]; + // Store viewport and inverse projection matrices per bucket + invert$2(circleArray.invProjMatrix, posMatrix); + circleArray.viewportMatrix = this.collisionIndex.getViewportMatrix(); + } + bucket.justReloaded = false; + } + storeCollisionData(bucketInstanceId, symbolIndex, collisionArrays, placedGlyphBoxes, placedIconBoxes, placedGlyphCircles) { + if (collisionArrays.textBox || collisionArrays.iconBox) { + // Store the actually used collision box for debug draw + let boxArray; + if (this.collisionBoxArrays.has(bucketInstanceId)) { + boxArray = this.collisionBoxArrays.get(bucketInstanceId); + } + else { + boxArray = new Map(); + this.collisionBoxArrays.set(bucketInstanceId, boxArray); + } + let realCollisionBox; + if (boxArray.has(symbolIndex)) { + realCollisionBox = boxArray.get(symbolIndex); + } + else { + realCollisionBox = { + text: null, + icon: null + }; + boxArray.set(symbolIndex, realCollisionBox); + } + if (collisionArrays.textBox) { + realCollisionBox.text = placedGlyphBoxes.box; + } + if (collisionArrays.iconBox) { + realCollisionBox.icon = placedIconBoxes.box; + } + } + if (placedGlyphCircles) { + let circleArray = this.collisionCircleArrays[bucketInstanceId]; + // Group collision circles together by bucket. Circles can't be pushed forward for rendering yet as the symbol placement + // for a bucket is not guaranteed to be complete before the commit-function has been called + if (circleArray === undefined) + circleArray = this.collisionCircleArrays[bucketInstanceId] = new CollisionCircleArray(); + for (let i = 0; i < placedGlyphCircles.circles.length; i += 4) { + circleArray.circles.push(placedGlyphCircles.circles[i + 0]); // x + circleArray.circles.push(placedGlyphCircles.circles[i + 1]); // y + circleArray.circles.push(placedGlyphCircles.circles[i + 2]); // radius + circleArray.circles.push(placedGlyphCircles.collisionDetected ? 1 : 0); // collisionDetected-flag + } + } + } + markUsedJustification(bucket, placedAnchor, symbolInstance, orientation) { + const justifications = { + 'left': symbolInstance.leftJustifiedTextSymbolIndex, + 'center': symbolInstance.centerJustifiedTextSymbolIndex, + 'right': symbolInstance.rightJustifiedTextSymbolIndex + }; + let autoIndex; + if (orientation === WritingMode.vertical) { + autoIndex = symbolInstance.verticalPlacedTextSymbolIndex; + } + else { + autoIndex = justifications[getAnchorJustification(placedAnchor)]; + } + const indexes = [ + symbolInstance.leftJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.verticalPlacedTextSymbolIndex + ]; + for (const index of indexes) { + if (index >= 0) { + if (autoIndex >= 0 && index !== autoIndex) { + // There are multiple justifications and this one isn't it: shift offscreen + bucket.text.placedSymbolArray.get(index).crossTileID = 0; + } + else { + // Either this is the chosen justification or the justification is hardwired: use this one + bucket.text.placedSymbolArray.get(index).crossTileID = symbolInstance.crossTileID; + } + } + } + } + markUsedOrientation(bucket, orientation, symbolInstance) { + const horizontal = (orientation === WritingMode.horizontal || orientation === WritingMode.horizontalOnly) ? orientation : 0; + const vertical = orientation === WritingMode.vertical ? orientation : 0; + const horizontalIndexes = [ + symbolInstance.leftJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.rightJustifiedTextSymbolIndex + ]; + for (const index of horizontalIndexes) { + bucket.text.placedSymbolArray.get(index).placedOrientation = horizontal; + } + if (symbolInstance.verticalPlacedTextSymbolIndex) { + bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).placedOrientation = vertical; + } + } + commit(now) { + this.commitTime = now; + this.zoomAtLastRecencyCheck = this.transform.zoom; + const prevPlacement = this.prevPlacement; + let placementChanged = false; + this.prevZoomAdjustment = prevPlacement ? prevPlacement.zoomAdjustment(this.transform.zoom) : 0; + const increment = prevPlacement ? prevPlacement.symbolFadeChange(now) : 1; + const prevOpacities = prevPlacement ? prevPlacement.opacities : {}; + const prevOffsets = prevPlacement ? prevPlacement.variableOffsets : {}; + const prevOrientations = prevPlacement ? prevPlacement.placedOrientations : {}; + // add the opacities from the current placement, and copy their current values from the previous placement + for (const crossTileID in this.placements) { + const jointPlacement = this.placements[crossTileID]; + const prevOpacity = prevOpacities[crossTileID]; + if (prevOpacity) { + this.opacities[crossTileID] = new JointOpacityState(prevOpacity, increment, jointPlacement.text, jointPlacement.icon); + placementChanged = placementChanged || + jointPlacement.text !== prevOpacity.text.placed || + jointPlacement.icon !== prevOpacity.icon.placed; + } + else { + this.opacities[crossTileID] = new JointOpacityState(null, increment, jointPlacement.text, jointPlacement.icon, jointPlacement.skipFade); + placementChanged = placementChanged || jointPlacement.text || jointPlacement.icon; + } + } + // copy and update values from the previous placement that aren't in the current placement but haven't finished fading + for (const crossTileID in prevOpacities) { + const prevOpacity = prevOpacities[crossTileID]; + if (!this.opacities[crossTileID]) { + const jointOpacity = new JointOpacityState(prevOpacity, increment, false, false); + if (!jointOpacity.isHidden()) { + this.opacities[crossTileID] = jointOpacity; + placementChanged = placementChanged || prevOpacity.text.placed || prevOpacity.icon.placed; + } + } + } + for (const crossTileID in prevOffsets) { + if (!this.variableOffsets[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) { + this.variableOffsets[crossTileID] = prevOffsets[crossTileID]; + } + } + for (const crossTileID in prevOrientations) { + if (!this.placedOrientations[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) { + this.placedOrientations[crossTileID] = prevOrientations[crossTileID]; + } + } + // this.lastPlacementChangeTime is the time of the last commit() that + // resulted in a placement change -- in other words, the start time of + // the last symbol fade animation + if (prevPlacement && prevPlacement.lastPlacementChangeTime === undefined) { + throw new Error('Last placement time for previous placement is not defined'); + } + if (placementChanged) { + this.lastPlacementChangeTime = now; + } + else if (typeof this.lastPlacementChangeTime !== 'number') { + this.lastPlacementChangeTime = prevPlacement ? prevPlacement.lastPlacementChangeTime : now; + } + } + updateLayerOpacities(styleLayer, tiles) { + const seenCrossTileIDs = {}; + for (const tile of tiles) { + const symbolBucket = tile.getBucket(styleLayer); + if (symbolBucket && tile.latestFeatureIndex && styleLayer.id === symbolBucket.layerIds[0]) { + this.updateBucketOpacities(symbolBucket, tile.tileID, seenCrossTileIDs, tile.collisionBoxArray); + } + } + } + updateBucketOpacities(bucket, tileID, seenCrossTileIDs, collisionBoxArray) { + if (bucket.hasTextData()) { + bucket.text.opacityVertexArray.clear(); + bucket.text.hasVisibleVertices = false; + } + if (bucket.hasIconData()) { + bucket.icon.opacityVertexArray.clear(); + bucket.icon.hasVisibleVertices = false; + } + if (bucket.hasIconCollisionBoxData()) + bucket.iconCollisionBox.collisionVertexArray.clear(); + if (bucket.hasTextCollisionBoxData()) + bucket.textCollisionBox.collisionVertexArray.clear(); + const layer = bucket.layers[0]; + const layout = layer.layout; + const duplicateOpacityState = new JointOpacityState(null, 0, false, false, true); + const textAllowOverlap = layout.get('text-allow-overlap'); + const iconAllowOverlap = layout.get('icon-allow-overlap'); + const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset'); + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const hasIconTextFit = layout.get('icon-text-fit') !== 'none'; + // If allow-overlap is true, we can show symbols before placement runs on them + // But we have to wait for placement if we potentially depend on a paired icon/text + // with allow-overlap: false. + // See https://github.com/mapbox/mapbox-gl-js/issues/7032 + const defaultOpacityState = new JointOpacityState(null, 0, textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || layout.get('icon-optional')), iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || layout.get('text-optional')), true); + if (!bucket.collisionArrays && collisionBoxArray && ((bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()))) { + bucket.deserializeCollisionBoxes(collisionBoxArray); + } + const addOpacities = (iconOrText, numVertices, opacity) => { + for (let i = 0; i < numVertices / 4; i++) { + iconOrText.opacityVertexArray.emplaceBack(opacity); + } + iconOrText.hasVisibleVertices = iconOrText.hasVisibleVertices || (opacity !== PACKED_HIDDEN_OPACITY); + }; + const boxArrays = this.collisionBoxArrays.get(bucket.bucketInstanceId); + for (let s = 0; s < bucket.symbolInstances.length; s++) { + const symbolInstance = bucket.symbolInstances.get(s); + const { numHorizontalGlyphVertices, numVerticalGlyphVertices, crossTileID } = symbolInstance; + const isDuplicate = seenCrossTileIDs[crossTileID]; + let opacityState = this.opacities[crossTileID]; + if (isDuplicate) { + opacityState = duplicateOpacityState; + } + else if (!opacityState) { + opacityState = defaultOpacityState; + // store the state so that future placements use it as a starting point + this.opacities[crossTileID] = opacityState; + } + seenCrossTileIDs[crossTileID] = true; + const hasText = numHorizontalGlyphVertices > 0 || numVerticalGlyphVertices > 0; + const hasIcon = symbolInstance.numIconVertices > 0; + const placedOrientation = this.placedOrientations[symbolInstance.crossTileID]; + const horizontalHidden = placedOrientation === WritingMode.vertical; + const verticalHidden = placedOrientation === WritingMode.horizontal || placedOrientation === WritingMode.horizontalOnly; + if (hasText) { + const packedOpacity = packOpacity(opacityState.text); + // Vertical text fades in/out on collision the same way as corresponding + // horizontal text. Switch between vertical/horizontal should be instantaneous + const horizontalOpacity = horizontalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity; + addOpacities(bucket.text, numHorizontalGlyphVertices, horizontalOpacity); + const verticalOpacity = verticalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity; + addOpacities(bucket.text, numVerticalGlyphVertices, verticalOpacity); + // If this label is completely faded, mark it so that we don't have to calculate + // its position at render time. If this layer has variable placement, shift the various + // symbol instances appropriately so that symbols from buckets that have yet to be placed + // offset appropriately. + const symbolHidden = opacityState.text.isHidden(); + [ + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.leftJustifiedTextSymbolIndex + ].forEach(index => { + if (index >= 0) { + bucket.text.placedSymbolArray.get(index).hidden = symbolHidden || horizontalHidden ? 1 : 0; + } + }); + if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) { + bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).hidden = symbolHidden || verticalHidden ? 1 : 0; + } + const prevOffset = this.variableOffsets[symbolInstance.crossTileID]; + if (prevOffset) { + this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, placedOrientation); + } + const prevOrientation = this.placedOrientations[symbolInstance.crossTileID]; + if (prevOrientation) { + this.markUsedJustification(bucket, 'left', symbolInstance, prevOrientation); + this.markUsedOrientation(bucket, prevOrientation, symbolInstance); + } + } + if (hasIcon) { + const packedOpacity = packOpacity(opacityState.icon); + const useHorizontal = !(hasIconTextFit && symbolInstance.verticalPlacedIconSymbolIndex && horizontalHidden); + if (symbolInstance.placedIconSymbolIndex >= 0) { + const horizontalOpacity = useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY; + addOpacities(bucket.icon, symbolInstance.numIconVertices, horizontalOpacity); + bucket.icon.placedSymbolArray.get(symbolInstance.placedIconSymbolIndex).hidden = + opacityState.icon.isHidden(); + } + if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) { + const verticalOpacity = !useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY; + addOpacities(bucket.icon, symbolInstance.numVerticalIconVertices, verticalOpacity); + bucket.icon.placedSymbolArray.get(symbolInstance.verticalPlacedIconSymbolIndex).hidden = + opacityState.icon.isHidden(); + } + } + const realBoxes = (boxArrays && boxArrays.has(s)) ? boxArrays.get(s) : { + text: null, + icon: null + }; + if (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()) { + const collisionArrays = bucket.collisionArrays[s]; + if (collisionArrays) { + let shift = new Point$2(0, 0); + if (collisionArrays.textBox || collisionArrays.verticalTextBox) { + let used = true; + if (hasVariablePlacement) { + const variableOffset = this.variableOffsets[crossTileID]; + if (variableOffset) { + // This will show either the currently placed position or the last + // successfully placed position (so you can visualize what collision + // just made the symbol disappear, and the most likely place for the + // symbol to come back) + shift = calculateVariableLayoutShift(variableOffset.anchor, variableOffset.width, variableOffset.height, variableOffset.textOffset, variableOffset.textBoxScale); + if (rotateWithMap) { + shift._rotate(pitchWithMap ? this.transform.angle : -this.transform.angle); + } + } + else { + // No offset -> this symbol hasn't been placed since coming on-screen + // No single box is particularly meaningful and all of them would be too noisy + // Use the center box just to show something's there, but mark it "not used" + used = false; + } + } + if (collisionArrays.textBox || collisionArrays.verticalTextBox) { + let hidden; + if (collisionArrays.textBox) { + hidden = horizontalHidden; + } + if (collisionArrays.verticalTextBox) { + hidden = verticalHidden; + } + updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || hidden, realBoxes.text, shift.x, shift.y); + } + } + if (collisionArrays.iconBox || collisionArrays.verticalIconBox) { + const verticalIconUsed = Boolean(!verticalHidden && collisionArrays.verticalIconBox); + let hidden; + if (collisionArrays.iconBox) { + hidden = verticalIconUsed; + } + if (collisionArrays.verticalIconBox) { + hidden = !verticalIconUsed; + } + updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, hidden, realBoxes.icon, hasIconTextFit ? shift.x : 0, hasIconTextFit ? shift.y : 0); + } + } + } + } + bucket.sortFeatures(this.transform.angle); + if (this.retainedQueryData[bucket.bucketInstanceId]) { + this.retainedQueryData[bucket.bucketInstanceId].featureSortOrder = bucket.featureSortOrder; + } + if (bucket.hasTextData() && bucket.text.opacityVertexBuffer) { + bucket.text.opacityVertexBuffer.updateData(bucket.text.opacityVertexArray); + } + if (bucket.hasIconData() && bucket.icon.opacityVertexBuffer) { + bucket.icon.opacityVertexBuffer.updateData(bucket.icon.opacityVertexArray); + } + if (bucket.hasIconCollisionBoxData() && bucket.iconCollisionBox.collisionVertexBuffer) { + bucket.iconCollisionBox.collisionVertexBuffer.updateData(bucket.iconCollisionBox.collisionVertexArray); + } + if (bucket.hasTextCollisionBoxData() && bucket.textCollisionBox.collisionVertexBuffer) { + bucket.textCollisionBox.collisionVertexBuffer.updateData(bucket.textCollisionBox.collisionVertexArray); + } + if (bucket.text.opacityVertexArray.length !== bucket.text.layoutVertexArray.length / 4) + throw new Error(`bucket.text.opacityVertexArray.length (= ${bucket.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${bucket.text.layoutVertexArray.length}) / 4`); + if (bucket.icon.opacityVertexArray.length !== bucket.icon.layoutVertexArray.length / 4) + throw new Error(`bucket.icon.opacityVertexArray.length (= ${bucket.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${bucket.icon.layoutVertexArray.length}) / 4`); + // Push generated collision circles to the bucket for debug rendering + if (bucket.bucketInstanceId in this.collisionCircleArrays) { + const instance = this.collisionCircleArrays[bucket.bucketInstanceId]; + bucket.placementInvProjMatrix = instance.invProjMatrix; + bucket.placementViewportMatrix = instance.viewportMatrix; + bucket.collisionCircleArray = instance.circles; + delete this.collisionCircleArrays[bucket.bucketInstanceId]; + } + } + symbolFadeChange(now) { + return this.fadeDuration === 0 ? + 1 : + ((now - this.commitTime) / this.fadeDuration + this.prevZoomAdjustment); + } + zoomAdjustment(zoom) { + // When zooming out quickly, labels can overlap each other. This + // adjustment is used to reduce the interval between placement calculations + // and to reduce the fade duration when zooming out quickly. Discovering the + // collisions more quickly and fading them more quickly reduces the unwanted effect. + return Math.max(0, (this.transform.zoom - zoom) / 1.5); + } + hasTransitions(now) { + return this.stale || + now - this.lastPlacementChangeTime < this.fadeDuration; + } + stillRecent(now, zoom) { + // The adjustment makes placement more frequent when zooming. + // This condition applies the adjustment only after the map has + // stopped zooming. This avoids adding extra jank while zooming. + const durationAdjustment = this.zoomAtLastRecencyCheck === zoom ? + (1 - this.zoomAdjustment(zoom)) : + 1; + this.zoomAtLastRecencyCheck = zoom; + return this.commitTime + this.fadeDuration * durationAdjustment > now; + } + setStale() { + this.stale = true; + } +} +function updateCollisionVertices(collisionVertexArray, placed, notUsed, realBox, shiftX, shiftY) { + if (!realBox || realBox.length === 0) { + realBox = [0, 0, 0, 0]; + } + const tlX = realBox[0] - viewportPadding; + const tlY = realBox[1] - viewportPadding; + const brX = realBox[2] - viewportPadding; + const brY = realBox[3] - viewportPadding; + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, tlX, tlY); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, brX, tlY); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, brX, brY); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, tlX, brY); +} +// All four vertices for a glyph will have the same opacity state +// So we pack the opacity into a uint8, and then repeat it four times +// to make a single uint32 that we can upload for each glyph in the +// label. +const shift25 = Math.pow(2, 25); +const shift24 = Math.pow(2, 24); +const shift17 = Math.pow(2, 17); +const shift16 = Math.pow(2, 16); +const shift9 = Math.pow(2, 9); +const shift8 = Math.pow(2, 8); +const shift1 = Math.pow(2, 1); +function packOpacity(opacityState) { + if (opacityState.opacity === 0 && !opacityState.placed) { + return 0; + } + else if (opacityState.opacity === 1 && opacityState.placed) { + return 4294967295; + } + const targetBit = opacityState.placed ? 1 : 0; + const opacityBits = Math.floor(opacityState.opacity * 127); + return opacityBits * shift25 + targetBit * shift24 + + opacityBits * shift17 + targetBit * shift16 + + opacityBits * shift9 + targetBit * shift8 + + opacityBits * shift1 + targetBit; +} +const PACKED_HIDDEN_OPACITY = 0; + +function createProjection() { + return { + isOccluded(_x, _y, _t) { + return false; + }, + getPitchedTextCorrection(_transform, _anchor, _tile) { + return 1.0; + }, + get useSpecialProjectionForSymbols() { return false; }, + projectTileCoordinates(_x, _y, _t, _ele) { + // This function should only be used when useSpecialProjectionForSymbols is set to true. + throw new Error('Not implemented.'); + }, + translatePosition(transform, tile, translate, translateAnchor) { + return translatePosition(transform, tile, translate, translateAnchor); + }, + getCircleRadiusCorrection(_) { + return 1.0; + } + }; +} +/** + * Returns a translation in tile units that correctly incorporates the view angle and the *-translate and *-translate-anchor properties. + * @param inViewportPixelUnitsUnits - True when the units accepted by the matrix are in viewport pixels instead of tile units. + * + * Temporarily imported from globe branch. + */ +function translatePosition(transform, tile, translate, translateAnchor, inViewportPixelUnitsUnits = false) { + if (!translate[0] && !translate[1]) + return [0, 0]; + const angle = inViewportPixelUnitsUnits ? + (translateAnchor === 'map' ? transform.angle : 0) : + (translateAnchor === 'viewport' ? -transform.angle : 0); + if (angle) { + const sinA = Math.sin(angle); + const cosA = Math.cos(angle); + translate = [ + translate[0] * cosA - translate[1] * sinA, + translate[0] * sinA + translate[1] * cosA + ]; + } + return [ + inViewportPixelUnitsUnits ? translate[0] : pixelsToTileUnits(tile, translate[0], transform.zoom), + inViewportPixelUnitsUnits ? translate[1] : pixelsToTileUnits(tile, translate[1], transform.zoom) + ]; +} + +class LayerPlacement { + constructor(styleLayer) { + this._sortAcrossTiles = styleLayer.layout.get('symbol-z-order') !== 'viewport-y' && + !styleLayer.layout.get('symbol-sort-key').isConstant(); + this._currentTileIndex = 0; + this._currentPartIndex = 0; + this._seenCrossTileIDs = {}; + this._bucketParts = []; + } + continuePlacement(tiles, placement, showCollisionBoxes, styleLayer, shouldPausePlacement) { + const bucketParts = this._bucketParts; + while (this._currentTileIndex < tiles.length) { + const tile = tiles[this._currentTileIndex]; + placement.getBucketParts(bucketParts, styleLayer, tile, this._sortAcrossTiles); + this._currentTileIndex++; + if (shouldPausePlacement()) { + return true; + } + } + if (this._sortAcrossTiles) { + this._sortAcrossTiles = false; + bucketParts.sort((a, b) => a.sortKey - b.sortKey); + } + while (this._currentPartIndex < bucketParts.length) { + const bucketPart = bucketParts[this._currentPartIndex]; + placement.placeLayerBucketPart(bucketPart, this._seenCrossTileIDs, showCollisionBoxes); + this._currentPartIndex++; + if (shouldPausePlacement()) { + return true; + } + } + return false; + } +} +class PauseablePlacement { + constructor(transform, terrain, order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, prevPlacement) { + this.placement = new Placement(transform, createProjection(), terrain, fadeDuration, crossSourceCollisions, prevPlacement); + this._currentPlacementIndex = order.length - 1; + this._forceFullPlacement = forceFullPlacement; + this._showCollisionBoxes = showCollisionBoxes; + this._done = false; + } + isDone() { + return this._done; + } + continuePlacement(order, layers, layerTiles) { + const startTime = browser.now(); + const shouldPausePlacement = () => { + return this._forceFullPlacement ? false : (browser.now() - startTime) > 2; + }; + while (this._currentPlacementIndex >= 0) { + const layerId = order[this._currentPlacementIndex]; + const layer = layers[layerId]; + const placementZoom = this.placement.collisionIndex.transform.zoom; + if (layer.type === 'symbol' && + (!layer.minzoom || layer.minzoom <= placementZoom) && + (!layer.maxzoom || layer.maxzoom > placementZoom)) { + if (!this._inProgressLayer) { + this._inProgressLayer = new LayerPlacement(layer); + } + const pausePlacement = this._inProgressLayer.continuePlacement(layerTiles[layer.source], this.placement, this._showCollisionBoxes, layer, shouldPausePlacement); + if (pausePlacement) { + // We didn't finish placing all layers within 2ms, + // but we can keep rendering with a partial placement + // We'll resume here on the next frame + return; + } + delete this._inProgressLayer; + } + this._currentPlacementIndex--; + } + this._done = true; + } + commit(now) { + this.placement.commit(now); + return this.placement; + } +} + +const ARRAY_TYPES = [ + Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, + Int32Array, Uint32Array, Float32Array, Float64Array +]; + +/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */ + +const VERSION = 1; // serialized format version +const HEADER_SIZE = 8; + +class KDBush { + + /** + * Creates an index from raw `ArrayBuffer` data. + * @param {ArrayBuffer} data + */ + static from(data) { + if (!(data instanceof ArrayBuffer)) { + throw new Error('Data must be an instance of ArrayBuffer.'); + } + const [magic, versionAndType] = new Uint8Array(data, 0, 2); + if (magic !== 0xdb) { + throw new Error('Data does not appear to be in a KDBush format.'); + } + const version = versionAndType >> 4; + if (version !== VERSION) { + throw new Error(`Got v${version} data when expected v${VERSION}.`); + } + const ArrayType = ARRAY_TYPES[versionAndType & 0x0f]; + if (!ArrayType) { + throw new Error('Unrecognized array type.'); + } + const [nodeSize] = new Uint16Array(data, 2, 1); + const [numItems] = new Uint32Array(data, 4, 1); + + return new KDBush(numItems, nodeSize, ArrayType, data); + } + + /** + * Creates an index that will hold a given number of items. + * @param {number} numItems + * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default). + * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default). + * @param {ArrayBuffer} [data] (For internal use only) + */ + constructor(numItems, nodeSize = 64, ArrayType = Float64Array, data) { + if (isNaN(numItems) || numItems < 0) throw new Error(`Unpexpected numItems value: ${numItems}.`); + + this.numItems = +numItems; + this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535); + this.ArrayType = ArrayType; + this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array; + + const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType); + const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT; + const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT; + const padCoords = (8 - idsByteSize % 8) % 8; + + if (arrayTypeIndex < 0) { + throw new Error(`Unexpected typed array class: ${ArrayType}.`); + } + + if (data && (data instanceof ArrayBuffer)) { // reconstruct an index from a buffer + this.data = data; + this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems); + this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2); + this._pos = numItems * 2; + this._finished = true; + } else { // initialize a new index + this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords); + this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems); + this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2); + this._pos = 0; + this._finished = false; + + // set header + new Uint8Array(this.data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]); + new Uint16Array(this.data, 2, 1)[0] = nodeSize; + new Uint32Array(this.data, 4, 1)[0] = numItems; + } + } + + /** + * Add a point to the index. + * @param {number} x + * @param {number} y + * @returns {number} An incremental index associated with the added item (starting from `0`). + */ + add(x, y) { + const index = this._pos >> 1; + this.ids[index] = index; + this.coords[this._pos++] = x; + this.coords[this._pos++] = y; + return index; + } + + /** + * Perform indexing of the added points. + */ + finish() { + const numAdded = this._pos >> 1; + if (numAdded !== this.numItems) { + throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`); + } + // kd-sort both arrays for efficient search + sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0); + + this._finished = true; + return this; + } + + /** + * Search the index for items within a given bounding box. + * @param {number} minX + * @param {number} minY + * @param {number} maxX + * @param {number} maxY + * @returns {number[]} An array of indices correponding to the found items. + */ + range(minX, minY, maxX, maxY) { + if (!this._finished) throw new Error('Data not yet indexed - call index.finish().'); + + const {ids, coords, nodeSize} = this; + const stack = [0, ids.length - 1, 0]; + const result = []; + + // recursively search for items in range in the kd-sorted arrays + while (stack.length) { + const axis = stack.pop() || 0; + const right = stack.pop() || 0; + const left = stack.pop() || 0; + + // if we reached "tree node", search linearly + if (right - left <= nodeSize) { + for (let i = left; i <= right; i++) { + const x = coords[2 * i]; + const y = coords[2 * i + 1]; + if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]); + } + continue; + } + + // otherwise find the middle index + const m = (left + right) >> 1; + + // include the middle item if it's in range + const x = coords[2 * m]; + const y = coords[2 * m + 1]; + if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]); + + // queue search in halves that intersect the query + if (axis === 0 ? minX <= x : minY <= y) { + stack.push(left); + stack.push(m - 1); + stack.push(1 - axis); + } + if (axis === 0 ? maxX >= x : maxY >= y) { + stack.push(m + 1); + stack.push(right); + stack.push(1 - axis); + } + } + + return result; + } + + /** + * Search the index for items within a given radius. + * @param {number} qx + * @param {number} qy + * @param {number} r Query radius. + * @returns {number[]} An array of indices correponding to the found items. + */ + within(qx, qy, r) { + if (!this._finished) throw new Error('Data not yet indexed - call index.finish().'); + + const {ids, coords, nodeSize} = this; + const stack = [0, ids.length - 1, 0]; + const result = []; + const r2 = r * r; + + // recursively search for items within radius in the kd-sorted arrays + while (stack.length) { + const axis = stack.pop() || 0; + const right = stack.pop() || 0; + const left = stack.pop() || 0; + + // if we reached "tree node", search linearly + if (right - left <= nodeSize) { + for (let i = left; i <= right; i++) { + if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]); + } + continue; + } + + // otherwise find the middle index + const m = (left + right) >> 1; + + // include the middle item if it's in range + const x = coords[2 * m]; + const y = coords[2 * m + 1]; + if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]); + + // queue search in halves that intersect the query + if (axis === 0 ? qx - r <= x : qy - r <= y) { + stack.push(left); + stack.push(m - 1); + stack.push(1 - axis); + } + if (axis === 0 ? qx + r >= x : qy + r >= y) { + stack.push(m + 1); + stack.push(right); + stack.push(1 - axis); + } + } + + return result; + } +} + +/** + * @param {Uint16Array | Uint32Array} ids + * @param {InstanceType} coords + * @param {number} nodeSize + * @param {number} left + * @param {number} right + * @param {number} axis + */ +function sort(ids, coords, nodeSize, left, right, axis) { + if (right - left <= nodeSize) return; + + const m = (left + right) >> 1; // middle index + + // sort ids and coords around the middle index so that the halves lie + // either left/right or top/bottom correspondingly (taking turns) + select(ids, coords, m, left, right, axis); + + // recursively kd-sort first half and second half on the opposite axis + sort(ids, coords, nodeSize, left, m - 1, 1 - axis); + sort(ids, coords, nodeSize, m + 1, right, 1 - axis); +} + +/** + * Custom Floyd-Rivest selection algorithm: sort ids and coords so that + * [left..k-1] items are smaller than k-th item (on either x or y axis) + * @param {Uint16Array | Uint32Array} ids + * @param {InstanceType} coords + * @param {number} k + * @param {number} left + * @param {number} right + * @param {number} axis + */ +function select(ids, coords, k, left, right, axis) { + + while (right > left) { + if (right - left > 600) { + const n = right - left + 1; + const m = k - left + 1; + const z = Math.log(n); + const s = 0.5 * Math.exp(2 * z / 3); + const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + const newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + select(ids, coords, k, newLeft, newRight, axis); + } + + const t = coords[2 * k + axis]; + let i = left; + let j = right; + + swapItem(ids, coords, left, k); + if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right); + + while (i < j) { + swapItem(ids, coords, i, j); + i++; + j--; + while (coords[2 * i + axis] < t) i++; + while (coords[2 * j + axis] > t) j--; + } + + if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j); + else { + j++; + swapItem(ids, coords, j, right); + } + + if (j <= k) left = j + 1; + if (k <= j) right = j - 1; + } +} + +/** + * @param {Uint16Array | Uint32Array} ids + * @param {InstanceType} coords + * @param {number} i + * @param {number} j + */ +function swapItem(ids, coords, i, j) { + swap(ids, i, j); + swap(coords, 2 * i, 2 * j); + swap(coords, 2 * i + 1, 2 * j + 1); +} + +/** + * @param {InstanceType} arr + * @param {number} i + * @param {number} j + */ +function swap(arr, i, j) { + const tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} + +/** + * @param {number} ax + * @param {number} ay + * @param {number} bx + * @param {number} by + */ +function sqDist(ax, ay, bx, by) { + const dx = ax - bx; + const dy = ay - by; + return dx * dx + dy * dy; +} + +/* + The CrossTileSymbolIndex generally works on the assumption that + a conceptual "unique symbol" can be identified by the text of + the label combined with the anchor point. The goal is to assign + these conceptual "unique symbols" a shared crossTileID that can be + used by Placement to keep fading opacity states consistent and to + deduplicate labels. + + The CrossTileSymbolIndex indexes all the current symbol instances and + their crossTileIDs. When a symbol bucket gets added or updated, the + index assigns a crossTileID to each of it's symbol instances by either + matching it with an existing id or assigning a new one. +*/ +// Round anchor positions to roughly 4 pixel grid +const roundingFactor = 512 / EXTENT / 2; +const KDBUSH_THRESHHOLD = 128; +class TileLayerIndex { + constructor(tileID, symbolInstances, bucketInstanceId) { + this.tileID = tileID; + this.bucketInstanceId = bucketInstanceId; + this._symbolsByKey = {}; + // group the symbolInstances by key + const symbolInstancesByKey = new Map(); + for (let i = 0; i < symbolInstances.length; i++) { + const symbolInstance = symbolInstances.get(i); + const key = symbolInstance.key; + const instances = symbolInstancesByKey.get(key); + if (instances) { + // This tile may have multiple symbol instances with the same key + // Store each one along with its coordinates + instances.push(symbolInstance); + } + else { + symbolInstancesByKey.set(key, [symbolInstance]); + } + } + // index the SymbolInstances in this each bucket + for (const [key, symbols] of symbolInstancesByKey) { + const positions = symbols.map(symbolInstance => ({ x: Math.floor(symbolInstance.anchorX * roundingFactor), y: Math.floor(symbolInstance.anchorY * roundingFactor) })); + const crossTileIDs = symbols.map(v => v.crossTileID); + const entry = { positions, crossTileIDs }; + // once we get too many symbols for a given key, it becomes much faster to index it before queries + if (entry.positions.length > KDBUSH_THRESHHOLD) { + const index = new KDBush(entry.positions.length, 16, Uint16Array); + for (const { x, y } of entry.positions) + index.add(x, y); + index.finish(); + // clear all references to the original positions data + delete entry.positions; + entry.index = index; + } + this._symbolsByKey[key] = entry; + } + } + // Converts the coordinates of the input symbol instance into coordinates that be can compared + // against other symbols in this index. Coordinates are: + // (1) local-tile-based (so after correction we get x,y values relative to our local anchorX/Y) + // (2) converted to the z-scale of this TileLayerIndex + // (3) down-sampled by "roundingFactor" from tile coordinate precision in order to be + // more tolerant of small differences between tiles. + getScaledCoordinates(symbolInstance, childTileID) { + const { x: localX, y: localY, z: localZ } = this.tileID.canonical; + const { x, y, z } = childTileID.canonical; + const zDifference = z - localZ; + const scale = roundingFactor / Math.pow(2, zDifference); + const xWorld = (x * EXTENT + symbolInstance.anchorX) * scale; + const yWorld = (y * EXTENT + symbolInstance.anchorY) * scale; + const xOffset = localX * EXTENT * roundingFactor; + const yOffset = localY * EXTENT * roundingFactor; + const result = { + x: Math.floor(xWorld - xOffset), + y: Math.floor(yWorld - yOffset) + }; + return result; + } + findMatches(symbolInstances, newTileID, zoomCrossTileIDs) { + const tolerance = this.tileID.canonical.z < newTileID.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - newTileID.canonical.z); + for (let i = 0; i < symbolInstances.length; i++) { + const symbolInstance = symbolInstances.get(i); + if (symbolInstance.crossTileID) { + // already has a match, skip + continue; + } + const entry = this._symbolsByKey[symbolInstance.key]; + if (!entry) { + // No symbol with this key in this bucket + continue; + } + const scaledSymbolCoord = this.getScaledCoordinates(symbolInstance, newTileID); + if (entry.index) { + // Return any symbol with the same keys whose coordinates are within 1 + // grid unit. (with a 4px grid, this covers a 12px by 12px area) + const indexes = entry.index.range(scaledSymbolCoord.x - tolerance, scaledSymbolCoord.y - tolerance, scaledSymbolCoord.x + tolerance, scaledSymbolCoord.y + tolerance).sort(); + for (const i of indexes) { + const crossTileID = entry.crossTileIDs[i]; + if (!zoomCrossTileIDs[crossTileID]) { + // Once we've marked ourselves duplicate against this parent symbol, + // don't let any other symbols at the same zoom level duplicate against + // the same parent (see issue #5993) + zoomCrossTileIDs[crossTileID] = true; + symbolInstance.crossTileID = crossTileID; + break; + } + } + } + else if (entry.positions) { + for (let i = 0; i < entry.positions.length; i++) { + const thisTileSymbol = entry.positions[i]; + const crossTileID = entry.crossTileIDs[i]; + // Return any symbol with the same keys whose coordinates are within 1 + // grid unit. (with a 4px grid, this covers a 12px by 12px area) + if (Math.abs(thisTileSymbol.x - scaledSymbolCoord.x) <= tolerance && + Math.abs(thisTileSymbol.y - scaledSymbolCoord.y) <= tolerance && + !zoomCrossTileIDs[crossTileID]) { + // Once we've marked ourselves duplicate against this parent symbol, + // don't let any other symbols at the same zoom level duplicate against + // the same parent (see issue #5993) + zoomCrossTileIDs[crossTileID] = true; + symbolInstance.crossTileID = crossTileID; + break; + } + } + } + } + } + getCrossTileIDsLists() { + return Object.values(this._symbolsByKey).map(({ crossTileIDs }) => crossTileIDs); + } +} +class CrossTileIDs { + constructor() { + this.maxCrossTileID = 0; + } + generate() { + return ++this.maxCrossTileID; + } +} +class CrossTileSymbolLayerIndex { + constructor() { + this.indexes = {}; + this.usedCrossTileIDs = {}; + this.lng = 0; + } + /* + * Sometimes when a user pans across the antimeridian the longitude value gets wrapped. + * To prevent labels from flashing out and in we adjust the tileID values in the indexes + * so that they match the new wrapped version of the map. + */ + handleWrapJump(lng) { + const wrapDelta = Math.round((lng - this.lng) / 360); + if (wrapDelta !== 0) { + for (const zoom in this.indexes) { + const zoomIndexes = this.indexes[zoom]; + const newZoomIndex = {}; + for (const key in zoomIndexes) { + // change the tileID's wrap and add it to a new index + const index = zoomIndexes[key]; + index.tileID = index.tileID.unwrapTo(index.tileID.wrap + wrapDelta); + newZoomIndex[index.tileID.key] = index; + } + this.indexes[zoom] = newZoomIndex; + } + } + this.lng = lng; + } + addBucket(tileID, bucket, crossTileIDs) { + if (this.indexes[tileID.overscaledZ] && + this.indexes[tileID.overscaledZ][tileID.key]) { + if (this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId === + bucket.bucketInstanceId) { + return false; + } + else { + // We're replacing this bucket with an updated version + // Remove the old bucket's "used crossTileIDs" now so that + // the new bucket can claim them. + // The old index entries themselves stick around until + // 'removeStaleBuckets' is called. + this.removeBucketCrossTileIDs(tileID.overscaledZ, this.indexes[tileID.overscaledZ][tileID.key]); + } + } + for (let i = 0; i < bucket.symbolInstances.length; i++) { + const symbolInstance = bucket.symbolInstances.get(i); + symbolInstance.crossTileID = 0; + } + if (!this.usedCrossTileIDs[tileID.overscaledZ]) { + this.usedCrossTileIDs[tileID.overscaledZ] = {}; + } + const zoomCrossTileIDs = this.usedCrossTileIDs[tileID.overscaledZ]; + for (const zoom in this.indexes) { + const zoomIndexes = this.indexes[zoom]; + if (Number(zoom) > tileID.overscaledZ) { + for (const id in zoomIndexes) { + const childIndex = zoomIndexes[id]; + if (childIndex.tileID.isChildOf(tileID)) { + childIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs); + } + } + } + else { + const parentCoord = tileID.scaledTo(Number(zoom)); + const parentIndex = zoomIndexes[parentCoord.key]; + if (parentIndex) { + parentIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs); + } + } + } + for (let i = 0; i < bucket.symbolInstances.length; i++) { + const symbolInstance = bucket.symbolInstances.get(i); + if (!symbolInstance.crossTileID) { + // symbol did not match any known symbol, assign a new id + symbolInstance.crossTileID = crossTileIDs.generate(); + zoomCrossTileIDs[symbolInstance.crossTileID] = true; + } + } + if (this.indexes[tileID.overscaledZ] === undefined) { + this.indexes[tileID.overscaledZ] = {}; + } + this.indexes[tileID.overscaledZ][tileID.key] = new TileLayerIndex(tileID, bucket.symbolInstances, bucket.bucketInstanceId); + return true; + } + removeBucketCrossTileIDs(zoom, removedBucket) { + for (const crossTileIDs of removedBucket.getCrossTileIDsLists()) { + for (const crossTileID of crossTileIDs) { + delete this.usedCrossTileIDs[zoom][crossTileID]; + } + } + } + removeStaleBuckets(currentIDs) { + let tilesChanged = false; + for (const z in this.indexes) { + const zoomIndexes = this.indexes[z]; + for (const tileKey in zoomIndexes) { + if (!currentIDs[zoomIndexes[tileKey].bucketInstanceId]) { + this.removeBucketCrossTileIDs(z, zoomIndexes[tileKey]); + delete zoomIndexes[tileKey]; + tilesChanged = true; + } + } + } + return tilesChanged; + } +} +class CrossTileSymbolIndex { + constructor() { + this.layerIndexes = {}; + this.crossTileIDs = new CrossTileIDs(); + this.maxBucketInstanceId = 0; + this.bucketsInCurrentPlacement = {}; + } + addLayer(styleLayer, tiles, lng) { + let layerIndex = this.layerIndexes[styleLayer.id]; + if (layerIndex === undefined) { + layerIndex = this.layerIndexes[styleLayer.id] = new CrossTileSymbolLayerIndex(); + } + let symbolBucketsChanged = false; + const currentBucketIDs = {}; + layerIndex.handleWrapJump(lng); + for (const tile of tiles) { + const symbolBucket = tile.getBucket(styleLayer); + if (!symbolBucket || styleLayer.id !== symbolBucket.layerIds[0]) + continue; + if (!symbolBucket.bucketInstanceId) { + symbolBucket.bucketInstanceId = ++this.maxBucketInstanceId; + } + if (layerIndex.addBucket(tile.tileID, symbolBucket, this.crossTileIDs)) { + symbolBucketsChanged = true; + } + currentBucketIDs[symbolBucket.bucketInstanceId] = true; + } + if (layerIndex.removeStaleBuckets(currentBucketIDs)) { + symbolBucketsChanged = true; + } + return symbolBucketsChanged; + } + pruneUnusedLayers(usedLayers) { + const usedLayerMap = {}; + usedLayers.forEach((usedLayer) => { + usedLayerMap[usedLayer] = true; + }); + for (const layerId in this.layerIndexes) { + if (!usedLayerMap[layerId]) { + delete this.layerIndexes[layerId]; + } + } + } +} + +// We're skipping validation errors with the `source.canvas` identifier in order +// to continue to allow canvas sources to be added at runtime/updated in +// smart setStyle (see https://github.com/mapbox/mapbox-gl-js/pull/6424): +const emitValidationErrors = (evented, errors) => emitValidationErrors$1(evented, errors && errors.filter(error => error.identifier !== 'source.canvas')); +const empty = emptyStyle(); +/** + * The Style base class + */ +class Style extends Evented { + constructor(map, options = {}) { + super(); + this._rtlPluginLoaded = () => { + for (const id in this.sourceCaches) { + const sourceType = this.sourceCaches[id].getSource().type; + if (sourceType === 'vector' || sourceType === 'geojson') { + // Non-vector sources don't have any symbols buckets to reload when the RTL text plugin loads + // They also load more quickly, so they're more likely to have already displaying tiles + // that would be unnecessarily booted by the plugin load event + this.sourceCaches[id].reload(); // Should be a no-op if the plugin loads before any tiles load + } + } + }; + this.map = map; + this.dispatcher = new Dispatcher(getGlobalWorkerPool(), map._getMapId()); + this.dispatcher.registerMessageHandler("GG" /* MessageType.getGlyphs */, (mapId, params) => { + return this.getGlyphs(mapId, params); + }); + this.dispatcher.registerMessageHandler("GI" /* MessageType.getImages */, (mapId, params) => { + return this.getImages(mapId, params); + }); + this.imageManager = new ImageManager(); + this.imageManager.setEventedParent(this); + this.glyphManager = new GlyphManager(map._requestManager, options.localIdeographFontFamily); + this.lineAtlas = new LineAtlas(256, 512); + this.crossTileSymbolIndex = new CrossTileSymbolIndex(); + this._spritesImagesIds = {}; + this._layers = {}; + this._order = []; + this.sourceCaches = {}; + this.zoomHistory = new ZoomHistory(); + this._loaded = false; + this._availableImages = []; + this._resetUpdates(); + this.dispatcher.broadcast("SR" /* MessageType.setReferrer */, getReferrer()); + rtlMainThreadPluginFactory().on(RTLPluginLoadedEventName, this._rtlPluginLoaded); + this.on('data', (event) => { + if (event.dataType !== 'source' || event.sourceDataType !== 'metadata') { + return; + } + const sourceCache = this.sourceCaches[event.sourceId]; + if (!sourceCache) { + return; + } + const source = sourceCache.getSource(); + if (!source || !source.vectorLayerIds) { + return; + } + for (const layerId in this._layers) { + const layer = this._layers[layerId]; + if (layer.source === source.id) { + this._validateLayer(layer); + } + } + }); + } + loadURL(url, options = {}, previousStyle) { + this.fire(new Event('dataloading', { dataType: 'style' })); + options.validate = typeof options.validate === 'boolean' ? + options.validate : true; + const request = this.map._requestManager.transformRequest(url, "Style" /* ResourceType.Style */); + this._loadStyleRequest = new AbortController(); + const abortController = this._loadStyleRequest; + getJSON(request, this._loadStyleRequest).then((response) => { + this._loadStyleRequest = null; + this._load(response.data, options, previousStyle); + }).catch((error) => { + this._loadStyleRequest = null; + if (error && !abortController.signal.aborted) { // ignore abort + this.fire(new ErrorEvent(error)); + } + }); + } + loadJSON(json, options = {}, previousStyle) { + this.fire(new Event('dataloading', { dataType: 'style' })); + this._frameRequest = new AbortController(); + browser.frameAsync(this._frameRequest).then(() => { + this._frameRequest = null; + options.validate = options.validate !== false; + this._load(json, options, previousStyle); + }).catch(() => { }); // ignore abort + } + loadEmpty() { + this.fire(new Event('dataloading', { dataType: 'style' })); + this._load(empty, { validate: false }); + } + _load(json, options, previousStyle) { + var _a; + const nextState = options.transformStyle ? options.transformStyle(previousStyle, json) : json; + if (options.validate && emitValidationErrors(this, validateStyle(nextState))) { + return; + } + this._loaded = true; + this.stylesheet = nextState; + for (const id in nextState.sources) { + this.addSource(id, nextState.sources[id], { validate: false }); + } + if (nextState.sprite) { + this._loadSprite(nextState.sprite); + } + else { + this.imageManager.setLoaded(true); + } + this.glyphManager.setURL(nextState.glyphs); + this._createLayers(); + this.light = new Light(this.stylesheet.light); + this.sky = new Sky(this.stylesheet.sky); + this.map.setTerrain((_a = this.stylesheet.terrain) !== null && _a !== void 0 ? _a : null); + this.fire(new Event('data', { dataType: 'style' })); + this.fire(new Event('style.load')); + } + _createLayers() { + const dereferencedLayers = derefLayers(this.stylesheet.layers); + // Broadcast layers to workers first, so that expensive style processing (createStyleLayer) + // can happen in parallel on both main and worker threads. + this.dispatcher.broadcast("SL" /* MessageType.setLayers */, dereferencedLayers); + this._order = dereferencedLayers.map((layer) => layer.id); + this._layers = {}; + // reset serialization field, to be populated only when needed + this._serializedLayers = null; + for (const layer of dereferencedLayers) { + const styledLayer = createStyleLayer(layer); + styledLayer.setEventedParent(this, { layer: { id: layer.id } }); + this._layers[layer.id] = styledLayer; + } + } + _loadSprite(sprite, isUpdate = false, completion = undefined) { + this.imageManager.setLoaded(false); + this._spriteRequest = new AbortController(); + let err; + loadSprite(sprite, this.map._requestManager, this.map.getPixelRatio(), this._spriteRequest).then((images) => { + this._spriteRequest = null; + if (images) { + for (const spriteId in images) { + this._spritesImagesIds[spriteId] = []; + // remove old sprite's loaded images (for the same sprite id) that are not in new sprite + const imagesToRemove = this._spritesImagesIds[spriteId] ? this._spritesImagesIds[spriteId].filter(id => !(id in images)) : []; + for (const id of imagesToRemove) { + this.imageManager.removeImage(id); + this._changedImages[id] = true; + } + for (const id in images[spriteId]) { + // don't prefix images of the "default" sprite + const imageId = spriteId === 'default' ? id : `${spriteId}:${id}`; + // save all the sprite's images' ids to be able to delete them in `removeSprite` + this._spritesImagesIds[spriteId].push(imageId); + if (imageId in this.imageManager.images) { + this.imageManager.updateImage(imageId, images[spriteId][id], false); + } + else { + this.imageManager.addImage(imageId, images[spriteId][id]); + } + if (isUpdate) { + this._changedImages[imageId] = true; + } + } + } + } + }).catch((error) => { + this._spriteRequest = null; + err = error; + this.fire(new ErrorEvent(err)); + }).finally(() => { + this.imageManager.setLoaded(true); + this._availableImages = this.imageManager.listImages(); + if (isUpdate) { + this._changed = true; + } + this.dispatcher.broadcast("SI" /* MessageType.setImages */, this._availableImages); + this.fire(new Event('data', { dataType: 'style' })); + if (completion) { + completion(err); + } + }); + } + _unloadSprite() { + for (const id of Object.values(this._spritesImagesIds).flat()) { + this.imageManager.removeImage(id); + this._changedImages[id] = true; + } + this._spritesImagesIds = {}; + this._availableImages = this.imageManager.listImages(); + this._changed = true; + this.dispatcher.broadcast("SI" /* MessageType.setImages */, this._availableImages); + this.fire(new Event('data', { dataType: 'style' })); + } + _validateLayer(layer) { + const sourceCache = this.sourceCaches[layer.source]; + if (!sourceCache) { + return; + } + const sourceLayer = layer.sourceLayer; + if (!sourceLayer) { + return; + } + const source = sourceCache.getSource(); + if (source.type === 'geojson' || (source.vectorLayerIds && source.vectorLayerIds.indexOf(sourceLayer) === -1)) { + this.fire(new ErrorEvent(new Error(`Source layer "${sourceLayer}" ` + + `does not exist on source "${source.id}" ` + + `as specified by style layer "${layer.id}".`))); + } + } + loaded() { + if (!this._loaded) + return false; + if (Object.keys(this._updatedSources).length) + return false; + for (const id in this.sourceCaches) + if (!this.sourceCaches[id].loaded()) + return false; + if (!this.imageManager.isLoaded()) + return false; + return true; + } + /** + * @hidden + * take an array of string IDs, and based on this._layers, generate an array of LayerSpecification + * @param ids - an array of string IDs, for which serialized layers will be generated. If omitted, all serialized layers will be returned + * @param returnClose - if true, return a clone of the layer object + * @returns generated result + */ + _serializeByIds(ids, returnClone = false) { + const serializedLayersDictionary = this._serializedAllLayers(); + if (!ids || ids.length === 0) { + return returnClone ? Object.values(clone$9(serializedLayersDictionary)) : Object.values(serializedLayersDictionary); + } + const serializedLayers = []; + for (const id of ids) { + // this check will skip all custom layers + if (serializedLayersDictionary[id]) { + const toPush = returnClone ? clone$9(serializedLayersDictionary[id]) : serializedLayersDictionary[id]; + serializedLayers.push(toPush); + } + } + return serializedLayers; + } + /** + * @hidden + * Lazy initialization of this._serializedLayers dictionary and return it + * @returns this._serializedLayers dictionary + */ + _serializedAllLayers() { + let serializedLayers = this._serializedLayers; + if (serializedLayers) { + return serializedLayers; + } + serializedLayers = this._serializedLayers = {}; + const allLayerIds = Object.keys(this._layers); + for (const layerId of allLayerIds) { + const layer = this._layers[layerId]; + if (layer.type !== 'custom') { + serializedLayers[layerId] = layer.serialize(); + } + } + return serializedLayers; + } + hasTransitions() { + if (this.light && this.light.hasTransition()) { + return true; + } + if (this.sky && this.sky.hasTransition()) { + return true; + } + for (const id in this.sourceCaches) { + if (this.sourceCaches[id].hasTransition()) { + return true; + } + } + for (const id in this._layers) { + if (this._layers[id].hasTransition()) { + return true; + } + } + return false; + } + _checkLoaded() { + if (!this._loaded) { + throw new Error('Style is not done loading.'); + } + } + /** + * @internal + * Apply queued style updates in a batch and recalculate zoom-dependent paint properties. + */ + update(parameters) { + if (!this._loaded) { + return; + } + const changed = this._changed; + if (changed) { + const updatedIds = Object.keys(this._updatedLayers); + const removedIds = Object.keys(this._removedLayers); + if (updatedIds.length || removedIds.length) { + this._updateWorkerLayers(updatedIds, removedIds); + } + for (const id in this._updatedSources) { + const action = this._updatedSources[id]; + if (action === 'reload') { + this._reloadSource(id); + } + else if (action === 'clear') { + this._clearSource(id); + } + else { + throw new Error(`Invalid action ${action}`); + } + } + this._updateTilesForChangedImages(); + this._updateTilesForChangedGlyphs(); + for (const id in this._updatedPaintProps) { + this._layers[id].updateTransitions(parameters); + } + this.light.updateTransitions(parameters); + this.sky.updateTransitions(parameters); + this._resetUpdates(); + } + const sourcesUsedBefore = {}; + // save 'used' status to sourcesUsedBefore object and reset all sourceCaches 'used' field to false + for (const sourceCacheId in this.sourceCaches) { + const sourceCache = this.sourceCaches[sourceCacheId]; + // sourceCache.used could be undefined, and sourcesUsedBefore[sourceCacheId] is also 'undefined' + sourcesUsedBefore[sourceCacheId] = sourceCache.used; + sourceCache.used = false; + } + // loop all layers and find layers that are not hidden at parameters.zoom + // and set used to true in sourceCaches dictionary for the sources of these layers + for (const layerId of this._order) { + const layer = this._layers[layerId]; + layer.recalculate(parameters, this._availableImages); + if (!layer.isHidden(parameters.zoom) && layer.source) { + this.sourceCaches[layer.source].used = true; + } + } + // cross check sourcesUsedBefore against updated this.sourceCaches dictionary + // if "used" field is different fire visibility event + for (const sourcesUsedBeforeId in sourcesUsedBefore) { + const sourceCache = this.sourceCaches[sourcesUsedBeforeId]; + // (undefine !== false) will evaluate to true and fire an useless visibility event + // need force "falsy" values to boolean to avoid the case above + if (!!sourcesUsedBefore[sourcesUsedBeforeId] !== !!sourceCache.used) { + sourceCache.fire(new Event('data', { + sourceDataType: 'visibility', + dataType: 'source', + sourceId: sourcesUsedBeforeId + })); + } + } + this.light.recalculate(parameters); + this.sky.recalculate(parameters); + this.z = parameters.zoom; + if (changed) { + this.fire(new Event('data', { dataType: 'style' })); + } + } + /* + * Apply any queued image changes. + */ + _updateTilesForChangedImages() { + const changedImages = Object.keys(this._changedImages); + if (changedImages.length) { + for (const name in this.sourceCaches) { + this.sourceCaches[name].reloadTilesForDependencies(['icons', 'patterns'], changedImages); + } + this._changedImages = {}; + } + } + _updateTilesForChangedGlyphs() { + if (this._glyphsDidChange) { + for (const name in this.sourceCaches) { + this.sourceCaches[name].reloadTilesForDependencies(['glyphs'], ['']); + } + this._glyphsDidChange = false; + } + } + _updateWorkerLayers(updatedIds, removedIds) { + this.dispatcher.broadcast("UL" /* MessageType.updateLayers */, { + layers: this._serializeByIds(updatedIds, false), + removedIds + }); + } + _resetUpdates() { + this._changed = false; + this._updatedLayers = {}; + this._removedLayers = {}; + this._updatedSources = {}; + this._updatedPaintProps = {}; + this._changedImages = {}; + this._glyphsDidChange = false; + } + /** + * Update this style's state to match the given style JSON, performing only + * the necessary mutations. + * + * May throw an Error ('Unimplemented: METHOD') if the mapbox-gl-style-spec + * diff algorithm produces an operation that is not supported. + * + * @returns true if any changes were made; false otherwise + */ + setState(nextState, options = {}) { + var _a; + this._checkLoaded(); + const serializedStyle = this.serialize(); + nextState = options.transformStyle ? options.transformStyle(serializedStyle, nextState) : nextState; + const validate = (_a = options.validate) !== null && _a !== void 0 ? _a : true; + if (validate && emitValidationErrors(this, validateStyle(nextState))) + return false; + nextState = clone$9(nextState); + nextState.layers = derefLayers(nextState.layers); + const changes = diffStyles(serializedStyle, nextState); + const operations = this._getOperationsToPerform(changes); + if (operations.unimplemented.length > 0) { + throw new Error(`Unimplemented: ${operations.unimplemented.join(', ')}.`); + } + if (operations.operations.length === 0) { + return false; + } + for (const styleChangeOperation of operations.operations) { + styleChangeOperation(); + } + this.stylesheet = nextState; + // reset serialization field, to be populated only when needed + this._serializedLayers = null; + return true; + } + _getOperationsToPerform(diff) { + const operations = []; + const unimplemented = []; + for (const op of diff) { + switch (op.command) { + case 'setCenter': + case 'setZoom': + case 'setBearing': + case 'setPitch': + continue; + case 'addLayer': + operations.push(() => this.addLayer.apply(this, op.args)); + break; + case 'removeLayer': + operations.push(() => this.removeLayer.apply(this, op.args)); + break; + case 'setPaintProperty': + operations.push(() => this.setPaintProperty.apply(this, op.args)); + break; + case 'setLayoutProperty': + operations.push(() => this.setLayoutProperty.apply(this, op.args)); + break; + case 'setFilter': + operations.push(() => this.setFilter.apply(this, op.args)); + break; + case 'addSource': + operations.push(() => this.addSource.apply(this, op.args)); + break; + case 'removeSource': + operations.push(() => this.removeSource.apply(this, op.args)); + break; + case 'setLayerZoomRange': + operations.push(() => this.setLayerZoomRange.apply(this, op.args)); + break; + case 'setLight': + operations.push(() => this.setLight.apply(this, op.args)); + break; + case 'setGeoJSONSourceData': + operations.push(() => this.setGeoJSONSourceData.apply(this, op.args)); + break; + case 'setGlyphs': + operations.push(() => this.setGlyphs.apply(this, op.args)); + break; + case 'setSprite': + operations.push(() => this.setSprite.apply(this, op.args)); + break; + case 'setSky': + operations.push(() => this.setSky.apply(this, op.args)); + break; + case 'setTerrain': + operations.push(() => this.map.setTerrain.apply(this, op.args)); + break; + case 'setTransition': + operations.push(() => { }); + break; + default: + unimplemented.push(op.command); + break; + } + } + return { + operations, + unimplemented + }; + } + addImage(id, image) { + if (this.getImage(id)) { + return this.fire(new ErrorEvent(new Error(`An image named "${id}" already exists.`))); + } + this.imageManager.addImage(id, image); + this._afterImageUpdated(id); + } + updateImage(id, image) { + this.imageManager.updateImage(id, image); + } + getImage(id) { + return this.imageManager.getImage(id); + } + removeImage(id) { + if (!this.getImage(id)) { + return this.fire(new ErrorEvent(new Error(`An image named "${id}" does not exist.`))); + } + this.imageManager.removeImage(id); + this._afterImageUpdated(id); + } + _afterImageUpdated(id) { + this._availableImages = this.imageManager.listImages(); + this._changedImages[id] = true; + this._changed = true; + this.dispatcher.broadcast("SI" /* MessageType.setImages */, this._availableImages); + this.fire(new Event('data', { dataType: 'style' })); + } + listImages() { + this._checkLoaded(); + return this.imageManager.listImages(); + } + addSource(id, source, options = {}) { + this._checkLoaded(); + if (this.sourceCaches[id] !== undefined) { + throw new Error(`Source "${id}" already exists.`); + } + if (!source.type) { + throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(source).join(', ')}.`); + } + const builtIns = ['vector', 'raster', 'geojson', 'video', 'image']; + const shouldValidate = builtIns.indexOf(source.type) >= 0; + if (shouldValidate && this._validate(validateStyle.source, `sources.${id}`, source, null, options)) + return; + if (this.map && this.map._collectResourceTiming) + source.collectResourceTiming = true; + const sourceCache = this.sourceCaches[id] = new SourceCache(id, source, this.dispatcher); + sourceCache.style = this; + sourceCache.setEventedParent(this, () => ({ + isSourceLoaded: sourceCache.loaded(), + source: sourceCache.serialize(), + sourceId: id + })); + sourceCache.onAdd(this.map); + this._changed = true; + } + /** + * Remove a source from this stylesheet, given its id. + * @param id - id of the source to remove + * @throws if no source is found with the given ID + */ + removeSource(id) { + this._checkLoaded(); + if (this.sourceCaches[id] === undefined) { + throw new Error('There is no source with this ID'); + } + for (const layerId in this._layers) { + if (this._layers[layerId].source === id) { + return this.fire(new ErrorEvent(new Error(`Source "${id}" cannot be removed while layer "${layerId}" is using it.`))); + } + } + const sourceCache = this.sourceCaches[id]; + delete this.sourceCaches[id]; + delete this._updatedSources[id]; + sourceCache.fire(new Event('data', { sourceDataType: 'metadata', dataType: 'source', sourceId: id })); + sourceCache.setEventedParent(null); + sourceCache.onRemove(this.map); + this._changed = true; + } + /** + * Set the data of a GeoJSON source, given its id. + * @param id - id of the source + * @param data - GeoJSON source + */ + setGeoJSONSourceData(id, data) { + this._checkLoaded(); + if (this.sourceCaches[id] === undefined) + throw new Error(`There is no source with this ID=${id}`); + const geojsonSource = this.sourceCaches[id].getSource(); + if (geojsonSource.type !== 'geojson') + throw new Error(`geojsonSource.type is ${geojsonSource.type}, which is !== 'geojson`); + geojsonSource.setData(data); + this._changed = true; + } + /** + * Get a source by ID. + * @param id - ID of the desired source + * @returns source + */ + getSource(id) { + return this.sourceCaches[id] && this.sourceCaches[id].getSource(); + } + /** + * Add a layer to the map style. The layer will be inserted before the layer with + * ID `before`, or appended if `before` is omitted. + * @param layerObject - The style layer to add. + * @param before - ID of an existing layer to insert before + * @param options - Style setter options. + */ + addLayer(layerObject, before, options = {}) { + this._checkLoaded(); + const id = layerObject.id; + if (this.getLayer(id)) { + this.fire(new ErrorEvent(new Error(`Layer "${id}" already exists on this map.`))); + return; + } + let layer; + if (layerObject.type === 'custom') { + if (emitValidationErrors(this, validateCustomStyleLayer(layerObject))) + return; + layer = createStyleLayer(layerObject); + } + else { + if ('source' in layerObject && typeof layerObject.source === 'object') { + this.addSource(id, layerObject.source); + layerObject = clone$9(layerObject); + layerObject = extend(layerObject, { source: id }); + } + // this layer is not in the style.layers array, so we pass an impossible array index + if (this._validate(validateStyle.layer, `layers.${id}`, layerObject, { arrayIndex: -1 }, options)) + return; + layer = createStyleLayer(layerObject); + this._validateLayer(layer); + layer.setEventedParent(this, { layer: { id } }); + } + const index = before ? this._order.indexOf(before) : this._order.length; + if (before && index === -1) { + this.fire(new ErrorEvent(new Error(`Cannot add layer "${id}" before non-existing layer "${before}".`))); + return; + } + this._order.splice(index, 0, id); + this._layerOrderChanged = true; + this._layers[id] = layer; + if (this._removedLayers[id] && layer.source && layer.type !== 'custom') { + // If, in the current batch, we have already removed this layer + // and we are now re-adding it with a different `type`, then we + // need to clear (rather than just reload) the underlying source's + // tiles. Otherwise, tiles marked 'reloading' will have buckets / + // buffers that are set up for the _previous_ version of this + // layer, causing, e.g.: + // https://github.com/mapbox/mapbox-gl-js/issues/3633 + const removed = this._removedLayers[id]; + delete this._removedLayers[id]; + if (removed.type !== layer.type) { + this._updatedSources[layer.source] = 'clear'; + } + else { + this._updatedSources[layer.source] = 'reload'; + this.sourceCaches[layer.source].pause(); + } + } + this._updateLayer(layer); + if (layer.onAdd) { + layer.onAdd(this.map); + } + } + /** + * Moves a layer to a different z-position. The layer will be inserted before the layer with + * ID `before`, or appended if `before` is omitted. + * @param id - ID of the layer to move + * @param before - ID of an existing layer to insert before + */ + moveLayer(id, before) { + this._checkLoaded(); + this._changed = true; + const layer = this._layers[id]; + if (!layer) { + this.fire(new ErrorEvent(new Error(`The layer '${id}' does not exist in the map's style and cannot be moved.`))); + return; + } + if (id === before) { + return; + } + const index = this._order.indexOf(id); + this._order.splice(index, 1); + const newIndex = before ? this._order.indexOf(before) : this._order.length; + if (before && newIndex === -1) { + this.fire(new ErrorEvent(new Error(`Cannot move layer "${id}" before non-existing layer "${before}".`))); + return; + } + this._order.splice(newIndex, 0, id); + this._layerOrderChanged = true; + } + /** + * Remove the layer with the given id from the style. + * A {@link ErrorEvent} event will be fired if no such layer exists. + * + * @param id - id of the layer to remove + */ + removeLayer(id) { + this._checkLoaded(); + const layer = this._layers[id]; + if (!layer) { + this.fire(new ErrorEvent(new Error(`Cannot remove non-existing layer "${id}".`))); + return; + } + layer.setEventedParent(null); + const index = this._order.indexOf(id); + this._order.splice(index, 1); + this._layerOrderChanged = true; + this._changed = true; + this._removedLayers[id] = layer; + delete this._layers[id]; + if (this._serializedLayers) { + delete this._serializedLayers[id]; + } + delete this._updatedLayers[id]; + delete this._updatedPaintProps[id]; + if (layer.onRemove) { + layer.onRemove(this.map); + } + } + /** + * Return the style layer object with the given `id`. + * + * @param id - id of the desired layer + * @returns a layer, if one with the given `id` exists + */ + getLayer(id) { + return this._layers[id]; + } + /** + * Return the ids of all layers currently in the style, including custom layers, in order. + * + * @returns ids of layers, in order + */ + getLayersOrder() { + return [...this._order]; + } + /** + * Checks if a specific layer is present within the style. + * + * @param id - the id of the desired layer + * @returns a boolean specifying if the given layer is present + */ + hasLayer(id) { + return id in this._layers; + } + setLayerZoomRange(layerId, minzoom, maxzoom) { + this._checkLoaded(); + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new ErrorEvent(new Error(`Cannot set the zoom range of non-existing layer "${layerId}".`))); + return; + } + if (layer.minzoom === minzoom && layer.maxzoom === maxzoom) + return; + if (minzoom != null) { + layer.minzoom = minzoom; + } + if (maxzoom != null) { + layer.maxzoom = maxzoom; + } + this._updateLayer(layer); + } + setFilter(layerId, filter, options = {}) { + this._checkLoaded(); + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new ErrorEvent(new Error(`Cannot filter non-existing layer "${layerId}".`))); + return; + } + if (deepEqual$1(layer.filter, filter)) { + return; + } + if (filter === null || filter === undefined) { + layer.filter = undefined; + this._updateLayer(layer); + return; + } + if (this._validate(validateStyle.filter, `layers.${layer.id}.filter`, filter, null, options)) { + return; + } + layer.filter = clone$9(filter); + this._updateLayer(layer); + } + /** + * Get a layer's filter object + * @param layer - the layer to inspect + * @returns the layer's filter, if any + */ + getFilter(layer) { + return clone$9(this.getLayer(layer).filter); + } + setLayoutProperty(layerId, name, value, options = {}) { + this._checkLoaded(); + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new ErrorEvent(new Error(`Cannot style non-existing layer "${layerId}".`))); + return; + } + if (deepEqual$1(layer.getLayoutProperty(name), value)) + return; + layer.setLayoutProperty(name, value, options); + this._updateLayer(layer); + } + /** + * Get a layout property's value from a given layer + * @param layerId - the layer to inspect + * @param name - the name of the layout property + * @returns the property value + */ + getLayoutProperty(layerId, name) { + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new ErrorEvent(new Error(`Cannot get style of non-existing layer "${layerId}".`))); + return; + } + return layer.getLayoutProperty(name); + } + setPaintProperty(layerId, name, value, options = {}) { + this._checkLoaded(); + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new ErrorEvent(new Error(`Cannot style non-existing layer "${layerId}".`))); + return; + } + if (deepEqual$1(layer.getPaintProperty(name), value)) + return; + const requiresRelayout = layer.setPaintProperty(name, value, options); + if (requiresRelayout) { + this._updateLayer(layer); + } + this._changed = true; + this._updatedPaintProps[layerId] = true; + // reset serialization field, to be populated only when needed + this._serializedLayers = null; + } + getPaintProperty(layer, name) { + return this.getLayer(layer).getPaintProperty(name); + } + setFeatureState(target, state) { + this._checkLoaded(); + const sourceId = target.source; + const sourceLayer = target.sourceLayer; + const sourceCache = this.sourceCaches[sourceId]; + if (sourceCache === undefined) { + this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`))); + return; + } + const sourceType = sourceCache.getSource().type; + if (sourceType === 'geojson' && sourceLayer) { + this.fire(new ErrorEvent(new Error('GeoJSON sources cannot have a sourceLayer parameter.'))); + return; + } + if (sourceType === 'vector' && !sourceLayer) { + this.fire(new ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.'))); + return; + } + if (target.id === undefined) { + this.fire(new ErrorEvent(new Error('The feature id parameter must be provided.'))); + } + sourceCache.setFeatureState(sourceLayer, target.id, state); + } + removeFeatureState(target, key) { + this._checkLoaded(); + const sourceId = target.source; + const sourceCache = this.sourceCaches[sourceId]; + if (sourceCache === undefined) { + this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`))); + return; + } + const sourceType = sourceCache.getSource().type; + const sourceLayer = sourceType === 'vector' ? target.sourceLayer : undefined; + if (sourceType === 'vector' && !sourceLayer) { + this.fire(new ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.'))); + return; + } + if (key && (typeof target.id !== 'string' && typeof target.id !== 'number')) { + this.fire(new ErrorEvent(new Error('A feature id is required to remove its specific state property.'))); + return; + } + sourceCache.removeFeatureState(sourceLayer, target.id, key); + } + getFeatureState(target) { + this._checkLoaded(); + const sourceId = target.source; + const sourceLayer = target.sourceLayer; + const sourceCache = this.sourceCaches[sourceId]; + if (sourceCache === undefined) { + this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`))); + return; + } + const sourceType = sourceCache.getSource().type; + if (sourceType === 'vector' && !sourceLayer) { + this.fire(new ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.'))); + return; + } + if (target.id === undefined) { + this.fire(new ErrorEvent(new Error('The feature id parameter must be provided.'))); + } + return sourceCache.getFeatureState(sourceLayer, target.id); + } + getTransition() { + return extend({ duration: 300, delay: 0 }, this.stylesheet && this.stylesheet.transition); + } + serialize() { + // We return undefined before we're loaded, following the pattern of Map.getStyle() before + // the Style object is initialized. + // Internally, Style._validate() calls Style.serialize() but callers are responsible for + // calling Style._checkLoaded() first if their validation requires the style to be loaded. + if (!this._loaded) + return; + const sources = mapObject(this.sourceCaches, (source) => source.serialize()); + const layers = this._serializeByIds(this._order, true); + const terrain = this.map.getTerrain() || undefined; + const myStyleSheet = this.stylesheet; + return filterObject({ + version: myStyleSheet.version, + name: myStyleSheet.name, + metadata: myStyleSheet.metadata, + light: myStyleSheet.light, + sky: myStyleSheet.sky, + center: myStyleSheet.center, + zoom: myStyleSheet.zoom, + bearing: myStyleSheet.bearing, + pitch: myStyleSheet.pitch, + sprite: myStyleSheet.sprite, + glyphs: myStyleSheet.glyphs, + transition: myStyleSheet.transition, + sources, + layers, + terrain + }, (value) => { return value !== undefined; }); + } + _updateLayer(layer) { + this._updatedLayers[layer.id] = true; + if (layer.source && !this._updatedSources[layer.source] && + //Skip for raster layers (https://github.com/mapbox/mapbox-gl-js/issues/7865) + this.sourceCaches[layer.source].getSource().type !== 'raster') { + this._updatedSources[layer.source] = 'reload'; + this.sourceCaches[layer.source].pause(); + } + // upon updating, serialized layer dictionary should be reset. + // When needed, it will be populated with the correct copy again. + this._serializedLayers = null; + this._changed = true; + } + _flattenAndSortRenderedFeatures(sourceResults) { + // Feature order is complicated. + // The order between features in two 2D layers is always determined by layer order. + // The order between features in two 3D layers is always determined by depth. + // The order between a feature in a 2D layer and a 3D layer is tricky: + // Most often layer order determines the feature order in this case. If + // a line layer is above a extrusion layer the line feature will be rendered + // above the extrusion. If the line layer is below the extrusion layer, + // it will be rendered below it. + // + // There is a weird case though. + // You have layers in this order: extrusion_layer_a, line_layer, extrusion_layer_b + // Each layer has a feature that overlaps the other features. + // The feature in extrusion_layer_a is closer than the feature in extrusion_layer_b so it is rendered above. + // The feature in line_layer is rendered above extrusion_layer_a. + // This means that that the line_layer feature is above the extrusion_layer_b feature despite + // it being in an earlier layer. + const isLayer3D = layerId => this._layers[layerId].type === 'fill-extrusion'; + const layerIndex = {}; + const features3D = []; + for (let l = this._order.length - 1; l >= 0; l--) { + const layerId = this._order[l]; + if (isLayer3D(layerId)) { + layerIndex[layerId] = l; + for (const sourceResult of sourceResults) { + const layerFeatures = sourceResult[layerId]; + if (layerFeatures) { + for (const featureWrapper of layerFeatures) { + features3D.push(featureWrapper); + } + } + } + } + } + features3D.sort((a, b) => { + return b.intersectionZ - a.intersectionZ; + }); + const features = []; + for (let l = this._order.length - 1; l >= 0; l--) { + const layerId = this._order[l]; + if (isLayer3D(layerId)) { + // add all 3D features that are in or above the current layer + for (let i = features3D.length - 1; i >= 0; i--) { + const topmost3D = features3D[i].feature; + if (layerIndex[topmost3D.layer.id] < l) + break; + features.push(topmost3D); + features3D.pop(); + } + } + else { + for (const sourceResult of sourceResults) { + const layerFeatures = sourceResult[layerId]; + if (layerFeatures) { + for (const featureWrapper of layerFeatures) { + features.push(featureWrapper.feature); + } + } + } + } + } + return features; + } + queryRenderedFeatures(queryGeometry, params, transform) { + if (params && params.filter) { + this._validate(validateStyle.filter, 'queryRenderedFeatures.filter', params.filter, null, params); + } + const includedSources = {}; + if (params && params.layers) { + if (!Array.isArray(params.layers)) { + this.fire(new ErrorEvent(new Error('parameters.layers must be an Array.'))); + return []; + } + for (const layerId of params.layers) { + const layer = this._layers[layerId]; + if (!layer) { + // this layer is not in the style.layers array + this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be queried for features.`))); + return []; + } + includedSources[layer.source] = true; + } + } + const sourceResults = []; + params.availableImages = this._availableImages; + // LayerSpecification is serialized StyleLayer, and this casting is safe. + const serializedLayers = this._serializedAllLayers(); + for (const id in this.sourceCaches) { + if (params.layers && !includedSources[id]) + continue; + sourceResults.push(queryRenderedFeatures(this.sourceCaches[id], this._layers, serializedLayers, queryGeometry, params, transform)); + } + if (this.placement) { + // If a placement has run, query against its CollisionIndex + // for symbol results, and treat it as an extra source to merge + sourceResults.push(queryRenderedSymbols(this._layers, serializedLayers, this.sourceCaches, queryGeometry, params, this.placement.collisionIndex, this.placement.retainedQueryData)); + } + return this._flattenAndSortRenderedFeatures(sourceResults); + } + querySourceFeatures(sourceID, params) { + if (params && params.filter) { + this._validate(validateStyle.filter, 'querySourceFeatures.filter', params.filter, null, params); + } + const sourceCache = this.sourceCaches[sourceID]; + return sourceCache ? querySourceFeatures(sourceCache, params) : []; + } + getLight() { + return this.light.getLight(); + } + setLight(lightOptions, options = {}) { + this._checkLoaded(); + const light = this.light.getLight(); + let _update = false; + for (const key in lightOptions) { + if (!deepEqual$1(lightOptions[key], light[key])) { + _update = true; + break; + } + } + if (!_update) + return; + const parameters = { + now: browser.now(), + transition: extend({ + duration: 300, + delay: 0 + }, this.stylesheet.transition) + }; + this.light.setLight(lightOptions, options); + this.light.updateTransitions(parameters); + } + getSky() { + var _a; + return (_a = this.stylesheet) === null || _a === void 0 ? void 0 : _a.sky; + } + setSky(skyOptions, options = {}) { + const sky = this.getSky(); + let update = false; + if (!skyOptions && !sky) + return; + if (skyOptions && !sky) { + update = true; + } + else if (!skyOptions && sky) { + update = true; + } + else { + for (const key in skyOptions) { + if (!deepEqual$1(skyOptions[key], sky[key])) { + update = true; + break; + } + } + } + if (!update) + return; + const parameters = { + now: browser.now(), + transition: extend({ + duration: 300, + delay: 0 + }, this.stylesheet.transition) + }; + this.stylesheet.sky = skyOptions; + this.sky.setSky(skyOptions, options); + this.sky.updateTransitions(parameters); + } + _validate(validate, key, value, props, options = {}) { + if (options && options.validate === false) { + return false; + } + return emitValidationErrors(this, validate.call(validateStyle, extend({ + key, + style: this.serialize(), + value, + styleSpec: v8Spec + }, props))); + } + _remove(mapRemoved = true) { + if (this._frameRequest) { + this._frameRequest.abort(); + this._frameRequest = null; + } + if (this._loadStyleRequest) { + this._loadStyleRequest.abort(); + this._loadStyleRequest = null; + } + if (this._spriteRequest) { + this._spriteRequest.abort(); + this._spriteRequest = null; + } + rtlMainThreadPluginFactory().off(RTLPluginLoadedEventName, this._rtlPluginLoaded); + for (const layerId in this._layers) { + const layer = this._layers[layerId]; + layer.setEventedParent(null); + } + for (const id in this.sourceCaches) { + const sourceCache = this.sourceCaches[id]; + sourceCache.setEventedParent(null); + sourceCache.onRemove(this.map); + } + this.imageManager.setEventedParent(null); + this.setEventedParent(null); + if (mapRemoved) { + this.dispatcher.broadcast("RM" /* MessageType.removeMap */, undefined); + } + this.dispatcher.remove(mapRemoved); + } + _clearSource(id) { + this.sourceCaches[id].clearTiles(); + } + _reloadSource(id) { + this.sourceCaches[id].resume(); + this.sourceCaches[id].reload(); + } + _updateSources(transform) { + for (const id in this.sourceCaches) { + this.sourceCaches[id].update(transform, this.map.terrain); + } + } + _generateCollisionBoxes() { + for (const id in this.sourceCaches) { + this._reloadSource(id); + } + } + _updatePlacement(transform, showCollisionBoxes, fadeDuration, crossSourceCollisions, forceFullPlacement = false) { + let symbolBucketsChanged = false; + let placementCommitted = false; + const layerTiles = {}; + for (const layerID of this._order) { + const styleLayer = this._layers[layerID]; + if (styleLayer.type !== 'symbol') + continue; + if (!layerTiles[styleLayer.source]) { + const sourceCache = this.sourceCaches[styleLayer.source]; + layerTiles[styleLayer.source] = sourceCache.getRenderableIds(true) + .map((id) => sourceCache.getTileByID(id)) + .sort((a, b) => (b.tileID.overscaledZ - a.tileID.overscaledZ) || (a.tileID.isLessThan(b.tileID) ? -1 : 1)); + } + const layerBucketsChanged = this.crossTileSymbolIndex.addLayer(styleLayer, layerTiles[styleLayer.source], transform.center.lng); + symbolBucketsChanged = symbolBucketsChanged || layerBucketsChanged; + } + this.crossTileSymbolIndex.pruneUnusedLayers(this._order); + // Anything that changes our "in progress" layer and tile indices requires us + // to start over. When we start over, we do a full placement instead of incremental + // to prevent starvation. + // We need to restart placement to keep layer indices in sync. + // Also force full placement when fadeDuration === 0 to ensure that newly loaded + // tiles will fully display symbols in their first frame + forceFullPlacement = forceFullPlacement || this._layerOrderChanged || fadeDuration === 0; + if (forceFullPlacement || !this.pauseablePlacement || (this.pauseablePlacement.isDone() && !this.placement.stillRecent(browser.now(), transform.zoom))) { + this.pauseablePlacement = new PauseablePlacement(transform, this.map.terrain, this._order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, this.placement); + this._layerOrderChanged = false; + } + if (this.pauseablePlacement.isDone()) { + // the last placement finished running, but the next one hasn’t + // started yet because of the `stillRecent` check immediately + // above, so mark it stale to ensure that we request another + // render frame + this.placement.setStale(); + } + else { + this.pauseablePlacement.continuePlacement(this._order, this._layers, layerTiles); + if (this.pauseablePlacement.isDone()) { + this.placement = this.pauseablePlacement.commit(browser.now()); + placementCommitted = true; + } + if (symbolBucketsChanged) { + // since the placement gets split over multiple frames it is possible + // these buckets were processed before they were changed and so the + // placement is already stale while it is in progress + this.pauseablePlacement.placement.setStale(); + } + } + if (placementCommitted || symbolBucketsChanged) { + for (const layerID of this._order) { + const styleLayer = this._layers[layerID]; + if (styleLayer.type !== 'symbol') + continue; + this.placement.updateLayerOpacities(styleLayer, layerTiles[styleLayer.source]); + } + } + // needsRender is false when we have just finished a placement that didn't change the visibility of any symbols + const needsRerender = !this.pauseablePlacement.isDone() || this.placement.hasTransitions(browser.now()); + return needsRerender; + } + _releaseSymbolFadeTiles() { + for (const id in this.sourceCaches) { + this.sourceCaches[id].releaseSymbolFadeTiles(); + } + } + // Callbacks from web workers + getImages(mapId, params) { + return __awaiter(this, void 0, void 0, function* () { + const images = yield this.imageManager.getImages(params.icons); + // Apply queued image changes before setting the tile's dependencies so that the tile + // is not reloaded unnecessarily. Without this forced update the reload could happen in cases + // like this one: + // - icons contains "my-image" + // - imageManager.getImages(...) triggers `onstyleimagemissing` + // - the user adds "my-image" within the callback + // - addImage adds "my-image" to this._changedImages + // - the next frame triggers a reload of this tile even though it already has the latest version + this._updateTilesForChangedImages(); + const sourceCache = this.sourceCaches[params.source]; + if (sourceCache) { + sourceCache.setDependencies(params.tileID.key, params.type, params.icons); + } + return images; + }); + } + getGlyphs(mapId, params) { + return __awaiter(this, void 0, void 0, function* () { + const glypgs = yield this.glyphManager.getGlyphs(params.stacks); + const sourceCache = this.sourceCaches[params.source]; + if (sourceCache) { + // we are not setting stacks as dependencies since for now + // we just need to know which tiles have glyph dependencies + sourceCache.setDependencies(params.tileID.key, params.type, ['']); + } + return glypgs; + }); + } + getGlyphsUrl() { + return this.stylesheet.glyphs || null; + } + setGlyphs(glyphsUrl, options = {}) { + this._checkLoaded(); + if (glyphsUrl && this._validate(validateStyle.glyphs, 'glyphs', glyphsUrl, null, options)) { + return; + } + this._glyphsDidChange = true; + this.stylesheet.glyphs = glyphsUrl; + this.glyphManager.entries = {}; + this.glyphManager.setURL(glyphsUrl); + } + /** + * Add a sprite. + * + * @param id - The id of the desired sprite + * @param url - The url to load the desired sprite from + * @param options - The style setter options + * @param completion - The completion handler + */ + addSprite(id, url, options = {}, completion) { + this._checkLoaded(); + const spriteToAdd = [{ id, url }]; + const updatedSprite = [ + ...coerceSpriteToArray(this.stylesheet.sprite), + ...spriteToAdd + ]; + if (this._validate(validateStyle.sprite, 'sprite', updatedSprite, null, options)) + return; + this.stylesheet.sprite = updatedSprite; + this._loadSprite(spriteToAdd, true, completion); + } + /** + * Remove a sprite by its id. When the last sprite is removed, the whole `this.stylesheet.sprite` object becomes + * `undefined`. This falsy `undefined` value later prevents attempts to load the sprite when it's absent. + * + * @param id - the id of the sprite to remove + */ + removeSprite(id) { + this._checkLoaded(); + const internalSpriteRepresentation = coerceSpriteToArray(this.stylesheet.sprite); + if (!internalSpriteRepresentation.find(sprite => sprite.id === id)) { + this.fire(new ErrorEvent(new Error(`Sprite "${id}" doesn't exists on this map.`))); + return; + } + if (this._spritesImagesIds[id]) { + for (const imageId of this._spritesImagesIds[id]) { + this.imageManager.removeImage(imageId); + this._changedImages[imageId] = true; + } + } + internalSpriteRepresentation.splice(internalSpriteRepresentation.findIndex(sprite => sprite.id === id), 1); + this.stylesheet.sprite = internalSpriteRepresentation.length > 0 ? internalSpriteRepresentation : undefined; + delete this._spritesImagesIds[id]; + this._availableImages = this.imageManager.listImages(); + this._changed = true; + this.dispatcher.broadcast("SI" /* MessageType.setImages */, this._availableImages); + this.fire(new Event('data', { dataType: 'style' })); + } + /** + * Get the current sprite value. + * + * @returns empty array when no sprite is set; id-url pairs otherwise + */ + getSprite() { + return coerceSpriteToArray(this.stylesheet.sprite); + } + /** + * Set a new value for the style's sprite. + * + * @param sprite - new sprite value + * @param options - style setter options + * @param completion - the completion handler + */ + setSprite(sprite, options = {}, completion) { + this._checkLoaded(); + if (sprite && this._validate(validateStyle.sprite, 'sprite', sprite, null, options)) { + return; + } + this.stylesheet.sprite = sprite; + if (sprite) { + this._loadSprite(sprite, true, completion); + } + else { + this._unloadSprite(); + if (completion) { + completion(null); + } + } + } +} + +var posAttributes = createLayout([ + { name: 'a_pos', type: 'Int16', components: 2 } +]); + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var preludeFrag = '#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\n'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var preludeVert = '#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture2D(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture2D(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var backgroundFrag = 'uniform vec4 u_color;uniform float u_opacity;void main() {gl_FragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var backgroundVert = 'attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var backgroundPatternFrag = 'uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var backgroundPatternVert = 'uniform mat4 u_matrix;uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var circleFrag = 'varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);lowp float antialiasblur=v_data.z;float antialiased_blur=-max(blur,antialiasblur);float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));gl_FragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var circleVert = 'uniform mat4 u_matrix;uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);float ele=get_elevation(circle_center);v_visibility=calculate_visibility(u_matrix*vec4(circle_center,ele,1.0));if (u_pitch_with_map) {vec2 corner_position=circle_center;if (u_scale_with_map) {corner_position+=extrude*(radius+stroke_width)*u_extrude_scale;} else {vec4 projected_center=u_matrix*vec4(circle_center,0,1);corner_position+=extrude*(radius+stroke_width)*u_extrude_scale*(projected_center.w/u_camera_to_center_distance);}gl_Position=u_matrix*vec4(corner_position,ele,1);} else {gl_Position=u_matrix*vec4(circle_center,ele,1);if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var clippingMaskFrag = 'void main() {gl_FragColor=vec4(1.0);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var clippingMaskVert = 'attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var heatmapFrag = 'uniform highp float u_intensity;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);gl_FragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var heatmapVert = 'uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec4 pos=vec4(floor(a_pos*0.5)+extrude,get_elevation(floor(a_pos*0.5)),1);gl_Position=u_matrix*pos;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var heatmapTextureFrag = 'uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(0.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var heatmapTextureVert = 'uniform mat4 u_matrix;uniform vec2 u_world;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var collisionBoxFrag = 'varying float v_placed;varying float v_notUsed;void main() {float alpha=0.5;gl_FragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var collisionBoxVert = 'attribute vec2 a_anchor_pos;attribute vec2 a_placed;attribute vec2 a_box_real;uniform mat4 u_matrix;uniform vec2 u_pixel_extrude_scale;varying float v_placed;varying float v_notUsed;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var collisionCircleFrag = 'varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var collisionCircleVert = 'attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var debugFrag = 'uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var debugVert = 'attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,get_elevation(a_pos),1);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillFrag = '#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillVert = 'attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillOutlineFrag = 'varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillOutlineVert = 'attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillOutlinePatternFrag = 'uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillOutlinePatternVert = 'uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillPatternFrag = '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillPatternVert = 'uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillExtrusionFrag = 'varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillExtrusionVert = 'uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillExtrusionPatternFrag = 'uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillExtrusionPatternVert = 'uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var hillshadePrepareFrag = '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var hillshadePrepareVert = 'uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var hillshadeFrag = 'uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var hillshadeVert = 'uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineFrag = 'uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineVert = '\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineGradientFrag = 'uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,v_uv);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineGradientVert = '\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;attribute float a_uv_x;attribute float a_split_index;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var linePatternFrag = '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var linePatternVert = '\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineSDFFrag = 'uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineSDFVert = '\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var rasterFrag = 'uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var rasterVert = 'uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolIconFrag = 'uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolIconVert = 'attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_tex;varying float v_fade_opacity;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolSDFFrag = '#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_2;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nfloat median(vec3 values) {return max(min(values.r,values.g),min(max(values.r,values.g),values.b));}float screenPxRange(float fontScale) {return fontScale*SDF_PX;}vec4 renderText(vec4 fill_color,vec4 halo_color,float opacity,float halo_width,float halo_blur,float EDGE_GAMMA,vec2 tex,float gamma_scale,float size,float fade_opacity) {float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}return color*(alpha*opacity*fade_opacity);}vec4 renderMSDFIcon(vec4 fill_color,vec4 halo_color,float opacity,float EDGE_GAMMA,vec2 tex,float gamma_scale,float size,float fade_opacity) {float fontScale=size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;vec3 s=texture2D(u_texture,tex).rgb;float sd=median(s);float dist=sd-0.5;if (u_is_halo) {color=halo_color;s=texture2D(u_texture_2,tex).rgb;sd=median(s);dist=sd-0.5;}float clampedDistance=clamp(dist*screenPxRange(fontScale)+0.5,0.0,1.0);highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,clampedDistance);return color*(alpha*opacity*fade_opacity);}void main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];gl_FragColor=u_is_text ? renderText(fill_color,halo_color,opacity,halo_width,halo_blur,EDGE_GAMMA,tex,gamma_scale,size,fade_opacity) : renderMSDFIcon(fill_color,halo_color,opacity,EDGE_GAMMA,tex,gamma_scale,size,fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolSDFVert = 'attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_data0;varying vec3 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolTextAndIconFrag = '#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolTextAndIconVert = 'attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec4 v_data0;varying vec4 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainDepthFrag = 'varying float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {gl_FragColor=pack(v_depth);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainCoordsFrag = 'precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;varying vec2 v_texture_pos;void main() {vec4 rgba=texture2D(u_texture,v_texture_pos);gl_FragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainFrag = 'uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;varying vec2 v_texture_pos;varying float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture2D(u_texture,v_texture_pos);if (v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);gl_FragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {gl_FragColor=surface_color;}}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainDepthVert = 'attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);v_depth=gl_Position.z/gl_Position.w;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainCoordsVert = 'attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainVert = 'attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform mat4 u_fog_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;varying float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var skyFrag = 'uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform float u_horizon;uniform float u_sky_horizon_blend;void main() {float y=gl_FragCoord.y;if (y > u_horizon) {float blend=y-u_horizon;if (blend < u_sky_horizon_blend) {gl_FragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {gl_FragColor=u_sky_color;}}}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var skyVert = 'attribute vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}'; + +// Disable Flow annotations here because Flow doesn't support importing GLSL files +const shaders = { + prelude: compile(preludeFrag, preludeVert), + background: compile(backgroundFrag, backgroundVert), + backgroundPattern: compile(backgroundPatternFrag, backgroundPatternVert), + circle: compile(circleFrag, circleVert), + clippingMask: compile(clippingMaskFrag, clippingMaskVert), + heatmap: compile(heatmapFrag, heatmapVert), + heatmapTexture: compile(heatmapTextureFrag, heatmapTextureVert), + collisionBox: compile(collisionBoxFrag, collisionBoxVert), + collisionCircle: compile(collisionCircleFrag, collisionCircleVert), + debug: compile(debugFrag, debugVert), + fill: compile(fillFrag, fillVert), + fillOutline: compile(fillOutlineFrag, fillOutlineVert), + fillOutlinePattern: compile(fillOutlinePatternFrag, fillOutlinePatternVert), + fillPattern: compile(fillPatternFrag, fillPatternVert), + fillExtrusion: compile(fillExtrusionFrag, fillExtrusionVert), + fillExtrusionPattern: compile(fillExtrusionPatternFrag, fillExtrusionPatternVert), + hillshadePrepare: compile(hillshadePrepareFrag, hillshadePrepareVert), + hillshade: compile(hillshadeFrag, hillshadeVert), + line: compile(lineFrag, lineVert), + lineGradient: compile(lineGradientFrag, lineGradientVert), + linePattern: compile(linePatternFrag, linePatternVert), + lineSDF: compile(lineSDFFrag, lineSDFVert), + raster: compile(rasterFrag, rasterVert), + symbolIcon: compile(symbolIconFrag, symbolIconVert), + symbolSDF: compile(symbolSDFFrag, symbolSDFVert), + symbolTextAndIcon: compile(symbolTextAndIconFrag, symbolTextAndIconVert), + terrain: compile(terrainFrag, terrainVert), + terrainDepth: compile(terrainDepthFrag, terrainDepthVert), + terrainCoords: compile(terrainCoordsFrag, terrainCoordsVert), + sky: compile(skyFrag, skyVert) +}; +// Expand #pragmas to #ifdefs. +function compile(fragmentSource, vertexSource) { + const re = /#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g; + const staticAttributes = vertexSource.match(/attribute ([\w]+) ([\w]+)/g); + const fragmentUniforms = fragmentSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g); + const vertexUniforms = vertexSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g); + const staticUniforms = vertexUniforms ? vertexUniforms.concat(fragmentUniforms) : fragmentUniforms; + const fragmentPragmas = {}; + fragmentSource = fragmentSource.replace(re, (match, operation, precision, type, name) => { + fragmentPragmas[name] = true; + if (operation === 'define') { + return ` +#ifndef HAS_UNIFORM_u_${name} +varying ${precision} ${type} ${name}; +#else +uniform ${precision} ${type} u_${name}; +#endif +`; + } + else /* if (operation === 'initialize') */ { + return ` +#ifdef HAS_UNIFORM_u_${name} + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + }); + vertexSource = vertexSource.replace(re, (match, operation, precision, type, name) => { + const attrType = type === 'float' ? 'vec2' : 'vec4'; + const unpackType = name.match(/color/) ? 'color' : attrType; + if (fragmentPragmas[name]) { + if (operation === 'define') { + return ` +#ifndef HAS_UNIFORM_u_${name} +uniform lowp float u_${name}_t; +attribute ${precision} ${attrType} a_${name}; +varying ${precision} ${type} ${name}; +#else +uniform ${precision} ${type} u_${name}; +#endif +`; + } + else /* if (operation === 'initialize') */ { + if (unpackType === 'vec4') { + // vec4 attributes are only used for cross-faded properties, and are not packed + return ` +#ifndef HAS_UNIFORM_u_${name} + ${name} = a_${name}; +#else + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + else { + return ` +#ifndef HAS_UNIFORM_u_${name} + ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t); +#else + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + } + } + else { + if (operation === 'define') { + return ` +#ifndef HAS_UNIFORM_u_${name} +uniform lowp float u_${name}_t; +attribute ${precision} ${attrType} a_${name}; +#else +uniform ${precision} ${type} u_${name}; +#endif +`; + } + else /* if (operation === 'initialize') */ { + if (unpackType === 'vec4') { + // vec4 attributes are only used for cross-faded properties, and are not packed + return ` +#ifndef HAS_UNIFORM_u_${name} + ${precision} ${type} ${name} = a_${name}; +#else + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + else /* */ { + return ` +#ifndef HAS_UNIFORM_u_${name} + ${precision} ${type} ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t); +#else + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + } + } + }); + return { fragmentSource, vertexSource, staticAttributes, staticUniforms }; +} + +/** + * @internal + * A vertex array object used to pass data to the webgl code + */ +class VertexArrayObject { + constructor() { + this.boundProgram = null; + this.boundLayoutVertexBuffer = null; + this.boundPaintVertexBuffers = []; + this.boundIndexBuffer = null; + this.boundVertexOffset = null; + this.boundDynamicVertexBuffer = null; + this.vao = null; + } + bind(context, program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3) { + this.context = context; + let paintBuffersDiffer = this.boundPaintVertexBuffers.length !== paintVertexBuffers.length; + for (let i = 0; !paintBuffersDiffer && i < paintVertexBuffers.length; i++) { + if (this.boundPaintVertexBuffers[i] !== paintVertexBuffers[i]) { + paintBuffersDiffer = true; + } + } + const isFreshBindRequired = (!this.vao || + this.boundProgram !== program || + this.boundLayoutVertexBuffer !== layoutVertexBuffer || + paintBuffersDiffer || + this.boundIndexBuffer !== indexBuffer || + this.boundVertexOffset !== vertexOffset || + this.boundDynamicVertexBuffer !== dynamicVertexBuffer || + this.boundDynamicVertexBuffer2 !== dynamicVertexBuffer2 || + this.boundDynamicVertexBuffer3 !== dynamicVertexBuffer3); + if (isFreshBindRequired) { + this.freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3); + } + else { + context.bindVertexArray.set(this.vao); + if (dynamicVertexBuffer) { + // The buffer may have been updated. Rebind to upload data. + dynamicVertexBuffer.bind(); + } + if (indexBuffer && indexBuffer.dynamicDraw) { + indexBuffer.bind(); + } + if (dynamicVertexBuffer2) { + dynamicVertexBuffer2.bind(); + } + if (dynamicVertexBuffer3) { + dynamicVertexBuffer3.bind(); + } + } + } + freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3) { + const numNextAttributes = program.numAttributes; + const context = this.context; + const gl = context.gl; + if (this.vao) + this.destroy(); + this.vao = context.createVertexArray(); + context.bindVertexArray.set(this.vao); + // store the arguments so that we can verify them when the vao is bound again + this.boundProgram = program; + this.boundLayoutVertexBuffer = layoutVertexBuffer; + this.boundPaintVertexBuffers = paintVertexBuffers; + this.boundIndexBuffer = indexBuffer; + this.boundVertexOffset = vertexOffset; + this.boundDynamicVertexBuffer = dynamicVertexBuffer; + this.boundDynamicVertexBuffer2 = dynamicVertexBuffer2; + this.boundDynamicVertexBuffer3 = dynamicVertexBuffer3; + layoutVertexBuffer.enableAttributes(gl, program); + for (const vertexBuffer of paintVertexBuffers) { + vertexBuffer.enableAttributes(gl, program); + } + if (dynamicVertexBuffer) { + dynamicVertexBuffer.enableAttributes(gl, program); + } + if (dynamicVertexBuffer2) { + dynamicVertexBuffer2.enableAttributes(gl, program); + } + if (dynamicVertexBuffer3) { + dynamicVertexBuffer3.enableAttributes(gl, program); + } + layoutVertexBuffer.bind(); + layoutVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset); + for (const vertexBuffer of paintVertexBuffers) { + vertexBuffer.bind(); + vertexBuffer.setVertexAttribPointers(gl, program, vertexOffset); + } + if (dynamicVertexBuffer) { + dynamicVertexBuffer.bind(); + dynamicVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset); + } + if (indexBuffer) { + indexBuffer.bind(); + } + if (dynamicVertexBuffer2) { + dynamicVertexBuffer2.bind(); + dynamicVertexBuffer2.setVertexAttribPointers(gl, program, vertexOffset); + } + if (dynamicVertexBuffer3) { + dynamicVertexBuffer3.bind(); + dynamicVertexBuffer3.setVertexAttribPointers(gl, program, vertexOffset); + } + context.currentNumAttributes = numNextAttributes; + } + destroy() { + if (this.vao) { + this.context.deleteVertexArray(this.vao); + this.vao = null; + } + } +} + +const terrainPreludeUniforms = (context, locations) => ({ + 'u_depth': new Uniform1i(context, locations.u_depth), + 'u_terrain': new Uniform1i(context, locations.u_terrain), + 'u_terrain_dim': new Uniform1f(context, locations.u_terrain_dim), + 'u_terrain_matrix': new UniformMatrix4f(context, locations.u_terrain_matrix), + 'u_terrain_unpack': new Uniform4f(context, locations.u_terrain_unpack), + 'u_terrain_exaggeration': new Uniform1f(context, locations.u_terrain_exaggeration) +}); +const terrainUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_texture': new Uniform1i(context, locations.u_texture), + 'u_ele_delta': new Uniform1f(context, locations.u_ele_delta), + 'u_fog_matrix': new UniformMatrix4f(context, locations.u_fog_matrix), + 'u_fog_color': new UniformColor(context, locations.u_fog_color), + 'u_fog_ground_blend': new Uniform1f(context, locations.u_fog_ground_blend), + 'u_fog_ground_blend_opacity': new Uniform1f(context, locations.u_fog_ground_blend_opacity), + 'u_horizon_color': new UniformColor(context, locations.u_horizon_color), + 'u_horizon_fog_blend': new Uniform1f(context, locations.u_horizon_fog_blend) +}); +const terrainDepthUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_ele_delta': new Uniform1f(context, locations.u_ele_delta) +}); +const terrainCoordsUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_texture': new Uniform1i(context, locations.u_texture), + 'u_terrain_coords_id': new Uniform1f(context, locations.u_terrain_coords_id), + 'u_ele_delta': new Uniform1f(context, locations.u_ele_delta) +}); +const terrainUniformValues = (matrix, eleDelta, fogMatrix, sky, pitch) => ({ + 'u_matrix': matrix, + 'u_texture': 0, + 'u_ele_delta': eleDelta, + 'u_fog_matrix': fogMatrix, + 'u_fog_color': sky ? sky.properties.get('fog-color') : Color.white, + 'u_fog_ground_blend': sky ? sky.properties.get('fog-ground-blend') : 1, + 'u_fog_ground_blend_opacity': sky ? sky.calculateFogBlendOpacity(pitch) : 0, + 'u_horizon_color': sky ? sky.properties.get('horizon-color') : Color.white, + 'u_horizon_fog_blend': sky ? sky.properties.get('horizon-fog-blend') : 1 +}); +const terrainDepthUniformValues = (matrix, eleDelta) => ({ + 'u_matrix': matrix, + 'u_ele_delta': eleDelta +}); +const terrainCoordsUniformValues = (matrix, coordsId, eleDelta) => ({ + 'u_matrix': matrix, + 'u_terrain_coords_id': coordsId / 255, + 'u_texture': 0, + 'u_ele_delta': eleDelta +}); + +function getTokenizedAttributesAndUniforms(array) { + const result = []; + for (let i = 0; i < array.length; i++) { + if (array[i] === null) + continue; + const token = array[i].split(' '); + result.push(token.pop()); + } + return result; +} +/** + * @internal + * A webgl program to execute in the GPU space + */ +class Program { + constructor(context, source, configuration, fixedUniforms, showOverdrawInspector, terrain) { + const gl = context.gl; + this.program = gl.createProgram(); + const staticAttrInfo = getTokenizedAttributesAndUniforms(source.staticAttributes); + const dynamicAttrInfo = configuration ? configuration.getBinderAttributes() : []; + const allAttrInfo = staticAttrInfo.concat(dynamicAttrInfo); + const preludeUniformsInfo = shaders.prelude.staticUniforms ? getTokenizedAttributesAndUniforms(shaders.prelude.staticUniforms) : []; + const staticUniformsInfo = source.staticUniforms ? getTokenizedAttributesAndUniforms(source.staticUniforms) : []; + const dynamicUniformsInfo = configuration ? configuration.getBinderUniforms() : []; + // remove duplicate uniforms + const uniformList = preludeUniformsInfo.concat(staticUniformsInfo).concat(dynamicUniformsInfo); + const allUniformsInfo = []; + for (const uniform of uniformList) { + if (allUniformsInfo.indexOf(uniform) < 0) + allUniformsInfo.push(uniform); + } + const defines = configuration ? configuration.defines() : []; + if (showOverdrawInspector) { + defines.push('#define OVERDRAW_INSPECTOR;'); + } + if (terrain) { + defines.push('#define TERRAIN3D;'); + } + const fragmentSource = defines.concat(shaders.prelude.fragmentSource, source.fragmentSource).join('\n'); + const vertexSource = defines.concat(shaders.prelude.vertexSource, source.vertexSource).join('\n'); + const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); + if (gl.isContextLost()) { + this.failedToCreate = true; + return; + } + gl.shaderSource(fragmentShader, fragmentSource); + gl.compileShader(fragmentShader); + if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) { + console.log(gl.getShaderInfoLog(fragmentShader)); + throw new Error(`Could not compile fragment shader:`); + } + gl.attachShader(this.program, fragmentShader); + const vertexShader = gl.createShader(gl.VERTEX_SHADER); + if (gl.isContextLost()) { + this.failedToCreate = true; + return; + } + gl.shaderSource(vertexShader, vertexSource); + gl.compileShader(vertexShader); + if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) { + throw new Error(`Could not compile vertex shader: ${gl.getShaderInfoLog(vertexShader)}`); + } + gl.attachShader(this.program, vertexShader); + this.attributes = {}; + const uniformLocations = {}; + this.numAttributes = allAttrInfo.length; + for (let i = 0; i < this.numAttributes; i++) { + if (allAttrInfo[i]) { + gl.bindAttribLocation(this.program, i, allAttrInfo[i]); + this.attributes[allAttrInfo[i]] = i; + } + } + gl.linkProgram(this.program); + if (!gl.getProgramParameter(this.program, gl.LINK_STATUS)) { + console.log(gl.getProgramInfoLog(this.program)); + throw new Error(`Program failed to link:`); + } + gl.deleteShader(vertexShader); + gl.deleteShader(fragmentShader); + for (let it = 0; it < allUniformsInfo.length; it++) { + const uniform = allUniformsInfo[it]; + if (uniform && !uniformLocations[uniform]) { + const uniformLocation = gl.getUniformLocation(this.program, uniform); + if (uniformLocation) { + uniformLocations[uniform] = uniformLocation; + } + } + } + this.fixedUniforms = fixedUniforms(context, uniformLocations); + this.terrainUniforms = terrainPreludeUniforms(context, uniformLocations); + this.binderUniforms = configuration ? configuration.getUniforms(context, uniformLocations) : []; + } + draw(context, drawMode, depthMode, stencilMode, colorMode, cullFaceMode, uniformValues, terrain, layerID, layoutVertexBuffer, indexBuffer, segments, currentProperties, zoom, configuration, dynamicLayoutBuffer, dynamicLayoutBuffer2, dynamicLayoutBuffer3) { + const gl = context.gl; + if (this.failedToCreate) + return; + context.program.set(this.program); + context.setDepthMode(depthMode); + context.setStencilMode(stencilMode); + context.setColorMode(colorMode); + context.setCullFace(cullFaceMode); + // set variables used by the 3d functions defined in _prelude.vertex.glsl + if (terrain) { + context.activeTexture.set(gl.TEXTURE2); + gl.bindTexture(gl.TEXTURE_2D, terrain.depthTexture); + context.activeTexture.set(gl.TEXTURE3); + gl.bindTexture(gl.TEXTURE_2D, terrain.texture); + for (const name in this.terrainUniforms) { + this.terrainUniforms[name].set(terrain[name]); + } + } + for (const name in this.fixedUniforms) { + this.fixedUniforms[name].set(uniformValues[name]); + } + if (configuration) { + configuration.setUniforms(context, this.binderUniforms, currentProperties, { zoom: zoom }); + } + let primitiveSize = 0; + switch (drawMode) { + case gl.LINES: + primitiveSize = 2; + break; + case gl.TRIANGLES: + primitiveSize = 3; + break; + case gl.LINE_STRIP: + primitiveSize = 1; + break; + } + for (const segment of segments.get()) { + const vaos = segment.vaos || (segment.vaos = {}); + const vao = vaos[layerID] || (vaos[layerID] = new VertexArrayObject()); + vao.bind(context, this, layoutVertexBuffer, configuration ? configuration.getPaintVertexBuffers() : [], indexBuffer, segment.vertexOffset, dynamicLayoutBuffer, dynamicLayoutBuffer2, dynamicLayoutBuffer3); + gl.drawElements(drawMode, segment.primitiveLength * primitiveSize, gl.UNSIGNED_SHORT, segment.primitiveOffset * primitiveSize * 2); + } + } +} + +function patternUniformValues(crossfade, painter, tile) { + const tileRatio = 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom); + const numTiles = Math.pow(2, tile.tileID.overscaledZ); + const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles; + const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles); + const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y; + return { + 'u_image': 0, + 'u_texsize': tile.imageAtlasTexture.size, + 'u_scale': [tileRatio, crossfade.fromScale, crossfade.toScale], + 'u_fade': crossfade.t, + // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision. + 'u_pixel_coord_upper': [pixelX >> 16, pixelY >> 16], + 'u_pixel_coord_lower': [pixelX & 0xFFFF, pixelY & 0xFFFF] + }; +} +function bgPatternUniformValues(image, crossfade, painter, tile) { + const imagePosA = painter.imageManager.getPattern(image.from.toString()); + const imagePosB = painter.imageManager.getPattern(image.to.toString()); + const { width, height } = painter.imageManager.getPixelSize(); + const numTiles = Math.pow(2, tile.tileID.overscaledZ); + const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles; + const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles); + const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y; + return { + 'u_image': 0, + 'u_pattern_tl_a': imagePosA.tl, + 'u_pattern_br_a': imagePosA.br, + 'u_pattern_tl_b': imagePosB.tl, + 'u_pattern_br_b': imagePosB.br, + 'u_texsize': [width, height], + 'u_mix': crossfade.t, + 'u_pattern_size_a': imagePosA.displaySize, + 'u_pattern_size_b': imagePosB.displaySize, + 'u_scale_a': crossfade.fromScale, + 'u_scale_b': crossfade.toScale, + 'u_tile_units_to_pixels': 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom), + // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision. + 'u_pixel_coord_upper': [pixelX >> 16, pixelY >> 16], + 'u_pixel_coord_lower': [pixelX & 0xFFFF, pixelY & 0xFFFF] + }; +} + +const fillExtrusionUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_lightpos': new Uniform3f(context, locations.u_lightpos), + 'u_lightintensity': new Uniform1f(context, locations.u_lightintensity), + 'u_lightcolor': new Uniform3f(context, locations.u_lightcolor), + 'u_vertical_gradient': new Uniform1f(context, locations.u_vertical_gradient), + 'u_opacity': new Uniform1f(context, locations.u_opacity) +}); +const fillExtrusionPatternUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_lightpos': new Uniform3f(context, locations.u_lightpos), + 'u_lightintensity': new Uniform1f(context, locations.u_lightintensity), + 'u_lightcolor': new Uniform3f(context, locations.u_lightcolor), + 'u_vertical_gradient': new Uniform1f(context, locations.u_vertical_gradient), + 'u_height_factor': new Uniform1f(context, locations.u_height_factor), + // pattern uniforms + 'u_image': new Uniform1i(context, locations.u_image), + 'u_texsize': new Uniform2f(context, locations.u_texsize), + 'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper), + 'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower), + 'u_scale': new Uniform3f(context, locations.u_scale), + 'u_fade': new Uniform1f(context, locations.u_fade), + 'u_opacity': new Uniform1f(context, locations.u_opacity) +}); +const fillExtrusionUniformValues = (matrix, painter, shouldUseVerticalGradient, opacity) => { + const light = painter.style.light; + const _lp = light.properties.get('position'); + const lightPos = [_lp.x, _lp.y, _lp.z]; + const lightMat = create$7(); + if (light.properties.get('anchor') === 'viewport') { + fromRotation$2(lightMat, -painter.transform.angle); + } + transformMat3$1(lightPos, lightPos, lightMat); + const lightColor = light.properties.get('color'); + return { + 'u_matrix': matrix, + 'u_lightpos': lightPos, + 'u_lightintensity': light.properties.get('intensity'), + 'u_lightcolor': [lightColor.r, lightColor.g, lightColor.b], + 'u_vertical_gradient': +shouldUseVerticalGradient, + 'u_opacity': opacity + }; +}; +const fillExtrusionPatternUniformValues = (matrix, painter, shouldUseVerticalGradient, opacity, coord, crossfade, tile) => { + return extend(fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity), patternUniformValues(crossfade, painter, tile), { + 'u_height_factor': -Math.pow(2, coord.overscaledZ) / tile.tileSize / 8 + }); +}; + +const fillUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix) +}); +const fillPatternUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_image': new Uniform1i(context, locations.u_image), + 'u_texsize': new Uniform2f(context, locations.u_texsize), + 'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper), + 'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower), + 'u_scale': new Uniform3f(context, locations.u_scale), + 'u_fade': new Uniform1f(context, locations.u_fade) +}); +const fillOutlineUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_world': new Uniform2f(context, locations.u_world) +}); +const fillOutlinePatternUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_world': new Uniform2f(context, locations.u_world), + 'u_image': new Uniform1i(context, locations.u_image), + 'u_texsize': new Uniform2f(context, locations.u_texsize), + 'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper), + 'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower), + 'u_scale': new Uniform3f(context, locations.u_scale), + 'u_fade': new Uniform1f(context, locations.u_fade) +}); +const fillUniformValues = (matrix) => ({ + 'u_matrix': matrix +}); +const fillPatternUniformValues = (matrix, painter, crossfade, tile) => extend(fillUniformValues(matrix), patternUniformValues(crossfade, painter, tile)); +const fillOutlineUniformValues = (matrix, drawingBufferSize) => ({ + 'u_matrix': matrix, + 'u_world': drawingBufferSize +}); +const fillOutlinePatternUniformValues = (matrix, painter, crossfade, tile, drawingBufferSize) => extend(fillPatternUniformValues(matrix, painter, crossfade, tile), { + 'u_world': drawingBufferSize +}); + +const circleUniforms = (context, locations) => ({ + 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance), + 'u_scale_with_map': new Uniform1i(context, locations.u_scale_with_map), + 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map), + 'u_extrude_scale': new Uniform2f(context, locations.u_extrude_scale), + 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio), + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix) +}); +const circleUniformValues = (painter, coord, tile, layer) => { + const transform = painter.transform; + let pitchWithMap, extrudeScale; + if (layer.paint.get('circle-pitch-alignment') === 'map') { + const pixelRatio = pixelsToTileUnits(tile, 1, transform.zoom); + pitchWithMap = true; + extrudeScale = [pixelRatio, pixelRatio]; + } + else { + pitchWithMap = false; + extrudeScale = transform.pixelsToGLUnits; + } + return { + 'u_camera_to_center_distance': transform.cameraToCenterDistance, + 'u_scale_with_map': +(layer.paint.get('circle-pitch-scale') === 'map'), + 'u_matrix': painter.translatePosMatrix(coord.posMatrix, tile, layer.paint.get('circle-translate'), layer.paint.get('circle-translate-anchor')), + 'u_pitch_with_map': +(pitchWithMap), + 'u_device_pixel_ratio': painter.pixelRatio, + 'u_extrude_scale': extrudeScale + }; +}; + +const collisionUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_pixel_extrude_scale': new Uniform2f(context, locations.u_pixel_extrude_scale) +}); +const collisionCircleUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_inv_matrix': new UniformMatrix4f(context, locations.u_inv_matrix), + 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance), + 'u_viewport_size': new Uniform2f(context, locations.u_viewport_size) +}); +const collisionUniformValues = (transform, matrix) => { + return { + 'u_matrix': matrix, + 'u_pixel_extrude_scale': [1.0 / transform.width, 1.0 / transform.height], + }; +}; +const collisionCircleUniformValues = (matrix, invMatrix, transform) => { + return { + 'u_matrix': matrix, + 'u_inv_matrix': invMatrix, + 'u_camera_to_center_distance': transform.cameraToCenterDistance, + 'u_viewport_size': [transform.width, transform.height] + }; +}; + +const debugUniforms = (context, locations) => ({ + 'u_color': new UniformColor(context, locations.u_color), + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_overlay': new Uniform1i(context, locations.u_overlay), + 'u_overlay_scale': new Uniform1f(context, locations.u_overlay_scale) +}); +const debugUniformValues = (matrix, color, scaleRatio = 1) => ({ + 'u_matrix': matrix, + 'u_color': color, + 'u_overlay': 0, + 'u_overlay_scale': scaleRatio +}); + +const clippingMaskUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix) +}); +const clippingMaskUniformValues = (matrix) => ({ + 'u_matrix': matrix +}); + +const heatmapUniforms = (context, locations) => ({ + 'u_extrude_scale': new Uniform1f(context, locations.u_extrude_scale), + 'u_intensity': new Uniform1f(context, locations.u_intensity), + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix) +}); +const heatmapTextureUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_world': new Uniform2f(context, locations.u_world), + 'u_image': new Uniform1i(context, locations.u_image), + 'u_color_ramp': new Uniform1i(context, locations.u_color_ramp), + 'u_opacity': new Uniform1f(context, locations.u_opacity) +}); +const heatmapUniformValues = (matrix, tile, zoom, intensity) => ({ + 'u_matrix': matrix, + 'u_extrude_scale': pixelsToTileUnits(tile, 1, zoom), + 'u_intensity': intensity +}); +const heatmapTextureUniformValues = (painter, layer, textureUnit, colorRampUnit) => { + const matrix = create$6(); + ortho(matrix, 0, painter.width, painter.height, 0, 0, 1); + const gl = painter.context.gl; + return { + 'u_matrix': matrix, + 'u_world': [gl.drawingBufferWidth, gl.drawingBufferHeight], + 'u_image': textureUnit, + 'u_color_ramp': colorRampUnit, + 'u_opacity': layer.paint.get('heatmap-opacity') + }; +}; + +const hillshadeUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_image': new Uniform1i(context, locations.u_image), + 'u_latrange': new Uniform2f(context, locations.u_latrange), + 'u_light': new Uniform2f(context, locations.u_light), + 'u_shadow': new UniformColor(context, locations.u_shadow), + 'u_highlight': new UniformColor(context, locations.u_highlight), + 'u_accent': new UniformColor(context, locations.u_accent) +}); +const hillshadePrepareUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_image': new Uniform1i(context, locations.u_image), + 'u_dimension': new Uniform2f(context, locations.u_dimension), + 'u_zoom': new Uniform1f(context, locations.u_zoom), + 'u_unpack': new Uniform4f(context, locations.u_unpack) +}); +const hillshadeUniformValues = (painter, tile, layer, coord) => { + const shadow = layer.paint.get('hillshade-shadow-color'); + const highlight = layer.paint.get('hillshade-highlight-color'); + const accent = layer.paint.get('hillshade-accent-color'); + let azimuthal = layer.paint.get('hillshade-illumination-direction') * (Math.PI / 180); + // modify azimuthal angle by map rotation if light is anchored at the viewport + if (layer.paint.get('hillshade-illumination-anchor') === 'viewport') { + azimuthal -= painter.transform.angle; + } + const align = !painter.options.moving; + return { + 'u_matrix': coord ? coord.posMatrix : painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped(), align), + 'u_image': 0, + 'u_latrange': getTileLatRange(painter, tile.tileID), + 'u_light': [layer.paint.get('hillshade-exaggeration'), azimuthal], + 'u_shadow': shadow, + 'u_highlight': highlight, + 'u_accent': accent + }; +}; +const hillshadeUniformPrepareValues = (tileID, dem) => { + const stride = dem.stride; + const matrix = create$6(); + // Flip rendering at y axis. + ortho(matrix, 0, EXTENT, -EXTENT, 0, 0, 1); + translate$1(matrix, matrix, [0, -EXTENT, 0]); + return { + 'u_matrix': matrix, + 'u_image': 1, + 'u_dimension': [stride, stride], + 'u_zoom': tileID.overscaledZ, + 'u_unpack': dem.getUnpackVector() + }; +}; +function getTileLatRange(painter, tileID) { + // for scaling the magnitude of a points slope by its latitude + const tilesAtZoom = Math.pow(2, tileID.canonical.z); + const y = tileID.canonical.y; + return [ + new MercatorCoordinate(0, y / tilesAtZoom).toLngLat().lat, + new MercatorCoordinate(0, (y + 1) / tilesAtZoom).toLngLat().lat + ]; +} + +const lineUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_ratio': new Uniform1f(context, locations.u_ratio), + 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio), + 'u_units_to_pixels': new Uniform2f(context, locations.u_units_to_pixels) +}); +const lineGradientUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_ratio': new Uniform1f(context, locations.u_ratio), + 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio), + 'u_units_to_pixels': new Uniform2f(context, locations.u_units_to_pixels), + 'u_image': new Uniform1i(context, locations.u_image), + 'u_image_height': new Uniform1f(context, locations.u_image_height) +}); +const linePatternUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_texsize': new Uniform2f(context, locations.u_texsize), + 'u_ratio': new Uniform1f(context, locations.u_ratio), + 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio), + 'u_image': new Uniform1i(context, locations.u_image), + 'u_units_to_pixels': new Uniform2f(context, locations.u_units_to_pixels), + 'u_scale': new Uniform3f(context, locations.u_scale), + 'u_fade': new Uniform1f(context, locations.u_fade) +}); +const lineSDFUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_ratio': new Uniform1f(context, locations.u_ratio), + 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio), + 'u_units_to_pixels': new Uniform2f(context, locations.u_units_to_pixels), + 'u_patternscale_a': new Uniform2f(context, locations.u_patternscale_a), + 'u_patternscale_b': new Uniform2f(context, locations.u_patternscale_b), + 'u_sdfgamma': new Uniform1f(context, locations.u_sdfgamma), + 'u_image': new Uniform1i(context, locations.u_image), + 'u_tex_y_a': new Uniform1f(context, locations.u_tex_y_a), + 'u_tex_y_b': new Uniform1f(context, locations.u_tex_y_b), + 'u_mix': new Uniform1f(context, locations.u_mix) +}); +const lineUniformValues = (painter, tile, layer, coord) => { + const transform = painter.transform; + return { + 'u_matrix': calculateMatrix(painter, tile, layer, coord), + 'u_ratio': 1 / pixelsToTileUnits(tile, 1, transform.zoom), + 'u_device_pixel_ratio': painter.pixelRatio, + 'u_units_to_pixels': [ + 1 / transform.pixelsToGLUnits[0], + 1 / transform.pixelsToGLUnits[1] + ] + }; +}; +const lineGradientUniformValues = (painter, tile, layer, imageHeight, coord) => { + return extend(lineUniformValues(painter, tile, layer, coord), { + 'u_image': 0, + 'u_image_height': imageHeight, + }); +}; +const linePatternUniformValues = (painter, tile, layer, crossfade, coord) => { + const transform = painter.transform; + const tileZoomRatio = calculateTileRatio(tile, transform); + return { + 'u_matrix': calculateMatrix(painter, tile, layer, coord), + 'u_texsize': tile.imageAtlasTexture.size, + // camera zoom ratio + 'u_ratio': 1 / pixelsToTileUnits(tile, 1, transform.zoom), + 'u_device_pixel_ratio': painter.pixelRatio, + 'u_image': 0, + 'u_scale': [tileZoomRatio, crossfade.fromScale, crossfade.toScale], + 'u_fade': crossfade.t, + 'u_units_to_pixels': [ + 1 / transform.pixelsToGLUnits[0], + 1 / transform.pixelsToGLUnits[1] + ] + }; +}; +const lineSDFUniformValues = (painter, tile, layer, dasharray, crossfade, coord) => { + const transform = painter.transform; + const lineAtlas = painter.lineAtlas; + const tileRatio = calculateTileRatio(tile, transform); + const round = layer.layout.get('line-cap') === 'round'; + const posA = lineAtlas.getDash(dasharray.from, round); + const posB = lineAtlas.getDash(dasharray.to, round); + const widthA = posA.width * crossfade.fromScale; + const widthB = posB.width * crossfade.toScale; + return extend(lineUniformValues(painter, tile, layer, coord), { + 'u_patternscale_a': [tileRatio / widthA, -posA.height / 2], + 'u_patternscale_b': [tileRatio / widthB, -posB.height / 2], + 'u_sdfgamma': lineAtlas.width / (Math.min(widthA, widthB) * 256 * painter.pixelRatio) / 2, + 'u_image': 0, + 'u_tex_y_a': posA.y, + 'u_tex_y_b': posB.y, + 'u_mix': crossfade.t + }); +}; +function calculateTileRatio(tile, transform) { + return 1 / pixelsToTileUnits(tile, 1, transform.tileZoom); +} +function calculateMatrix(painter, tile, layer, coord) { + return painter.translatePosMatrix(coord ? coord.posMatrix : tile.tileID.posMatrix, tile, layer.paint.get('line-translate'), layer.paint.get('line-translate-anchor')); +} + +const rasterUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_tl_parent': new Uniform2f(context, locations.u_tl_parent), + 'u_scale_parent': new Uniform1f(context, locations.u_scale_parent), + 'u_buffer_scale': new Uniform1f(context, locations.u_buffer_scale), + 'u_fade_t': new Uniform1f(context, locations.u_fade_t), + 'u_opacity': new Uniform1f(context, locations.u_opacity), + 'u_image0': new Uniform1i(context, locations.u_image0), + 'u_image1': new Uniform1i(context, locations.u_image1), + 'u_brightness_low': new Uniform1f(context, locations.u_brightness_low), + 'u_brightness_high': new Uniform1f(context, locations.u_brightness_high), + 'u_saturation_factor': new Uniform1f(context, locations.u_saturation_factor), + 'u_contrast_factor': new Uniform1f(context, locations.u_contrast_factor), + 'u_spin_weights': new Uniform3f(context, locations.u_spin_weights) +}); +const rasterUniformValues = (matrix, parentTL, parentScaleBy, fade, layer) => ({ + 'u_matrix': matrix, + 'u_tl_parent': parentTL, + 'u_scale_parent': parentScaleBy, + 'u_buffer_scale': 1, + 'u_fade_t': fade.mix, + 'u_opacity': fade.opacity * layer.paint.get('raster-opacity'), + 'u_image0': 0, + 'u_image1': 1, + 'u_brightness_low': layer.paint.get('raster-brightness-min'), + 'u_brightness_high': layer.paint.get('raster-brightness-max'), + 'u_saturation_factor': saturationFactor(layer.paint.get('raster-saturation')), + 'u_contrast_factor': contrastFactor(layer.paint.get('raster-contrast')), + 'u_spin_weights': spinWeights(layer.paint.get('raster-hue-rotate')) +}); +function spinWeights(angle) { + angle *= Math.PI / 180; + const s = Math.sin(angle); + const c = Math.cos(angle); + return [ + (2 * c + 1) / 3, + (-Math.sqrt(3) * s - c + 1) / 3, + (Math.sqrt(3) * s - c + 1) / 3 + ]; +} +function contrastFactor(contrast) { + return contrast > 0 ? + 1 / (1 - contrast) : + 1 + contrast; +} +function saturationFactor(saturation) { + return saturation > 0 ? + 1 - 1 / (1.001 - saturation) : + -saturation; +} + +const symbolIconUniforms = (context, locations) => ({ + 'u_is_size_zoom_constant': new Uniform1i(context, locations.u_is_size_zoom_constant), + 'u_is_size_feature_constant': new Uniform1i(context, locations.u_is_size_feature_constant), + 'u_size_t': new Uniform1f(context, locations.u_size_t), + 'u_size': new Uniform1f(context, locations.u_size), + 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance), + 'u_pitch': new Uniform1f(context, locations.u_pitch), + 'u_rotate_symbol': new Uniform1i(context, locations.u_rotate_symbol), + 'u_aspect_ratio': new Uniform1f(context, locations.u_aspect_ratio), + 'u_fade_change': new Uniform1f(context, locations.u_fade_change), + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_label_plane_matrix': new UniformMatrix4f(context, locations.u_label_plane_matrix), + 'u_coord_matrix': new UniformMatrix4f(context, locations.u_coord_matrix), + 'u_is_text': new Uniform1i(context, locations.u_is_text), + 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map), + 'u_is_along_line': new Uniform1i(context, locations.u_is_along_line), + 'u_is_variable_anchor': new Uniform1i(context, locations.u_is_variable_anchor), + 'u_texsize': new Uniform2f(context, locations.u_texsize), + 'u_texture': new Uniform1i(context, locations.u_texture), + 'u_translation': new Uniform2f(context, locations.u_translation), + 'u_pitched_scale': new Uniform1f(context, locations.u_pitched_scale), +}); +const symbolSDFUniforms = (context, locations) => ({ + 'u_is_size_zoom_constant': new Uniform1i(context, locations.u_is_size_zoom_constant), + 'u_is_size_feature_constant': new Uniform1i(context, locations.u_is_size_feature_constant), + 'u_size_t': new Uniform1f(context, locations.u_size_t), + 'u_size': new Uniform1f(context, locations.u_size), + 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance), + 'u_pitch': new Uniform1f(context, locations.u_pitch), + 'u_rotate_symbol': new Uniform1i(context, locations.u_rotate_symbol), + 'u_aspect_ratio': new Uniform1f(context, locations.u_aspect_ratio), + 'u_fade_change': new Uniform1f(context, locations.u_fade_change), + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_label_plane_matrix': new UniformMatrix4f(context, locations.u_label_plane_matrix), + 'u_coord_matrix': new UniformMatrix4f(context, locations.u_coord_matrix), + 'u_is_text': new Uniform1i(context, locations.u_is_text), + 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map), + 'u_is_along_line': new Uniform1i(context, locations.u_is_along_line), + 'u_is_variable_anchor': new Uniform1i(context, locations.u_is_variable_anchor), + 'u_texsize': new Uniform2f(context, locations.u_texsize), + 'u_texture': new Uniform1i(context, locations.u_texture), + 'u_texture_2': new Uniform1i(context, locations.u_texture_2), + 'u_gamma_scale': new Uniform1f(context, locations.u_gamma_scale), + 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio), + 'u_is_halo': new Uniform1i(context, locations.u_is_halo), + 'u_translation': new Uniform2f(context, locations.u_translation), + 'u_pitched_scale': new Uniform1f(context, locations.u_pitched_scale), +}); +const symbolTextAndIconUniforms = (context, locations) => ({ + 'u_is_size_zoom_constant': new Uniform1i(context, locations.u_is_size_zoom_constant), + 'u_is_size_feature_constant': new Uniform1i(context, locations.u_is_size_feature_constant), + 'u_size_t': new Uniform1f(context, locations.u_size_t), + 'u_size': new Uniform1f(context, locations.u_size), + 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance), + 'u_pitch': new Uniform1f(context, locations.u_pitch), + 'u_rotate_symbol': new Uniform1i(context, locations.u_rotate_symbol), + 'u_aspect_ratio': new Uniform1f(context, locations.u_aspect_ratio), + 'u_fade_change': new Uniform1f(context, locations.u_fade_change), + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_label_plane_matrix': new UniformMatrix4f(context, locations.u_label_plane_matrix), + 'u_coord_matrix': new UniformMatrix4f(context, locations.u_coord_matrix), + 'u_is_text': new Uniform1i(context, locations.u_is_text), + 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map), + 'u_is_along_line': new Uniform1i(context, locations.u_is_along_line), + 'u_is_variable_anchor': new Uniform1i(context, locations.u_is_variable_anchor), + 'u_texsize': new Uniform2f(context, locations.u_texsize), + 'u_texsize_icon': new Uniform2f(context, locations.u_texsize_icon), + 'u_texture': new Uniform1i(context, locations.u_texture), + 'u_texture_icon': new Uniform1i(context, locations.u_texture_icon), + 'u_gamma_scale': new Uniform1f(context, locations.u_gamma_scale), + 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio), + 'u_is_halo': new Uniform1i(context, locations.u_is_halo), + 'u_translation': new Uniform2f(context, locations.u_translation), + 'u_pitched_scale': new Uniform1f(context, locations.u_pitched_scale), +}); +const symbolIconUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, pitchedScale) => { + const transform = painter.transform; + return { + 'u_is_size_zoom_constant': +(functionType === 'constant' || functionType === 'source'), + 'u_is_size_feature_constant': +(functionType === 'constant' || functionType === 'camera'), + 'u_size_t': size ? size.uSizeT : 0, + 'u_size': size ? size.uSize : 0, + 'u_camera_to_center_distance': transform.cameraToCenterDistance, + 'u_pitch': transform.pitch / 360 * 2 * Math.PI, + 'u_rotate_symbol': +rotateInShader, + 'u_aspect_ratio': transform.width / transform.height, + 'u_fade_change': painter.options.fadeDuration ? painter.symbolFadeChange : 1, + 'u_matrix': matrix, + 'u_label_plane_matrix': labelPlaneMatrix, + 'u_coord_matrix': glCoordMatrix, + 'u_is_text': +isText, + 'u_pitch_with_map': +pitchWithMap, + 'u_is_along_line': isAlongLine, + 'u_is_variable_anchor': isVariableAnchor, + 'u_texsize': texSize, + 'u_texture': 0, + 'u_translation': translation, + 'u_pitched_scale': pitchedScale + }; +}; +const symbolSDFUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, isHalo, pitchedScale) => { + const transform = painter.transform; + return extend(symbolIconUniformValues(functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, pitchedScale), { + 'u_gamma_scale': (pitchWithMap ? Math.cos(transform._pitch) * transform.cameraToCenterDistance : 1), + 'u_device_pixel_ratio': painter.pixelRatio, + 'u_is_halo': +isHalo, + 'u_texture_2': 1 + }); +}; +const symbolTextAndIconUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, texSizeSDF, texSizeIcon, pitchedScale) => { + return extend(symbolSDFUniformValues(functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, true, texSizeSDF, true, pitchedScale), { + 'u_texsize_icon': texSizeIcon, + 'u_texture_icon': 1 + }); +}; + +const backgroundUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_opacity': new Uniform1f(context, locations.u_opacity), + 'u_color': new UniformColor(context, locations.u_color) +}); +const backgroundPatternUniforms = (context, locations) => ({ + 'u_matrix': new UniformMatrix4f(context, locations.u_matrix), + 'u_opacity': new Uniform1f(context, locations.u_opacity), + 'u_image': new Uniform1i(context, locations.u_image), + 'u_pattern_tl_a': new Uniform2f(context, locations.u_pattern_tl_a), + 'u_pattern_br_a': new Uniform2f(context, locations.u_pattern_br_a), + 'u_pattern_tl_b': new Uniform2f(context, locations.u_pattern_tl_b), + 'u_pattern_br_b': new Uniform2f(context, locations.u_pattern_br_b), + 'u_texsize': new Uniform2f(context, locations.u_texsize), + 'u_mix': new Uniform1f(context, locations.u_mix), + 'u_pattern_size_a': new Uniform2f(context, locations.u_pattern_size_a), + 'u_pattern_size_b': new Uniform2f(context, locations.u_pattern_size_b), + 'u_scale_a': new Uniform1f(context, locations.u_scale_a), + 'u_scale_b': new Uniform1f(context, locations.u_scale_b), + 'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper), + 'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower), + 'u_tile_units_to_pixels': new Uniform1f(context, locations.u_tile_units_to_pixels) +}); +const backgroundUniformValues = (matrix, opacity, color) => ({ + 'u_matrix': matrix, + 'u_opacity': opacity, + 'u_color': color +}); +const backgroundPatternUniformValues = (matrix, opacity, painter, image, tile, crossfade) => extend(bgPatternUniformValues(image, crossfade, painter, tile), { + 'u_matrix': matrix, + 'u_opacity': opacity +}); + +const skyUniforms = (context, locations) => ({ + 'u_sky_color': new UniformColor(context, locations.u_sky_color), + 'u_horizon_color': new UniformColor(context, locations.u_horizon_color), + 'u_horizon': new Uniform1f(context, locations.u_horizon), + 'u_sky_horizon_blend': new Uniform1f(context, locations.u_sky_horizon_blend), +}); +const skyUniformValues = (sky, transform, pixelRatio) => ({ + 'u_sky_color': sky.properties.get('sky-color'), + 'u_horizon_color': sky.properties.get('horizon-color'), + 'u_horizon': (transform.height / 2 + transform.getHorizon()) * pixelRatio, + 'u_sky_horizon_blend': (sky.properties.get('sky-horizon-blend') * transform.height / 2) * pixelRatio, +}); + +const programUniforms = { + fillExtrusion: fillExtrusionUniforms, + fillExtrusionPattern: fillExtrusionPatternUniforms, + fill: fillUniforms, + fillPattern: fillPatternUniforms, + fillOutline: fillOutlineUniforms, + fillOutlinePattern: fillOutlinePatternUniforms, + circle: circleUniforms, + collisionBox: collisionUniforms, + collisionCircle: collisionCircleUniforms, + debug: debugUniforms, + clippingMask: clippingMaskUniforms, + heatmap: heatmapUniforms, + heatmapTexture: heatmapTextureUniforms, + hillshade: hillshadeUniforms, + hillshadePrepare: hillshadePrepareUniforms, + line: lineUniforms, + lineGradient: lineGradientUniforms, + linePattern: linePatternUniforms, + lineSDF: lineSDFUniforms, + raster: rasterUniforms, + symbolIcon: symbolIconUniforms, + symbolSDF: symbolSDFUniforms, + symbolTextAndIcon: symbolTextAndIconUniforms, + background: backgroundUniforms, + backgroundPattern: backgroundPatternUniforms, + terrain: terrainUniforms, + terrainDepth: terrainDepthUniforms, + terrainCoords: terrainCoordsUniforms, + sky: skyUniforms +}; + +/** + * @internal + * an index buffer class + */ +class IndexBuffer { + constructor(context, array, dynamicDraw) { + this.context = context; + const gl = context.gl; + this.buffer = gl.createBuffer(); + this.dynamicDraw = Boolean(dynamicDraw); + // The bound index buffer is part of vertex array object state. We don't want to + // modify whatever VAO happens to be currently bound, so make sure the default + // vertex array provided by the context is bound instead. + this.context.unbindVAO(); + context.bindElementBuffer.set(this.buffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW); + if (!this.dynamicDraw) { + delete array.arrayBuffer; + } + } + bind() { + this.context.bindElementBuffer.set(this.buffer); + } + updateData(array) { + const gl = this.context.gl; + if (!this.dynamicDraw) + throw new Error('Attempted to update data while not in dynamic mode.'); + // The right VAO will get this buffer re-bound later in VertexArrayObject#bind + // See https://github.com/mapbox/mapbox-gl-js/issues/5620 + this.context.unbindVAO(); + this.bind(); + gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, array.arrayBuffer); + } + destroy() { + const gl = this.context.gl; + if (this.buffer) { + gl.deleteBuffer(this.buffer); + delete this.buffer; + } + } +} + +/** + * An Enum for AttributeType + */ +const AttributeType = { + Int8: 'BYTE', + Uint8: 'UNSIGNED_BYTE', + Int16: 'SHORT', + Uint16: 'UNSIGNED_SHORT', + Int32: 'INT', + Uint32: 'UNSIGNED_INT', + Float32: 'FLOAT' +}; +/** + * @internal + * The `VertexBuffer` class turns a `StructArray` into a WebGL buffer. Each member of the StructArray's + * Struct type is converted to a WebGL attribute. + */ +class VertexBuffer { + /** + * @param dynamicDraw - Whether this buffer will be repeatedly updated. + */ + constructor(context, array, attributes, dynamicDraw) { + this.length = array.length; + this.attributes = attributes; + this.itemSize = array.bytesPerElement; + this.dynamicDraw = dynamicDraw; + this.context = context; + const gl = context.gl; + this.buffer = gl.createBuffer(); + context.bindVertexBuffer.set(this.buffer); + gl.bufferData(gl.ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW); + if (!this.dynamicDraw) { + delete array.arrayBuffer; + } + } + bind() { + this.context.bindVertexBuffer.set(this.buffer); + } + updateData(array) { + if (array.length !== this.length) + throw new Error(`Length of new data is ${array.length}, which doesn't match current length of ${this.length}`); + const gl = this.context.gl; + this.bind(); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, array.arrayBuffer); + } + enableAttributes(gl, program) { + for (let j = 0; j < this.attributes.length; j++) { + const member = this.attributes[j]; + const attribIndex = program.attributes[member.name]; + if (attribIndex !== undefined) { + gl.enableVertexAttribArray(attribIndex); + } + } + } + /** + * Set the attribute pointers in a WebGL context + * @param gl - The WebGL context + * @param program - The active WebGL program + * @param vertexOffset - Index of the starting vertex of the segment + */ + setVertexAttribPointers(gl, program, vertexOffset) { + for (let j = 0; j < this.attributes.length; j++) { + const member = this.attributes[j]; + const attribIndex = program.attributes[member.name]; + if (attribIndex !== undefined) { + gl.vertexAttribPointer(attribIndex, member.components, gl[AttributeType[member.type]], false, this.itemSize, member.offset + (this.itemSize * (vertexOffset || 0))); + } + } + } + /** + * Destroy the GL buffer bound to the given WebGL context + */ + destroy() { + const gl = this.context.gl; + if (this.buffer) { + gl.deleteBuffer(this.buffer); + delete this.buffer; + } + } +} + +const cache = new WeakMap(); +function isWebGL2(gl) { + var _a; + if (cache.has(gl)) { + return cache.get(gl); + } + else { + const value = (_a = gl.getParameter(gl.VERSION)) === null || _a === void 0 ? void 0 : _a.startsWith('WebGL 2.0'); + cache.set(gl, value); + return value; + } +} + +class BaseValue { + constructor(context) { + this.gl = context.gl; + this.default = this.getDefault(); + this.current = this.default; + this.dirty = false; + } + get() { + return this.current; + } + set(value) { + // overridden in child classes; + } + getDefault() { + return this.default; // overridden in child classes + } + setDefault() { + this.set(this.default); + } +} +class ClearColor extends BaseValue { + getDefault() { + return Color.transparent; + } + set(v) { + const c = this.current; + if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) + return; + this.gl.clearColor(v.r, v.g, v.b, v.a); + this.current = v; + this.dirty = false; + } +} +class ClearDepth extends BaseValue { + getDefault() { + return 1; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.clearDepth(v); + this.current = v; + this.dirty = false; + } +} +class ClearStencil extends BaseValue { + getDefault() { + return 0; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.clearStencil(v); + this.current = v; + this.dirty = false; + } +} +class ColorMask extends BaseValue { + getDefault() { + return [true, true, true, true]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) + return; + this.gl.colorMask(v[0], v[1], v[2], v[3]); + this.current = v; + this.dirty = false; + } +} +class DepthMask extends BaseValue { + getDefault() { + return true; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.depthMask(v); + this.current = v; + this.dirty = false; + } +} +class StencilMask extends BaseValue { + getDefault() { + return 0xFF; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.stencilMask(v); + this.current = v; + this.dirty = false; + } +} +class StencilFunc extends BaseValue { + getDefault() { + return { + func: this.gl.ALWAYS, + ref: 0, + mask: 0xFF + }; + } + set(v) { + const c = this.current; + if (v.func === c.func && v.ref === c.ref && v.mask === c.mask && !this.dirty) + return; + this.gl.stencilFunc(v.func, v.ref, v.mask); + this.current = v; + this.dirty = false; + } +} +class StencilOp extends BaseValue { + getDefault() { + const gl = this.gl; + return [gl.KEEP, gl.KEEP, gl.KEEP]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && !this.dirty) + return; + this.gl.stencilOp(v[0], v[1], v[2]); + this.current = v; + this.dirty = false; + } +} +class StencilTest extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (v) { + gl.enable(gl.STENCIL_TEST); + } + else { + gl.disable(gl.STENCIL_TEST); + } + this.current = v; + this.dirty = false; + } +} +class DepthRange extends BaseValue { + getDefault() { + return [0, 1]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && !this.dirty) + return; + this.gl.depthRange(v[0], v[1]); + this.current = v; + this.dirty = false; + } +} +class DepthTest extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (v) { + gl.enable(gl.DEPTH_TEST); + } + else { + gl.disable(gl.DEPTH_TEST); + } + this.current = v; + this.dirty = false; + } +} +class DepthFunc extends BaseValue { + getDefault() { + return this.gl.LESS; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.depthFunc(v); + this.current = v; + this.dirty = false; + } +} +class Blend extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (v) { + gl.enable(gl.BLEND); + } + else { + gl.disable(gl.BLEND); + } + this.current = v; + this.dirty = false; + } +} +class BlendFunc extends BaseValue { + getDefault() { + const gl = this.gl; + return [gl.ONE, gl.ZERO]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && !this.dirty) + return; + this.gl.blendFunc(v[0], v[1]); + this.current = v; + this.dirty = false; + } +} +class BlendColor extends BaseValue { + getDefault() { + return Color.transparent; + } + set(v) { + const c = this.current; + if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) + return; + this.gl.blendColor(v.r, v.g, v.b, v.a); + this.current = v; + this.dirty = false; + } +} +class BlendEquation extends BaseValue { + getDefault() { + return this.gl.FUNC_ADD; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.blendEquation(v); + this.current = v; + this.dirty = false; + } +} +class CullFace extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (v) { + gl.enable(gl.CULL_FACE); + } + else { + gl.disable(gl.CULL_FACE); + } + this.current = v; + this.dirty = false; + } +} +class CullFaceSide extends BaseValue { + getDefault() { + return this.gl.BACK; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.cullFace(v); + this.current = v; + this.dirty = false; + } +} +class FrontFace extends BaseValue { + getDefault() { + return this.gl.CCW; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.frontFace(v); + this.current = v; + this.dirty = false; + } +} +class ProgramValue extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.useProgram(v); + this.current = v; + this.dirty = false; + } +} +class ActiveTextureUnit extends BaseValue { + getDefault() { + return this.gl.TEXTURE0; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.activeTexture(v); + this.current = v; + this.dirty = false; + } +} +class Viewport extends BaseValue { + getDefault() { + const gl = this.gl; + return [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) + return; + this.gl.viewport(v[0], v[1], v[2], v[3]); + this.current = v; + this.dirty = false; + } +} +class BindFramebuffer extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, v); + this.current = v; + this.dirty = false; + } +} +class BindRenderbuffer extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.bindRenderbuffer(gl.RENDERBUFFER, v); + this.current = v; + this.dirty = false; + } +} +class BindTexture extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, v); + this.current = v; + this.dirty = false; + } +} +class BindVertexBuffer extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.bindBuffer(gl.ARRAY_BUFFER, v); + this.current = v; + this.dirty = false; + } +} +class BindElementBuffer extends BaseValue { + getDefault() { + return null; + } + set(v) { + // Always rebind + const gl = this.gl; + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, v); + this.current = v; + this.dirty = false; + } +} +class BindVertexArray extends BaseValue { + getDefault() { + return null; + } + set(v) { + var _a; + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (isWebGL2(gl)) { + gl.bindVertexArray(v); + } + else { + (_a = gl.getExtension('OES_vertex_array_object')) === null || _a === void 0 ? void 0 : _a.bindVertexArrayOES(v); + } + this.current = v; + this.dirty = false; + } +} +class PixelStoreUnpack extends BaseValue { + getDefault() { + return 4; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_ALIGNMENT, v); + this.current = v; + this.dirty = false; + } +} +class PixelStoreUnpackPremultiplyAlpha extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, v); + this.current = v; + this.dirty = false; + } +} +class PixelStoreUnpackFlipY extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, v); + this.current = v; + this.dirty = false; + } +} +class FramebufferAttachment extends BaseValue { + constructor(context, parent) { + super(context); + this.context = context; + this.parent = parent; + } + getDefault() { + return null; + } +} +class ColorAttachment extends FramebufferAttachment { + setDirty() { + this.dirty = true; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.context.bindFramebuffer.set(this.parent); + // note: it's possible to attach a renderbuffer to the color + // attachment point, but thus far MBGL only uses textures for color + const gl = this.gl; + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, v, 0); + this.current = v; + this.dirty = false; + } +} +class DepthAttachment extends FramebufferAttachment { + set(v) { + if (v === this.current && !this.dirty) + return; + this.context.bindFramebuffer.set(this.parent); + // note: it's possible to attach a texture to the depth attachment + // point, but thus far MBGL only uses renderbuffers for depth + const gl = this.gl; + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, v); + this.current = v; + this.dirty = false; + } +} +class DepthStencilAttachment extends FramebufferAttachment { + set(v) { + if (v === this.current && !this.dirty) + return; + this.context.bindFramebuffer.set(this.parent); + // note: it's possible to attach a texture to the depth attachment + // point, but thus far MBGL only uses renderbuffers for depth + const gl = this.gl; + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, v); + this.current = v; + this.dirty = false; + } +} + +/** + * @internal + * A framebuffer holder object + */ +class Framebuffer { + constructor(context, width, height, hasDepth, hasStencil) { + this.context = context; + this.width = width; + this.height = height; + const gl = context.gl; + const fbo = this.framebuffer = gl.createFramebuffer(); + this.colorAttachment = new ColorAttachment(context, fbo); + if (hasDepth) { + this.depthAttachment = hasStencil ? new DepthStencilAttachment(context, fbo) : new DepthAttachment(context, fbo); + } + else if (hasStencil) { + throw new Error('Stencil cannot be set without depth'); + } + if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) { + throw new Error('Framebuffer is not complete'); + } + } + destroy() { + const gl = this.context.gl; + const texture = this.colorAttachment.get(); + if (texture) + gl.deleteTexture(texture); + if (this.depthAttachment) { + const renderbuffer = this.depthAttachment.get(); + if (renderbuffer) + gl.deleteRenderbuffer(renderbuffer); + } + gl.deleteFramebuffer(this.framebuffer); + } +} + +const ZERO = 0x0000; +const ONE = 0x0001; +const ONE_MINUS_SRC_ALPHA = 0x0303; +class ColorMode { + constructor(blendFunction, blendColor, mask) { + this.blendFunction = blendFunction; + this.blendColor = blendColor; + this.mask = mask; + } +} +ColorMode.Replace = [ONE, ZERO]; +ColorMode.disabled = new ColorMode(ColorMode.Replace, Color.transparent, [false, false, false, false]); +ColorMode.unblended = new ColorMode(ColorMode.Replace, Color.transparent, [true, true, true, true]); +ColorMode.alphaBlended = new ColorMode([ONE, ONE_MINUS_SRC_ALPHA], Color.transparent, [true, true, true, true]); + +/** + * @internal + * A webgl wrapper class to allow injection, mocking and abstaction + */ +class Context { + constructor(gl) { + var _a, _b; + this.gl = gl; + this.clearColor = new ClearColor(this); + this.clearDepth = new ClearDepth(this); + this.clearStencil = new ClearStencil(this); + this.colorMask = new ColorMask(this); + this.depthMask = new DepthMask(this); + this.stencilMask = new StencilMask(this); + this.stencilFunc = new StencilFunc(this); + this.stencilOp = new StencilOp(this); + this.stencilTest = new StencilTest(this); + this.depthRange = new DepthRange(this); + this.depthTest = new DepthTest(this); + this.depthFunc = new DepthFunc(this); + this.blend = new Blend(this); + this.blendFunc = new BlendFunc(this); + this.blendColor = new BlendColor(this); + this.blendEquation = new BlendEquation(this); + this.cullFace = new CullFace(this); + this.cullFaceSide = new CullFaceSide(this); + this.frontFace = new FrontFace(this); + this.program = new ProgramValue(this); + this.activeTexture = new ActiveTextureUnit(this); + this.viewport = new Viewport(this); + this.bindFramebuffer = new BindFramebuffer(this); + this.bindRenderbuffer = new BindRenderbuffer(this); + this.bindTexture = new BindTexture(this); + this.bindVertexBuffer = new BindVertexBuffer(this); + this.bindElementBuffer = new BindElementBuffer(this); + this.bindVertexArray = new BindVertexArray(this); + this.pixelStoreUnpack = new PixelStoreUnpack(this); + this.pixelStoreUnpackPremultiplyAlpha = new PixelStoreUnpackPremultiplyAlpha(this); + this.pixelStoreUnpackFlipY = new PixelStoreUnpackFlipY(this); + this.extTextureFilterAnisotropic = (gl.getExtension('EXT_texture_filter_anisotropic') || + gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || + gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic')); + if (this.extTextureFilterAnisotropic) { + this.extTextureFilterAnisotropicMax = gl.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } + this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + if (isWebGL2(gl)) { + this.HALF_FLOAT = gl.HALF_FLOAT; + const extColorBufferHalfFloat = gl.getExtension('EXT_color_buffer_half_float'); + this.RGBA16F = (_a = gl.RGBA16F) !== null && _a !== void 0 ? _a : extColorBufferHalfFloat === null || extColorBufferHalfFloat === void 0 ? void 0 : extColorBufferHalfFloat.RGBA16F_EXT; + this.RGB16F = (_b = gl.RGB16F) !== null && _b !== void 0 ? _b : extColorBufferHalfFloat === null || extColorBufferHalfFloat === void 0 ? void 0 : extColorBufferHalfFloat.RGB16F_EXT; + gl.getExtension('EXT_color_buffer_float'); + } + else { + gl.getExtension('EXT_color_buffer_half_float'); + gl.getExtension('OES_texture_half_float_linear'); + const extTextureHalfFloat = gl.getExtension('OES_texture_half_float'); + this.HALF_FLOAT = extTextureHalfFloat === null || extTextureHalfFloat === void 0 ? void 0 : extTextureHalfFloat.HALF_FLOAT_OES; + } + } + setDefault() { + this.unbindVAO(); + this.clearColor.setDefault(); + this.clearDepth.setDefault(); + this.clearStencil.setDefault(); + this.colorMask.setDefault(); + this.depthMask.setDefault(); + this.stencilMask.setDefault(); + this.stencilFunc.setDefault(); + this.stencilOp.setDefault(); + this.stencilTest.setDefault(); + this.depthRange.setDefault(); + this.depthTest.setDefault(); + this.depthFunc.setDefault(); + this.blend.setDefault(); + this.blendFunc.setDefault(); + this.blendColor.setDefault(); + this.blendEquation.setDefault(); + this.cullFace.setDefault(); + this.cullFaceSide.setDefault(); + this.frontFace.setDefault(); + this.program.setDefault(); + this.activeTexture.setDefault(); + this.bindFramebuffer.setDefault(); + this.pixelStoreUnpack.setDefault(); + this.pixelStoreUnpackPremultiplyAlpha.setDefault(); + this.pixelStoreUnpackFlipY.setDefault(); + } + setDirty() { + this.clearColor.dirty = true; + this.clearDepth.dirty = true; + this.clearStencil.dirty = true; + this.colorMask.dirty = true; + this.depthMask.dirty = true; + this.stencilMask.dirty = true; + this.stencilFunc.dirty = true; + this.stencilOp.dirty = true; + this.stencilTest.dirty = true; + this.depthRange.dirty = true; + this.depthTest.dirty = true; + this.depthFunc.dirty = true; + this.blend.dirty = true; + this.blendFunc.dirty = true; + this.blendColor.dirty = true; + this.blendEquation.dirty = true; + this.cullFace.dirty = true; + this.cullFaceSide.dirty = true; + this.frontFace.dirty = true; + this.program.dirty = true; + this.activeTexture.dirty = true; + this.viewport.dirty = true; + this.bindFramebuffer.dirty = true; + this.bindRenderbuffer.dirty = true; + this.bindTexture.dirty = true; + this.bindVertexBuffer.dirty = true; + this.bindElementBuffer.dirty = true; + this.bindVertexArray.dirty = true; + this.pixelStoreUnpack.dirty = true; + this.pixelStoreUnpackPremultiplyAlpha.dirty = true; + this.pixelStoreUnpackFlipY.dirty = true; + } + createIndexBuffer(array, dynamicDraw) { + return new IndexBuffer(this, array, dynamicDraw); + } + createVertexBuffer(array, attributes, dynamicDraw) { + return new VertexBuffer(this, array, attributes, dynamicDraw); + } + createRenderbuffer(storageFormat, width, height) { + const gl = this.gl; + const rbo = gl.createRenderbuffer(); + this.bindRenderbuffer.set(rbo); + gl.renderbufferStorage(gl.RENDERBUFFER, storageFormat, width, height); + this.bindRenderbuffer.set(null); + return rbo; + } + createFramebuffer(width, height, hasDepth, hasStencil) { + return new Framebuffer(this, width, height, hasDepth, hasStencil); + } + clear({ color, depth, stencil }) { + const gl = this.gl; + let mask = 0; + if (color) { + mask |= gl.COLOR_BUFFER_BIT; + this.clearColor.set(color); + this.colorMask.set([true, true, true, true]); + } + if (typeof depth !== 'undefined') { + mask |= gl.DEPTH_BUFFER_BIT; + // Workaround for platforms where clearDepth doesn't seem to work + // without resetting the depthRange. See https://github.com/mapbox/mapbox-gl-js/issues/3437 + this.depthRange.set([0, 1]); + this.clearDepth.set(depth); + this.depthMask.set(true); + } + if (typeof stencil !== 'undefined') { + mask |= gl.STENCIL_BUFFER_BIT; + this.clearStencil.set(stencil); + this.stencilMask.set(0xFF); + } + gl.clear(mask); + } + setCullFace(cullFaceMode) { + if (cullFaceMode.enable === false) { + this.cullFace.set(false); + } + else { + this.cullFace.set(true); + this.cullFaceSide.set(cullFaceMode.mode); + this.frontFace.set(cullFaceMode.frontFace); + } + } + setDepthMode(depthMode) { + if (depthMode.func === this.gl.ALWAYS && !depthMode.mask) { + this.depthTest.set(false); + } + else { + this.depthTest.set(true); + this.depthFunc.set(depthMode.func); + this.depthMask.set(depthMode.mask); + this.depthRange.set(depthMode.range); + } + } + setStencilMode(stencilMode) { + if (stencilMode.test.func === this.gl.ALWAYS && !stencilMode.mask) { + this.stencilTest.set(false); + } + else { + this.stencilTest.set(true); + this.stencilMask.set(stencilMode.mask); + this.stencilOp.set([stencilMode.fail, stencilMode.depthFail, stencilMode.pass]); + this.stencilFunc.set({ + func: stencilMode.test.func, + ref: stencilMode.ref, + mask: stencilMode.test.mask + }); + } + } + setColorMode(colorMode) { + if (deepEqual$1(colorMode.blendFunction, ColorMode.Replace)) { + this.blend.set(false); + } + else { + this.blend.set(true); + this.blendFunc.set(colorMode.blendFunction); + this.blendColor.set(colorMode.blendColor); + } + this.colorMask.set(colorMode.mask); + } + createVertexArray() { + var _a; + if (isWebGL2(this.gl)) + return this.gl.createVertexArray(); + return (_a = this.gl.getExtension('OES_vertex_array_object')) === null || _a === void 0 ? void 0 : _a.createVertexArrayOES(); + } + deleteVertexArray(x) { + var _a; + if (isWebGL2(this.gl)) + return this.gl.deleteVertexArray(x); + return (_a = this.gl.getExtension('OES_vertex_array_object')) === null || _a === void 0 ? void 0 : _a.deleteVertexArrayOES(x); + } + unbindVAO() { + // Unbinding the VAO prevents other things (custom layers, new buffer creation) from + // unintentionally changing the state of the last VAO used. + this.bindVertexArray.set(null); + } +} + +const ALWAYS$1 = 0x0207; +class DepthMode { + constructor(depthFunc, depthMask, depthRange) { + this.func = depthFunc; + this.mask = depthMask; + this.range = depthRange; + } +} +DepthMode.ReadOnly = false; +DepthMode.ReadWrite = true; +DepthMode.disabled = new DepthMode(ALWAYS$1, DepthMode.ReadOnly, [0, 1]); + +const ALWAYS = 0x0207; +const KEEP = 0x1E00; +class StencilMode { + constructor(test, ref, mask, fail, depthFail, pass) { + this.test = test; + this.ref = ref; + this.mask = mask; + this.fail = fail; + this.depthFail = depthFail; + this.pass = pass; + } +} +StencilMode.disabled = new StencilMode({ func: ALWAYS, mask: 0 }, 0, 0, KEEP, KEEP, KEEP); + +const BACK = 0x0405; +const CCW = 0x0901; +class CullFaceMode { + constructor(enable, mode, frontFace) { + this.enable = enable; + this.mode = mode; + this.frontFace = frontFace; + } +} +CullFaceMode.disabled = new CullFaceMode(false, BACK, CCW); +CullFaceMode.backCCW = new CullFaceMode(true, BACK, CCW); + +let quadTriangles; +function drawCollisionDebug(painter, sourceCache, layer, coords, isText) { + const context = painter.context; + const gl = context.gl; + const program = painter.useProgram('collisionBox'); + const tileBatches = []; + let circleCount = 0; + let circleOffset = 0; + for (let i = 0; i < coords.length; i++) { + const coord = coords[i]; + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const buffers = isText ? bucket.textCollisionBox : bucket.iconCollisionBox; + // Get collision circle data of this bucket + const circleArray = bucket.collisionCircleArray; + if (circleArray.length > 0) { + // We need to know the projection matrix that was used for projecting collision circles to the screen. + // This might vary between buckets as the symbol placement is a continuous process. This matrix is + // required for transforming points from previous screen space to the current one + const invTransform = create$6(); + mul$5(invTransform, bucket.placementInvProjMatrix, painter.transform.glCoordMatrix); + mul$5(invTransform, invTransform, bucket.placementViewportMatrix); + tileBatches.push({ + circleArray, + circleOffset, + transform: coord.posMatrix, // Ignore translation + invTransform, + coord + }); + circleCount += circleArray.length / 4; // 4 values per circle + circleOffset = circleCount; + } + // Draw collision boxes + if (!buffers) { + continue; + } + program.draw(context, gl.LINES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, collisionUniformValues(painter.transform, coord.posMatrix), painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord), layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer, buffers.segments, null, painter.transform.zoom, null, null, buffers.collisionVertexBuffer); + } + if (!isText || !tileBatches.length) { + return; + } + // Render collision circles + const circleProgram = painter.useProgram('collisionCircle'); + // Construct vertex data + const vertexData = new CollisionCircleLayoutArray(); + vertexData.resize(circleCount * 4); + vertexData._trim(); + let vertexOffset = 0; + for (const batch of tileBatches) { + for (let i = 0; i < batch.circleArray.length / 4; i++) { + const circleIdx = i * 4; + const x = batch.circleArray[circleIdx + 0]; + const y = batch.circleArray[circleIdx + 1]; + const radius = batch.circleArray[circleIdx + 2]; + const collision = batch.circleArray[circleIdx + 3]; + // 4 floats per vertex, 4 vertices per quad + vertexData.emplace(vertexOffset++, x, y, radius, collision, 0); + vertexData.emplace(vertexOffset++, x, y, radius, collision, 1); + vertexData.emplace(vertexOffset++, x, y, radius, collision, 2); + vertexData.emplace(vertexOffset++, x, y, radius, collision, 3); + } + } + if (!quadTriangles || quadTriangles.length < circleCount * 2) { + quadTriangles = createQuadTriangles(circleCount); + } + const indexBuffer = context.createIndexBuffer(quadTriangles, true); + const vertexBuffer = context.createVertexBuffer(vertexData, collisionCircleLayout.members, true); + // Render batches + for (const batch of tileBatches) { + const uniforms = collisionCircleUniformValues(batch.transform, batch.invTransform, painter.transform); + circleProgram.draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, uniforms, painter.style.map.terrain && painter.style.map.terrain.getTerrainData(batch.coord), layer.id, vertexBuffer, indexBuffer, SegmentVector.simpleSegment(0, batch.circleOffset * 2, batch.circleArray.length, batch.circleArray.length / 2), null, painter.transform.zoom, null, null, null); + } + vertexBuffer.destroy(); + indexBuffer.destroy(); +} +function createQuadTriangles(quadCount) { + const triCount = quadCount * 2; + const array = new QuadTriangleArray(); + array.resize(triCount); + array._trim(); + // Two triangles and 4 vertices per quad. + for (let i = 0; i < triCount; i++) { + const idx = i * 6; + array.uint16[idx + 0] = i * 4 + 0; + array.uint16[idx + 1] = i * 4 + 1; + array.uint16[idx + 2] = i * 4 + 2; + array.uint16[idx + 3] = i * 4 + 2; + array.uint16[idx + 4] = i * 4 + 3; + array.uint16[idx + 5] = i * 4 + 0; + } + return array; +} + +const identityMat4 = identity$2(new Float32Array(16)); +function drawSymbols(painter, sourceCache, layer, coords, variableOffsets) { + if (painter.renderPass !== 'translucent') + return; + // Disable the stencil test so that labels aren't clipped to tile boundaries. + const stencilMode = StencilMode.disabled; + const colorMode = painter.colorModeForRenderPass(); + const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset'); + //Compute variable-offsets before painting since icons and text data positioning + //depend on each other in this case. + if (hasVariablePlacement) { + updateVariableAnchors(coords, painter, layer, sourceCache, layer.layout.get('text-rotation-alignment'), layer.layout.get('text-pitch-alignment'), layer.paint.get('text-translate'), layer.paint.get('text-translate-anchor'), variableOffsets); + } + if (layer.paint.get('icon-opacity').constantOr(1) !== 0) { + drawLayerSymbols(painter, sourceCache, layer, coords, false, layer.paint.get('icon-translate'), layer.paint.get('icon-translate-anchor'), layer.layout.get('icon-rotation-alignment'), layer.layout.get('icon-pitch-alignment'), layer.layout.get('icon-keep-upright'), stencilMode, colorMode); + } + if (layer.paint.get('text-opacity').constantOr(1) !== 0) { + drawLayerSymbols(painter, sourceCache, layer, coords, true, layer.paint.get('text-translate'), layer.paint.get('text-translate-anchor'), layer.layout.get('text-rotation-alignment'), layer.layout.get('text-pitch-alignment'), layer.layout.get('text-keep-upright'), stencilMode, colorMode); + } + if (sourceCache.map.showCollisionBoxes) { + drawCollisionDebug(painter, sourceCache, layer, coords, true); + drawCollisionDebug(painter, sourceCache, layer, coords, false); + } +} +function calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize) { + const { horizontalAlign, verticalAlign } = getAnchorAlignment(anchor); + const shiftX = -(horizontalAlign - 0.5) * width; + const shiftY = -(verticalAlign - 0.5) * height; + return new Point$2((shiftX / textBoxScale + textOffset[0]) * renderTextSize, (shiftY / textBoxScale + textOffset[1]) * renderTextSize); +} +function updateVariableAnchors(coords, painter, layer, sourceCache, rotationAlignment, pitchAlignment, translate, translateAnchor, variableOffsets) { + const transform = painter.transform; + const projection = createProjection(); + const rotateWithMap = rotationAlignment === 'map'; + const pitchWithMap = pitchAlignment === 'map'; + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket || !bucket.text || !bucket.text.segments.get().length) + continue; + const sizeData = bucket.textSizeData; + const size = evaluateSizeForZoom(sizeData, transform.zoom); + const pixelToTileScale = pixelsToTileUnits(tile, 1, painter.transform.zoom); + const labelPlaneMatrix = getLabelPlaneMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, pixelToTileScale); + const updateTextFitIcon = layer.layout.get('icon-text-fit') !== 'none' && bucket.hasIconData(); + if (size) { + const tileScale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ); + const getElevation = painter.style.map.terrain ? (x, y) => painter.style.map.terrain.getElevation(coord, x, y) : null; + const translation = projection.translatePosition(transform, tile, translate, translateAnchor); + updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, transform, labelPlaneMatrix, coord.posMatrix, tileScale, size, updateTextFitIcon, projection, translation, coord.toUnwrapped(), getElevation); + } + } +} +function getShiftedAnchor(projectedAnchorPoint, projectionContext, rotateWithMap, shift, transformAngle, pitchedTextShiftCorrection) { + // Usual case is that we take the projected anchor and add the pixel-based shift + // calculated earlier. In the (somewhat weird) case of pitch-aligned text, we add an equivalent + // tile-unit based shift to the anchor before projecting to the label plane. + const translatedAnchor = projectionContext.tileAnchorPoint.add(new Point$2(projectionContext.translation[0], projectionContext.translation[1])); + if (projectionContext.pitchWithMap) { + let adjustedShift = shift.mult(pitchedTextShiftCorrection); + if (!rotateWithMap) { + adjustedShift = adjustedShift.rotate(-transformAngle); + } + const tileAnchorShifted = translatedAnchor.add(adjustedShift); + return project(tileAnchorShifted.x, tileAnchorShifted.y, projectionContext.labelPlaneMatrix, projectionContext.getElevation).point; + } + else { + if (rotateWithMap) { + // Compute the angle with which to rotate the anchor, so that it is aligned with + // the map's actual east-west axis. Very similar to what is done in the shader. + const projectedAnchorRight = projectTileCoordinatesToViewport(projectionContext.tileAnchorPoint.x + 1, projectionContext.tileAnchorPoint.y, projectionContext); + const east = projectedAnchorRight.point.sub(projectedAnchorPoint); + const angle = Math.atan(east.y / east.x) + (east.x < 0 ? Math.PI : 0); + return projectedAnchorPoint.add(shift.rotate(angle)); + } + else { + return projectedAnchorPoint.add(shift); + } + } +} +function updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, transform, labelPlaneMatrix, posMatrix, tileScale, size, updateTextFitIcon, projection, translation, unwrappedTileID, getElevation) { + const placedSymbols = bucket.text.placedSymbolArray; + const dynamicTextLayoutVertexArray = bucket.text.dynamicLayoutVertexArray; + const dynamicIconLayoutVertexArray = bucket.icon.dynamicLayoutVertexArray; + const placedTextShifts = {}; + dynamicTextLayoutVertexArray.clear(); + for (let s = 0; s < placedSymbols.length; s++) { + const symbol = placedSymbols.get(s); + const skipOrientation = bucket.allowVerticalPlacement && !symbol.placedOrientation; + const variableOffset = (!symbol.hidden && symbol.crossTileID && !skipOrientation) ? variableOffsets[symbol.crossTileID] : null; + if (!variableOffset) { + // These symbols are from a justification that is not being used, or a label that wasn't placed + // so we don't need to do the extra math to figure out what incremental shift to apply. + hideGlyphs(symbol.numGlyphs, dynamicTextLayoutVertexArray); + } + else { + const tileAnchor = new Point$2(symbol.anchorX, symbol.anchorY); + const projectionContext = { + getElevation, + width: transform.width, + height: transform.height, + labelPlaneMatrix, + lineVertexArray: null, + pitchWithMap, + projection, + projectionCache: null, + tileAnchorPoint: tileAnchor, + translation, + unwrappedTileID + }; + const projectedAnchor = pitchWithMap ? + project(tileAnchor.x, tileAnchor.y, posMatrix, getElevation) : + projectTileCoordinatesToViewport(tileAnchor.x, tileAnchor.y, projectionContext); + const perspectiveRatio = getPerspectiveRatio(transform.cameraToCenterDistance, projectedAnchor.signedDistanceFromCamera); + let renderTextSize = evaluateSizeForFeature(bucket.textSizeData, size, symbol) * perspectiveRatio / ONE_EM; + if (pitchWithMap) { + // Go from size in pixels to equivalent size in tile units + renderTextSize *= bucket.tilePixelRatio / tileScale; + } + const { width, height, anchor, textOffset, textBoxScale } = variableOffset; + const shift = calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize); + const pitchedTextCorrection = projection.getPitchedTextCorrection(transform, tileAnchor.add(new Point$2(translation[0], translation[1])), unwrappedTileID); + const shiftedAnchor = getShiftedAnchor(projectedAnchor.point, projectionContext, rotateWithMap, shift, transform.angle, pitchedTextCorrection); + const angle = (bucket.allowVerticalPlacement && symbol.placedOrientation === WritingMode.vertical) ? Math.PI / 2 : 0; + for (let g = 0; g < symbol.numGlyphs; g++) { + addDynamicAttributes(dynamicTextLayoutVertexArray, shiftedAnchor, angle); + } + //Only offset horizontal text icons + if (updateTextFitIcon && symbol.associatedIconIndex >= 0) { + placedTextShifts[symbol.associatedIconIndex] = { shiftedAnchor, angle }; + } + } + } + if (updateTextFitIcon) { + dynamicIconLayoutVertexArray.clear(); + const placedIcons = bucket.icon.placedSymbolArray; + for (let i = 0; i < placedIcons.length; i++) { + const placedIcon = placedIcons.get(i); + if (placedIcon.hidden) { + hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray); + } + else { + const shift = placedTextShifts[i]; + if (!shift) { + hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray); + } + else { + for (let g = 0; g < placedIcon.numGlyphs; g++) { + addDynamicAttributes(dynamicIconLayoutVertexArray, shift.shiftedAnchor, shift.angle); + } + } + } + } + bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicIconLayoutVertexArray); + } + bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicTextLayoutVertexArray); +} +function getSymbolProgramName(isSDF, isText, bucket) { + if (bucket.iconsInText && isText) { + return 'symbolTextAndIcon'; + } + else if (isSDF) { + return 'symbolSDF'; + } + else { + return 'symbolIcon'; + } +} +function drawLayerSymbols(painter, sourceCache, layer, coords, isText, translate, translateAnchor, rotationAlignment, pitchAlignment, keepUpright, stencilMode, colorMode) { + const context = painter.context; + const gl = context.gl; + const tr = painter.transform; + const projection = createProjection(); + const rotateWithMap = rotationAlignment === 'map'; + const pitchWithMap = pitchAlignment === 'map'; + const alongLine = rotationAlignment !== 'viewport' && layer.layout.get('symbol-placement') !== 'point'; + // Line label rotation happens in `updateLineLabels` + // Pitched point labels are automatically rotated by the labelPlaneMatrix projection + // Unpitched point labels need to have their rotation applied after projection + const rotateInShader = rotateWithMap && !pitchWithMap && !alongLine; + const isViewportLine = !pitchWithMap && alongLine; + const hasSortKey = !layer.layout.get('symbol-sort-key').isConstant(); + let sortFeaturesByKey = false; + const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly); + const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset'); + const tileRenderState = []; + const pitchedTextRescaling = projection.getCircleRadiusCorrection(tr); + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const buffers = isText ? bucket.text : bucket.icon; + if (!buffers || !buffers.segments.get().length || !buffers.hasVisibleVertices) + continue; + const programConfiguration = buffers.programConfigurations.get(layer.id); + const isSDF = isText || bucket.sdfIcons; + const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData; + const transformed = pitchWithMap || tr.pitch !== 0; + const program = painter.useProgram(getSymbolProgramName(isSDF, isText, bucket), programConfiguration); + const size = evaluateSizeForZoom(sizeData, tr.zoom); + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + let texSize; + let texSizeIcon = [0, 0]; + let atlasTexture; + let atlasInterpolation; + let atlasTextureIcon = null; + let atlasInterpolationIcon; + let atlasBackgroundTexture; + if (isText) { + atlasTexture = tile.glyphAtlasTexture; + atlasInterpolation = gl.LINEAR; + texSize = tile.glyphAtlasTexture.size; + if (bucket.iconsInText) { + texSizeIcon = tile.imageAtlasTexture.size; + atlasTextureIcon = tile.imageAtlasTexture; + const zoomDependentSize = sizeData.kind === 'composite' || sizeData.kind === 'camera'; + atlasInterpolationIcon = transformed || painter.options.rotating || painter.options.zooming || zoomDependentSize ? gl.LINEAR : gl.NEAREST; + } + } + else { + const iconScaled = layer.layout.get('icon-size').constantOr(0) !== 1 || bucket.iconsNeedLinear; + atlasTexture = tile.imageAtlasTexture; + atlasBackgroundTexture = tile.imageBackgroundsAtlasTexture; + atlasInterpolation = isSDF || painter.options.rotating || painter.options.zooming || iconScaled || transformed ? + gl.LINEAR : + gl.NEAREST; + texSize = tile.imageAtlasTexture.size; + } + const s = pixelsToTileUnits(tile, 1, painter.transform.zoom); + const baseMatrix = isViewportLine ? coord.posMatrix : identityMat4; + const labelPlaneMatrix = getLabelPlaneMatrix(baseMatrix, pitchWithMap, rotateWithMap, painter.transform, s); + const glCoordMatrixForShader = getGlCoordMatrix(baseMatrix, pitchWithMap, rotateWithMap, painter.transform, s); + const glCoordMatrixForSymbolPlacement = getGlCoordMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, s); + const translation = projection.translatePosition(painter.transform, tile, translate, translateAnchor); + const hasVariableAnchors = hasVariablePlacement && bucket.hasTextData(); + const updateTextFitIcon = layer.layout.get('icon-text-fit') !== 'none' && + hasVariableAnchors && + bucket.hasIconData(); + if (alongLine) { + const getElevation = painter.style.map.terrain ? (x, y) => painter.style.map.terrain.getElevation(coord, x, y) : null; + const rotateToLine = layer.layout.get('text-rotation-alignment') === 'map'; + updateLineLabels(bucket, coord.posMatrix, painter, isText, labelPlaneMatrix, glCoordMatrixForSymbolPlacement, pitchWithMap, keepUpright, rotateToLine, projection, coord.toUnwrapped(), tr.width, tr.height, translation, getElevation); + } + const matrix = coord.posMatrix; // formerly also incorporated translate and translate-anchor + const shaderVariableAnchor = (isText && hasVariablePlacement) || updateTextFitIcon; + const noLabelPlane = (alongLine || shaderVariableAnchor); + const uLabelPlaneMatrix = noLabelPlane ? identityMat4 : labelPlaneMatrix; + const uglCoordMatrix = glCoordMatrixForShader; // formerly also incorporated translate and translate-anchor + const hasHalo = isSDF && layer.paint.get(isText ? 'text-halo-width' : 'icon-halo-width').constantOr(1) !== 0; + let uniformValues; + if (isSDF) { + if (!bucket.iconsInText) { + uniformValues = symbolSDFUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, translation, isText, texSize, true, pitchedTextRescaling); + } + else { + uniformValues = symbolTextAndIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, translation, texSize, texSizeIcon, pitchedTextRescaling); + } + } + else { + uniformValues = symbolIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, translation, isText, texSize, pitchedTextRescaling); + } + const state = { + program, + buffers, + uniformValues, + atlasTexture, + atlasBackgroundTexture, + atlasTextureIcon, + atlasInterpolation, + atlasInterpolationIcon, + isSDF, + hasHalo + }; + if (hasSortKey && bucket.canOverlap) { + sortFeaturesByKey = true; + const oldSegments = buffers.segments.get(); + for (const segment of oldSegments) { + tileRenderState.push({ + segments: new SegmentVector([segment]), + sortKey: segment.sortKey, + state, + terrainData + }); + } + } + else { + tileRenderState.push({ + segments: buffers.segments, + sortKey: 0, + state, + terrainData + }); + } + } + if (sortFeaturesByKey) { + tileRenderState.sort((a, b) => a.sortKey - b.sortKey); + } + for (const segmentState of tileRenderState) { + const state = segmentState.state; + context.activeTexture.set(gl.TEXTURE0); + state.atlasTexture.bind(state.atlasInterpolation, gl.CLAMP_TO_EDGE); + if (state.atlasTextureIcon || state.atlasBackgroundTexture) { + context.activeTexture.set(gl.TEXTURE1); + if (state.atlasTextureIcon) { + state.atlasTextureIcon.bind(state.atlasInterpolationIcon, gl.CLAMP_TO_EDGE); + } + if (state.atlasBackgroundTexture) { + state.atlasBackgroundTexture.bind(state.atlasInterpolation, gl.CLAMP_TO_EDGE); + } + } + if (state.isSDF) { + const uniformValues = state.uniformValues; + if (state.hasHalo) { + uniformValues['u_is_halo'] = 1; + drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, uniformValues, segmentState.terrainData); + } + uniformValues['u_is_halo'] = 0; + } + drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, state.uniformValues, segmentState.terrainData); + } +} +function drawSymbolElements(buffers, segments, layer, painter, program, depthMode, stencilMode, colorMode, uniformValues, terrainData) { + const context = painter.context; + const gl = context.gl; + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer, segments, layer.paint, painter.transform.zoom, buffers.programConfigurations.get(layer.id), buffers.dynamicLayoutVertexBuffer, buffers.opacityVertexBuffer); +} + +function drawCircles(painter, sourceCache, layer, coords) { + if (painter.renderPass !== 'translucent') + return; + const opacity = layer.paint.get('circle-opacity'); + const strokeWidth = layer.paint.get('circle-stroke-width'); + const strokeOpacity = layer.paint.get('circle-stroke-opacity'); + const sortFeaturesByKey = !layer.layout.get('circle-sort-key').isConstant(); + if (opacity.constantOr(1) === 0 && (strokeWidth.constantOr(1) === 0 || strokeOpacity.constantOr(1) === 0)) { + return; + } + const context = painter.context; + const gl = context.gl; + const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly); + // Turn off stencil testing to allow circles to be drawn across boundaries, + // so that large circles are not clipped to tiles + const stencilMode = StencilMode.disabled; + const colorMode = painter.colorModeForRenderPass(); + const segmentsRenderStates = []; + for (let i = 0; i < coords.length; i++) { + const coord = coords[i]; + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram('circle', programConfiguration); + const layoutVertexBuffer = bucket.layoutVertexBuffer; + const indexBuffer = bucket.indexBuffer; + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + const uniformValues = circleUniformValues(painter, coord, tile, layer); + const state = { + programConfiguration, + program, + layoutVertexBuffer, + indexBuffer, + uniformValues, + terrainData + }; + if (sortFeaturesByKey) { + const oldSegments = bucket.segments.get(); + for (const segment of oldSegments) { + segmentsRenderStates.push({ + segments: new SegmentVector([segment]), + sortKey: segment.sortKey, + state + }); + } + } + else { + segmentsRenderStates.push({ + segments: bucket.segments, + sortKey: 0, + state + }); + } + } + if (sortFeaturesByKey) { + segmentsRenderStates.sort((a, b) => a.sortKey - b.sortKey); + } + for (const segmentsState of segmentsRenderStates) { + const { programConfiguration, program, layoutVertexBuffer, indexBuffer, uniformValues, terrainData } = segmentsState.state; + const segments = segmentsState.segments; + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, layoutVertexBuffer, indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration); + } +} + +function drawHeatmap(painter, sourceCache, layer, tileIDs) { + if (layer.paint.get('heatmap-opacity') === 0) { + return; + } + const context = painter.context; + if (painter.style.map.terrain) { + for (const coord of tileIDs) { + const tile = sourceCache.getTile(coord); + // Skip tiles that have uncovered parents to avoid flickering; we don't need + // to use complex tile masking here because the change between zoom levels is subtle, + // so it's fine to simply render the parent until all its 4 children are loaded + if (sourceCache.hasRenderableParent(coord)) + continue; + if (painter.renderPass === 'offscreen') { + prepareHeatmapTerrain(painter, tile, layer, coord); + } + else if (painter.renderPass === 'translucent') { + renderHeatmapTerrain(painter, layer, coord); + } + } + context.viewport.set([0, 0, painter.width, painter.height]); + } + else { + if (painter.renderPass === 'offscreen') { + prepareHeatmapFlat(painter, sourceCache, layer, tileIDs); + } + else if (painter.renderPass === 'translucent') { + renderHeatmapFlat(painter, layer); + } + } +} +function prepareHeatmapFlat(painter, sourceCache, layer, coords) { + const context = painter.context; + const gl = context.gl; + // Allow kernels to be drawn across boundaries, so that + // large kernels are not clipped to tiles + const stencilMode = StencilMode.disabled; + // Turn on additive blending for kernels, which is a key aspect of kernel density estimation formula + const colorMode = new ColorMode([gl.ONE, gl.ONE], Color.transparent, [true, true, true, true]); + bindFramebuffer(context, painter, layer); + context.clear({ color: Color.transparent }); + for (let i = 0; i < coords.length; i++) { + const coord = coords[i]; + // Skip tiles that have uncovered parents to avoid flickering; we don't need + // to use complex tile masking here because the change between zoom levels is subtle, + // so it's fine to simply render the parent until all its 4 children are loaded + if (sourceCache.hasRenderableParent(coord)) + continue; + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram('heatmap', programConfiguration); + const { zoom } = painter.transform; + program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.disabled, heatmapUniformValues(coord.posMatrix, tile, zoom, layer.paint.get('heatmap-intensity')), null, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration); + } + context.viewport.set([0, 0, painter.width, painter.height]); +} +function renderHeatmapFlat(painter, layer) { + const context = painter.context; + const gl = context.gl; + context.setColorMode(painter.colorModeForRenderPass()); + // Here we bind two different textures from which we'll sample in drawing + // heatmaps: the kernel texture, prepared in the offscreen pass, and a + // color ramp texture. + const fbo = layer.heatmapFbos.get(HEATMAP_FULL_RENDER_FBO_KEY); + if (!fbo) + return; + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get()); + context.activeTexture.set(gl.TEXTURE1); + const colorRampTexture = getColorRampTexture(context, layer); + colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + painter.useProgram('heatmapTexture').draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, heatmapTextureUniformValues(painter, layer, 0, 1), null, layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer, painter.viewportSegments, layer.paint, painter.transform.zoom); +} +function prepareHeatmapTerrain(painter, tile, layer, coord) { + const context = painter.context; + const gl = context.gl; + const stencilMode = StencilMode.disabled; + // Turn on additive blending for kernels, which is a key aspect of kernel density estimation formula + const colorMode = new ColorMode([gl.ONE, gl.ONE], Color.transparent, [true, true, true, true]); + const bucket = tile.getBucket(layer); + if (!bucket) + return; + const tileKey = coord.key; + let fbo = layer.heatmapFbos.get(tileKey); + if (!fbo) { + fbo = createHeatmapFbo(context, tile.tileSize, tile.tileSize); + layer.heatmapFbos.set(tileKey, fbo); + } + context.bindFramebuffer.set(fbo.framebuffer); + context.viewport.set([0, 0, tile.tileSize, tile.tileSize]); + context.clear({ color: Color.transparent }); + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram('heatmap', programConfiguration); + const terrainData = painter.style.map.terrain.getTerrainData(coord); + program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.disabled, heatmapUniformValues(coord.posMatrix, tile, painter.transform.zoom, layer.paint.get('heatmap-intensity')), terrainData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration); +} +function renderHeatmapTerrain(painter, layer, coord) { + const context = painter.context; + const gl = context.gl; + context.setColorMode(painter.colorModeForRenderPass()); + const colorRampTexture = getColorRampTexture(context, layer); + // Here we bind two different textures from which we'll sample in drawing + // heatmaps: the kernel texture, prepared in the offscreen pass, and a + // color ramp texture. + const tileKey = coord.key; + const fbo = layer.heatmapFbos.get(tileKey); + if (!fbo) + return; + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get()); + context.activeTexture.set(gl.TEXTURE1); + colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + painter.useProgram('heatmapTexture').draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, heatmapTextureUniformValues(painter, layer, 0, 1), null, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments, layer.paint, painter.transform.zoom); + // destroy the FBO after rendering + fbo.destroy(); + layer.heatmapFbos.delete(tileKey); +} +function bindFramebuffer(context, painter, layer) { + const gl = context.gl; + context.activeTexture.set(gl.TEXTURE1); + // Use a 4x downscaled screen texture for better performance + context.viewport.set([0, 0, painter.width / 4, painter.height / 4]); + let fbo = layer.heatmapFbos.get(HEATMAP_FULL_RENDER_FBO_KEY); + if (!fbo) { + fbo = createHeatmapFbo(context, painter.width / 4, painter.height / 4); + layer.heatmapFbos.set(HEATMAP_FULL_RENDER_FBO_KEY, fbo); + } + else { + gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get()); + context.bindFramebuffer.set(fbo.framebuffer); + } +} +function createHeatmapFbo(context, width, height) { + var _a, _b; + const gl = context.gl; + const texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + // Use the higher precision half-float texture where available (producing much smoother looking heatmaps); + // Otherwise, fall back to a low precision texture + const numType = (_a = context.HALF_FLOAT) !== null && _a !== void 0 ? _a : gl.UNSIGNED_BYTE; + const internalFormat = (_b = context.RGBA16F) !== null && _b !== void 0 ? _b : gl.RGBA; + gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, width, height, 0, gl.RGBA, numType, null); + const fbo = context.createFramebuffer(width, height, false, false); + fbo.colorAttachment.set(texture); + return fbo; +} +function getColorRampTexture(context, layer) { + if (!layer.colorRampTexture) { + layer.colorRampTexture = new Texture(context, layer.colorRamp, context.gl.RGBA); + } + return layer.colorRampTexture; +} + +function drawLine(painter, sourceCache, layer, coords) { + if (painter.renderPass !== 'translucent') + return; + const opacity = layer.paint.get('line-opacity'); + const width = layer.paint.get('line-width'); + if (opacity.constantOr(1) === 0 || width.constantOr(1) === 0) + return; + const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly); + const colorMode = painter.colorModeForRenderPass(); + const dasharray = layer.paint.get('line-dasharray'); + const patternProperty = layer.paint.get('line-pattern'); + const image = patternProperty.constantOr(1); + const gradient = layer.paint.get('line-gradient'); + const crossfade = layer.getCrossfadeParameters(); + const programId = image ? 'linePattern' : + dasharray ? 'lineSDF' : + gradient ? 'lineGradient' : 'line'; + const context = painter.context; + const gl = context.gl; + let firstTile = true; + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + if (image && !tile.patternsLoaded()) + continue; + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const programConfiguration = bucket.programConfigurations.get(layer.id); + const prevProgram = painter.context.program.get(); + const program = painter.useProgram(programId, programConfiguration); + const programChanged = firstTile || program.program !== prevProgram; + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + const constantPattern = patternProperty.constantOr(null); + if (constantPattern && tile.imageAtlas) { + const atlas = tile.imageAtlas; + const posTo = atlas.patternPositions[constantPattern.to.toString()]; + const posFrom = atlas.patternPositions[constantPattern.from.toString()]; + if (posTo && posFrom) + programConfiguration.setConstantPatternPositions(posTo, posFrom); + } + const terrainCoord = terrainData ? coord : null; + const uniformValues = image ? linePatternUniformValues(painter, tile, layer, crossfade, terrainCoord) : + dasharray ? lineSDFUniformValues(painter, tile, layer, dasharray, crossfade, terrainCoord) : + gradient ? lineGradientUniformValues(painter, tile, layer, bucket.lineClipsArray.length, terrainCoord) : + lineUniformValues(painter, tile, layer, terrainCoord); + if (image) { + context.activeTexture.set(gl.TEXTURE0); + tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + programConfiguration.updatePaintBuffers(crossfade); + } + else if (dasharray && (programChanged || painter.lineAtlas.dirty)) { + context.activeTexture.set(gl.TEXTURE0); + painter.lineAtlas.bind(context); + } + else if (gradient) { + const layerGradient = bucket.gradients[layer.id]; + let gradientTexture = layerGradient.texture; + if (layer.gradientVersion !== layerGradient.version) { + let textureResolution = 256; + if (layer.stepInterpolant) { + const sourceMaxZoom = sourceCache.getSource().maxzoom; + const potentialOverzoom = coord.canonical.z === sourceMaxZoom ? + Math.ceil(1 << (painter.transform.maxZoom - coord.canonical.z)) : 1; + const lineLength = bucket.maxLineLength / EXTENT; + // Logical pixel tile size is 512px, and 1024px right before current zoom + 1 + const maxTilePixelSize = 1024; + // Maximum possible texture coverage heuristic, bound by hardware max texture size + const maxTextureCoverage = lineLength * maxTilePixelSize * potentialOverzoom; + textureResolution = clamp$1(nextPowerOfTwo(maxTextureCoverage), 256, context.maxTextureSize); + } + layerGradient.gradient = renderColorRamp({ + expression: layer.gradientExpression(), + evaluationKey: 'lineProgress', + resolution: textureResolution, + image: layerGradient.gradient || undefined, + clips: bucket.lineClipsArray + }); + if (layerGradient.texture) { + layerGradient.texture.update(layerGradient.gradient); + } + else { + layerGradient.texture = new Texture(context, layerGradient.gradient, gl.RGBA); + } + layerGradient.version = layer.gradientVersion; + gradientTexture = layerGradient.texture; + } + context.activeTexture.set(gl.TEXTURE0); + gradientTexture.bind(layer.stepInterpolant ? gl.NEAREST : gl.LINEAR, gl.CLAMP_TO_EDGE); + } + program.draw(context, gl.TRIANGLES, depthMode, painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration, bucket.layoutVertexBuffer2); + firstTile = false; + // once refactored so that bound texture state is managed, we'll also be able to remove this firstTile/programChanged logic + } +} + +/** + * A simple helper shared by draw_fill and draw_fill_extrusions to find the correct pattern positions AND update program. + * For transitionable properties, especially 'fill-pattern' and 'fill-extrusion-pattern', while rendering certain frames + * tile.imageAtlas has been updated by worker to hold the new pattern only, but rendering code is still looking for the previous image. + * The mismatch was causing setConstantPatternPositions method not being called and pixelRatio was always the + * default of 1, instead of actual values set by original map.addImage. + * + * @param programConfiguration - to be used to set pattern position and device pixel ratio. + * @param propertyName - 'fill-pattern' or 'fill-extrusion-pattern' property key + * @param constantPattern - either 'fill-pattern' or 'fill-extrusion-pattern' property value + * @param tile - current tile being drawn + * @param layer - current layer being rendered + */ +function updatePatternPositionsInProgram(programConfiguration, propertyName, constantPattern, tile, layer) { + if (!constantPattern || !tile || !tile.imageAtlas) { + return; + } + const patternPositions = tile.imageAtlas.patternPositions; + let posTo = patternPositions[constantPattern.to.toString()]; + let posFrom = patternPositions[constantPattern.from.toString()]; + // https://github.com/maplibre/maplibre-gl-js/issues/3377 + if (!posTo && posFrom) + posTo = posFrom; + if (!posFrom && posTo) + posFrom = posTo; + // try again in case patternPositions has been updated by worker + if (!posTo || !posFrom) { + const transitioned = layer.getPaintProperty(propertyName); + posTo = patternPositions[transitioned]; + posFrom = patternPositions[transitioned]; + } + if (posTo && posFrom) { + programConfiguration.setConstantPatternPositions(posTo, posFrom); + } +} + +function drawFill(painter, sourceCache, layer, coords) { + const color = layer.paint.get('fill-color'); + const opacity = layer.paint.get('fill-opacity'); + if (opacity.constantOr(1) === 0) { + return; + } + const colorMode = painter.colorModeForRenderPass(); + const pattern = layer.paint.get('fill-pattern'); + const pass = painter.opaquePassEnabledForLayer() && + (!pattern.constantOr(1) && + color.constantOr(Color.transparent).a === 1 && + opacity.constantOr(0) === 1) ? 'opaque' : 'translucent'; + // Draw fill + if (painter.renderPass === pass) { + const depthMode = painter.depthModeForSublayer(1, painter.renderPass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly); + drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, false); + } + // Draw stroke + if (painter.renderPass === 'translucent' && layer.paint.get('fill-antialias')) { + // If we defined a different color for the fill outline, we are + // going to ignore the bits in 0x07 and just care about the global + // clipping mask. + // Otherwise, we only want to drawFill the antialiased parts that are + // *outside* the current shape. This is important in case the fill + // or stroke color is translucent. If we wouldn't clip to outside + // the current shape, some pixels from the outline stroke overlapped + // the (non-antialiased) fill. + const depthMode = painter.depthModeForSublayer(layer.getPaintProperty('fill-outline-color') ? 2 : 0, DepthMode.ReadOnly); + drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, true); + } +} +function drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, isOutline) { + const gl = painter.context.gl; + const fillPropertyName = 'fill-pattern'; + const patternProperty = layer.paint.get(fillPropertyName); + const image = patternProperty && patternProperty.constantOr(1); + const crossfade = layer.getCrossfadeParameters(); + let drawMode, programName, uniformValues, indexBuffer, segments; + if (!isOutline) { + programName = image ? 'fillPattern' : 'fill'; + drawMode = gl.TRIANGLES; + } + else { + programName = image && !layer.getPaintProperty('fill-outline-color') ? 'fillOutlinePattern' : 'fillOutline'; + drawMode = gl.LINES; + } + const constantPattern = patternProperty.constantOr(null); + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + if (image && !tile.patternsLoaded()) + continue; + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram(programName, programConfiguration); + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + if (image) { + painter.context.activeTexture.set(gl.TEXTURE0); + tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + programConfiguration.updatePaintBuffers(crossfade); + } + updatePatternPositionsInProgram(programConfiguration, fillPropertyName, constantPattern, tile, layer); + const terrainCoord = terrainData ? coord : null; + const posMatrix = terrainCoord ? terrainCoord.posMatrix : coord.posMatrix; + const tileMatrix = painter.translatePosMatrix(posMatrix, tile, layer.paint.get('fill-translate'), layer.paint.get('fill-translate-anchor')); + if (!isOutline) { + indexBuffer = bucket.indexBuffer; + segments = bucket.segments; + uniformValues = image ? + fillPatternUniformValues(tileMatrix, painter, crossfade, tile) : + fillUniformValues(tileMatrix); + } + else { + indexBuffer = bucket.indexBuffer2; + segments = bucket.segments2; + const drawingBufferSize = [gl.drawingBufferWidth, gl.drawingBufferHeight]; + uniformValues = (programName === 'fillOutlinePattern' && image) ? + fillOutlinePatternUniformValues(tileMatrix, painter, crossfade, tile, drawingBufferSize) : + fillOutlineUniformValues(tileMatrix, drawingBufferSize); + } + program.draw(painter.context, drawMode, depthMode, painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, bucket.layoutVertexBuffer, indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration); + } +} + +function drawFillExtrusion(painter, source, layer, coords) { + const opacity = layer.paint.get('fill-extrusion-opacity'); + if (opacity === 0) { + return; + } + if (painter.renderPass === 'translucent') { + const depthMode = new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D); + if (opacity === 1 && !layer.paint.get('fill-extrusion-pattern').constantOr(1)) { + const colorMode = painter.colorModeForRenderPass(); + drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, colorMode); + } + else { + // Draw transparent buildings in two passes so that only the closest surface is drawn. + // First draw all the extrusions into only the depth buffer. No colors are drawn. + drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, ColorMode.disabled); + // Then draw all the extrusions a second type, only coloring fragments if they have the + // same depth value as the closest fragment in the previous pass. Use the stencil buffer + // to prevent the second draw in cases where we have coincident polygons. + drawExtrusionTiles(painter, source, layer, coords, depthMode, painter.stencilModeFor3D(), painter.colorModeForRenderPass()); + } + } +} +function drawExtrusionTiles(painter, source, layer, coords, depthMode, stencilMode, colorMode) { + const context = painter.context; + const gl = context.gl; + const fillPropertyName = 'fill-extrusion-pattern'; + const patternProperty = layer.paint.get(fillPropertyName); + const image = patternProperty.constantOr(1); + const crossfade = layer.getCrossfadeParameters(); + const opacity = layer.paint.get('fill-extrusion-opacity'); + const constantPattern = patternProperty.constantOr(null); + for (const coord of coords) { + const tile = source.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram(image ? 'fillExtrusionPattern' : 'fillExtrusion', programConfiguration); + if (image) { + painter.context.activeTexture.set(gl.TEXTURE0); + tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + programConfiguration.updatePaintBuffers(crossfade); + } + updatePatternPositionsInProgram(programConfiguration, fillPropertyName, constantPattern, tile, layer); + const matrix = painter.translatePosMatrix(coord.posMatrix, tile, layer.paint.get('fill-extrusion-translate'), layer.paint.get('fill-extrusion-translate-anchor')); + const shouldUseVerticalGradient = layer.paint.get('fill-extrusion-vertical-gradient'); + const uniformValues = image ? + fillExtrusionPatternUniformValues(matrix, painter, shouldUseVerticalGradient, opacity, coord, crossfade, tile) : + fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity); + program.draw(context, context.gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration, painter.style.map.terrain && bucket.centroidVertexBuffer); + } +} + +function drawHillshade(painter, sourceCache, layer, tileIDs) { + if (painter.renderPass !== 'offscreen' && painter.renderPass !== 'translucent') + return; + const context = painter.context; + const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly); + const colorMode = painter.colorModeForRenderPass(); + const [stencilModes, coords] = painter.renderPass === 'translucent' ? + painter.stencilConfigForOverlap(tileIDs) : [{}, tileIDs]; + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + if (typeof tile.needsHillshadePrepare !== 'undefined' && tile.needsHillshadePrepare && painter.renderPass === 'offscreen') { + prepareHillshade(painter, tile, layer, depthMode, StencilMode.disabled, colorMode); + } + else if (painter.renderPass === 'translucent') { + renderHillshade(painter, coord, tile, layer, depthMode, stencilModes[coord.overscaledZ], colorMode); + } + } + context.viewport.set([0, 0, painter.width, painter.height]); +} +function renderHillshade(painter, coord, tile, layer, depthMode, stencilMode, colorMode) { + const context = painter.context; + const gl = context.gl; + const fbo = tile.fbo; + if (!fbo) + return; + const program = painter.useProgram('hillshade'); + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get()); + const terrainCoord = terrainData ? coord : null; + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, hillshadeUniformValues(painter, tile, layer, terrainCoord), terrainData, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments); +} +// hillshade rendering is done in two steps. the prepare step first calculates the slope of the terrain in the x and y +// directions for each pixel, and saves those values to a framebuffer texture in the r and g channels. +function prepareHillshade(painter, tile, layer, depthMode, stencilMode, colorMode) { + const context = painter.context; + const gl = context.gl; + const dem = tile.dem; + if (dem && dem.data) { + const tileSize = dem.dim; + const textureStride = dem.stride; + const pixelData = dem.getPixels(); + context.activeTexture.set(gl.TEXTURE1); + context.pixelStoreUnpackPremultiplyAlpha.set(false); + tile.demTexture = tile.demTexture || painter.getTileTexture(textureStride); + if (tile.demTexture) { + const demTexture = tile.demTexture; + demTexture.update(pixelData, { premultiply: false }); + demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE); + } + else { + tile.demTexture = new Texture(context, pixelData, gl.RGBA, { premultiply: false }); + tile.demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE); + } + context.activeTexture.set(gl.TEXTURE0); + let fbo = tile.fbo; + if (!fbo) { + const renderTexture = new Texture(context, { width: tileSize, height: tileSize, data: null }, gl.RGBA); + renderTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + fbo = tile.fbo = context.createFramebuffer(tileSize, tileSize, true, false); + fbo.colorAttachment.set(renderTexture.texture); + } + context.bindFramebuffer.set(fbo.framebuffer); + context.viewport.set([0, 0, tileSize, tileSize]); + painter.useProgram('hillshadePrepare').draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, hillshadeUniformPrepareValues(tile.tileID, dem), null, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments); + tile.needsHillshadePrepare = false; + } +} + +function drawRaster(painter, sourceCache, layer, tileIDs) { + if (painter.renderPass !== 'translucent') + return; + if (layer.paint.get('raster-opacity') === 0) + return; + if (!tileIDs.length) + return; + const context = painter.context; + const gl = context.gl; + const source = sourceCache.getSource(); + const program = painter.useProgram('raster'); + const colorMode = painter.colorModeForRenderPass(); + const [stencilModes, coords] = source instanceof ImageSource ? [{}, tileIDs] : + painter.stencilConfigForOverlap(tileIDs); + const minTileZ = coords[coords.length - 1].overscaledZ; + const align = !painter.options.moving; + for (const coord of coords) { + // Set the lower zoom level to sublayer 0, and higher zoom levels to higher sublayers + // Use gl.LESS to prevent double drawing in areas where tiles overlap. + const depthMode = painter.depthModeForSublayer(coord.overscaledZ - minTileZ, layer.paint.get('raster-opacity') === 1 ? DepthMode.ReadWrite : DepthMode.ReadOnly, gl.LESS); + const tile = sourceCache.getTile(coord); + tile.registerFadeDuration(layer.paint.get('raster-fade-duration')); + const parentTile = sourceCache.findLoadedParent(coord, 0); + const siblingTile = sourceCache.findLoadedSibling(coord); + // Prefer parent tile if present + const fadeTileReference = parentTile || siblingTile || null; + const fade = getFadeValues(tile, fadeTileReference, sourceCache, layer, painter.transform, painter.style.map.terrain); + let parentScaleBy, parentTL; + const textureFilter = layer.paint.get('raster-resampling') === 'nearest' ? gl.NEAREST : gl.LINEAR; + context.activeTexture.set(gl.TEXTURE0); + tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST); + context.activeTexture.set(gl.TEXTURE1); + if (parentTile) { + parentTile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST); + parentScaleBy = Math.pow(2, parentTile.tileID.overscaledZ - tile.tileID.overscaledZ); + parentTL = [tile.tileID.canonical.x * parentScaleBy % 1, tile.tileID.canonical.y * parentScaleBy % 1]; + } + else { + tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST); + } + // Enable anisotropic filtering only when the pitch is greater than 20 degrees + // to preserve image sharpness on flat or slightly tilted maps. + if (tile.texture.useMipmap && context.extTextureFilterAnisotropic && painter.transform.pitch > 20) { + gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax); + } + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + const terrainCoord = terrainData ? coord : null; + const posMatrix = terrainCoord ? terrainCoord.posMatrix : painter.transform.calculatePosMatrix(coord.toUnwrapped(), align); + const uniformValues = rasterUniformValues(posMatrix, parentTL || [0, 0], parentScaleBy || 1, fade, layer); + if (source instanceof ImageSource) { + program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, source.boundsBuffer, painter.quadTriangleIndexBuffer, source.boundsSegments); + } + else { + program.draw(context, gl.TRIANGLES, depthMode, stencilModes[coord.overscaledZ], colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments); + } + } +} +function getFadeValues(tile, parentTile, sourceCache, layer, transform, terrain) { + const fadeDuration = layer.paint.get('raster-fade-duration'); + if (!terrain && fadeDuration > 0) { + const now = browser.now(); + const sinceTile = (now - tile.timeAdded) / fadeDuration; + const sinceParent = parentTile ? (now - parentTile.timeAdded) / fadeDuration : -1; + const source = sourceCache.getSource(); + const idealZ = transform.coveringZoomLevel({ + tileSize: source.tileSize, + roundZoom: source.roundZoom + }); + // if no parent or parent is older, fade in; if parent is younger, fade out + const fadeIn = !parentTile || Math.abs(parentTile.tileID.overscaledZ - idealZ) > Math.abs(tile.tileID.overscaledZ - idealZ); + const childOpacity = (fadeIn && tile.refreshedUponExpiration) ? 1 : clamp$1(fadeIn ? sinceTile : 1 - sinceParent, 0, 1); + // we don't crossfade tiles that were just refreshed upon expiring: + // once they're old enough to pass the crossfading threshold + // (fadeDuration), unset the `refreshedUponExpiration` flag so we don't + // incorrectly fail to crossfade them when zooming + if (tile.refreshedUponExpiration && sinceTile >= 1) + tile.refreshedUponExpiration = false; + if (parentTile) { + return { + opacity: 1, + mix: 1 - childOpacity + }; + } + else { + return { + opacity: childOpacity, + mix: 0 + }; + } + } + else { + return { + opacity: 1, + mix: 0 + }; + } +} + +function drawBackground(painter, sourceCache, layer, coords) { + const color = layer.paint.get('background-color'); + const opacity = layer.paint.get('background-opacity'); + if (opacity === 0) + return; + const context = painter.context; + const gl = context.gl; + const transform = painter.transform; + const tileSize = transform.tileSize; + const image = layer.paint.get('background-pattern'); + if (painter.isPatternMissing(image)) + return; + const pass = (!image && color.a === 1 && opacity === 1 && painter.opaquePassEnabledForLayer()) ? 'opaque' : 'translucent'; + if (painter.renderPass !== pass) + return; + const stencilMode = StencilMode.disabled; + const depthMode = painter.depthModeForSublayer(0, pass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly); + const colorMode = painter.colorModeForRenderPass(); + const program = painter.useProgram(image ? 'backgroundPattern' : 'background'); + const tileIDs = coords ? coords : transform.coveringTiles({ tileSize, terrain: painter.style.map.terrain }); + if (image) { + context.activeTexture.set(gl.TEXTURE0); + painter.imageManager.bind(painter.context); + } + const crossfade = layer.getCrossfadeParameters(); + for (const tileID of tileIDs) { + const matrix = coords ? tileID.posMatrix : painter.transform.calculatePosMatrix(tileID.toUnwrapped()); + const uniformValues = image ? + backgroundPatternUniformValues(matrix, opacity, painter, image, { tileID, tileSize }, crossfade) : + backgroundUniformValues(matrix, opacity, color); + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(tileID); + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, painter.tileExtentBuffer, painter.quadTriangleIndexBuffer, painter.tileExtentSegments); + } +} + +const topColor = new Color(1, 0, 0, 1); +const btmColor = new Color(0, 1, 0, 1); +const leftColor = new Color(0, 0, 1, 1); +const rightColor = new Color(1, 0, 1, 1); +const centerColor = new Color(0, 1, 1, 1); +function drawDebugPadding(painter) { + const padding = painter.transform.padding; + const lineWidth = 3; + // Top + drawHorizontalLine(painter, painter.transform.height - (padding.top || 0), lineWidth, topColor); + // Bottom + drawHorizontalLine(painter, padding.bottom || 0, lineWidth, btmColor); + // Left + drawVerticalLine(painter, padding.left || 0, lineWidth, leftColor); + // Right + drawVerticalLine(painter, painter.transform.width - (padding.right || 0), lineWidth, rightColor); + // Center + const center = painter.transform.centerPoint; + drawCrosshair(painter, center.x, painter.transform.height - center.y, centerColor); +} +function drawCrosshair(painter, x, y, color) { + const size = 20; + const lineWidth = 2; + //Vertical line + drawDebugSSRect(painter, x - lineWidth / 2, y - size / 2, lineWidth, size, color); + //Horizontal line + drawDebugSSRect(painter, x - size / 2, y - lineWidth / 2, size, lineWidth, color); +} +function drawHorizontalLine(painter, y, lineWidth, color) { + drawDebugSSRect(painter, 0, y + lineWidth / 2, painter.transform.width, lineWidth, color); +} +function drawVerticalLine(painter, x, lineWidth, color) { + drawDebugSSRect(painter, x - lineWidth / 2, 0, lineWidth, painter.transform.height, color); +} +function drawDebugSSRect(painter, x, y, width, height, color) { + const context = painter.context; + const gl = context.gl; + gl.enable(gl.SCISSOR_TEST); + gl.scissor(x * painter.pixelRatio, y * painter.pixelRatio, width * painter.pixelRatio, height * painter.pixelRatio); + context.clear({ color }); + gl.disable(gl.SCISSOR_TEST); +} +function drawDebug(painter, sourceCache, coords) { + for (let i = 0; i < coords.length; i++) { + drawDebugTile(painter, sourceCache, coords[i]); + } +} +function drawDebugTile(painter, sourceCache, coord) { + const context = painter.context; + const gl = context.gl; + const posMatrix = coord.posMatrix; + const program = painter.useProgram('debug'); + const depthMode = DepthMode.disabled; + const stencilMode = StencilMode.disabled; + const colorMode = painter.colorModeForRenderPass(); + const id = '$debug'; + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + context.activeTexture.set(gl.TEXTURE0); + const tileRawData = sourceCache.getTileByID(coord.key).latestRawTileData; + const tileByteLength = (tileRawData && tileRawData.byteLength) || 0; + const tileSizeKb = Math.floor(tileByteLength / 1024); + const tileSize = sourceCache.getTile(coord).tileSize; + const scaleRatio = (512 / Math.min(tileSize, 512) * (coord.overscaledZ / painter.transform.zoom)) * 0.5; + let tileIdText = coord.canonical.toString(); + if (coord.overscaledZ !== coord.canonical.z) { + tileIdText += ` => ${coord.overscaledZ}`; + } + const tileLabel = `${tileIdText} ${tileSizeKb}kB`; + drawTextToOverlay(painter, tileLabel); + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, ColorMode.alphaBlended, CullFaceMode.disabled, debugUniformValues(posMatrix, Color.transparent, scaleRatio), null, id, painter.debugBuffer, painter.quadTriangleIndexBuffer, painter.debugSegments); + program.draw(context, gl.LINE_STRIP, depthMode, stencilMode, colorMode, CullFaceMode.disabled, debugUniformValues(posMatrix, Color.red), terrainData, id, painter.debugBuffer, painter.tileBorderIndexBuffer, painter.debugSegments); +} +function drawTextToOverlay(painter, text) { + painter.initDebugOverlayCanvas(); + const canvas = painter.debugOverlayCanvas; + const gl = painter.context.gl; + const ctx2d = painter.debugOverlayCanvas.getContext('2d'); + ctx2d.clearRect(0, 0, canvas.width, canvas.height); + ctx2d.shadowColor = 'white'; + ctx2d.shadowBlur = 2; + ctx2d.lineWidth = 1.5; + ctx2d.strokeStyle = 'white'; + ctx2d.textBaseline = 'top'; + ctx2d.font = `bold ${36}px Open Sans, sans-serif`; + ctx2d.fillText(text, 5, 5); + ctx2d.strokeText(text, 5, 5); + painter.debugOverlayTexture.update(canvas); + painter.debugOverlayTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); +} +function selectDebugSource(style, zoom) { + // Use vector source with highest maxzoom + // Else use source with highest maxzoom of any type + let selectedSource = null; + const layers = Object.values(style._layers); + const sources = layers.flatMap((layer) => { + if (layer.source && !layer.isHidden(zoom)) { + const sourceCache = style.sourceCaches[layer.source]; + return [sourceCache]; + } + else { + return []; + } + }); + const vectorSources = sources.filter((source) => source.getSource().type === 'vector'); + const otherSources = sources.filter((source) => source.getSource().type !== 'vector'); + const considerSource = (source) => { + if (!selectedSource || (selectedSource.getSource().maxzoom < source.getSource().maxzoom)) { + selectedSource = source; + } + }; + vectorSources.forEach((source) => considerSource(source)); + if (!selectedSource) { + otherSources.forEach((source) => considerSource(source)); + } + return selectedSource; +} + +function drawCustom(painter, sourceCache, layer) { + const context = painter.context; + const implementation = layer.implementation; + if (painter.renderPass === 'offscreen') { + const prerender = implementation.prerender; + if (prerender) { + painter.setCustomLayerDefaults(); + context.setColorMode(painter.colorModeForRenderPass()); + prerender.call(implementation, context.gl, painter.transform.customLayerMatrix()); + context.setDirty(); + painter.setBaseState(); + } + } + else if (painter.renderPass === 'translucent') { + painter.setCustomLayerDefaults(); + context.setColorMode(painter.colorModeForRenderPass()); + context.setStencilMode(StencilMode.disabled); + const depthMode = implementation.renderingMode === '3d' ? + new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D) : + painter.depthModeForSublayer(0, DepthMode.ReadOnly); + context.setDepthMode(depthMode); + implementation.render(context.gl, painter.transform.customLayerMatrix(), { farZ: painter.transform.farZ, nearZ: painter.transform.nearZ, fov: painter.transform._fov, modelViewProjectionMatrix: painter.transform.modelViewProjectionMatrix, projectionMatrix: painter.transform.projectionMatrix }); + context.setDirty(); + painter.setBaseState(); + context.bindFramebuffer.set(null); + } +} + +/** + * Redraw the Depth Framebuffer + * @param painter - the painter + * @param terrain - the terrain + */ +function drawDepth(painter, terrain) { + const context = painter.context; + const gl = context.gl; + const colorMode = ColorMode.unblended; + const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]); + const mesh = terrain.getTerrainMesh(); + const tiles = terrain.sourceCache.getRenderableTiles(); + const program = painter.useProgram('terrainDepth'); + context.bindFramebuffer.set(terrain.getFramebuffer('depth').framebuffer); + context.viewport.set([0, 0, painter.width / devicePixelRatio, painter.height / devicePixelRatio]); + context.clear({ color: Color.transparent, depth: 1 }); + for (const tile of tiles) { + const terrainData = terrain.getTerrainData(tile.tileID); + const posMatrix = painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped()); + const uniformValues = terrainDepthUniformValues(posMatrix, terrain.getMeshFrameDelta(painter.transform.zoom)); + program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments); + } + context.bindFramebuffer.set(null); + context.viewport.set([0, 0, painter.width, painter.height]); +} +/** + * Redraw the Coords Framebuffers + * @param painter - the painter + * @param terrain - the terrain + */ +function drawCoords(painter, terrain) { + const context = painter.context; + const gl = context.gl; + const colorMode = ColorMode.unblended; + const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]); + const mesh = terrain.getTerrainMesh(); + const coords = terrain.getCoordsTexture(); + const tiles = terrain.sourceCache.getRenderableTiles(); + // draw tile-coords into framebuffer + const program = painter.useProgram('terrainCoords'); + context.bindFramebuffer.set(terrain.getFramebuffer('coords').framebuffer); + context.viewport.set([0, 0, painter.width / devicePixelRatio, painter.height / devicePixelRatio]); + context.clear({ color: Color.transparent, depth: 1 }); + terrain.coordsIndex = []; + for (const tile of tiles) { + const terrainData = terrain.getTerrainData(tile.tileID); + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, coords.texture); + const posMatrix = painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped()); + const uniformValues = terrainCoordsUniformValues(posMatrix, 255 - terrain.coordsIndex.length, terrain.getMeshFrameDelta(painter.transform.zoom)); + program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments); + terrain.coordsIndex.push(tile.tileID.key); + } + context.bindFramebuffer.set(null); + context.viewport.set([0, 0, painter.width, painter.height]); +} +function drawTerrain(painter, terrain, tiles) { + const context = painter.context; + const gl = context.gl; + const colorMode = painter.colorModeForRenderPass(); + const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D); + const program = painter.useProgram('terrain'); + const mesh = terrain.getTerrainMesh(); + context.bindFramebuffer.set(null); + context.viewport.set([0, 0, painter.width, painter.height]); + for (const tile of tiles) { + const texture = painter.renderToTexture.getTexture(tile); + const terrainData = terrain.getTerrainData(tile.tileID); + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + const posMatrix = painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped()); + const eleDelta = terrain.getMeshFrameDelta(painter.transform.zoom); + const fogMatrix = painter.transform.calculateFogMatrix(tile.tileID.toUnwrapped()); + const uniformValues = terrainUniformValues(posMatrix, eleDelta, fogMatrix, painter.style.sky, painter.transform.pitch); + program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments); + } +} + +class Mesh { + constructor(vertexBuffer, indexBuffer, segments) { + this.vertexBuffer = vertexBuffer; + this.indexBuffer = indexBuffer; + this.segments = segments; + } + destroy() { + this.vertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.segments.destroy(); + this.vertexBuffer = null; + this.indexBuffer = null; + this.segments = null; + } +} + +function drawSky(painter, sky) { + const context = painter.context; + const gl = context.gl; + const skyUniforms = skyUniformValues(sky, painter.style.map.transform, painter.pixelRatio); + const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]); + const stencilMode = StencilMode.disabled; + const colorMode = painter.colorModeForRenderPass(); + const program = painter.useProgram('sky'); + if (!sky.mesh) { + const vertexArray = new PosArray(); + vertexArray.emplaceBack(-1, -1); + vertexArray.emplaceBack(1, -1); + vertexArray.emplaceBack(1, 1); + vertexArray.emplaceBack(-1, 1); + const indexArray = new TriangleIndexArray(); + indexArray.emplaceBack(0, 1, 2); + indexArray.emplaceBack(0, 2, 3); + sky.mesh = new Mesh(context.createVertexBuffer(vertexArray, posAttributes.members), context.createIndexBuffer(indexArray), SegmentVector.simpleSegment(0, 0, vertexArray.length, indexArray.length)); + } + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, skyUniforms, undefined, 'sky', sky.mesh.vertexBuffer, sky.mesh.indexBuffer, sky.mesh.segments); +} + +/** + * @internal + * Initialize a new painter object. + */ +class Painter { + constructor(gl, transform) { + this.context = new Context(gl); + this.transform = transform; + this._tileTextures = {}; + this.terrainFacilitator = { dirty: true, matrix: identity$2(new Float64Array(16)), renderTime: 0 }; + this.setup(); + // Within each layer there are multiple distinct z-planes that can be drawn to. + // This is implemented using the WebGL depth buffer. + this.numSublayers = SourceCache.maxUnderzooming + SourceCache.maxOverzooming + 1; + this.depthEpsilon = 1 / Math.pow(2, 16); + this.crossTileSymbolIndex = new CrossTileSymbolIndex(); + } + /* + * Update the GL viewport, projection matrix, and transforms to compensate + * for a new width and height value. + */ + resize(width, height, pixelRatio) { + this.width = Math.floor(width * pixelRatio); + this.height = Math.floor(height * pixelRatio); + this.pixelRatio = pixelRatio; + this.context.viewport.set([0, 0, this.width, this.height]); + if (this.style) { + for (const layerId of this.style._order) { + this.style._layers[layerId].resize(); + } + } + } + setup() { + const context = this.context; + const tileExtentArray = new PosArray(); + tileExtentArray.emplaceBack(0, 0); + tileExtentArray.emplaceBack(EXTENT, 0); + tileExtentArray.emplaceBack(0, EXTENT); + tileExtentArray.emplaceBack(EXTENT, EXTENT); + this.tileExtentBuffer = context.createVertexBuffer(tileExtentArray, posAttributes.members); + this.tileExtentSegments = SegmentVector.simpleSegment(0, 0, 4, 2); + const debugArray = new PosArray(); + debugArray.emplaceBack(0, 0); + debugArray.emplaceBack(EXTENT, 0); + debugArray.emplaceBack(0, EXTENT); + debugArray.emplaceBack(EXTENT, EXTENT); + this.debugBuffer = context.createVertexBuffer(debugArray, posAttributes.members); + this.debugSegments = SegmentVector.simpleSegment(0, 0, 4, 5); + const rasterBoundsArray = new RasterBoundsArray(); + rasterBoundsArray.emplaceBack(0, 0, 0, 0); + rasterBoundsArray.emplaceBack(EXTENT, 0, EXTENT, 0); + rasterBoundsArray.emplaceBack(0, EXTENT, 0, EXTENT); + rasterBoundsArray.emplaceBack(EXTENT, EXTENT, EXTENT, EXTENT); + this.rasterBoundsBuffer = context.createVertexBuffer(rasterBoundsArray, rasterBoundsAttributes.members); + this.rasterBoundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2); + const viewportArray = new PosArray(); + viewportArray.emplaceBack(0, 0); + viewportArray.emplaceBack(1, 0); + viewportArray.emplaceBack(0, 1); + viewportArray.emplaceBack(1, 1); + this.viewportBuffer = context.createVertexBuffer(viewportArray, posAttributes.members); + this.viewportSegments = SegmentVector.simpleSegment(0, 0, 4, 2); + const tileLineStripIndices = new LineStripIndexArray(); + tileLineStripIndices.emplaceBack(0); + tileLineStripIndices.emplaceBack(1); + tileLineStripIndices.emplaceBack(3); + tileLineStripIndices.emplaceBack(2); + tileLineStripIndices.emplaceBack(0); + this.tileBorderIndexBuffer = context.createIndexBuffer(tileLineStripIndices); + const quadTriangleIndices = new TriangleIndexArray(); + quadTriangleIndices.emplaceBack(0, 1, 2); + quadTriangleIndices.emplaceBack(2, 1, 3); + this.quadTriangleIndexBuffer = context.createIndexBuffer(quadTriangleIndices); + const gl = this.context.gl; + this.stencilClearMode = new StencilMode({ func: gl.ALWAYS, mask: 0 }, 0x0, 0xFF, gl.ZERO, gl.ZERO, gl.ZERO); + } + /* + * Reset the drawing canvas by clearing the stencil buffer so that we can draw + * new tiles at the same location, while retaining previously drawn pixels. + */ + clearStencil() { + const context = this.context; + const gl = context.gl; + this.nextStencilID = 1; + this.currentStencilSource = undefined; + // As a temporary workaround for https://github.com/mapbox/mapbox-gl-js/issues/5490, + // pending an upstream fix, we draw a fullscreen stencil=0 clipping mask here, + // effectively clearing the stencil buffer: once an upstream patch lands, remove + // this function in favor of context.clear({ stencil: 0x0 }) + const matrix = create$6(); + ortho(matrix, 0, this.width, this.height, 0, 0, 1); + scale$5(matrix, matrix, [gl.drawingBufferWidth, gl.drawingBufferHeight, 0]); + this.useProgram('clippingMask').draw(context, gl.TRIANGLES, DepthMode.disabled, this.stencilClearMode, ColorMode.disabled, CullFaceMode.disabled, clippingMaskUniformValues(matrix), null, '$clipping', this.viewportBuffer, this.quadTriangleIndexBuffer, this.viewportSegments); + } + _renderTileClippingMasks(layer, tileIDs) { + if (this.currentStencilSource === layer.source || !layer.isTileClipped() || !tileIDs || !tileIDs.length) + return; + this.currentStencilSource = layer.source; + const context = this.context; + const gl = context.gl; + if (this.nextStencilID + tileIDs.length > 256) { + // we'll run out of fresh IDs so we need to clear and start from scratch + this.clearStencil(); + } + context.setColorMode(ColorMode.disabled); + context.setDepthMode(DepthMode.disabled); + const program = this.useProgram('clippingMask'); + this._tileClippingMaskIDs = {}; + for (const tileID of tileIDs) { + const id = this._tileClippingMaskIDs[tileID.key] = this.nextStencilID++; + const terrainData = this.style.map.terrain && this.style.map.terrain.getTerrainData(tileID); + program.draw(context, gl.TRIANGLES, DepthMode.disabled, + // Tests will always pass, and ref value will be written to stencil buffer. + new StencilMode({ func: gl.ALWAYS, mask: 0 }, id, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE), ColorMode.disabled, CullFaceMode.disabled, clippingMaskUniformValues(tileID.posMatrix), terrainData, '$clipping', this.tileExtentBuffer, this.quadTriangleIndexBuffer, this.tileExtentSegments); + } + } + stencilModeFor3D() { + this.currentStencilSource = undefined; + if (this.nextStencilID + 1 > 256) { + this.clearStencil(); + } + const id = this.nextStencilID++; + const gl = this.context.gl; + return new StencilMode({ func: gl.NOTEQUAL, mask: 0xFF }, id, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE); + } + stencilModeForClipping(tileID) { + const gl = this.context.gl; + return new StencilMode({ func: gl.EQUAL, mask: 0xFF }, this._tileClippingMaskIDs[tileID.key], 0x00, gl.KEEP, gl.KEEP, gl.REPLACE); + } + /* + * Sort coordinates by Z as drawing tiles is done in Z-descending order. + * All children with the same Z write the same stencil value. Children + * stencil values are greater than parent's. This is used only for raster + * and raster-dem tiles, which are already clipped to tile boundaries, to + * mask area of tile overlapped by children tiles. + * Stencil ref values continue range used in _tileClippingMaskIDs. + * + * Returns [StencilMode for tile overscaleZ map, sortedCoords]. + */ + stencilConfigForOverlap(tileIDs) { + const gl = this.context.gl; + const coords = tileIDs.sort((a, b) => b.overscaledZ - a.overscaledZ); + const minTileZ = coords[coords.length - 1].overscaledZ; + const stencilValues = coords[0].overscaledZ - minTileZ + 1; + if (stencilValues > 1) { + this.currentStencilSource = undefined; + if (this.nextStencilID + stencilValues > 256) { + this.clearStencil(); + } + const zToStencilMode = {}; + for (let i = 0; i < stencilValues; i++) { + zToStencilMode[i + minTileZ] = new StencilMode({ func: gl.GEQUAL, mask: 0xFF }, i + this.nextStencilID, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE); + } + this.nextStencilID += stencilValues; + return [zToStencilMode, coords]; + } + return [{ [minTileZ]: StencilMode.disabled }, coords]; + } + colorModeForRenderPass() { + const gl = this.context.gl; + if (this._showOverdrawInspector) { + const numOverdrawSteps = 8; + const a = 1 / numOverdrawSteps; + return new ColorMode([gl.CONSTANT_COLOR, gl.ONE], new Color(a, a, a, 0), [true, true, true, true]); + } + else if (this.renderPass === 'opaque') { + return ColorMode.unblended; + } + else { + return ColorMode.alphaBlended; + } + } + depthModeForSublayer(n, mask, func) { + if (!this.opaquePassEnabledForLayer()) + return DepthMode.disabled; + const depth = 1 - ((1 + this.currentLayer) * this.numSublayers + n) * this.depthEpsilon; + return new DepthMode(func || this.context.gl.LEQUAL, mask, [depth, depth]); + } + /* + * The opaque pass and 3D layers both use the depth buffer. + * Layers drawn above 3D layers need to be drawn using the + * painter's algorithm so that they appear above 3D features. + * This returns true for layers that can be drawn using the + * opaque pass. + */ + opaquePassEnabledForLayer() { + return this.currentLayer < this.opaquePassCutoff; + } + render(style, options) { + this.style = style; + this.options = options; + this.lineAtlas = style.lineAtlas; + this.imageManager = style.imageManager; + this.glyphManager = style.glyphManager; + this.symbolFadeChange = style.placement.symbolFadeChange(browser.now()); + this.imageManager.beginFrame(); + const layerIds = this.style._order; + const sourceCaches = this.style.sourceCaches; + const coordsAscending = {}; + const coordsDescending = {}; + const coordsDescendingSymbol = {}; + for (const id in sourceCaches) { + const sourceCache = sourceCaches[id]; + if (sourceCache.used) { + sourceCache.prepare(this.context); + } + coordsAscending[id] = sourceCache.getVisibleCoordinates(); + coordsDescending[id] = coordsAscending[id].slice().reverse(); + coordsDescendingSymbol[id] = sourceCache.getVisibleCoordinates(true).reverse(); + } + this.opaquePassCutoff = Infinity; + for (let i = 0; i < layerIds.length; i++) { + const layerId = layerIds[i]; + if (this.style._layers[layerId].is3D()) { + this.opaquePassCutoff = i; + break; + } + } + this.maybeDrawDepthAndCoords(false); + if (this.renderToTexture) { + this.renderToTexture.prepareForRender(this.style, this.transform.zoom); + // this is disabled, because render-to-texture is rendering all layers from bottom to top. + this.opaquePassCutoff = 0; + } + // Offscreen pass =============================================== + // We first do all rendering that requires rendering to a separate + // framebuffer, and then save those for rendering back to the map + // later: in doing this we avoid doing expensive framebuffer restores. + this.renderPass = 'offscreen'; + for (const layerId of layerIds) { + const layer = this.style._layers[layerId]; + if (!layer.hasOffscreenPass() || layer.isHidden(this.transform.zoom)) + continue; + const coords = coordsDescending[layer.source]; + if (layer.type !== 'custom' && !coords.length) + continue; + this.renderLayer(this, sourceCaches[layer.source], layer, coords); + } + // Rebind the main framebuffer now that all offscreen layers have been rendered: + this.context.bindFramebuffer.set(null); + // Clear buffers in preparation for drawing to the main framebuffer + this.context.clear({ color: options.showOverdrawInspector ? Color.black : Color.transparent, depth: 1 }); + this.clearStencil(); + // draw sky first to not overwrite symbols + if (this.style.sky) + drawSky(this, this.style.sky); + this._showOverdrawInspector = options.showOverdrawInspector; + this.depthRangeFor3D = [0, 1 - ((style._order.length + 2) * this.numSublayers * this.depthEpsilon)]; + // Opaque pass =============================================== + // Draw opaque layers top-to-bottom first. + if (!this.renderToTexture) { + this.renderPass = 'opaque'; + for (this.currentLayer = layerIds.length - 1; this.currentLayer >= 0; this.currentLayer--) { + const layer = this.style._layers[layerIds[this.currentLayer]]; + const sourceCache = sourceCaches[layer.source]; + const coords = coordsAscending[layer.source]; + this._renderTileClippingMasks(layer, coords); + this.renderLayer(this, sourceCache, layer, coords); + } + } + // Translucent pass =============================================== + // Draw all other layers bottom-to-top. + this.renderPass = 'translucent'; + for (this.currentLayer = 0; this.currentLayer < layerIds.length; this.currentLayer++) { + const layer = this.style._layers[layerIds[this.currentLayer]]; + const sourceCache = sourceCaches[layer.source]; + if (this.renderToTexture && this.renderToTexture.renderLayer(layer)) + continue; + // For symbol layers in the translucent pass, we add extra tiles to the renderable set + // for cross-tile symbol fading. Symbol layers don't use tile clipping, so no need to render + // separate clipping masks + const coords = (layer.type === 'symbol' ? coordsDescendingSymbol : coordsDescending)[layer.source]; + this._renderTileClippingMasks(layer, coordsAscending[layer.source]); + this.renderLayer(this, sourceCache, layer, coords); + } + if (this.options.showTileBoundaries) { + const selectedSource = selectDebugSource(this.style, this.transform.zoom); + if (selectedSource) { + drawDebug(this, selectedSource, selectedSource.getVisibleCoordinates()); + } + } + if (this.options.showPadding) { + drawDebugPadding(this); + } + // Set defaults for most GL values so that anyone using the state after the render + // encounters more expected values. + this.context.setDefault(); + } + /** + * Update the depth and coords framebuffers, if the contents of those frame buffers is out of date. + * If requireExact is false, then the contents of those frame buffers is not updated if it is close + * to accurate (that is, the camera has not moved much since it was updated last). + */ + maybeDrawDepthAndCoords(requireExact) { + if (!this.style || !this.style.map || !this.style.map.terrain) { + return; + } + const prevMatrix = this.terrainFacilitator.matrix; + const currMatrix = this.transform.modelViewProjectionMatrix; + // Update coords/depth-framebuffer on camera movement, or tile reloading + let doUpdate = this.terrainFacilitator.dirty; + doUpdate || (doUpdate = requireExact ? !exactEquals$5(prevMatrix, currMatrix) : !equals$6(prevMatrix, currMatrix)); + doUpdate || (doUpdate = this.style.map.terrain.sourceCache.tilesAfterTime(this.terrainFacilitator.renderTime).length > 0); + if (!doUpdate) { + return; + } + copy$5(prevMatrix, currMatrix); + this.terrainFacilitator.renderTime = Date.now(); + this.terrainFacilitator.dirty = false; + drawDepth(this, this.style.map.terrain); + drawCoords(this, this.style.map.terrain); + } + renderLayer(painter, sourceCache, layer, coords) { + if (layer.isHidden(this.transform.zoom)) + return; + if (layer.type !== 'background' && layer.type !== 'custom' && !(coords || []).length) + return; + this.id = layer.id; + switch (layer.type) { + case 'symbol': + drawSymbols(painter, sourceCache, layer, coords, this.style.placement.variableOffsets); + break; + case 'circle': + drawCircles(painter, sourceCache, layer, coords); + break; + case 'heatmap': + drawHeatmap(painter, sourceCache, layer, coords); + break; + case 'line': + drawLine(painter, sourceCache, layer, coords); + break; + case 'fill': + drawFill(painter, sourceCache, layer, coords); + break; + case 'fill-extrusion': + drawFillExtrusion(painter, sourceCache, layer, coords); + break; + case 'hillshade': + drawHillshade(painter, sourceCache, layer, coords); + break; + case 'raster': + drawRaster(painter, sourceCache, layer, coords); + break; + case 'background': + drawBackground(painter, sourceCache, layer, coords); + break; + case 'custom': + drawCustom(painter, sourceCache, layer); + break; + } + } + /** + * Transform a matrix to incorporate the *-translate and *-translate-anchor properties into it. + * @param inViewportPixelUnitsUnits - True when the units accepted by the matrix are in viewport pixels instead of tile units. + * @returns matrix + */ + translatePosMatrix(matrix, tile, translate, translateAnchor, inViewportPixelUnitsUnits) { + if (!translate[0] && !translate[1]) + return matrix; + const angle = inViewportPixelUnitsUnits ? + (translateAnchor === 'map' ? this.transform.angle : 0) : + (translateAnchor === 'viewport' ? -this.transform.angle : 0); + if (angle) { + const sinA = Math.sin(angle); + const cosA = Math.cos(angle); + translate = [ + translate[0] * cosA - translate[1] * sinA, + translate[0] * sinA + translate[1] * cosA + ]; + } + const translation = [ + inViewportPixelUnitsUnits ? translate[0] : pixelsToTileUnits(tile, translate[0], this.transform.zoom), + inViewportPixelUnitsUnits ? translate[1] : pixelsToTileUnits(tile, translate[1], this.transform.zoom), + 0 + ]; + const translatedMatrix = new Float32Array(16); + translate$1(translatedMatrix, matrix, translation); + return translatedMatrix; + } + saveTileTexture(texture) { + const textures = this._tileTextures[texture.size[0]]; + if (!textures) { + this._tileTextures[texture.size[0]] = [texture]; + } + else { + textures.push(texture); + } + } + getTileTexture(size) { + const textures = this._tileTextures[size]; + return textures && textures.length > 0 ? textures.pop() : null; + } + /** + * Checks whether a pattern image is needed, and if it is, whether it is not loaded. + * + * @returns true if a needed image is missing and rendering needs to be skipped. + */ + isPatternMissing(image) { + if (!image) + return false; + if (!image.from || !image.to) + return true; + const imagePosA = this.imageManager.getPattern(image.from.toString()); + const imagePosB = this.imageManager.getPattern(image.to.toString()); + return !imagePosA || !imagePosB; + } + useProgram(name, programConfiguration) { + this.cache = this.cache || {}; + const key = name + + (programConfiguration ? programConfiguration.cacheKey : '') + + (this._showOverdrawInspector ? '/overdraw' : '') + + (this.style.map.terrain ? '/terrain' : ''); + if (!this.cache[key]) { + this.cache[key] = new Program(this.context, shaders[name], programConfiguration, programUniforms[name], this._showOverdrawInspector, this.style.map.terrain); + } + return this.cache[key]; + } + /* + * Reset some GL state to default values to avoid hard-to-debug bugs + * in custom layers. + */ + setCustomLayerDefaults() { + // Prevent custom layers from unintentionally modify the last VAO used. + // All other state is state is restored on it's own, but for VAOs it's + // simpler to unbind so that we don't have to track the state of VAOs. + this.context.unbindVAO(); + // The default values for this state is meaningful and often expected. + // Leaving this state dirty could cause a lot of confusion for users. + this.context.cullFace.setDefault(); + this.context.activeTexture.setDefault(); + this.context.pixelStoreUnpack.setDefault(); + this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(); + this.context.pixelStoreUnpackFlipY.setDefault(); + } + /* + * Set GL state that is shared by all layers. + */ + setBaseState() { + const gl = this.context.gl; + this.context.cullFace.set(false); + this.context.viewport.set([0, 0, this.width, this.height]); + this.context.blendEquation.set(gl.FUNC_ADD); + } + initDebugOverlayCanvas() { + if (this.debugOverlayCanvas == null) { + this.debugOverlayCanvas = document.createElement('canvas'); + this.debugOverlayCanvas.width = 512; + this.debugOverlayCanvas.height = 512; + const gl = this.context.gl; + this.debugOverlayTexture = new Texture(this.context, this.debugOverlayCanvas, gl.RGBA); + } + } + destroy() { + if (this.debugOverlayTexture) { + this.debugOverlayTexture.destroy(); + } + } + /* + * Return true if drawing buffer size is != from requested size. + * That means that we've reached GL limits somehow. + * Note: drawing buffer size changes only when canvas size changes + */ + overLimit() { + const { drawingBufferWidth, drawingBufferHeight } = this.context.gl; + return this.width !== drawingBufferWidth || this.height !== drawingBufferHeight; + } +} + +class Frustum { + constructor(points, planes) { + this.points = points; + this.planes = planes; + } + static fromInvProjectionMatrix(invProj, worldSize, zoom) { + const clipSpaceCorners = [ + [-1, 1, -1, 1], + [1, 1, -1, 1], + [1, -1, -1, 1], + [-1, -1, -1, 1], + [-1, 1, 1, 1], + [1, 1, 1, 1], + [1, -1, 1, 1], + [-1, -1, 1, 1] + ]; + const scale = Math.pow(2, zoom); + // Transform frustum corner points from clip space to tile space, Z to meters + const frustumCoords = clipSpaceCorners.map(v => { + v = transformMat4$1([], v, invProj); + const s = 1.0 / v[3] / worldSize * scale; + return mul$3(v, v, [s, s, 1.0 / v[3], s]); + }); + const frustumPlanePointIndices = [ + [0, 1, 2], // near + [6, 5, 4], // far + [0, 3, 7], // left + [2, 1, 5], // right + [3, 2, 6], // bottom + [0, 4, 5] // top + ]; + const frustumPlanes = frustumPlanePointIndices.map((p) => { + const a = sub$2([], frustumCoords[p[0]], frustumCoords[p[1]]); + const b = sub$2([], frustumCoords[p[2]], frustumCoords[p[1]]); + const n = normalize$4([], cross$2([], a, b)); + const d = -dot$5(n, frustumCoords[p[1]]); + return n.concat(d); + }); + return new Frustum(frustumCoords, frustumPlanes); + } +} +class Aabb { + constructor(min_, max_) { + this.min = min_; + this.max = max_; + this.center = scale$4([], add$4([], this.min, this.max), 0.5); + } + quadrant(index) { + const split = [(index % 2) === 0, index < 2]; + const qMin = clone$4(this.min); + const qMax = clone$4(this.max); + for (let axis = 0; axis < split.length; axis++) { + qMin[axis] = split[axis] ? this.min[axis] : this.center[axis]; + qMax[axis] = split[axis] ? this.center[axis] : this.max[axis]; + } + // Elevation is always constant, hence quadrant.max.z = this.max.z + qMax[2] = this.max[2]; + return new Aabb(qMin, qMax); + } + distanceX(point) { + const pointOnAabb = Math.max(Math.min(this.max[0], point[0]), this.min[0]); + return pointOnAabb - point[0]; + } + distanceY(point) { + const pointOnAabb = Math.max(Math.min(this.max[1], point[1]), this.min[1]); + return pointOnAabb - point[1]; + } + // Performs a frustum-aabb intersection test. Returns 0 if there's no intersection, + // 1 if shapes are intersecting and 2 if the aabb if fully inside the frustum. + intersects(frustum) { + // Execute separating axis test between two convex objects to find intersections + // Each frustum plane together with 3 major axes define the separating axes + const aabbPoints = [ + [this.min[0], this.min[1], this.min[2], 1], + [this.max[0], this.min[1], this.min[2], 1], + [this.max[0], this.max[1], this.min[2], 1], + [this.min[0], this.max[1], this.min[2], 1], + [this.min[0], this.min[1], this.max[2], 1], + [this.max[0], this.min[1], this.max[2], 1], + [this.max[0], this.max[1], this.max[2], 1], + [this.min[0], this.max[1], this.max[2], 1] + ]; + let fullyInside = true; + for (let p = 0; p < frustum.planes.length; p++) { + const plane = frustum.planes[p]; + let pointsInside = 0; + for (let i = 0; i < aabbPoints.length; i++) { + if (dot$4(plane, aabbPoints[i]) >= 0) { + pointsInside++; + } + } + if (pointsInside === 0) + return 0; + if (pointsInside !== aabbPoints.length) + fullyInside = false; + } + if (fullyInside) + return 2; + for (let axis = 0; axis < 3; axis++) { + let projMin = Number.MAX_VALUE; + let projMax = -Number.MAX_VALUE; + for (let p = 0; p < frustum.points.length; p++) { + const projectedPoint = frustum.points[p][axis] - this.min[axis]; + projMin = Math.min(projMin, projectedPoint); + projMax = Math.max(projMax, projectedPoint); + } + if (projMax < 0 || projMin > this.max[axis] - this.min[axis]) + return 0; + } + return 1; + } +} + +/** + * An `EdgeInset` object represents screen space padding applied to the edges of the viewport. + * This shifts the apprent center or the vanishing point of the map. This is useful for adding floating UI elements + * on top of the map and having the vanishing point shift as UI elements resize. + * + * @group Geography and Geometry + */ +class EdgeInsets { + constructor(top = 0, bottom = 0, left = 0, right = 0) { + if (isNaN(top) || top < 0 || + isNaN(bottom) || bottom < 0 || + isNaN(left) || left < 0 || + isNaN(right) || right < 0) { + throw new Error('Invalid value for edge-insets, top, bottom, left and right must all be numbers'); + } + this.top = top; + this.bottom = bottom; + this.left = left; + this.right = right; + } + /** + * Interpolates the inset in-place. + * This maintains the current inset value for any inset not present in `target`. + * @param start - interpolation start + * @param target - interpolation target + * @param t - interpolation step/weight + * @returns the insets + */ + interpolate(start, target, t) { + if (target.top != null && start.top != null) + this.top = interpolate.number(start.top, target.top, t); + if (target.bottom != null && start.bottom != null) + this.bottom = interpolate.number(start.bottom, target.bottom, t); + if (target.left != null && start.left != null) + this.left = interpolate.number(start.left, target.left, t); + if (target.right != null && start.right != null) + this.right = interpolate.number(start.right, target.right, t); + return this; + } + /** + * Utility method that computes the new apprent center or vanishing point after applying insets. + * This is in pixels and with the top left being (0.0) and +y being downwards. + * + * @param width - the width + * @param height - the height + * @returns the point + */ + getCenter(width, height) { + // Clamp insets so they never overflow width/height and always calculate a valid center + const x = clamp$1((this.left + width - this.right) / 2, 0, width); + const y = clamp$1((this.top + height - this.bottom) / 2, 0, height); + return new Point$2(x, y); + } + equals(other) { + return this.top === other.top && + this.bottom === other.bottom && + this.left === other.left && + this.right === other.right; + } + clone() { + return new EdgeInsets(this.top, this.bottom, this.left, this.right); + } + /** + * Returns the current state as json, useful when you want to have a + * read-only representation of the inset. + * + * @returns state as json + */ + toJSON() { + return { + top: this.top, + bottom: this.bottom, + left: this.left, + right: this.right + }; + } +} + +const MAX_VALID_LATITUDE = 85.051129; +/** + * @internal + * A single transform, generally used for a single tile to be + * scaled, rotated, and zoomed. + */ +class Transform { + constructor(minZoom, maxZoom, minPitch, maxPitch, renderWorldCopies) { + this.tileSize = 512; // constant + this._renderWorldCopies = renderWorldCopies === undefined ? true : !!renderWorldCopies; + this._minZoom = minZoom || 0; + this._maxZoom = maxZoom || 22; + this._minPitch = (minPitch === undefined || minPitch === null) ? 0 : minPitch; + this._maxPitch = (maxPitch === undefined || maxPitch === null) ? 60 : maxPitch; + this.setMaxBounds(); + this.width = 0; + this.height = 0; + this._center = new LngLat(0, 0); + this._elevation = 0; + this.zoom = 0; + this.angle = 0; + this._fov = 0.6435011087932844; + this._pitch = 0; + this._unmodified = true; + this._edgeInsets = new EdgeInsets(); + this._posMatrixCache = {}; + this._alignedPosMatrixCache = {}; + this._fogMatrixCache = {}; + this.minElevationForCurrentTile = 0; + } + clone() { + const clone = new Transform(this._minZoom, this._maxZoom, this._minPitch, this.maxPitch, this._renderWorldCopies); + clone.apply(this); + return clone; + } + apply(that) { + this.tileSize = that.tileSize; + this.latRange = that.latRange; + this.lngRange = that.lngRange; + this.width = that.width; + this.height = that.height; + this._center = that._center; + this._elevation = that._elevation; + this.minElevationForCurrentTile = that.minElevationForCurrentTile; + this.zoom = that.zoom; + this.angle = that.angle; + this._fov = that._fov; + this._pitch = that._pitch; + this._unmodified = that._unmodified; + this._edgeInsets = that._edgeInsets.clone(); + this._calcMatrices(); + } + get minZoom() { return this._minZoom; } + set minZoom(zoom) { + if (this._minZoom === zoom) + return; + this._minZoom = zoom; + this.zoom = Math.max(this.zoom, zoom); + } + get maxZoom() { return this._maxZoom; } + set maxZoom(zoom) { + if (this._maxZoom === zoom) + return; + this._maxZoom = zoom; + this.zoom = Math.min(this.zoom, zoom); + } + get minPitch() { return this._minPitch; } + set minPitch(pitch) { + if (this._minPitch === pitch) + return; + this._minPitch = pitch; + this.pitch = Math.max(this.pitch, pitch); + } + get maxPitch() { return this._maxPitch; } + set maxPitch(pitch) { + if (this._maxPitch === pitch) + return; + this._maxPitch = pitch; + this.pitch = Math.min(this.pitch, pitch); + } + get renderWorldCopies() { return this._renderWorldCopies; } + set renderWorldCopies(renderWorldCopies) { + if (renderWorldCopies === undefined) { + renderWorldCopies = true; + } + else if (renderWorldCopies === null) { + renderWorldCopies = false; + } + this._renderWorldCopies = renderWorldCopies; + } + get worldSize() { + return this.tileSize * this.scale; + } + get centerOffset() { + return this.centerPoint._sub(this.size._div(2)); + } + get size() { + return new Point$2(this.width, this.height); + } + get bearing() { + return -this.angle / Math.PI * 180; + } + set bearing(bearing) { + const b = -wrap(bearing, -180, 180) * Math.PI / 180; + if (this.angle === b) + return; + this._unmodified = false; + this.angle = b; + this._calcMatrices(); + // 2x2 matrix for rotating points + this.rotationMatrix = create$9(); + rotate$4(this.rotationMatrix, this.rotationMatrix, this.angle); + } + get pitch() { + return this._pitch / Math.PI * 180; + } + set pitch(pitch) { + const p = clamp$1(pitch, this.minPitch, this.maxPitch) / 180 * Math.PI; + if (this._pitch === p) + return; + this._unmodified = false; + this._pitch = p; + this._calcMatrices(); + } + get fov() { + return this._fov / Math.PI * 180; + } + set fov(fov) { + fov = Math.max(0.01, Math.min(60, fov)); + if (this._fov === fov) + return; + this._unmodified = false; + this._fov = fov / 180 * Math.PI; + this._calcMatrices(); + } + get zoom() { return this._zoom; } + set zoom(zoom) { + const constrainedZoom = Math.min(Math.max(zoom, this.minZoom), this.maxZoom); + if (this._zoom === constrainedZoom) + return; + this._unmodified = false; + this._zoom = constrainedZoom; + this.tileZoom = Math.max(0, Math.floor(constrainedZoom)); + this.scale = this.zoomScale(constrainedZoom); + this._constrain(); + this._calcMatrices(); + } + get center() { return this._center; } + set center(center) { + if (center.lat === this._center.lat && center.lng === this._center.lng) + return; + this._unmodified = false; + this._center = center; + this._constrain(); + this._calcMatrices(); + } + /** + * Elevation at current center point, meters above sea level + */ + get elevation() { return this._elevation; } + set elevation(elevation) { + if (elevation === this._elevation) + return; + this._elevation = elevation; + this._constrain(); + this._calcMatrices(); + } + get padding() { return this._edgeInsets.toJSON(); } + set padding(padding) { + if (this._edgeInsets.equals(padding)) + return; + this._unmodified = false; + //Update edge-insets in place + this._edgeInsets.interpolate(this._edgeInsets, padding, 1); + this._calcMatrices(); + } + /** + * The center of the screen in pixels with the top-left corner being (0,0) + * and +y axis pointing downwards. This accounts for padding. + */ + get centerPoint() { + return this._edgeInsets.getCenter(this.width, this.height); + } + /** + * Returns if the padding params match + * + * @param padding - the padding to check against + * @returns true if they are equal, false otherwise + */ + isPaddingEqual(padding) { + return this._edgeInsets.equals(padding); + } + /** + * Helper method to update edge-insets in place + * + * @param start - the starting padding + * @param target - the target padding + * @param t - the step/weight + */ + interpolatePadding(start, target, t) { + this._unmodified = false; + this._edgeInsets.interpolate(start, target, t); + this._constrain(); + this._calcMatrices(); + } + /** + * Return a zoom level that will cover all tiles the transform + * @param options - the options + * @returns zoom level An integer zoom level at which all tiles will be visible. + */ + coveringZoomLevel(options) { + const z = (options.roundZoom ? Math.round : Math.floor)(this.zoom + this.scaleZoom(this.tileSize / options.tileSize)); + // At negative zoom levels load tiles from z0 because negative tile zoom levels don't exist. + return Math.max(0, z); + } + /** + * Return any "wrapped" copies of a given tile coordinate that are visible + * in the current view. + */ + getVisibleUnwrappedCoordinates(tileID) { + const result = [new UnwrappedTileID(0, tileID)]; + if (this._renderWorldCopies) { + const utl = this.pointCoordinate(new Point$2(0, 0)); + const utr = this.pointCoordinate(new Point$2(this.width, 0)); + const ubl = this.pointCoordinate(new Point$2(this.width, this.height)); + const ubr = this.pointCoordinate(new Point$2(0, this.height)); + const w0 = Math.floor(Math.min(utl.x, utr.x, ubl.x, ubr.x)); + const w1 = Math.floor(Math.max(utl.x, utr.x, ubl.x, ubr.x)); + // Add an extra copy of the world on each side to properly render ImageSources and CanvasSources. + // Both sources draw outside the tile boundaries of the tile that "contains them" so we need + // to add extra copies on both sides in case offscreen tiles need to draw into on-screen ones. + const extraWorldCopy = 1; + for (let w = w0 - extraWorldCopy; w <= w1 + extraWorldCopy; w++) { + if (w === 0) + continue; + result.push(new UnwrappedTileID(w, tileID)); + } + } + return result; + } + /** + * Return all coordinates that could cover this transform for a covering + * zoom level. + * @param options - the options + * @returns OverscaledTileIDs + */ + coveringTiles(options) { + var _a, _b; + let z = this.coveringZoomLevel(options); + const actualZ = z; + if (options.minzoom !== undefined && z < options.minzoom) + return []; + if (options.maxzoom !== undefined && z > options.maxzoom) + z = options.maxzoom; + const cameraCoord = this.pointCoordinate(this.getCameraPoint()); + const centerCoord = MercatorCoordinate.fromLngLat(this.center); + const numTiles = Math.pow(2, z); + const cameraPoint = [numTiles * cameraCoord.x, numTiles * cameraCoord.y, 0]; + const centerPoint = [numTiles * centerCoord.x, numTiles * centerCoord.y, 0]; + const cameraFrustum = Frustum.fromInvProjectionMatrix(this.invModelViewProjectionMatrix, this.worldSize, z); + // 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 + let minZoom = options.minzoom || 0; + // Use 0.1 as an epsilon to avoid for explicit == 0.0 floating point checks + if (!options.terrain && this.pitch <= 60.0 && this._edgeInsets.top < 0.1) + minZoom = z; + // There should always be a certain number of maximum zoom level tiles surrounding the center location in 2D or in front of the camera in 3D + const radiusOfMaxLvlLodInTiles = options.terrain ? 2 / Math.min(this.tileSize, options.tileSize) * this.tileSize : 3; + const newRootTile = (wrap) => { + return { + aabb: new Aabb([wrap * numTiles, 0, 0], [(wrap + 1) * numTiles, numTiles, 0]), + zoom: 0, + x: 0, + y: 0, + wrap, + fullyVisible: false + }; + }; + // Do a depth-first traversal to find visible tiles and proper levels of detail + const stack = []; + const result = []; + const maxZoom = z; + const overscaledZ = options.reparseOverscaled ? actualZ : z; + if (this._renderWorldCopies) { + // Render copy of the globe thrice on both sides + for (let i = 1; i <= 3; i++) { + stack.push(newRootTile(-i)); + stack.push(newRootTile(i)); + } + } + stack.push(newRootTile(0)); + while (stack.length > 0) { + const it = stack.pop(); + const x = it.x; + const y = it.y; + let fullyVisible = it.fullyVisible; + // Visibility of a tile is not required if any of its ancestor if fully inside the frustum + if (!fullyVisible) { + const intersectResult = it.aabb.intersects(cameraFrustum); + if (intersectResult === 0) + continue; + fullyVisible = intersectResult === 2; + } + const refPoint = options.terrain ? cameraPoint : centerPoint; + const distanceX = it.aabb.distanceX(refPoint); + const distanceY = it.aabb.distanceY(refPoint); + const longestDim = Math.max(Math.abs(distanceX), Math.abs(distanceY)); + // We're using distance based heuristics to determine if a tile should be split into quadrants or not. + // radiusOfMaxLvlLodInTiles defines that there's always a certain number of maxLevel tiles next to the map center. + // Using the fact that a parent node in quadtree is twice the size of its children (per dimension) + // we can define distance thresholds for each relative level: + // f(k) = offset + 2 + 4 + 8 + 16 + ... + 2^k. This is the same as "offset+2^(k+1)-2" + const distToSplit = radiusOfMaxLvlLodInTiles + (1 << (maxZoom - it.zoom)) - 2; + // Have we reached the target depth or is the tile too far away to be any split further? + if (it.zoom === maxZoom || (longestDim > distToSplit && it.zoom >= minZoom)) { + const dz = maxZoom - it.zoom, dx = cameraPoint[0] - 0.5 - (x << dz), dy = cameraPoint[1] - 0.5 - (y << dz); + result.push({ + tileID: new OverscaledTileID(it.zoom === maxZoom ? overscaledZ : it.zoom, it.wrap, it.zoom, x, y), + distanceSq: sqrLen([centerPoint[0] - 0.5 - x, centerPoint[1] - 0.5 - y]), + // this variable is currently not used, but may be important to reduce the amount of loaded tiles + tileDistanceToCamera: Math.sqrt(dx * dx + dy * dy) + }); + continue; + } + for (let i = 0; i < 4; i++) { + const childX = (x << 1) + (i % 2); + const childY = (y << 1) + (i >> 1); + const childZ = it.zoom + 1; + let quadrant = it.aabb.quadrant(i); + if (options.terrain) { + const tileID = new OverscaledTileID(childZ, it.wrap, childZ, childX, childY); + const minMax = options.terrain.getMinMaxElevation(tileID); + const minElevation = (_a = minMax.minElevation) !== null && _a !== void 0 ? _a : this.elevation; + const maxElevation = (_b = minMax.maxElevation) !== null && _b !== void 0 ? _b : this.elevation; + quadrant = new Aabb([quadrant.min[0], quadrant.min[1], minElevation], [quadrant.max[0], quadrant.max[1], maxElevation]); + } + stack.push({ aabb: quadrant, zoom: childZ, x: childX, y: childY, wrap: it.wrap, fullyVisible }); + } + } + return result.sort((a, b) => a.distanceSq - b.distanceSq).map(a => a.tileID); + } + resize(width, height) { + this.width = width; + this.height = height; + this.pixelsToGLUnits = [2 / width, -2 / height]; + this._constrain(); + this._calcMatrices(); + } + get unmodified() { return this._unmodified; } + zoomScale(zoom) { return Math.pow(2, zoom); } + scaleZoom(scale) { return Math.log(scale) / Math.LN2; } + /** + * Convert from LngLat to world coordinates (Mercator coordinates scaled by 512) + * @param lnglat - the lngLat + * @returns Point + */ + project(lnglat) { + const lat = clamp$1(lnglat.lat, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE); + return new Point$2(mercatorXfromLng(lnglat.lng) * this.worldSize, mercatorYfromLat(lat) * this.worldSize); + } + /** + * Convert from world coordinates ([0, 512],[0, 512]) to LngLat ([-180, 180], [-90, 90]) + * @param point - world coordinate + * @returns LngLat + */ + unproject(point) { + return new MercatorCoordinate(point.x / this.worldSize, point.y / this.worldSize).toLngLat(); + } + get point() { return this.project(this.center); } + /** + * get the camera position in LngLat and altitudes in meter + * @returns An object with lngLat & altitude. + */ + getCameraPosition() { + const lngLat = this.pointLocation(this.getCameraPoint()); + const altitude = Math.cos(this._pitch) * this.cameraToCenterDistance / this._pixelPerMeter; + return { lngLat, altitude: altitude + this.elevation }; + } + /** + * This method works in combination with freezeElevation activated. + * freezeElevation is enabled during map-panning because during this the camera should sit in constant height. + * After panning finished, call this method to recalculate the zoomlevel for the current camera-height in current terrain. + * @param terrain - the terrain + */ + recalculateZoom(terrain) { + const origElevation = this.elevation; + const origAltitude = Math.cos(this._pitch) * this.cameraToCenterDistance / this._pixelPerMeter; + // find position the camera is looking on + const center = this.pointLocation(this.centerPoint, terrain); + const elevation = terrain.getElevationForLngLatZoom(center, this.tileZoom); + const deltaElevation = this.elevation - elevation; + if (!deltaElevation) + return; + // The camera's altitude off the ground + the ground's elevation = a constant: + // this means the camera stays at the same total height. + const requiredAltitude = origAltitude + origElevation - elevation; + // Since altitude = Math.cos(this._pitch) * this.cameraToCenterDistance / pixelPerMeter: + const requiredPixelPerMeter = Math.cos(this._pitch) * this.cameraToCenterDistance / requiredAltitude; + // Since pixelPerMeter = mercatorZfromAltitude(1, center.lat) * worldSize: + const requiredWorldSize = requiredPixelPerMeter / mercatorZfromAltitude(1, center.lat); + // Since worldSize = this.tileSize * scale: + const requiredScale = requiredWorldSize / this.tileSize; + const zoom = this.scaleZoom(requiredScale); + // update matrices + this._elevation = elevation; + this._center = center; + this.zoom = zoom; + } + setLocationAtPoint(lnglat, point) { + const a = this.pointCoordinate(point); + const b = this.pointCoordinate(this.centerPoint); + const loc = this.locationCoordinate(lnglat); + const newCenter = new MercatorCoordinate(loc.x - (a.x - b.x), loc.y - (a.y - b.y)); + this.center = this.coordinateLocation(newCenter); + if (this._renderWorldCopies) { + this.center = this.center.wrap(); + } + } + /** + * Given a LngLat location, return the screen point that corresponds to it + * @param lnglat - location + * @param terrain - optional terrain + * @returns screen point + */ + locationPoint(lnglat, terrain) { + return terrain ? + this.coordinatePoint(this.locationCoordinate(lnglat), terrain.getElevationForLngLatZoom(lnglat, this.tileZoom), this.pixelMatrix3D) : + this.coordinatePoint(this.locationCoordinate(lnglat)); + } + /** + * Given a point on screen, return its lnglat + * @param p - screen point + * @param terrain - optional terrain + * @returns lnglat location + */ + pointLocation(p, terrain) { + return this.coordinateLocation(this.pointCoordinate(p, terrain)); + } + /** + * Given a geographical lnglat, return an unrounded + * coordinate that represents it at low zoom level. + * @param lnglat - the location + * @returns The mercator coordinate + */ + locationCoordinate(lnglat) { + return MercatorCoordinate.fromLngLat(lnglat); + } + /** + * Given a Coordinate, return its geographical position. + * @param coord - mercator coordinates + * @returns lng and lat + */ + coordinateLocation(coord) { + return coord && coord.toLngLat(); + } + /** + * Given a Point, return its mercator coordinate. + * @param p - the point + * @param terrain - optional terrain + * @returns lnglat + */ + pointCoordinate(p, terrain) { + // get point-coordinate from terrain coordinates framebuffer + if (terrain) { + const coordinate = terrain.pointCoordinate(p); + if (coordinate != null) { + return coordinate; + } + } + // calculate point-coordinate on flat earth + const targetZ = 0; + // since we don't know the correct projected z value for the point, + // unproject two points to get a line and then find the point on that + // line with z=0 + const coord0 = [p.x, p.y, 0, 1]; + const coord1 = [p.x, p.y, 1, 1]; + transformMat4$1(coord0, coord0, this.pixelMatrixInverse); + transformMat4$1(coord1, coord1, this.pixelMatrixInverse); + const w0 = coord0[3]; + const w1 = coord1[3]; + const x0 = coord0[0] / w0; + const x1 = coord1[0] / w1; + const y0 = coord0[1] / w0; + const y1 = coord1[1] / w1; + const z0 = coord0[2] / w0; + const z1 = coord1[2] / w1; + const t = z0 === z1 ? 0 : (targetZ - z0) / (z1 - z0); + return new MercatorCoordinate(interpolate.number(x0, x1, t) / this.worldSize, interpolate.number(y0, y1, t) / this.worldSize); + } + /** + * Given a coordinate, return the screen point that corresponds to it + * @param coord - the coordinates + * @param elevation - the elevation + * @param pixelMatrix - the pixel matrix + * @returns screen point + */ + coordinatePoint(coord, elevation = 0, pixelMatrix = this.pixelMatrix) { + const p = [coord.x * this.worldSize, coord.y * this.worldSize, elevation, 1]; + transformMat4$1(p, p, pixelMatrix); + return new Point$2(p[0] / p[3], p[1] / p[3]); + } + /** + * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not + * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region. + * @returns Returns a {@link LngLatBounds} object describing the map's geographical bounds. + */ + getBounds() { + const top = Math.max(0, this.height / 2 - this.getHorizon()); + return new LngLatBounds() + .extend(this.pointLocation(new Point$2(0, top))) + .extend(this.pointLocation(new Point$2(this.width, top))) + .extend(this.pointLocation(new Point$2(this.width, this.height))) + .extend(this.pointLocation(new Point$2(0, this.height))); + } + /** + * Returns the maximum geographical bounds the map is constrained to, or `null` if none set. + * @returns max bounds + */ + getMaxBounds() { + if (!this.latRange || this.latRange.length !== 2 || + !this.lngRange || this.lngRange.length !== 2) + return null; + return new LngLatBounds([this.lngRange[0], this.latRange[0]], [this.lngRange[1], this.latRange[1]]); + } + /** + * Calculate pixel height of the visible horizon in relation to map-center (e.g. height/2), + * multiplied by a static factor to simulate the earth-radius. + * The calculated value is the horizontal line from the camera-height to sea-level. + * @returns Horizon above center in pixels. + */ + getHorizon() { + return Math.tan(Math.PI / 2 - this._pitch) * this.cameraToCenterDistance * 0.85; + } + /** + * Sets or clears the map's geographical constraints. + * @param bounds - A {@link LngLatBounds} object describing the new geographic boundaries of the map. + */ + setMaxBounds(bounds) { + if (bounds) { + this.lngRange = [bounds.getWest(), bounds.getEast()]; + this.latRange = [bounds.getSouth(), bounds.getNorth()]; + this._constrain(); + } + else { + this.lngRange = null; + this.latRange = [-MAX_VALID_LATITUDE, MAX_VALID_LATITUDE]; + } + } + calculateTileMatrix(unwrappedTileID) { + const canonical = unwrappedTileID.canonical; + const scale = this.worldSize / this.zoomScale(canonical.z); + const unwrappedX = canonical.x + Math.pow(2, canonical.z) * unwrappedTileID.wrap; + const worldMatrix = identity$2(new Float64Array(16)); + translate$1(worldMatrix, worldMatrix, [unwrappedX * scale, canonical.y * scale, 0]); + scale$5(worldMatrix, worldMatrix, [scale / EXTENT, scale / EXTENT, 1]); + return worldMatrix; + } + /** + * Calculate the posMatrix that, given a tile coordinate, would be used to display the tile on a map. + * @param unwrappedTileID - the tile ID + */ + calculatePosMatrix(unwrappedTileID, aligned = false) { + const posMatrixKey = unwrappedTileID.key; + const cache = aligned ? this._alignedPosMatrixCache : this._posMatrixCache; + if (cache[posMatrixKey]) { + return cache[posMatrixKey]; + } + const posMatrix = this.calculateTileMatrix(unwrappedTileID); + multiply$5(posMatrix, aligned ? this.alignedModelViewProjectionMatrix : this.modelViewProjectionMatrix, posMatrix); + cache[posMatrixKey] = new Float32Array(posMatrix); + return cache[posMatrixKey]; + } + /** + * Calculate the fogMatrix that, given a tile coordinate, would be used to calculate fog on the map. + * @param unwrappedTileID - the tile ID + * @private + */ + calculateFogMatrix(unwrappedTileID) { + const posMatrixKey = unwrappedTileID.key; + const cache = this._fogMatrixCache; + if (cache[posMatrixKey]) { + return cache[posMatrixKey]; + } + const fogMatrix = this.calculateTileMatrix(unwrappedTileID); + multiply$5(fogMatrix, this.fogMatrix, fogMatrix); + cache[posMatrixKey] = new Float32Array(fogMatrix); + return cache[posMatrixKey]; + } + customLayerMatrix() { + return this.mercatorMatrix.slice(); + } + /** + * Get center lngLat and zoom to ensure that + * 1) everything beyond the bounds is excluded + * 2) a given lngLat is as near the center as possible + * Bounds are those set by maxBounds or North & South "Poles" and, if only 1 globe is displayed, antimeridian. + */ + getConstrained(lngLat, zoom) { + zoom = clamp$1(+zoom, this.minZoom, this.maxZoom); + const result = { + center: new LngLat(lngLat.lng, lngLat.lat), + zoom + }; + let lngRange = this.lngRange; + if (!this._renderWorldCopies && lngRange === null) { + const almost180 = 180 - 1e-10; + lngRange = [-almost180, almost180]; + } + const worldSize = this.tileSize * this.zoomScale(result.zoom); // A world size for the requested zoom level, not the current world size + let minY = 0; + let maxY = worldSize; + let minX = 0; + let maxX = worldSize; + let scaleY = 0; + let scaleX = 0; + const { x: screenWidth, y: screenHeight } = this.size; + if (this.latRange) { + const latRange = this.latRange; + minY = mercatorYfromLat(latRange[1]) * worldSize; + maxY = mercatorYfromLat(latRange[0]) * worldSize; + const shouldZoomIn = maxY - minY < screenHeight; + if (shouldZoomIn) + scaleY = screenHeight / (maxY - minY); + } + if (lngRange) { + minX = wrap(mercatorXfromLng(lngRange[0]) * worldSize, 0, worldSize); + maxX = wrap(mercatorXfromLng(lngRange[1]) * worldSize, 0, worldSize); + if (maxX < minX) + maxX += worldSize; + const shouldZoomIn = maxX - minX < screenWidth; + if (shouldZoomIn) + scaleX = screenWidth / (maxX - minX); + } + const { x: originalX, y: originalY } = this.project.call({ worldSize }, lngLat); + let modifiedX, modifiedY; + const scale = Math.max(scaleX || 0, scaleY || 0); + if (scale) { + // zoom in to exclude all beyond the given lng/lat ranges + const newPoint = new Point$2(scaleX ? (maxX + minX) / 2 : originalX, scaleY ? (maxY + minY) / 2 : originalY); + result.center = this.unproject.call({ worldSize }, newPoint).wrap(); + result.zoom += this.scaleZoom(scale); + return result; + } + if (this.latRange) { + const h2 = screenHeight / 2; + if (originalY - h2 < minY) + modifiedY = minY + h2; + if (originalY + h2 > maxY) + modifiedY = maxY - h2; + } + if (lngRange) { + const centerX = (minX + maxX) / 2; + let wrappedX = originalX; + if (this._renderWorldCopies) { + wrappedX = wrap(originalX, centerX - worldSize / 2, centerX + worldSize / 2); + } + const w2 = screenWidth / 2; + if (wrappedX - w2 < minX) + modifiedX = minX + w2; + if (wrappedX + w2 > maxX) + modifiedX = maxX - w2; + } + // pan the map if the screen goes off the range + if (modifiedX !== undefined || modifiedY !== undefined) { + const newPoint = new Point$2(modifiedX !== null && modifiedX !== void 0 ? modifiedX : originalX, modifiedY !== null && modifiedY !== void 0 ? modifiedY : originalY); + result.center = this.unproject.call({ worldSize }, newPoint).wrap(); + } + return result; + } + _constrain() { + if (!this.center || !this.width || !this.height || this._constraining) + return; + this._constraining = true; + const unmodified = this._unmodified; + const { center, zoom } = this.getConstrained(this.center, this.zoom); + this.center = center; + this.zoom = zoom; + this._unmodified = unmodified; + this._constraining = false; + } + _calcMatrices() { + if (!this.height) + return; + const halfFov = this._fov / 2; + const offset = this.centerOffset; + const x = this.point.x, y = this.point.y; + this.cameraToCenterDistance = 0.5 / Math.tan(halfFov) * this.height; + this._pixelPerMeter = mercatorZfromAltitude(1, this.center.lat) * this.worldSize; + let m = identity$2(new Float64Array(16)); + scale$5(m, m, [this.width / 2, -this.height / 2, 1]); + translate$1(m, m, [1, -1, 0]); + this.labelPlaneMatrix = m; + m = identity$2(new Float64Array(16)); + scale$5(m, m, [1, -1, 1]); + translate$1(m, m, [-1, -1, 0]); + scale$5(m, m, [2 / this.width, 2 / this.height, 1]); + this.glCoordMatrix = m; + // Calculate the camera to sea-level distance in pixel in respect of terrain + const cameraToSeaLevelDistance = this.cameraToCenterDistance + this._elevation * this._pixelPerMeter / Math.cos(this._pitch); + // In case of negative minimum elevation (e.g. the dead see, under the sea maps) use a lower plane for calculation + const minElevation = Math.min(this.elevation, this.minElevationForCurrentTile); + const cameraToLowestPointDistance = cameraToSeaLevelDistance - minElevation * this._pixelPerMeter / Math.cos(this._pitch); + const lowestPlane = minElevation < 0 ? cameraToLowestPointDistance : cameraToSeaLevelDistance; + // Find the distance from the center point [width/2 + offset.x, height/2 + offset.y] to the + // center top point [width/2 + offset.x, 0] in Z units, using the law of sines. + // 1 Z unit is equivalent to 1 horizontal px at the center of the map + // (the distance between[width/2, height/2] and [width/2 + 1, height/2]) + const groundAngle = Math.PI / 2 + this._pitch; + const fovAboveCenter = this._fov * (0.5 + offset.y / this.height); + const topHalfSurfaceDistance = Math.sin(fovAboveCenter) * lowestPlane / Math.sin(clamp$1(Math.PI - groundAngle - fovAboveCenter, 0.01, Math.PI - 0.01)); + // Find the distance from the center point to the horizon + const horizon = this.getHorizon(); + const horizonAngle = Math.atan(horizon / this.cameraToCenterDistance); + const fovCenterToHorizon = 2 * horizonAngle * (0.5 + offset.y / (horizon * 2)); + const topHalfSurfaceDistanceHorizon = Math.sin(fovCenterToHorizon) * lowestPlane / Math.sin(clamp$1(Math.PI - groundAngle - fovCenterToHorizon, 0.01, Math.PI - 0.01)); + // Calculate z distance of the farthest fragment that should be rendered. + // Add a bit extra to avoid precision problems when a fragment's distance is exactly `furthestDistance` + const topHalfMinDistance = Math.min(topHalfSurfaceDistance, topHalfSurfaceDistanceHorizon); + this.farZ = (Math.cos(Math.PI / 2 - this._pitch) * topHalfMinDistance + lowestPlane) * 1.01; + // The larger the value of nearZ is + // - the more depth precision is available for features (good) + // - clipping starts appearing sooner when the camera is close to 3d features (bad) + // + // Other values work for mapbox-gl-js but deck.gl was encountering precision issues + // when rendering custom layers. This value was experimentally chosen and + // seems to solve z-fighting issues in deck.gl while not clipping buildings too close to the camera. + this.nearZ = this.height / 50; + // matrix for conversion from location to clip space(-1 .. 1) + m = new Float64Array(16); + perspective(m, this._fov, this.width / this.height, this.nearZ, this.farZ); + // Apply center of perspective offset + m[8] = -offset.x * 2 / this.width; + m[9] = offset.y * 2 / this.height; + this.projectionMatrix = clone$5(m); + scale$5(m, m, [1, -1, 1]); + translate$1(m, m, [0, 0, -this.cameraToCenterDistance]); + rotateX$3(m, m, this._pitch); + rotateZ$3(m, m, this.angle); + translate$1(m, m, [-x, -y, 0]); + // The mercatorMatrix can be used to transform points from mercator coordinates + // ([0, 0] nw, [1, 1] se) to clip space. + this.mercatorMatrix = scale$5([], m, [this.worldSize, this.worldSize, this.worldSize]); + // scale vertically to meters per pixel (inverse of ground resolution): + scale$5(m, m, [1, 1, this._pixelPerMeter]); + // matrix for conversion from world space to screen coordinates in 2D + this.pixelMatrix = multiply$5(new Float64Array(16), this.labelPlaneMatrix, m); + // matrix for conversion from world space to clip space (-1 .. 1) + translate$1(m, m, [0, 0, -this.elevation]); // elevate camera over terrain + this.modelViewProjectionMatrix = m; + this.invModelViewProjectionMatrix = invert$2([], m); + // create a fog matrix, same es proj-matrix but with near clipping-plane in mapcenter + // needed to calculate a correct z-value for fog calculation, because projMatrix z value is not + this.fogMatrix = new Float64Array(16); + perspective(this.fogMatrix, this._fov, this.width / this.height, cameraToSeaLevelDistance, this.farZ); + this.fogMatrix[8] = -offset.x * 2 / this.width; + this.fogMatrix[9] = offset.y * 2 / this.height; + scale$5(this.fogMatrix, this.fogMatrix, [1, -1, 1]); + translate$1(this.fogMatrix, this.fogMatrix, [0, 0, -this.cameraToCenterDistance]); + rotateX$3(this.fogMatrix, this.fogMatrix, this._pitch); + rotateZ$3(this.fogMatrix, this.fogMatrix, this.angle); + translate$1(this.fogMatrix, this.fogMatrix, [-x, -y, 0]); + scale$5(this.fogMatrix, this.fogMatrix, [1, 1, this._pixelPerMeter]); + translate$1(this.fogMatrix, this.fogMatrix, [0, 0, -this.elevation]); // elevate camera over terrain + // matrix for conversion from world space to screen coordinates in 3D + this.pixelMatrix3D = multiply$5(new Float64Array(16), this.labelPlaneMatrix, m); + // Make a second projection matrix that is aligned to a pixel grid for rendering raster tiles. + // We're rounding the (floating point) x/y values to achieve to avoid rendering raster images to fractional + // coordinates. Additionally, we adjust by half a pixel in either direction in case that viewport dimension + // is an odd integer to preserve rendering to the pixel grid. We're rotating this shift based on the angle + // of the transformation so that 0°, 90°, 180°, and 270° rasters are crisp, and adjust the shift so that + // it is always <= 0.5 pixels. + const xShift = (this.width % 2) / 2, yShift = (this.height % 2) / 2, angleCos = Math.cos(this.angle), angleSin = Math.sin(this.angle), dx = x - Math.round(x) + angleCos * xShift + angleSin * yShift, dy = y - Math.round(y) + angleCos * yShift + angleSin * xShift; + const alignedM = new Float64Array(m); + translate$1(alignedM, alignedM, [dx > 0.5 ? dx - 1 : dx, dy > 0.5 ? dy - 1 : dy, 0]); + this.alignedModelViewProjectionMatrix = alignedM; + // inverse matrix for conversion from screen coordinates to location + m = invert$2(new Float64Array(16), this.pixelMatrix); + if (!m) + throw new Error('failed to invert matrix'); + this.pixelMatrixInverse = m; + this._posMatrixCache = {}; + this._alignedPosMatrixCache = {}; + this._fogMatrixCache = {}; + } + maxPitchScaleFactor() { + // calcMatrices hasn't run yet + if (!this.pixelMatrixInverse) + return 1; + const coord = this.pointCoordinate(new Point$2(0, 0)); + const p = [coord.x * this.worldSize, coord.y * this.worldSize, 0, 1]; + const topPoint = transformMat4$1(p, p, this.pixelMatrix); + return topPoint[3] / this.cameraToCenterDistance; + } + /** + * The camera looks at the map from a 3D (lng, lat, altitude) location. Let's use `cameraLocation` + * as the name for the location under the camera and on the surface of the earth (lng, lat, 0). + * `cameraPoint` is the projected position of the `cameraLocation`. + * + * This point is useful to us because only fill-extrusions that are between `cameraPoint` and + * the query point on the surface of the earth can extend and intersect the query. + * + * When the map is not pitched the `cameraPoint` is equivalent to the center of the map because + * the camera is right above the center of the map. + */ + getCameraPoint() { + const pitch = this._pitch; + const yOffset = Math.tan(pitch) * (this.cameraToCenterDistance || 1); + return this.centerPoint.add(new Point$2(0, yOffset)); + } + /** + * When the map is pitched, some of the 3D features that intersect a query will not intersect + * the query at the surface of the earth. Instead the feature may be closer and only intersect + * the query because it extrudes into the air. + * @param queryGeometry - For point queries, the line from the query point to the "camera point", + * for other geometries, the envelope of the query geometry and the "camera point" + * @returns a geometry that includes all of the original query as well as all possible ares of the + * screen where the *base* of a visible extrusion could be. + * + */ + getCameraQueryGeometry(queryGeometry) { + const c = this.getCameraPoint(); + if (queryGeometry.length === 1) { + return [queryGeometry[0], c]; + } + else { + let minX = c.x; + let minY = c.y; + let maxX = c.x; + let maxY = c.y; + for (const p of queryGeometry) { + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + return [ + new Point$2(minX, minY), + new Point$2(maxX, minY), + new Point$2(maxX, maxY), + new Point$2(minX, maxY), + new Point$2(minX, minY) + ]; + } + } + /** + * Return the distance to the camera in clip space from a LngLat. + * This can be compared to the value from the depth buffer (terrain.depthAtPoint) + * to determine whether a point is occluded. + * @param lngLat - the point + * @param elevation - the point's elevation + * @returns depth value in clip space (between 0 and 1) + */ + lngLatToCameraDepth(lngLat, elevation) { + const coord = this.locationCoordinate(lngLat); + const p = [coord.x * this.worldSize, coord.y * this.worldSize, elevation, 1]; + transformMat4$1(p, p, this.modelViewProjectionMatrix); + return (p[2] / p[3]); + } +} + +/** + * Throttle the given function to run at most every `period` milliseconds. + */ +function throttle(fn, time) { + let pending = false; + let timerId = null; + let lastCallContext = null; + let lastCallArgs; + const later = () => { + timerId = null; + if (pending) { + fn.apply(lastCallContext, lastCallArgs); + timerId = setTimeout(later, time); + pending = false; + } + }; + return (...args) => { + pending = true; + lastCallContext = this; + lastCallArgs = args; + if (!timerId) { + later(); + } + return timerId; + }; +} + +/** + * Adds the map's position to its page's location hash. + * Passed as an option to the map object. + * + * @group Markers and Controls + */ +class Hash { + constructor(hashName) { + this._getCurrentHash = () => { + // Get the current hash from location, stripped from its number sign + const hash = window.location.hash.replace('#', ''); + if (this._hashName) { + // Split the parameter-styled hash into parts and find the value we need + let keyval; + hash.split('&').map(part => part.split('=')).forEach(part => { + if (part[0] === this._hashName) { + keyval = part; + } + }); + return (keyval ? keyval[1] || '' : '').split('/'); + } + return hash.split('/'); + }; + this._onHashChange = () => { + const loc = this._getCurrentHash(); + if (loc.length >= 3 && !loc.some(v => isNaN(v))) { + const bearing = this._map.dragRotate.isEnabled() && this._map.touchZoomRotate.isEnabled() ? +(loc[3] || 0) : this._map.getBearing(); + this._map.jumpTo({ + center: [+loc[2], +loc[1]], + zoom: +loc[0], + bearing, + pitch: +(loc[4] || 0) + }); + return true; + } + return false; + }; + this._updateHashUnthrottled = () => { + // Replace if already present, else append the updated hash string + const location = window.location.href.replace(/(#.+)?$/, this.getHashString()); + window.history.replaceState(window.history.state, null, location); + }; + this._removeHash = () => { + const currentHash = this._getCurrentHash(); + if (currentHash.length === 0) { + return; + } + const baseHash = currentHash.join('/'); + let targetHash = baseHash; + if (targetHash.split('&').length > 0) { + targetHash = targetHash.split('&')[0]; // #3/1/2&foo=bar -> #3/1/2 + } + if (this._hashName) { + targetHash = `${this._hashName}=${baseHash}`; + } + let replaceString = window.location.hash.replace(targetHash, ''); + if (replaceString.startsWith('#&')) { + replaceString = replaceString.slice(0, 1) + replaceString.slice(2); + } + else if (replaceString === '#') { + replaceString = ''; + } + let location = window.location.href.replace(/(#.+)?$/, replaceString); + location = location.replace('&&', '&'); + window.history.replaceState(window.history.state, null, location); + }; + /** + * Mobile Safari doesn't allow updating the hash more than 100 times per 30 seconds. + */ + this._updateHash = throttle(this._updateHashUnthrottled, 30 * 1000 / 100); + this._hashName = hashName && encodeURIComponent(hashName); + } + /** + * Map element to listen for coordinate changes + * + * @param map - The map object + */ + addTo(map) { + this._map = map; + addEventListener('hashchange', this._onHashChange, false); + this._map.on('moveend', this._updateHash); + return this; + } + /** + * Removes hash + */ + remove() { + removeEventListener('hashchange', this._onHashChange, false); + this._map.off('moveend', this._updateHash); + clearTimeout(this._updateHash()); + this._removeHash(); + delete this._map; + return this; + } + getHashString(mapFeedback) { + const center = this._map.getCenter(), zoom = Math.round(this._map.getZoom() * 100) / 100, + // derived from equation: 512px * 2^z / 360 / 10^d < 0.5px + precision = Math.ceil((zoom * Math.LN2 + Math.log(512 / 360 / 0.5)) / Math.LN10), m = Math.pow(10, precision), lng = Math.round(center.lng * m) / m, lat = Math.round(center.lat * m) / m, bearing = this._map.getBearing(), pitch = this._map.getPitch(); + let hash = ''; + if (mapFeedback) { + // new map feedback site has some constraints that don't allow + // us to use the same hash format as we do for the Map hash option. + hash += `/${lng}/${lat}/${zoom}`; + } + else { + hash += `${zoom}/${lat}/${lng}`; + } + if (bearing || pitch) + hash += (`/${Math.round(bearing * 10) / 10}`); + if (pitch) + hash += (`/${Math.round(pitch)}`); + if (this._hashName) { + const hashName = this._hashName; + let found = false; + const parts = window.location.hash.slice(1).split('&').map(part => { + const key = part.split('=')[0]; + if (key === hashName) { + found = true; + return `${key}=${hash}`; + } + return part; + }).filter(a => a); + if (!found) { + parts.push(`${hashName}=${hash}`); + } + return `#${parts.join('&')}`; + } + return `#${hash}`; + } +} + +const defaultInertiaOptions = { + linearity: 0.3, + easing: bezier$1(0, 0, 0.3, 1), +}; +const defaultPanInertiaOptions = extend({ + deceleration: 2500, + maxSpeed: 1400 +}, defaultInertiaOptions); +const defaultZoomInertiaOptions = extend({ + deceleration: 20, + maxSpeed: 1400 +}, defaultInertiaOptions); +const defaultBearingInertiaOptions = extend({ + deceleration: 1000, + maxSpeed: 360 +}, defaultInertiaOptions); +const defaultPitchInertiaOptions = extend({ + deceleration: 1000, + maxSpeed: 90 +}, defaultInertiaOptions); +class HandlerInertia { + constructor(map) { + this._map = map; + this.clear(); + } + clear() { + this._inertiaBuffer = []; + } + record(settings) { + this._drainInertiaBuffer(); + this._inertiaBuffer.push({ time: browser.now(), settings }); + } + _drainInertiaBuffer() { + const inertia = this._inertiaBuffer, now = browser.now(), cutoff = 160; //msec + while (inertia.length > 0 && now - inertia[0].time > cutoff) + inertia.shift(); + } + _onMoveEnd(panInertiaOptions) { + this._drainInertiaBuffer(); + if (this._inertiaBuffer.length < 2) { + return; + } + const deltas = { + zoom: 0, + bearing: 0, + pitch: 0, + pan: new Point$2(0, 0), + pinchAround: undefined, + around: undefined + }; + for (const { settings } of this._inertiaBuffer) { + deltas.zoom += settings.zoomDelta || 0; + deltas.bearing += settings.bearingDelta || 0; + deltas.pitch += settings.pitchDelta || 0; + if (settings.panDelta) + deltas.pan._add(settings.panDelta); + if (settings.around) + deltas.around = settings.around; + if (settings.pinchAround) + deltas.pinchAround = settings.pinchAround; + } + const lastEntry = this._inertiaBuffer[this._inertiaBuffer.length - 1]; + const duration = (lastEntry.time - this._inertiaBuffer[0].time); + const easeOptions = {}; + if (deltas.pan.mag()) { + const result = calculateEasing(deltas.pan.mag(), duration, extend({}, defaultPanInertiaOptions, panInertiaOptions || {})); + easeOptions.offset = deltas.pan.mult(result.amount / deltas.pan.mag()); + easeOptions.center = this._map.transform.center; + extendDuration(easeOptions, result); + } + if (deltas.zoom) { + const result = calculateEasing(deltas.zoom, duration, defaultZoomInertiaOptions); + easeOptions.zoom = this._map.transform.zoom + result.amount; + extendDuration(easeOptions, result); + } + if (deltas.bearing) { + const result = calculateEasing(deltas.bearing, duration, defaultBearingInertiaOptions); + easeOptions.bearing = this._map.transform.bearing + clamp$1(result.amount, -179, 179); + extendDuration(easeOptions, result); + } + if (deltas.pitch) { + const result = calculateEasing(deltas.pitch, duration, defaultPitchInertiaOptions); + easeOptions.pitch = this._map.transform.pitch + result.amount; + extendDuration(easeOptions, result); + } + if (easeOptions.zoom || easeOptions.bearing) { + const last = deltas.pinchAround === undefined ? deltas.around : deltas.pinchAround; + easeOptions.around = last ? this._map.unproject(last) : this._map.getCenter(); + } + this.clear(); + return extend(easeOptions, { + noMoveStart: true + }); + } +} +// Unfortunately zoom, bearing, etc can't have different durations and easings so +// we need to choose one. We use the longest duration and it's corresponding easing. +function extendDuration(easeOptions, result) { + if (!easeOptions.duration || easeOptions.duration < result.duration) { + easeOptions.duration = result.duration; + easeOptions.easing = result.easing; + } +} +function calculateEasing(amount, inertiaDuration, inertiaOptions) { + const { maxSpeed, linearity, deceleration } = inertiaOptions; + const speed = clamp$1(amount * linearity / (inertiaDuration / 1000), -maxSpeed, maxSpeed); + const duration = Math.abs(speed) / (deceleration * linearity); + return { + easing: inertiaOptions.easing, + duration: duration * 1000, + amount: speed * (duration / 2) + }; +} + +/** + * `MapMouseEvent` is the event type for mouse-related map events. + * + * @group Event Related + * + * @example + * ```ts + * // The `click` event is an example of a `MapMouseEvent`. + * // Set up an event listener on the map. + * map.on('click', (e) => { + * // The event object (e) contains information like the + * // coordinates of the point on the map that was clicked. + * console.log('A click event has occurred at ' + e.lngLat); + * }); + * ``` + */ +class MapMouseEvent extends Event { + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the following default map behaviors: + * + * * On `mousedown` events, the behavior of {@link DragPanHandler} + * * On `mousedown` events, the behavior of {@link DragRotateHandler} + * * On `mousedown` events, the behavior of {@link BoxZoomHandler} + * * On `dblclick` events, the behavior of {@link DoubleClickZoomHandler} + * + */ + preventDefault() { + this._defaultPrevented = true; + } + /** + * `true` if `preventDefault` has been called. + */ + get defaultPrevented() { + return this._defaultPrevented; + } + constructor(type, map, originalEvent, data = {}) { + const point = DOM.mousePos(map.getCanvas(), originalEvent); + const lngLat = map.unproject(point); + super(type, extend({ point, lngLat, originalEvent }, data)); + this._defaultPrevented = false; + this.target = map; + } +} +/** + * `MapTouchEvent` is the event type for touch-related map events. + * + * @group Event Related + */ +class MapTouchEvent extends Event { + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the following default map behaviors: + * + * * On `touchstart` events, the behavior of {@link DragPanHandler} + * * On `touchstart` events, the behavior of {@link TwoFingersTouchZoomRotateHandler} + * + */ + preventDefault() { + this._defaultPrevented = true; + } + /** + * `true` if `preventDefault` has been called. + */ + get defaultPrevented() { + return this._defaultPrevented; + } + constructor(type, map, originalEvent) { + const touches = type === 'touchend' ? originalEvent.changedTouches : originalEvent.touches; + const points = DOM.touchPos(map.getCanvasContainer(), touches); + const lngLats = points.map((t) => map.unproject(t)); + const point = points.reduce((prev, curr, i, arr) => { + return prev.add(curr.div(arr.length)); + }, new Point$2(0, 0)); + const lngLat = map.unproject(point); + super(type, { points, point, lngLats, lngLat, originalEvent }); + this._defaultPrevented = false; + } +} +/** + * `MapWheelEvent` is the event type for the `wheel` map event. + * + * @group Event Related + */ +class MapWheelEvent extends Event { + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the behavior of {@link ScrollZoomHandler}. + */ + preventDefault() { + this._defaultPrevented = true; + } + /** + * `true` if `preventDefault` has been called. + */ + get defaultPrevented() { + return this._defaultPrevented; + } + /** */ + constructor(type, map, originalEvent) { + super(type, { originalEvent }); + this._defaultPrevented = false; + } +} + +class MapEventHandler { + constructor(map, options) { + this._map = map; + this._clickTolerance = options.clickTolerance; + } + reset() { + delete this._mousedownPos; + } + wheel(e) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - ScrollZoom + return this._firePreventable(new MapWheelEvent(e.type, this._map, e)); + } + mousedown(e, point) { + this._mousedownPos = point; + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - MousePan + // - MouseRotate + // - MousePitch + // - DblclickHandler + return this._firePreventable(new MapMouseEvent(e.type, this._map, e)); + } + mouseup(e) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + click(e, point) { + if (this._mousedownPos && this._mousedownPos.dist(point) >= this._clickTolerance) + return; + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + dblclick(e) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - DblClickZoom + return this._firePreventable(new MapMouseEvent(e.type, this._map, e)); + } + mouseover(e) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + mouseout(e) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + touchstart(e) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - TouchPan + // - TouchZoom + // - TouchRotate + // - TouchPitch + // - TapZoom + // - SwipeZoom + return this._firePreventable(new MapTouchEvent(e.type, this._map, e)); + } + touchmove(e) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + touchend(e) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + touchcancel(e) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + _firePreventable(mapEvent) { + this._map.fire(mapEvent); + if (mapEvent.defaultPrevented) { + // returning an object marks the handler as active and resets other handlers + return {}; + } + } + isEnabled() { + return true; + } + isActive() { + return false; + } + enable() { } + disable() { } +} +class BlockableMapEventHandler { + constructor(map) { + this._map = map; + } + reset() { + this._delayContextMenu = false; + this._ignoreContextMenu = true; + delete this._contextMenuEvent; + } + mousemove(e) { + // mousemove map events should not be fired when interaction handlers (pan, rotate, etc) are active + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + mousedown() { + this._delayContextMenu = true; + this._ignoreContextMenu = false; + } + mouseup() { + this._delayContextMenu = false; + if (this._contextMenuEvent) { + this._map.fire(new MapMouseEvent('contextmenu', this._map, this._contextMenuEvent)); + delete this._contextMenuEvent; + } + } + contextmenu(e) { + if (this._delayContextMenu) { + // Mac: contextmenu fired on mousedown; we save it until mouseup for consistency's sake + this._contextMenuEvent = e; + } + else if (!this._ignoreContextMenu) { + // Windows: contextmenu fired on mouseup, so fire event now + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + // prevent browser context menu when necessary + if (this._map.listens('contextmenu')) { + e.preventDefault(); + } + } + isEnabled() { + return true; + } + isActive() { + return false; + } + enable() { } + disable() { } +} + +/** + * @internal + * Shared utilities for the Handler classes to access the correct camera state. + * If Camera.transformCameraUpdate is specified or terrain is enabled, the + * "desired state" of camera may differ from the state used for rendering. The + * handlers need the "desired state" to track accumulated changes. + */ +class TransformProvider { + constructor(map) { + this._map = map; + } + get transform() { + return this._map._requestedCameraState || this._map.transform; + } + get center() { + return { lng: this.transform.center.lng, lat: this.transform.center.lat }; + } + get zoom() { + return this.transform.zoom; + } + get pitch() { + return this.transform.pitch; + } + get bearing() { + return this.transform.bearing; + } + unproject(point) { + return this.transform.pointLocation(Point$2.convert(point), this._map.terrain); + } +} + +/** + * The `BoxZoomHandler` allows the user to zoom the map to fit within a bounding box. + * The bounding box is defined by clicking and holding `shift` while dragging the cursor. + * + * @group Handlers + */ +class BoxZoomHandler { + /** @internal */ + constructor(map, options) { + this._map = map; + this._tr = new TransformProvider(map); + this._el = map.getCanvasContainer(); + this._container = map.getContainer(); + this._clickTolerance = options.clickTolerance || 1; + } + /** + * Returns a Boolean indicating whether the "box zoom" interaction is enabled. + * + * @returns `true` if the "box zoom" interaction is enabled. + */ + isEnabled() { + return !!this._enabled; + } + /** + * Returns a Boolean indicating whether the "box zoom" interaction is active, i.e. currently being used. + * + * @returns `true` if the "box zoom" interaction is active. + */ + isActive() { + return !!this._active; + } + /** + * Enables the "box zoom" interaction. + * + * @example + * ```ts + * map.boxZoom.enable(); + * ``` + */ + enable() { + if (this.isEnabled()) + return; + this._enabled = true; + } + /** + * Disables the "box zoom" interaction. + * + * @example + * ```ts + * map.boxZoom.disable(); + * ``` + */ + disable() { + if (!this.isEnabled()) + return; + this._enabled = false; + } + mousedown(e, point) { + if (!this.isEnabled()) + return; + if (!(e.shiftKey && e.button === 0)) + return; + DOM.disableDrag(); + this._startPos = this._lastPos = point; + this._active = true; + } + mousemoveWindow(e, point) { + if (!this._active) + return; + const pos = point; + if (this._lastPos.equals(pos) || (!this._box && pos.dist(this._startPos) < this._clickTolerance)) { + return; + } + const p0 = this._startPos; + this._lastPos = pos; + if (!this._box) { + this._box = DOM.create('div', 'maplibregl-boxzoom', this._container); + this._container.classList.add('maplibregl-crosshair'); + this._fireEvent('boxzoomstart', e); + } + const minX = Math.min(p0.x, pos.x), maxX = Math.max(p0.x, pos.x), minY = Math.min(p0.y, pos.y), maxY = Math.max(p0.y, pos.y); + DOM.setTransform(this._box, `translate(${minX}px,${minY}px)`); + this._box.style.width = `${maxX - minX}px`; + this._box.style.height = `${maxY - minY}px`; + } + mouseupWindow(e, point) { + if (!this._active) + return; + if (e.button !== 0) + return; + const p0 = this._startPos, p1 = point; + this.reset(); + DOM.suppressClick(); + if (p0.x === p1.x && p0.y === p1.y) { + this._fireEvent('boxzoomcancel', e); + } + else { + this._map.fire(new Event('boxzoomend', { originalEvent: e })); + return { + cameraAnimation: map => map.fitScreenCoordinates(p0, p1, this._tr.bearing, { linear: true }) + }; + } + } + keydown(e) { + if (!this._active) + return; + if (e.keyCode === 27) { + this.reset(); + this._fireEvent('boxzoomcancel', e); + } + } + reset() { + this._active = false; + this._container.classList.remove('maplibregl-crosshair'); + if (this._box) { + DOM.remove(this._box); + this._box = null; + } + DOM.enableDrag(); + delete this._startPos; + delete this._lastPos; + } + _fireEvent(type, e) { + return this._map.fire(new Event(type, { originalEvent: e })); + } +} + +function indexTouches(touches, points) { + if (touches.length !== points.length) + throw new Error(`The number of touches and points are not equal - touches ${touches.length}, points ${points.length}`); + const obj = {}; + for (let i = 0; i < touches.length; i++) { + obj[touches[i].identifier] = points[i]; + } + return obj; +} + +function getCentroid(points) { + const sum = new Point$2(0, 0); + for (const point of points) { + sum._add(point); + } + return sum.div(points.length); +} +const MAX_TAP_INTERVAL = 500; +const MAX_TOUCH_TIME = 500; +const MAX_DIST = 30; +class SingleTapRecognizer { + constructor(options) { + this.reset(); + this.numTouches = options.numTouches; + } + reset() { + delete this.centroid; + delete this.startTime; + delete this.touches; + this.aborted = false; + } + touchstart(e, points, mapTouches) { + if (this.centroid || mapTouches.length > this.numTouches) { + this.aborted = true; + } + if (this.aborted) { + return; + } + if (this.startTime === undefined) { + this.startTime = e.timeStamp; + } + if (mapTouches.length === this.numTouches) { + this.centroid = getCentroid(points); + this.touches = indexTouches(mapTouches, points); + } + } + touchmove(e, points, mapTouches) { + if (this.aborted || !this.centroid) + return; + const newTouches = indexTouches(mapTouches, points); + for (const id in this.touches) { + const prevPos = this.touches[id]; + const pos = newTouches[id]; + if (!pos || pos.dist(prevPos) > MAX_DIST) { + this.aborted = true; + } + } + } + touchend(e, points, mapTouches) { + if (!this.centroid || e.timeStamp - this.startTime > MAX_TOUCH_TIME) { + this.aborted = true; + } + if (mapTouches.length === 0) { + const centroid = !this.aborted && this.centroid; + this.reset(); + if (centroid) + return centroid; + } + } +} +class TapRecognizer { + constructor(options) { + this.singleTap = new SingleTapRecognizer(options); + this.numTaps = options.numTaps; + this.reset(); + } + reset() { + this.lastTime = Infinity; + delete this.lastTap; + this.count = 0; + this.singleTap.reset(); + } + touchstart(e, points, mapTouches) { + this.singleTap.touchstart(e, points, mapTouches); + } + touchmove(e, points, mapTouches) { + this.singleTap.touchmove(e, points, mapTouches); + } + touchend(e, points, mapTouches) { + const tap = this.singleTap.touchend(e, points, mapTouches); + if (tap) { + const soonEnough = e.timeStamp - this.lastTime < MAX_TAP_INTERVAL; + const closeEnough = !this.lastTap || this.lastTap.dist(tap) < MAX_DIST; + if (!soonEnough || !closeEnough) { + this.reset(); + } + this.count++; + this.lastTime = e.timeStamp; + this.lastTap = tap; + if (this.count === this.numTaps) { + this.reset(); + return tap; + } + } + } +} + +/** + * A `TapZoomHandler` allows the user to zoom the map at a point by double tapping + */ +class TapZoomHandler { + constructor(map) { + this._tr = new TransformProvider(map); + this._zoomIn = new TapRecognizer({ + numTouches: 1, + numTaps: 2 + }); + this._zoomOut = new TapRecognizer({ + numTouches: 2, + numTaps: 1 + }); + this.reset(); + } + reset() { + this._active = false; + this._zoomIn.reset(); + this._zoomOut.reset(); + } + touchstart(e, points, mapTouches) { + this._zoomIn.touchstart(e, points, mapTouches); + this._zoomOut.touchstart(e, points, mapTouches); + } + touchmove(e, points, mapTouches) { + this._zoomIn.touchmove(e, points, mapTouches); + this._zoomOut.touchmove(e, points, mapTouches); + } + touchend(e, points, mapTouches) { + const zoomInPoint = this._zoomIn.touchend(e, points, mapTouches); + const zoomOutPoint = this._zoomOut.touchend(e, points, mapTouches); + const tr = this._tr; + if (zoomInPoint) { + this._active = true; + e.preventDefault(); + setTimeout(() => this.reset(), 0); + return { + cameraAnimation: (map) => map.easeTo({ + duration: 300, + zoom: tr.zoom + 1, + around: tr.unproject(zoomInPoint) + }, { originalEvent: e }) + }; + } + else if (zoomOutPoint) { + this._active = true; + e.preventDefault(); + setTimeout(() => this.reset(), 0); + return { + cameraAnimation: (map) => map.easeTo({ + duration: 300, + zoom: tr.zoom - 1, + around: tr.unproject(zoomOutPoint) + }, { originalEvent: e }) + }; + } + } + touchcancel() { + this.reset(); + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } +} + +/** + * A generic class to create handlers for drag events, from both mouse and touch events. + */ +class DragHandler { + constructor(options) { + this._enabled = !!options.enable; + this._moveStateManager = options.moveStateManager; + this._clickTolerance = options.clickTolerance || 1; + this._moveFunction = options.move; + this._activateOnStart = !!options.activateOnStart; + options.assignEvents(this); + this.reset(); + } + reset(e) { + this._active = false; + this._moved = false; + delete this._lastPoint; + this._moveStateManager.endMove(e); + } + _move(...params) { + const move = this._moveFunction(...params); + if (move.bearingDelta || move.pitchDelta || move.around || move.panDelta) { + this._active = true; + return move; + } + } + dragStart(e, point) { + if (!this.isEnabled() || this._lastPoint) + return; + if (!this._moveStateManager.isValidStartEvent(e)) + return; + this._moveStateManager.startMove(e); + this._lastPoint = point['length'] ? point[0] : point; + if (this._activateOnStart && this._lastPoint) + this._active = true; + } + dragMove(e, point) { + if (!this.isEnabled()) + return; + const lastPoint = this._lastPoint; + if (!lastPoint) + return; + e.preventDefault(); + if (!this._moveStateManager.isValidMoveEvent(e)) { + this.reset(e); + return; + } + const movePoint = point['length'] ? point[0] : point; + if (!this._moved && movePoint.dist(lastPoint) < this._clickTolerance) + return; + this._moved = true; + this._lastPoint = movePoint; + return this._move(lastPoint, movePoint); + } + dragEnd(e) { + if (!this.isEnabled() || !this._lastPoint) + return; + if (!this._moveStateManager.isValidEndEvent(e)) + return; + if (this._moved) + DOM.suppressClick(); + this.reset(e); + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } + getClickTolerance() { + return this._clickTolerance; + } +} + +const LEFT_BUTTON$1 = 0; +const RIGHT_BUTTON$1 = 2; +// the values for each button in MouseEvent.buttons +const BUTTONS_FLAGS = { + [LEFT_BUTTON$1]: 1, + [RIGHT_BUTTON$1]: 2 +}; +function buttonNoLongerPressed(e, button) { + const flag = BUTTONS_FLAGS[button]; + return e.buttons === undefined || (e.buttons & flag) !== flag; +} +class MouseMoveStateManager { + constructor(options) { + this._correctEvent = options.checkCorrectEvent; + } + startMove(e) { + const eventButton = DOM.mouseButton(e); + this._eventButton = eventButton; + } + endMove(_e) { + delete this._eventButton; + } + isValidStartEvent(e) { + return this._correctEvent(e); + } + isValidMoveEvent(e) { + // Some browsers don't fire a `mouseup` when the mouseup occurs outside + // the window or iframe: + // https://github.com/mapbox/mapbox-gl-js/issues/4622 + // + // If the button is no longer pressed during this `mousemove` it may have + // been released outside of the window or iframe. + return !buttonNoLongerPressed(e, this._eventButton); + } + isValidEndEvent(e) { + const eventButton = DOM.mouseButton(e); + return eventButton === this._eventButton; + } +} +class OneFingerTouchMoveStateManager { + constructor() { + this._firstTouch = undefined; + } + _isOneFingerTouch(e) { + return e.targetTouches.length === 1; + } + _isSameTouchEvent(e) { + return e.targetTouches[0].identifier === this._firstTouch; + } + startMove(e) { + const firstTouch = e.targetTouches[0].identifier; + this._firstTouch = firstTouch; + } + endMove(_e) { + delete this._firstTouch; + } + isValidStartEvent(e) { + return this._isOneFingerTouch(e); + } + isValidMoveEvent(e) { + return this._isOneFingerTouch(e) && this._isSameTouchEvent(e); + } + isValidEndEvent(e) { + return this._isOneFingerTouch(e) && this._isSameTouchEvent(e); + } +} + +const LEFT_BUTTON = 0; +const RIGHT_BUTTON = 2; +const assignEvents$1 = (handler) => { + handler.mousedown = handler.dragStart; + handler.mousemoveWindow = handler.dragMove; + handler.mouseup = handler.dragEnd; + handler.contextmenu = (e) => { + e.preventDefault(); + }; +}; +const generateMousePanHandler = ({ enable, clickTolerance, }) => { + const mouseMoveStateManager = new MouseMoveStateManager({ + checkCorrectEvent: (e) => DOM.mouseButton(e) === LEFT_BUTTON && !e.ctrlKey, + }); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ around: point, panDelta: point.sub(lastPoint) }), + activateOnStart: true, + moveStateManager: mouseMoveStateManager, + enable, + assignEvents: assignEvents$1, + }); +}; +const generateMouseRotationHandler = ({ enable, clickTolerance, bearingDegreesPerPixelMoved = 0.8 }) => { + const mouseMoveStateManager = new MouseMoveStateManager({ + checkCorrectEvent: (e) => (DOM.mouseButton(e) === LEFT_BUTTON && e.ctrlKey) || + (DOM.mouseButton(e) === RIGHT_BUTTON), + }); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ bearingDelta: (point.x - lastPoint.x) * bearingDegreesPerPixelMoved }), + // prevent browser context menu when necessary; we don't allow it with rotation + // because we can't discern rotation gesture start from contextmenu on Mac + moveStateManager: mouseMoveStateManager, + enable, + assignEvents: assignEvents$1, + }); +}; +const generateMousePitchHandler = ({ enable, clickTolerance, pitchDegreesPerPixelMoved = -0.5 }) => { + const mouseMoveStateManager = new MouseMoveStateManager({ + checkCorrectEvent: (e) => (DOM.mouseButton(e) === LEFT_BUTTON && e.ctrlKey) || + (DOM.mouseButton(e) === RIGHT_BUTTON), + }); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ pitchDelta: (point.y - lastPoint.y) * pitchDegreesPerPixelMoved }), + // prevent browser context menu when necessary; we don't allow it with rotation + // because we can't discern rotation gesture start from contextmenu on Mac + moveStateManager: mouseMoveStateManager, + enable, + assignEvents: assignEvents$1, + }); +}; + +/** + * A `TouchPanHandler` allows the user to pan the map using touch gestures. + */ +class TouchPanHandler { + constructor(options, map) { + this._clickTolerance = options.clickTolerance || 1; + this._map = map; + this.reset(); + } + reset() { + this._active = false; + this._touches = {}; + this._sum = new Point$2(0, 0); + } + _shouldBePrevented(touchesCount) { + const minTouches = this._map.cooperativeGestures.isEnabled() ? 2 : 1; + return touchesCount < minTouches; + } + touchstart(e, points, mapTouches) { + return this._calculateTransform(e, points, mapTouches); + } + touchmove(e, points, mapTouches) { + if (!this._active) + return; + if (this._shouldBePrevented(mapTouches.length)) { + this._map.cooperativeGestures.notifyGestureBlocked('touch_pan', e); + return; + } + e.preventDefault(); + return this._calculateTransform(e, points, mapTouches); + } + touchend(e, points, mapTouches) { + this._calculateTransform(e, points, mapTouches); + if (this._active && this._shouldBePrevented(mapTouches.length)) { + this.reset(); + } + } + touchcancel() { + this.reset(); + } + _calculateTransform(e, points, mapTouches) { + if (mapTouches.length > 0) + this._active = true; + const touches = indexTouches(mapTouches, points); + const touchPointSum = new Point$2(0, 0); + const touchDeltaSum = new Point$2(0, 0); + let touchDeltaCount = 0; + for (const identifier in touches) { + const point = touches[identifier]; + const prevPoint = this._touches[identifier]; + if (prevPoint) { + touchPointSum._add(point); + touchDeltaSum._add(point.sub(prevPoint)); + touchDeltaCount++; + touches[identifier] = point; + } + } + this._touches = touches; + if (this._shouldBePrevented(touchDeltaCount) || !touchDeltaSum.mag()) + return; + const panDelta = touchDeltaSum.div(touchDeltaCount); + this._sum._add(panDelta); + if (this._sum.mag() < this._clickTolerance) + return; + const around = touchPointSum.div(touchDeltaCount); + return { + around, + panDelta + }; + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } +} + +/** + * The `TwoFingersTouchHandler`s allows the user to zoom, pitch and rotate the map using two fingers + * + */ +class TwoFingersTouchHandler { + /** @internal */ + constructor() { + this.reset(); + } + reset() { + this._active = false; + delete this._firstTwoTouches; + } + touchstart(e, points, mapTouches) { + //log('touchstart', points, e.target.innerHTML, e.targetTouches.length ? e.targetTouches[0].target.innerHTML: undefined); + if (this._firstTwoTouches || mapTouches.length < 2) + return; + this._firstTwoTouches = [ + mapTouches[0].identifier, + mapTouches[1].identifier + ]; + // implemented by child classes + this._start([points[0], points[1]]); + } + touchmove(e, points, mapTouches) { + if (!this._firstTwoTouches) + return; + e.preventDefault(); + const [idA, idB] = this._firstTwoTouches; + const a = getTouchById(mapTouches, points, idA); + const b = getTouchById(mapTouches, points, idB); + if (!a || !b) + return; + const pinchAround = this._aroundCenter ? null : a.add(b).div(2); + // implemented by child classes + return this._move([a, b], pinchAround, e); + } + touchend(e, points, mapTouches) { + if (!this._firstTwoTouches) + return; + const [idA, idB] = this._firstTwoTouches; + const a = getTouchById(mapTouches, points, idA); + const b = getTouchById(mapTouches, points, idB); + if (a && b) + return; + if (this._active) + DOM.suppressClick(); + this.reset(); + } + touchcancel() { + this.reset(); + } + /** + * Enables the "drag to pitch" interaction. + * + * @example + * ```ts + * map.touchPitch.enable(); + * ``` + */ + enable(options) { + this._enabled = true; + this._aroundCenter = !!options && options.around === 'center'; + } + /** + * Disables the "drag to pitch" interaction. + * + * @example + * ```ts + * map.touchPitch.disable(); + * ``` + */ + disable() { + this._enabled = false; + this.reset(); + } + /** + * Returns a Boolean indicating whether the "drag to pitch" interaction is enabled. + * + * @returns `true` if the "drag to pitch" interaction is enabled. + */ + isEnabled() { + return !!this._enabled; + } + /** + * Returns a Boolean indicating whether the "drag to pitch" interaction is active, i.e. currently being used. + * + * @returns `true` if the "drag to pitch" interaction is active. + */ + isActive() { + return !!this._active; + } +} +function getTouchById(mapTouches, points, identifier) { + for (let i = 0; i < mapTouches.length; i++) { + if (mapTouches[i].identifier === identifier) + return points[i]; + } + return undefined; +} +/* ZOOM */ +const ZOOM_THRESHOLD = 0.1; +function getZoomDelta(distance, lastDistance) { + return Math.log(distance / lastDistance) / Math.LN2; +} +/** + * The `TwoFingersTouchHandler`s allows the user to zoom the map two fingers + * + * @group Handlers + */ +class TwoFingersTouchZoomHandler extends TwoFingersTouchHandler { + reset() { + super.reset(); + delete this._distance; + delete this._startDistance; + } + _start(points) { + this._startDistance = this._distance = points[0].dist(points[1]); + } + _move(points, pinchAround) { + const lastDistance = this._distance; + this._distance = points[0].dist(points[1]); + if (!this._active && Math.abs(getZoomDelta(this._distance, this._startDistance)) < ZOOM_THRESHOLD) + return; + this._active = true; + return { + zoomDelta: getZoomDelta(this._distance, lastDistance), + pinchAround + }; + } +} +/* ROTATE */ +const ROTATION_THRESHOLD = 25; // pixels along circumference of touch circle +function getBearingDelta(a, b) { + return a.angleWith(b) * 180 / Math.PI; +} +/** + * The `TwoFingersTouchHandler`s allows the user to rotate the map two fingers + * + * @group Handlers + */ +class TwoFingersTouchRotateHandler extends TwoFingersTouchHandler { + reset() { + super.reset(); + delete this._minDiameter; + delete this._startVector; + delete this._vector; + } + _start(points) { + this._startVector = this._vector = points[0].sub(points[1]); + this._minDiameter = points[0].dist(points[1]); + } + _move(points, pinchAround, _e) { + const lastVector = this._vector; + this._vector = points[0].sub(points[1]); + if (!this._active && this._isBelowThreshold(this._vector)) + return; + this._active = true; + return { + bearingDelta: getBearingDelta(this._vector, lastVector), + pinchAround + }; + } + _isBelowThreshold(vector) { + /* + * The threshold before a rotation actually happens is configured in + * pixels along the circumference of the circle formed by the two fingers. + * This makes the threshold in degrees larger when the fingers are close + * together and smaller when the fingers are far apart. + * + * Use the smallest diameter from the whole gesture to reduce sensitivity + * when pinching in and out. + */ + this._minDiameter = Math.min(this._minDiameter, vector.mag()); + const circumference = Math.PI * this._minDiameter; + const threshold = ROTATION_THRESHOLD / circumference * 360; + const bearingDeltaSinceStart = getBearingDelta(vector, this._startVector); + return Math.abs(bearingDeltaSinceStart) < threshold; + } +} +/* PITCH */ +function isVertical(vector) { + return Math.abs(vector.y) > Math.abs(vector.x); +} +const ALLOWED_SINGLE_TOUCH_TIME = 100; +/** + * The `TwoFingersTouchPitchHandler` allows the user to pitch the map by dragging up and down with two fingers. + * + * @group Handlers + */ +class TwoFingersTouchPitchHandler extends TwoFingersTouchHandler { + constructor(map) { + super(); + this._currentTouchCount = 0; + this._map = map; + } + reset() { + super.reset(); + this._valid = undefined; + delete this._firstMove; + delete this._lastPoints; + } + touchstart(e, points, mapTouches) { + super.touchstart(e, points, mapTouches); + this._currentTouchCount = mapTouches.length; + } + _start(points) { + this._lastPoints = points; + if (isVertical(points[0].sub(points[1]))) { + // fingers are more horizontal than vertical + this._valid = false; + } + } + _move(points, center, e) { + // If cooperative gestures is enabled, we need a 3-finger minimum for this gesture to register + if (this._map.cooperativeGestures.isEnabled() && this._currentTouchCount < 3) { + return; + } + const vectorA = points[0].sub(this._lastPoints[0]); + const vectorB = points[1].sub(this._lastPoints[1]); + this._valid = this.gestureBeginsVertically(vectorA, vectorB, e.timeStamp); + if (!this._valid) + return; + this._lastPoints = points; + this._active = true; + const yDeltaAverage = (vectorA.y + vectorB.y) / 2; + const degreesPerPixelMoved = -0.5; + return { + pitchDelta: yDeltaAverage * degreesPerPixelMoved + }; + } + gestureBeginsVertically(vectorA, vectorB, timeStamp) { + if (this._valid !== undefined) + return this._valid; + const threshold = 2; + const movedA = vectorA.mag() >= threshold; + const movedB = vectorB.mag() >= threshold; + // neither finger has moved a meaningful amount, wait + if (!movedA && !movedB) + return; + // One finger has moved and the other has not. + // If enough time has passed, decide it is not a pitch. + if (!movedA || !movedB) { + if (this._firstMove === undefined) { + this._firstMove = timeStamp; + } + if (timeStamp - this._firstMove < ALLOWED_SINGLE_TOUCH_TIME) { + // still waiting for a movement from the second finger + return undefined; + } + else { + return false; + } + } + const isSameDirection = vectorA.y > 0 === vectorB.y > 0; + return isVertical(vectorA) && isVertical(vectorB) && isSameDirection; + } +} + +const defaultOptions$5 = { + panStep: 100, + bearingStep: 15, + pitchStep: 10 +}; +/** + * The `KeyboardHandler` allows the user to zoom, rotate, and pan the map using + * the following keyboard shortcuts: + * + * - `=` / `+`: Increase the zoom level by 1. + * - `Shift-=` / `Shift-+`: Increase the zoom level by 2. + * - `-`: Decrease the zoom level by 1. + * - `Shift--`: Decrease the zoom level by 2. + * - Arrow keys: Pan by 100 pixels. + * - `Shift+⇢`: Increase the rotation by 15 degrees. + * - `Shift+⇠`: Decrease the rotation by 15 degrees. + * - `Shift+⇡`: Increase the pitch by 10 degrees. + * - `Shift+⇣`: Decrease the pitch by 10 degrees. + * + * @group Handlers + */ +class KeyboardHandler { + /** @internal */ + constructor(map) { + this._tr = new TransformProvider(map); + const stepOptions = defaultOptions$5; + this._panStep = stepOptions.panStep; + this._bearingStep = stepOptions.bearingStep; + this._pitchStep = stepOptions.pitchStep; + this._rotationDisabled = false; + } + reset() { + this._active = false; + } + keydown(e) { + if (e.altKey || e.ctrlKey || e.metaKey) + return; + let zoomDir = 0; + let bearingDir = 0; + let pitchDir = 0; + let xDir = 0; + let yDir = 0; + switch (e.keyCode) { + case 61: + case 107: + case 171: + case 187: + zoomDir = 1; + break; + case 189: + case 109: + case 173: + zoomDir = -1; + break; + case 37: + if (e.shiftKey) { + bearingDir = -1; + } + else { + e.preventDefault(); + xDir = -1; + } + break; + case 39: + if (e.shiftKey) { + bearingDir = 1; + } + else { + e.preventDefault(); + xDir = 1; + } + break; + case 38: + if (e.shiftKey) { + pitchDir = 1; + } + else { + e.preventDefault(); + yDir = -1; + } + break; + case 40: + if (e.shiftKey) { + pitchDir = -1; + } + else { + e.preventDefault(); + yDir = 1; + } + break; + default: + return; + } + if (this._rotationDisabled) { + bearingDir = 0; + pitchDir = 0; + } + return { + cameraAnimation: (map) => { + const tr = this._tr; + map.easeTo({ + duration: 300, + easeId: 'keyboardHandler', + easing: easeOut, + zoom: zoomDir ? Math.round(tr.zoom) + zoomDir * (e.shiftKey ? 2 : 1) : tr.zoom, + bearing: tr.bearing + bearingDir * this._bearingStep, + pitch: tr.pitch + pitchDir * this._pitchStep, + offset: [-xDir * this._panStep, -yDir * this._panStep], + center: tr.center + }, { originalEvent: e }); + } + }; + } + /** + * Enables the "keyboard rotate and zoom" interaction. + * + * @example + * ```ts + * map.keyboard.enable(); + * ``` + */ + enable() { + this._enabled = true; + } + /** + * Disables the "keyboard rotate and zoom" interaction. + * + * @example + * ```ts + * map.keyboard.disable(); + * ``` + */ + disable() { + this._enabled = false; + this.reset(); + } + /** + * Returns a Boolean indicating whether the "keyboard rotate and zoom" + * interaction is enabled. + * + * @returns `true` if the "keyboard rotate and zoom" + * interaction is enabled. + */ + isEnabled() { + return this._enabled; + } + /** + * Returns true if the handler is enabled and has detected the start of a + * zoom/rotate gesture. + * + * @returns `true` if the handler is enabled and has detected the + * start of a zoom/rotate gesture. + */ + isActive() { + return this._active; + } + /** + * Disables the "keyboard pan/rotate" interaction, leaving the + * "keyboard zoom" interaction enabled. + * + * @example + * ```ts + * map.keyboard.disableRotation(); + * ``` + */ + disableRotation() { + this._rotationDisabled = true; + } + /** + * Enables the "keyboard pan/rotate" interaction. + * + * @example + * ```ts + * map.keyboard.enable(); + * map.keyboard.enableRotation(); + * ``` + */ + enableRotation() { + this._rotationDisabled = false; + } +} +function easeOut(t) { + return t * (2 - t); +} + +// deltaY value for mouse scroll wheel identification +const wheelZoomDelta = 4.000244140625; +// These magic numbers control the rate of zoom. Trackpad events fire at a greater +// frequency than mouse scroll wheel, so reduce the zoom rate per wheel tick +const defaultZoomRate = 1 / 100; +const wheelZoomRate = 1 / 450; +// upper bound on how much we scale the map in any single render frame; this +// is used to limit zoom rate in the case of very fast scrolling +const maxScalePerFrame = 2; +/** + * The `ScrollZoomHandler` allows the user to zoom the map by scrolling. + * + * @group Handlers + */ +class ScrollZoomHandler { + /** @internal */ + constructor(map, triggerRenderFrame) { + this._onTimeout = (initialEvent) => { + this._type = 'wheel'; + this._delta -= this._lastValue; + if (!this._active) { + this._start(initialEvent); + } + }; + this._map = map; + this._tr = new TransformProvider(map); + this._triggerRenderFrame = triggerRenderFrame; + this._delta = 0; + this._defaultZoomRate = defaultZoomRate; + this._wheelZoomRate = wheelZoomRate; + } + /** + * Set the zoom rate of a trackpad + * @param zoomRate - 1/100 The rate used to scale trackpad movement to a zoom value. + * @example + * Speed up trackpad zoom + * ```ts + * map.scrollZoom.setZoomRate(1/25); + * ``` + */ + setZoomRate(zoomRate) { + this._defaultZoomRate = zoomRate; + } + /** + * Set the zoom rate of a mouse wheel + * @param wheelZoomRate - 1/450 The rate used to scale mouse wheel movement to a zoom value. + * @example + * Slow down zoom of mouse wheel + * ```ts + * map.scrollZoom.setWheelZoomRate(1/600); + * ``` + */ + setWheelZoomRate(wheelZoomRate) { + this._wheelZoomRate = wheelZoomRate; + } + /** + * Returns a Boolean indicating whether the "scroll to zoom" interaction is enabled. + * @returns `true` if the "scroll to zoom" interaction is enabled. + */ + isEnabled() { + return !!this._enabled; + } + /* + * Active state is turned on and off with every scroll wheel event and is set back to false before the map + * render is called, so _active is not a good candidate for determining if a scroll zoom animation is in + * progress. + */ + isActive() { + return !!this._active || this._finishTimeout !== undefined; + } + isZooming() { + return !!this._zooming; + } + /** + * Enables the "scroll to zoom" interaction. + * + * @param options - Options object. + * @example + * ```ts + * map.scrollZoom.enable(); + * map.scrollZoom.enable({ around: 'center' }) + * ``` + */ + enable(options) { + if (this.isEnabled()) + return; + this._enabled = true; + this._aroundCenter = !!options && options.around === 'center'; + } + /** + * Disables the "scroll to zoom" interaction. + * + * @example + * ```ts + * map.scrollZoom.disable(); + * ``` + */ + disable() { + if (!this.isEnabled()) + return; + this._enabled = false; + } + /** + * Determines whether or not the gesture is blocked due to cooperativeGestures. + */ + _shouldBePrevented(e) { + if (!this._map.cooperativeGestures.isEnabled()) { + return false; + } + const isTrackpadPinch = e.ctrlKey; + const isBypassed = isTrackpadPinch || this._map.cooperativeGestures.isBypassed(e); + return !isBypassed; + } + wheel(e) { + if (!this.isEnabled()) + return; + if (this._shouldBePrevented(e)) { + this._map.cooperativeGestures.notifyGestureBlocked('wheel_zoom', e); + return; + } + let value = e.deltaMode === WheelEvent.DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY; + const now = browser.now(), timeDelta = now - (this._lastWheelEventTime || 0); + this._lastWheelEventTime = now; + if (value !== 0 && (value % wheelZoomDelta) === 0) { + // This one is definitely a mouse wheel event. + this._type = 'wheel'; + } + else if (value !== 0 && Math.abs(value) < 4) { + // This one is definitely a trackpad event because it is so small. + this._type = 'trackpad'; + } + else if (timeDelta > 400) { + // This is likely a new scroll action. + this._type = null; + this._lastValue = value; + // Start a timeout in case this was a singular event, and delay it by up to 40ms. + this._timeout = setTimeout(this._onTimeout, 40, e); + } + else if (!this._type) { + // This is a repeating event, but we don't know the type of event just yet. + // If the delta per time is small, we assume it's a fast trackpad; otherwise we switch into wheel mode. + this._type = (Math.abs(timeDelta * value) < 200) ? 'trackpad' : 'wheel'; + // Make sure our delayed event isn't fired again, because we accumulate + // the previous event (which was less than 40ms ago) into this event. + if (this._timeout) { + clearTimeout(this._timeout); + this._timeout = null; + value += this._lastValue; + } + } + // Slow down zoom if shift key is held for more precise zooming + if (e.shiftKey && value) + value = value / 4; + // Only fire the callback if we actually know what type of scrolling device the user uses. + if (this._type) { + this._lastWheelEvent = e; + this._delta -= value; + if (!this._active) { + this._start(e); + } + } + e.preventDefault(); + } + _start(e) { + if (!this._delta) + return; + if (this._frameId) { + this._frameId = null; + } + this._active = true; + if (!this.isZooming()) { + this._zooming = true; + } + if (this._finishTimeout) { + clearTimeout(this._finishTimeout); + delete this._finishTimeout; + } + const pos = DOM.mousePos(this._map.getCanvas(), e); + const tr = this._tr; + if (pos.y > tr.transform.height / 2 - tr.transform.getHorizon()) { + this._around = LngLat.convert(this._aroundCenter ? tr.center : tr.unproject(pos)); + } + else { + // Do not use current cursor position if above the horizon to avoid 'unproject' this point + // as it is not mapped into 'coords' framebuffer or inversible with 'pixelMatrixInverse'. + this._around = LngLat.convert(tr.center); + } + this._aroundPoint = tr.transform.locationPoint(this._around); + if (!this._frameId) { + this._frameId = true; + this._triggerRenderFrame(); + } + } + renderFrame() { + if (!this._frameId) + return; + this._frameId = null; + if (!this.isActive()) + return; + const tr = this._tr.transform; + // if we've had scroll events since the last render frame, consume the + // accumulated delta, and update the target zoom level accordingly + if (this._delta !== 0) { + // For trackpad events and single mouse wheel ticks, use the default zoom rate + const zoomRate = (this._type === 'wheel' && Math.abs(this._delta) > wheelZoomDelta) ? this._wheelZoomRate : this._defaultZoomRate; + // Scale by sigmoid of scroll wheel delta. + let scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * zoomRate))); + if (this._delta < 0 && scale !== 0) { + scale = 1 / scale; + } + const fromScale = typeof this._targetZoom === 'number' ? tr.zoomScale(this._targetZoom) : tr.scale; + this._targetZoom = Math.min(tr.maxZoom, Math.max(tr.minZoom, tr.scaleZoom(fromScale * scale))); + // if this is a mouse wheel, refresh the starting zoom and easing + // function we're using to smooth out the zooming between wheel + // events + if (this._type === 'wheel') { + this._startZoom = tr.zoom; + this._easing = this._smoothOutEasing(200); + } + this._delta = 0; + } + const targetZoom = typeof this._targetZoom === 'number' ? + this._targetZoom : tr.zoom; + const startZoom = this._startZoom; + const easing = this._easing; + let finished = false; + let zoom; + const lastWheelEventTimeDiff = browser.now() - this._lastWheelEventTime; + if (this._type === 'wheel' && startZoom && easing && lastWheelEventTimeDiff) { + const t = Math.min(lastWheelEventTimeDiff / 200, 1); + const k = easing(t); + zoom = interpolate.number(startZoom, targetZoom, k); + if (t < 1) { + if (!this._frameId) { + this._frameId = true; + } + } + else { + finished = true; + } + } + else { + zoom = targetZoom; + finished = true; + } + this._active = true; + if (finished) { + this._active = false; + this._finishTimeout = setTimeout(() => { + this._zooming = false; + this._triggerRenderFrame(); + delete this._targetZoom; + delete this._finishTimeout; + }, 200); + } + return { + noInertia: true, + needsRenderFrame: !finished, + zoomDelta: zoom - tr.zoom, + around: this._aroundPoint, + originalEvent: this._lastWheelEvent + }; + } + _smoothOutEasing(duration) { + let easing = defaultEasing; + if (this._prevEase) { + const currentEase = this._prevEase; + const t = (browser.now() - currentEase.start) / currentEase.duration; + const speed = currentEase.easing(t + 0.01) - currentEase.easing(t); + // Quick hack to make new bezier that is continuous with last + const x = 0.27 / Math.sqrt(speed * speed + 0.0001) * 0.01; + const y = Math.sqrt(0.27 * 0.27 - x * x); + easing = bezier$1(x, y, 0.25, 1); + } + this._prevEase = { + start: browser.now(), + duration, + easing + }; + return easing; + } + reset() { + this._active = false; + this._zooming = false; + delete this._targetZoom; + if (this._finishTimeout) { + clearTimeout(this._finishTimeout); + delete this._finishTimeout; + } + } +} + +/** + * The `DoubleClickZoomHandler` allows the user to zoom the map at a point by + * double clicking or double tapping. + * + * @group Handlers + */ +class DoubleClickZoomHandler { + /** @internal */ + constructor(clickZoom, TapZoom) { + this._clickZoom = clickZoom; + this._tapZoom = TapZoom; + } + /** + * Enables the "double click to zoom" interaction. + * + * @example + * ```ts + * map.doubleClickZoom.enable(); + * ``` + */ + enable() { + this._clickZoom.enable(); + this._tapZoom.enable(); + } + /** + * Disables the "double click to zoom" interaction. + * + * @example + * ```ts + * map.doubleClickZoom.disable(); + * ``` + */ + disable() { + this._clickZoom.disable(); + this._tapZoom.disable(); + } + /** + * Returns a Boolean indicating whether the "double click to zoom" interaction is enabled. + * + * @returns `true` if the "double click to zoom" interaction is enabled. + */ + isEnabled() { + return this._clickZoom.isEnabled() && this._tapZoom.isEnabled(); + } + /** + * Returns a Boolean indicating whether the "double click to zoom" interaction is active, i.e. currently being used. + * + * @returns `true` if the "double click to zoom" interaction is active. + */ + isActive() { + return this._clickZoom.isActive() || this._tapZoom.isActive(); + } +} + +/** + * The `ClickZoomHandler` allows the user to zoom the map at a point by double clicking + * It is used by other handlers + */ +class ClickZoomHandler { + /** @internal */ + constructor(map) { + this._tr = new TransformProvider(map); + this.reset(); + } + reset() { + this._active = false; + } + dblclick(e, point) { + e.preventDefault(); + return { + cameraAnimation: (map) => { + map.easeTo({ + duration: 300, + zoom: this._tr.zoom + (e.shiftKey ? -1 : 1), + around: this._tr.unproject(point) + }, { originalEvent: e }); + } + }; + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } +} + +/** + * A `TapDragZoomHandler` allows the user to zoom the map at a point by double tapping. It also allows the user pan the map by dragging. + */ +class TapDragZoomHandler { + constructor() { + this._tap = new TapRecognizer({ + numTouches: 1, + numTaps: 1 + }); + this.reset(); + } + reset() { + this._active = false; + delete this._swipePoint; + delete this._swipeTouch; + delete this._tapTime; + delete this._tapPoint; + this._tap.reset(); + } + touchstart(e, points, mapTouches) { + if (this._swipePoint) + return; + if (!this._tapTime) { + this._tap.touchstart(e, points, mapTouches); + } + else { + const swipePoint = points[0]; + const soonEnough = e.timeStamp - this._tapTime < MAX_TAP_INTERVAL; + const closeEnough = this._tapPoint.dist(swipePoint) < MAX_DIST; + if (!soonEnough || !closeEnough) { + this.reset(); + } + else if (mapTouches.length > 0) { + this._swipePoint = swipePoint; + this._swipeTouch = mapTouches[0].identifier; + } + } + } + touchmove(e, points, mapTouches) { + if (!this._tapTime) { + this._tap.touchmove(e, points, mapTouches); + } + else if (this._swipePoint) { + if (mapTouches[0].identifier !== this._swipeTouch) { + return; + } + const newSwipePoint = points[0]; + const dist = newSwipePoint.y - this._swipePoint.y; + this._swipePoint = newSwipePoint; + e.preventDefault(); + this._active = true; + return { + zoomDelta: dist / 128 + }; + } + } + touchend(e, points, mapTouches) { + if (!this._tapTime) { + const point = this._tap.touchend(e, points, mapTouches); + if (point) { + this._tapTime = e.timeStamp; + this._tapPoint = point; + } + } + else if (this._swipePoint) { + if (mapTouches.length === 0) { + this.reset(); + } + } + } + touchcancel() { + this.reset(); + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } +} + +/** + * The `DragPanHandler` allows the user to pan the map by clicking and dragging + * the cursor. + * + * @group Handlers + */ +class DragPanHandler { + /** @internal */ + constructor(el, mousePan, touchPan) { + this._el = el; + this._mousePan = mousePan; + this._touchPan = touchPan; + } + /** + * Enables the "drag to pan" interaction. + * + * @param options - Options object + * @example + * ```ts + * map.dragPan.enable(); + * map.dragPan.enable({ + * linearity: 0.3, + * easing: bezier(0, 0, 0.3, 1), + * maxSpeed: 1400, + * deceleration: 2500, + * }); + * ``` + */ + enable(options) { + this._inertiaOptions = options || {}; + this._mousePan.enable(); + this._touchPan.enable(); + this._el.classList.add('maplibregl-touch-drag-pan'); + } + /** + * Disables the "drag to pan" interaction. + * + * @example + * ```ts + * map.dragPan.disable(); + * ``` + */ + disable() { + this._mousePan.disable(); + this._touchPan.disable(); + this._el.classList.remove('maplibregl-touch-drag-pan'); + } + /** + * Returns a Boolean indicating whether the "drag to pan" interaction is enabled. + * + * @returns `true` if the "drag to pan" interaction is enabled. + */ + isEnabled() { + return this._mousePan.isEnabled() && this._touchPan.isEnabled(); + } + /** + * Returns a Boolean indicating whether the "drag to pan" interaction is active, i.e. currently being used. + * + * @returns `true` if the "drag to pan" interaction is active. + */ + isActive() { + return this._mousePan.isActive() || this._touchPan.isActive(); + } +} + +/** + * The `DragRotateHandler` allows the user to rotate the map by clicking and + * dragging the cursor while holding the right mouse button or `ctrl` key. + * + * @group Handlers + */ +class DragRotateHandler { + /** @internal */ + constructor(options, mouseRotate, mousePitch) { + this._pitchWithRotate = options.pitchWithRotate; + this._mouseRotate = mouseRotate; + this._mousePitch = mousePitch; + } + /** + * Enables the "drag to rotate" interaction. + * + * @example + * ```ts + * map.dragRotate.enable(); + * ``` + */ + enable() { + this._mouseRotate.enable(); + if (this._pitchWithRotate) + this._mousePitch.enable(); + } + /** + * Disables the "drag to rotate" interaction. + * + * @example + * ```ts + * map.dragRotate.disable(); + * ``` + */ + disable() { + this._mouseRotate.disable(); + this._mousePitch.disable(); + } + /** + * Returns a Boolean indicating whether the "drag to rotate" interaction is enabled. + * + * @returns `true` if the "drag to rotate" interaction is enabled. + */ + isEnabled() { + return this._mouseRotate.isEnabled() && (!this._pitchWithRotate || this._mousePitch.isEnabled()); + } + /** + * Returns a Boolean indicating whether the "drag to rotate" interaction is active, i.e. currently being used. + * + * @returns `true` if the "drag to rotate" interaction is active. + */ + isActive() { + return this._mouseRotate.isActive() || this._mousePitch.isActive(); + } +} + +/** + * The `TwoFingersTouchZoomRotateHandler` allows the user to zoom and rotate the map by + * pinching on a touchscreen. + * + * They can zoom with one finger by double tapping and dragging. On the second tap, + * hold the finger down and drag up or down to zoom in or out. + * + * @group Handlers + */ +class TwoFingersTouchZoomRotateHandler { + /** @internal */ + constructor(el, touchZoom, touchRotate, tapDragZoom) { + this._el = el; + this._touchZoom = touchZoom; + this._touchRotate = touchRotate; + this._tapDragZoom = tapDragZoom; + this._rotationDisabled = false; + this._enabled = true; + } + /** + * Enables the "pinch to rotate and zoom" interaction. + * + * @param options - Options object. + * + * @example + * ```ts + * map.touchZoomRotate.enable(); + * map.touchZoomRotate.enable({ around: 'center' }); + * ``` + */ + enable(options) { + this._touchZoom.enable(options); + if (!this._rotationDisabled) + this._touchRotate.enable(options); + this._tapDragZoom.enable(); + this._el.classList.add('maplibregl-touch-zoom-rotate'); + } + /** + * Disables the "pinch to rotate and zoom" interaction. + * + * @example + * ```ts + * map.touchZoomRotate.disable(); + * ``` + */ + disable() { + this._touchZoom.disable(); + this._touchRotate.disable(); + this._tapDragZoom.disable(); + this._el.classList.remove('maplibregl-touch-zoom-rotate'); + } + /** + * Returns a Boolean indicating whether the "pinch to rotate and zoom" interaction is enabled. + * + * @returns `true` if the "pinch to rotate and zoom" interaction is enabled. + */ + isEnabled() { + return this._touchZoom.isEnabled() && + (this._rotationDisabled || this._touchRotate.isEnabled()) && + this._tapDragZoom.isEnabled(); + } + /** + * Returns true if the handler is enabled and has detected the start of a zoom/rotate gesture. + * + * @returns `true` if the handler is active, `false` otherwise + */ + isActive() { + return this._touchZoom.isActive() || this._touchRotate.isActive() || this._tapDragZoom.isActive(); + } + /** + * Disables the "pinch to rotate" interaction, leaving the "pinch to zoom" + * interaction enabled. + * + * @example + * ```ts + * map.touchZoomRotate.disableRotation(); + * ``` + */ + disableRotation() { + this._rotationDisabled = true; + this._touchRotate.disable(); + } + /** + * Enables the "pinch to rotate" interaction. + * + * @example + * ```ts + * map.touchZoomRotate.enable(); + * map.touchZoomRotate.enableRotation(); + * ``` + */ + enableRotation() { + this._rotationDisabled = false; + if (this._touchZoom.isEnabled()) + this._touchRotate.enable(); + } +} + +/** + * A `CooperativeGestureHandler` is a control that adds cooperative gesture info when user tries to zoom in/out. + * + * When the CooperativeGestureHandler blocks a gesture, it will emit a `cooperativegestureprevented` event. + * + * @group Handlers + * + * @example + * ```ts + * const map = new Map({ + * cooperativeGestures: true + * }); + * ``` + * @see [Example: cooperative gestures](https://maplibre.org/maplibre-gl-js/docs/examples/cooperative-gestures/) + **/ +class CooperativeGesturesHandler { + constructor(map, options) { + /** + * This is the key that will allow to bypass the cooperative gesture protection + */ + this._bypassKey = navigator.userAgent.indexOf('Mac') !== -1 ? 'metaKey' : 'ctrlKey'; + this._map = map; + this._options = options; + this._enabled = false; + } + isActive() { + return false; + } + reset() { } + _setupUI() { + if (this._container) + return; + const mapCanvasContainer = this._map.getCanvasContainer(); + // Add a cooperative gestures class (enable touch-action: pan-x pan-y;) + mapCanvasContainer.classList.add('maplibregl-cooperative-gestures'); + this._container = DOM.create('div', 'maplibregl-cooperative-gesture-screen', mapCanvasContainer); + let desktopMessage = this._map._getUIString('CooperativeGesturesHandler.WindowsHelpText'); + if (this._bypassKey === 'metaKey') { + desktopMessage = this._map._getUIString('CooperativeGesturesHandler.MacHelpText'); + } + const mobileMessage = this._map._getUIString('CooperativeGesturesHandler.MobileHelpText'); + // Create and append the desktop message div + const desktopDiv = document.createElement('div'); + desktopDiv.className = 'maplibregl-desktop-message'; + desktopDiv.textContent = desktopMessage; + this._container.appendChild(desktopDiv); + // Create and append the mobile message div + const mobileDiv = document.createElement('div'); + mobileDiv.className = 'maplibregl-mobile-message'; + mobileDiv.textContent = mobileMessage; + this._container.appendChild(mobileDiv); + // Remove cooperative gesture screen from the accessibility tree since screenreaders cannot interact with the map using gestures + this._container.setAttribute('aria-hidden', 'true'); + } + _destroyUI() { + if (this._container) { + DOM.remove(this._container); + const mapCanvasContainer = this._map.getCanvasContainer(); + mapCanvasContainer.classList.remove('maplibregl-cooperative-gestures'); + } + delete this._container; + } + enable() { + this._setupUI(); + this._enabled = true; + } + disable() { + this._enabled = false; + this._destroyUI(); + } + isEnabled() { + return this._enabled; + } + isBypassed(event) { + return event[this._bypassKey]; + } + notifyGestureBlocked(gestureType, originalEvent) { + if (!this._enabled) + return; + // notify subscribers that a cooperative gesture was prevented + this._map.fire(new Event('cooperativegestureprevented', { gestureType, originalEvent })); + // Alert user how to scroll/pan + this._container.classList.add('maplibregl-show'); + setTimeout(() => { + this._container.classList.remove('maplibregl-show'); + }, 100); + } +} + +const isMoving = (p) => p.zoom || p.drag || p.pitch || p.rotate; +class RenderFrameEvent extends Event { +} +function hasChange(result) { + return (result.panDelta && result.panDelta.mag()) || result.zoomDelta || result.bearingDelta || result.pitchDelta; +} +class HandlerManager { + constructor(map, options) { + this.handleWindowEvent = (e) => { + this.handleEvent(e, `${e.type}Window`); + }; + this.handleEvent = (e, eventName) => { + if (e.type === 'blur') { + this.stop(true); + return; + } + this._updatingCamera = true; + const inputEvent = e.type === 'renderFrame' ? undefined : e; + /* + * We don't call e.preventDefault() for any events by default. + * Handlers are responsible for calling it where necessary. + */ + const mergedHandlerResult = { needsRenderFrame: false }; + const eventsInProgress = {}; + const activeHandlers = {}; + const eventTouches = e.touches; + const mapTouches = eventTouches ? this._getMapTouches(eventTouches) : undefined; + const points = mapTouches ? + DOM.touchPos(this._map.getCanvas(), mapTouches) : + DOM.mousePos(this._map.getCanvas(), e); + for (const { handlerName, handler, allowed } of this._handlers) { + if (!handler.isEnabled()) + continue; + let data; + if (this._blockedByActive(activeHandlers, allowed, handlerName)) { + handler.reset(); + } + else { + if (handler[eventName || e.type]) { + data = handler[eventName || e.type](e, points, mapTouches); + this.mergeHandlerResult(mergedHandlerResult, eventsInProgress, data, handlerName, inputEvent); + if (data && data.needsRenderFrame) { + this._triggerRenderFrame(); + } + } + } + if (data || handler.isActive()) { + activeHandlers[handlerName] = handler; + } + } + const deactivatedHandlers = {}; + for (const name in this._previousActiveHandlers) { + if (!activeHandlers[name]) { + deactivatedHandlers[name] = inputEvent; + } + } + this._previousActiveHandlers = activeHandlers; + if (Object.keys(deactivatedHandlers).length || hasChange(mergedHandlerResult)) { + this._changes.push([mergedHandlerResult, eventsInProgress, deactivatedHandlers]); + this._triggerRenderFrame(); + } + if (Object.keys(activeHandlers).length || hasChange(mergedHandlerResult)) { + this._map._stop(true); + } + this._updatingCamera = false; + const { cameraAnimation } = mergedHandlerResult; + if (cameraAnimation) { + this._inertia.clear(); + this._fireEvents({}, {}, true); + this._changes = []; + cameraAnimation(this._map); + } + }; + this._map = map; + this._el = this._map.getCanvasContainer(); + this._handlers = []; + this._handlersById = {}; + this._changes = []; + this._inertia = new HandlerInertia(map); + this._bearingSnap = options.bearingSnap; + this._previousActiveHandlers = {}; + // Track whether map is currently moving, to compute start/move/end events + this._eventsInProgress = {}; + this._addDefaultHandlers(options); + const el = this._el; + this._listeners = [ + // This needs to be `passive: true` so that a double tap fires two + // pairs of touchstart/end events in iOS Safari 13. If this is set to + // `passive: false` then the second pair of events is only fired if + // preventDefault() is called on the first touchstart. Calling preventDefault() + // undesirably prevents click events. + [el, 'touchstart', { passive: true }], + // This needs to be `passive: false` so that scrolls and pinches can be + // prevented in browsers that don't support `touch-actions: none`, for example iOS Safari 12. + [el, 'touchmove', { passive: false }], + [el, 'touchend', undefined], + [el, 'touchcancel', undefined], + [el, 'mousedown', undefined], + [el, 'mousemove', undefined], + [el, 'mouseup', undefined], + // Bind window-level event listeners for move and up/end events. In the absence of + // the pointer capture API, which is not supported by all necessary platforms, + // window-level event listeners give us the best shot at capturing events that + // fall outside the map canvas element. Use `{capture: true}` for the move event + // to prevent map move events from being fired during a drag. + [document, 'mousemove', { capture: true }], + [document, 'mouseup', undefined], + [el, 'mouseover', undefined], + [el, 'mouseout', undefined], + [el, 'dblclick', undefined], + [el, 'click', undefined], + [el, 'keydown', { capture: false }], + [el, 'keyup', undefined], + [el, 'wheel', { passive: false }], + [el, 'contextmenu', undefined], + [window, 'blur', undefined] + ]; + for (const [target, type, listenerOptions] of this._listeners) { + DOM.addEventListener(target, type, target === document ? this.handleWindowEvent : this.handleEvent, listenerOptions); + } + } + destroy() { + for (const [target, type, listenerOptions] of this._listeners) { + DOM.removeEventListener(target, type, target === document ? this.handleWindowEvent : this.handleEvent, listenerOptions); + } + } + _addDefaultHandlers(options) { + const map = this._map; + const el = map.getCanvasContainer(); + this._add('mapEvent', new MapEventHandler(map, options)); + const boxZoom = map.boxZoom = new BoxZoomHandler(map, options); + this._add('boxZoom', boxZoom); + if (options.interactive && options.boxZoom) { + boxZoom.enable(); + } + const cooperativeGestures = map.cooperativeGestures = new CooperativeGesturesHandler(map, options.cooperativeGestures); + this._add('cooperativeGestures', cooperativeGestures); + if (options.cooperativeGestures) { + cooperativeGestures.enable(); + } + const tapZoom = new TapZoomHandler(map); + const clickZoom = new ClickZoomHandler(map); + map.doubleClickZoom = new DoubleClickZoomHandler(clickZoom, tapZoom); + this._add('tapZoom', tapZoom); + this._add('clickZoom', clickZoom); + if (options.interactive && options.doubleClickZoom) { + map.doubleClickZoom.enable(); + } + const tapDragZoom = new TapDragZoomHandler(); + this._add('tapDragZoom', tapDragZoom); + const touchPitch = map.touchPitch = new TwoFingersTouchPitchHandler(map); + this._add('touchPitch', touchPitch); + if (options.interactive && options.touchPitch) { + map.touchPitch.enable(options.touchPitch); + } + const mouseRotate = generateMouseRotationHandler(options); + const mousePitch = generateMousePitchHandler(options); + map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch); + this._add('mouseRotate', mouseRotate, ['mousePitch']); + this._add('mousePitch', mousePitch, ['mouseRotate']); + if (options.interactive && options.dragRotate) { + map.dragRotate.enable(); + } + const mousePan = generateMousePanHandler(options); + const touchPan = new TouchPanHandler(options, map); + map.dragPan = new DragPanHandler(el, mousePan, touchPan); + this._add('mousePan', mousePan); + this._add('touchPan', touchPan, ['touchZoom', 'touchRotate']); + if (options.interactive && options.dragPan) { + map.dragPan.enable(options.dragPan); + } + const touchRotate = new TwoFingersTouchRotateHandler(); + const touchZoom = new TwoFingersTouchZoomHandler(); + map.touchZoomRotate = new TwoFingersTouchZoomRotateHandler(el, touchZoom, touchRotate, tapDragZoom); + this._add('touchRotate', touchRotate, ['touchPan', 'touchZoom']); + this._add('touchZoom', touchZoom, ['touchPan', 'touchRotate']); + if (options.interactive && options.touchZoomRotate) { + map.touchZoomRotate.enable(options.touchZoomRotate); + } + const scrollZoom = map.scrollZoom = new ScrollZoomHandler(map, () => this._triggerRenderFrame()); + this._add('scrollZoom', scrollZoom, ['mousePan']); + if (options.interactive && options.scrollZoom) { + map.scrollZoom.enable(options.scrollZoom); + } + const keyboard = map.keyboard = new KeyboardHandler(map); + this._add('keyboard', keyboard); + if (options.interactive && options.keyboard) { + map.keyboard.enable(); + } + this._add('blockableMapEvent', new BlockableMapEventHandler(map)); + } + _add(handlerName, handler, allowed) { + this._handlers.push({ handlerName, handler, allowed }); + this._handlersById[handlerName] = handler; + } + stop(allowEndAnimation) { + // do nothing if this method was triggered by a gesture update + if (this._updatingCamera) + return; + for (const { handler } of this._handlers) { + handler.reset(); + } + this._inertia.clear(); + this._fireEvents({}, {}, allowEndAnimation); + this._changes = []; + } + isActive() { + for (const { handler } of this._handlers) { + if (handler.isActive()) + return true; + } + return false; + } + isZooming() { + return !!this._eventsInProgress.zoom || this._map.scrollZoom.isZooming(); + } + isRotating() { + return !!this._eventsInProgress.rotate; + } + isMoving() { + return Boolean(isMoving(this._eventsInProgress)) || this.isZooming(); + } + _blockedByActive(activeHandlers, allowed, myName) { + for (const name in activeHandlers) { + if (name === myName) + continue; + if (!allowed || allowed.indexOf(name) < 0) { + return true; + } + } + return false; + } + _getMapTouches(touches) { + const mapTouches = []; + for (const t of touches) { + const target = t.target; + if (this._el.contains(target)) { + mapTouches.push(t); + } + } + return mapTouches; + } + mergeHandlerResult(mergedHandlerResult, eventsInProgress, handlerResult, name, e) { + if (!handlerResult) + return; + extend(mergedHandlerResult, handlerResult); + const eventData = { handlerName: name, originalEvent: handlerResult.originalEvent || e }; + // track which handler changed which camera property + if (handlerResult.zoomDelta !== undefined) { + eventsInProgress.zoom = eventData; + } + if (handlerResult.panDelta !== undefined) { + eventsInProgress.drag = eventData; + } + if (handlerResult.pitchDelta !== undefined) { + eventsInProgress.pitch = eventData; + } + if (handlerResult.bearingDelta !== undefined) { + eventsInProgress.rotate = eventData; + } + } + _applyChanges() { + const combined = {}; + const combinedEventsInProgress = {}; + const combinedDeactivatedHandlers = {}; + for (const [change, eventsInProgress, deactivatedHandlers] of this._changes) { + if (change.panDelta) + combined.panDelta = (combined.panDelta || new Point$2(0, 0))._add(change.panDelta); + if (change.zoomDelta) + combined.zoomDelta = (combined.zoomDelta || 0) + change.zoomDelta; + if (change.bearingDelta) + combined.bearingDelta = (combined.bearingDelta || 0) + change.bearingDelta; + if (change.pitchDelta) + combined.pitchDelta = (combined.pitchDelta || 0) + change.pitchDelta; + if (change.around !== undefined) + combined.around = change.around; + if (change.pinchAround !== undefined) + combined.pinchAround = change.pinchAround; + if (change.noInertia) + combined.noInertia = change.noInertia; + extend(combinedEventsInProgress, eventsInProgress); + extend(combinedDeactivatedHandlers, deactivatedHandlers); + } + this._updateMapTransform(combined, combinedEventsInProgress, combinedDeactivatedHandlers); + this._changes = []; + } + _updateMapTransform(combinedResult, combinedEventsInProgress, deactivatedHandlers) { + const map = this._map; + const tr = map._getTransformForUpdate(); + const terrain = map.terrain; + if (!hasChange(combinedResult) && !(terrain && this._terrainMovement)) { + return this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true); + } + let { panDelta, zoomDelta, bearingDelta, pitchDelta, around, pinchAround } = combinedResult; + if (pinchAround !== undefined) { + around = pinchAround; + } + // stop any ongoing camera animations (easeTo, flyTo) + map._stop(true); + around = around || map.transform.centerPoint; + const loc = tr.pointLocation(panDelta ? around.sub(panDelta) : around); + if (bearingDelta) + tr.bearing += bearingDelta; + if (pitchDelta) + tr.pitch += pitchDelta; + if (zoomDelta) + tr.zoom += zoomDelta; + if (!terrain) { + tr.setLocationAtPoint(loc, around); + } + else { + // when 3d-terrain is enabled act a little different: + // - dragging do not drag the picked point itself, instead it drags the map by pixel-delta. + // With this approach it is no longer possible to pick a point from somewhere near + // the horizon to the center in one move. + // So this logic avoids the problem, that in such cases you easily loose orientation. + if (!this._terrainMovement && + (combinedEventsInProgress.drag || combinedEventsInProgress.zoom)) { + // When starting to drag or move, flag it and register moveend to clear flagging + this._terrainMovement = true; + this._map._elevationFreeze = true; + tr.setLocationAtPoint(loc, around); + } + else if (combinedEventsInProgress.drag && this._terrainMovement) { + // drag map + tr.center = tr.pointLocation(tr.centerPoint.sub(panDelta)); + } + else { + tr.setLocationAtPoint(loc, around); + } + } + map._applyUpdatedTransform(tr); + this._map._update(); + if (!combinedResult.noInertia) + this._inertia.record(combinedResult); + this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true); + } + _fireEvents(newEventsInProgress, deactivatedHandlers, allowEndAnimation) { + const wasMoving = isMoving(this._eventsInProgress); + const nowMoving = isMoving(newEventsInProgress); + const startEvents = {}; + for (const eventName in newEventsInProgress) { + const { originalEvent } = newEventsInProgress[eventName]; + if (!this._eventsInProgress[eventName]) { + startEvents[`${eventName}start`] = originalEvent; + } + this._eventsInProgress[eventName] = newEventsInProgress[eventName]; + } + // fire start events only after this._eventsInProgress has been updated + if (!wasMoving && nowMoving) { + this._fireEvent('movestart', nowMoving.originalEvent); + } + for (const name in startEvents) { + this._fireEvent(name, startEvents[name]); + } + if (nowMoving) { + this._fireEvent('move', nowMoving.originalEvent); + } + for (const eventName in newEventsInProgress) { + const { originalEvent } = newEventsInProgress[eventName]; + this._fireEvent(eventName, originalEvent); + } + const endEvents = {}; + let originalEndEvent; + for (const eventName in this._eventsInProgress) { + const { handlerName, originalEvent } = this._eventsInProgress[eventName]; + if (!this._handlersById[handlerName].isActive()) { + delete this._eventsInProgress[eventName]; + originalEndEvent = deactivatedHandlers[handlerName] || originalEvent; + endEvents[`${eventName}end`] = originalEndEvent; + } + } + for (const name in endEvents) { + this._fireEvent(name, endEvents[name]); + } + const stillMoving = isMoving(this._eventsInProgress); + const finishedMoving = (wasMoving || nowMoving) && !stillMoving; + if (finishedMoving && this._terrainMovement) { + this._map._elevationFreeze = false; + this._terrainMovement = false; + const tr = this._map._getTransformForUpdate(); + tr.recalculateZoom(this._map.terrain); + this._map._applyUpdatedTransform(tr); + } + if (allowEndAnimation && finishedMoving) { + this._updatingCamera = true; + const inertialEase = this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions); + const shouldSnapToNorth = bearing => bearing !== 0 && -this._bearingSnap < bearing && bearing < this._bearingSnap; + if (inertialEase && (inertialEase.essential || !browser.prefersReducedMotion)) { + if (shouldSnapToNorth(inertialEase.bearing || this._map.getBearing())) { + inertialEase.bearing = 0; + } + inertialEase.freezeElevation = true; + this._map.easeTo(inertialEase, { originalEvent: originalEndEvent }); + } + else { + this._map.fire(new Event('moveend', { originalEvent: originalEndEvent })); + if (shouldSnapToNorth(this._map.getBearing())) { + this._map.resetNorth(); + } + } + this._updatingCamera = false; + } + } + _fireEvent(type, e) { + this._map.fire(new Event(type, e ? { originalEvent: e } : {})); + } + _requestFrame() { + this._map.triggerRepaint(); + return this._map._renderTaskQueue.add(timeStamp => { + delete this._frameId; + this.handleEvent(new RenderFrameEvent('renderFrame', { timeStamp })); + this._applyChanges(); + }); + } + _triggerRenderFrame() { + if (this._frameId === undefined) { + this._frameId = this._requestFrame(); + } + } +} + +class Camera extends Evented { + constructor(transform, options) { + super(); + // Callback for map._requestRenderFrame + this._renderFrameCallback = () => { + const t = Math.min((browser.now() - this._easeStart) / this._easeOptions.duration, 1); + this._onEaseFrame(this._easeOptions.easing(t)); + // if _stop is called during _onEaseFrame from _fireMoveEvents we should avoid a new _requestRenderFrame, checking it by ensuring _easeFrameId was not deleted + if (t < 1 && this._easeFrameId) { + this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback); + } + else { + this.stop(); + } + }; + this._moving = false; + this._zooming = false; + this.transform = transform; + this._bearingSnap = options.bearingSnap; + this.on('moveend', () => { + delete this._requestedCameraState; + }); + } + /** + * Returns the map's geographical centerpoint. + * + * @returns The map's geographical centerpoint. + * @example + * Return a LngLat object such as `{lng: 0, lat: 0}` + * ```ts + * let center = map.getCenter(); + * // access longitude and latitude values directly + * let {lng, lat} = map.getCenter(); + * ``` + */ + getCenter() { return new LngLat(this.transform.center.lng, this.transform.center.lat); } + /** + * Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param center - The centerpoint to set. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * map.setCenter([-74, 38]); + * ``` + */ + setCenter(center, eventData) { + return this.jumpTo({ center }, eventData); + } + /** + * Pans the map by the specified offset. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param offset - `x` and `y` coordinates by which to pan the map. + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/) + */ + panBy(offset, options, eventData) { + offset = Point$2.convert(offset).mult(-1); + return this.panTo(this.transform.center, extend({ offset }, options), eventData); + } + /** + * Pans the map to the specified location with an animated transition. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param lnglat - The location to pan the map to. + * @param options - Options describing the destination and animation of the transition. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * map.panTo([-74, 38]); + * // Specify that the panTo animation should last 5000 milliseconds. + * map.panTo([-74, 38], {duration: 5000}); + * ``` + * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/live-update-feature/) + */ + panTo(lnglat, options, eventData) { + return this.easeTo(extend({ + center: lnglat + }, options), eventData); + } + /** + * Returns the map's current zoom level. + * + * @returns The map's current zoom level. + * @example + * ```ts + * map.getZoom(); + * ``` + */ + getZoom() { return this.transform.zoom; } + /** + * Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param zoom - The zoom level to set (0-20). + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Zoom to the zoom level 5 without an animated transition + * ```ts + * map.setZoom(5); + * ``` + */ + setZoom(zoom, eventData) { + this.jumpTo({ zoom }, eventData); + return this; + } + /** + * Zooms the map to the specified zoom level, with an animated transition. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param zoom - The zoom level to transition to. + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * // Zoom to the zoom level 5 without an animated transition + * map.zoomTo(5); + * // Zoom to the zoom level 8 with an animated transition + * map.zoomTo(8, { + * duration: 2000, + * offset: [100, 50] + * }); + * ``` + */ + zoomTo(zoom, options, eventData) { + return this.easeTo(extend({ + zoom + }, options), eventData); + } + /** + * Increases the map's zoom level by 1. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Zoom the map in one level with a custom animation duration + * ```ts + * map.zoomIn({duration: 1000}); + * ``` + */ + zoomIn(options, eventData) { + this.zoomTo(this.getZoom() + 1, options, eventData); + return this; + } + /** + * Decreases the map's zoom level by 1. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Zoom the map out one level with a custom animation offset + * ```ts + * map.zoomOut({offset: [80, 60]}); + * ``` + */ + zoomOut(options, eventData) { + this.zoomTo(this.getZoom() - 1, options, eventData); + return this; + } + /** + * Returns the map's current bearing. The bearing is the compass direction that is "up"; for example, a bearing + * of 90° orients the map so that east is up. + * + * @returns The map's current bearing. + * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/) + */ + getBearing() { return this.transform.bearing; } + /** + * Sets the map's bearing (rotation). The bearing is the compass direction that is "up"; for example, a bearing + * of 90° orients the map so that east is up. + * + * Equivalent to `jumpTo({bearing: bearing})`. + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param bearing - The desired bearing. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Rotate the map to 90 degrees + * ```ts + * map.setBearing(90); + * ``` + */ + setBearing(bearing, eventData) { + this.jumpTo({ bearing }, eventData); + return this; + } + /** + * Returns the current padding applied around the map viewport. + * + * @returns The current padding around the map viewport. + */ + getPadding() { return this.transform.padding; } + /** + * Sets the padding in pixels around the viewport. + * + * Equivalent to `jumpTo({padding: padding})`. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param padding - The desired padding. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Sets a left padding of 300px, and a top padding of 50px + * ```ts + * map.setPadding({ left: 300, top: 50 }); + * ``` + */ + setPadding(padding, eventData) { + this.jumpTo({ padding }, eventData); + return this; + } + /** + * Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction + * that is "up"; for example, a bearing of 90° orients the map so that east is up. + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param bearing - The desired bearing. + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + rotateTo(bearing, options, eventData) { + return this.easeTo(extend({ + bearing + }, options), eventData); + } + /** + * Rotates the map so that north is up (0° bearing), with an animated transition. + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + resetNorth(options, eventData) { + this.rotateTo(0, extend({ duration: 1000 }, options), eventData); + return this; + } + /** + * Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + resetNorthPitch(options, eventData) { + this.easeTo(extend({ + bearing: 0, + pitch: 0, + duration: 1000 + }, options), eventData); + return this; + } + /** + * Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the + * `bearingSnap` threshold). + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + snapToNorth(options, eventData) { + if (Math.abs(this.getBearing()) < this._bearingSnap) { + return this.resetNorth(options, eventData); + } + return this; + } + /** + * Returns the map's current pitch (tilt). + * + * @returns The map's current pitch, measured in degrees away from the plane of the screen. + */ + getPitch() { return this.transform.pitch; } + /** + * Sets the map's pitch (tilt). Equivalent to `jumpTo({pitch: pitch})`. + * + * Triggers the following events: `movestart`, `moveend`, `pitchstart`, and `pitchend`. + * + * @param pitch - The pitch to set, measured in degrees away from the plane of the screen (0-60). + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + setPitch(pitch, eventData) { + this.jumpTo({ pitch }, eventData); + return this; + } + /** + * @param bounds - Calculate the center for these bounds in the viewport and use + * the highest zoom level up to and including `Map#getMaxZoom()` that fits + * in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0. + * Bounds will be taken in [sw, ne] order. Southwest point will always be to the left of the northeast point. + * @param options - Options object + * @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`. + * If map is unable to fit, method will warn and return undefined. + * @example + * ```ts + * let bbox = [[-79, 43], [-73, 45]]; + * let newCameraTransform = map.cameraForBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + */ + cameraForBounds(bounds, options) { + bounds = LngLatBounds.convert(bounds).adjustAntiMeridian(); + const bearing = options && options.bearing || 0; + return this._cameraForBoxAndBearing(bounds.getNorthWest(), bounds.getSouthEast(), bearing, options); + } + /** + * @internal + * Calculate the center of these two points in the viewport and use + * the highest zoom level up to and including `Map#getMaxZoom()` that fits + * the points in the viewport at the specified bearing. + * @param p0 - First point + * @param p1 - Second point + * @param bearing - Desired map bearing at end of animation, in degrees + * @param options - the camera options + * @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`. + * If map is unable to fit, method will warn and return undefined. + * @example + * ```ts + * let p0 = [-79, 43]; + * let p1 = [-73, 45]; + * let bearing = 90; + * let newCameraTransform = map._cameraForBoxAndBearing(p0, p1, bearing, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + */ + _cameraForBoxAndBearing(p0, p1, bearing, options) { + const defaultPadding = { + top: 0, + bottom: 0, + right: 0, + left: 0 + }; + options = extend({ + padding: defaultPadding, + offset: [0, 0], + maxZoom: this.transform.maxZoom + }, options); + if (typeof options.padding === 'number') { + const p = options.padding; + options.padding = { + top: p, + bottom: p, + right: p, + left: p + }; + } + options.padding = extend(defaultPadding, options.padding); + const tr = this.transform; + const edgePadding = tr.padding; + // Consider all corners of the rotated bounding box derived from the given points + // when find the camera position that fits the given points. + const bounds = new LngLatBounds(p0, p1); + const nwWorld = tr.project(bounds.getNorthWest()); + const neWorld = tr.project(bounds.getNorthEast()); + const seWorld = tr.project(bounds.getSouthEast()); + const swWorld = tr.project(bounds.getSouthWest()); + const bearingRadians = degreesToRadians(-bearing); + const nwRotatedWorld = nwWorld.rotate(bearingRadians); + const neRotatedWorld = neWorld.rotate(bearingRadians); + const seRotatedWorld = seWorld.rotate(bearingRadians); + const swRotatedWorld = swWorld.rotate(bearingRadians); + const upperRight = new Point$2(Math.max(nwRotatedWorld.x, neRotatedWorld.x, swRotatedWorld.x, seRotatedWorld.x), Math.max(nwRotatedWorld.y, neRotatedWorld.y, swRotatedWorld.y, seRotatedWorld.y)); + const lowerLeft = new Point$2(Math.min(nwRotatedWorld.x, neRotatedWorld.x, swRotatedWorld.x, seRotatedWorld.x), Math.min(nwRotatedWorld.y, neRotatedWorld.y, swRotatedWorld.y, seRotatedWorld.y)); + // Calculate zoom: consider the original bbox and padding. + const size = upperRight.sub(lowerLeft); + const scaleX = (tr.width - (edgePadding.left + edgePadding.right + options.padding.left + options.padding.right)) / size.x; + const scaleY = (tr.height - (edgePadding.top + edgePadding.bottom + options.padding.top + options.padding.bottom)) / size.y; + if (scaleY < 0 || scaleX < 0) { + warnOnce('Map cannot fit within canvas with the given bounds, padding, and/or offset.'); + return undefined; + } + const zoom = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom); + // Calculate center: apply the zoom, the configured offset, as well as offset that exists as a result of padding. + const offset = Point$2.convert(options.offset); + const paddingOffsetX = (options.padding.left - options.padding.right) / 2; + const paddingOffsetY = (options.padding.top - options.padding.bottom) / 2; + const paddingOffset = new Point$2(paddingOffsetX, paddingOffsetY); + const rotatedPaddingOffset = paddingOffset.rotate(degreesToRadians(bearing)); + const offsetAtInitialZoom = offset.add(rotatedPaddingOffset); + const offsetAtFinalZoom = offsetAtInitialZoom.mult(tr.scale / tr.zoomScale(zoom)); + const center = tr.unproject( + // either world diagonal can be used (NW-SE or NE-SW) + nwWorld.add(seWorld).div(2).sub(offsetAtFinalZoom)); + return { + center, + zoom, + bearing + }; + } + /** + * Pans and zooms the map to contain its visible area within the specified geographical bounds. + * This function will also reset the map's bearing to 0 if bearing is nonzero. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param bounds - Center these bounds in the viewport and use the highest + * zoom level up to and including `Map#getMaxZoom()` that fits them in the viewport. + * Bounds will be taken in [sw, ne] order. Southwest point will always be to the left of the northeast point. + * @param options - Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * let bbox = [[-79, 43], [-73, 45]]; + * map.fitBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + * @see [Fit a map to a bounding box](https://maplibre.org/maplibre-gl-js/docs/examples/fitbounds/) + */ + fitBounds(bounds, options, eventData) { + return this._fitInternal(this.cameraForBounds(bounds, options), options, eventData); + } + /** + * Pans, rotates and zooms the map to to fit the box made by points p0 and p1 + * once the map is rotated to the specified bearing. To zoom without rotating, + * pass in the current map bearing. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend` and `rotate`. + * + * @param p0 - First point on screen, in pixel coordinates + * @param p1 - Second point on screen, in pixel coordinates + * @param bearing - Desired map bearing at end of animation, in degrees + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * let p0 = [220, 400]; + * let p1 = [500, 900]; + * map.fitScreenCoordinates(p0, p1, map.getBearing(), { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + * @see Used by {@link BoxZoomHandler} + */ + fitScreenCoordinates(p0, p1, bearing, options, eventData) { + return this._fitInternal(this._cameraForBoxAndBearing(this.transform.pointLocation(Point$2.convert(p0)), this.transform.pointLocation(Point$2.convert(p1)), bearing, options), options, eventData); + } + _fitInternal(calculatedOptions, options, eventData) { + // cameraForBounds warns + returns undefined if unable to fit: + if (!calculatedOptions) + return this; + options = extend(calculatedOptions, options); + // Explicitly remove the padding field because, calculatedOptions already accounts for padding by setting zoom and center accordingly. + delete options.padding; + return options.linear ? + this.easeTo(options, eventData) : + this.flyTo(options, eventData); + } + /** + * Changes any combination of center, zoom, bearing, and pitch, without + * an animated transition. The map will retain its current values for any + * details not specified in `options`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`, + * `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * // jump to coordinates at current zoom + * map.jumpTo({center: [0, 0]}); + * // jump with zoom, pitch, and bearing options + * map.jumpTo({ + * center: [0, 0], + * zoom: 8, + * pitch: 45, + * bearing: 90 + * }); + * ``` + * @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js/docs/examples/jump-to/) + * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/live-update-feature/) + */ + jumpTo(options, eventData) { + this.stop(); + const tr = this._getTransformForUpdate(); + let zoomChanged = false, bearingChanged = false, pitchChanged = false; + if ('zoom' in options && tr.zoom !== +options.zoom) { + zoomChanged = true; + tr.zoom = +options.zoom; + } + if (options.center !== undefined) { + tr.center = LngLat.convert(options.center); + } + if ('bearing' in options && tr.bearing !== +options.bearing) { + bearingChanged = true; + tr.bearing = +options.bearing; + } + if ('pitch' in options && tr.pitch !== +options.pitch) { + pitchChanged = true; + tr.pitch = +options.pitch; + } + if (options.padding != null && !tr.isPaddingEqual(options.padding)) { + tr.padding = options.padding; + } + this._applyUpdatedTransform(tr); + this.fire(new Event('movestart', eventData)) + .fire(new Event('move', eventData)); + if (zoomChanged) { + this.fire(new Event('zoomstart', eventData)) + .fire(new Event('zoom', eventData)) + .fire(new Event('zoomend', eventData)); + } + if (bearingChanged) { + this.fire(new Event('rotatestart', eventData)) + .fire(new Event('rotate', eventData)) + .fire(new Event('rotateend', eventData)); + } + if (pitchChanged) { + this.fire(new Event('pitchstart', eventData)) + .fire(new Event('pitch', eventData)) + .fire(new Event('pitchend', eventData)); + } + return this.fire(new Event('moveend', eventData)); + } + /** + * Calculates pitch, zoom and bearing for looking at `newCenter` with the camera position being `newCenter` + * and returns them as {@link CameraOptions}. + * @param from - The camera to look from + * @param altitudeFrom - The altitude of the camera to look from + * @param to - The center to look at + * @param altitudeTo - Optional altitude of the center to look at. If none given the ground height will be used. + * @returns the calculated camera options + */ + calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo = 0) { + const fromMerc = MercatorCoordinate.fromLngLat(from, altitudeFrom); + const toMerc = MercatorCoordinate.fromLngLat(to, altitudeTo); + const dx = toMerc.x - fromMerc.x; + const dy = toMerc.y - fromMerc.y; + const dz = toMerc.z - fromMerc.z; + const distance3D = Math.hypot(dx, dy, dz); + if (distance3D === 0) + throw new Error('Can\'t calculate camera options with same From and To'); + const groundDistance = Math.hypot(dx, dy); + const zoom = this.transform.scaleZoom(this.transform.cameraToCenterDistance / distance3D / this.transform.tileSize); + const bearing = (Math.atan2(dx, -dy) * 180) / Math.PI; + let pitch = (Math.acos(groundDistance / distance3D) * 180) / Math.PI; + pitch = dz < 0 ? 90 - pitch : 90 + pitch; + return { + center: toMerc.toLngLat(), + zoom, + pitch, + bearing + }; + } + /** + * Changes any combination of `center`, `zoom`, `bearing`, `pitch`, and `padding` with an animated transition + * between old and new values. The map will retain its current values for any + * details not specified in `options`. + * + * Note: The transition will happen instantly if the user has enabled + * the `reduced motion` accessibility feature enabled in their operating system, + * unless `options` includes `essential: true`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`, + * `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options describing the destination and animation of the transition. + * Accepts {@link CameraOptions} and {@link AnimationOptions}. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/) + */ + easeTo(options, eventData) { + var _a; + this._stop(false, options.easeId); + options = extend({ + offset: [0, 0], + duration: 500, + easing: defaultEasing + }, options); + if (options.animate === false || (!options.essential && browser.prefersReducedMotion)) + options.duration = 0; + const tr = this._getTransformForUpdate(), startZoom = tr.zoom, startBearing = tr.bearing, startPitch = tr.pitch, startPadding = tr.padding, bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing, pitch = 'pitch' in options ? +options.pitch : startPitch, padding = 'padding' in options ? options.padding : tr.padding; + const offsetAsPoint = Point$2.convert(options.offset); + let pointAtOffset = tr.centerPoint.add(offsetAsPoint); + const locationAtOffset = tr.pointLocation(pointAtOffset); + const { center, zoom } = tr.getConstrained(LngLat.convert(options.center || locationAtOffset), (_a = options.zoom) !== null && _a !== void 0 ? _a : startZoom); + this._normalizeCenter(center, tr); + const from = tr.project(locationAtOffset); + const delta = tr.project(center).sub(from); + const finalScale = tr.zoomScale(zoom - startZoom); + let around, aroundPoint; + if (options.around) { + around = LngLat.convert(options.around); + aroundPoint = tr.locationPoint(around); + } + const currently = { + moving: this._moving, + zooming: this._zooming, + rotating: this._rotating, + pitching: this._pitching + }; + this._zooming = this._zooming || (zoom !== startZoom); + this._rotating = this._rotating || (startBearing !== bearing); + this._pitching = this._pitching || (pitch !== startPitch); + this._padding = !tr.isPaddingEqual(padding); + this._easeId = options.easeId; + this._prepareEase(eventData, options.noMoveStart, currently); + if (this.terrain) + this._prepareElevation(center); + this._ease((k) => { + if (this._zooming) { + tr.zoom = interpolate.number(startZoom, zoom, k); + } + if (this._rotating) { + tr.bearing = interpolate.number(startBearing, bearing, k); + } + if (this._pitching) { + tr.pitch = interpolate.number(startPitch, pitch, k); + } + if (this._padding) { + tr.interpolatePadding(startPadding, padding, k); + // When padding is being applied, Transform#centerPoint is changing continuously, + // thus we need to recalculate offsetPoint every frame + pointAtOffset = tr.centerPoint.add(offsetAsPoint); + } + if (this.terrain && !options.freezeElevation) + this._updateElevation(k); + if (around) { + tr.setLocationAtPoint(around, aroundPoint); + } + else { + const scale = tr.zoomScale(tr.zoom - startZoom); + const base = zoom > startZoom ? + Math.min(2, finalScale) : + Math.max(0.5, finalScale); + const speedup = Math.pow(base, 1 - k); + const newCenter = tr.unproject(from.add(delta.mult(k * speedup)).mult(scale)); + tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset); + } + this._applyUpdatedTransform(tr); + this._fireMoveEvents(eventData); + }, (interruptingEaseId) => { + if (this.terrain && options.freezeElevation) + this._finalizeElevation(); + this._afterEase(eventData, interruptingEaseId); + }, options); + return this; + } + _prepareEase(eventData, noMoveStart, currently = {}) { + this._moving = true; + if (!noMoveStart && !currently.moving) { + this.fire(new Event('movestart', eventData)); + } + if (this._zooming && !currently.zooming) { + this.fire(new Event('zoomstart', eventData)); + } + if (this._rotating && !currently.rotating) { + this.fire(new Event('rotatestart', eventData)); + } + if (this._pitching && !currently.pitching) { + this.fire(new Event('pitchstart', eventData)); + } + } + _prepareElevation(center) { + this._elevationCenter = center; + this._elevationStart = this.transform.elevation; + this._elevationTarget = this.terrain.getElevationForLngLatZoom(center, this.transform.tileZoom); + this._elevationFreeze = true; + } + _updateElevation(k) { + this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter, this.transform.tileZoom); + const elevation = this.terrain.getElevationForLngLatZoom(this._elevationCenter, this.transform.tileZoom); + // target terrain updated during flight, slowly move camera to new height + if (k < 1 && elevation !== this._elevationTarget) { + const pitch1 = this._elevationTarget - this._elevationStart; + const pitch2 = (elevation - (pitch1 * k + this._elevationStart)) / (1 - k); + this._elevationStart += k * (pitch1 - pitch2); + this._elevationTarget = elevation; + } + this.transform.elevation = interpolate.number(this._elevationStart, this._elevationTarget, k); + } + _finalizeElevation() { + this._elevationFreeze = false; + this.transform.recalculateZoom(this.terrain); + } + /** + * @internal + * Called when the camera is about to be manipulated. + * If `transformCameraUpdate` is specified or terrain is enabled, a copy of + * the current transform is created to track the accumulated changes. + * This underlying transform represents the "desired state" proposed by input handlers / animations / UI controls. + * It may differ from the state used for rendering (`this.transform`). + * @returns Transform to apply changes to + */ + _getTransformForUpdate() { + if (!this.transformCameraUpdate && !this.terrain) + return this.transform; + if (!this._requestedCameraState) { + this._requestedCameraState = this.transform.clone(); + } + return this._requestedCameraState; + } + /** + * @internal + * Checks the given transform for the camera being below terrain surface and + * returns new pitch and zoom to fix that. + * + * With the new pitch and zoom, the camera will be at the same ground + * position but at higher altitude. It will still point to the same spot on + * the map. + * + * @param tr - The transform to check. + */ + _elevateCameraIfInsideTerrain(tr) { + const camera = tr.getCameraPosition(); + const minAltitude = this.terrain.getElevationForLngLatZoom(camera.lngLat, tr.zoom); + if (camera.altitude < minAltitude) { + const newCamera = this.calculateCameraOptionsFromTo(camera.lngLat, minAltitude, tr.center, tr.elevation); + return { + pitch: newCamera.pitch, + zoom: newCamera.zoom, + }; + } + return {}; + } + /** + * @internal + * Called after the camera is done being manipulated. + * @param tr - the requested camera end state + * If the camera is inside terrain, it gets elevated. + * Call `transformCameraUpdate` if present, and then apply the "approved" changes. + */ + _applyUpdatedTransform(tr) { + const modifiers = []; + if (this.terrain) { + modifiers.push(tr => this._elevateCameraIfInsideTerrain(tr)); + } + if (this.transformCameraUpdate) { + modifiers.push(tr => this.transformCameraUpdate(tr)); + } + if (!modifiers.length) { + return; + } + const finalTransform = tr.clone(); + for (const modifier of modifiers) { + const nextTransform = finalTransform.clone(); + const { center, zoom, pitch, bearing, elevation } = modifier(nextTransform); + if (center) + nextTransform.center = center; + if (zoom !== undefined) + nextTransform.zoom = zoom; + if (pitch !== undefined) + nextTransform.pitch = pitch; + if (bearing !== undefined) + nextTransform.bearing = bearing; + if (elevation !== undefined) + nextTransform.elevation = elevation; + finalTransform.apply(nextTransform); + } + this.transform.apply(finalTransform); + } + _fireMoveEvents(eventData) { + this.fire(new Event('move', eventData)); + if (this._zooming) { + this.fire(new Event('zoom', eventData)); + } + if (this._rotating) { + this.fire(new Event('rotate', eventData)); + } + if (this._pitching) { + this.fire(new Event('pitch', eventData)); + } + } + _afterEase(eventData, easeId) { + // if this easing is being stopped to start another easing with + // the same id then don't fire any events to avoid extra start/stop events + if (this._easeId && easeId && this._easeId === easeId) { + return; + } + delete this._easeId; + const wasZooming = this._zooming; + const wasRotating = this._rotating; + const wasPitching = this._pitching; + this._moving = false; + this._zooming = false; + this._rotating = false; + this._pitching = false; + this._padding = false; + if (wasZooming) { + this.fire(new Event('zoomend', eventData)); + } + if (wasRotating) { + this.fire(new Event('rotateend', eventData)); + } + if (wasPitching) { + this.fire(new Event('pitchend', eventData)); + } + this.fire(new Event('moveend', eventData)); + } + /** + * Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that + * evokes flight. The animation seamlessly incorporates zooming and panning to help + * the user maintain her bearings even after traversing a great distance. + * + * Note: The animation will be skipped, and this will behave equivalently to `jumpTo` + * if the user has the `reduced motion` accessibility feature enabled in their operating system, + * unless 'options' includes `essential: true`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`, + * `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options describing the destination and animation of the transition. + * Accepts {@link CameraOptions}, {@link AnimationOptions}, + * and the following additional options. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * // fly with default options to null island + * map.flyTo({center: [0, 0], zoom: 9}); + * // using flyTo options + * map.flyTo({ + * center: [0, 0], + * zoom: 9, + * speed: 0.2, + * curve: 1, + * easing(t) { + * return t; + * } + * }); + * ``` + * @see [Fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/flyto/) + * @see [Slowly fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/flyto-options/) + * @see [Fly to a location based on scroll position](https://maplibre.org/maplibre-gl-js/docs/examples/scroll-fly-to/) + */ + flyTo(options, eventData) { + var _a; + // Fall through to jumpTo if user has set prefers-reduced-motion + if (!options.essential && browser.prefersReducedMotion) { + const coercedOptions = pick(options, ['center', 'zoom', 'bearing', 'pitch', 'around']); + return this.jumpTo(coercedOptions, eventData); + } + // This method implements an “optimal path” animation, as detailed in: + // + // Van Wijk, Jarke J.; Nuij, Wim A. A. “Smooth and efficient zooming and panning.” INFOVIS + // ’03. pp. 15–22. . + // + // Where applicable, local variable documentation begins with the associated variable or + // function in van Wijk (2003). + this.stop(); + options = extend({ + offset: [0, 0], + speed: 1.2, + curve: 1.42, + easing: defaultEasing + }, options); + const tr = this._getTransformForUpdate(), startZoom = tr.zoom, startBearing = tr.bearing, startPitch = tr.pitch, startPadding = tr.padding; + const bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing; + const pitch = 'pitch' in options ? +options.pitch : startPitch; + const padding = 'padding' in options ? options.padding : tr.padding; + const offsetAsPoint = Point$2.convert(options.offset); + let pointAtOffset = tr.centerPoint.add(offsetAsPoint); + const locationAtOffset = tr.pointLocation(pointAtOffset); + const { center, zoom } = tr.getConstrained(LngLat.convert(options.center || locationAtOffset), (_a = options.zoom) !== null && _a !== void 0 ? _a : startZoom); + this._normalizeCenter(center, tr); + const scale = tr.zoomScale(zoom - startZoom); + const from = tr.project(locationAtOffset); + const delta = tr.project(center).sub(from); + let rho = options.curve; + // w₀: Initial visible span, measured in pixels at the initial scale. + const w0 = Math.max(tr.width, tr.height), + // w₁: Final visible span, measured in pixels with respect to the initial scale. + w1 = w0 / scale, + // Length of the flight path as projected onto the ground plane, measured in pixels from + // the world image origin at the initial scale. + u1 = delta.mag(); + if ('minZoom' in options) { + const minZoom = clamp$1(Math.min(options.minZoom, startZoom, zoom), tr.minZoom, tr.maxZoom); + // wm: Maximum visible span, measured in pixels with respect to the initial + // scale. + const wMax = w0 / tr.zoomScale(minZoom - startZoom); + rho = Math.sqrt(wMax / u1 * 2); + } + // ρ² + const rho2 = rho * rho; + /** + * rᵢ: Returns the zoom-out factor at one end of the animation. + * + * @param descent - `true` for the descent, `false` for the ascent + */ + function zoomOutFactor(descent) { + const b = (w1 * w1 - w0 * w0 + (descent ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (descent ? w1 : w0) * rho2 * u1); + return Math.log(Math.sqrt(b * b + 1) - b); + } + function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; } + function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; } + function tanh(n) { return sinh(n) / cosh(n); } + // r₀: Zoom-out factor during ascent. + const r0 = zoomOutFactor(false); + // w(s): Returns the visible span on the ground, measured in pixels with respect to the + // initial scale. Assumes an angular field of view of 2 arctan ½ ≈ 53°. + let w = function (s) { + return (cosh(r0) / cosh(r0 + rho * s)); + }; + // u(s): Returns the distance along the flight path as projected onto the ground plane, + // measured in pixels from the world image origin at the initial scale. + let u = function (s) { + return w0 * ((cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2) / u1; + }; + // S: Total length of the flight path, measured in ρ-screenfuls. + let S = (zoomOutFactor(true) - r0) / rho; + // When u₀ = u₁, the optimal path doesn’t require both ascent and descent. + if (Math.abs(u1) < 0.000001 || !isFinite(S)) { + // Perform a more or less instantaneous transition if the path is too short. + if (Math.abs(w0 - w1) < 0.000001) + return this.easeTo(options, eventData); + const k = w1 < w0 ? -1 : 1; + S = Math.abs(Math.log(w1 / w0)) / rho; + u = () => 0; + w = (s) => Math.exp(k * rho * s); + } + if ('duration' in options) { + options.duration = +options.duration; + } + else { + const V = 'screenSpeed' in options ? +options.screenSpeed / rho : +options.speed; + options.duration = 1000 * S / V; + } + if (options.maxDuration && options.duration > options.maxDuration) { + options.duration = 0; + } + this._zooming = true; + this._rotating = (startBearing !== bearing); + this._pitching = (pitch !== startPitch); + this._padding = !tr.isPaddingEqual(padding); + this._prepareEase(eventData, false); + if (this.terrain) + this._prepareElevation(center); + this._ease((k) => { + // s: The distance traveled along the flight path, measured in ρ-screenfuls. + const s = k * S; + const scale = 1 / w(s); + tr.zoom = k === 1 ? zoom : startZoom + tr.scaleZoom(scale); + if (this._rotating) { + tr.bearing = interpolate.number(startBearing, bearing, k); + } + if (this._pitching) { + tr.pitch = interpolate.number(startPitch, pitch, k); + } + if (this._padding) { + tr.interpolatePadding(startPadding, padding, k); + // When padding is being applied, Transform#centerPoint is changing continuously, + // thus we need to recalculate offsetPoint every frame + pointAtOffset = tr.centerPoint.add(offsetAsPoint); + } + if (this.terrain && !options.freezeElevation) + this._updateElevation(k); + const newCenter = k === 1 ? center : tr.unproject(from.add(delta.mult(u(s))).mult(scale)); + tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset); + this._applyUpdatedTransform(tr); + this._fireMoveEvents(eventData); + }, () => { + if (this.terrain && options.freezeElevation) + this._finalizeElevation(); + this._afterEase(eventData); + }, options); + return this; + } + isEasing() { + return !!this._easeFrameId; + } + /** + * Stops any animated transition underway. + */ + stop() { + return this._stop(); + } + _stop(allowGestures, easeId) { + var _a; + if (this._easeFrameId) { + this._cancelRenderFrame(this._easeFrameId); + delete this._easeFrameId; + delete this._onEaseFrame; + } + if (this._onEaseEnd) { + // The _onEaseEnd function might emit events which trigger new + // animation, which sets a new _onEaseEnd. Ensure we don't delete + // it unintentionally. + const onEaseEnd = this._onEaseEnd; + delete this._onEaseEnd; + onEaseEnd.call(this, easeId); + } + if (!allowGestures) { + (_a = this.handlers) === null || _a === void 0 ? void 0 : _a.stop(false); + } + return this; + } + _ease(frame, finish, options) { + if (options.animate === false || options.duration === 0) { + frame(1); + finish(); + } + else { + this._easeStart = browser.now(); + this._easeOptions = options; + this._onEaseFrame = frame; + this._onEaseEnd = finish; + this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback); + } + } + // convert bearing so that it's numerically close to the current one so that it interpolates properly + _normalizeBearing(bearing, currentBearing) { + bearing = wrap(bearing, -180, 180); + const diff = Math.abs(bearing - currentBearing); + if (Math.abs(bearing - 360 - currentBearing) < diff) + bearing -= 360; + if (Math.abs(bearing + 360 - currentBearing) < diff) + bearing += 360; + return bearing; + } + // If a path crossing the antimeridian would be shorter, extend the final coordinate so that + // interpolating between the two endpoints will cross it. + _normalizeCenter(center, tr) { + if (!tr.renderWorldCopies || tr.lngRange) + return; + const delta = center.lng - tr.center.lng; + center.lng += + delta > 180 ? -360 : + delta < -180 ? 360 : 0; + } + /** + * Get the elevation difference between a given point + * and a point that is currently in the middle of the screen. + * This method should be used for proper positioning of custom 3d objects, as explained [here](https://maplibre.org/maplibre-gl-js/docs/examples/add-3d-model-with-terrain/) + * Returns null if terrain is not enabled. + * This method is subject to change in Maplibre GL JS v5. + * @param lngLatLike - [x,y] or LngLat coordinates of the location + * @returns elevation offset in meters + */ + queryTerrainElevation(lngLatLike) { + if (!this.terrain) { + return null; + } + const elevation = this.terrain.getElevationForLngLatZoom(LngLat.convert(lngLatLike), this.transform.tileZoom); + return elevation - this.transform.elevation; + } +} + +const defaultAttributionControlOptions = { + compact: true, + customAttribution: 'MapLibre' +}; +/** + * An `AttributionControl` control presents the map's attribution information. By default, the attribution control is expanded (regardless of map width). + * @group Markers and Controls + * @example + * ```ts + * let map = new Map({attributionControl: false}) + * .addControl(new AttributionControl({ + * compact: true + * })); + * ``` + */ +class AttributionControl { + /** + * @param options - the attribution options + */ + constructor(options = defaultAttributionControlOptions) { + this._toggleAttribution = () => { + if (this._container.classList.contains('maplibregl-compact')) { + if (this._container.classList.contains('maplibregl-compact-show')) { + this._container.setAttribute('open', ''); + this._container.classList.remove('maplibregl-compact-show'); + } + else { + this._container.classList.add('maplibregl-compact-show'); + this._container.removeAttribute('open'); + } + } + }; + this._updateData = (e) => { + if (e && (e.sourceDataType === 'metadata' || e.sourceDataType === 'visibility' || e.dataType === 'style' || e.type === 'terrain')) { + this._updateAttributions(); + } + }; + this._updateCompact = () => { + if (this._map.getCanvasContainer().offsetWidth <= 640 || this._compact) { + if (this._compact === false) { + this._container.setAttribute('open', ''); + } + else if (!this._container.classList.contains('maplibregl-compact') && !this._container.classList.contains('maplibregl-attrib-empty')) { + this._container.setAttribute('open', ''); + this._container.classList.add('maplibregl-compact', 'maplibregl-compact-show'); + } + } + else { + this._container.setAttribute('open', ''); + if (this._container.classList.contains('maplibregl-compact')) { + this._container.classList.remove('maplibregl-compact', 'maplibregl-compact-show'); + } + } + }; + this._updateCompactMinimize = () => { + if (this._container.classList.contains('maplibregl-compact')) { + if (this._container.classList.contains('maplibregl-compact-show')) { + this._container.classList.remove('maplibregl-compact-show'); + } + } + }; + this.options = options; + } + getDefaultPosition() { + return 'bottom-right'; + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._compact = this.options.compact; + this._container = DOM.create('details', 'maplibregl-ctrl maplibregl-ctrl-attrib'); + this._compactButton = DOM.create('summary', 'maplibregl-ctrl-attrib-button', this._container); + this._compactButton.addEventListener('click', this._toggleAttribution); + this._setElementTitle(this._compactButton, 'ToggleAttribution'); + this._innerContainer = DOM.create('div', 'maplibregl-ctrl-attrib-inner', this._container); + this._updateAttributions(); + this._updateCompact(); + this._map.on('styledata', this._updateData); + this._map.on('sourcedata', this._updateData); + this._map.on('terrain', this._updateData); + this._map.on('resize', this._updateCompact); + this._map.on('drag', this._updateCompactMinimize); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + this._map.off('styledata', this._updateData); + this._map.off('sourcedata', this._updateData); + this._map.off('terrain', this._updateData); + this._map.off('resize', this._updateCompact); + this._map.off('drag', this._updateCompactMinimize); + this._map = undefined; + this._compact = undefined; + this._attribHTML = undefined; + } + _setElementTitle(element, title) { + const str = this._map._getUIString(`AttributionControl.${title}`); + element.title = str; + element.setAttribute('aria-label', str); + } + _updateAttributions() { + if (!this._map.style) + return; + let attributions = []; + if (this.options.customAttribution) { + if (Array.isArray(this.options.customAttribution)) { + attributions = attributions.concat(this.options.customAttribution.map(attribution => { + if (typeof attribution !== 'string') + return ''; + return attribution; + })); + } + else if (typeof this.options.customAttribution === 'string') { + attributions.push(this.options.customAttribution); + } + } + if (this._map.style.stylesheet) { + const stylesheet = this._map.style.stylesheet; + this.styleOwner = stylesheet.owner; + this.styleId = stylesheet.id; + } + const sourceCaches = this._map.style.sourceCaches; + for (const id in sourceCaches) { + const sourceCache = sourceCaches[id]; + if (sourceCache.used || sourceCache.usedForTerrain) { + const source = sourceCache.getSource(); + if (source.attribution && attributions.indexOf(source.attribution) < 0) { + attributions.push(source.attribution); + } + } + } + // remove any entries that are whitespace + attributions = attributions.filter(e => String(e).trim()); + // remove any entries that are substrings of another entry. + // first sort by length so that substrings come first + attributions.sort((a, b) => a.length - b.length); + attributions = attributions.filter((attrib, i) => { + for (let j = i + 1; j < attributions.length; j++) { + if (attributions[j].indexOf(attrib) >= 0) { + return false; + } + } + return true; + }); + // check if attribution string is different to minimize DOM changes + const attribHTML = attributions.join(' | '); + if (attribHTML === this._attribHTML) + return; + this._attribHTML = attribHTML; + if (attributions.length) { + this._innerContainer.innerHTML = attribHTML; + this._container.classList.remove('maplibregl-attrib-empty'); + } + else { + this._container.classList.add('maplibregl-attrib-empty'); + } + this._updateCompact(); + // remove old DOM node from _editLink + this._editLink = null; + } +} + +/** + * A `LogoControl` is a control that adds the watermark. + * + * @group Markers and Controls + * + * @example + * ```ts + * map.addControl(new LogoControl({compact: false})); + * ``` + **/ +class LogoControl { + /** + * @param options - the control's options + */ + constructor(options = {}) { + this._updateCompact = () => { + const containerChildren = this._container.children; + if (containerChildren.length) { + const anchor = containerChildren[0]; + if (this._map.getCanvasContainer().offsetWidth <= 640 || this._compact) { + if (this._compact !== false) { + anchor.classList.add('maplibregl-compact'); + } + } + else { + anchor.classList.remove('maplibregl-compact'); + } + } + }; + this.options = options; + } + getDefaultPosition() { + return 'bottom-left'; + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._compact = this.options && this.options.compact; + this._container = DOM.create('div', 'maplibregl-ctrl'); + const anchor = DOM.create('a', 'maplibregl-ctrl-logo'); + anchor.target = '_blank'; + anchor.rel = 'noopener nofollow'; + anchor.href = 'https://maplibre.org/'; + anchor.setAttribute('aria-label', this._map._getUIString('LogoControl.Title')); + anchor.setAttribute('rel', 'noopener nofollow'); + this._container.appendChild(anchor); + this._container.style.display = 'block'; + this._map.on('resize', this._updateCompact); + this._updateCompact(); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + this._map.off('resize', this._updateCompact); + this._map = undefined; + this._compact = undefined; + } +} + +class TaskQueue { + constructor() { + this._queue = []; + this._id = 0; + this._cleared = false; + this._currentlyRunning = false; + } + add(callback) { + const id = ++this._id; + const queue = this._queue; + queue.push({ callback, id, cancelled: false }); + return id; + } + remove(id) { + const running = this._currentlyRunning; + const queue = running ? this._queue.concat(running) : this._queue; + for (const task of queue) { + if (task.id === id) { + task.cancelled = true; + return; + } + } + } + run(timeStamp = 0) { + if (this._currentlyRunning) + throw new Error('Attempting to run(), but is already running.'); + const queue = this._currentlyRunning = this._queue; + // Tasks queued by callbacks in the current queue should be executed + // on the next run, not the current run. + this._queue = []; + for (const task of queue) { + if (task.cancelled) + continue; + task.callback(timeStamp); + if (this._cleared) + break; + } + this._cleared = false; + this._currentlyRunning = false; + } + clear() { + if (this._currentlyRunning) { + this._cleared = true; + } + this._queue = []; + } +} + +var PerformanceMarkers; +(function (PerformanceMarkers) { + PerformanceMarkers["create"] = "create"; + PerformanceMarkers["load"] = "load"; + PerformanceMarkers["fullLoad"] = "fullLoad"; +})(PerformanceMarkers || (PerformanceMarkers = {})); +let lastFrameTime = null; +let frameTimes = []; +const minFramerateTarget = 60; +const frameTimeTarget = 1000 / minFramerateTarget; +const loadTimeKey = 'loadTime'; +const fullLoadTimeKey = 'fullLoadTime'; +const PerformanceUtils = { + mark(marker) { + performance.mark(marker); + }, + frame(timestamp) { + const currTimestamp = timestamp; + if (lastFrameTime != null) { + const frameTime = currTimestamp - lastFrameTime; + frameTimes.push(frameTime); + } + lastFrameTime = currTimestamp; + }, + clearMetrics() { + lastFrameTime = null; + frameTimes = []; + performance.clearMeasures(loadTimeKey); + performance.clearMeasures(fullLoadTimeKey); + for (const marker in PerformanceMarkers) { + performance.clearMarks(PerformanceMarkers[marker]); + } + }, + getPerformanceMetrics() { + performance.measure(loadTimeKey, PerformanceMarkers.create, PerformanceMarkers.load); + performance.measure(fullLoadTimeKey, PerformanceMarkers.create, PerformanceMarkers.fullLoad); + const loadTime = performance.getEntriesByName(loadTimeKey)[0].duration; + const fullLoadTime = performance.getEntriesByName(fullLoadTimeKey)[0].duration; + const totalFrames = frameTimes.length; + const avgFrameTime = frameTimes.reduce((prev, curr) => prev + curr, 0) / totalFrames / 1000; + const fps = 1 / avgFrameTime; + // count frames that missed our framerate target + const droppedFrames = frameTimes + .filter((frameTime) => frameTime > frameTimeTarget) + .reduce((acc, curr) => { + return acc + (curr - frameTimeTarget) / frameTimeTarget; + }, 0); + const percentDroppedFrames = (droppedFrames / (totalFrames + droppedFrames)) * 100; + return { + loadTime, + fullLoadTime, + fps, + percentDroppedFrames, + totalFrames + }; + } +}; +/** + * @internal + * Safe wrapper for the performance resource timing API in web workers with graceful degradation + */ +class RequestPerformance { + constructor(request) { + this._marks = { + start: [request.url, 'start'].join('#'), + end: [request.url, 'end'].join('#'), + measure: request.url.toString() + }; + performance.mark(this._marks.start); + } + finish() { + performance.mark(this._marks.end); + let resourceTimingData = performance.getEntriesByName(this._marks.measure); + // fallback if web worker implementation of perf.getEntriesByName returns empty + if (resourceTimingData.length === 0) { + performance.measure(this._marks.measure, this._marks.start, this._marks.end); + resourceTimingData = performance.getEntriesByName(this._marks.measure); + // cleanup + performance.clearMarks(this._marks.start); + performance.clearMarks(this._marks.end); + performance.clearMeasures(this._marks.measure); + } + return resourceTimingData; + } +} +var performance$1 = performance; + +var pos3dAttributes = createLayout([ + { name: 'a_pos3d', type: 'Int16', components: 3 } +]); + +/** + * @internal + * This class is a helper for the Terrain-class, it: + * + * - loads raster-dem tiles + * - manages all renderToTexture tiles. + * - caches previous rendered tiles. + * - finds all necessary renderToTexture tiles for a OverscaledTileID area + * - finds the corresponding raster-dem tile for OverscaledTileID + */ +class TerrainSourceCache extends Evented { + constructor(sourceCache) { + super(); + this.sourceCache = sourceCache; + this._tiles = {}; + this._renderableTilesKeys = []; + this._sourceTileCache = {}; + this.minzoom = 0; + this.maxzoom = 22; + this.tileSize = 512; + this.deltaZoom = 1; + sourceCache.usedForTerrain = true; + sourceCache.tileSize = this.tileSize * 2 ** this.deltaZoom; + } + destruct() { + this.sourceCache.usedForTerrain = false; + this.sourceCache.tileSize = null; + } + /** + * Load Terrain Tiles, create internal render-to-texture tiles, free GPU memory. + * @param transform - the operation to do + * @param terrain - the terrain + */ + update(transform, terrain) { + // load raster-dem tiles for the current scene. + this.sourceCache.update(transform, terrain); + // create internal render-to-texture tiles for the current scene. + this._renderableTilesKeys = []; + const keys = {}; + for (const tileID of transform.coveringTiles({ + tileSize: this.tileSize, + minzoom: this.minzoom, + maxzoom: this.maxzoom, + reparseOverscaled: false, + terrain + })) { + keys[tileID.key] = true; + this._renderableTilesKeys.push(tileID.key); + if (!this._tiles[tileID.key]) { + tileID.posMatrix = new Float64Array(16); + ortho(tileID.posMatrix, 0, EXTENT, 0, EXTENT, 0, 1); + this._tiles[tileID.key] = new Tile(tileID, this.tileSize); + } + } + // free unused tiles + for (const key in this._tiles) { + if (!keys[key]) + delete this._tiles[key]; + } + } + /** + * Free render to texture cache + * @param tileID - optional, free only corresponding to tileID. + */ + freeRtt(tileID) { + for (const key in this._tiles) { + const tile = this._tiles[key]; + if (!tileID || tile.tileID.equals(tileID) || tile.tileID.isChildOf(tileID) || tileID.isChildOf(tile.tileID)) + tile.rtt = []; + } + } + /** + * get a list of tiles, which are loaded and should be rendered in the current scene + * @returns the renderable tiles + */ + getRenderableTiles() { + return this._renderableTilesKeys.map(key => this.getTileByID(key)); + } + /** + * get terrain tile by the TileID key + * @param id - the tile id + * @returns the tile + */ + getTileByID(id) { + return this._tiles[id]; + } + /** + * Searches for the corresponding current renderable terrain-tiles + * @param tileID - the tile to look for + * @returns the tiles that were found + */ + getTerrainCoords(tileID) { + const coords = {}; + for (const key of this._renderableTilesKeys) { + const _tileID = this._tiles[key].tileID; + if (_tileID.canonical.equals(tileID.canonical)) { + const coord = tileID.clone(); + coord.posMatrix = new Float64Array(16); + ortho(coord.posMatrix, 0, EXTENT, 0, EXTENT, 0, 1); + coords[key] = coord; + } + else if (_tileID.canonical.isChildOf(tileID.canonical)) { + const coord = tileID.clone(); + coord.posMatrix = new Float64Array(16); + const dz = _tileID.canonical.z - tileID.canonical.z; + const dx = _tileID.canonical.x - (_tileID.canonical.x >> dz << dz); + const dy = _tileID.canonical.y - (_tileID.canonical.y >> dz << dz); + const size = EXTENT >> dz; + ortho(coord.posMatrix, 0, size, 0, size, 0, 1); + translate$1(coord.posMatrix, coord.posMatrix, [-dx * size, -dy * size, 0]); + coords[key] = coord; + } + else if (tileID.canonical.isChildOf(_tileID.canonical)) { + const coord = tileID.clone(); + coord.posMatrix = new Float64Array(16); + const dz = tileID.canonical.z - _tileID.canonical.z; + const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz); + const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz); + const size = EXTENT >> dz; + ortho(coord.posMatrix, 0, EXTENT, 0, EXTENT, 0, 1); + translate$1(coord.posMatrix, coord.posMatrix, [dx * size, dy * size, 0]); + scale$5(coord.posMatrix, coord.posMatrix, [1 / (2 ** dz), 1 / (2 ** dz), 0]); + coords[key] = coord; + } + } + return coords; + } + /** + * find the covering raster-dem tile + * @param tileID - the tile to look for + * @param searchForDEM - Optional parameter to search for (parent) sourcetiles with loaded dem. + * @returns the tile + */ + getSourceTile(tileID, searchForDEM) { + const source = this.sourceCache._source; + let z = tileID.overscaledZ - this.deltaZoom; + if (z > source.maxzoom) + z = source.maxzoom; + if (z < source.minzoom) + return null; + // cache for tileID to terrain-tileID + if (!this._sourceTileCache[tileID.key]) + this._sourceTileCache[tileID.key] = tileID.scaledTo(z).key; + let tile = this.sourceCache.getTileByID(this._sourceTileCache[tileID.key]); + // during tile-loading phase look if parent tiles (with loaded dem) are available. + if (!(tile && tile.dem) && searchForDEM) + while (z >= source.minzoom && !(tile && tile.dem)) + tile = this.sourceCache.getTileByID(tileID.scaledTo(z--).key); + return tile; + } + /** + * get a list of tiles, loaded after a specific time. This is used to update depth & coords framebuffers. + * @param time - the time + * @returns the relevant tiles + */ + tilesAfterTime(time = Date.now()) { + return Object.values(this._tiles).filter(t => t.timeAdded >= time); + } +} + +/** + * @internal + * This is the main class which handles most of the 3D Terrain logic. It has the following topics: + * + * 1. loads raster-dem tiles via the internal sourceCache this.sourceCache + * 2. creates a depth-framebuffer, which is used to calculate the visibility of coordinates + * 3. creates a coords-framebuffer, which is used the get to tile-coordinate for a screen-pixel + * 4. stores all render-to-texture tiles in the this.sourceCache._tiles + * 5. calculates the elevation for a specific tile-coordinate + * 6. creates a terrain-mesh + * + * A note about the GPU resource-usage: + * + * Framebuffers: + * + * - one for the depth & coords framebuffer with the size of the map-div. + * - one for rendering a tile to texture with the size of tileSize (= 512x512). + * + * Textures: + * + * - one texture for an empty raster-dem tile with size 1x1 + * - one texture for an empty depth-buffer, when terrain is disabled with size 1x1 + * - one texture for an each loaded raster-dem with size of the source.tileSize + * - one texture for the coords-framebuffer with the size of the map-div. + * - one texture for the depth-framebuffer with the size of the map-div. + * - one texture for the encoded tile-coords with the size 2*tileSize (=1024x1024) + * - finally for each render-to-texture tile (= this._tiles) a set of textures + * for each render stack (The stack-concept is documented in painter.ts). + * + * Normally there exists 1-3 Textures per tile, depending on the stylesheet. + * Each Textures has the size 2*tileSize (= 1024x1024). Also there exists a + * cache of the last 150 newest rendered tiles. + * + */ +class Terrain { + constructor(painter, sourceCache, options) { + this.painter = painter; + this.sourceCache = new TerrainSourceCache(sourceCache); + this.options = options; + this.exaggeration = typeof options.exaggeration === 'number' ? options.exaggeration : 1.0; + this.qualityFactor = 2; + this.meshSize = 128; + this._demMatrixCache = {}; + this.coordsIndex = []; + this._coordsTextureSize = 1024; + } + /** + * get the elevation-value from original dem-data for a given tile-coordinate + * @param tileID - the tile to get elevation for + * @param x - between 0 .. EXTENT + * @param y - between 0 .. EXTENT + * @param extent - optional, default 8192 + * @returns the elevation + */ + getDEMElevation(tileID, x, y, extent = EXTENT) { + var _a; + if (!(x >= 0 && x < extent && y >= 0 && y < extent)) + return 0; + const terrain = this.getTerrainData(tileID); + const dem = (_a = terrain.tile) === null || _a === void 0 ? void 0 : _a.dem; + if (!dem) + return 0; + const pos = transformMat4([], [x / extent * EXTENT, y / extent * EXTENT], terrain.u_terrain_matrix); + const coord = [pos[0] * dem.dim, pos[1] * dem.dim]; + // bilinear interpolation + const cx = Math.floor(coord[0]), cy = Math.floor(coord[1]), tx = coord[0] - cx, ty = coord[1] - cy; + return (dem.get(cx, cy) * (1 - tx) * (1 - ty) + + dem.get(cx + 1, cy) * (tx) * (1 - ty) + + dem.get(cx, cy + 1) * (1 - tx) * (ty) + + dem.get(cx + 1, cy + 1) * (tx) * (ty)); + } + /** + * Get the elevation for given {@link LngLat} in respect of exaggeration. + * @param lnglat - the location + * @param zoom - the zoom + * @returns the elevation + */ + getElevationForLngLatZoom(lnglat, zoom) { + if (!isInBoundsForZoomLngLat(zoom, lnglat.wrap())) + return 0; + const { tileID, mercatorX, mercatorY } = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom); + return this.getElevation(tileID, mercatorX % EXTENT, mercatorY % EXTENT, EXTENT); + } + /** + * Get the elevation for given coordinate in respect of exaggeration. + * @param tileID - the tile id + * @param x - between 0 .. EXTENT + * @param y - between 0 .. EXTENT + * @param extent - optional, default 8192 + * @returns the elevation + */ + getElevation(tileID, x, y, extent = EXTENT) { + return this.getDEMElevation(tileID, x, y, extent) * this.exaggeration; + } + /** + * returns a Terrain Object for a tile. Unless the tile corresponds to data (e.g. tile is loading), return a flat dem object + * @param tileID - the tile to get the terrain for + * @returns the terrain data to use in the program + */ + getTerrainData(tileID) { + // create empty DEM Objects, which will used while raster-dem tiles are loading. + // creates an empty depth-buffer texture which is needed, during the initialization process of the 3d mesh.. + if (!this._emptyDemTexture) { + const context = this.painter.context; + const image = new RGBAImage({ width: 1, height: 1 }, new Uint8Array(1 * 4)); + this._emptyDepthTexture = new Texture(context, image, context.gl.RGBA, { premultiply: false }); + this._emptyDemUnpack = [0, 0, 0, 0]; + this._emptyDemTexture = new Texture(context, new RGBAImage({ width: 1, height: 1 }), context.gl.RGBA, { premultiply: false }); + this._emptyDemTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE); + this._emptyDemMatrix = identity$2([]); + } + // find covering dem tile and prepare demTexture + const sourceTile = this.sourceCache.getSourceTile(tileID, true); + if (sourceTile && sourceTile.dem && (!sourceTile.demTexture || sourceTile.needsTerrainPrepare)) { + const context = this.painter.context; + sourceTile.demTexture = this.painter.getTileTexture(sourceTile.dem.stride); + if (sourceTile.demTexture) + sourceTile.demTexture.update(sourceTile.dem.getPixels(), { premultiply: false }); + else + sourceTile.demTexture = new Texture(context, sourceTile.dem.getPixels(), context.gl.RGBA, { premultiply: false }); + sourceTile.demTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE); + sourceTile.needsTerrainPrepare = false; + } + // create matrix for lookup in dem data + const matrixKey = sourceTile && (sourceTile + sourceTile.tileID.key) + tileID.key; + if (matrixKey && !this._demMatrixCache[matrixKey]) { + const maxzoom = this.sourceCache.sourceCache._source.maxzoom; + let dz = tileID.canonical.z - sourceTile.tileID.canonical.z; + if (tileID.overscaledZ > tileID.canonical.z) { + if (tileID.canonical.z >= maxzoom) + dz = tileID.canonical.z - maxzoom; + else + warnOnce('cannot calculate elevation if elevation maxzoom > source.maxzoom'); + } + const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz); + const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz); + const demMatrix = fromScaling(new Float64Array(16), [1 / (EXTENT << dz), 1 / (EXTENT << dz), 0]); + translate$1(demMatrix, demMatrix, [dx * EXTENT, dy * EXTENT, 0]); + this._demMatrixCache[tileID.key] = { matrix: demMatrix, coord: tileID }; + } + // return uniform values & textures + return { + 'u_depth': 2, + 'u_terrain': 3, + 'u_terrain_dim': sourceTile && sourceTile.dem && sourceTile.dem.dim || 1, + 'u_terrain_matrix': matrixKey ? this._demMatrixCache[tileID.key].matrix : this._emptyDemMatrix, + 'u_terrain_unpack': sourceTile && sourceTile.dem && sourceTile.dem.getUnpackVector() || this._emptyDemUnpack, + 'u_terrain_exaggeration': this.exaggeration, + texture: (sourceTile && sourceTile.demTexture || this._emptyDemTexture).texture, + depthTexture: (this._fboDepthTexture || this._emptyDepthTexture).texture, + tile: sourceTile + }; + } + /** + * get a framebuffer as big as the map-div, which will be used to render depth & coords into a texture + * @param texture - the texture + * @returns the frame buffer + */ + getFramebuffer(texture) { + const painter = this.painter; + const width = painter.width / devicePixelRatio; + const height = painter.height / devicePixelRatio; + if (this._fbo && (this._fbo.width !== width || this._fbo.height !== height)) { + this._fbo.destroy(); + this._fboCoordsTexture.destroy(); + this._fboDepthTexture.destroy(); + delete this._fbo; + delete this._fboDepthTexture; + delete this._fboCoordsTexture; + } + if (!this._fboCoordsTexture) { + this._fboCoordsTexture = new Texture(painter.context, { width, height, data: null }, painter.context.gl.RGBA, { premultiply: false }); + this._fboCoordsTexture.bind(painter.context.gl.NEAREST, painter.context.gl.CLAMP_TO_EDGE); + } + if (!this._fboDepthTexture) { + this._fboDepthTexture = new Texture(painter.context, { width, height, data: null }, painter.context.gl.RGBA, { premultiply: false }); + this._fboDepthTexture.bind(painter.context.gl.NEAREST, painter.context.gl.CLAMP_TO_EDGE); + } + if (!this._fbo) { + this._fbo = painter.context.createFramebuffer(width, height, true, false); + this._fbo.depthAttachment.set(painter.context.createRenderbuffer(painter.context.gl.DEPTH_COMPONENT16, width, height)); + } + this._fbo.colorAttachment.set(texture === 'coords' ? this._fboCoordsTexture.texture : this._fboDepthTexture.texture); + return this._fbo; + } + /** + * create coords texture, needed to grab coordinates from canvas + * encode coords coordinate into 4 bytes: + * - 8 lower bits for x + * - 8 lower bits for y + * - 4 higher bits for x + * - 4 higher bits for y + * - 8 bits for coordsIndex (1 .. 255) (= number of terraintile), is later setted in draw_terrain uniform value + * @returns the texture + */ + getCoordsTexture() { + const context = this.painter.context; + if (this._coordsTexture) + return this._coordsTexture; + const data = new Uint8Array(this._coordsTextureSize * this._coordsTextureSize * 4); + for (let y = 0, i = 0; y < this._coordsTextureSize; y++) + for (let x = 0; x < this._coordsTextureSize; x++, i += 4) { + data[i + 0] = x & 255; + data[i + 1] = y & 255; + data[i + 2] = ((x >> 8) << 4) | (y >> 8); + data[i + 3] = 0; + } + const image = new RGBAImage({ width: this._coordsTextureSize, height: this._coordsTextureSize }, new Uint8Array(data.buffer)); + const texture = new Texture(context, image, context.gl.RGBA, { premultiply: false }); + texture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE); + this._coordsTexture = texture; + return texture; + } + /** + * Reads a pixel from the coords-framebuffer and translate this to mercator. + * @param p - Screen-Coordinate + * @returns mercator coordinate for a screen pixel + */ + pointCoordinate(p) { + // First, ensure the coords framebuffer is up to date. + this.painter.maybeDrawDepthAndCoords(true); + const rgba = new Uint8Array(4); + const context = this.painter.context, gl = context.gl; + const px = Math.round(p.x * this.painter.pixelRatio / devicePixelRatio); + const py = Math.round(p.y * this.painter.pixelRatio / devicePixelRatio); + const fbHeight = Math.round(this.painter.height / devicePixelRatio); + // grab coordinate pixel from coordinates framebuffer + context.bindFramebuffer.set(this.getFramebuffer('coords').framebuffer); + gl.readPixels(px, fbHeight - py - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rgba); + context.bindFramebuffer.set(null); + // decode coordinates (encoding see getCoordsTexture) + const x = rgba[0] + ((rgba[2] >> 4) << 8); + const y = rgba[1] + ((rgba[2] & 15) << 8); + const tileID = this.coordsIndex[255 - rgba[3]]; + const tile = tileID && this.sourceCache.getTileByID(tileID); + if (!tile) + return null; + const coordsSize = this._coordsTextureSize; + const worldSize = (1 << tile.tileID.canonical.z) * coordsSize; + return new MercatorCoordinate((tile.tileID.canonical.x * coordsSize + x) / worldSize + tile.tileID.wrap, (tile.tileID.canonical.y * coordsSize + y) / worldSize, this.getElevation(tile.tileID, x, y, coordsSize)); + } + /** + * Reads the depth value from the depth-framebuffer at a given screen pixel + * @param p - Screen coordinate + * @returns depth value in clip space (between 0 and 1) + */ + depthAtPoint(p) { + const rgba = new Uint8Array(4); + const context = this.painter.context, gl = context.gl; + context.bindFramebuffer.set(this.getFramebuffer('depth').framebuffer); + gl.readPixels(p.x, this.painter.height / devicePixelRatio - p.y - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rgba); + context.bindFramebuffer.set(null); + // decode coordinates (encoding see terran_depth.fragment.glsl) + const depthValue = (rgba[0] / (256 * 256 * 256) + rgba[1] / (256 * 256) + rgba[2] / 256 + rgba[3]) / 256; + return depthValue; + } + /** + * create a regular mesh which will be used by all terrain-tiles + * @returns the created regular mesh + */ + getTerrainMesh() { + if (this._mesh) + return this._mesh; + const context = this.painter.context; + const vertexArray = new Pos3dArray(); + const indexArray = new TriangleIndexArray(); + const meshSize = this.meshSize; + const delta = EXTENT / meshSize; + const meshSize2 = meshSize * meshSize; + for (let y = 0; y <= meshSize; y++) + for (let x = 0; x <= meshSize; x++) + vertexArray.emplaceBack(x * delta, y * delta, 0); + for (let y = 0; y < meshSize2; y += meshSize + 1) + for (let x = 0; x < meshSize; x++) { + indexArray.emplaceBack(x + y, meshSize + x + y + 1, meshSize + x + y + 2); + indexArray.emplaceBack(x + y, meshSize + x + y + 2, x + y + 1); + } + // add an extra frame around the mesh to avoid stiching on tile boundaries with different zoomlevels + // first code-block is for top-bottom frame and second for left-right frame + const offsetTop = vertexArray.length, offsetBottom = offsetTop + (meshSize + 1) * 2; + for (const y of [0, 1]) + for (let x = 0; x <= meshSize; x++) + for (const z of [0, 1]) + vertexArray.emplaceBack(x * delta, y * EXTENT, z); + for (let x = 0; x < meshSize * 2; x += 2) { + indexArray.emplaceBack(offsetBottom + x, offsetBottom + x + 1, offsetBottom + x + 3); + indexArray.emplaceBack(offsetBottom + x, offsetBottom + x + 3, offsetBottom + x + 2); + indexArray.emplaceBack(offsetTop + x, offsetTop + x + 3, offsetTop + x + 1); + indexArray.emplaceBack(offsetTop + x, offsetTop + x + 2, offsetTop + x + 3); + } + const offsetLeft = vertexArray.length, offsetRight = offsetLeft + (meshSize + 1) * 2; + for (const x of [0, 1]) + for (let y = 0; y <= meshSize; y++) + for (const z of [0, 1]) + vertexArray.emplaceBack(x * EXTENT, y * delta, z); + for (let y = 0; y < meshSize * 2; y += 2) { + indexArray.emplaceBack(offsetLeft + y, offsetLeft + y + 1, offsetLeft + y + 3); + indexArray.emplaceBack(offsetLeft + y, offsetLeft + y + 3, offsetLeft + y + 2); + indexArray.emplaceBack(offsetRight + y, offsetRight + y + 3, offsetRight + y + 1); + indexArray.emplaceBack(offsetRight + y, offsetRight + y + 2, offsetRight + y + 3); + } + this._mesh = new Mesh(context.createVertexBuffer(vertexArray, pos3dAttributes.members), context.createIndexBuffer(indexArray), SegmentVector.simpleSegment(0, 0, vertexArray.length, indexArray.length)); + return this._mesh; + } + /** + * Calculates a height of the frame around the terrain-mesh to avoid stiching between + * tile boundaries in different zoomlevels. + * @param zoom - current zoomlevel + * @returns the elevation delta in meters + */ + getMeshFrameDelta(zoom) { + // divide by 5 is evaluated by trial & error to get a frame in the right height + return 2 * Math.PI * earthRadius / Math.pow(2, zoom) / 5; + } + getMinTileElevationForLngLatZoom(lnglat, zoom) { + var _a; + const { tileID } = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom); + return (_a = this.getMinMaxElevation(tileID).minElevation) !== null && _a !== void 0 ? _a : 0; + } + /** + * Get the minimum and maximum elevation contained in a tile. This includes any + * exaggeration included in the terrain. + * + * @param tileID - ID of the tile to be used as a source for the min/max elevation + * @returns the minimum and maximum elevation found in the tile, including the terrain's + * exaggeration + */ + getMinMaxElevation(tileID) { + const tile = this.getTerrainData(tileID).tile; + const minMax = { minElevation: null, maxElevation: null }; + if (tile && tile.dem) { + minMax.minElevation = tile.dem.min * this.exaggeration; + minMax.maxElevation = tile.dem.max * this.exaggeration; + } + return minMax; + } + _getOverscaledTileIDFromLngLatZoom(lnglat, zoom) { + const mercatorCoordinate = MercatorCoordinate.fromLngLat(lnglat.wrap()); + const worldSize = (1 << zoom) * EXTENT; + const mercatorX = mercatorCoordinate.x * worldSize; + const mercatorY = mercatorCoordinate.y * worldSize; + const tileX = Math.floor(mercatorX / EXTENT), tileY = Math.floor(mercatorY / EXTENT); + const tileID = new OverscaledTileID(zoom, 0, zoom, tileX, tileY); + return { + tileID, + mercatorX, + mercatorY + }; + } +} + +/** + * @internal + * `RenderPool` is a resource pool for textures and framebuffers + */ +class RenderPool { + constructor(_context, _size, _tileSize) { + this._context = _context; + this._size = _size; + this._tileSize = _tileSize; + this._objects = []; + this._recentlyUsed = []; + this._stamp = 0; + } + destruct() { + for (const obj of this._objects) { + obj.texture.destroy(); + obj.fbo.destroy(); + } + } + _createObject(id) { + const fbo = this._context.createFramebuffer(this._tileSize, this._tileSize, true, true); + const texture = new Texture(this._context, { width: this._tileSize, height: this._tileSize, data: null }, this._context.gl.RGBA); + texture.bind(this._context.gl.LINEAR, this._context.gl.CLAMP_TO_EDGE); + fbo.depthAttachment.set(this._context.createRenderbuffer(this._context.gl.DEPTH_STENCIL, this._tileSize, this._tileSize)); + fbo.colorAttachment.set(texture.texture); + return { id, fbo, texture, stamp: -1, inUse: false }; + } + getObjectForId(id) { + return this._objects[id]; + } + useObject(obj) { + obj.inUse = true; + this._recentlyUsed = this._recentlyUsed.filter(id => obj.id !== id); + this._recentlyUsed.push(obj.id); + } + stampObject(obj) { + obj.stamp = ++this._stamp; + } + getOrCreateFreeObject() { + // check for free existing object + for (const id of this._recentlyUsed) { + if (!this._objects[id].inUse) + return this._objects[id]; + } + if (this._objects.length >= this._size) + throw new Error('No free RenderPool available, call freeAllObjects() required!'); + // create new object + const obj = this._createObject(this._objects.length); + this._objects.push(obj); + return obj; + } + freeObject(obj) { + obj.inUse = false; + } + freeAllObjects() { + for (const obj of this._objects) + this.freeObject(obj); + } + isFull() { + if (this._objects.length < this._size) { + return false; + } + return this._objects.some(o => !o.inUse) === false; + } +} + +/** + * lookup table which layers should rendered to texture + */ +const LAYERS = { + background: true, + fill: true, + line: true, + raster: true, + hillshade: true +}; +/** + * @internal + * A helper class to help define what should be rendered to texture and how + */ +class RenderToTexture { + constructor(painter, terrain) { + this.painter = painter; + this.terrain = terrain; + this.pool = new RenderPool(painter.context, 30, terrain.sourceCache.tileSize * terrain.qualityFactor); + } + destruct() { + this.pool.destruct(); + } + getTexture(tile) { + return this.pool.getObjectForId(tile.rtt[this._stacks.length - 1].id).texture; + } + prepareForRender(style, zoom) { + this._stacks = []; + this._prevType = null; + this._rttTiles = []; + this._renderableTiles = this.terrain.sourceCache.getRenderableTiles(); + this._renderableLayerIds = style._order.filter(id => !style._layers[id].isHidden(zoom)); + this._coordsDescendingInv = {}; + for (const id in style.sourceCaches) { + this._coordsDescendingInv[id] = {}; + const tileIDs = style.sourceCaches[id].getVisibleCoordinates(); + for (const tileID of tileIDs) { + const keys = this.terrain.sourceCache.getTerrainCoords(tileID); + for (const key in keys) { + if (!this._coordsDescendingInv[id][key]) + this._coordsDescendingInv[id][key] = []; + this._coordsDescendingInv[id][key].push(keys[key]); + } + } + } + this._coordsDescendingInvStr = {}; + for (const id of style._order) { + const layer = style._layers[id], source = layer.source; + if (LAYERS[layer.type]) { + if (!this._coordsDescendingInvStr[source]) { + this._coordsDescendingInvStr[source] = {}; + for (const key in this._coordsDescendingInv[source]) + this._coordsDescendingInvStr[source][key] = this._coordsDescendingInv[source][key].map(c => c.key).sort().join(); + } + } + } + // check tiles to render + for (const tile of this._renderableTiles) { + for (const source in this._coordsDescendingInvStr) { + // rerender if there are more coords to render than in the last rendering + const coords = this._coordsDescendingInvStr[source][tile.tileID.key]; + if (coords && coords !== tile.rttCoords[source]) + tile.rtt = []; + } + } + } + /** + * due that switching textures is relatively slow, the render + * layer-by-layer context is not practicable. To bypass this problem + * this lines of code stack all layers and later render all at once. + * Because of the stylesheet possibility to mixing render-to-texture layers + * and 'live'-layers (f.e. symbols) it is necessary to create more stacks. For example + * a symbol-layer is in between of fill-layers. + * @param layer - the layer to render + * @returns if true layer is rendered to texture, otherwise false + */ + renderLayer(layer) { + if (layer.isHidden(this.painter.transform.zoom)) + return false; + const type = layer.type; + const painter = this.painter; + const isLastLayer = this._renderableLayerIds[this._renderableLayerIds.length - 1] === layer.id; + // remember background, fill, line & raster layer to render into a stack + if (LAYERS[type]) { + // create a new stack if previous layer was not rendered to texture (f.e. symbols) + if (!this._prevType || !LAYERS[this._prevType]) + this._stacks.push([]); + // push current render-to-texture layer to render-stack + this._prevType = type; + this._stacks[this._stacks.length - 1].push(layer.id); + // rendering is done later, all in once + if (!isLastLayer) + return true; + } + // in case a stack is finished render all collected stack-layers into a texture + if (LAYERS[this._prevType] || (LAYERS[type] && isLastLayer)) { + this._prevType = type; + const stack = this._stacks.length - 1, layers = this._stacks[stack] || []; + for (const tile of this._renderableTiles) { + // if render pool is full draw current tiles to screen and free pool + if (this.pool.isFull()) { + drawTerrain(this.painter, this.terrain, this._rttTiles); + this._rttTiles = []; + this.pool.freeAllObjects(); + } + this._rttTiles.push(tile); + // check for cached PoolObject + if (tile.rtt[stack]) { + const obj = this.pool.getObjectForId(tile.rtt[stack].id); + if (obj.stamp === tile.rtt[stack].stamp) { + this.pool.useObject(obj); + continue; + } + } + // get free PoolObject + const obj = this.pool.getOrCreateFreeObject(); + this.pool.useObject(obj); + this.pool.stampObject(obj); + tile.rtt[stack] = { id: obj.id, stamp: obj.stamp }; + // prepare PoolObject for rendering + painter.context.bindFramebuffer.set(obj.fbo.framebuffer); + painter.context.clear({ color: Color.transparent, stencil: 0 }); + painter.currentStencilSource = undefined; + for (let l = 0; l < layers.length; l++) { + const layer = painter.style._layers[layers[l]]; + const coords = layer.source ? this._coordsDescendingInv[layer.source][tile.tileID.key] : [tile.tileID]; + painter.context.viewport.set([0, 0, obj.fbo.width, obj.fbo.height]); + painter._renderTileClippingMasks(layer, coords); + painter.renderLayer(painter, painter.style.sourceCaches[layer.source], layer, coords); + if (layer.source) + tile.rttCoords[layer.source] = this._coordsDescendingInvStr[layer.source][tile.tileID.key]; + } + } + drawTerrain(this.painter, this.terrain, this._rttTiles); + this._rttTiles = []; + this.pool.freeAllObjects(); + return LAYERS[type]; + } + return false; + } +} + +const defaultLocale = { + 'AttributionControl.ToggleAttribution': 'Toggle attribution', + 'AttributionControl.MapFeedback': 'Map feedback', + 'FullscreenControl.Enter': 'Enter fullscreen', + 'FullscreenControl.Exit': 'Exit fullscreen', + 'GeolocateControl.FindMyLocation': 'Find my location', + 'GeolocateControl.LocationNotAvailable': 'Location not available', + 'LogoControl.Title': 'MapLibre logo', + 'Map.Title': 'Map', + 'Marker.Title': 'Map marker', + 'NavigationControl.ResetBearing': 'Reset bearing to north', + 'NavigationControl.ZoomIn': 'Zoom in', + 'NavigationControl.ZoomOut': 'Zoom out', + 'Popup.Close': 'Close popup', + 'ScaleControl.Feet': 'ft', + 'ScaleControl.Meters': 'm', + 'ScaleControl.Kilometers': 'km', + 'ScaleControl.Miles': 'mi', + 'ScaleControl.NauticalMiles': 'nm', + 'TerrainControl.Enable': 'Enable terrain', + 'TerrainControl.Disable': 'Disable terrain', + 'CooperativeGesturesHandler.WindowsHelpText': 'Use Ctrl + scroll to zoom the map', + 'CooperativeGesturesHandler.MacHelpText': 'Use ⌘ + scroll to zoom the map', + 'CooperativeGesturesHandler.MobileHelpText': 'Use two fingers to move the map', +}; + +const version$1 = packageJSON.version; +const defaultMinZoom = -2; +const defaultMaxZoom = 22; +// the default values, but also the valid range +const defaultMinPitch = 0; +const defaultMaxPitch = 60; +// use this variable to check maxPitch for validity +const maxPitchThreshold = 85; +const defaultOptions$4 = { + hash: false, + interactive: true, + bearingSnap: 7, + attributionControl: defaultAttributionControlOptions, + maplibreLogo: false, + failIfMajorPerformanceCaveat: false, + preserveDrawingBuffer: false, + refreshExpiredTiles: true, + scrollZoom: true, + minZoom: defaultMinZoom, + maxZoom: defaultMaxZoom, + minPitch: defaultMinPitch, + maxPitch: defaultMaxPitch, + boxZoom: true, + dragRotate: true, + dragPan: true, + keyboard: true, + doubleClickZoom: true, + touchZoomRotate: true, + touchPitch: true, + cooperativeGestures: false, + trackResize: true, + center: [0, 0], + zoom: 0, + bearing: 0, + pitch: 0, + renderWorldCopies: true, + maxTileCacheSize: null, + maxTileCacheZoomLevels: config.MAX_TILE_CACHE_ZOOM_LEVELS, + transformRequest: null, + transformCameraUpdate: null, + fadeDuration: 300, + crossSourceCollisions: true, + clickTolerance: 3, + localIdeographFontFamily: 'sans-serif', + pitchWithRotate: true, + validateStyle: true, + /**Because GL MAX_TEXTURE_SIZE is usually at least 4096px. */ + maxCanvasSize: [4096, 4096], + cancelPendingTileRequestsWhileZooming: true +}; +/** + * The `Map` object represents the map on your page. It exposes methods + * and properties that enable you to programmatically change the map, + * and fires events as users interact with it. + * + * You create a `Map` by specifying a `container` and other options, see {@link MapOptions} for the full list. + * Then MapLibre GL JS initializes the map on the page and returns your `Map` object. + * + * @group Main + * + * @example + * ```ts + * let map = new Map({ + * container: 'map', + * center: [-122.420679, 37.772537], + * zoom: 13, + * style: style_object, + * hash: true, + * transformRequest: (url, resourceType)=> { + * if(resourceType === 'Source' && url.startsWith('http://myHost')) { + * return { + * url: url.replace('http', 'https'), + * headers: { 'my-custom-header': true}, + * credentials: 'include' // Include cookies for cross-origin requests + * } + * } + * } + * }); + * ``` + * @see [Display a map](https://maplibre.org/maplibre-gl-js/docs/examples/simple-map/) + */ +let Map$1 = class Map extends Camera { + constructor(options) { + PerformanceUtils.mark(PerformanceMarkers.create); + const resolvedOptions = Object.assign(Object.assign({}, defaultOptions$4), options); + if (resolvedOptions.minZoom != null && resolvedOptions.maxZoom != null && resolvedOptions.minZoom > resolvedOptions.maxZoom) { + throw new Error('maxZoom must be greater than or equal to minZoom'); + } + if (resolvedOptions.minPitch != null && resolvedOptions.maxPitch != null && resolvedOptions.minPitch > resolvedOptions.maxPitch) { + throw new Error('maxPitch must be greater than or equal to minPitch'); + } + if (resolvedOptions.minPitch != null && resolvedOptions.minPitch < defaultMinPitch) { + throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`); + } + if (resolvedOptions.maxPitch != null && resolvedOptions.maxPitch > maxPitchThreshold) { + throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`); + } + const transform = new Transform(resolvedOptions.minZoom, resolvedOptions.maxZoom, resolvedOptions.minPitch, resolvedOptions.maxPitch, resolvedOptions.renderWorldCopies); + super(transform, { bearingSnap: resolvedOptions.bearingSnap }); + this._idleTriggered = false; + this._crossFadingFactor = 1; + this._renderTaskQueue = new TaskQueue(); + this._controls = []; + this._mapId = uniqueId(); + this._contextLost = (event) => { + event.preventDefault(); + if (this._frameRequest) { + this._frameRequest.abort(); + this._frameRequest = null; + } + this.fire(new Event('webglcontextlost', { originalEvent: event })); + }; + this._contextRestored = (event) => { + this._setupPainter(); + this.resize(); + this._update(); + this.fire(new Event('webglcontextrestored', { originalEvent: event })); + }; + this._onMapScroll = (event) => { + if (event.target !== this._container) + return; + // Revert any scroll which would move the canvas outside of the view + this._container.scrollTop = 0; + this._container.scrollLeft = 0; + return false; + }; + this._onWindowOnline = () => { + this._update(); + }; + this._interactive = resolvedOptions.interactive; + this._maxTileCacheSize = resolvedOptions.maxTileCacheSize; + this._maxTileCacheZoomLevels = resolvedOptions.maxTileCacheZoomLevels; + this._failIfMajorPerformanceCaveat = resolvedOptions.failIfMajorPerformanceCaveat === true; + this._preserveDrawingBuffer = resolvedOptions.preserveDrawingBuffer === true; + this._antialias = resolvedOptions.antialias === true; + this._trackResize = resolvedOptions.trackResize === true; + this._bearingSnap = resolvedOptions.bearingSnap; + this._refreshExpiredTiles = resolvedOptions.refreshExpiredTiles === true; + this._fadeDuration = resolvedOptions.fadeDuration; + this._crossSourceCollisions = resolvedOptions.crossSourceCollisions === true; + this._collectResourceTiming = resolvedOptions.collectResourceTiming === true; + this._locale = Object.assign(Object.assign({}, defaultLocale), resolvedOptions.locale); + this._clickTolerance = resolvedOptions.clickTolerance; + this._overridePixelRatio = resolvedOptions.pixelRatio; + this._maxCanvasSize = resolvedOptions.maxCanvasSize; + this.transformCameraUpdate = resolvedOptions.transformCameraUpdate; + this.cancelPendingTileRequestsWhileZooming = resolvedOptions.cancelPendingTileRequestsWhileZooming === true; + this._imageQueueHandle = ImageRequest.addThrottleControl(() => this.isMoving()); + this._requestManager = new RequestManager(resolvedOptions.transformRequest); + if (typeof resolvedOptions.container === 'string') { + this._container = document.getElementById(resolvedOptions.container); + if (!this._container) { + throw new Error(`Container '${resolvedOptions.container}' not found.`); + } + } + else if (resolvedOptions.container instanceof HTMLElement) { + this._container = resolvedOptions.container; + } + else { + throw new Error('Invalid type: \'container\' must be a String or HTMLElement.'); + } + if (resolvedOptions.maxBounds) { + this.setMaxBounds(resolvedOptions.maxBounds); + } + this._setupContainer(); + this._setupPainter(); + this.on('move', () => this._update(false)) + .on('moveend', () => this._update(false)) + .on('zoom', () => this._update(true)) + .on('terrain', () => { + this.painter.terrainFacilitator.dirty = true; + this._update(true); + }) + .once('idle', () => { this._idleTriggered = true; }); + if (typeof window !== 'undefined') { + addEventListener('online', this._onWindowOnline, false); + let initialResizeEventCaptured = false; + const throttledResizeCallback = throttle((entries) => { + if (this._trackResize && !this._removed) { + this.resize(entries); + this.redraw(); + } + }, 50); + this._resizeObserver = new ResizeObserver((entries) => { + if (!initialResizeEventCaptured) { + initialResizeEventCaptured = true; + return; + } + throttledResizeCallback(entries); + }); + this._resizeObserver.observe(this._container); + } + this.handlers = new HandlerManager(this, resolvedOptions); + const hashName = (typeof resolvedOptions.hash === 'string' && resolvedOptions.hash) || undefined; + this._hash = resolvedOptions.hash && (new Hash(hashName)).addTo(this); + // don't set position from options if set through hash + if (!this._hash || !this._hash._onHashChange()) { + this.jumpTo({ + center: resolvedOptions.center, + zoom: resolvedOptions.zoom, + bearing: resolvedOptions.bearing, + pitch: resolvedOptions.pitch + }); + if (resolvedOptions.bounds) { + this.resize(); + this.fitBounds(resolvedOptions.bounds, extend({}, resolvedOptions.fitBoundsOptions, { duration: 0 })); + } + } + this.resize(); + this._localIdeographFontFamily = resolvedOptions.localIdeographFontFamily; + this._validateStyle = resolvedOptions.validateStyle; + if (resolvedOptions.style) + this.setStyle(resolvedOptions.style, { localIdeographFontFamily: resolvedOptions.localIdeographFontFamily }); + if (resolvedOptions.attributionControl) + this.addControl(new AttributionControl(typeof resolvedOptions.attributionControl === 'boolean' ? undefined : resolvedOptions.attributionControl)); + if (resolvedOptions.maplibreLogo) + this.addControl(new LogoControl(), resolvedOptions.logoPosition); + this.on('style.load', () => { + if (this.transform.unmodified) { + this.jumpTo(this.style.stylesheet); + } + }); + this.on('data', (event) => { + this._update(event.dataType === 'style'); + this.fire(new Event(`${event.dataType}data`, event)); + }); + this.on('dataloading', (event) => { + this.fire(new Event(`${event.dataType}dataloading`, event)); + }); + this.on('dataabort', (event) => { + this.fire(new Event('sourcedataabort', event)); + }); + } + /** + * @internal + * Returns a unique number for this map instance which is used for the MapLoadEvent + * to make sure we only fire one event per instantiated map object. + * @returns the uniq map ID + */ + _getMapId() { + return this._mapId; + } + /** + * Adds an {@link IControl} to the map, calling `control.onAdd(this)`. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param control - The {@link IControl} to add. + * @param position - position on the map to which the control will be added. + * Valid values are `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. Defaults to `'top-right'`. + * @example + * Add zoom and rotation controls to the map. + * ```ts + * map.addControl(new NavigationControl()); + * ``` + * @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigation/) + */ + addControl(control, position) { + if (position === undefined) { + if (control.getDefaultPosition) { + position = control.getDefaultPosition(); + } + else { + position = 'top-right'; + } + } + if (!control || !control.onAdd) { + return this.fire(new ErrorEvent(new Error('Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.'))); + } + const controlElement = control.onAdd(this); + this._controls.push(control); + const positionContainer = this._controlPositions[position]; + if (position.indexOf('bottom') !== -1) { + positionContainer.insertBefore(controlElement, positionContainer.firstChild); + } + else { + positionContainer.appendChild(controlElement); + } + return this; + } + /** + * Removes the control from the map. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param control - The {@link IControl} to remove. + * @example + * ```ts + * // Define a new navigation control. + * let navigation = new NavigationControl(); + * // Add zoom and rotation controls to the map. + * map.addControl(navigation); + * // Remove zoom and rotation controls from the map. + * map.removeControl(navigation); + * ``` + */ + removeControl(control) { + if (!control || !control.onRemove) { + return this.fire(new ErrorEvent(new Error('Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.'))); + } + const ci = this._controls.indexOf(control); + if (ci > -1) + this._controls.splice(ci, 1); + control.onRemove(this); + return this; + } + /** + * Checks if a control exists on the map. + * + * @param control - The {@link IControl} to check. + * @returns true if map contains control. + * @example + * ```ts + * // Define a new navigation control. + * let navigation = new NavigationControl(); + * // Add zoom and rotation controls to the map. + * map.addControl(navigation); + * // Check that the navigation control exists on the map. + * map.hasControl(navigation); + * ``` + */ + hasControl(control) { + return this._controls.indexOf(control) > -1; + } + calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo) { + if (altitudeTo == null && this.terrain) { + altitudeTo = this.terrain.getElevationForLngLatZoom(to, this.transform.tileZoom); + } + return super.calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo); + } + /** + * Resizes the map according to the dimensions of its + * `container` element. + * + * Checks if the map container size changed and updates the map if it has changed. + * This method must be called after the map's `container` is resized programmatically + * or when the map is shown after being initially hidden with CSS. + * + * Triggers the following events: `movestart`, `move`, `moveend`, and `resize`. + * + * @param eventData - Additional properties to be passed to `movestart`, `move`, `resize`, and `moveend` + * events that get triggered as a result of resize. This can be useful for differentiating the + * source of an event (for example, user-initiated or programmatically-triggered events). + * @example + * Resize the map when the map container is shown after being initially hidden with CSS. + * ```ts + * let mapDiv = document.getElementById('map'); + * if (mapDiv.style.visibility === true) map.resize(); + * ``` + */ + resize(eventData) { + var _a; + const dimensions = this._containerDimensions(); + const width = dimensions[0]; + const height = dimensions[1]; + const clampedPixelRatio = this._getClampedPixelRatio(width, height); + this._resizeCanvas(width, height, clampedPixelRatio); + this.painter.resize(width, height, clampedPixelRatio); + // check if we've reached GL limits, in that case further clamps pixelRatio + if (this.painter.overLimit()) { + const gl = this.painter.context.gl; + // store updated _maxCanvasSize value + this._maxCanvasSize = [gl.drawingBufferWidth, gl.drawingBufferHeight]; + const clampedPixelRatio = this._getClampedPixelRatio(width, height); + this._resizeCanvas(width, height, clampedPixelRatio); + this.painter.resize(width, height, clampedPixelRatio); + } + this.transform.resize(width, height); + (_a = this._requestedCameraState) === null || _a === void 0 ? void 0 : _a.resize(width, height); + const fireMoving = !this._moving; + if (fireMoving) { + this.stop(); + this.fire(new Event('movestart', eventData)) + .fire(new Event('move', eventData)); + } + this.fire(new Event('resize', eventData)); + if (fireMoving) + this.fire(new Event('moveend', eventData)); + return this; + } + /** + * @internal + * Return the map's pixel ratio eventually scaled down to respect maxCanvasSize. + * Internally you should use this and not getPixelRatio(). + */ + _getClampedPixelRatio(width, height) { + const { 0: maxCanvasWidth, 1: maxCanvasHeight } = this._maxCanvasSize; + const pixelRatio = this.getPixelRatio(); + const canvasWidth = width * pixelRatio; + const canvasHeight = height * pixelRatio; + const widthScaleFactor = canvasWidth > maxCanvasWidth ? (maxCanvasWidth / canvasWidth) : 1; + const heightScaleFactor = canvasHeight > maxCanvasHeight ? (maxCanvasHeight / canvasHeight) : 1; + return Math.min(widthScaleFactor, heightScaleFactor) * pixelRatio; + } + /** + * Returns the map's pixel ratio. + * Note that the pixel ratio actually applied may be lower to respect maxCanvasSize. + * @returns The pixel ratio. + */ + getPixelRatio() { + var _a; + return (_a = this._overridePixelRatio) !== null && _a !== void 0 ? _a : devicePixelRatio; + } + /** + * Sets the map's pixel ratio. This allows to override `devicePixelRatio`. + * After this call, the canvas' `width` attribute will be `container.clientWidth * pixelRatio` + * and its height attribute will be `container.clientHeight * pixelRatio`. + * Set this to null to disable `devicePixelRatio` override. + * Note that the pixel ratio actually applied may be lower to respect maxCanvasSize. + * @param pixelRatio - The pixel ratio. + */ + setPixelRatio(pixelRatio) { + this._overridePixelRatio = pixelRatio; + this.resize(); + } + /** + * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not + * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region. + * @returns The geographical bounds of the map as {@link LngLatBounds}. + * @example + * ```ts + * let bounds = map.getBounds(); + * ``` + */ + getBounds() { + return this.transform.getBounds(); + } + /** + * Returns the maximum geographical bounds the map is constrained to, or `null` if none set. + * @returns The map object. + * @example + * ```ts + * let maxBounds = map.getMaxBounds(); + * ``` + */ + getMaxBounds() { + return this.transform.getMaxBounds(); + } + /** + * Sets or clears the map's geographical bounds. + * + * Pan and zoom operations are constrained within these bounds. + * If a pan or zoom is performed that would + * display regions outside these bounds, the map will + * instead display a position and zoom level + * as close as possible to the operation's request while still + * remaining within the bounds. + * + * @param bounds - The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds. + * @example + * Define bounds that conform to the `LngLatBoundsLike` object as set the max bounds. + * ```ts + * let bounds = [ + * [-74.04728, 40.68392], // [west, south] + * [-73.91058, 40.87764] // [east, north] + * ]; + * map.setMaxBounds(bounds); + * ``` + */ + setMaxBounds(bounds) { + this.transform.setMaxBounds(LngLatBounds.convert(bounds)); + return this._update(); + } + /** + * Sets or clears the map's minimum zoom level. + * If the map's current zoom level is lower than the new minimum, + * the map will zoom to the new minimum. + * + * It is not always possible to zoom out and reach the set `minZoom`. + * Other factors such as map height may restrict zooming. For example, + * if the map is 512px tall it will not be possible to zoom below zoom 0 + * no matter what the `minZoom` is set to. + * + * A {@link ErrorEvent} event will be fired if minZoom is out of bounds. + * + * @param minZoom - The minimum zoom level to set (-2 - 24). + * If `null` or `undefined` is provided, the function removes the current minimum zoom (i.e. sets it to -2). + * @example + * ```ts + * map.setMinZoom(12.25); + * ``` + */ + setMinZoom(minZoom) { + minZoom = minZoom === null || minZoom === undefined ? defaultMinZoom : minZoom; + if (minZoom >= defaultMinZoom && minZoom <= this.transform.maxZoom) { + this.transform.minZoom = minZoom; + this._update(); + if (this.getZoom() < minZoom) + this.setZoom(minZoom); + return this; + } + else + throw new Error(`minZoom must be between ${defaultMinZoom} and the current maxZoom, inclusive`); + } + /** + * Returns the map's minimum allowable zoom level. + * + * @returns minZoom + * @example + * ```ts + * let minZoom = map.getMinZoom(); + * ``` + */ + getMinZoom() { return this.transform.minZoom; } + /** + * Sets or clears the map's maximum zoom level. + * If the map's current zoom level is higher than the new maximum, + * the map will zoom to the new maximum. + * + * A {@link ErrorEvent} event will be fired if minZoom is out of bounds. + * + * @param maxZoom - The maximum zoom level to set. + * If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22). + * @example + * ```ts + * map.setMaxZoom(18.75); + * ``` + */ + setMaxZoom(maxZoom) { + maxZoom = maxZoom === null || maxZoom === undefined ? defaultMaxZoom : maxZoom; + if (maxZoom >= this.transform.minZoom) { + this.transform.maxZoom = maxZoom; + this._update(); + if (this.getZoom() > maxZoom) + this.setZoom(maxZoom); + return this; + } + else + throw new Error('maxZoom must be greater than the current minZoom'); + } + /** + * Returns the map's maximum allowable zoom level. + * + * @returns The maxZoom + * @example + * ```ts + * let maxZoom = map.getMaxZoom(); + * ``` + */ + getMaxZoom() { return this.transform.maxZoom; } + /** + * Sets or clears the map's minimum pitch. + * If the map's current pitch is lower than the new minimum, + * the map will pitch to the new minimum. + * + * A {@link ErrorEvent} event will be fired if minPitch is out of bounds. + * + * @param minPitch - The minimum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. + * If `null` or `undefined` is provided, the function removes the current minimum pitch (i.e. sets it to 0). + */ + setMinPitch(minPitch) { + minPitch = minPitch === null || minPitch === undefined ? defaultMinPitch : minPitch; + if (minPitch < defaultMinPitch) { + throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`); + } + if (minPitch >= defaultMinPitch && minPitch <= this.transform.maxPitch) { + this.transform.minPitch = minPitch; + this._update(); + if (this.getPitch() < minPitch) + this.setPitch(minPitch); + return this; + } + else + throw new Error(`minPitch must be between ${defaultMinPitch} and the current maxPitch, inclusive`); + } + /** + * Returns the map's minimum allowable pitch. + * + * @returns The minPitch + */ + getMinPitch() { return this.transform.minPitch; } + /** + * Sets or clears the map's maximum pitch. + * If the map's current pitch is higher than the new maximum, + * the map will pitch to the new maximum. + * + * A {@link ErrorEvent} event will be fired if maxPitch is out of bounds. + * + * @param maxPitch - The maximum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. + * If `null` or `undefined` is provided, the function removes the current maximum pitch (sets it to 60). + */ + setMaxPitch(maxPitch) { + maxPitch = maxPitch === null || maxPitch === undefined ? defaultMaxPitch : maxPitch; + if (maxPitch > maxPitchThreshold) { + throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`); + } + if (maxPitch >= this.transform.minPitch) { + this.transform.maxPitch = maxPitch; + this._update(); + if (this.getPitch() > maxPitch) + this.setPitch(maxPitch); + return this; + } + else + throw new Error('maxPitch must be greater than the current minPitch'); + } + /** + * Returns the map's maximum allowable pitch. + * + * @returns The maxPitch + */ + getMaxPitch() { return this.transform.maxPitch; } + /** + * 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`: + * + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * @returns The renderWorldCopies + * @example + * ```ts + * let worldCopiesRendered = map.getRenderWorldCopies(); + * ``` + * @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/) + */ + getRenderWorldCopies() { return this.transform.renderWorldCopies; } + /** + * Sets the state of `renderWorldCopies`. + * + * @param renderWorldCopies - If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`: + * + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * + * `undefined` is treated as `true`, `null` is treated as `false`. + * @example + * ```ts + * map.setRenderWorldCopies(true); + * ``` + * @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/) + */ + setRenderWorldCopies(renderWorldCopies) { + this.transform.renderWorldCopies = renderWorldCopies; + return this._update(); + } + /** + * Returns a [Point](https://github.com/mapbox/point-geometry) representing pixel coordinates, relative to the map's `container`, + * that correspond to the specified geographical location. + * + * @param lnglat - The geographical location to project. + * @returns The [Point](https://github.com/mapbox/point-geometry) corresponding to `lnglat`, relative to the map's `container`. + * @example + * ```ts + * let coordinate = [-122.420679, 37.772537]; + * let point = map.project(coordinate); + * ``` + */ + project(lnglat) { + return this.transform.locationPoint(LngLat.convert(lnglat), this.style && this.terrain); + } + /** + * Returns a {@link LngLat} representing geographical coordinates that correspond + * to the specified pixel coordinates. + * + * @param point - The pixel coordinates to unproject. + * @returns The {@link LngLat} corresponding to `point`. + * @example + * ```ts + * map.on('click', (e) => { + * // When the map is clicked, get the geographic coordinate. + * let coordinate = map.unproject(e.point); + * }); + * ``` + */ + unproject(point) { + return this.transform.pointLocation(Point$2.convert(point), this.terrain); + } + /** + * Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture. + * @returns true if the map is moving. + * @example + * ```ts + * let isMoving = map.isMoving(); + * ``` + */ + isMoving() { + var _a; + return this._moving || ((_a = this.handlers) === null || _a === void 0 ? void 0 : _a.isMoving()); + } + /** + * Returns true if the map is zooming due to a camera animation or user gesture. + * @returns true if the map is zooming. + * @example + * ```ts + * let isZooming = map.isZooming(); + * ``` + */ + isZooming() { + var _a; + return this._zooming || ((_a = this.handlers) === null || _a === void 0 ? void 0 : _a.isZooming()); + } + /** + * Returns true if the map is rotating due to a camera animation or user gesture. + * @returns true if the map is rotating. + * @example + * ```ts + * map.isRotating(); + * ``` + */ + isRotating() { + var _a; + return this._rotating || ((_a = this.handlers) === null || _a === void 0 ? void 0 : _a.isRotating()); + } + _createDelegatedListener(type, layerIds, listener) { + if (type === 'mouseenter' || type === 'mouseover') { + let mousein = false; + const mousemove = (e) => { + const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId)); + const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, { layers: existingLayers }) : []; + if (!features.length) { + mousein = false; + } + else if (!mousein) { + mousein = true; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent, { features })); + } + }; + const mouseout = () => { + mousein = false; + }; + return { layers: layerIds, listener, delegates: { mousemove, mouseout } }; + } + else if (type === 'mouseleave' || type === 'mouseout') { + let mousein = false; + const mousemove = (e) => { + const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId)); + const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, { layers: existingLayers }) : []; + if (features.length) { + mousein = true; + } + else if (mousein) { + mousein = false; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent)); + } + }; + const mouseout = (e) => { + if (mousein) { + mousein = false; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent)); + } + }; + return { layers: layerIds, listener, delegates: { mousemove, mouseout } }; + } + else { + const delegate = (e) => { + const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId)); + const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, { layers: existingLayers }) : []; + if (features.length) { + // Here we need to mutate the original event, so that preventDefault works as expected. + e.features = features; + listener.call(this, e); + delete e.features; + } + }; + return { layers: layerIds, listener, delegates: { [type]: delegate } }; + } + } + _saveDelegatedListener(type, delegatedListener) { + this._delegatedListeners = this._delegatedListeners || {}; + this._delegatedListeners[type] = this._delegatedListeners[type] || []; + this._delegatedListeners[type].push(delegatedListener); + } + _removeDelegatedListener(type, layerIds, listener) { + if (!this._delegatedListeners || !this._delegatedListeners[type]) { + return; + } + const listeners = this._delegatedListeners[type]; + for (let i = 0; i < listeners.length; i++) { + const delegatedListener = listeners[i]; + if (delegatedListener.listener === listener && + delegatedListener.layers.length === layerIds.length && + delegatedListener.layers.every((layerId) => layerIds.includes(layerId))) { + for (const event in delegatedListener.delegates) { + this.off(event, delegatedListener.delegates[event]); + } + listeners.splice(i, 1); + return; + } + } + } + on(type, layerIdsOrListener, listener) { + if (listener === undefined) { + return super.on(type, layerIdsOrListener); + } + const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener; + const delegatedListener = this._createDelegatedListener(type, layerIds, listener); + this._saveDelegatedListener(type, delegatedListener); + for (const event in delegatedListener.delegates) { + this.on(event, delegatedListener.delegates[event]); + } + return this; + } + once(type, layerIdsOrListener, listener) { + if (listener === undefined) { + return super.once(type, layerIdsOrListener); + } + const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener; + const delegatedListener = this._createDelegatedListener(type, layerIds, listener); + for (const key in delegatedListener.delegates) { + const delegate = delegatedListener.delegates[key]; + delegatedListener.delegates[key] = (...args) => { + this._removeDelegatedListener(type, layerIds, listener); + delegate(...args); + }; + } + this._saveDelegatedListener(type, delegatedListener); + for (const event in delegatedListener.delegates) { + this.once(event, delegatedListener.delegates[event]); + } + return this; + } + off(type, layerIdsOrListener, listener) { + if (listener === undefined) { + return super.off(type, layerIdsOrListener); + } + const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener; + this._removeDelegatedListener(type, layerIds, listener); + return this; + } + /** + * Returns an array of MapGeoJSONFeature objects + * representing visible features that satisfy the query parameters. + * + * @param geometryOrOptions - (optional) The geometry of the query region: + * either a single point or southwest and northeast points describing a bounding box. + * Omitting this parameter (i.e. calling {@link Map#queryRenderedFeatures} with zero arguments, + * or with only a `options` argument) is equivalent to passing a bounding box encompassing the entire + * map viewport. + * The geometryOrOptions can receive a {@link QueryRenderedFeaturesOptions} only to support a situation where the function receives only one parameter which is the options parameter. + * @param options - (optional) Options object. + * + * @returns An array of MapGeoJSONFeature objects. + * + * The `properties` value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only + * string and numeric property values are supported (i.e. `null`, `Array`, and `Object` values are not supported). + * + * Each feature includes top-level `layer`, `source`, and `sourceLayer` properties. The `layer` property is an object + * representing the style layer to which the feature belongs. Layout and paint properties in this object contain values + * which are fully evaluated for the given zoom level and feature. + * + * Only features that are currently rendered are included. Some features will **not** be included, like: + * + * - Features from layers whose `visibility` property is `"none"`. + * - Features from layers whose zoom range excludes the current zoom level. + * - Symbol features that have been hidden due to text or icon collision. + * + * Features from all other layers are included, including features that may have no visible + * contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to + * 0. + * + * The topmost rendered feature appears first in the returned array, and subsequent features are sorted by + * descending z-order. Features that are rendered multiple times (due to wrapping across the antemeridian at low + * zoom levels) are returned only once (though subject to the following caveat). + * + * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature + * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple + * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. + * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding + * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile + * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple + * tiles due to tile buffering. + * + * @example + * Find all features at a point + * ```ts + * let features = map.queryRenderedFeatures( + * [20, 35], + * { layers: ['my-layer-name'] } + * ); + * ``` + * + * @example + * Find all features within a static bounding box + * ```ts + * let features = map.queryRenderedFeatures( + * [[10, 20], [30, 50]], + * { layers: ['my-layer-name'] } + * ); + * ``` + * + * @example + * Find all features within a bounding box around a point + * ```ts + * let width = 10; + * let height = 20; + * let features = map.queryRenderedFeatures([ + * [point.x - width / 2, point.y - height / 2], + * [point.x + width / 2, point.y + height / 2] + * ], { layers: ['my-layer-name'] }); + * ``` + * + * @example + * Query all rendered features from a single layer + * ```ts + * let features = map.queryRenderedFeatures({ layers: ['my-layer-name'] }); + * ``` + * @see [Get features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/queryrenderedfeatures/) + */ + queryRenderedFeatures(geometryOrOptions, options) { + if (!this.style) { + return []; + } + let queryGeometry; + const isGeometry = geometryOrOptions instanceof Point$2 || Array.isArray(geometryOrOptions); + const geometry = isGeometry ? geometryOrOptions : [[0, 0], [this.transform.width, this.transform.height]]; + options = options || (isGeometry ? {} : geometryOrOptions) || {}; + if (geometry instanceof Point$2 || typeof geometry[0] === 'number') { + queryGeometry = [Point$2.convert(geometry)]; + } + else { + const tl = Point$2.convert(geometry[0]); + const br = Point$2.convert(geometry[1]); + queryGeometry = [tl, new Point$2(br.x, tl.y), br, new Point$2(tl.x, br.y), tl]; + } + return this.style.queryRenderedFeatures(queryGeometry, options, this.transform); + } + /** + * Returns an array of MapGeoJSONFeature objects + * representing features within the specified vector tile or GeoJSON source that satisfy the query parameters. + * + * @param sourceId - The ID of the vector tile or GeoJSON source to query. + * @param parameters - The options object. + * @returns An array of MapGeoJSONFeature objects. + * + * In contrast to {@link Map#queryRenderedFeatures}, this function returns all features matching the query parameters, + * whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded + * vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently + * visible viewport. + * + * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature + * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple + * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. + * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding + * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile + * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple + * tiles due to tile buffering. + * + * @example + * Find all features in one source layer in a vector source + * ```ts + * let features = map.querySourceFeatures('your-source-id', { + * sourceLayer: 'your-source-layer' + * }); + * ``` + * + */ + querySourceFeatures(sourceId, parameters) { + return this.style.querySourceFeatures(sourceId, parameters); + } + /** + * Updates the map's MapLibre style object with a new value. + * + * 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 + * against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites + * (images used for icons and patterns) and glyphs (fonts for label text) **cannot** be diffed. If the sprites or fonts used in the current + * style and the given style are different in any way, the map renderer will force a full update, removing the current style and building + * the given one from scratch. + * + * + * @param style - A JSON object conforming to the schema described in the + * [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/), or a URL to such JSON. + * @param options - The options object. + * + * @example + * ```ts + * map.setStyle("https://demotiles.maplibre.org/style.json"); + * + * map.setStyle('https://demotiles.maplibre.org/style.json', { + * transformStyle: (previousStyle, nextStyle) => ({ + * ...nextStyle, + * sources: { + * ...nextStyle.sources, + * // copy a source from previous style + * 'osm': previousStyle.sources.osm + * }, + * layers: [ + * // background layer + * nextStyle.layers[0], + * // copy a layer from previous style + * previousStyle.layers[0], + * // other layers from the next style + * ...nextStyle.layers.slice(1).map(layer => { + * // hide the layers we don't need from demotiles style + * if (layer.id.startsWith('geolines')) { + * layer.layout = {...layer.layout || {}, visibility: 'none'}; + * // filter out US polygons + * } else if (layer.id.startsWith('coastline') || layer.id.startsWith('countries')) { + * layer.filter = ['!=', ['get', 'ADM0_A3'], 'USA']; + * } + * return layer; + * }) + * ] + * }) + * }); + * ``` + */ + setStyle(style, options) { + options = extend({}, { + localIdeographFontFamily: this._localIdeographFontFamily, + validate: this._validateStyle + }, options); + if ((options.diff !== false && options.localIdeographFontFamily === this._localIdeographFontFamily) && this.style && style) { + this._diffStyle(style, options); + return this; + } + else { + this._localIdeographFontFamily = options.localIdeographFontFamily; + return this._updateStyle(style, options); + } + } + /** + * Updates the requestManager's transform request with a new function + * + * @param transformRequest - 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. + * Expected to return an object with a `url` property and optionally `headers` and `credentials` properties + * + * @example + * ```ts + * map.setTransformRequest((url: string, resourceType: string) => {}); + * ``` + */ + setTransformRequest(transformRequest) { + this._requestManager.setTransformRequest(transformRequest); + return this; + } + _getUIString(key) { + const str = this._locale[key]; + if (str == null) { + throw new Error(`Missing UI string '${key}'`); + } + return str; + } + _updateStyle(style, options) { + // transformStyle relies on having previous style serialized, if it is not loaded yet, delay _updateStyle until previous style is loaded + if (options.transformStyle && this.style && !this.style._loaded) { + this.style.once('style.load', () => this._updateStyle(style, options)); + return; + } + const previousStyle = this.style && options.transformStyle ? this.style.serialize() : undefined; + if (this.style) { + this.style.setEventedParent(null); + // Only release workers when map is getting disposed + this.style._remove(!style); + } + if (!style) { + delete this.style; + return this; + } + else { + this.style = new Style(this, options || {}); + } + this.style.setEventedParent(this, { style: this.style }); + if (typeof style === 'string') { + this.style.loadURL(style, options, previousStyle); + } + else { + this.style.loadJSON(style, options, previousStyle); + } + return this; + } + _lazyInitEmptyStyle() { + if (!this.style) { + this.style = new Style(this, {}); + this.style.setEventedParent(this, { style: this.style }); + this.style.loadEmpty(); + } + } + _diffStyle(style, options) { + if (typeof style === 'string') { + const url = style; + const request = this._requestManager.transformRequest(url, "Style" /* ResourceType.Style */); + getJSON(request, new AbortController()).then((response) => { + this._updateDiff(response.data, options); + }).catch((error) => { + if (error) { + this.fire(new ErrorEvent(error)); + } + }); + } + else if (typeof style === 'object') { + this._updateDiff(style, options); + } + } + _updateDiff(style, options) { + try { + if (this.style.setState(style, options)) { + this._update(true); + } + } + catch (e) { + warnOnce(`Unable to perform style diff: ${e.message || e.error || e}. Rebuilding the style from scratch.`); + this._updateStyle(style, options); + } + } + /** + * Returns the map's MapLibre style object, a JSON object which can be used to recreate the map's style. + * + * @returns The map's style JSON object. + * + * @example + * ```ts + * let styleJson = map.getStyle(); + * ``` + * + */ + getStyle() { + if (this.style) { + return this.style.serialize(); + } + } + /** + * Returns a Boolean indicating whether the map's style is fully loaded. + * + * @returns A Boolean indicating whether the style is fully loaded. + * + * @example + * ```ts + * let styleLoadStatus = map.isStyleLoaded(); + * ``` + */ + isStyleLoaded() { + if (!this.style) + return warnOnce('There is no style added to the map.'); + return this.style.loaded(); + } + /** + * Adds a source to the map's style. + * + * Events triggered: + * + * Triggers the `source.add` event. + * + * @param id - The ID of the source to add. Must not conflict with existing sources. + * @param source - The source object, conforming to the + * MapLibre Style Specification's [source definition](https://maplibre.org/maplibre-style-spec/sources) or + * {@link CanvasSourceSpecification}. + * @example + * ```ts + * map.addSource('my-data', { + * type: 'vector', + * url: 'https://demotiles.maplibre.org/tiles/tiles.json' + * }); + * ``` + * @example + * ```ts + * map.addSource('my-data', { + * "type": "geojson", + * "data": { + * "type": "Feature", + * "geometry": { + * "type": "Point", + * "coordinates": [-77.0323, 38.9131] + * }, + * "properties": { + * "title": "Mapbox DC", + * "marker-symbol": "monument" + * } + * } + * }); + * ``` + * @see GeoJSON source: [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/live-geojson/) + */ + addSource(id, source) { + this._lazyInitEmptyStyle(); + this.style.addSource(id, source); + return this._update(true); + } + /** + * Returns a Boolean indicating whether the source is loaded. Returns `true` if the source with + * the given ID in the map's style has no outstanding network requests, otherwise `false`. + * + * A {@link ErrorEvent} event will be fired if there is no source wit the specified ID. + * + * @param id - The ID of the source to be checked. + * @returns A Boolean indicating whether the source is loaded. + * @example + * ```ts + * let sourceLoaded = map.isSourceLoaded('bathymetry-data'); + * ``` + */ + isSourceLoaded(id) { + const source = this.style && this.style.sourceCaches[id]; + if (source === undefined) { + this.fire(new ErrorEvent(new Error(`There is no source with ID '${id}'`))); + return; + } + return source.loaded(); + } + /** + * Loads a 3D terrain mesh, based on a "raster-dem" source. + * + * Triggers the `terrain` event. + * + * @param options - Options object. + * @example + * ```ts + * map.setTerrain({ source: 'terrain' }); + * ``` + */ + setTerrain(options) { + this.style._checkLoaded(); + // clear event handlers + if (this._terrainDataCallback) + this.style.off('data', this._terrainDataCallback); + if (!options) { + // remove terrain + if (this.terrain) + this.terrain.sourceCache.destruct(); + this.terrain = null; + if (this.painter.renderToTexture) + this.painter.renderToTexture.destruct(); + this.painter.renderToTexture = null; + this.transform.minElevationForCurrentTile = 0; + this.transform.elevation = 0; + } + else { + // add terrain + const sourceCache = this.style.sourceCaches[options.source]; + if (!sourceCache) + throw new Error(`cannot load terrain, because there exists no source with ID: ${options.source}`); + // Update terrain tiles when adding new terrain + if (this.terrain === null) + sourceCache.reload(); + // Warn once if user is using the same source for hillshade and terrain + for (const index in this.style._layers) { + const thisLayer = this.style._layers[index]; + if (thisLayer.type === 'hillshade' && thisLayer.source === options.source) { + warnOnce('You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.'); + } + } + this.terrain = new Terrain(this.painter, sourceCache, options); + this.painter.renderToTexture = new RenderToTexture(this.painter, this.terrain); + this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + this._terrainDataCallback = e => { + if (e.dataType === 'style') { + this.terrain.sourceCache.freeRtt(); + } + else if (e.dataType === 'source' && e.tile) { + if (e.sourceId === options.source && !this._elevationFreeze) { + this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + } + this.terrain.sourceCache.freeRtt(e.tile.tileID); + } + }; + this.style.on('data', this._terrainDataCallback); + } + this.fire(new Event('terrain', { terrain: options })); + return this; + } + /** + * Get the terrain-options if terrain is loaded + * @returns the TerrainSpecification passed to setTerrain + * @example + * ```ts + * map.getTerrain(); // { source: 'terrain' }; + * ``` + */ + getTerrain() { + var _a, _b; + return (_b = (_a = this.terrain) === null || _a === void 0 ? void 0 : _a.options) !== null && _b !== void 0 ? _b : null; + } + /** + * Returns a Boolean indicating whether all tiles in the viewport from all sources on + * the style are loaded. + * + * @returns A Boolean indicating whether all tiles are loaded. + * @example + * ```ts + * let tilesLoaded = map.areTilesLoaded(); + * ``` + */ + areTilesLoaded() { + const sources = this.style && this.style.sourceCaches; + for (const id in sources) { + const source = sources[id]; + const tiles = source._tiles; + for (const t in tiles) { + const tile = tiles[t]; + if (!(tile.state === 'loaded' || tile.state === 'errored')) + return false; + } + } + return true; + } + /** + * Removes a source from the map's style. + * + * @param id - The ID of the source to remove. + * @example + * ```ts + * map.removeSource('bathymetry-data'); + * ``` + */ + removeSource(id) { + this.style.removeSource(id); + return this._update(true); + } + /** + * Returns the source with the specified ID in the map's style. + * + * This method is often used to update a source using the instance members for the relevant + * source type as defined in classes that derive from {@link Source}. + * For example, setting the `data` for a GeoJSON source or updating the `url` and `coordinates` + * of an image source. + * + * @param id - The ID of the source to get. + * @returns The style source with the specified ID or `undefined` if the ID + * corresponds to no existing sources. + * The shape of the object varies by source type. + * A list of options for each source type is available on the MapLibre Style Specification's + * [Sources](https://maplibre.org/maplibre-style-spec/sources/) page. + * @example + * ```ts + * let sourceObject = map.getSource('points'); + * ``` + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + * @see [Animate a point](https://maplibre.org/maplibre-gl-js/docs/examples/animate-point-along-line/) + * @see [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/live-geojson/) + */ + getSource(id) { + return this.style.getSource(id); + } + /** + * Add an image to the style. This image can be displayed on the map like any other icon in the style's + * sprite using the image's ID with + * [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image), + * [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern), + * [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern), + * or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern). + * + * A {@link ErrorEvent} event will be fired if the image parameter is invalid or there is not enough space in the sprite to add this image. + * + * @param id - The ID of the image. + * @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data` + * properties with the same format as `ImageData`. + * @param options - Options object. + * @example + * ```ts + * // If the style's sprite does not already contain an image with ID 'cat', + * // add the image 'cat-icon.png' to the style's sprite with the ID 'cat'. + * const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png'); + * if (!map.hasImage('cat')) map.addImage('cat', image.data); + * + * // Add a stretchable image that can be used with `icon-text-fit` + * // In this example, the image is 600px wide by 400px high. + * const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png'); + * if (map.hasImage('border-image')) return; + * map.addImage('border-image', image.data, { + * content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border + * stretchX: [[16, 584]], // stretch everything horizontally except the 16px border + * stretchY: [[16, 384]], // stretch everything vertically except the 16px border + * }); + * ``` + * @see Use `HTMLImageElement`: [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image/) + * @see Use `ImageData`: [Add a generated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-generated/) + */ + addImage(id, image, options = {}) { + const { pixelRatio = 1, sdf = false, stretchX, stretchY, content, textFitWidth, textFitHeight } = options; + this._lazyInitEmptyStyle(); + const version = 0; + if (image instanceof HTMLImageElement || isImageBitmap(image)) { + const { width, height, data } = browser.getImageData(image); + this.style.addImage(id, { data: new RGBAImage({ width, height }, data), pixelRatio, stretchX, stretchY, content, textFitWidth, textFitHeight, sdf, version }); + } + else if (image.width === undefined || image.height === undefined) { + return this.fire(new ErrorEvent(new Error('Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' + + 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`'))); + } + else { + const { width, height, data } = image; + const userImage = image; + this.style.addImage(id, { + data: new RGBAImage({ width, height }, new Uint8Array(data)), + pixelRatio, + stretchX, + stretchY, + content, + textFitWidth, + textFitHeight, + sdf, + version, + userImage + }); + if (userImage.onAdd) { + userImage.onAdd(this, id); + } + return this; + } + } + /** + * Update an existing image in a style. This image can be displayed on the map like any other icon in the style's + * sprite using the image's ID with + * [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image), + * [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern), + * [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern), + * or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern). + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param id - The ID of the image. + * @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data` + * properties with the same format as `ImageData`. + * @example + * ```ts + * // If an image with the ID 'cat' already exists in the style's sprite, + * // replace that image with a new image, 'other-cat-icon.png'. + * if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png'); + * ``` + */ + updateImage(id, image) { + const existingImage = this.style.getImage(id); + if (!existingImage) { + return this.fire(new ErrorEvent(new Error('The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.'))); + } + const imageData = (image instanceof HTMLImageElement || isImageBitmap(image)) ? + browser.getImageData(image) : + image; + const { width, height, data } = imageData; + if (width === undefined || height === undefined) { + return this.fire(new ErrorEvent(new Error('Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' + + 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`'))); + } + if (width !== existingImage.data.width || height !== existingImage.data.height) { + return this.fire(new ErrorEvent(new Error('The width and height of the updated image must be that same as the previous version of the image'))); + } + const copy = !(image instanceof HTMLImageElement || isImageBitmap(image)); + existingImage.data.replace(data, copy); + this.style.updateImage(id, existingImage); + return this; + } + /** + * Returns an image, specified by ID, currently available in the map. + * This includes both images from the style's original sprite + * and any images that have been added at runtime using {@link Map#addImage}. + * + * @param id - The ID of the image. + * @returns An image in the map with the specified ID. + * + * @example + * ```ts + * let coffeeShopIcon = map.getImage("coffee_cup"); + * ``` + */ + getImage(id) { + return this.style.getImage(id); + } + /** + * Check whether or not an image with a specific ID exists in the style. This checks both images + * in the style's original sprite and any images + * that have been added at runtime using {@link Map#addImage}. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param id - The ID of the image. + * + * @returns A Boolean indicating whether the image exists. + * @example + * Check if an image with the ID 'cat' exists in the style's sprite. + * ```ts + * let catIconExists = map.hasImage('cat'); + * ``` + */ + hasImage(id) { + if (!id) { + this.fire(new ErrorEvent(new Error('Missing required image id'))); + return false; + } + return !!this.style.getImage(id); + } + /** + * Remove an image from a style. This can be an image from the style's original + * sprite or any images + * that have been added at runtime using {@link Map#addImage}. + * + * @param id - The ID of the image. + * + * @example + * ```ts + * // If an image with the ID 'cat' exists in + * // the style's sprite, remove it. + * if (map.hasImage('cat')) map.removeImage('cat'); + * ``` + */ + removeImage(id) { + this.style.removeImage(id); + } + /** + * Load an image from an external URL to be used with {@link Map#addImage}. External + * domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS). + * + * @param url - The URL of the image file. Image file must be in png, webp, or jpg format. + * @returns a promise that is resolved when the image is loaded + * + * @example + * Load an image from an external URL. + * ```ts + * const response = await map.loadImage('https://picsum.photos/50/50'); + * // Add the loaded image to the style's sprite with the ID 'photo'. + * map.addImage('photo', response.data); + * ``` + * @see [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image/) + */ + loadImage(url) { + return ImageRequest.getImage(this._requestManager.transformRequest(url, "Image" /* ResourceType.Image */), new AbortController()); + } + /** + * Returns an Array of strings containing the IDs of all images currently available in the map. + * This includes both images from the style's original sprite + * and any images that have been added at runtime using {@link Map#addImage}. + * + * @returns An Array of strings containing the names of all sprites/images currently available in the map. + * + * @example + * ```ts + * let allImages = map.listImages(); + * ``` + */ + listImages() { + return this.style.listImages(); + } + /** + * Adds a [MapLibre style layer](https://maplibre.org/maplibre-style-spec/layers) + * to the map's style. + * + * A layer defines how data from a specified source will be styled. Read more about layer types + * and available paint and layout properties in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/layers). + * + * @param layer - The layer to add, + * conforming to either the MapLibre Style Specification's [layer definition](https://maplibre.org/maplibre-style-spec/layers) or, + * less commonly, the {@link CustomLayerInterface} specification. Can also be a layer definition with an embedded source definition. + * The MapLibre Style Specification's layer definition is appropriate for most layers. + * + * @param beforeId - The ID of an existing layer to insert the new layer before, + * resulting in the new layer appearing visually beneath the existing layer. + * If this argument is not specified, the layer will be appended to the end of the layers array + * and appear visually above all other layers. + * + * @example + * Add a circle layer with a vector source + * ```ts + * map.addLayer({ + * id: 'points-of-interest', + * source: { + * type: 'vector', + * url: 'https://demotiles.maplibre.org/tiles/tiles.json' + * }, + * 'source-layer': 'poi_label', + * type: 'circle', + * paint: { + * // MapLibre Style Specification paint properties + * }, + * layout: { + * // MapLibre Style Specification layout properties + * } + * }); + * ``` + * + * @example + * Define a source before using it to create a new layer + * ```ts + * map.addSource('state-data', { + * type: 'geojson', + * data: 'path/to/data.geojson' + * }); + * + * map.addLayer({ + * id: 'states', + * // References the GeoJSON source defined above + * // and does not require a `source-layer` + * source: 'state-data', + * type: 'symbol', + * layout: { + * // Set the label content to the + * // feature's `name` property + * text-field: ['get', 'name'] + * } + * }); + * ``` + * + * @example + * Add a new symbol layer before an existing layer + * ```ts + * map.addLayer({ + * id: 'states', + * // References a source that's already been defined + * source: 'state-data', + * type: 'symbol', + * layout: { + * // Set the label content to the + * // feature's `name` property + * text-field: ['get', 'name'] + * } + * // Add the layer before the existing `cities` layer + * }, 'cities'); + * ``` + * @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/cluster/) + * @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/vector-source/) + * @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/wms/) + */ + addLayer(layer, beforeId) { + this._lazyInitEmptyStyle(); + this.style.addLayer(layer, beforeId); + return this._update(true); + } + /** + * Moves a layer to a different z-position. + * + * @param id - The ID of the layer to move. + * @param 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. + * + * @example + * 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. + * ```ts + * map.moveLayer('polygon', 'country-label'); + * ``` + */ + moveLayer(id, beforeId) { + this.style.moveLayer(id, beforeId); + return this._update(true); + } + /** + * Removes the layer with the given ID from the map's style. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param id - The ID of the layer to remove + * + * @example + * If a layer with ID 'state-data' exists, remove it. + * ```ts + * if (map.getLayer('state-data')) map.removeLayer('state-data'); + * ``` + */ + removeLayer(id) { + this.style.removeLayer(id); + return this._update(true); + } + /** + * Returns the layer with the specified ID in the map's style. + * + * @param id - The ID of the layer to get. + * @returns The layer with the specified ID, or `undefined` + * if the ID corresponds to no existing layers. + * + * @example + * ```ts + * let stateDataLayer = map.getLayer('state-data'); + * ``` + * @see [Filter symbols by toggling a list](https://maplibre.org/maplibre-gl-js/docs/examples/filter-markers/) + * @see [Filter symbols by text input](https://maplibre.org/maplibre-gl-js/docs/examples/filter-markers-by-input/) + */ + getLayer(id) { + return this.style.getLayer(id); + } + /** + * Return the ids of all layers currently in the style, including custom layers, in order. + * + * @returns ids of layers, in order + * + * @example + * ```ts + * const orderedLayerIds = map.getLayersOrder(); + * ``` + */ + getLayersOrder() { + return this.style.getLayersOrder(); + } + /** + * Sets the zoom extent for the specified style layer. The zoom extent includes the + * [minimum zoom level](https://maplibre.org/maplibre-style-spec/layers/#minzoom) + * and [maximum zoom level](https://maplibre.org/maplibre-style-spec/layers/#maxzoom)) + * at which the layer will be rendered. + * + * Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the + * minimum zoom level of the _source layer_ because the data does not exist at those zoom levels. If the minimum + * zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style + * layer will not be rendered at all zoom levels in the zoom range. + * + * @param layerId - The ID of the layer to which the zoom extent will be applied. + * @param minzoom - The minimum zoom to set (0-24). + * @param maxzoom - The maximum zoom to set (0-24). + * + * @example + * ```ts + * map.setLayerZoomRange('my-layer', 2, 5); + * ``` + */ + setLayerZoomRange(layerId, minzoom, maxzoom) { + this.style.setLayerZoomRange(layerId, minzoom, maxzoom); + return this._update(true); + } + /** + * Sets the filter for the specified style layer. + * + * Filters control which features a style layer renders from its source. + * Any feature for which the filter expression evaluates to `true` will be + * rendered on the map. Those that are false will be hidden. + * + * Use `setFilter` to show a subset of your source data. + * + * To clear the filter, pass `null` or `undefined` as the second parameter. + * + * @param layerId - The ID of the layer to which the filter will be applied. + * @param filter - The filter, conforming to the MapLibre Style Specification's + * [filter definition](https://maplibre.org/maplibre-style-spec/layers/#filter). If `null` or `undefined` is provided, the function removes any existing filter from the layer. + * @param options - Options object. + * + * @example + * Display only features with the 'name' property 'USA' + * ```ts + * map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']); + * ``` + * @example + * Display only features with five or more 'available-spots' + * ```ts + * map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]); + * ``` + * @example + * Remove the filter for the 'bike-docks' style layer + * ```ts + * map.setFilter('bike-docks', null); + * ``` + * @see [Create a timeline animation](https://maplibre.org/maplibre-gl-js/docs/examples/timeline-animation/) + */ + setFilter(layerId, filter, options = {}) { + this.style.setFilter(layerId, filter, options); + return this._update(true); + } + /** + * Returns the filter applied to the specified style layer. + * + * @param layerId - The ID of the style layer whose filter to get. + * @returns The layer's filter. + */ + getFilter(layerId) { + return this.style.getFilter(layerId); + } + /** + * Sets the value of a paint property in the specified style layer. + * + * @param layerId - The ID of the layer to set the paint property in. + * @param name - The name of the paint property to set. + * @param value - The value of the paint property to set. + * Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/). + * Pass `null` to unset the existing value. + * @param options - Options object. + * @example + * ```ts + * map.setPaintProperty('my-layer', 'fill-color', '#faafee'); + * ``` + * @see [Change a layer's color with buttons](https://maplibre.org/maplibre-gl-js/docs/examples/color-switcher/) + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + setPaintProperty(layerId, name, value, options = {}) { + this.style.setPaintProperty(layerId, name, value, options); + return this._update(true); + } + /** + * Returns the value of a paint property in the specified style layer. + * + * @param layerId - The ID of the layer to get the paint property from. + * @param name - The name of a paint property to get. + * @returns The value of the specified paint property. + */ + getPaintProperty(layerId, name) { + return this.style.getPaintProperty(layerId, name); + } + /** + * Sets the value of a layout property in the specified style layer. + * + * @param layerId - The ID of the layer to set the layout property in. + * @param name - The name of the layout property to set. + * @param value - The value of the layout property. Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/). + * @param options - The options object. + * @example + * ```ts + * map.setLayoutProperty('my-layer', 'visibility', 'none'); + * ``` + */ + setLayoutProperty(layerId, name, value, options = {}) { + this.style.setLayoutProperty(layerId, name, value, options); + return this._update(true); + } + /** + * Returns the value of a layout property in the specified style layer. + * + * @param layerId - The ID of the layer to get the layout property from. + * @param name - The name of the layout property to get. + * @returns The value of the specified layout property. + */ + getLayoutProperty(layerId, name) { + return this.style.getLayoutProperty(layerId, name); + } + /** + * Sets the value of the style's glyphs property. + * + * @param glyphsUrl - Glyph URL to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/glyphs/). + * @param options - Options object. + * @example + * ```ts + * map.setGlyphs('https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf'); + * ``` + */ + setGlyphs(glyphsUrl, options = {}) { + this._lazyInitEmptyStyle(); + this.style.setGlyphs(glyphsUrl, options); + return this._update(true); + } + /** + * Returns the value of the style's glyphs URL + * + * @returns glyphs Style's glyphs url + */ + getGlyphs() { + return this.style.getGlyphsUrl(); + } + /** + * Adds a sprite to the map's style. Fires the `style` event. + * + * @param id - The ID of the sprite to add. Must not conflict with existing sprites. + * @param url - The URL to load the sprite from + * @param options - Options object. + * @example + * ```ts + * map.addSprite('sprite-two', 'http://example.com/sprite-two'); + * ``` + */ + addSprite(id, url, options = {}) { + this._lazyInitEmptyStyle(); + this.style.addSprite(id, url, options, (err) => { + if (!err) { + this._update(true); + } + }); + return this; + } + /** + * Removes the sprite from the map's style. Fires the `style` event. + * + * @param id - The ID of the sprite to remove. If the sprite is declared as a single URL, the ID must be "default". + * @example + * ```ts + * map.removeSprite('sprite-two'); + * map.removeSprite('default'); + * ``` + */ + removeSprite(id) { + this._lazyInitEmptyStyle(); + this.style.removeSprite(id); + return this._update(true); + } + /** + * Returns the as-is value of the style's sprite. + * + * @returns style's sprite list of id-url pairs + */ + getSprite() { + return this.style.getSprite(); + } + /** + * Sets the value of the style's sprite property. + * + * @param spriteUrl - Sprite URL to set. + * @param options - Options object. + * @example + * ```ts + * map.setSprite('YOUR_SPRITE_URL'); + * ``` + */ + setSprite(spriteUrl, options = {}) { + this._lazyInitEmptyStyle(); + this.style.setSprite(spriteUrl, options, (err) => { + if (!err) { + this._update(true); + } + }); + return this; + } + /** + * Sets the any combination of light values. + * + * @param light - Light properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/light). + * @param options - Options object. + * + * @example + * ```ts + * let layerVisibility = map.getLayoutProperty('my-layer', 'visibility'); + * ``` + */ + setLight(light, options = {}) { + this._lazyInitEmptyStyle(); + this.style.setLight(light, options); + return this._update(true); + } + /** + * Returns the value of the light object. + * + * @returns light Light properties of the style. + */ + getLight() { + return this.style.getLight(); + } + /** + * Loads sky and fog defined by {@link SkySpecification} onto the map. + * Note: The fog only shows when using the terrain 3D feature. + * @param sky - Sky properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/sky/). + * @returns `this` + * @example + * ```ts + * map.setSky({ 'sky-color': '#00f' }); + * ``` + */ + setSky(sky) { + this._lazyInitEmptyStyle(); + this.style.setSky(sky); + return this._update(true); + } + /** + * Returns the value of the sky object. + * + * @returns the sky properties of the style. + * @example + * ```ts + * map.getSky(); + * ``` + */ + getSky() { + return this.style.getSky(); + } + /** + * Sets the `state` of a feature. + * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime. + * When using this method, the `state` object is merged with any existing key-value pairs in the feature's state. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * This method can only be used with sources that have a `feature.id` attribute. The `feature.id` attribute can be defined in three ways: + * + * - For vector or GeoJSON sources, including an `id` attribute in the original data file. + * - For vector or GeoJSON sources, using the [`promoteId`](https://maplibre.org/maplibre-style-spec/sources/#vector-promoteId) option at the time the source is defined. + * - For GeoJSON sources, using the [`generateId`](https://maplibre.org/maplibre-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. + * + * _Note: You can use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state) to access the values in a feature's state object for the purposes of styling._ + * + * @param feature - Feature identifier. Feature objects returned from + * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param state - A set of key-value pairs. The values should be valid JSON types. + * + * @example + * ```ts + * // When the mouse moves over the `my-layer` layer, update + * // the feature state for the feature under the mouse + * map.on('mousemove', 'my-layer', (e) => { + * if (e.features.length > 0) { + * map.setFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id, + * }, { + * hover: true + * }); + * } + * }); + * ``` + * @see [Create a hover effect](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/) + */ + setFeatureState(feature, state) { + this.style.setFeatureState(feature, state); + return this._update(); + } + /** + * Removes the `state` of a feature, setting it back to the default behavior. + * If only a `target.source` is specified, it will remove the state for all features from that source. + * If `target.id` is also specified, it will remove all keys for that feature's state. + * If `key` is also specified, it removes only that key from that feature's state. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * @param target - Identifier of where to remove state. It can be a source, a feature, or a specific key of feature. + * Feature objects returned from {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param key - (optional) The key in the feature state to reset. + * @example + * Reset the entire state object for all features in the `my-source` source + * ```ts + * map.removeFeatureState({ + * source: 'my-source' + * }); + * ``` + * + * @example + * When the mouse leaves the `my-layer` layer, + * reset the entire state object for the + * feature under the mouse + * ```ts + * map.on('mouseleave', 'my-layer', (e) => { + * map.removeFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }); + * }); + * ``` + * + * @example + * When the mouse leaves the `my-layer` layer, + * reset only the `hover` key-value pair in the + * state for the feature under the mouse + * ```ts + * map.on('mouseleave', 'my-layer', (e) => { + * map.removeFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }, 'hover'); + * }); + * ``` + */ + removeFeatureState(target, key) { + this.style.removeFeatureState(target, key); + return this._update(); + } + /** + * Gets the `state` of a feature. + * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * _Note: To access the values in a feature's state object for the purposes of styling the feature, use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state)._ + * + * @param feature - Feature identifier. Feature objects returned from + * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @returns The state of the feature: a set of key-value pairs that was assigned to the feature at runtime. + * + * @example + * When the mouse moves over the `my-layer` layer, + * get the feature state for the feature under the mouse + * ```ts + * map.on('mousemove', 'my-layer', (e) => { + * if (e.features.length > 0) { + * map.getFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }); + * } + * }); + * ``` + */ + getFeatureState(feature) { + return this.style.getFeatureState(feature); + } + /** + * Returns the map's containing HTML element. + * + * @returns The map's container. + */ + getContainer() { + return this._container; + } + /** + * Returns the HTML element containing the map's `` element. + * + * If you want to add non-GL overlays to the map, you should append them to this element. + * + * This is the element to which event bindings for map interactivity (such as panning and zooming) are + * attached. It will receive bubbled events from child elements such as the ``, but not from + * map controls. + * + * @returns The container of the map's ``. + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + getCanvasContainer() { + return this._canvasContainer; + } + /** + * Returns the map's `` element. + * + * @returns The map's `` element. + * @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-on-symbol/) + */ + getCanvas() { + return this._canvas; + } + _containerDimensions() { + let width = 0; + let height = 0; + if (this._container) { + width = this._container.clientWidth || 400; + height = this._container.clientHeight || 300; + } + return [width, height]; + } + _setupContainer() { + const container = this._container; + container.classList.add('maplibregl-map'); + const canvasContainer = this._canvasContainer = DOM.create('div', 'maplibregl-canvas-container', container); + if (this._interactive) { + canvasContainer.classList.add('maplibregl-interactive'); + } + this._canvas = DOM.create('canvas', 'maplibregl-canvas', canvasContainer); + this._canvas.addEventListener('webglcontextlost', this._contextLost, false); + this._canvas.addEventListener('webglcontextrestored', this._contextRestored, false); + this._canvas.setAttribute('tabindex', this._interactive ? '0' : '-1'); + this._canvas.setAttribute('aria-label', this._getUIString('Map.Title')); + this._canvas.setAttribute('role', 'region'); + const dimensions = this._containerDimensions(); + const clampedPixelRatio = this._getClampedPixelRatio(dimensions[0], dimensions[1]); + this._resizeCanvas(dimensions[0], dimensions[1], clampedPixelRatio); + const controlContainer = this._controlContainer = DOM.create('div', 'maplibregl-control-container', container); + const positions = this._controlPositions = {}; + ['top-left', 'top-right', 'bottom-left', 'bottom-right'].forEach((positionName) => { + positions[positionName] = DOM.create('div', `maplibregl-ctrl-${positionName} `, controlContainer); + }); + this._container.addEventListener('scroll', this._onMapScroll, false); + } + _resizeCanvas(width, height, pixelRatio) { + // Request the required canvas size taking the pixelratio into account. + this._canvas.width = Math.floor(pixelRatio * width); + this._canvas.height = Math.floor(pixelRatio * height); + // Maintain the same canvas size, potentially downscaling it for HiDPI displays + this._canvas.style.width = `${width}px`; + this._canvas.style.height = `${height}px`; + } + _setupPainter() { + const attributes = { + alpha: true, + stencil: true, + depth: true, + failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat, + preserveDrawingBuffer: this._preserveDrawingBuffer, + antialias: this._antialias || false + }; + let webglcontextcreationerrorDetailObject = null; + this._canvas.addEventListener('webglcontextcreationerror', (args) => { + webglcontextcreationerrorDetailObject = { requestedAttributes: attributes }; + if (args) { + webglcontextcreationerrorDetailObject.statusMessage = args.statusMessage; + webglcontextcreationerrorDetailObject.type = args.type; + } + }, { once: true }); + const gl = this._canvas.getContext('webgl2', attributes) || + this._canvas.getContext('webgl', attributes); + if (!gl) { + const msg = 'Failed to initialize WebGL'; + if (webglcontextcreationerrorDetailObject) { + webglcontextcreationerrorDetailObject.message = msg; + throw new Error(JSON.stringify(webglcontextcreationerrorDetailObject)); + } + else { + throw new Error(msg); + } + } + this.painter = new Painter(gl, this.transform); + webpSupported.testSupport(gl); + } + /** + * Returns a Boolean indicating whether the map is fully loaded. + * + * Returns `false` if the style is not yet fully loaded, + * or if there has been a change to the sources or style that + * has not yet fully loaded. + * + * @returns A Boolean indicating whether the map is fully loaded. + */ + loaded() { + return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded(); + } + /** + * @internal + * Update this map's style and sources, and re-render the map. + * + * @param updateStyle - mark the map's style for reprocessing as + * well as its sources + */ + _update(updateStyle) { + if (!this.style || !this.style._loaded) + return this; + this._styleDirty = this._styleDirty || updateStyle; + this._sourcesDirty = true; + this.triggerRepaint(); + return this; + } + /** + * @internal + * Request that the given callback be executed during the next render + * frame. Schedule a render frame if one is not already scheduled. + * + * @returns An id that can be used to cancel the callback + */ + _requestRenderFrame(callback) { + this._update(); + return this._renderTaskQueue.add(callback); + } + _cancelRenderFrame(id) { + this._renderTaskQueue.remove(id); + } + /** + * @internal + * Call when a (re-)render of the map is required: + * + * - The style has changed (`setPaintProperty()`, etc.) + * - Source data has changed (e.g. tiles have finished loading) + * - The map has is moving (or just finished moving) + * - A transition is in progress + * + * @param paintStartTimeStamp - The time when the animation frame began executing. + */ + _render(paintStartTimeStamp) { + const fadeDuration = this._idleTriggered ? this._fadeDuration : 0; + // A custom layer may have used the context asynchronously. Mark the state as dirty. + this.painter.context.setDirty(); + this.painter.setBaseState(); + this._renderTaskQueue.run(paintStartTimeStamp); + // A task queue callback may have fired a user event which may have removed the map + if (this._removed) + return; + let crossFading = false; + // If the style has changed, the map is being zoomed, or a transition or fade is in progress: + // - Apply style changes (in a batch) + // - Recalculate paint properties. + if (this.style && this._styleDirty) { + this._styleDirty = false; + const zoom = this.transform.zoom; + const now = browser.now(); + this.style.zoomHistory.update(zoom, now); + const parameters = new EvaluationParameters(zoom, { + now, + fadeDuration, + zoomHistory: this.style.zoomHistory, + transition: this.style.getTransition() + }); + const factor = parameters.crossFadingFactor(); + if (factor !== 1 || factor !== this._crossFadingFactor) { + crossFading = true; + this._crossFadingFactor = factor; + } + this.style.update(parameters); + } + // If we are in _render for any reason other than an in-progress paint + // transition, update source caches to check for and load any tiles we + // need for the current transform + if (this.style && this._sourcesDirty) { + this._sourcesDirty = false; + this.style._updateSources(this.transform); + } + // update terrain stuff + if (this.terrain) { + this.terrain.sourceCache.update(this.transform, this.terrain); + this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + if (!this._elevationFreeze) { + this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + } + } + else { + this.transform.minElevationForCurrentTile = 0; + this.transform.elevation = 0; + } + this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, fadeDuration, this._crossSourceCollisions); + // Actually draw + this.painter.render(this.style, { + showTileBoundaries: this.showTileBoundaries, + showOverdrawInspector: this._showOverdrawInspector, + rotating: this.isRotating(), + zooming: this.isZooming(), + moving: this.isMoving(), + fadeDuration, + showPadding: this.showPadding, + }); + this.fire(new Event('render')); + if (this.loaded() && !this._loaded) { + this._loaded = true; + PerformanceUtils.mark(PerformanceMarkers.load); + this.fire(new Event('load')); + } + if (this.style && (this.style.hasTransitions() || crossFading)) { + this._styleDirty = true; + } + if (this.style && !this._placementDirty) { + // Since no fade operations are in progress, we can release + // all tiles held for fading. If we didn't do this, the tiles + // would just sit in the SourceCaches until the next render + this.style._releaseSymbolFadeTiles(); + } + // Schedule another render frame if it's needed. + // + // Even though `_styleDirty` and `_sourcesDirty` are reset in this + // method, synchronous events fired during Style#update or + // Style#_updateSources could have caused them to be set again. + const somethingDirty = this._sourcesDirty || this._styleDirty || this._placementDirty; + if (somethingDirty || this._repaint) { + this.triggerRepaint(); + } + else if (!this.isMoving() && this.loaded()) { + this.fire(new Event('idle')); + } + if (this._loaded && !this._fullyLoaded && !somethingDirty) { + this._fullyLoaded = true; + PerformanceUtils.mark(PerformanceMarkers.fullLoad); + } + return this; + } + /** + * Force a synchronous redraw of the map. + * @example + * ```ts + * map.redraw(); + * ``` + */ + redraw() { + if (this.style) { + // cancel the scheduled update + if (this._frameRequest) { + this._frameRequest.abort(); + this._frameRequest = null; + } + this._render(0); + } + return this; + } + /** + * Clean up and release all internal resources associated with this map. + * + * This includes DOM elements, event bindings, web workers, and WebGL resources. + * + * Use this method when you are done using the map and wish to ensure that it no + * longer consumes browser resources. Afterwards, you must not call any other + * methods on the map. + */ + remove() { + var _a; + if (this._hash) + this._hash.remove(); + for (const control of this._controls) + control.onRemove(this); + this._controls = []; + if (this._frameRequest) { + this._frameRequest.abort(); + this._frameRequest = null; + } + this._renderTaskQueue.clear(); + this.painter.destroy(); + this.handlers.destroy(); + delete this.handlers; + this.setStyle(null); + if (typeof window !== 'undefined') { + removeEventListener('online', this._onWindowOnline, false); + } + ImageRequest.removeThrottleControl(this._imageQueueHandle); + (_a = this._resizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect(); + const extension = this.painter.context.gl.getExtension('WEBGL_lose_context'); + if (extension === null || extension === void 0 ? void 0 : extension.loseContext) + extension.loseContext(); + this._canvas.removeEventListener('webglcontextrestored', this._contextRestored, false); + this._canvas.removeEventListener('webglcontextlost', this._contextLost, false); + DOM.remove(this._canvasContainer); + DOM.remove(this._controlContainer); + this._container.classList.remove('maplibregl-map'); + PerformanceUtils.clearMetrics(); + this._removed = true; + this.fire(new Event('remove')); + } + /** + * Trigger the rendering of a single frame. Use this method with custom layers to + * repaint the map when the layer changes. Calling this multiple times before the + * next frame is rendered will still result in only a single frame being rendered. + * @example + * ```ts + * map.triggerRepaint(); + * ``` + * @see [Add a 3D model](https://maplibre.org/maplibre-gl-js/docs/examples/add-3d-model/) + * @see [Add an animated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-animated/) + */ + triggerRepaint() { + if (this.style && !this._frameRequest) { + this._frameRequest = new AbortController(); + browser.frameAsync(this._frameRequest).then((paintStartTimeStamp) => { + PerformanceUtils.frame(paintStartTimeStamp); + this._frameRequest = null; + this._render(paintStartTimeStamp); + }).catch(() => { }); // ignore abort error + } + } + /** + * Gets and sets a Boolean indicating whether the map will render an outline + * around each tile and the tile ID. These tile boundaries are useful for + * debugging. + * + * The uncompressed file size of the first vector source is drawn in the top left + * corner of each tile, next to the tile ID. + * + * @example + * ```ts + * map.showTileBoundaries = true; + * ``` + */ + get showTileBoundaries() { return !!this._showTileBoundaries; } + set showTileBoundaries(value) { + if (this._showTileBoundaries === value) + return; + this._showTileBoundaries = value; + this._update(); + } + /** + * Gets and sets a Boolean indicating whether the map will visualize + * the padding offsets. + */ + get showPadding() { return !!this._showPadding; } + set showPadding(value) { + if (this._showPadding === value) + return; + this._showPadding = value; + this._update(); + } + /** + * Gets and sets a Boolean indicating whether the map will render boxes + * around all symbols in the data source, revealing which symbols + * were rendered or which were hidden due to collisions. + * This information is useful for debugging. + */ + get showCollisionBoxes() { return !!this._showCollisionBoxes; } + set showCollisionBoxes(value) { + if (this._showCollisionBoxes === value) + return; + this._showCollisionBoxes = value; + if (value) { + // When we turn collision boxes on we have to generate them for existing tiles + // When we turn them off, there's no cost to leaving existing boxes in place + this.style._generateCollisionBoxes(); + } + else { + // Otherwise, call an update to remove collision boxes + this._update(); + } + } + /** + * Gets and sets a Boolean indicating whether the map should color-code + * each fragment to show how many times it has been shaded. + * White fragments have been shaded 8 or more times. + * Black fragments have been shaded 0 times. + * This information is useful for debugging. + */ + get showOverdrawInspector() { return !!this._showOverdrawInspector; } + set showOverdrawInspector(value) { + if (this._showOverdrawInspector === value) + return; + this._showOverdrawInspector = value; + this._update(); + } + /** + * Gets and sets a Boolean indicating whether the map will + * continuously repaint. This information is useful for analyzing performance. + */ + get repaint() { return !!this._repaint; } + set repaint(value) { + if (this._repaint !== value) { + this._repaint = value; + this.triggerRepaint(); + } + } + // show vertices + get vertices() { return !!this._vertices; } + set vertices(value) { this._vertices = value; this._update(); } + /** + * Returns the package version of the library + * @returns Package version of the library + */ + get version() { + return version$1; + } + /** + * Returns the elevation for the point where the camera is looking. + * This value corresponds to: + * "meters above sea level" * "exaggeration" + * @returns The elevation. + */ + getCameraTargetElevation() { + return this.transform.elevation; + } +}; + +const assignEvents = (handler) => { + handler.touchstart = handler.dragStart; + handler.touchmoveWindow = handler.dragMove; + handler.touchend = handler.dragEnd; +}; +const generateOneFingerTouchRotationHandler = ({ enable, clickTolerance, bearingDegreesPerPixelMoved = 0.8 }) => { + const touchMoveStateManager = new OneFingerTouchMoveStateManager(); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ bearingDelta: (point.x - lastPoint.x) * bearingDegreesPerPixelMoved }), + moveStateManager: touchMoveStateManager, + enable, + assignEvents, + }); +}; +const generateOneFingerTouchPitchHandler = ({ enable, clickTolerance, pitchDegreesPerPixelMoved = -0.5 }) => { + const touchMoveStateManager = new OneFingerTouchMoveStateManager(); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ pitchDelta: (point.y - lastPoint.y) * pitchDegreesPerPixelMoved }), + moveStateManager: touchMoveStateManager, + enable, + assignEvents, + }); +}; + +const defaultOptions$3 = { + showCompass: true, + showZoom: true, + visualizePitch: false +}; +/** + * A `NavigationControl` control contains zoom buttons and a compass. + * + * @group Markers and Controls + * + * @example + * ```ts + * let nav = new NavigationControl(); + * map.addControl(nav, 'top-left'); + * ``` + * @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigation/) + */ +class NavigationControl { + /** + * @param options - the control's options + */ + constructor(options) { + this._updateZoomButtons = () => { + const zoom = this._map.getZoom(); + const isMax = zoom === this._map.getMaxZoom(); + const isMin = zoom === this._map.getMinZoom(); + this._zoomInButton.disabled = isMax; + this._zoomOutButton.disabled = isMin; + this._zoomInButton.setAttribute('aria-disabled', isMax.toString()); + this._zoomOutButton.setAttribute('aria-disabled', isMin.toString()); + }; + this._rotateCompassArrow = () => { + const rotate = this.options.visualizePitch ? + `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)` : + `rotate(${this._map.transform.angle * (180 / Math.PI)}deg)`; + this._compassIcon.style.transform = rotate; + }; + this._setButtonTitle = (button, title) => { + const str = this._map._getUIString(`NavigationControl.${title}`); + button.title = str; + button.setAttribute('aria-label', str); + }; + this.options = extend({}, defaultOptions$3, options); + this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group'); + this._container.addEventListener('contextmenu', (e) => e.preventDefault()); + if (this.options.showZoom) { + this._zoomInButton = this._createButton('maplibregl-ctrl-zoom-in', (e) => this._map.zoomIn({}, { originalEvent: e })); + DOM.create('span', 'maplibregl-ctrl-icon', this._zoomInButton).setAttribute('aria-hidden', 'true'); + this._zoomOutButton = this._createButton('maplibregl-ctrl-zoom-out', (e) => this._map.zoomOut({}, { originalEvent: e })); + DOM.create('span', 'maplibregl-ctrl-icon', this._zoomOutButton).setAttribute('aria-hidden', 'true'); + } + if (this.options.showCompass) { + this._compass = this._createButton('maplibregl-ctrl-compass', (e) => { + if (this.options.visualizePitch) { + this._map.resetNorthPitch({}, { originalEvent: e }); + } + else { + this._map.resetNorth({}, { originalEvent: e }); + } + }); + this._compassIcon = DOM.create('span', 'maplibregl-ctrl-icon', this._compass); + this._compassIcon.setAttribute('aria-hidden', 'true'); + } + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + if (this.options.showZoom) { + this._setButtonTitle(this._zoomInButton, 'ZoomIn'); + this._setButtonTitle(this._zoomOutButton, 'ZoomOut'); + this._map.on('zoom', this._updateZoomButtons); + this._updateZoomButtons(); + } + if (this.options.showCompass) { + this._setButtonTitle(this._compass, 'ResetBearing'); + if (this.options.visualizePitch) { + this._map.on('pitch', this._rotateCompassArrow); + } + this._map.on('rotate', this._rotateCompassArrow); + this._rotateCompassArrow(); + this._handler = new MouseRotateWrapper(this._map, this._compass, this.options.visualizePitch); + } + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + if (this.options.showZoom) { + this._map.off('zoom', this._updateZoomButtons); + } + if (this.options.showCompass) { + if (this.options.visualizePitch) { + this._map.off('pitch', this._rotateCompassArrow); + } + this._map.off('rotate', this._rotateCompassArrow); + this._handler.off(); + delete this._handler; + } + delete this._map; + } + _createButton(className, fn) { + const a = DOM.create('button', className, this._container); + a.type = 'button'; + a.addEventListener('click', fn); + return a; + } +} +class MouseRotateWrapper { + constructor(map, element, pitch = false) { + this.mousedown = (e) => { + this.startMouse(extend({}, e, { ctrlKey: true, preventDefault: () => e.preventDefault() }), DOM.mousePos(this.element, e)); + DOM.addEventListener(window, 'mousemove', this.mousemove); + DOM.addEventListener(window, 'mouseup', this.mouseup); + }; + this.mousemove = (e) => { + this.moveMouse(e, DOM.mousePos(this.element, e)); + }; + this.mouseup = (e) => { + this.mouseRotate.dragEnd(e); + if (this.mousePitch) + this.mousePitch.dragEnd(e); + this.offTemp(); + }; + this.touchstart = (e) => { + if (e.targetTouches.length !== 1) { + this.reset(); + } + else { + this._startPos = this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0]; + this.startTouch(e, this._startPos); + DOM.addEventListener(window, 'touchmove', this.touchmove, { passive: false }); + DOM.addEventListener(window, 'touchend', this.touchend); + } + }; + this.touchmove = (e) => { + if (e.targetTouches.length !== 1) { + this.reset(); + } + else { + this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0]; + this.moveTouch(e, this._lastPos); + } + }; + this.touchend = (e) => { + if (e.targetTouches.length === 0 && + this._startPos && + this._lastPos && + this._startPos.dist(this._lastPos) < this._clickTolerance) { + this.element.click(); + } + delete this._startPos; + delete this._lastPos; + this.offTemp(); + }; + this.reset = () => { + this.mouseRotate.reset(); + if (this.mousePitch) + this.mousePitch.reset(); + this.touchRotate.reset(); + if (this.touchPitch) + this.touchPitch.reset(); + delete this._startPos; + delete this._lastPos; + this.offTemp(); + }; + this._clickTolerance = 10; + const mapRotateTolerance = map.dragRotate._mouseRotate.getClickTolerance(); + const mapPitchTolerance = map.dragRotate._mousePitch.getClickTolerance(); + this.element = element; + this.mouseRotate = generateMouseRotationHandler({ clickTolerance: mapRotateTolerance, enable: true }); + this.touchRotate = generateOneFingerTouchRotationHandler({ clickTolerance: mapRotateTolerance, enable: true }); + this.map = map; + if (pitch) { + this.mousePitch = generateMousePitchHandler({ clickTolerance: mapPitchTolerance, enable: true }); + this.touchPitch = generateOneFingerTouchPitchHandler({ clickTolerance: mapPitchTolerance, enable: true }); + } + DOM.addEventListener(element, 'mousedown', this.mousedown); + DOM.addEventListener(element, 'touchstart', this.touchstart, { passive: false }); + DOM.addEventListener(element, 'touchcancel', this.reset); + } + startMouse(e, point) { + this.mouseRotate.dragStart(e, point); + if (this.mousePitch) + this.mousePitch.dragStart(e, point); + DOM.disableDrag(); + } + startTouch(e, point) { + this.touchRotate.dragStart(e, point); + if (this.touchPitch) + this.touchPitch.dragStart(e, point); + DOM.disableDrag(); + } + moveMouse(e, point) { + const map = this.map; + const { bearingDelta } = this.mouseRotate.dragMove(e, point) || {}; + if (bearingDelta) + map.setBearing(map.getBearing() + bearingDelta); + if (this.mousePitch) { + const { pitchDelta } = this.mousePitch.dragMove(e, point) || {}; + if (pitchDelta) + map.setPitch(map.getPitch() + pitchDelta); + } + } + moveTouch(e, point) { + const map = this.map; + const { bearingDelta } = this.touchRotate.dragMove(e, point) || {}; + if (bearingDelta) + map.setBearing(map.getBearing() + bearingDelta); + if (this.touchPitch) { + const { pitchDelta } = this.touchPitch.dragMove(e, point) || {}; + if (pitchDelta) + map.setPitch(map.getPitch() + pitchDelta); + } + } + off() { + const element = this.element; + DOM.removeEventListener(element, 'mousedown', this.mousedown); + DOM.removeEventListener(element, 'touchstart', this.touchstart, { passive: false }); + DOM.removeEventListener(window, 'touchmove', this.touchmove, { passive: false }); + DOM.removeEventListener(window, 'touchend', this.touchend); + DOM.removeEventListener(element, 'touchcancel', this.reset); + this.offTemp(); + } + offTemp() { + DOM.enableDrag(); + DOM.removeEventListener(window, 'mousemove', this.mousemove); + DOM.removeEventListener(window, 'mouseup', this.mouseup); + DOM.removeEventListener(window, 'touchmove', this.touchmove, { passive: false }); + DOM.removeEventListener(window, 'touchend', this.touchend); + } +} + +let supportsGeolocation; +function checkGeolocationSupport() { + return __awaiter(this, arguments, void 0, function* (forceRecalculation = false) { + if (supportsGeolocation !== undefined && !forceRecalculation) { + return supportsGeolocation; + } + if (window.navigator.permissions === undefined) { + supportsGeolocation = !!window.navigator.geolocation; + return supportsGeolocation; + } + // navigator.permissions has incomplete browser support + // https://caniuse.com/#feat=permissions-api + // Test for the case where a browser disables Geolocation because of an + // insecure origin + try { + const permissions = yield window.navigator.permissions.query({ name: 'geolocation' }); + supportsGeolocation = permissions.state !== 'denied'; // eslint-disable-line require-atomic-updates + } + catch (_a) { + // Fix for iOS16 which rejects query but still supports geolocation + supportsGeolocation = !!window.navigator.geolocation; // eslint-disable-line require-atomic-updates + } + return supportsGeolocation; + }); +} + +/** + * Given a LngLat, prior projected position, and a transform, return a new LngLat shifted + * n × 360° east or west for some n ≥ 0 such that: + * + * * the projected location of the result is on screen, if possible, and secondarily: + * * the difference between the projected location of the result and the prior position + * is minimized. + * + * The object is to preserve perceived object constancy for Popups and Markers as much as + * possible; they should avoid shifting large distances across the screen, even when the + * map center changes by ±360° due to automatic wrapping, and when about to go off screen, + * should wrap just enough to avoid doing so. + */ +function smartWrap(lngLat, priorPos, transform) { + const originalLngLat = new LngLat(lngLat.lng, lngLat.lat); + lngLat = new LngLat(lngLat.lng, lngLat.lat); + // First, try shifting one world in either direction, and see if either is closer to the + // prior position. This preserves object constancy when the map center is auto-wrapped + // during animations. + if (priorPos) { + const left = new LngLat(lngLat.lng - 360, lngLat.lat); + const right = new LngLat(lngLat.lng + 360, lngLat.lat); + const delta = transform.locationPoint(lngLat).distSqr(priorPos); + if (transform.locationPoint(left).distSqr(priorPos) < delta) { + lngLat = left; + } + else if (transform.locationPoint(right).distSqr(priorPos) < delta) { + lngLat = right; + } + } + // Second, wrap toward the center until the new position is on screen, or we can't get + // any closer. + while (Math.abs(lngLat.lng - transform.center.lng) > 180) { + const pos = transform.locationPoint(lngLat); + if (pos.x >= 0 && pos.y >= 0 && pos.x <= transform.width && pos.y <= transform.height) { + break; + } + if (lngLat.lng > transform.center.lng) { + lngLat.lng -= 360; + } + else { + lngLat.lng += 360; + } + } + // Apply the change only if new coord is below horizon + if (lngLat.lng !== originalLngLat.lng && + transform.locationPoint(lngLat).y > (transform.height / 2 - transform.getHorizon())) { + return lngLat; + } + return originalLngLat; +} + +const anchorTranslate = { + 'center': 'translate(-50%,-50%)', + 'top': 'translate(-50%,0)', + 'top-left': 'translate(0,0)', + 'top-right': 'translate(-100%,0)', + 'bottom': 'translate(-50%,-100%)', + 'bottom-left': 'translate(0,-100%)', + 'bottom-right': 'translate(-100%,-100%)', + 'left': 'translate(0,-50%)', + 'right': 'translate(-100%,-50%)' +}; +function applyAnchorClass(element, anchor, prefix) { + const classList = element.classList; + for (const key in anchorTranslate) { + classList.remove(`maplibregl-${prefix}-anchor-${key}`); + } + classList.add(`maplibregl-${prefix}-anchor-${anchor}`); +} + +/** + * Creates a marker component + * + * @group Markers and Controls + * + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([30.5, 50.5]) + * .addTo(map); + * ``` + * + * @example + * Set options + * ```ts + * let marker = new Marker({ + * color: "#FFFFFF", + * draggable: true + * }).setLngLat([30.5, 50.5]) + * .addTo(map); + * ``` + * @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/custom-marker-icons/) + * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/) + * + * ## Events + * + * **Event** `dragstart` of type {@link Event} will be fired when dragging starts. + * + * **Event** `drag` of type {@link Event} will be fired while dragging. + * + * **Event** `dragend` of type {@link Event} will be fired when the marker is finished being dragged. + */ +class Marker extends Evented { + /** + * @param options - the options + */ + constructor(options) { + super(); + this._onKeyPress = (e) => { + const code = e.code; + const legacyCode = e.charCode || e.keyCode; + if ((code === 'Space') || (code === 'Enter') || + (legacyCode === 32) || (legacyCode === 13) // space or enter + ) { + this.togglePopup(); + } + }; + this._onMapClick = (e) => { + const targetElement = e.originalEvent.target; + const element = this._element; + if (this._popup && (targetElement === element || element.contains(targetElement))) { + this.togglePopup(); + } + }; + this._update = (e) => { + var _a; + if (!this._map) + return; + const isFullyLoaded = this._map.loaded() && !this._map.isMoving(); + if ((e === null || e === void 0 ? void 0 : e.type) === 'terrain' || ((e === null || e === void 0 ? void 0 : e.type) === 'render' && !isFullyLoaded)) { + this._map.once('render', this._update); + } + if (this._map.transform.renderWorldCopies) { + this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map.transform); + } + else { + this._lngLat = (_a = this._lngLat) === null || _a === void 0 ? void 0 : _a.wrap(); + } + this._flatPos = this._pos = this._map.project(this._lngLat)._add(this._offset); + if (this._map.terrain) { + // flat position is saved because smartWrap needs non-elevated points + this._flatPos = this._map.transform.locationPoint(this._lngLat)._add(this._offset); + } + let rotation = ''; + if (this._rotationAlignment === 'viewport' || this._rotationAlignment === 'auto') { + rotation = `rotateZ(${this._rotation}deg)`; + } + else if (this._rotationAlignment === 'map') { + rotation = `rotateZ(${this._rotation - this._map.getBearing()}deg)`; + } + let pitch = ''; + if (this._pitchAlignment === 'viewport' || this._pitchAlignment === 'auto') { + pitch = 'rotateX(0deg)'; + } + else if (this._pitchAlignment === 'map') { + pitch = `rotateX(${this._map.getPitch()}deg)`; + } + // because rounding the coordinates at every `move` event causes stuttered zooming + // we only round them when _update is called with `moveend` or when its called with + // no arguments (when the Marker is initialized or Marker#setLngLat is invoked). + if (!this._subpixelPositioning && (!e || e.type === 'moveend')) { + this._pos = this._pos.round(); + } + DOM.setTransform(this._element, `${anchorTranslate[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${pitch} ${rotation}`); + browser.frameAsync(new AbortController()).then(() => { + this._updateOpacity(e && e.type === 'moveend'); + }).catch(() => { }); + }; + this._onMove = (e) => { + if (!this._isDragging) { + const clickTolerance = this._clickTolerance || this._map._clickTolerance; + this._isDragging = e.point.dist(this._pointerdownPos) >= clickTolerance; + } + if (!this._isDragging) + return; + this._pos = e.point.sub(this._positionDelta); + this._lngLat = this._map.unproject(this._pos); + this.setLngLat(this._lngLat); + // suppress click event so that popups don't toggle on drag + this._element.style.pointerEvents = 'none'; + // make sure dragstart only fires on the first move event after mousedown. + // this can't be on mousedown because that event doesn't necessarily + // imply that a drag is about to happen. + if (this._state === 'pending') { + this._state = 'active'; + this.fire(new Event('dragstart')); + } + this.fire(new Event('drag')); + }; + this._onUp = () => { + // revert to normal pointer event handling + this._element.style.pointerEvents = 'auto'; + this._positionDelta = null; + this._pointerdownPos = null; + this._isDragging = false; + this._map.off('mousemove', this._onMove); + this._map.off('touchmove', this._onMove); + // only fire dragend if it was preceded by at least one drag event + if (this._state === 'active') { + this.fire(new Event('dragend')); + } + this._state = 'inactive'; + }; + this._addDragHandler = (e) => { + if (this._element.contains(e.originalEvent.target)) { + e.preventDefault(); + // We need to calculate the pixel distance between the click point + // and the marker position, with the offset accounted for. Then we + // can subtract this distance from the mousemove event's position + // to calculate the new marker position. + // If we don't do this, the marker 'jumps' to the click position + // creating a jarring UX effect. + this._positionDelta = e.point.sub(this._pos).add(this._offset); + this._pointerdownPos = e.point; + this._state = 'pending'; + this._map.on('mousemove', this._onMove); + this._map.on('touchmove', this._onMove); + this._map.once('mouseup', this._onUp); + this._map.once('touchend', this._onUp); + } + }; + this._anchor = options && options.anchor || 'center'; + this._color = options && options.color || '#3FB1CE'; + this._scale = options && options.scale || 1; + this._draggable = options && options.draggable || false; + this._clickTolerance = options && options.clickTolerance || 0; + this._subpixelPositioning = options && options.subpixelPositioning || false; + this._isDragging = false; + this._state = 'inactive'; + this._rotation = options && options.rotation || 0; + this._rotationAlignment = options && options.rotationAlignment || 'auto'; + this._pitchAlignment = options && options.pitchAlignment && options.pitchAlignment !== 'auto' ? options.pitchAlignment : this._rotationAlignment; + this.setOpacity(); // set default opacity + this.setOpacity(options === null || options === void 0 ? void 0 : options.opacity, options === null || options === void 0 ? void 0 : options.opacityWhenCovered); + if (!options || !options.element) { + this._defaultMarker = true; + this._element = DOM.create('div'); + // create default map marker SVG + const svg = DOM.createNS('http://www.w3.org/2000/svg', 'svg'); + const defaultHeight = 41; + const defaultWidth = 27; + svg.setAttributeNS(null, 'display', 'block'); + svg.setAttributeNS(null, 'height', `${defaultHeight}px`); + svg.setAttributeNS(null, 'width', `${defaultWidth}px`); + svg.setAttributeNS(null, 'viewBox', `0 0 ${defaultWidth} ${defaultHeight}`); + const markerLarge = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + markerLarge.setAttributeNS(null, 'stroke', 'none'); + markerLarge.setAttributeNS(null, 'stroke-width', '1'); + markerLarge.setAttributeNS(null, 'fill', 'none'); + markerLarge.setAttributeNS(null, 'fill-rule', 'evenodd'); + const page1 = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + page1.setAttributeNS(null, 'fill-rule', 'nonzero'); + const shadow = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + shadow.setAttributeNS(null, 'transform', 'translate(3.0, 29.0)'); + shadow.setAttributeNS(null, 'fill', '#000000'); + const ellipses = [ + { 'rx': '10.5', 'ry': '5.25002273' }, + { 'rx': '10.5', 'ry': '5.25002273' }, + { 'rx': '9.5', 'ry': '4.77275007' }, + { 'rx': '8.5', 'ry': '4.29549936' }, + { 'rx': '7.5', 'ry': '3.81822308' }, + { 'rx': '6.5', 'ry': '3.34094679' }, + { 'rx': '5.5', 'ry': '2.86367051' }, + { 'rx': '4.5', 'ry': '2.38636864' } + ]; + for (const data of ellipses) { + const ellipse = DOM.createNS('http://www.w3.org/2000/svg', 'ellipse'); + ellipse.setAttributeNS(null, 'opacity', '0.04'); + ellipse.setAttributeNS(null, 'cx', '10.5'); + ellipse.setAttributeNS(null, 'cy', '5.80029008'); + ellipse.setAttributeNS(null, 'rx', data['rx']); + ellipse.setAttributeNS(null, 'ry', data['ry']); + shadow.appendChild(ellipse); + } + const background = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + background.setAttributeNS(null, 'fill', this._color); + const bgPath = DOM.createNS('http://www.w3.org/2000/svg', 'path'); + 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'); + background.appendChild(bgPath); + const border = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + border.setAttributeNS(null, 'opacity', '0.25'); + border.setAttributeNS(null, 'fill', '#000000'); + const borderPath = DOM.createNS('http://www.w3.org/2000/svg', 'path'); + 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'); + border.appendChild(borderPath); + const maki = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + maki.setAttributeNS(null, 'transform', 'translate(6.0, 7.0)'); + maki.setAttributeNS(null, 'fill', '#FFFFFF'); + const circleContainer = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + circleContainer.setAttributeNS(null, 'transform', 'translate(8.0, 8.0)'); + const circle1 = DOM.createNS('http://www.w3.org/2000/svg', 'circle'); + circle1.setAttributeNS(null, 'fill', '#000000'); + circle1.setAttributeNS(null, 'opacity', '0.25'); + circle1.setAttributeNS(null, 'cx', '5.5'); + circle1.setAttributeNS(null, 'cy', '5.5'); + circle1.setAttributeNS(null, 'r', '5.4999962'); + const circle2 = DOM.createNS('http://www.w3.org/2000/svg', 'circle'); + circle2.setAttributeNS(null, 'fill', '#FFFFFF'); + circle2.setAttributeNS(null, 'cx', '5.5'); + circle2.setAttributeNS(null, 'cy', '5.5'); + circle2.setAttributeNS(null, 'r', '5.4999962'); + circleContainer.appendChild(circle1); + circleContainer.appendChild(circle2); + page1.appendChild(shadow); + page1.appendChild(background); + page1.appendChild(border); + page1.appendChild(maki); + page1.appendChild(circleContainer); + svg.appendChild(page1); + svg.setAttributeNS(null, 'height', `${defaultHeight * this._scale}px`); + svg.setAttributeNS(null, 'width', `${defaultWidth * this._scale}px`); + this._element.appendChild(svg); + // if no element and no offset option given apply an offset for the default marker + // the -14 as the y value of the default marker offset was determined as follows + // + // the marker tip is at the center of the shadow ellipse from the default svg + // 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)" + // offset to the svg center "height (41 / 2)" gives (29.0 + 5.80029008) - (41 / 2) and rounded for an integer pixel offset gives 14 + // negative is used to move the marker up from the center so the tip is at the Marker lngLat + this._offset = Point$2.convert(options && options.offset || [0, -14]); + } + else { + this._element = options.element; + this._offset = Point$2.convert(options && options.offset || [0, 0]); + } + this._element.classList.add('maplibregl-marker'); + this._element.addEventListener('dragstart', (e) => { + e.preventDefault(); + }); + this._element.addEventListener('mousedown', (e) => { + // prevent focusing on click + e.preventDefault(); + }); + applyAnchorClass(this._element, this._anchor, 'marker'); + if (options && options.className) { + for (const name of options.className.split(' ')) { + this._element.classList.add(name); + } + } + this._popup = null; + } + /** + * Attaches the `Marker` to a `Map` object. + * @param map - The MapLibre GL JS map to add the marker to. + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([30.5, 50.5]) + * .addTo(map); // add the marker to the map + * ``` + */ + addTo(map) { + this.remove(); + this._map = map; + this._element.setAttribute('aria-label', map._getUIString('Marker.Title')); + map.getCanvasContainer().appendChild(this._element); + map.on('move', this._update); + map.on('moveend', this._update); + map.on('terrain', this._update); + this.setDraggable(this._draggable); + this._update(); + // If we attached the `click` listener to the marker element, the popup + // would close once the event propagated to `map` due to the + // `Popup#_onClickClose` listener. + this._map.on('click', this._onMapClick); + return this; + } + /** + * Removes the marker from a map + * @example + * ```ts + * let marker = new Marker().addTo(map); + * marker.remove(); + * ``` + */ + remove() { + if (this._opacityTimeout) { + clearTimeout(this._opacityTimeout); + delete this._opacityTimeout; + } + if (this._map) { + this._map.off('click', this._onMapClick); + this._map.off('move', this._update); + this._map.off('moveend', this._update); + this._map.off('terrain', this._update); + this._map.off('mousedown', this._addDragHandler); + this._map.off('touchstart', this._addDragHandler); + this._map.off('mouseup', this._onUp); + this._map.off('touchend', this._onUp); + this._map.off('mousemove', this._onMove); + this._map.off('touchmove', this._onMove); + delete this._map; + } + DOM.remove(this._element); + if (this._popup) + this._popup.remove(); + return this; + } + /** + * Get the marker's geographical location. + * + * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously + * set by `setLngLat` because `Marker` wraps the anchor longitude across copies of the world to keep + * the marker on screen. + * + * @returns A {@link LngLat} describing the marker's location. + * @example + * ```ts + * // Store the marker's longitude and latitude coordinates in a variable + * let lngLat = marker.getLngLat(); + * // Print the marker's longitude and latitude values in the console + * console.log('Longitude: ' + lngLat.lng + ', Latitude: ' + lngLat.lat ) + * ``` + * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/) + */ + getLngLat() { + return this._lngLat; + } + /** + * Set the marker's geographical position and move it. + * @param lnglat - A {@link LngLat} describing where the marker should be located. + * @example + * Create a new marker, set the longitude and latitude, and add it to the map + * ```ts + * new Marker() + * .setLngLat([-65.017, -16.457]) + * .addTo(map); + * ``` + * @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/custom-marker-icons/) + * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/) + */ + setLngLat(lnglat) { + this._lngLat = LngLat.convert(lnglat); + this._pos = null; + if (this._popup) + this._popup.setLngLat(this._lngLat); + this._update(); + return this; + } + /** + * Returns the `Marker`'s HTML element. + * @returns element + */ + getElement() { + return this._element; + } + /** + * Binds a {@link Popup} to the {@link Marker}. + * @param popup - An instance of the {@link Popup} class. If undefined or null, any popup + * set on this {@link Marker} instance is unset. + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([0, 0]) + * .setPopup(new Popup().setHTML("

Hello World!

")) // add popup + * .addTo(map); + * ``` + * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/) + */ + setPopup(popup) { + if (this._popup) { + this._popup.remove(); + this._popup = null; + this._element.removeEventListener('keypress', this._onKeyPress); + if (!this._originalTabIndex) { + this._element.removeAttribute('tabindex'); + } + } + if (popup) { + if (!('offset' in popup.options)) { + const markerHeight = 41 - (5.8 / 2); + const markerRadius = 13.5; + const linearOffset = Math.abs(markerRadius) / Math.SQRT2; + popup.options.offset = this._defaultMarker ? { + 'top': [0, 0], + 'top-left': [0, 0], + 'top-right': [0, 0], + 'bottom': [0, -markerHeight], + 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + 'left': [markerRadius, (markerHeight - markerRadius) * -1], + 'right': [-markerRadius, (markerHeight - markerRadius) * -1] + } : this._offset; + } + this._popup = popup; + this._originalTabIndex = this._element.getAttribute('tabindex'); + if (!this._originalTabIndex) { + this._element.setAttribute('tabindex', '0'); + } + this._element.addEventListener('keypress', this._onKeyPress); + } + return this; + } + /** + * Set the option to allow subpixel positioning of the marker by passing a boolean + * + * @param value - when set to `true`, subpixel positioning is enabled for the marker. + * + * @example + * ```ts + * let marker = new Marker() + * marker.setSubpixelPositioning(true); + * ``` + */ + setSubpixelPositioning(value) { + this._subpixelPositioning = value; + return this; + } + /** + * Returns the {@link Popup} instance that is bound to the {@link Marker}. + * @returns popup + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([0, 0]) + * .setPopup(new Popup().setHTML("

Hello World!

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

Hello World!

")) + * .addTo(map); + * + * marker.togglePopup(); // toggle popup open or closed + * ``` + */ + togglePopup() { + const popup = this._popup; + if (this._element.style.opacity === this._opacityWhenCovered) + return this; + if (!popup) + return this; + else if (popup.isOpen()) + popup.remove(); + else { + popup.setLngLat(this._lngLat); + popup.addTo(this._map); + } + return this; + } + _updateOpacity(force = false) { + var _a, _b; + const terrain = (_a = this._map) === null || _a === void 0 ? void 0 : _a.terrain; + if (!terrain) { + if (this._element.style.opacity !== this._opacity) { + this._element.style.opacity = this._opacity; + } + return; + } + if (force) { + this._opacityTimeout = null; + } + else { + if (this._opacityTimeout) { + return; + } + this._opacityTimeout = setTimeout(() => { + this._opacityTimeout = null; + }, 100); + } + const map = this._map; + // Read depth framebuffer, getting position of terrain in line of sight to marker + const terrainDistance = map.terrain.depthAtPoint(this._pos); + // Transform marker position to clip space + const elevation = map.terrain.getElevationForLngLatZoom(this._lngLat, map.transform.tileZoom); + const markerDistance = map.transform.lngLatToCameraDepth(this._lngLat, elevation); + const forgiveness = .006; + if (markerDistance - terrainDistance < forgiveness) { + this._element.style.opacity = this._opacity; + return; + } + // If the base is obscured, use the offset to check if the marker's center is obscured. + const metersToCenter = -this._offset.y / map.transform._pixelPerMeter; + const elevationToCenter = Math.sin(map.getPitch() * Math.PI / 180) * metersToCenter; + const terrainDistanceCenter = map.terrain.depthAtPoint(new Point$2(this._pos.x, this._pos.y - this._offset.y)); + const markerDistanceCenter = map.transform.lngLatToCameraDepth(this._lngLat, elevation + elevationToCenter); + // Display at full opacity if center is visible. + const centerIsInvisible = markerDistanceCenter - terrainDistanceCenter > forgiveness; + if (((_b = this._popup) === null || _b === void 0 ? void 0 : _b.isOpen()) && centerIsInvisible) + this._popup.remove(); + this._element.style.opacity = centerIsInvisible ? this._opacityWhenCovered : this._opacity; + } + /** + * Get the marker's offset. + * @returns The marker's screen coordinates in pixels. + */ + getOffset() { + return this._offset; + } + /** + * Sets the offset of the marker + * @param offset - The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up. + */ + setOffset(offset) { + this._offset = Point$2.convert(offset); + this._update(); + return this; + } + /** + * Adds a CSS class to the marker element. + * + * @param className - on-empty string with CSS class name to add to marker element + * + * @example + * ``` + * let marker = new Marker() + * marker.addClassName('some-class') + * ``` + */ + addClassName(className) { + this._element.classList.add(className); + } + /** + * Removes a CSS class from the marker element. + * + * @param className - Non-empty string with CSS class name to remove from marker element + * + * @example + * ```ts + * let marker = new Marker() + * marker.removeClassName('some-class') + * ``` + */ + removeClassName(className) { + this._element.classList.remove(className); + } + /** + * Add or remove the given CSS class on the marker element, depending on whether the element currently has that class. + * + * @param className - Non-empty string with CSS class name to add/remove + * + * @returns if the class was removed return false, if class was added, then return true + * + * @example + * ```ts + * let marker = new Marker() + * marker.toggleClassName('toggleClass') + * ``` + */ + toggleClassName(className) { + return this._element.classList.toggle(className); + } + /** + * Sets the `draggable` property and functionality of the marker + * @param shouldBeDraggable - Turns drag functionality on/off + */ + setDraggable(shouldBeDraggable) { + this._draggable = !!shouldBeDraggable; // convert possible undefined value to false + // handle case where map may not exist yet + // e.g. when setDraggable is called before addTo + if (this._map) { + if (shouldBeDraggable) { + this._map.on('mousedown', this._addDragHandler); + this._map.on('touchstart', this._addDragHandler); + } + else { + this._map.off('mousedown', this._addDragHandler); + this._map.off('touchstart', this._addDragHandler); + } + } + return this; + } + /** + * Returns true if the marker can be dragged + * @returns True if the marker is draggable. + */ + isDraggable() { + return this._draggable; + } + /** + * Sets the `rotation` property of the marker. + * @param rotation - The rotation angle of the marker (clockwise, in degrees), relative to its respective {@link Marker#setRotationAlignment} setting. + */ + setRotation(rotation) { + this._rotation = rotation || 0; + this._update(); + return this; + } + /** + * Returns the current rotation angle of the marker (in degrees). + * @returns The current rotation angle of the marker. + */ + getRotation() { + return this._rotation; + } + /** + * Sets the `rotationAlignment` property of the marker. + * @param alignment - Sets the `rotationAlignment` property of the marker. defaults to 'auto' + */ + setRotationAlignment(alignment) { + this._rotationAlignment = alignment || 'auto'; + this._update(); + return this; + } + /** + * Returns the current `rotationAlignment` property of the marker. + * @returns The current rotational alignment of the marker. + */ + getRotationAlignment() { + return this._rotationAlignment; + } + /** + * Sets the `pitchAlignment` property of the marker. + * @param alignment - Sets the `pitchAlignment` property of the marker. If alignment is 'auto', it will automatically match `rotationAlignment`. + */ + setPitchAlignment(alignment) { + this._pitchAlignment = alignment && alignment !== 'auto' ? alignment : this._rotationAlignment; + this._update(); + return this; + } + /** + * Returns the current `pitchAlignment` property of the marker. + * @returns The current pitch alignment of the marker in degrees. + */ + getPitchAlignment() { + return this._pitchAlignment; + } + /** + * Sets the `opacity` and `opacityWhenCovered` properties of the marker. + * When called without arguments, resets opacity and opacityWhenCovered to defaults + * @param opacity - Sets the `opacity` property of the marker. + * @param opacityWhenCovered - Sets the `opacityWhenCovered` property of the marker. + */ + setOpacity(opacity, opacityWhenCovered) { + if (opacity === undefined && opacityWhenCovered === undefined) { + this._opacity = '1'; + this._opacityWhenCovered = '0.2'; + } + if (opacity !== undefined) { + this._opacity = opacity; + } + if (opacityWhenCovered !== undefined) { + this._opacityWhenCovered = opacityWhenCovered; + } + if (this._map) { + this._updateOpacity(true); + } + return this; + } +} + +const defaultOptions$2 = { + positionOptions: { + enableHighAccuracy: false, + maximumAge: 0, + timeout: 6000 /* 6 sec */ + }, + fitBoundsOptions: { + maxZoom: 15 + }, + trackUserLocation: false, + showAccuracyCircle: true, + showUserLocation: true +}; +let numberOfWatches = 0; +let noTimeout = false; +/** + * A `GeolocateControl` control provides a button that uses the browser's geolocation + * API to locate the user on the map. + * + * Not all browsers support geolocation, + * and some users may disable the feature. Geolocation support for modern + * browsers including Chrome requires sites to be served over HTTPS. If + * geolocation support is not available, the `GeolocateControl` will show + * as disabled. + * + * The zoom level applied will depend on the accuracy of the geolocation provided by the device. + * + * 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: + * * 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. + * * passive - the user's location dot automatically updates, but the map's camera does not. Occurs upon the user initiating a map movement. + * * disabled - occurs if Geolocation is not available, disabled or denied. + * + * These interaction states can't be controlled programmatically, rather they are set based on user interactions. + * + * ## State Diagram + * ![GeolocateControl state diagram](https://github.com/maplibre/maplibre-gl-js/assets/3269297/78e720e5-d781-4da8-9803-a7a0e6aaaa9f) + * + * @group Markers and Controls + * + * @example + * ```ts + * map.addControl(new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * })); + * ``` + * @see [Locate the user](https://maplibre.org/maplibre-gl-js/docs/examples/locate-user/) + * + * ## Events + * + * **Event** `trackuserlocationend` of type {@link Event} will be fired when the `GeolocateControl` 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. + * + * **Event** `trackuserlocationstart` of type {@link Event} will be fired when the `GeolocateControl` 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). + * + * **Event** `userlocationlostfocus` of type {@link Event} will be fired when the `GeolocateControl` 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. + * + * **Event** `userlocationfocus` of type {@link Event} will be fired when the `GeolocateControl` changes to the active lock state, which happens upon 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. + * + * **Event** `geolocate` of type {@link Event} will be fired on each Geolocation API position update which returned as success. + * `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). + * + * **Event** `error` of type {@link Event} will be fired on each Geolocation API position update which returned as an error. + * `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). + * + * **Event** `outofmaxbounds` of type {@link Event} will be fired on each Geolocation API position update which returned as success but user position is out of map `maxBounds`. + * `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). + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a trackuserlocationend event occurs. + * geolocate.on('trackuserlocationend', () => { + * console.log('A trackuserlocationend event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a trackuserlocationstart event occurs. + * geolocate.on('trackuserlocationstart', () => { + * console.log('A trackuserlocationstart event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an userlocationlostfocus event occurs. + * geolocate.on('userlocationlostfocus', function() { + * console.log('An userlocationlostfocus event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an userlocationfocus event occurs. + * geolocate.on('userlocationfocus', function() { + * console.log('An userlocationfocus event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a geolocate event occurs. + * geolocate.on('geolocate', () => { + * console.log('A geolocate event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an error event occurs. + * geolocate.on('error', () => { + * console.log('An error event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an outofmaxbounds event occurs. + * geolocate.on('outofmaxbounds', () => { + * console.log('An outofmaxbounds event has occurred.') + * }); + * ``` + */ +class GeolocateControl extends Evented { + /** + * @param options - the control's options + */ + constructor(options) { + super(); + /** + * When the Geolocation API returns a new location, update the `GeolocateControl`. + * + * @param position - the Geolocation API Position + */ + this._onSuccess = (position) => { + if (!this._map) { + // control has since been removed + return; + } + if (this._isOutOfMapMaxBounds(position)) { + this._setErrorState(); + this.fire(new Event('outofmaxbounds', position)); + this._updateMarker(); + this._finish(); + return; + } + if (this.options.trackUserLocation) { + // keep a record of the position so that if the state is BACKGROUND and the user + // clicks the button, we can move to ACTIVE_LOCK immediately without waiting for + // watchPosition to trigger _onSuccess + this._lastKnownPosition = position; + switch (this._watchState) { + case 'WAITING_ACTIVE': + case 'ACTIVE_LOCK': + case 'ACTIVE_ERROR': + this._watchState = 'ACTIVE_LOCK'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active'); + break; + case 'BACKGROUND': + case 'BACKGROUND_ERROR': + this._watchState = 'BACKGROUND'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background'); + break; + default: + throw new Error(`Unexpected watchState ${this._watchState}`); + } + } + // if showUserLocation and the watch state isn't off then update the marker location + if (this.options.showUserLocation && this._watchState !== 'OFF') { + this._updateMarker(position); + } + // if in normal mode (not watch mode), or if in watch mode and the state is active watch + // then update the camera + if (!this.options.trackUserLocation || this._watchState === 'ACTIVE_LOCK') { + this._updateCamera(position); + } + if (this.options.showUserLocation) { + this._dotElement.classList.remove('maplibregl-user-location-dot-stale'); + } + this.fire(new Event('geolocate', position)); + this._finish(); + }; + /** + * Update the camera location to center on the current position + * + * @param position - the Geolocation API Position + */ + this._updateCamera = (position) => { + const center = new LngLat(position.coords.longitude, position.coords.latitude); + const radius = position.coords.accuracy; + const bearing = this._map.getBearing(); + const options = extend({ bearing }, this.options.fitBoundsOptions); + const newBounds = LngLatBounds.fromLngLat(center, radius); + this._map.fitBounds(newBounds, options, { + geolocateSource: true // tag this camera change so it won't cause the control to change to background state + }); + }; + /** + * Update the user location dot Marker to the current position + * + * @param position - the Geolocation API Position + */ + this._updateMarker = (position) => { + if (position) { + const center = new LngLat(position.coords.longitude, position.coords.latitude); + this._accuracyCircleMarker.setLngLat(center).addTo(this._map); + this._userLocationDotMarker.setLngLat(center).addTo(this._map); + this._accuracy = position.coords.accuracy; + if (this.options.showUserLocation && this.options.showAccuracyCircle) { + this._updateCircleRadius(); + } + } + else { + this._userLocationDotMarker.remove(); + this._accuracyCircleMarker.remove(); + } + }; + this._onZoom = () => { + if (this.options.showUserLocation && this.options.showAccuracyCircle) { + this._updateCircleRadius(); + } + }; + this._onError = (error) => { + if (!this._map) { + // control has since been removed + return; + } + if (this.options.trackUserLocation) { + if (error.code === 1) { + // PERMISSION_DENIED + this._watchState = 'OFF'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error'); + this._geolocateButton.disabled = true; + const title = this._map._getUIString('GeolocateControl.LocationNotAvailable'); + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + if (this._geolocationWatchID !== undefined) { + this._clearWatch(); + } + } + else if (error.code === 3 && noTimeout) { + // this represents a forced error state + // this was triggered to force immediate geolocation when a watch is already present + // see https://github.com/mapbox/mapbox-gl-js/issues/8214 + // and https://w3c.github.io/geolocation-api/#example-5-forcing-the-user-agent-to-return-a-fresh-cached-position + return; + } + else { + this._setErrorState(); + } + } + if (this._watchState !== 'OFF' && this.options.showUserLocation) { + this._dotElement.classList.add('maplibregl-user-location-dot-stale'); + } + this.fire(new Event('error', error)); + this._finish(); + }; + this._finish = () => { + if (this._timeoutId) { + clearTimeout(this._timeoutId); + } + this._timeoutId = undefined; + }; + this._setupUI = () => { + // the control could have been removed before reaching here + if (!this._map) { + return; + } + this._container.addEventListener('contextmenu', (e) => e.preventDefault()); + this._geolocateButton = DOM.create('button', 'maplibregl-ctrl-geolocate', this._container); + DOM.create('span', 'maplibregl-ctrl-icon', this._geolocateButton).setAttribute('aria-hidden', 'true'); + this._geolocateButton.type = 'button'; + this._geolocateButton.disabled = true; + }; + this._finishSetupUI = (supported) => { + // this method is called asynchronously during onAdd + if (!this._map) { + // control has since been removed + return; + } + if (supported === false) { + warnOnce('Geolocation support is not available so the GeolocateControl will be disabled.'); + const title = this._map._getUIString('GeolocateControl.LocationNotAvailable'); + this._geolocateButton.disabled = true; + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + } + else { + const title = this._map._getUIString('GeolocateControl.FindMyLocation'); + this._geolocateButton.disabled = false; + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + } + if (this.options.trackUserLocation) { + this._geolocateButton.setAttribute('aria-pressed', 'false'); + this._watchState = 'OFF'; + } + // when showUserLocation is enabled, keep the Geolocate button disabled until the device location marker is setup on the map + if (this.options.showUserLocation) { + this._dotElement = DOM.create('div', 'maplibregl-user-location-dot'); + this._userLocationDotMarker = new Marker({ element: this._dotElement }); + this._circleElement = DOM.create('div', 'maplibregl-user-location-accuracy-circle'); + this._accuracyCircleMarker = new Marker({ element: this._circleElement, pitchAlignment: 'map' }); + if (this.options.trackUserLocation) + this._watchState = 'OFF'; + this._map.on('zoom', this._onZoom); + } + this._geolocateButton.addEventListener('click', () => this.trigger()); + this._setup = true; + // when the camera is changed (and it's not as a result of the Geolocation Control) change + // the watch mode to background watch, so that the marker is updated but not the camera. + if (this.options.trackUserLocation) { + this._map.on('movestart', (event) => { + const fromResize = event.originalEvent && event.originalEvent.type === 'resize'; + if (!event.geolocateSource && this._watchState === 'ACTIVE_LOCK' && !fromResize) { + this._watchState = 'BACKGROUND'; + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this.fire(new Event('trackuserlocationend')); + this.fire(new Event('userlocationlostfocus')); + } + }); + } + }; + this.options = extend({}, defaultOptions$2, options); + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group'); + this._setupUI(); + checkGeolocationSupport().then((supported) => this._finishSetupUI(supported)); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + // clear the geolocation watch if exists + if (this._geolocationWatchID !== undefined) { + window.navigator.geolocation.clearWatch(this._geolocationWatchID); + this._geolocationWatchID = undefined; + } + // clear the markers from the map + if (this.options.showUserLocation && this._userLocationDotMarker) { + this._userLocationDotMarker.remove(); + } + if (this.options.showAccuracyCircle && this._accuracyCircleMarker) { + this._accuracyCircleMarker.remove(); + } + DOM.remove(this._container); + this._map.off('zoom', this._onZoom); + this._map = undefined; + numberOfWatches = 0; + noTimeout = false; + } + /** + * Check if the Geolocation API Position is outside the map's `maxBounds`. + * + * @param position - the Geolocation API Position + * @returns `true` if position is outside the map's `maxBounds`, otherwise returns `false`. + */ + _isOutOfMapMaxBounds(position) { + const bounds = this._map.getMaxBounds(); + const coordinates = position.coords; + return bounds && (coordinates.longitude < bounds.getWest() || + coordinates.longitude > bounds.getEast() || + coordinates.latitude < bounds.getSouth() || + coordinates.latitude > bounds.getNorth()); + } + _setErrorState() { + switch (this._watchState) { + case 'WAITING_ACTIVE': + this._watchState = 'ACTIVE_ERROR'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active-error'); + break; + case 'ACTIVE_LOCK': + this._watchState = 'ACTIVE_ERROR'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting'); + // turn marker grey + break; + case 'BACKGROUND': + this._watchState = 'BACKGROUND_ERROR'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background-error'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting'); + // turn marker grey + break; + case 'ACTIVE_ERROR': + break; + default: + throw new Error(`Unexpected watchState ${this._watchState}`); + } + } + _updateCircleRadius() { + const bounds = this._map.getBounds(); + const southEastPoint = bounds.getSouthEast(); + const northEastPoint = bounds.getNorthEast(); + const mapHeightInMeters = southEastPoint.distanceTo(northEastPoint); + const mapHeightInPixels = this._map._container.clientHeight; + const circleDiameter = Math.ceil(2 * (this._accuracy / (mapHeightInMeters / mapHeightInPixels))); + this._circleElement.style.width = `${circleDiameter}px`; + this._circleElement.style.height = `${circleDiameter}px`; + } + /** + * Programmatically request and move the map to the user's location. + * + * @returns `false` if called before control was added to a map, otherwise returns `true`. + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * map.on('load', () => { + * geolocate.trigger(); + * }); + * ``` + */ + trigger() { + if (!this._setup) { + warnOnce('Geolocate control triggered before added to a map'); + return false; + } + if (this.options.trackUserLocation) { + // update watchState and do any outgoing state cleanup + switch (this._watchState) { + case 'OFF': + // turn on the Geolocate Control + this._watchState = 'WAITING_ACTIVE'; + this.fire(new Event('trackuserlocationstart')); + break; + case 'WAITING_ACTIVE': + case 'ACTIVE_LOCK': + case 'ACTIVE_ERROR': + case 'BACKGROUND_ERROR': + // turn off the Geolocate Control + numberOfWatches--; + noTimeout = false; + this._watchState = 'OFF'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error'); + this.fire(new Event('trackuserlocationend')); + break; + case 'BACKGROUND': + this._watchState = 'ACTIVE_LOCK'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background'); + // set camera to last known location + if (this._lastKnownPosition) + this._updateCamera(this._lastKnownPosition); + this.fire(new Event('trackuserlocationstart')); + this.fire(new Event('userlocationfocus')); + break; + default: + throw new Error(`Unexpected watchState ${this._watchState}`); + } + // incoming state setup + switch (this._watchState) { + case 'WAITING_ACTIVE': + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active'); + break; + case 'ACTIVE_LOCK': + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active'); + break; + case 'OFF': + break; + default: + throw new Error(`Unexpected watchState ${this._watchState}`); + } + // manage geolocation.watchPosition / geolocation.clearWatch + if (this._watchState === 'OFF' && this._geolocationWatchID !== undefined) { + // clear watchPosition as we've changed to an OFF state + this._clearWatch(); + } + else if (this._geolocationWatchID === undefined) { + // enable watchPosition since watchState is not OFF and there is no watchPosition already running + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.setAttribute('aria-pressed', 'true'); + numberOfWatches++; + let positionOptions; + if (numberOfWatches > 1) { + positionOptions = { maximumAge: 600000, timeout: 0 }; + noTimeout = true; + } + else { + positionOptions = this.options.positionOptions; + noTimeout = false; + } + this._geolocationWatchID = window.navigator.geolocation.watchPosition(this._onSuccess, this._onError, positionOptions); + } + } + else { + window.navigator.geolocation.getCurrentPosition(this._onSuccess, this._onError, this.options.positionOptions); + // This timeout ensures that we still call finish() even if + // the user declines to share their location in Firefox + this._timeoutId = setTimeout(this._finish, 10000 /* 10sec */); + } + return true; + } + _clearWatch() { + window.navigator.geolocation.clearWatch(this._geolocationWatchID); + this._geolocationWatchID = undefined; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.setAttribute('aria-pressed', 'false'); + if (this.options.showUserLocation) { + this._updateMarker(null); + } + } +} + +const defaultOptions$1 = { + maxWidth: 100, + unit: 'metric' +}; +/** + * A `ScaleControl` control displays the ratio of a distance on the map to the corresponding distance on the ground. + * + * @group Markers and Controls + * + * @example + * ```ts + * let scale = new ScaleControl({ + * maxWidth: 80, + * unit: 'imperial' + * }); + * map.addControl(scale); + * + * scale.setUnit('metric'); + * ``` + */ +class ScaleControl { + /** + * @param options - the control's options + */ + constructor(options) { + this._onMove = () => { + updateScale(this._map, this._container, this.options); + }; + /** + * Set the scale's unit of the distance + * + * @param unit - Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`). + */ + this.setUnit = (unit) => { + this.options.unit = unit; + updateScale(this._map, this._container, this.options); + }; + this.options = Object.assign(Object.assign({}, defaultOptions$1), options); + } + getDefaultPosition() { + return 'bottom-left'; + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-scale', map.getContainer()); + this._map.on('move', this._onMove); + this._onMove(); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + this._map.off('move', this._onMove); + this._map = undefined; + } +} +function updateScale(map, container, options) { + // A horizontal scale is imagined to be present at center of the map + // container with maximum length (Default) as 100px. + // Using spherical law of cosines approximation, the real distance is + // found between the two coordinates. + const maxWidth = options && options.maxWidth || 100; + const y = map._container.clientHeight / 2; + const left = map.unproject([0, y]); + const right = map.unproject([maxWidth, y]); + const maxMeters = left.distanceTo(right); + // The real distance corresponding to 100px scale length is rounded off to + // near pretty number and the scale length for the same is found out. + // Default unit of the scale is based on User's locale. + if (options && options.unit === 'imperial') { + const maxFeet = 3.2808 * maxMeters; + if (maxFeet > 5280) { + const maxMiles = maxFeet / 5280; + setScale(container, maxWidth, maxMiles, map._getUIString('ScaleControl.Miles')); + } + else { + setScale(container, maxWidth, maxFeet, map._getUIString('ScaleControl.Feet')); + } + } + else if (options && options.unit === 'nautical') { + const maxNauticals = maxMeters / 1852; + setScale(container, maxWidth, maxNauticals, map._getUIString('ScaleControl.NauticalMiles')); + } + else if (maxMeters >= 1000) { + setScale(container, maxWidth, maxMeters / 1000, map._getUIString('ScaleControl.Kilometers')); + } + else { + setScale(container, maxWidth, maxMeters, map._getUIString('ScaleControl.Meters')); + } +} +function setScale(container, maxWidth, maxDistance, unit) { + const distance = getRoundNum(maxDistance); + const ratio = distance / maxDistance; + container.style.width = `${maxWidth * ratio}px`; + container.innerHTML = `${distance} ${unit}`; +} +function getDecimalRoundNum(d) { + const multiplier = Math.pow(10, Math.ceil(-Math.log(d) / Math.LN10)); + return Math.round(d * multiplier) / multiplier; +} +function getRoundNum(num) { + const pow10 = Math.pow(10, (`${Math.floor(num)}`).length - 1); + let d = num / pow10; + d = d >= 10 ? 10 : + d >= 5 ? 5 : + d >= 3 ? 3 : + d >= 2 ? 2 : + d >= 1 ? 1 : getDecimalRoundNum(d); + return pow10 * d; +} + +/** + * A `FullscreenControl` control contains a button for toggling the map in and out of fullscreen mode. + * When [requestFullscreen](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen) is not supported, fullscreen is handled via CSS properties. + * The map's `cooperativeGestures` option is temporarily disabled while the map + * is in fullscreen mode, and is restored when the map exist fullscreen mode. + * + * @group Markers and Controls + * @param options - the full screen control options + * + * @example + * ```ts + * map.addControl(new FullscreenControl({container: document.querySelector('body')})); + * ``` + * @see [View a fullscreen map](https://maplibre.org/maplibre-gl-js/docs/examples/fullscreen/) + * + * ## Events + * + * **Event** `fullscreenstart` of type {@link Event} will be fired when fullscreen mode has started. + * + * **Event** `fullscreenend` of type {@link Event} will be fired when fullscreen mode has ended. + */ +class FullscreenControl extends Evented { + /** + * @param options - the control's options + */ + constructor(options = {}) { + super(); + this._onFullscreenChange = () => { + var _a; + let fullscreenElement = window.document.fullscreenElement || + window.document.mozFullScreenElement || + window.document.webkitFullscreenElement || + window.document.msFullscreenElement; + while ((_a = fullscreenElement === null || fullscreenElement === void 0 ? void 0 : fullscreenElement.shadowRoot) === null || _a === void 0 ? void 0 : _a.fullscreenElement) { + fullscreenElement = fullscreenElement.shadowRoot.fullscreenElement; + } + if ((fullscreenElement === this._container) !== this._fullscreen) { + this._handleFullscreenChange(); + } + }; + this._onClickFullscreen = () => { + if (this._isFullscreen()) { + this._exitFullscreen(); + } + else { + this._requestFullscreen(); + } + }; + this._fullscreen = false; + if (options && options.container) { + if (options.container instanceof HTMLElement) { + this._container = options.container; + } + else { + warnOnce('Full screen control \'container\' must be a DOM element.'); + } + } + if ('onfullscreenchange' in document) { + this._fullscreenchange = 'fullscreenchange'; + } + else if ('onmozfullscreenchange' in document) { + this._fullscreenchange = 'mozfullscreenchange'; + } + else if ('onwebkitfullscreenchange' in document) { + this._fullscreenchange = 'webkitfullscreenchange'; + } + else if ('onmsfullscreenchange' in document) { + this._fullscreenchange = 'MSFullscreenChange'; + } + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + if (!this._container) + this._container = this._map.getContainer(); + this._controlContainer = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group'); + this._setupUI(); + return this._controlContainer; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._controlContainer); + this._map = null; + window.document.removeEventListener(this._fullscreenchange, this._onFullscreenChange); + } + _setupUI() { + const button = this._fullscreenButton = DOM.create('button', (('maplibregl-ctrl-fullscreen')), this._controlContainer); + DOM.create('span', 'maplibregl-ctrl-icon', button).setAttribute('aria-hidden', 'true'); + button.type = 'button'; + this._updateTitle(); + this._fullscreenButton.addEventListener('click', this._onClickFullscreen); + window.document.addEventListener(this._fullscreenchange, this._onFullscreenChange); + } + _updateTitle() { + const title = this._getTitle(); + this._fullscreenButton.setAttribute('aria-label', title); + this._fullscreenButton.title = title; + } + _getTitle() { + return this._map._getUIString(this._isFullscreen() ? 'FullscreenControl.Exit' : 'FullscreenControl.Enter'); + } + _isFullscreen() { + return this._fullscreen; + } + _handleFullscreenChange() { + this._fullscreen = !this._fullscreen; + this._fullscreenButton.classList.toggle('maplibregl-ctrl-shrink'); + this._fullscreenButton.classList.toggle('maplibregl-ctrl-fullscreen'); + this._updateTitle(); + if (this._fullscreen) { + this.fire(new Event('fullscreenstart')); + this._prevCooperativeGesturesEnabled = this._map.cooperativeGestures.isEnabled(); + this._map.cooperativeGestures.disable(); + } + else { + this.fire(new Event('fullscreenend')); + if (this._prevCooperativeGesturesEnabled) { + this._map.cooperativeGestures.enable(); + } + } + } + _exitFullscreen() { + if (window.document.exitFullscreen) { + window.document.exitFullscreen(); + } + else if (window.document.mozCancelFullScreen) { + window.document.mozCancelFullScreen(); + } + else if (window.document.msExitFullscreen) { + window.document.msExitFullscreen(); + } + else if (window.document.webkitCancelFullScreen) { + window.document.webkitCancelFullScreen(); + } + else { + this._togglePseudoFullScreen(); + } + } + _requestFullscreen() { + if (this._container.requestFullscreen) { + this._container.requestFullscreen(); + } + else if (this._container.mozRequestFullScreen) { + this._container.mozRequestFullScreen(); + } + else if (this._container.msRequestFullscreen) { + this._container.msRequestFullscreen(); + } + else if (this._container.webkitRequestFullscreen) { + this._container.webkitRequestFullscreen(); + } + else { + this._togglePseudoFullScreen(); + } + } + _togglePseudoFullScreen() { + this._container.classList.toggle('maplibregl-pseudo-fullscreen'); + this._handleFullscreenChange(); + this._map.resize(); + } +} + +/** + * A `TerrainControl` control contains a button for turning the terrain on and off. + * + * @group Markers and Controls + * + * @example + * ```ts + * let map = new Map({TerrainControl: false}) + * .addControl(new TerrainControl({ + * source: "terrain" + * })); + * ``` + */ +class TerrainControl { + /** + * @param options - the control's options + */ + constructor(options) { + this._toggleTerrain = () => { + if (this._map.getTerrain()) { + this._map.setTerrain(null); + } + else { + this._map.setTerrain(this.options); + } + this._updateTerrainIcon(); + }; + this._updateTerrainIcon = () => { + this._terrainButton.classList.remove('maplibregl-ctrl-terrain'); + this._terrainButton.classList.remove('maplibregl-ctrl-terrain-enabled'); + if (this._map.terrain) { + this._terrainButton.classList.add('maplibregl-ctrl-terrain-enabled'); + this._terrainButton.title = this._map._getUIString('TerrainControl.Disable'); + } + else { + this._terrainButton.classList.add('maplibregl-ctrl-terrain'); + this._terrainButton.title = this._map._getUIString('TerrainControl.Enable'); + } + }; + this.options = options; + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group'); + this._terrainButton = DOM.create('button', 'maplibregl-ctrl-terrain', this._container); + DOM.create('span', 'maplibregl-ctrl-icon', this._terrainButton).setAttribute('aria-hidden', 'true'); + this._terrainButton.type = 'button'; + this._terrainButton.addEventListener('click', this._toggleTerrain); + this._updateTerrainIcon(); + this._map.on('terrain', this._updateTerrainIcon); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + this._map.off('terrain', this._updateTerrainIcon); + this._map = undefined; + } +} + +const defaultOptions = { + closeButton: true, + closeOnClick: true, + focusAfterOpen: true, + className: '', + maxWidth: '240px', + subpixelPositioning: false +}; +const focusQuerySelector = [ + 'a[href]', + '[tabindex]:not([tabindex=\'-1\'])', + '[contenteditable]:not([contenteditable=\'false\'])', + 'button:not([disabled])', + 'input:not([disabled])', + 'select:not([disabled])', + 'textarea:not([disabled])', +].join(', '); +/** + * A popup component. + * + * @group Markers and Controls + * + * + * @example + * Create a popup + * ```ts + * let popup = new Popup(); + * // Set an event listener that will fire + * // any time the popup is opened + * popup.on('open', () => { + * console.log('popup was opened'); + * }); + * ``` + * + * @example + * Create a popup + * ```ts + * let popup = new Popup(); + * // Set an event listener that will fire + * // any time the popup is closed + * popup.on('close', () => { + * console.log('popup was closed'); + * }); + * ``` + * + * @example + * ```ts + * let markerHeight = 50, markerRadius = 10, linearOffset = 25; + * let popupOffsets = { + * 'top': [0, 0], + * 'top-left': [0,0], + * 'top-right': [0,0], + * 'bottom': [0, -markerHeight], + * 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + * 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + * 'left': [markerRadius, (markerHeight - markerRadius) * -1], + * 'right': [-markerRadius, (markerHeight - markerRadius) * -1] + * }; + * let popup = new Popup({offset: popupOffsets, className: 'my-class'}) + * .setLngLat(e.lngLat) + * .setHTML("

Hello World!

") + * .setMaxWidth("300px") + * .addTo(map); + * ``` + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/) + * + * ## Events + * + * **Event** `open` of type {@link Event} will be fired when the popup is opened manually or programmatically. + * + * **Event** `close` of type {@link Event} will be fired when the popup is closed manually or programmatically. + */ +class Popup extends Evented { + /** + * @param options - the options + */ + constructor(options) { + super(); + /** + * Removes the popup from the map it has been added to. + * + * @example + * ```ts + * let popup = new Popup().addTo(map); + * popup.remove(); + * ``` + */ + this.remove = () => { + if (this._content) { + DOM.remove(this._content); + } + if (this._container) { + DOM.remove(this._container); + delete this._container; + } + if (this._map) { + this._map.off('move', this._update); + this._map.off('move', this._onClose); + this._map.off('click', this._onClose); + this._map.off('remove', this.remove); + this._map.off('mousemove', this._onMouseMove); + this._map.off('mouseup', this._onMouseUp); + this._map.off('drag', this._onDrag); + this._map._canvasContainer.classList.remove('maplibregl-track-pointer'); + delete this._map; + this.fire(new Event('close')); + } + return this; + }; + this._onMouseUp = (event) => { + this._update(event.point); + }; + this._onMouseMove = (event) => { + this._update(event.point); + }; + this._onDrag = (event) => { + this._update(event.point); + }; + this._update = (cursor) => { + var _a; + const hasPosition = this._lngLat || this._trackPointer; + if (!this._map || !hasPosition || !this._content) { + return; + } + if (!this._container) { + this._container = DOM.create('div', 'maplibregl-popup', this._map.getContainer()); + this._tip = DOM.create('div', 'maplibregl-popup-tip', this._container); + this._container.appendChild(this._content); + if (this.options.className) { + for (const name of this.options.className.split(' ')) { + this._container.classList.add(name); + } + } + if (this._closeButton) { + this._closeButton.setAttribute('aria-label', this._map._getUIString('Popup.Close')); + } + if (this._trackPointer) { + this._container.classList.add('maplibregl-popup-track-pointer'); + } + } + if (this.options.maxWidth && this._container.style.maxWidth !== this.options.maxWidth) { + this._container.style.maxWidth = this.options.maxWidth; + } + if (this._map.transform.renderWorldCopies && !this._trackPointer) { + this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map.transform); + } + else { + this._lngLat = (_a = this._lngLat) === null || _a === void 0 ? void 0 : _a.wrap(); + } + if (this._trackPointer && !cursor) + return; + const pos = this._flatPos = this._pos = this._trackPointer && cursor ? cursor : this._map.project(this._lngLat); + if (this._map.terrain) { + // flat position is saved because smartWrap needs non-elevated points + this._flatPos = this._trackPointer && cursor ? cursor : this._map.transform.locationPoint(this._lngLat); + } + let anchor = this.options.anchor; + const offset = normalizeOffset(this.options.offset); + if (!anchor) { + const width = this._container.offsetWidth; + const height = this._container.offsetHeight; + let anchorComponents; + if (pos.y + offset.bottom.y < height) { + anchorComponents = ['top']; + } + else if (pos.y > this._map.transform.height - height) { + anchorComponents = ['bottom']; + } + else { + anchorComponents = []; + } + if (pos.x < width / 2) { + anchorComponents.push('left'); + } + else if (pos.x > this._map.transform.width - width / 2) { + anchorComponents.push('right'); + } + if (anchorComponents.length === 0) { + anchor = 'bottom'; + } + else { + anchor = anchorComponents.join('-'); + } + } + let offsetedPos = pos.add(offset[anchor]); + if (!this.options.subpixelPositioning) { + offsetedPos = offsetedPos.round(); + } + DOM.setTransform(this._container, `${anchorTranslate[anchor]} translate(${offsetedPos.x}px,${offsetedPos.y}px)`); + applyAnchorClass(this._container, anchor, 'popup'); + }; + this._onClose = () => { + this.remove(); + }; + this.options = extend(Object.create(defaultOptions), options); + } + /** + * Adds the popup to a map. + * + * @param map - The MapLibre GL JS map to add the popup to. + * @example + * ```ts + * new Popup() + * .setLngLat([0, 0]) + * .setHTML("

Null Island

") + * .addTo(map); + * ``` + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + * @see [Show polygon information on click](https://maplibre.org/maplibre-gl-js/docs/examples/polygon-popup-on-click/) + */ + addTo(map) { + if (this._map) + this.remove(); + this._map = map; + if (this.options.closeOnClick) { + this._map.on('click', this._onClose); + } + if (this.options.closeOnMove) { + this._map.on('move', this._onClose); + } + this._map.on('remove', this.remove); + this._update(); + this._focusFirstElement(); + if (this._trackPointer) { + this._map.on('mousemove', this._onMouseMove); + this._map.on('mouseup', this._onMouseUp); + if (this._container) { + this._container.classList.add('maplibregl-popup-track-pointer'); + } + this._map._canvasContainer.classList.add('maplibregl-track-pointer'); + } + else { + this._map.on('move', this._update); + } + this.fire(new Event('open')); + return this; + } + /** + * @returns `true` if the popup is open, `false` if it is closed. + */ + isOpen() { + return !!this._map; + } + /** + * Returns the geographical location of the popup's anchor. + * + * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously + * set by `setLngLat` because `Popup` wraps the anchor longitude across copies of the world to keep + * the popup on screen. + * + * @returns The geographical location of the popup's anchor. + */ + getLngLat() { + return this._lngLat; + } + /** + * Sets the geographical location of the popup's anchor, and moves the popup to it. Replaces trackPointer() behavior. + * + * @param lnglat - The geographical location to set as the popup's anchor. + */ + setLngLat(lnglat) { + this._lngLat = LngLat.convert(lnglat); + this._pos = null; + this._flatPos = null; + this._trackPointer = false; + this._update(); + if (this._map) { + this._map.on('move', this._update); + this._map.off('mousemove', this._onMouseMove); + if (this._container) { + this._container.classList.remove('maplibregl-popup-track-pointer'); + } + this._map._canvasContainer.classList.remove('maplibregl-track-pointer'); + } + return this; + } + /** + * Tracks the popup anchor to the cursor position on screens with a pointer device (it will be hidden on touchscreens). Replaces the `setLngLat` behavior. + * For most use cases, set `closeOnClick` and `closeButton` to `false`. + * @example + * ```ts + * let popup = new Popup({ closeOnClick: false, closeButton: false }) + * .setHTML("

Hello World!

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

Hello World!

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

Hello World!

") + * .addTo(map); + * ``` + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/) + */ + setHTML(html) { + const frag = document.createDocumentFragment(); + const temp = document.createElement('body'); + let child; + temp.innerHTML = html; + while (true) { + child = temp.firstChild; + if (!child) + break; + frag.appendChild(child); + } + return this.setDOMContent(frag); + } + /** + * Returns the popup's maximum width. + * + * @returns The maximum width of the popup. + */ + getMaxWidth() { + var _a; + return (_a = this._container) === null || _a === void 0 ? void 0 : _a.style.maxWidth; + } + /** + * Sets the popup's maximum width. This is setting the CSS property `max-width`. + * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width + * + * @param maxWidth - A string representing the value for the maximum width. + */ + setMaxWidth(maxWidth) { + this.options.maxWidth = maxWidth; + this._update(); + return this; + } + /** + * Sets the popup's content to the element provided as a DOM node. + * + * @param htmlNode - A DOM node to be used as content for the popup. + * @example + * Create an element with the popup content + * ```ts + * let div = document.createElement('div'); + * div.innerHTML = 'Hello, world!'; + * let popup = new Popup() + * .setLngLat(e.lngLat) + * .setDOMContent(div) + * .addTo(map); + * ``` + */ + setDOMContent(htmlNode) { + if (this._content) { + // Clear out children first. + while (this._content.hasChildNodes()) { + if (this._content.firstChild) { + this._content.removeChild(this._content.firstChild); + } + } + } + else { + this._content = DOM.create('div', 'maplibregl-popup-content', this._container); + } + // The close button should be the last tabbable element inside the popup for a good keyboard UX. + this._content.appendChild(htmlNode); + this._createCloseButton(); + this._update(); + this._focusFirstElement(); + return this; + } + /** + * Adds a CSS class to the popup container element. + * + * @param className - Non-empty string with CSS class name to add to popup container + * + * @example + * ```ts + * let popup = new Popup() + * popup.addClassName('some-class') + * ``` + */ + addClassName(className) { + if (this._container) { + this._container.classList.add(className); + } + return this; + } + /** + * Removes a CSS class from the popup container element. + * + * @param className - Non-empty string with CSS class name to remove from popup container + * + * @example + * ```ts + * let popup = new Popup() + * popup.removeClassName('some-class') + * ``` + */ + removeClassName(className) { + if (this._container) { + this._container.classList.remove(className); + } + return this; + } + /** + * Sets the popup's offset. + * + * @param offset - Sets the popup's offset. + */ + setOffset(offset) { + this.options.offset = offset; + this._update(); + return this; + } + /** + * Add or remove the given CSS class on the popup container, depending on whether the container currently has that class. + * + * @param className - Non-empty string with CSS class name to add/remove + * + * @returns if the class was removed return false, if class was added, then return true, undefined if there is no container + * + * @example + * ```ts + * let popup = new Popup() + * popup.toggleClassName('toggleClass') + * ``` + */ + toggleClassName(className) { + if (this._container) { + return this._container.classList.toggle(className); + } + } + /** + * Set the option to allow subpixel positioning of the popup by passing a boolean + * + * @param value - When boolean is true, subpixel positioning is enabled for the popup. + * + * @example + * ```ts + * let popup = new Popup() + * popup.setSubpixelPositioning(true); + * ``` + */ + setSubpixelPositioning(value) { + this.options.subpixelPositioning = value; + } + _createCloseButton() { + if (this.options.closeButton) { + this._closeButton = DOM.create('button', 'maplibregl-popup-close-button', this._content); + this._closeButton.type = 'button'; + this._closeButton.innerHTML = '×'; + this._closeButton.addEventListener('click', this._onClose); + } + } + _focusFirstElement() { + if (!this.options.focusAfterOpen || !this._container) + return; + const firstFocusable = this._container.querySelector(focusQuerySelector); + if (firstFocusable) + firstFocusable.focus(); + } +} +function normalizeOffset(offset) { + if (!offset) { + return normalizeOffset(new Point$2(0, 0)); + } + else if (typeof offset === 'number') { + // input specifies a radius from which to calculate offsets at all positions + const cornerOffset = Math.round(Math.abs(offset) / Math.SQRT2); + return { + 'center': new Point$2(0, 0), + 'top': new Point$2(0, offset), + 'top-left': new Point$2(cornerOffset, cornerOffset), + 'top-right': new Point$2(-cornerOffset, cornerOffset), + 'bottom': new Point$2(0, -offset), + 'bottom-left': new Point$2(cornerOffset, -cornerOffset), + 'bottom-right': new Point$2(-cornerOffset, -cornerOffset), + 'left': new Point$2(offset, 0), + 'right': new Point$2(-offset, 0) + }; + } + else if (offset instanceof Point$2 || Array.isArray(offset)) { + // input specifies a single offset to be applied to all positions + const convertedOffset = Point$2.convert(offset); + return { + 'center': convertedOffset, + 'top': convertedOffset, + 'top-left': convertedOffset, + 'top-right': convertedOffset, + 'bottom': convertedOffset, + 'bottom-left': convertedOffset, + 'bottom-right': convertedOffset, + 'left': convertedOffset, + 'right': convertedOffset + }; + } + else { + // input specifies an offset per position + return { + 'center': Point$2.convert(offset['center'] || [0, 0]), + 'top': Point$2.convert(offset['top'] || [0, 0]), + 'top-left': Point$2.convert(offset['top-left'] || [0, 0]), + 'top-right': Point$2.convert(offset['top-right'] || [0, 0]), + 'bottom': Point$2.convert(offset['bottom'] || [0, 0]), + 'bottom-left': Point$2.convert(offset['bottom-left'] || [0, 0]), + 'bottom-right': Point$2.convert(offset['bottom-right'] || [0, 0]), + 'left': Point$2.convert(offset['left'] || [0, 0]), + 'right': Point$2.convert(offset['right'] || [0, 0]) + }; + } +} + +const version = packageJSON.version; +/** + * Sets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text). + * Necessary for supporting the Arabic and Hebrew languages, which are written right-to-left. + * + * @param pluginURL - URL pointing to the Mapbox RTL text plugin source. + * @param lazy - If set to `true`, maplibre will defer loading the plugin until rtl text is encountered, + * rtl text will then be rendered only after the plugin finishes loading. + * @example + * ```ts + * setRTLTextPlugin('https://unpkg.com/@mapbox/mapbox-gl-rtl-text@0.2.3/mapbox-gl-rtl-text.js', false); + * ``` + * @see [Add support for right-to-left scripts](https://maplibre.org/maplibre-gl-js/docs/examples/mapbox-gl-rtl-text/) + */ +function setRTLTextPlugin(pluginURL, lazy) { + return rtlMainThreadPluginFactory().setRTLTextPlugin(pluginURL, lazy); +} +/** + * Gets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text) status. + * The status can be `unavailable` (i.e. not requested or removed), `loading`, `loaded` or `error`. + * If the status is `loaded` and the plugin is requested again, an error will be thrown. + * + * @example + * ```ts + * const pluginStatus = getRTLTextPluginStatus(); + * ``` + */ +function getRTLTextPluginStatus() { + return rtlMainThreadPluginFactory().getRTLTextPluginStatus(); +} +/** + * Returns the package version of the library + * @returns Package version of the library + */ +function getVersion() { return version; } +/** + * Gets the number of web workers instantiated on a page with GL JS maps. + * By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3). + * Make sure to set this property before creating any map instances for it to have effect. + * + * @returns Number of workers currently configured. + * @example + * ```ts + * const workerCount = getWorkerCount() + * ``` + */ +function getWorkerCount() { return WorkerPool.workerCount; } +/** + * Sets the number of web workers instantiated on a page with GL JS maps. + * By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3). + * Make sure to set this property before creating any map instances for it to have effect. + * + * @example + * ```ts + * setWorkerCount(2); + * ``` + */ +function setWorkerCount(count) { WorkerPool.workerCount = count; } +/** + * Gets and sets the maximum number of images (raster tiles, sprites, icons) to load in parallel, + * which affects performance in raster-heavy maps. 16 by default. + * + * @returns Number of parallel requests currently configured. + * @example + * ```ts + * getMaxParallelImageRequests(); + * ``` + */ +function getMaxParallelImageRequests() { return config.MAX_PARALLEL_IMAGE_REQUESTS; } +/** + * Sets the maximum number of images (raster tiles, sprites, icons) to load in parallel, + * which affects performance in raster-heavy maps. 16 by default. + * + * @example + * ```ts + * setMaxParallelImageRequests(10); + * ``` + */ +function setMaxParallelImageRequests(numRequests) { config.MAX_PARALLEL_IMAGE_REQUESTS = numRequests; } +/** + * Gets the worker url + * @returns The worker url + */ +function getWorkerUrl() { return config.WORKER_URL; } +/** + * Sets the worker url + */ +function setWorkerUrl(value) { config.WORKER_URL = value; } +/** + * Allows loading javascript code in the worker thread. + * *Note* that since this is using some very internal classes and flows it is considered experimental and can break at any point. + * + * It can be useful for the following examples: + * 1. Using `self.addProtocol` in the worker thread - note that you might need to also register the protocol on the main thread. + * 2. Using `self.registerWorkerSource(workerSource: WorkerSource)` to register a worker source, which should come with `addSourceType` usually. + * 3. using `self.actor.registerMessageHandler` to override some internal worker operations + * @param workerUrl - the worker url e.g. a url of a javascript file to load in the worker + * @returns + * + * @example + * ```ts + * // below is an example of sending a js file to the worker to load the method there + * // Note that you'll need to call the global function `addProtocol` in the worker to register the protocol there. + * // add-protocol-worker.js + * async function loadFn(params, abortController) { + * const t = await fetch(`https://${params.url.split("://")[1]}`); + * if (t.status == 200) { + * const buffer = await t.arrayBuffer(); + * return {data: buffer} + * } else { + * throw new Error(`Tile fetch error: ${t.statusText}`); + * } + * } + * self.addProtocol('custom', loadFn); + * + * // main.js + * importScriptInWorkers('add-protocol-worker.js'); + * ``` + */ +function importScriptInWorkers(workerUrl) { return getGlobalDispatcher().broadcast("IS" /* MessageType.importScript */, workerUrl); } + +exports.AJAXError = AJAXError; +exports.AttributionControl = AttributionControl; +exports.BoxZoomHandler = BoxZoomHandler; +exports.CanvasSource = CanvasSource; +exports.CooperativeGesturesHandler = CooperativeGesturesHandler; +exports.DoubleClickZoomHandler = DoubleClickZoomHandler; +exports.DragPanHandler = DragPanHandler; +exports.DragRotateHandler = DragRotateHandler; +exports.EdgeInsets = EdgeInsets; +exports.Evented = Evented; +exports.FullscreenControl = FullscreenControl; +exports.GeoJSONSource = GeoJSONSource; +exports.GeolocateControl = GeolocateControl; +exports.Hash = Hash; +exports.ImageSource = ImageSource; +exports.KeyboardHandler = KeyboardHandler; +exports.LngLat = LngLat; +exports.LngLatBounds = LngLatBounds; +exports.LogoControl = LogoControl; +exports.Map = Map$1; +exports.MapMouseEvent = MapMouseEvent; +exports.MapTouchEvent = MapTouchEvent; +exports.MapWheelEvent = MapWheelEvent; +exports.Marker = Marker; +exports.MercatorCoordinate = MercatorCoordinate; +exports.NavigationControl = NavigationControl; +exports.Point = Point$2; +exports.Popup = Popup; +exports.RasterDEMTileSource = RasterDEMTileSource; +exports.RasterTileSource = RasterTileSource; +exports.ScaleControl = ScaleControl; +exports.ScrollZoomHandler = ScrollZoomHandler; +exports.Style = Style; +exports.TerrainControl = TerrainControl; +exports.TwoFingersTouchPitchHandler = TwoFingersTouchPitchHandler; +exports.TwoFingersTouchRotateHandler = TwoFingersTouchRotateHandler; +exports.TwoFingersTouchZoomHandler = TwoFingersTouchZoomHandler; +exports.TwoFingersTouchZoomRotateHandler = TwoFingersTouchZoomRotateHandler; +exports.VectorTileSource = VectorTileSource; +exports.VideoSource = VideoSource; +exports.addProtocol = addProtocol; +exports.addSourceType = addSourceType; +exports.clearPrewarmedResources = clearPrewarmedResources; +exports.config = config; +exports.getMaxParallelImageRequests = getMaxParallelImageRequests; +exports.getRTLTextPluginStatus = getRTLTextPluginStatus; +exports.getVersion = getVersion; +exports.getWorkerCount = getWorkerCount; +exports.getWorkerUrl = getWorkerUrl; +exports.importScriptInWorkers = importScriptInWorkers; +exports.prewarm = prewarm; +exports.removeProtocol = removeProtocol; +exports.setMaxParallelImageRequests = setMaxParallelImageRequests; +exports.setRTLTextPlugin = setRTLTextPlugin; +exports.setWorkerCount = setWorkerCount; +exports.setWorkerUrl = setWorkerUrl; + +})); +//# sourceMappingURL=maplibre-gl-csp-dev.js.map diff --git a/dist/maplibre-gl-csp-worker-dev.js b/dist/maplibre-gl-csp-worker-dev.js new file mode 100644 index 0000000000..8c13f17c63 --- /dev/null +++ b/dist/maplibre-gl-csp-worker-dev.js @@ -0,0 +1,35849 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v4.7.0/LICENSE.txt + */ +var maplibregl = (function () { +'use strict'; + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; + +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; + +function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; + +function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +}; + +function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; + +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +var __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); + +function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +/** @deprecated */ +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}; + +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +} + +function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +function __classPrivateFieldIn(state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} + +function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + +} + +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + function next() { + while (env.stack.length) { + var rec = env.stack.pop(); + try { + var result = rec.dispose && rec.dispose.call(rec.value); + if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + catch (e) { + fail(e); + } + } + if (env.hasError) throw env.error; + } + return next(); +} + +var tslib_es6 = { + __extends: __extends, + __assign: __assign, + __rest: __rest, + __decorate: __decorate, + __param: __param, + __metadata: __metadata, + __awaiter: __awaiter, + __generator: __generator, + __createBinding: __createBinding, + __exportStar: __exportStar, + __values: __values, + __read: __read, + __spread: __spread, + __spreadArrays: __spreadArrays, + __spreadArray: __spreadArray, + __await: __await, + __asyncGenerator: __asyncGenerator, + __asyncDelegator: __asyncDelegator, + __asyncValues: __asyncValues, + __makeTemplateObject: __makeTemplateObject, + __importStar: __importStar, + __importDefault: __importDefault, + __classPrivateFieldGet: __classPrivateFieldGet, + __classPrivateFieldSet: __classPrivateFieldSet, + __classPrivateFieldIn: __classPrivateFieldIn, + __addDisposableResource: __addDisposableResource, + __disposeResources: __disposeResources, +}; + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs$1 (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function getDefaultExportFromNamespaceIfPresent (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; +} + +function getDefaultExportFromNamespaceIfNotNamed (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; +} + +function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a () { + if (this instanceof a) { + return Reflect.construct(f, arguments, this.constructor); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} + +'use strict'; + +var pointGeometry = Point$2; + +/** + * A standalone point geometry with useful accessor, comparison, and + * modification methods. + * + * @class Point + * @param {Number} x the x-coordinate. this could be longitude or screen + * pixels, or any other sort of unit. + * @param {Number} y the y-coordinate. this could be latitude or screen + * pixels, or any other sort of unit. + * @example + * var point = new Point(-77, 38); + */ +function Point$2(x, y) { + this.x = x; + this.y = y; +} + +Point$2.prototype = { + + /** + * Clone this point, returning a new point that can be modified + * without affecting the old one. + * @return {Point} the clone + */ + clone: function() { return new Point$2(this.x, this.y); }, + + /** + * Add this point's x & y coordinates to another point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + add: function(p) { return this.clone()._add(p); }, + + /** + * Subtract this point's x & y coordinates to from point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + sub: function(p) { return this.clone()._sub(p); }, + + /** + * Multiply this point's x & y coordinates by point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + multByPoint: function(p) { return this.clone()._multByPoint(p); }, + + /** + * Divide this point's x & y coordinates by point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + divByPoint: function(p) { return this.clone()._divByPoint(p); }, + + /** + * Multiply this point's x & y coordinates by a factor, + * yielding a new point. + * @param {Point} k factor + * @return {Point} output point + */ + mult: function(k) { return this.clone()._mult(k); }, + + /** + * Divide this point's x & y coordinates by a factor, + * yielding a new point. + * @param {Point} k factor + * @return {Point} output point + */ + div: function(k) { return this.clone()._div(k); }, + + /** + * Rotate this point around the 0, 0 origin by an angle a, + * given in radians + * @param {Number} a angle to rotate around, in radians + * @return {Point} output point + */ + rotate: function(a) { return this.clone()._rotate(a); }, + + /** + * Rotate this point around p point by an angle a, + * given in radians + * @param {Number} a angle to rotate around, in radians + * @param {Point} p Point to rotate around + * @return {Point} output point + */ + rotateAround: function(a,p) { return this.clone()._rotateAround(a,p); }, + + /** + * Multiply this point by a 4x1 transformation matrix + * @param {Array} m transformation matrix + * @return {Point} output point + */ + matMult: function(m) { return this.clone()._matMult(m); }, + + /** + * Calculate this point but as a unit vector from 0, 0, meaning + * that the distance from the resulting point to the 0, 0 + * coordinate will be equal to 1 and the angle from the resulting + * point to the 0, 0 coordinate will be the same as before. + * @return {Point} unit vector point + */ + unit: function() { return this.clone()._unit(); }, + + /** + * Compute a perpendicular point, where the new y coordinate + * is the old x coordinate and the new x coordinate is the old y + * coordinate multiplied by -1 + * @return {Point} perpendicular point + */ + perp: function() { return this.clone()._perp(); }, + + /** + * Return a version of this point with the x & y coordinates + * rounded to integers. + * @return {Point} rounded point + */ + round: function() { return this.clone()._round(); }, + + /** + * Return the magitude of this point: this is the Euclidean + * distance from the 0, 0 coordinate to this point's x and y + * coordinates. + * @return {Number} magnitude + */ + mag: function() { + return Math.sqrt(this.x * this.x + this.y * this.y); + }, + + /** + * Judge whether this point is equal to another point, returning + * true or false. + * @param {Point} other the other point + * @return {boolean} whether the points are equal + */ + equals: function(other) { + return this.x === other.x && + this.y === other.y; + }, + + /** + * Calculate the distance from this point to another point + * @param {Point} p the other point + * @return {Number} distance + */ + dist: function(p) { + return Math.sqrt(this.distSqr(p)); + }, + + /** + * Calculate the distance from this point to another point, + * without the square root step. Useful if you're comparing + * relative distances. + * @param {Point} p the other point + * @return {Number} distance + */ + distSqr: function(p) { + var dx = p.x - this.x, + dy = p.y - this.y; + return dx * dx + dy * dy; + }, + + /** + * Get the angle from the 0, 0 coordinate to this point, in radians + * coordinates. + * @return {Number} angle + */ + angle: function() { + return Math.atan2(this.y, this.x); + }, + + /** + * Get the angle from this point to another point, in radians + * @param {Point} b the other point + * @return {Number} angle + */ + angleTo: function(b) { + return Math.atan2(this.y - b.y, this.x - b.x); + }, + + /** + * Get the angle between this point and another point, in radians + * @param {Point} b the other point + * @return {Number} angle + */ + angleWith: function(b) { + return this.angleWithSep(b.x, b.y); + }, + + /* + * Find the angle of the two vectors, solving the formula for + * the cross product a x b = |a||b|sin(θ) for θ. + * @param {Number} x the x-coordinate + * @param {Number} y the y-coordinate + * @return {Number} the angle in radians + */ + angleWithSep: function(x, y) { + return Math.atan2( + this.x * y - this.y * x, + this.x * x + this.y * y); + }, + + _matMult: function(m) { + var x = m[0] * this.x + m[1] * this.y, + y = m[2] * this.x + m[3] * this.y; + this.x = x; + this.y = y; + return this; + }, + + _add: function(p) { + this.x += p.x; + this.y += p.y; + return this; + }, + + _sub: function(p) { + this.x -= p.x; + this.y -= p.y; + return this; + }, + + _mult: function(k) { + this.x *= k; + this.y *= k; + return this; + }, + + _div: function(k) { + this.x /= k; + this.y /= k; + return this; + }, + + _multByPoint: function(p) { + this.x *= p.x; + this.y *= p.y; + return this; + }, + + _divByPoint: function(p) { + this.x /= p.x; + this.y /= p.y; + return this; + }, + + _unit: function() { + this._div(this.mag()); + return this; + }, + + _perp: function() { + var y = this.y; + this.y = this.x; + this.x = -y; + return this; + }, + + _rotate: function(angle) { + var cos = Math.cos(angle), + sin = Math.sin(angle), + x = cos * this.x - sin * this.y, + y = sin * this.x + cos * this.y; + this.x = x; + this.y = y; + return this; + }, + + _rotateAround: function(angle, p) { + var cos = Math.cos(angle), + sin = Math.sin(angle), + x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y), + y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y); + this.x = x; + this.y = y; + return this; + }, + + _round: function() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } +}; + +/** + * Construct a point from an array if necessary, otherwise if the input + * is already a Point, or an unknown type, return it unchanged + * @param {Array|Point|*} a any kind of input value + * @return {Point} constructed point, or passed-through value. + * @example + * // this + * var point = Point.convert([0, 1]); + * // is equivalent to + * var point = new Point(0, 1); + */ +Point$2.convert = function (a) { + if (a instanceof Point$2) { + return a; + } + if (Array.isArray(a)) { + return new Point$2(a[0], a[1]); + } + return a; +}; + +var Point$3 = /*@__PURE__*/getDefaultExportFromCjs$1(pointGeometry); + +'use strict'; + +var unitbezier$1 = UnitBezier$2; + +function UnitBezier$2(p1x, p1y, p2x, p2y) { + // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). + this.cx = 3.0 * p1x; + this.bx = 3.0 * (p2x - p1x) - this.cx; + this.ax = 1.0 - this.cx - this.bx; + + this.cy = 3.0 * p1y; + this.by = 3.0 * (p2y - p1y) - this.cy; + this.ay = 1.0 - this.cy - this.by; + + this.p1x = p1x; + this.p1y = p1y; + this.p2x = p2x; + this.p2y = p2y; +} + +UnitBezier$2.prototype = { + sampleCurveX: function (t) { + // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. + return ((this.ax * t + this.bx) * t + this.cx) * t; + }, + + sampleCurveY: function (t) { + return ((this.ay * t + this.by) * t + this.cy) * t; + }, + + sampleCurveDerivativeX: function (t) { + return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; + }, + + solveCurveX: function (x, epsilon) { + if (epsilon === undefined) epsilon = 1e-6; + + if (x < 0.0) return 0.0; + if (x > 1.0) return 1.0; + + var t = x; + + // First try a few iterations of Newton's method - normally very fast. + for (var i = 0; i < 8; i++) { + var x2 = this.sampleCurveX(t) - x; + if (Math.abs(x2) < epsilon) return t; + + var d2 = this.sampleCurveDerivativeX(t); + if (Math.abs(d2) < 1e-6) break; + + t = t - x2 / d2; + } + + // Fall back to the bisection method for reliability. + var t0 = 0.0; + var t1 = 1.0; + t = x; + + for (i = 0; i < 20; i++) { + x2 = this.sampleCurveX(t); + if (Math.abs(x2 - x) < epsilon) break; + + if (x > x2) { + t0 = t; + } else { + t1 = t; + } + + t = (t1 - t0) * 0.5 + t0; + } + + return t; + }, + + solve: function (x, epsilon) { + return this.sampleCurveY(this.solveCurveX(x, epsilon)); + } +}; + +var UnitBezier$3 = /*@__PURE__*/getDefaultExportFromCjs$1(unitbezier$1); + +let supportsOffscreenCanvas; +function offscreenCanvasSupported() { + if (supportsOffscreenCanvas == null) { + supportsOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && + new OffscreenCanvas(1, 1).getContext('2d') && + typeof createImageBitmap === 'function'; + } + return supportsOffscreenCanvas; +} + +let offscreenCanvasDistorted; +/** + * Some browsers don't return the exact pixels from a canvas to prevent user fingerprinting (see #3185). + * This function writes pixels to an OffscreenCanvas and reads them back using getImageData, returning false + * if they don't match. + * + * @returns true if the browser supports OffscreenCanvas but it distorts getImageData results, false otherwise. + */ +function isOffscreenCanvasDistorted() { + if (offscreenCanvasDistorted == null) { + offscreenCanvasDistorted = false; + if (offscreenCanvasSupported()) { + const size = 5; + const canvas = new OffscreenCanvas(size, size); + const context = canvas.getContext('2d', { willReadFrequently: true }); + if (context) { + // fill each pixel with an RGB value that should make the byte at index i equal to i (except alpha channel): + // [0, 1, 2, 255, 4, 5, 6, 255, 8, 9, 10, 255, ...] + for (let i = 0; i < size * size; i++) { + const base = i * 4; + context.fillStyle = `rgb(${base},${base + 1},${base + 2})`; + context.fillRect(i % size, Math.floor(i / size), 1, 1); + } + const data = context.getImageData(0, 0, size, size).data; + for (let i = 0; i < size * size * 4; i++) { + if (i % 4 !== 3 && data[i] !== i) { + offscreenCanvasDistorted = true; + break; + } + } + } + } + } + return offscreenCanvasDistorted || false; +} + +/** + * For a given collection of 2D points, returns their axis-aligned bounding box, + * in the format [minX, minY, maxX, maxY]. + */ +function getAABB(points) { + let tlX = Infinity; + let tlY = Infinity; + let brX = -Infinity; + let brY = -Infinity; + for (const p of points) { + tlX = Math.min(tlX, p.x); + tlY = Math.min(tlY, p.y); + brX = Math.max(brX, p.x); + brY = Math.max(brY, p.y); + } + return [tlX, tlY, brX, brY]; +} +/** + * Given a value `t` that varies between 0 and 1, return + * an interpolation function that eases between 0 and 1 in a pleasing + * cubic in-out fashion. + */ +function easeCubicInOut(t) { + if (t <= 0) + return 0; + if (t >= 1) + return 1; + const t2 = t * t, t3 = t2 * t; + return 4 * (t < 0.5 ? t3 : 3 * (t - t2) + t3 - 0.75); +} +/** + * Given given (x, y), (x1, y1) control points for a bezier curve, + * return a function that interpolates along that curve. + * + * @param p1x - control point 1 x coordinate + * @param p1y - control point 1 y coordinate + * @param p2x - control point 2 x coordinate + * @param p2y - control point 2 y coordinate + */ +function bezier$1(p1x, p1y, p2x, p2y) { + const bezier = new UnitBezier$3(p1x, p1y, p2x, p2y); + return (t) => { + return bezier.solve(t); + }; +} +/** + * A default bezier-curve powered easing function with + * control points (0.25, 0.1) and (0.25, 1) + */ +const defaultEasing = bezier$1(0.25, 0.1, 0.25, 1); +/** + * constrain n to the given range via min + max + * + * @param n - value + * @param min - the minimum value to be returned + * @param max - the maximum value to be returned + * @returns the clamped value + */ +function clamp$1(n, min, max) { + return Math.min(max, Math.max(min, n)); +} +/** + * constrain n to the given range, excluding the minimum, via modular arithmetic + * + * @param n - value + * @param min - the minimum value to be returned, exclusive + * @param max - the maximum value to be returned, inclusive + * @returns constrained number + */ +function wrap$1(n, min, max) { + const d = max - min; + const w = ((n - min) % d + d) % d + min; + return (w === min) ? max : w; +} +/** + * Compute the difference between the keys in one object and the keys + * in another object. + * + * @returns keys difference + */ +function keysDifference(obj, other) { + const difference = []; + for (const i in obj) { + if (!(i in other)) { + difference.push(i); + } + } + return difference; +} +function extend$1(dest, ...sources) { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; +} +/** + * Given an object and a number of properties as strings, return version + * of that object with only those properties. + * + * @param src - the object + * @param properties - an array of property names chosen + * to appear on the resulting object. + * @returns object with limited properties. + * @example + * ```ts + * let foo = { name: 'Charlie', age: 10 }; + * let justName = pick(foo, ['name']); // justName = { name: 'Charlie' } + * ``` + */ +function pick(src, properties) { + const result = {}; + for (let i = 0; i < properties.length; i++) { + const k = properties[i]; + if (k in src) { + result[k] = src[k]; + } + } + return result; +} +let id = 1; +/** + * Return a unique numeric id, starting at 1 and incrementing with + * each call. + * + * @returns unique numeric id. + */ +function uniqueId() { + return id++; +} +/** + * Return whether a given value is a power of two + */ +function isPowerOfTwo(value) { + return (Math.log(value) / Math.LN2) % 1 === 0; +} +/** + * Return the next power of two, or the input value if already a power of two + */ +function nextPowerOfTwo(value) { + if (value <= 1) + return 1; + return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2)); +} +/** + * Create an object by mapping all the values of an existing object while + * preserving their keys. + */ +function mapObject(input, iterator, context) { + const output = {}; + for (const key in input) { + output[key] = iterator.call(context || this, input[key], key, input); + } + return output; +} +/** + * Create an object by filtering out values of an existing object. + */ +function filterObject(input, iterator, context) { + const output = {}; + for (const key in input) { + if (iterator.call(context || this, input[key], key, input)) { + output[key] = input[key]; + } + } + return output; +} +/** + * Deeply compares two object literals. + * @param a - first object literal to be compared + * @param b - second object literal to be compared + * @returns true if the two object literals are deeply equal, false otherwise + */ +function deepEqual$1(a, b) { + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) { + if (!deepEqual$1(a[i], b[i])) + return false; + } + return true; + } + if (typeof a === 'object' && a !== null && b !== null) { + if (!(typeof b === 'object')) + return false; + const keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) + return false; + for (const key in a) { + if (!deepEqual$1(a[key], b[key])) + return false; + } + return true; + } + return a === b; +} +/** + * Deeply clones two objects. + */ +function clone$9(input) { + if (Array.isArray(input)) { + return input.map(clone$9); + } + else if (typeof input === 'object' && input) { + return mapObject(input, clone$9); + } + else { + return input; + } +} +/** + * Check if two arrays have at least one common element. + */ +function arraysIntersect(a, b) { + for (let l = 0; l < a.length; l++) { + if (b.indexOf(a[l]) >= 0) + return true; + } + return false; +} +/** + * Print a warning message to the console and ensure duplicate warning messages + * are not printed. + */ +const warnOnceHistory = {}; +function warnOnce(message) { + if (!warnOnceHistory[message]) { + // console isn't defined in some WebWorkers, see #2558 + if (typeof console !== 'undefined') + console.warn(message); + warnOnceHistory[message] = true; + } +} +/** + * Indicates if the provided Points are in a counter clockwise (true) or clockwise (false) order + * + * @returns true for a counter clockwise set of points + */ +// https://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/ +function isCounterClockwise(a, b, c) { + return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x); +} +/** + * For two lines a and b in 2d space, defined by any two points along the lines, + * find the intersection point, or return null if the lines are parallel + * + * @param a1 - First point on line a + * @param a2 - Second point on line a + * @param b1 - First point on line b + * @param b2 - Second point on line b + * + * @returns the intersection point of the two lines or null if they are parallel + */ +function findLineIntersection(a1, a2, b1, b2) { + const aDeltaY = a2.y - a1.y; + const aDeltaX = a2.x - a1.x; + const bDeltaY = b2.y - b1.y; + const bDeltaX = b2.x - b1.x; + const denominator = (bDeltaY * aDeltaX) - (bDeltaX * aDeltaY); + if (denominator === 0) { + // Lines are parallel + return null; + } + const originDeltaY = a1.y - b1.y; + const originDeltaX = a1.x - b1.x; + const aInterpolation = (bDeltaX * originDeltaY - bDeltaY * originDeltaX) / denominator; + // Find intersection by projecting out from origin of first segment + return new Point$3(a1.x + (aInterpolation * aDeltaX), a1.y + (aInterpolation * aDeltaY)); +} +/** + * Converts spherical coordinates to cartesian coordinates. + * + * @param spherical - Spherical coordinates, in [radial, azimuthal, polar] + * @returns cartesian coordinates in [x, y, z] + */ +function sphericalToCartesian([r, azimuthal, polar]) { + // We abstract "north"/"up" (compass-wise) to be 0° when really this is 90° (π/2): + // correct for that here + azimuthal += 90; + // Convert azimuthal and polar angles to radians + azimuthal *= Math.PI / 180; + polar *= Math.PI / 180; + return { + x: r * Math.cos(azimuthal) * Math.sin(polar), + y: r * Math.sin(azimuthal) * Math.sin(polar), + z: r * Math.cos(polar) + }; +} +/** + * Returns true if the when run in the web-worker context. + * + * @returns `true` if the when run in the web-worker context. + */ +function isWorker(self) { + // @ts-ignore + return typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof WorkerGlobalScope; +} +/** + * Parses data from 'Cache-Control' headers. + * + * @param cacheControl - Value of 'Cache-Control' header + * @returns object containing parsed header info. + */ +function parseCacheControl(cacheControl) { + // Taken from [Wreck](https://github.com/hapijs/wreck) + const re = /(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g; + const header = {}; + cacheControl.replace(re, ($0, $1, $2, $3) => { + const value = $2 || $3; + header[$1] = value ? value.toLowerCase() : true; + return ''; + }); + if (header['max-age']) { + const maxAge = parseInt(header['max-age'], 10); + if (isNaN(maxAge)) + delete header['max-age']; + else + header['max-age'] = maxAge; + } + return header; +} +let _isSafari = null; +/** + * Returns true when run in WebKit derived browsers. + * This is used as a workaround for a memory leak in Safari caused by using Transferable objects to + * transfer data between WebWorkers and the main thread. + * https://github.com/mapbox/mapbox-gl-js/issues/8771 + * + * This should be removed once the underlying Safari issue is fixed. + * + * @param scope - Since this function is used both on the main thread and WebWorker context, + * let the calling scope pass in the global scope object. + * @returns `true` when run in WebKit derived browsers. + */ +function isSafari(scope) { + if (_isSafari == null) { + const userAgent = scope.navigator ? scope.navigator.userAgent : null; + _isSafari = !!scope.safari || + !!(userAgent && (/\b(iPad|iPhone|iPod)\b/.test(userAgent) || (!!userAgent.match('Safari') && !userAgent.match('Chrome')))); + } + return _isSafari; +} +function storageAvailable(type) { + try { + const storage = window[type]; + storage.setItem('_mapbox_test_', 1); + storage.removeItem('_mapbox_test_'); + return true; + } + catch (e) { + return false; + } +} +// The following methods are from https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem +//Unicode compliant base64 encoder for strings +function b64EncodeUnicode(str) { + return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => { + return String.fromCharCode(Number('0x' + p1)); //eslint-disable-line + })); +} +// Unicode compliant decoder for base64-encoded strings +function b64DecodeUnicode(str) { + return decodeURIComponent(atob(str).split('').map((c) => { + return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); //eslint-disable-line + }).join('')); +} +function isImageBitmap(image) { + return typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap; +} +/** + * Converts an ArrayBuffer to an ImageBitmap. + * + * Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work + * perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting + * ArrayBuffers. + * + * @param data - Data to convert + * @returns - A promise resolved when the conversion is finished + */ +const arrayBufferToImageBitmap = (data) => __awaiter(void 0, void 0, void 0, function* () { + if (data.byteLength === 0) { + return createImageBitmap(new ImageData(1, 1)); + } + const blob = new Blob([new Uint8Array(data)], { type: 'image/png' }); + try { + return createImageBitmap(blob); + } + catch (e) { + throw 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.`); + } +}); +const transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII='; +/** + * Converts an ArrayBuffer to an HTMLImageElement. + * + * Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work + * perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting + * ArrayBuffers. + * + * @param data - Data to convert + * @returns - A promise resolved when the conversion is finished + */ +const arrayBufferToImage = (data) => { + return new Promise((resolve, reject) => { + const img = new Image(); + img.onload = () => { + resolve(img); + URL.revokeObjectURL(img.src); + // prevent image dataURI memory leak in Safari; + // but don't free the image immediately because it might be uploaded in the next frame + // https://github.com/mapbox/mapbox-gl-js/issues/10226 + img.onload = null; + window.requestAnimationFrame(() => { img.src = transparentPngUrl; }); + }; + img.onerror = () => reject(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.')); + const blob = new Blob([new Uint8Array(data)], { type: 'image/png' }); + img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl; + }); +}; +/** + * Computes the webcodecs VideoFrame API options to select a rectangle out of + * an image and write it into the destination rectangle. + * + * Rect (x/y/width/height) select the overlapping rectangle from the source image + * and layout (offset/stride) write that overlapping rectangle to the correct place + * in the destination image. + * + * Offset is the byte offset in the dest image that the first pixel appears at + * and stride is the number of bytes to the start of the next row: + * ┌───────────┐ + * │ dest │ + * │ ┌───┼───────┐ + * │offset→│▓▓▓│ source│ + * │ │▓▓▓│ │ + * │ └───┼───────┘ + * │stride ⇠╌╌╌│ + * │╌╌╌╌╌╌→ │ + * └───────────┘ + * + * @param image - source image containing a width and height attribute + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns the layout and rect options to pass into VideoFrame API + */ +function computeVideoFrameParameters(image, x, y, width, height) { + const destRowOffset = Math.max(-x, 0) * 4; + const firstSourceRow = Math.max(0, y); + const firstDestRow = firstSourceRow - y; + const offset = firstDestRow * width * 4 + destRowOffset; + const stride = width * 4; + const sourceLeft = Math.max(0, x); + const sourceTop = Math.max(0, y); + const sourceRight = Math.min(image.width, x + width); + const sourceBottom = Math.min(image.height, y + height); + return { + rect: { + x: sourceLeft, + y: sourceTop, + width: sourceRight - sourceLeft, + height: sourceBottom - sourceTop + }, + layout: [{ offset, stride }] + }; +} +/** + * Reads pixels from an ImageBitmap/Image/canvas using webcodec VideoFrame API. + * + * @param data - image, imagebitmap, or canvas to parse + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred + */ +function readImageUsingVideoFrame(image, x, y, width, height) { + return __awaiter(this, void 0, void 0, function* () { + if (typeof VideoFrame === 'undefined') { + throw new Error('VideoFrame not supported'); + } + const frame = new VideoFrame(image, { timestamp: 0 }); + try { + const format = frame === null || frame === void 0 ? void 0 : frame.format; + if (!format || !(format.startsWith('BGR') || format.startsWith('RGB'))) { + throw new Error(`Unrecognized format ${format}`); + } + const swapBR = format.startsWith('BGR'); + const result = new Uint8ClampedArray(width * height * 4); + yield frame.copyTo(result, computeVideoFrameParameters(image, x, y, width, height)); + if (swapBR) { + for (let i = 0; i < result.length; i += 4) { + const tmp = result[i]; + result[i] = result[i + 2]; + result[i + 2] = tmp; + } + } + return result; + } + finally { + frame.close(); + } + }); +} +let offscreenCanvas; +let offscreenCanvasContext; +/** + * Reads pixels from an ImageBitmap/Image/canvas using OffscreenCanvas + * + * @param data - image, imagebitmap, or canvas to parse + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred + */ +function readImageDataUsingOffscreenCanvas(imgBitmap, x, y, width, height) { + const origWidth = imgBitmap.width; + const origHeight = imgBitmap.height; + // Lazily initialize OffscreenCanvas + if (!offscreenCanvas || !offscreenCanvasContext) { + // Dem tiles are typically 256x256 + offscreenCanvas = new OffscreenCanvas(origWidth, origHeight); + offscreenCanvasContext = offscreenCanvas.getContext('2d', { willReadFrequently: true }); + } + offscreenCanvas.width = origWidth; + offscreenCanvas.height = origHeight; + offscreenCanvasContext.drawImage(imgBitmap, 0, 0, origWidth, origHeight); + const imgData = offscreenCanvasContext.getImageData(x, y, width, height); + offscreenCanvasContext.clearRect(0, 0, origWidth, origHeight); + return imgData.data; +} +/** + * Reads RGBA pixels from an preferring OffscreenCanvas, but falling back to VideoFrame if supported and + * the browser is mangling OffscreenCanvas getImageData results. + * + * @param data - image, imagebitmap, or canvas to parse + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns a promise containing the parsed RGBA pixel values of the image + */ +function getImageData(image, x, y, width, height) { + return __awaiter(this, void 0, void 0, function* () { + if (isOffscreenCanvasDistorted()) { + try { + return yield readImageUsingVideoFrame(image, x, y, width, height); + } + catch (e) { + // fall back to OffscreenCanvas + } + } + return readImageDataUsingOffscreenCanvas(image, x, y, width, height); + }); +} +/** + * This method is used in order to register an event listener using a lambda function. + * The return value will allow unsubscribing from the event, without the need to store the method reference. + * @param target - The target + * @param message - The message + * @param listener - The listener + * @param options - The options + * @returns a subscription object that can be used to unsubscribe from the event + */ +function subscribe(target, message, listener, options) { + target.addEventListener(message, listener, options); + return { + unsubscribe: () => { + target.removeEventListener(message, listener, options); + } + }; +} +/** + * This method converts degrees to radians. + * The return value is the radian value. + * @param degrees - The number of degrees + * @returns radians + */ +function degreesToRadians(degrees) { + return degrees * Math.PI / 180; +} +/** + * The maximum world tile zoom (Z). + * In other words, the upper bound supported for tile zoom. + */ +const MAX_TILE_ZOOM = 25; +/** + * The minimum world tile zoom (Z). + * In other words, the lower bound supported for tile zoom. + */ +const MIN_TILE_ZOOM = 0; + +/* +This file was copied from https://github.com/mapbox/grid-index and was +migrated from JavaScript to TypeScript. + +Copyright (c) 2016, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +*/ +const NUM_PARAMS = 3; +class TransferableGridIndex { + constructor(extent, n, padding) { + const cells = this.cells = []; + if (extent instanceof ArrayBuffer) { + this.arrayBuffer = extent; + const array = new Int32Array(this.arrayBuffer); + extent = array[0]; + n = array[1]; + padding = array[2]; + this.d = n + 2 * padding; + for (let k = 0; k < this.d * this.d; k++) { + const start = array[NUM_PARAMS + k]; + const end = array[NUM_PARAMS + k + 1]; + cells.push(start === end ? null : array.subarray(start, end)); + } + const keysOffset = array[NUM_PARAMS + cells.length]; + const bboxesOffset = array[NUM_PARAMS + cells.length + 1]; + this.keys = array.subarray(keysOffset, bboxesOffset); + this.bboxes = array.subarray(bboxesOffset); + this.insert = this._insertReadonly; + } + else { + this.d = n + 2 * padding; + for (let i = 0; i < this.d * this.d; i++) { + cells.push([]); + } + this.keys = []; + this.bboxes = []; + } + this.n = n; + this.extent = extent; + this.padding = padding; + this.scale = n / extent; + this.uid = 0; + const p = (padding / n) * extent; + this.min = -p; + this.max = extent + p; + } + insert(key, x1, y1, x2, y2) { + this._forEachCell(x1, y1, x2, y2, this._insertCell, this.uid++, undefined, undefined); + this.keys.push(key); + this.bboxes.push(x1); + this.bboxes.push(y1); + this.bboxes.push(x2); + this.bboxes.push(y2); + } + _insertReadonly() { + throw new Error('Cannot insert into a GridIndex created from an ArrayBuffer.'); + } + _insertCell(x1, y1, x2, y2, cellIndex, uid) { + this.cells[cellIndex].push(uid); + } + query(x1, y1, x2, y2, intersectionTest) { + const min = this.min; + const max = this.max; + if (x1 <= min && y1 <= min && max <= x2 && max <= y2 && !intersectionTest) { + // We use `Array#slice` because `this.keys` may be a `Int32Array` and + // some browsers (Safari and IE) do not support `TypedArray#slice` + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice#Browser_compatibility + return Array.prototype.slice.call(this.keys); + } + else { + const result = []; + const seenUids = {}; + this._forEachCell(x1, y1, x2, y2, this._queryCell, result, seenUids, intersectionTest); + return result; + } + } + _queryCell(x1, y1, x2, y2, cellIndex, result, seenUids, intersectionTest) { + const cell = this.cells[cellIndex]; + if (cell !== null) { + const keys = this.keys; + const bboxes = this.bboxes; + for (let u = 0; u < cell.length; u++) { + const uid = cell[u]; + if (seenUids[uid] === undefined) { + const offset = uid * 4; + if (intersectionTest ? + intersectionTest(bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) : + ((x1 <= bboxes[offset + 2]) && + (y1 <= bboxes[offset + 3]) && + (x2 >= bboxes[offset + 0]) && + (y2 >= bboxes[offset + 1]))) { + seenUids[uid] = true; + result.push(keys[uid]); + } + else { + seenUids[uid] = false; + } + } + } + } + } + _forEachCell(x1, y1, x2, y2, fn, arg1, arg2, intersectionTest) { + const cx1 = this._convertToCellCoord(x1); + const cy1 = this._convertToCellCoord(y1); + const cx2 = this._convertToCellCoord(x2); + const cy2 = this._convertToCellCoord(y2); + for (let x = cx1; x <= cx2; x++) { + for (let y = cy1; y <= cy2; y++) { + const cellIndex = this.d * y + x; + if (intersectionTest && !intersectionTest(this._convertFromCellCoord(x), this._convertFromCellCoord(y), this._convertFromCellCoord(x + 1), this._convertFromCellCoord(y + 1))) + continue; + if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, intersectionTest)) + return; + } + } + } + _convertFromCellCoord(x) { + return (x - this.padding) / this.scale; + } + _convertToCellCoord(x) { + return Math.max(0, Math.min(this.d - 1, Math.floor(x * this.scale) + this.padding)); + } + toArrayBuffer() { + if (this.arrayBuffer) + return this.arrayBuffer; + const cells = this.cells; + const metadataLength = NUM_PARAMS + this.cells.length + 1 + 1; + let totalCellLength = 0; + for (let i = 0; i < this.cells.length; i++) { + totalCellLength += this.cells[i].length; + } + const array = new Int32Array(metadataLength + totalCellLength + this.keys.length + this.bboxes.length); + array[0] = this.extent; + array[1] = this.n; + array[2] = this.padding; + let offset = metadataLength; + for (let k = 0; k < cells.length; k++) { + const cell = cells[k]; + array[NUM_PARAMS + k] = offset; + array.set(cell, offset); + offset += cell.length; + } + array[NUM_PARAMS + cells.length] = offset; + array.set(this.keys, offset); + offset += this.keys.length; + array[NUM_PARAMS + cells.length + 1] = offset; + array.set(this.bboxes, offset); + offset += this.bboxes.length; + return array.buffer; + } + static serialize(grid, transferables) { + const buffer = grid.toArrayBuffer(); + if (transferables) { + transferables.push(buffer); + } + return { buffer }; + } + static deserialize(serialized) { + return new TransferableGridIndex(serialized.buffer); + } +} + +var $version = 8; +var $root = { + version: { + required: true, + type: "enum", + values: [ + 8 + ] + }, + name: { + type: "string" + }, + metadata: { + type: "*" + }, + center: { + type: "array", + value: "number" + }, + zoom: { + type: "number" + }, + bearing: { + type: "number", + "default": 0, + period: 360, + units: "degrees" + }, + pitch: { + type: "number", + "default": 0, + units: "degrees" + }, + light: { + type: "light" + }, + sky: { + type: "sky" + }, + projection: { + type: "projection" + }, + terrain: { + type: "terrain" + }, + sources: { + required: true, + type: "sources" + }, + sprite: { + type: "sprite" + }, + glyphs: { + type: "string" + }, + transition: { + type: "transition" + }, + layers: { + required: true, + type: "array", + value: "layer" + } +}; +var sources = { + "*": { + type: "source" + } +}; +var source = [ + "source_vector", + "source_raster", + "source_raster_dem", + "source_geojson", + "source_video", + "source_image" +]; +var source_vector = { + type: { + required: true, + type: "enum", + values: { + vector: { + } + } + }, + url: { + type: "string" + }, + tiles: { + type: "array", + value: "string" + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ] + }, + scheme: { + type: "enum", + values: { + xyz: { + }, + tms: { + } + }, + "default": "xyz" + }, + minzoom: { + type: "number", + "default": 0 + }, + maxzoom: { + type: "number", + "default": 22 + }, + attribution: { + type: "string" + }, + promoteId: { + type: "promoteId" + }, + volatile: { + type: "boolean", + "default": false + }, + "*": { + type: "*" + } +}; +var source_raster = { + type: { + required: true, + type: "enum", + values: { + raster: { + } + } + }, + url: { + type: "string" + }, + tiles: { + type: "array", + value: "string" + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ] + }, + minzoom: { + type: "number", + "default": 0 + }, + maxzoom: { + type: "number", + "default": 22 + }, + tileSize: { + type: "number", + "default": 512, + units: "pixels" + }, + scheme: { + type: "enum", + values: { + xyz: { + }, + tms: { + } + }, + "default": "xyz" + }, + attribution: { + type: "string" + }, + volatile: { + type: "boolean", + "default": false + }, + "*": { + type: "*" + } +}; +var source_raster_dem = { + type: { + required: true, + type: "enum", + values: { + "raster-dem": { + } + } + }, + url: { + type: "string" + }, + tiles: { + type: "array", + value: "string" + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ] + }, + minzoom: { + type: "number", + "default": 0 + }, + maxzoom: { + type: "number", + "default": 22 + }, + tileSize: { + type: "number", + "default": 512, + units: "pixels" + }, + attribution: { + type: "string" + }, + encoding: { + type: "enum", + values: { + terrarium: { + }, + mapbox: { + }, + custom: { + } + }, + "default": "mapbox" + }, + redFactor: { + type: "number", + "default": 1 + }, + blueFactor: { + type: "number", + "default": 1 + }, + greenFactor: { + type: "number", + "default": 1 + }, + baseShift: { + type: "number", + "default": 0 + }, + volatile: { + type: "boolean", + "default": false + }, + "*": { + type: "*" + } +}; +var source_geojson = { + type: { + required: true, + type: "enum", + values: { + geojson: { + } + } + }, + data: { + required: true, + type: "*" + }, + maxzoom: { + type: "number", + "default": 18 + }, + attribution: { + type: "string" + }, + buffer: { + type: "number", + "default": 128, + maximum: 512, + minimum: 0 + }, + filter: { + type: "*" + }, + tolerance: { + type: "number", + "default": 0.375 + }, + cluster: { + type: "boolean", + "default": false + }, + clusterRadius: { + type: "number", + "default": 50, + minimum: 0 + }, + clusterMaxZoom: { + type: "number" + }, + clusterMinPoints: { + type: "number" + }, + clusterProperties: { + type: "*" + }, + lineMetrics: { + type: "boolean", + "default": false + }, + generateId: { + type: "boolean", + "default": false + }, + promoteId: { + type: "promoteId" + } +}; +var source_video = { + type: { + required: true, + type: "enum", + values: { + video: { + } + } + }, + urls: { + required: true, + type: "array", + value: "string" + }, + coordinates: { + required: true, + type: "array", + length: 4, + value: { + type: "array", + length: 2, + value: "number" + } + } +}; +var source_image = { + type: { + required: true, + type: "enum", + values: { + image: { + } + } + }, + url: { + required: true, + type: "string" + }, + coordinates: { + required: true, + type: "array", + length: 4, + value: { + type: "array", + length: 2, + value: "number" + } + } +}; +var layer = { + id: { + type: "string", + required: true + }, + type: { + type: "enum", + values: { + fill: { + }, + line: { + }, + symbol: { + }, + circle: { + }, + heatmap: { + }, + "fill-extrusion": { + }, + raster: { + }, + hillshade: { + }, + background: { + } + }, + required: true + }, + metadata: { + type: "*" + }, + source: { + type: "string" + }, + "source-layer": { + type: "string" + }, + minzoom: { + type: "number", + minimum: 0, + maximum: 24 + }, + maxzoom: { + type: "number", + minimum: 0, + maximum: 24 + }, + filter: { + type: "filter" + }, + layout: { + type: "layout" + }, + paint: { + type: "paint" + } +}; +var layout$7 = [ + "layout_fill", + "layout_line", + "layout_circle", + "layout_heatmap", + "layout_fill-extrusion", + "layout_symbol", + "layout_raster", + "layout_hillshade", + "layout_background" +]; +var layout_background = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_fill = { + "fill-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_circle = { + "circle-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_heatmap = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_line = { + "line-cap": { + type: "enum", + values: { + butt: { + }, + round: { + }, + square: { + } + }, + "default": "butt", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-join": { + type: "enum", + values: { + bevel: { + }, + round: { + }, + miter: { + } + }, + "default": "miter", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "line-miter-limit": { + type: "number", + "default": 2, + requires: [ + { + "line-join": "miter" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-round-limit": { + type: "number", + "default": 1.05, + requires: [ + { + "line-join": "round" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_symbol = { + "symbol-placement": { + type: "enum", + values: { + point: { + }, + line: { + }, + "line-center": { + } + }, + "default": "point", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-spacing": { + type: "number", + "default": 250, + minimum: 1, + units: "pixels", + requires: [ + { + "symbol-placement": "line" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-avoid-edges": { + type: "boolean", + "default": false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "symbol-z-order": { + type: "enum", + values: { + auto: { + }, + "viewport-y": { + }, + source: { + } + }, + "default": "auto", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-allow-overlap": { + type: "boolean", + "default": false, + requires: [ + "icon-image", + { + "!": "icon-overlap" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-overlap": { + type: "enum", + values: { + never: { + }, + always: { + }, + cooperative: { + } + }, + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-ignore-placement": { + type: "boolean", + "default": false, + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-optional": { + type: "boolean", + "default": false, + requires: [ + "icon-image", + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-rotation-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-size": { + type: "number", + "default": 1, + minimum: 0, + units: "factor of the original icon size", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-text-fit": { + type: "enum", + values: { + none: { + }, + width: { + }, + height: { + }, + both: { + } + }, + "default": "none", + requires: [ + "icon-image", + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-text-fit-padding": { + type: "array", + value: "number", + length: 4, + "default": [ + 0, + 0, + 0, + 0 + ], + units: "pixels", + requires: [ + "icon-image", + "text-field", + { + "icon-text-fit": [ + "both", + "width", + "height" + ] + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-image": { + type: "resolvedImage", + tokens: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-rotate": { + type: "number", + "default": 0, + period: 360, + units: "degrees", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-padding": { + type: "padding", + "default": [ + 2 + ], + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-keep-upright": { + type: "boolean", + "default": false, + requires: [ + "icon-image", + { + "icon-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-offset": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-anchor": { + type: "enum", + values: { + center: { + }, + left: { + }, + right: { + }, + top: { + }, + bottom: { + }, + "top-left": { + }, + "top-right": { + }, + "bottom-left": { + }, + "bottom-right": { + } + }, + "default": "center", + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-pitch-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-pitch-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotation-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + "viewport-glyph": { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-field": { + type: "formatted", + "default": "", + tokens: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-font": { + type: "array", + value: "string", + "default": [ + "Open Sans Regular", + "Arial Unicode MS Regular" + ], + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-size": { + type: "number", + "default": 16, + minimum: 0, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-width": { + type: "number", + "default": 10, + minimum: 0, + units: "ems", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-line-height": { + type: "number", + "default": 1.2, + units: "ems", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-letter-spacing": { + type: "number", + "default": 0, + units: "ems", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-justify": { + type: "enum", + values: { + auto: { + }, + left: { + }, + center: { + }, + right: { + } + }, + "default": "center", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-radial-offset": { + type: "number", + units: "ems", + "default": 0, + requires: [ + "text-field" + ], + "property-type": "data-driven", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + } + }, + "text-variable-anchor": { + type: "array", + value: "enum", + values: { + center: { + }, + left: { + }, + right: { + }, + top: { + }, + bottom: { + }, + "top-left": { + }, + "top-right": { + }, + "bottom-left": { + }, + "bottom-right": { + } + }, + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-variable-anchor-offset": { + type: "variableAnchorOffsetCollection", + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-anchor": { + type: "enum", + values: { + center: { + }, + left: { + }, + right: { + }, + top: { + }, + bottom: { + }, + "top-left": { + }, + "top-right": { + }, + "bottom-left": { + }, + "bottom-right": { + } + }, + "default": "center", + requires: [ + "text-field", + { + "!": "text-variable-anchor" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-angle": { + type: "number", + "default": 45, + units: "degrees", + requires: [ + "text-field", + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-writing-mode": { + type: "array", + value: "enum", + values: { + horizontal: { + }, + vertical: { + } + }, + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotate": { + type: "number", + "default": 0, + period: 360, + units: "degrees", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-padding": { + type: "number", + "default": 2, + minimum: 0, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-keep-upright": { + type: "boolean", + "default": true, + requires: [ + "text-field", + { + "text-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-transform": { + type: "enum", + values: { + none: { + }, + uppercase: { + }, + lowercase: { + } + }, + "default": "none", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-offset": { + type: "array", + value: "number", + units: "ems", + length: 2, + "default": [ + 0, + 0 + ], + requires: [ + "text-field", + { + "!": "text-radial-offset" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-allow-overlap": { + type: "boolean", + "default": false, + requires: [ + "text-field", + { + "!": "text-overlap" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-overlap": { + type: "enum", + values: { + never: { + }, + always: { + }, + cooperative: { + } + }, + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-ignore-placement": { + type: "boolean", + "default": false, + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-optional": { + type: "boolean", + "default": false, + requires: [ + "text-field", + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_raster = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_hillshade = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var filter = { + type: "array", + value: "*" +}; +var filter_operator = { + type: "enum", + values: { + "==": { + }, + "!=": { + }, + ">": { + }, + ">=": { + }, + "<": { + }, + "<=": { + }, + "in": { + }, + "!in": { + }, + all: { + }, + any: { + }, + none: { + }, + has: { + }, + "!has": { + } + } +}; +var geometry_type = { + type: "enum", + values: { + Point: { + }, + LineString: { + }, + Polygon: { + } + } +}; +var function_stop = { + type: "array", + minimum: 0, + maximum: 24, + value: [ + "number", + "color" + ], + length: 2 +}; +var expression$1 = { + type: "array", + value: "*", + minimum: 1 +}; +var light = { + anchor: { + type: "enum", + "default": "viewport", + values: { + map: { + }, + viewport: { + } + }, + "property-type": "data-constant", + transition: false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + } + }, + position: { + type: "array", + "default": [ + 1.15, + 210, + 30 + ], + length: 3, + value: "number", + "property-type": "data-constant", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + } + }, + color: { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + intensity: { + type: "number", + "property-type": "data-constant", + "default": 0.5, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + } +}; +var sky = { + "sky-color": { + type: "color", + "property-type": "data-constant", + "default": "#88C6FC", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "horizon-color": { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "fog-color": { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "fog-ground-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.5, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "horizon-fog-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.8, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "sky-horizon-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.8, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "atmosphere-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.8, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + } +}; +var terrain = { + source: { + type: "string", + required: true + }, + exaggeration: { + type: "number", + minimum: 0, + "default": 1 + } +}; +var projection$1 = { + type: { + type: "enum", + "default": "mercator", + values: { + mercator: { + }, + globe: { + } + } + } +}; +var paint$9 = [ + "paint_fill", + "paint_line", + "paint_circle", + "paint_heatmap", + "paint_fill-extrusion", + "paint_symbol", + "paint_raster", + "paint_hillshade", + "paint_background" +]; +var paint_fill = { + "fill-antialias": { + type: "boolean", + "default": true, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "fill-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-outline-color": { + type: "color", + transition: true, + requires: [ + { + "!": "fill-pattern" + }, + { + "fill-antialias": true + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "fill-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + } +}; +var paint_line = { + "line-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "line-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "line-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-width": { + type: "number", + "default": 1, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-gap-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-offset": { + type: "number", + "default": 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-dasharray": { + type: "array", + value: "number", + minimum: 0, + transition: true, + units: "line widths", + requires: [ + { + "!": "line-pattern" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "line-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "line-gradient": { + type: "color", + transition: false, + requires: [ + { + "!": "line-dasharray" + }, + { + "!": "line-pattern" + }, + { + source: "geojson", + has: { + lineMetrics: true + } + } + ], + expression: { + interpolated: true, + parameters: [ + "line-progress" + ] + }, + "property-type": "color-ramp" + } +}; +var paint_circle = { + "circle-radius": { + type: "number", + "default": 5, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-blur": { + type: "number", + "default": 0, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "circle-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-scale": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "viewport", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-stroke-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + } +}; +var paint_heatmap = { + "heatmap-radius": { + type: "number", + "default": 30, + minimum: 1, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-weight": { + type: "number", + "default": 1, + minimum: 0, + transition: false, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-intensity": { + type: "number", + "default": 1, + minimum: 0, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "heatmap-color": { + type: "color", + "default": [ + "interpolate", + [ + "linear" + ], + [ + "heatmap-density" + ], + 0, + "rgba(0, 0, 255, 0)", + 0.1, + "royalblue", + 0.3, + "cyan", + 0.5, + "lime", + 0.7, + "yellow", + 1, + "red" + ], + transition: false, + expression: { + interpolated: true, + parameters: [ + "heatmap-density" + ] + }, + "property-type": "color-ramp" + }, + "heatmap-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_symbol = { + "icon-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-color": { + type: "color", + "default": "rgba(0, 0, 0, 0)", + transition: true, + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "icon-image", + "icon-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-color": { + type: "color", + "default": "#000000", + transition: true, + overridable: true, + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-color": { + type: "color", + "default": "rgba(0, 0, 0, 0)", + transition: true, + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "text-field", + "text-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_raster = { + "raster-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-hue-rotate": { + type: "number", + "default": 0, + period: 360, + transition: true, + units: "degrees", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-min": { + type: "number", + "default": 0, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-max": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-saturation": { + type: "number", + "default": 0, + minimum: -1, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-contrast": { + type: "number", + "default": 0, + minimum: -1, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-resampling": { + type: "enum", + values: { + linear: { + }, + nearest: { + } + }, + "default": "linear", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-fade-duration": { + type: "number", + "default": 300, + minimum: 0, + transition: false, + units: "milliseconds", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_hillshade = { + "hillshade-illumination-direction": { + type: "number", + "default": 335, + minimum: 0, + maximum: 359, + transition: false, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-illumination-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "viewport", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-exaggeration": { + type: "number", + "default": 0.5, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-shadow-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-highlight-color": { + type: "color", + "default": "#FFFFFF", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-accent-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_background = { + "background-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "background-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "background-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "background-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var transition = { + duration: { + type: "number", + "default": 300, + minimum: 0, + units: "milliseconds" + }, + delay: { + type: "number", + "default": 0, + minimum: 0, + units: "milliseconds" + } +}; +var promoteId = { + "*": { + type: "string" + } +}; +var v8Spec = { + $version: $version, + $root: $root, + sources: sources, + source: source, + source_vector: source_vector, + source_raster: source_raster, + source_raster_dem: source_raster_dem, + source_geojson: source_geojson, + source_video: source_video, + source_image: source_image, + layer: layer, + layout: layout$7, + layout_background: layout_background, + layout_fill: layout_fill, + layout_circle: layout_circle, + layout_heatmap: layout_heatmap, + "layout_fill-extrusion": { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}, + layout_line: layout_line, + layout_symbol: layout_symbol, + layout_raster: layout_raster, + layout_hillshade: layout_hillshade, + filter: filter, + filter_operator: filter_operator, + geometry_type: geometry_type, + "function": { + expression: { + type: "expression" + }, + stops: { + type: "array", + value: "function_stop" + }, + base: { + type: "number", + "default": 1, + minimum: 0 + }, + property: { + type: "string", + "default": "$zoom" + }, + type: { + type: "enum", + values: { + identity: { + }, + exponential: { + }, + interval: { + }, + categorical: { + } + }, + "default": "exponential" + }, + colorSpace: { + type: "enum", + values: { + rgb: { + }, + lab: { + }, + hcl: { + } + }, + "default": "rgb" + }, + "default": { + type: "*", + required: false + } +}, + function_stop: function_stop, + expression: expression$1, + light: light, + sky: sky, + terrain: terrain, + projection: projection$1, + paint: paint$9, + paint_fill: paint_fill, + "paint_fill-extrusion": { + "fill-extrusion-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "fill-extrusion-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "fill-extrusion-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "fill-extrusion-height": { + type: "number", + "default": 0, + minimum: 0, + units: "meters", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-base": { + type: "number", + "default": 0, + minimum: 0, + units: "meters", + transition: true, + requires: [ + "fill-extrusion-height" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-vertical-gradient": { + type: "boolean", + "default": true, + transition: false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}, + paint_line: paint_line, + paint_circle: paint_circle, + paint_heatmap: paint_heatmap, + paint_symbol: paint_symbol, + paint_raster: paint_raster, + paint_hillshade: paint_hillshade, + paint_background: paint_background, + transition: transition, + "property-type": { + "data-driven": { + type: "property-type" + }, + "cross-faded": { + type: "property-type" + }, + "cross-faded-data-driven": { + type: "property-type" + }, + "color-ramp": { + type: "property-type" + }, + "data-constant": { + type: "property-type" + }, + constant: { + type: "property-type" + } +}, + promoteId: promoteId +}; + +const refProperties = ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout']; + +function deref(layer, parent) { + const result = {}; + for (const k in layer) { + if (k !== 'ref') { + result[k] = layer[k]; + } + } + refProperties.forEach((k) => { + if (k in parent) { + result[k] = parent[k]; + } + }); + return result; +} +/** + * Given an array of layers, some of which may contain `ref` properties + * whose value is the `id` of another property, return a new array where + * such layers have been augmented with the 'type', 'source', etc. properties + * from the parent layer, and the `ref` property has been removed. + * + * The input is not modified. The output may contain references to portions + * of the input. + * + * @private + * @param {Array} layers + * @returns {Array} + */ +function derefLayers(layers) { + layers = layers.slice(); + const map = Object.create(null); + for (let i = 0; i < layers.length; i++) { + map[layers[i].id] = layers[i]; + } + for (let i = 0; i < layers.length; i++) { + if ('ref' in layers[i]) { + layers[i] = deref(layers[i], map[layers[i].ref]); + } + } + return layers; +} + +/** + * Deeply compares two object literals. + * + * @private + */ +function deepEqual(a, b) { + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) { + if (!deepEqual(a[i], b[i])) + return false; + } + return true; + } + if (typeof a === 'object' && a !== null && b !== null) { + if (!(typeof b === 'object')) + return false; + const keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) + return false; + for (const key in a) { + if (!deepEqual(a[key], b[key])) + return false; + } + return true; + } + return a === b; +} + +/** + * The main reason for this method is to allow type check when adding a command to the array. + * @param commands - The commands array to add to + * @param command - The command to add + */ +function addCommand(commands, command) { + commands.push(command); +} +function addSource(sourceId, after, commands) { + addCommand(commands, { command: 'addSource', args: [sourceId, after[sourceId]] }); +} +function removeSource(sourceId, commands, sourcesRemoved) { + addCommand(commands, { command: 'removeSource', args: [sourceId] }); + sourcesRemoved[sourceId] = true; +} +function updateSource(sourceId, after, commands, sourcesRemoved) { + removeSource(sourceId, commands, sourcesRemoved); + addSource(sourceId, after, commands); +} +function canUpdateGeoJSON(before, after, sourceId) { + let prop; + for (prop in before[sourceId]) { + if (!Object.prototype.hasOwnProperty.call(before[sourceId], prop)) + continue; + if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + for (prop in after[sourceId]) { + if (!Object.prototype.hasOwnProperty.call(after[sourceId], prop)) + continue; + if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + return true; +} +function diffSources(before, after, commands, sourcesRemoved) { + before = before || {}; + after = after || {}; + let sourceId; + // look for sources to remove + for (sourceId in before) { + if (!Object.prototype.hasOwnProperty.call(before, sourceId)) + continue; + if (!Object.prototype.hasOwnProperty.call(after, sourceId)) { + removeSource(sourceId, commands, sourcesRemoved); + } + } + // look for sources to add/update + for (sourceId in after) { + if (!Object.prototype.hasOwnProperty.call(after, sourceId)) + continue; + if (!Object.prototype.hasOwnProperty.call(before, sourceId)) { + addSource(sourceId, after, commands); + } + else if (!deepEqual(before[sourceId], after[sourceId])) { + if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) { + addCommand(commands, { command: 'setGeoJSONSourceData', args: [sourceId, after[sourceId].data] }); + } + else { + // no update command, must remove then add + updateSource(sourceId, after, commands, sourcesRemoved); + } + } + } +} +function diffLayerPropertyChanges(before, after, commands, layerId, klass, command) { + before = before || {}; + after = after || {}; + for (const prop in before) { + if (!Object.prototype.hasOwnProperty.call(before, prop)) + continue; + if (!deepEqual(before[prop], after[prop])) { + commands.push({ command, args: [layerId, prop, after[prop], klass] }); + } + } + for (const prop in after) { + if (!Object.prototype.hasOwnProperty.call(after, prop) || Object.prototype.hasOwnProperty.call(before, prop)) + continue; + if (!deepEqual(before[prop], after[prop])) { + commands.push({ command, args: [layerId, prop, after[prop], klass] }); + } + } +} +function pluckId(layer) { + return layer.id; +} +function indexById(group, layer) { + group[layer.id] = layer; + return group; +} +function diffLayers(before, after, commands) { + before = before || []; + after = after || []; + // order of layers by id + const beforeOrder = before.map(pluckId); + const afterOrder = after.map(pluckId); + // index of layer by id + const beforeIndex = before.reduce(indexById, {}); + const afterIndex = after.reduce(indexById, {}); + // track order of layers as if they have been mutated + const tracker = beforeOrder.slice(); + // layers that have been added do not need to be diffed + const clean = Object.create(null); + let layerId; + let beforeLayer; + let afterLayer; + let insertBeforeLayerId; + let prop; + // remove layers + for (let i = 0, d = 0; i < beforeOrder.length; i++) { + layerId = beforeOrder[i]; + if (!Object.prototype.hasOwnProperty.call(afterIndex, layerId)) { + addCommand(commands, { command: 'removeLayer', args: [layerId] }); + tracker.splice(tracker.indexOf(layerId, d), 1); + } + else { + // limit where in tracker we need to look for a match + d++; + } + } + // add/reorder layers + for (let i = 0, d = 0; i < afterOrder.length; i++) { + // work backwards as insert is before an existing layer + layerId = afterOrder[afterOrder.length - 1 - i]; + if (tracker[tracker.length - 1 - i] === layerId) + continue; + if (Object.prototype.hasOwnProperty.call(beforeIndex, layerId)) { + // remove the layer before we insert at the correct position + addCommand(commands, { command: 'removeLayer', args: [layerId] }); + tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1); + } + else { + // limit where in tracker we need to look for a match + d++; + } + // add layer at correct position + insertBeforeLayerId = tracker[tracker.length - i]; + addCommand(commands, { command: 'addLayer', args: [afterIndex[layerId], insertBeforeLayerId] }); + tracker.splice(tracker.length - i, 0, layerId); + clean[layerId] = true; + } + // update layers + for (let i = 0; i < afterOrder.length; i++) { + layerId = afterOrder[i]; + beforeLayer = beforeIndex[layerId]; + afterLayer = afterIndex[layerId]; + // no need to update if previously added (new or moved) + if (clean[layerId] || deepEqual(beforeLayer, afterLayer)) + continue; + // If source, source-layer, or type have changes, then remove the layer + // and add it back 'from scratch'. + if (!deepEqual(beforeLayer.source, afterLayer.source) || !deepEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !deepEqual(beforeLayer.type, afterLayer.type)) { + addCommand(commands, { command: 'removeLayer', args: [layerId] }); + // we add the layer back at the same position it was already in, so + // there's no need to update the `tracker` + insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1]; + addCommand(commands, { command: 'addLayer', args: [afterLayer, insertBeforeLayerId] }); + continue; + } + // layout, paint, filter, minzoom, maxzoom + diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, 'setLayoutProperty'); + diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, 'setPaintProperty'); + if (!deepEqual(beforeLayer.filter, afterLayer.filter)) { + addCommand(commands, { command: 'setFilter', args: [layerId, afterLayer.filter] }); + } + if (!deepEqual(beforeLayer.minzoom, afterLayer.minzoom) || !deepEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) { + addCommand(commands, { command: 'setLayerZoomRange', args: [layerId, afterLayer.minzoom, afterLayer.maxzoom] }); + } + // handle all other layer props, including paint.* + for (prop in beforeLayer) { + if (!Object.prototype.hasOwnProperty.call(beforeLayer, prop)) + continue; + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || + prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') + continue; + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), 'setPaintProperty'); + } + else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) { + addCommand(commands, { command: 'setLayerProperty', args: [layerId, prop, afterLayer[prop]] }); + } + } + for (prop in afterLayer) { + if (!Object.prototype.hasOwnProperty.call(afterLayer, prop) || Object.prototype.hasOwnProperty.call(beforeLayer, prop)) + continue; + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || + prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') + continue; + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), 'setPaintProperty'); + } + else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) { + addCommand(commands, { command: 'setLayerProperty', args: [layerId, prop, afterLayer[prop]] }); + } + } + } +} +/** + * Diff two stylesheet + * + * Creates semanticly aware diffs that can easily be applied at runtime. + * Operations produced by the diff closely resemble the maplibre-gl-js API. Any + * error creating the diff will fall back to the 'setStyle' operation. + * + * Example diff: + * [ + * { command: 'setConstant', args: ['@water', '#0000FF'] }, + * { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] } + * ] + * + * @private + * @param {*} [before] stylesheet to compare from + * @param {*} after stylesheet to compare to + * @returns Array list of changes + */ +function diffStyles(before, after) { + if (!before) + return [{ command: 'setStyle', args: [after] }]; + let commands = []; + try { + // Handle changes to top-level properties + if (!deepEqual(before.version, after.version)) { + return [{ command: 'setStyle', args: [after] }]; + } + if (!deepEqual(before.center, after.center)) { + commands.push({ command: 'setCenter', args: [after.center] }); + } + if (!deepEqual(before.zoom, after.zoom)) { + commands.push({ command: 'setZoom', args: [after.zoom] }); + } + if (!deepEqual(before.bearing, after.bearing)) { + commands.push({ command: 'setBearing', args: [after.bearing] }); + } + if (!deepEqual(before.pitch, after.pitch)) { + commands.push({ command: 'setPitch', args: [after.pitch] }); + } + if (!deepEqual(before.sprite, after.sprite)) { + commands.push({ command: 'setSprite', args: [after.sprite] }); + } + if (!deepEqual(before.glyphs, after.glyphs)) { + commands.push({ command: 'setGlyphs', args: [after.glyphs] }); + } + if (!deepEqual(before.transition, after.transition)) { + commands.push({ command: 'setTransition', args: [after.transition] }); + } + if (!deepEqual(before.light, after.light)) { + commands.push({ command: 'setLight', args: [after.light] }); + } + if (!deepEqual(before.terrain, after.terrain)) { + commands.push({ command: 'setTerrain', args: [after.terrain] }); + } + if (!deepEqual(before.sky, after.sky)) { + commands.push({ command: 'setSky', args: [after.sky] }); + } + if (!deepEqual(before.projection, after.projection)) { + commands.push({ command: 'setProjection', args: [after.projection] }); + } + // Handle changes to `sources` + // If a source is to be removed, we also--before the removeSource + // command--need to remove all the style layers that depend on it. + const sourcesRemoved = {}; + // First collect the {add,remove}Source commands + const removeOrAddSourceCommands = []; + diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved); + // Push a removeLayer command for each style layer that depends on a + // source that's being removed. + // Also, exclude any such layers them from the input to `diffLayers` + // below, so that diffLayers produces the appropriate `addLayers` + // command + const beforeLayers = []; + if (before.layers) { + before.layers.forEach((layer) => { + if ('source' in layer && sourcesRemoved[layer.source]) { + commands.push({ command: 'removeLayer', args: [layer.id] }); + } + else { + beforeLayers.push(layer); + } + }); + } + commands = commands.concat(removeOrAddSourceCommands); + // Handle changes to `layers` + diffLayers(beforeLayers, after.layers, commands); + } + catch (e) { + // fall back to setStyle + console.warn('Unable to compute style diff:', e); + commands = [{ command: 'setStyle', args: [after] }]; + } + return commands; +} + +// Note: Do not inherit from Error. It breaks when transpiling to ES5. +class ValidationError { + constructor(key, value, message, identifier) { + this.message = (key ? `${key}: ` : '') + message; + if (identifier) + this.identifier = identifier; + if (value !== null && value !== undefined && value.__line__) { + this.line = value.__line__; + } + } +} + +// Note: Do not inherit from Error. It breaks when transpiling to ES5. +class ParsingError { + constructor(error) { + this.error = error; + this.message = error.message; + const match = error.message.match(/line (\d+)/); + this.line = match ? parseInt(match[1], 10) : 0; + } +} + +function extendBy(output, ...inputs) { + for (const input of inputs) { + for (const k in input) { + output[k] = input[k]; + } + } + return output; +} + +class ExpressionParsingError extends Error { + constructor(key, message) { + super(message); + this.message = message; + this.key = key; + } +} + +/** + * Tracks `let` bindings during expression parsing. + * @private + */ +class Scope { + constructor(parent, bindings = []) { + this.parent = parent; + this.bindings = {}; + for (const [name, expression] of bindings) { + this.bindings[name] = expression; + } + } + concat(bindings) { + return new Scope(this, bindings); + } + get(name) { + if (this.bindings[name]) { + return this.bindings[name]; + } + if (this.parent) { + return this.parent.get(name); + } + throw new Error(`${name} not found in scope.`); + } + has(name) { + if (this.bindings[name]) + return true; + return this.parent ? this.parent.has(name) : false; + } +} + +const NullType = { kind: 'null' }; +const NumberType = { kind: 'number' }; +const StringType = { kind: 'string' }; +const BooleanType = { kind: 'boolean' }; +const ColorType = { kind: 'color' }; +const ObjectType = { kind: 'object' }; +const ValueType = { kind: 'value' }; +const ErrorType = { kind: 'error' }; +const CollatorType = { kind: 'collator' }; +const FormattedType = { kind: 'formatted' }; +const PaddingType = { kind: 'padding' }; +const ResolvedImageType = { kind: 'resolvedImage' }; +const VariableAnchorOffsetCollectionType = { kind: 'variableAnchorOffsetCollection' }; +function array$1(itemType, N) { + return { + kind: 'array', + itemType, + N + }; +} +function toString$1(type) { + if (type.kind === 'array') { + const itemType = toString$1(type.itemType); + return typeof type.N === 'number' ? + `array<${itemType}, ${type.N}>` : + type.itemType.kind === 'value' ? 'array' : `array<${itemType}>`; + } + else { + return type.kind; + } +} +const valueMemberTypes = [ + NullType, + NumberType, + StringType, + BooleanType, + ColorType, + FormattedType, + ObjectType, + array$1(ValueType), + PaddingType, + ResolvedImageType, + VariableAnchorOffsetCollectionType +]; +/** + * Returns null if `t` is a subtype of `expected`; otherwise returns an + * error message. + * @private + */ +function checkSubtype(expected, t) { + if (t.kind === 'error') { + // Error is a subtype of every type + return null; + } + else if (expected.kind === 'array') { + if (t.kind === 'array' && + ((t.N === 0 && t.itemType.kind === 'value') || !checkSubtype(expected.itemType, t.itemType)) && + (typeof expected.N !== 'number' || expected.N === t.N)) { + return null; + } + } + else if (expected.kind === t.kind) { + return null; + } + else if (expected.kind === 'value') { + for (const memberType of valueMemberTypes) { + if (!checkSubtype(memberType, t)) { + return null; + } + } + } + return `Expected ${toString$1(expected)} but found ${toString$1(t)} instead.`; +} +function isValidType(provided, allowedTypes) { + return allowedTypes.some(t => t.kind === provided.kind); +} +function isValidNativeType(provided, allowedTypes) { + return allowedTypes.some(t => { + if (t === 'null') { + return provided === null; + } + else if (t === 'array') { + return Array.isArray(provided); + } + else if (t === 'object') { + return provided && !Array.isArray(provided) && typeof provided === 'object'; + } + else { + return t === typeof provided; + } + }); +} +/** + * Verify whether the specified type is of the same type as the specified sample. + * + * @param provided Type to verify + * @param sample Sample type to reference + * @returns `true` if both objects are of the same type, `false` otherwise + * @example basic types + * if (verifyType(outputType, ValueType)) { + * // type narrowed to: + * outputType.kind; // 'value' + * } + * @example array types + * if (verifyType(outputType, array(NumberType))) { + * // type narrowed to: + * outputType.kind; // 'array' + * outputType.itemType; // NumberTypeT + * outputType.itemType.kind; // 'number' + * } + */ +function verifyType(provided, sample) { + if (provided.kind === 'array' && sample.kind === 'array') { + return provided.itemType.kind === sample.itemType.kind && typeof provided.N === 'number'; + } + return provided.kind === sample.kind; +} + +// See https://observablehq.com/@mbostock/lab-and-rgb +const Xn = 0.96422, Yn = 1, Zn = 0.82521, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1, deg2rad = Math.PI / 180, rad2deg = 180 / Math.PI; +function constrainAngle(angle) { + angle = angle % 360; + if (angle < 0) { + angle += 360; + } + return angle; +} +function rgbToLab([r, g, b, alpha]) { + r = rgb2xyz(r); + g = rgb2xyz(g); + b = rgb2xyz(b); + let x, z; + const y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn); + if (r === g && g === b) { + x = z = y; + } + else { + x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn); + z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn); + } + const l = 116 * y - 16; + return [(l < 0) ? 0 : l, 500 * (x - y), 200 * (y - z), alpha]; +} +function rgb2xyz(x) { + return (x <= 0.04045) ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); +} +function xyz2lab(t) { + return (t > t3) ? Math.pow(t, 1 / 3) : t / t2 + t0; +} +function labToRgb([l, a, b, alpha]) { + let y = (l + 16) / 116, x = isNaN(a) ? y : y + a / 500, z = isNaN(b) ? y : y - b / 200; + y = Yn * lab2xyz(y); + x = Xn * lab2xyz(x); + z = Zn * lab2xyz(z); + return [ + xyz2rgb(3.1338561 * x - 1.6168667 * y - 0.4906146 * z), // D50 -> sRGB + xyz2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z), + xyz2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z), + alpha, + ]; +} +function xyz2rgb(x) { + x = (x <= 0.00304) ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055; + return (x < 0) ? 0 : (x > 1) ? 1 : x; // clip to 0..1 range +} +function lab2xyz(t) { + return (t > t1) ? t * t * t : t2 * (t - t0); +} +function rgbToHcl(rgbColor) { + const [l, a, b, alpha] = rgbToLab(rgbColor); + const c = Math.sqrt(a * a + b * b); + const h = Math.round(c * 10000) ? constrainAngle(Math.atan2(b, a) * rad2deg) : NaN; + return [h, c, l, alpha]; +} +function hclToRgb([h, c, l, alpha]) { + h = isNaN(h) ? 0 : h * deg2rad; + return labToRgb([l, Math.cos(h) * c, Math.sin(h) * c, alpha]); +} +// https://drafts.csswg.org/css-color-4/#hsl-to-rgb +function hslToRgb([h, s, l, alpha]) { + h = constrainAngle(h); + s /= 100; + l /= 100; + function f(n) { + const k = (n + h / 30) % 12; + const a = s * Math.min(l, 1 - l); + return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); + } + return [f(0), f(8), f(4), alpha]; +} + +/** + * CSS color parser compliant with CSS Color 4 Specification. + * Supports: named colors, `transparent` keyword, all rgb hex notations, + * rgb(), rgba(), hsl() and hsla() functions. + * Does not round the parsed values to integers from the range 0..255. + * + * Syntax: + * + * = | + * = | + * + * rgb() = rgb( {3} [ / ]? ) | rgb( {3} [ / ]? ) + * rgb() = rgb( #{3} , ? ) | rgb( #{3} , ? ) + * + * hsl() = hsl( [ / ]? ) + * hsl() = hsl( , , , ? ) + * + * Caveats: + * - - with optional `deg` suffix; `grad`, `rad`, `turn` are not supported + * - `none` keyword is not supported + * - comments inside rgb()/hsl() are not supported + * - legacy color syntax rgba() is supported with an identical grammar and behavior to rgb() + * - legacy color syntax hsla() is supported with an identical grammar and behavior to hsl() + * + * @param input CSS color string to parse. + * @returns Color in sRGB color space, with `red`, `green`, `blue` + * and `alpha` channels normalized to the range 0..1, + * or `undefined` if the input is not a valid color string. + */ +function parseCssColor(input) { + input = input.toLowerCase().trim(); + if (input === 'transparent') { + return [0, 0, 0, 0]; + } + // 'white', 'black', 'blue' + const namedColorsMatch = namedColors[input]; + if (namedColorsMatch) { + const [r, g, b] = namedColorsMatch; + return [r / 255, g / 255, b / 255, 1]; + } + // #f0c, #f0cf, #ff00cc, #ff00ccff + if (input.startsWith('#')) { + const hexRegexp = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/; + if (hexRegexp.test(input)) { + const step = input.length < 6 ? 1 : 2; + let i = 1; + return [ + parseHex(input.slice(i, i += step)), + parseHex(input.slice(i, i += step)), + parseHex(input.slice(i, i += step)), + parseHex(input.slice(i, i + step) || 'ff'), + ]; + } + } + // rgb(128 0 0), rgb(50% 0% 0%), rgba(255,0,255,0.6), rgb(255 0 255 / 60%), rgb(100% 0% 100% /.6) + if (input.startsWith('rgb')) { + const rgbRegExp = /^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/; + const rgbMatch = input.match(rgbRegExp); + if (rgbMatch) { + const [_, // eslint-disable-line @typescript-eslint/no-unused-vars + r, // + rp, // % (optional) + f1, // , (optional) + g, // + gp, // % (optional) + f2, // , (optional) + b, // + bp, // % (optional) + f3, // ,|/ (optional) + a, // (optional) + ap, // % (optional) + ] = rgbMatch; + const argFormat = [f1 || ' ', f2 || ' ', f3].join(''); + if (argFormat === ' ' || + argFormat === ' /' || + argFormat === ',,' || + argFormat === ',,,') { + const valFormat = [rp, gp, bp].join(''); + const maxValue = (valFormat === '%%%') ? 100 : + (valFormat === '') ? 255 : 0; + if (maxValue) { + const rgba = [ + clamp(+r / maxValue, 0, 1), + clamp(+g / maxValue, 0, 1), + clamp(+b / maxValue, 0, 1), + a ? parseAlpha(+a, ap) : 1, + ]; + if (validateNumbers(rgba)) { + return rgba; + } + // invalid numbers + } + // values must be all numbers or all percentages + } + return; // comma optional syntax requires no commas at all + } + } + // hsl(120 50% 80%), hsla(120deg,50%,80%,.9), hsl(12e1 50% 80% / 90%) + const hslRegExp = /^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/; + const hslMatch = input.match(hslRegExp); + if (hslMatch) { + const [_, // eslint-disable-line @typescript-eslint/no-unused-vars + h, // + f1, // , (optional) + s, // + f2, // , (optional) + l, // + f3, // ,|/ (optional) + a, // (optional) + ap, // % (optional) + ] = hslMatch; + const argFormat = [f1 || ' ', f2 || ' ', f3].join(''); + if (argFormat === ' ' || + argFormat === ' /' || + argFormat === ',,' || + argFormat === ',,,') { + const hsla = [ + +h, + clamp(+s, 0, 100), + clamp(+l, 0, 100), + a ? parseAlpha(+a, ap) : 1, + ]; + if (validateNumbers(hsla)) { + return hslToRgb(hsla); + } + // invalid numbers + } + // comma optional syntax requires no commas at all + } +} +function parseHex(hex) { + return parseInt(hex.padEnd(2, hex), 16) / 255; +} +function parseAlpha(a, asPercentage) { + return clamp(asPercentage ? (a / 100) : a, 0, 1); +} +function clamp(n, min, max) { + return Math.min(Math.max(min, n), max); +} +/** + * The regular expression for numeric values is not super specific, and it may + * happen that it will accept a value that is not a valid number. In order to + * detect and eliminate such values this function exists. + * + * @param array Array of uncertain numbers. + * @returns `true` if the specified array contains only valid numbers, `false` otherwise. + */ +function validateNumbers(array) { + return !array.some(Number.isNaN); +} +/** + * To generate: + * - visit {@link https://www.w3.org/TR/css-color-4/#named-colors} + * - run in the console: + * @example + * copy(`{\n${[...document.querySelector('.named-color-table tbody').children].map((tr) => `${tr.cells[2].textContent.trim()}: [${tr.cells[4].textContent.trim().split(/\s+/).join(', ')}],`).join('\n')}\n}`); + */ +const namedColors = { + aliceblue: [240, 248, 255], + antiquewhite: [250, 235, 215], + aqua: [0, 255, 255], + aquamarine: [127, 255, 212], + azure: [240, 255, 255], + beige: [245, 245, 220], + bisque: [255, 228, 196], + black: [0, 0, 0], + blanchedalmond: [255, 235, 205], + blue: [0, 0, 255], + blueviolet: [138, 43, 226], + brown: [165, 42, 42], + burlywood: [222, 184, 135], + cadetblue: [95, 158, 160], + chartreuse: [127, 255, 0], + chocolate: [210, 105, 30], + coral: [255, 127, 80], + cornflowerblue: [100, 149, 237], + cornsilk: [255, 248, 220], + crimson: [220, 20, 60], + cyan: [0, 255, 255], + darkblue: [0, 0, 139], + darkcyan: [0, 139, 139], + darkgoldenrod: [184, 134, 11], + darkgray: [169, 169, 169], + darkgreen: [0, 100, 0], + darkgrey: [169, 169, 169], + darkkhaki: [189, 183, 107], + darkmagenta: [139, 0, 139], + darkolivegreen: [85, 107, 47], + darkorange: [255, 140, 0], + darkorchid: [153, 50, 204], + darkred: [139, 0, 0], + darksalmon: [233, 150, 122], + darkseagreen: [143, 188, 143], + darkslateblue: [72, 61, 139], + darkslategray: [47, 79, 79], + darkslategrey: [47, 79, 79], + darkturquoise: [0, 206, 209], + darkviolet: [148, 0, 211], + deeppink: [255, 20, 147], + deepskyblue: [0, 191, 255], + dimgray: [105, 105, 105], + dimgrey: [105, 105, 105], + dodgerblue: [30, 144, 255], + firebrick: [178, 34, 34], + floralwhite: [255, 250, 240], + forestgreen: [34, 139, 34], + fuchsia: [255, 0, 255], + gainsboro: [220, 220, 220], + ghostwhite: [248, 248, 255], + gold: [255, 215, 0], + goldenrod: [218, 165, 32], + gray: [128, 128, 128], + green: [0, 128, 0], + greenyellow: [173, 255, 47], + grey: [128, 128, 128], + honeydew: [240, 255, 240], + hotpink: [255, 105, 180], + indianred: [205, 92, 92], + indigo: [75, 0, 130], + ivory: [255, 255, 240], + khaki: [240, 230, 140], + lavender: [230, 230, 250], + lavenderblush: [255, 240, 245], + lawngreen: [124, 252, 0], + lemonchiffon: [255, 250, 205], + lightblue: [173, 216, 230], + lightcoral: [240, 128, 128], + lightcyan: [224, 255, 255], + lightgoldenrodyellow: [250, 250, 210], + lightgray: [211, 211, 211], + lightgreen: [144, 238, 144], + lightgrey: [211, 211, 211], + lightpink: [255, 182, 193], + lightsalmon: [255, 160, 122], + lightseagreen: [32, 178, 170], + lightskyblue: [135, 206, 250], + lightslategray: [119, 136, 153], + lightslategrey: [119, 136, 153], + lightsteelblue: [176, 196, 222], + lightyellow: [255, 255, 224], + lime: [0, 255, 0], + limegreen: [50, 205, 50], + linen: [250, 240, 230], + magenta: [255, 0, 255], + maroon: [128, 0, 0], + mediumaquamarine: [102, 205, 170], + mediumblue: [0, 0, 205], + mediumorchid: [186, 85, 211], + mediumpurple: [147, 112, 219], + mediumseagreen: [60, 179, 113], + mediumslateblue: [123, 104, 238], + mediumspringgreen: [0, 250, 154], + mediumturquoise: [72, 209, 204], + mediumvioletred: [199, 21, 133], + midnightblue: [25, 25, 112], + mintcream: [245, 255, 250], + mistyrose: [255, 228, 225], + moccasin: [255, 228, 181], + navajowhite: [255, 222, 173], + navy: [0, 0, 128], + oldlace: [253, 245, 230], + olive: [128, 128, 0], + olivedrab: [107, 142, 35], + orange: [255, 165, 0], + orangered: [255, 69, 0], + orchid: [218, 112, 214], + palegoldenrod: [238, 232, 170], + palegreen: [152, 251, 152], + paleturquoise: [175, 238, 238], + palevioletred: [219, 112, 147], + papayawhip: [255, 239, 213], + peachpuff: [255, 218, 185], + peru: [205, 133, 63], + pink: [255, 192, 203], + plum: [221, 160, 221], + powderblue: [176, 224, 230], + purple: [128, 0, 128], + rebeccapurple: [102, 51, 153], + red: [255, 0, 0], + rosybrown: [188, 143, 143], + royalblue: [65, 105, 225], + saddlebrown: [139, 69, 19], + salmon: [250, 128, 114], + sandybrown: [244, 164, 96], + seagreen: [46, 139, 87], + seashell: [255, 245, 238], + sienna: [160, 82, 45], + silver: [192, 192, 192], + skyblue: [135, 206, 235], + slateblue: [106, 90, 205], + slategray: [112, 128, 144], + slategrey: [112, 128, 144], + snow: [255, 250, 250], + springgreen: [0, 255, 127], + steelblue: [70, 130, 180], + tan: [210, 180, 140], + teal: [0, 128, 128], + thistle: [216, 191, 216], + tomato: [255, 99, 71], + turquoise: [64, 224, 208], + violet: [238, 130, 238], + wheat: [245, 222, 179], + white: [255, 255, 255], + whitesmoke: [245, 245, 245], + yellow: [255, 255, 0], + yellowgreen: [154, 205, 50], +}; + +/** + * Color representation used by WebGL. + * Defined in sRGB color space and pre-blended with alpha. + * @private + */ +class Color { + /** + * @param r Red component premultiplied by `alpha` 0..1 + * @param g Green component premultiplied by `alpha` 0..1 + * @param b Blue component premultiplied by `alpha` 0..1 + * @param [alpha=1] Alpha component 0..1 + * @param [premultiplied=true] Whether the `r`, `g` and `b` values have already + * been multiplied by alpha. If `true` nothing happens if `false` then they will + * be multiplied automatically. + */ + constructor(r, g, b, alpha = 1, premultiplied = true) { + this.r = r; + this.g = g; + this.b = b; + this.a = alpha; + if (!premultiplied) { + this.r *= alpha; + this.g *= alpha; + this.b *= alpha; + if (!alpha) { + // alpha = 0 erases completely rgb channels. This behavior is not desirable + // if this particular color is later used in color interpolation. + // Because of that, a reference to original color is saved. + this.overwriteGetter('rgb', [r, g, b, alpha]); + } + } + } + /** + * Parses CSS color strings and converts colors to sRGB color space if needed. + * Officially supported color formats: + * - keyword, e.g. 'aquamarine' or 'steelblue' + * - hex (with 3, 4, 6 or 8 digits), e.g. '#f0f' or '#e9bebea9' + * - rgb and rgba, e.g. 'rgb(0,240,120)' or 'rgba(0%,94%,47%,0.1)' or 'rgb(0 240 120 / .3)' + * - hsl and hsla, e.g. 'hsl(0,0%,83%)' or 'hsla(0,0%,83%,.5)' or 'hsl(0 0% 83% / 20%)' + * + * @param input CSS color string to parse. + * @returns A `Color` instance, or `undefined` if the input is not a valid color string. + */ + static parse(input) { + // in zoom-and-property function input could be an instance of Color class + if (input instanceof Color) { + return input; + } + if (typeof input !== 'string') { + return; + } + const rgba = parseCssColor(input); + if (rgba) { + return new Color(...rgba, false); + } + } + /** + * Used in color interpolation and by 'to-rgba' expression. + * + * @returns Gien color, with reversed alpha blending, in sRGB color space. + */ + get rgb() { + const { r, g, b, a } = this; + const f = a || Infinity; // reverse alpha blending factor + return this.overwriteGetter('rgb', [r / f, g / f, b / f, a]); + } + /** + * Used in color interpolation. + * + * @returns Gien color, with reversed alpha blending, in HCL color space. + */ + get hcl() { + return this.overwriteGetter('hcl', rgbToHcl(this.rgb)); + } + /** + * Used in color interpolation. + * + * @returns Gien color, with reversed alpha blending, in LAB color space. + */ + get lab() { + return this.overwriteGetter('lab', rgbToLab(this.rgb)); + } + /** + * Lazy getter pattern. When getter is called for the first time lazy value + * is calculated and then overwrites getter function in given object instance. + * + * @example: + * const redColor = Color.parse('red'); + * let x = redColor.hcl; // this will invoke `get hcl()`, which will calculate + * // the value of red in HCL space and invoke this `overwriteGetter` function + * // which in turn will set a field with a key 'hcl' in the `redColor` object. + * // In other words it will override `get hcl()` from its `Color` prototype + * // with its own property: hcl = [calculated red value in hcl]. + * let y = redColor.hcl; // next call will no longer invoke getter but simply + * // return the previously calculated value + * x === y; // true - `x` is exactly the same object as `y` + * + * @param getterKey Getter key + * @param lazyValue Lazily calculated value to be memoized by current instance + * @private + */ + overwriteGetter(getterKey, lazyValue) { + Object.defineProperty(this, getterKey, { value: lazyValue }); + return lazyValue; + } + /** + * Used by 'to-string' expression. + * + * @returns Serialized color in format `rgba(r,g,b,a)` + * where r,g,b are numbers within 0..255 and alpha is number within 1..0 + * + * @example + * var purple = new Color.parse('purple'); + * purple.toString; // = "rgba(128,0,128,1)" + * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)'); + * translucentGreen.toString(); // = "rgba(26,207,26,0.73)" + */ + toString() { + const [r, g, b, a] = this.rgb; + return `rgba(${[r, g, b].map(n => Math.round(n * 255)).join(',')},${a})`; + } +} +Color.black = new Color(0, 0, 0, 1); +Color.white = new Color(1, 1, 1, 1); +Color.transparent = new Color(0, 0, 0, 0); +Color.red = new Color(1, 0, 0, 1); + +// Flow type declarations for Intl cribbed from +// https://github.com/facebook/flow/issues/1270 +class Collator { + constructor(caseSensitive, diacriticSensitive, locale) { + if (caseSensitive) + this.sensitivity = diacriticSensitive ? 'variant' : 'case'; + else + this.sensitivity = diacriticSensitive ? 'accent' : 'base'; + this.locale = locale; + this.collator = new Intl.Collator(this.locale ? this.locale : [], { sensitivity: this.sensitivity, usage: 'search' }); + } + compare(lhs, rhs) { + return this.collator.compare(lhs, rhs); + } + resolvedLocale() { + // We create a Collator without "usage: search" because we don't want + // the search options encoded in our result (e.g. "en-u-co-search") + return new Intl.Collator(this.locale ? this.locale : []) + .resolvedOptions().locale; + } +} + +class FormattedSection { + constructor(text, image, scale, fontStack, textColor) { + this.text = text; + this.image = image; + this.scale = scale; + this.fontStack = fontStack; + this.textColor = textColor; + } +} +class Formatted { + constructor(sections) { + this.sections = sections; + } + static fromString(unformatted) { + return new Formatted([new FormattedSection(unformatted, null, null, null, null)]); + } + isEmpty() { + if (this.sections.length === 0) + return true; + return !this.sections.some(section => section.text.length !== 0 || + (section.image && section.image.name.length !== 0)); + } + static factory(text) { + if (text instanceof Formatted) { + return text; + } + else { + return Formatted.fromString(text); + } + } + toString() { + if (this.sections.length === 0) + return ''; + return this.sections.map(section => section.text).join(''); + } +} + +/** + * A set of four numbers representing padding around a box. Create instances from + * bare arrays or numeric values using the static method `Padding.parse`. + * @private + */ +class Padding { + constructor(values) { + this.values = values.slice(); + } + /** + * Numeric padding values + * @param input A padding value + * @returns A `Padding` instance, or `undefined` if the input is not a valid padding value. + */ + static parse(input) { + if (input instanceof Padding) { + return input; + } + // Backwards compatibility: bare number is treated the same as array with single value. + // Padding applies to all four sides. + if (typeof input === 'number') { + return new Padding([input, input, input, input]); + } + if (!Array.isArray(input)) { + return undefined; + } + if (input.length < 1 || input.length > 4) { + return undefined; + } + for (const val of input) { + if (typeof val !== 'number') { + return undefined; + } + } + // Expand shortcut properties into explicit 4-sided values + switch (input.length) { + case 1: + input = [input[0], input[0], input[0], input[0]]; + break; + case 2: + input = [input[0], input[1], input[0], input[1]]; + break; + case 3: + input = [input[0], input[1], input[2], input[1]]; + break; + } + return new Padding(input); + } + toString() { + return JSON.stringify(this.values); + } +} + +/** Set of valid anchor positions, as a set for validation */ +const anchors = new Set(['center', 'left', 'right', 'top', 'bottom', 'top-left', 'top-right', 'bottom-left', 'bottom-right']); +/** + * Utility class to assist managing values for text-variable-anchor-offset property. Create instances from + * bare arrays using the static method `VariableAnchorOffsetCollection.parse`. + * @private + */ +class VariableAnchorOffsetCollection { + constructor(values) { + this.values = values.slice(); + } + static parse(input) { + if (input instanceof VariableAnchorOffsetCollection) { + return input; + } + if (!Array.isArray(input) || + input.length < 1 || + input.length % 2 !== 0) { + return undefined; + } + for (let i = 0; i < input.length; i += 2) { + // Elements in even positions should be anchor positions; Elements in odd positions should be offset values + const anchorValue = input[i]; + const offsetValue = input[i + 1]; + if (typeof anchorValue !== 'string' || !anchors.has(anchorValue)) { + return undefined; + } + if (!Array.isArray(offsetValue) || offsetValue.length !== 2 || typeof offsetValue[0] !== 'number' || typeof offsetValue[1] !== 'number') { + return undefined; + } + } + return new VariableAnchorOffsetCollection(input); + } + toString() { + return JSON.stringify(this.values); + } +} + +class ResolvedImage { + constructor(options) { + this.name = options.name; + this.available = options.available; + } + toString() { + return this.name; + } + static fromString(name) { + if (!name) + return null; // treat empty values as no image + return new ResolvedImage({ name, available: false }); + } +} + +function validateRGBA(r, g, b, a) { + if (!(typeof r === 'number' && r >= 0 && r <= 255 && + typeof g === 'number' && g >= 0 && g <= 255 && + typeof b === 'number' && b >= 0 && b <= 255)) { + const value = typeof a === 'number' ? [r, g, b, a] : [r, g, b]; + return `Invalid rgba value [${value.join(', ')}]: 'r', 'g', and 'b' must be between 0 and 255.`; + } + if (!(typeof a === 'undefined' || (typeof a === 'number' && a >= 0 && a <= 1))) { + return `Invalid rgba value [${[r, g, b, a].join(', ')}]: 'a' must be between 0 and 1.`; + } + return null; +} +function isValue(mixed) { + if (mixed === null || + typeof mixed === 'string' || + typeof mixed === 'boolean' || + typeof mixed === 'number' || + mixed instanceof Color || + mixed instanceof Collator || + mixed instanceof Formatted || + mixed instanceof Padding || + mixed instanceof VariableAnchorOffsetCollection || + mixed instanceof ResolvedImage) { + return true; + } + else if (Array.isArray(mixed)) { + for (const item of mixed) { + if (!isValue(item)) { + return false; + } + } + return true; + } + else if (typeof mixed === 'object') { + for (const key in mixed) { + if (!isValue(mixed[key])) { + return false; + } + } + return true; + } + else { + return false; + } +} +function typeOf(value) { + if (value === null) { + return NullType; + } + else if (typeof value === 'string') { + return StringType; + } + else if (typeof value === 'boolean') { + return BooleanType; + } + else if (typeof value === 'number') { + return NumberType; + } + else if (value instanceof Color) { + return ColorType; + } + else if (value instanceof Collator) { + return CollatorType; + } + else if (value instanceof Formatted) { + return FormattedType; + } + else if (value instanceof Padding) { + return PaddingType; + } + else if (value instanceof VariableAnchorOffsetCollection) { + return VariableAnchorOffsetCollectionType; + } + else if (value instanceof ResolvedImage) { + return ResolvedImageType; + } + else if (Array.isArray(value)) { + const length = value.length; + let itemType; + for (const item of value) { + const t = typeOf(item); + if (!itemType) { + itemType = t; + } + else if (itemType === t) { + continue; + } + else { + itemType = ValueType; + break; + } + } + return array$1(itemType || ValueType, length); + } + else { + return ObjectType; + } +} +function toString(value) { + const type = typeof value; + if (value === null) { + return ''; + } + else if (type === 'string' || type === 'number' || type === 'boolean') { + return String(value); + } + else if (value instanceof Color || value instanceof Formatted || value instanceof Padding || value instanceof VariableAnchorOffsetCollection || value instanceof ResolvedImage) { + return value.toString(); + } + else { + return JSON.stringify(value); + } +} + +class Literal { + constructor(type, value) { + this.type = type; + this.value = value; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (!isValue(args[1])) + return context.error('invalid value'); + const value = args[1]; + let type = typeOf(value); + // special case: infer the item type if possible for zero-length arrays + const expected = context.expectedType; + if (type.kind === 'array' && + type.N === 0 && + expected && + expected.kind === 'array' && + (typeof expected.N !== 'number' || expected.N === 0)) { + type = expected; + } + return new Literal(type, value); + } + evaluate() { + return this.value; + } + eachChild() { } + outputDefined() { + return true; + } +} + +class RuntimeError { + constructor(message) { + this.name = 'ExpressionEvaluationError'; + this.message = message; + } + toJSON() { + return this.message; + } +} + +const types$1 = { + string: StringType, + number: NumberType, + boolean: BooleanType, + object: ObjectType +}; +class Assertion { + constructor(type, args) { + this.type = type; + this.args = args; + } + static parse(args, context) { + if (args.length < 2) + return context.error('Expected at least one argument.'); + let i = 1; + let type; + const name = args[0]; + if (name === 'array') { + let itemType; + if (args.length > 2) { + const type = args[1]; + if (typeof type !== 'string' || !(type in types$1) || type === 'object') + return context.error('The item type argument of "array" must be one of string, number, boolean', 1); + itemType = types$1[type]; + i++; + } + else { + itemType = ValueType; + } + let N; + if (args.length > 3) { + if (args[2] !== null && + (typeof args[2] !== 'number' || + args[2] < 0 || + args[2] !== Math.floor(args[2]))) { + return context.error('The length argument to "array" must be a positive integer literal', 2); + } + N = args[2]; + i++; + } + type = array$1(itemType, N); + } + else { + if (!types$1[name]) + throw new Error(`Types doesn't contain name = ${name}`); + type = types$1[name]; + } + const parsed = []; + for (; i < args.length; i++) { + const input = context.parse(args[i], i, ValueType); + if (!input) + return null; + parsed.push(input); + } + return new Assertion(type, parsed); + } + evaluate(ctx) { + for (let i = 0; i < this.args.length; i++) { + const value = this.args[i].evaluate(ctx); + const error = checkSubtype(this.type, typeOf(value)); + if (!error) { + return value; + } + else if (i === this.args.length - 1) { + throw new RuntimeError(`Expected value to be of type ${toString$1(this.type)}, but found ${toString$1(typeOf(value))} instead.`); + } + } + throw new Error(); + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return this.args.every(arg => arg.outputDefined()); + } +} + +const types = { + 'to-boolean': BooleanType, + 'to-color': ColorType, + 'to-number': NumberType, + 'to-string': StringType +}; +/** + * Special form for error-coalescing coercion expressions "to-number", + * "to-color". Since these coercions can fail at runtime, they accept multiple + * arguments, only evaluating one at a time until one succeeds. + * + * @private + */ +class Coercion { + constructor(type, args) { + this.type = type; + this.args = args; + } + static parse(args, context) { + if (args.length < 2) + return context.error('Expected at least one argument.'); + const name = args[0]; + if (!types[name]) + throw new Error(`Can't parse ${name} as it is not part of the known types`); + if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2) + return context.error('Expected one argument.'); + const type = types[name]; + const parsed = []; + for (let i = 1; i < args.length; i++) { + const input = context.parse(args[i], i, ValueType); + if (!input) + return null; + parsed.push(input); + } + return new Coercion(type, parsed); + } + evaluate(ctx) { + switch (this.type.kind) { + case 'boolean': + return Boolean(this.args[0].evaluate(ctx)); + case 'color': { + let input; + let error; + for (const arg of this.args) { + input = arg.evaluate(ctx); + error = null; + if (input instanceof Color) { + return input; + } + else if (typeof input === 'string') { + const c = ctx.parseColor(input); + if (c) + return c; + } + else if (Array.isArray(input)) { + if (input.length < 3 || input.length > 4) { + error = `Invalid rbga value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`; + } + else { + error = validateRGBA(input[0], input[1], input[2], input[3]); + } + if (!error) { + return new Color(input[0] / 255, input[1] / 255, input[2] / 255, input[3]); + } + } + } + throw new RuntimeError(error || `Could not parse color from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`); + } + case 'padding': { + let input; + for (const arg of this.args) { + input = arg.evaluate(ctx); + const pad = Padding.parse(input); + if (pad) { + return pad; + } + } + throw new RuntimeError(`Could not parse padding from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`); + } + case 'variableAnchorOffsetCollection': { + let input; + for (const arg of this.args) { + input = arg.evaluate(ctx); + const coll = VariableAnchorOffsetCollection.parse(input); + if (coll) { + return coll; + } + } + throw new RuntimeError(`Could not parse variableAnchorOffsetCollection from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`); + } + case 'number': { + let value = null; + for (const arg of this.args) { + value = arg.evaluate(ctx); + if (value === null) + return 0; + const num = Number(value); + if (isNaN(num)) + continue; + return num; + } + throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`); + } + case 'formatted': + // There is no explicit 'to-formatted' but this coercion can be implicitly + // created by properties that expect the 'formatted' type. + return Formatted.fromString(toString(this.args[0].evaluate(ctx))); + case 'resolvedImage': + return ResolvedImage.fromString(toString(this.args[0].evaluate(ctx))); + default: + return toString(this.args[0].evaluate(ctx)); + } + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return this.args.every(arg => arg.outputDefined()); + } +} + +const geometryTypes = ['Unknown', 'Point', 'LineString', 'Polygon']; +class EvaluationContext { + constructor() { + this.globals = null; + this.feature = null; + this.featureState = null; + this.formattedSection = null; + this._parseColorCache = {}; + this.availableImages = null; + this.canonical = null; + } + id() { + return this.feature && 'id' in this.feature ? this.feature.id : null; + } + geometryType() { + return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null; + } + geometry() { + return this.feature && 'geometry' in this.feature ? this.feature.geometry : null; + } + canonicalID() { + return this.canonical; + } + properties() { + return this.feature && this.feature.properties || {}; + } + parseColor(input) { + let cached = this._parseColorCache[input]; + if (!cached) { + cached = this._parseColorCache[input] = Color.parse(input); + } + return cached; + } +} + +/** + * State associated parsing at a given point in an expression tree. + * @private + */ +class ParsingContext { + constructor(registry, isConstantFunc, path = [], expectedType, scope = new Scope(), errors = []) { + this.registry = registry; + this.path = path; + this.key = path.map(part => `[${part}]`).join(''); + this.scope = scope; + this.errors = errors; + this.expectedType = expectedType; + this._isConstant = isConstantFunc; + } + /** + * @param expr the JSON expression to parse + * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed + * @param options + * @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. + * @private + */ + parse(expr, index, expectedType, bindings, options = {}) { + if (index) { + return this.concat(index, expectedType, bindings)._parse(expr, options); + } + return this._parse(expr, options); + } + _parse(expr, options) { + if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') { + expr = ['literal', expr]; + } + function annotate(parsed, type, typeAnnotation) { + if (typeAnnotation === 'assert') { + return new Assertion(type, [parsed]); + } + else if (typeAnnotation === 'coerce') { + return new Coercion(type, [parsed]); + } + else { + return parsed; + } + } + if (Array.isArray(expr)) { + if (expr.length === 0) { + return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].'); + } + const op = expr[0]; + if (typeof op !== 'string') { + this.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use ["literal", [...]].`, 0); + return null; + } + const Expr = this.registry[op]; + if (Expr) { + let parsed = Expr.parse(expr, this); + if (!parsed) + return null; + if (this.expectedType) { + const expected = this.expectedType; + const actual = parsed.type; + // When we expect a number, string, boolean, or array but have a value, wrap it in an assertion. + // When we expect a color or formatted string, but have a string or value, wrap it in a coercion. + // Otherwise, we do static type-checking. + // + // These behaviors are overridable for: + // * The "coalesce" operator, which needs to omit type annotations. + // * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion. + // + if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') { + parsed = annotate(parsed, expected, options.typeAnnotation || 'assert'); + } + else if ((expected.kind === 'color' || expected.kind === 'formatted' || expected.kind === 'resolvedImage') && (actual.kind === 'value' || actual.kind === 'string')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } + else if (expected.kind === 'padding' && (actual.kind === 'value' || actual.kind === 'number' || actual.kind === 'array')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } + else if (expected.kind === 'variableAnchorOffsetCollection' && (actual.kind === 'value' || actual.kind === 'array')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } + else if (this.checkSubtype(expected, actual)) { + return null; + } + } + // If an expression's arguments are all literals, we can evaluate + // it immediately and replace it with a literal value in the + // parsed/compiled result. Expressions that expect an image should + // not be resolved here so we can later get the available images. + if (!(parsed instanceof Literal) && (parsed.type.kind !== 'resolvedImage') && this._isConstant(parsed)) { + const ec = new EvaluationContext(); + try { + parsed = new Literal(parsed.type, parsed.evaluate(ec)); + } + catch (e) { + this.error(e.message); + return null; + } + } + return parsed; + } + return this.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); + } + else if (typeof expr === 'undefined') { + return this.error('\'undefined\' value invalid. Use null instead.'); + } + else if (typeof expr === 'object') { + return this.error('Bare objects invalid. Use ["literal", {...}] instead.'); + } + else { + return this.error(`Expected an array, but found ${typeof expr} instead.`); + } + } + /** + * Returns a copy of this context suitable for parsing the subexpression at + * index `index`, optionally appending to 'let' binding map. + * + * Note that `errors` property, intended for collecting errors while + * parsing, is copied by reference rather than cloned. + * @private + */ + concat(index, expectedType, bindings) { + const path = typeof index === 'number' ? this.path.concat(index) : this.path; + const scope = bindings ? this.scope.concat(bindings) : this.scope; + return new ParsingContext(this.registry, this._isConstant, path, expectedType || null, scope, this.errors); + } + /** + * Push a parsing (or type checking) error into the `this.errors` + * @param error The message + * @param keys Optionally specify the source of the error at a child + * of the current expression at `this.key`. + * @private + */ + error(error, ...keys) { + const key = `${this.key}${keys.map(k => `[${k}]`).join('')}`; + this.errors.push(new ExpressionParsingError(key, error)); + } + /** + * Returns null if `t` is a subtype of `expected`; otherwise returns an + * error message and also pushes it to `this.errors`. + * @param expected The expected type + * @param t The actual type + * @returns null if `t` is a subtype of `expected`; otherwise returns an error message + */ + checkSubtype(expected, t) { + const error = checkSubtype(expected, t); + if (error) + this.error(error); + return error; + } +} + +class Let { + constructor(bindings, result) { + this.type = result.type; + this.bindings = [].concat(bindings); + this.result = result; + } + evaluate(ctx) { + return this.result.evaluate(ctx); + } + eachChild(fn) { + for (const binding of this.bindings) { + fn(binding[1]); + } + fn(this.result); + } + static parse(args, context) { + if (args.length < 4) + return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`); + const bindings = []; + for (let i = 1; i < args.length - 1; i += 2) { + const name = args[i]; + if (typeof name !== 'string') { + return context.error(`Expected string, but found ${typeof name} instead.`, i); + } + if (/[^a-zA-Z0-9_]/.test(name)) { + return context.error('Variable names must contain only alphanumeric characters or \'_\'.', i); + } + const value = context.parse(args[i + 1], i + 1); + if (!value) + return null; + bindings.push([name, value]); + } + const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings); + if (!result) + return null; + return new Let(bindings, result); + } + outputDefined() { + return this.result.outputDefined(); + } +} + +class Var { + constructor(name, boundExpression) { + this.type = boundExpression.type; + this.name = name; + this.boundExpression = boundExpression; + } + static parse(args, context) { + if (args.length !== 2 || typeof args[1] !== 'string') + return context.error('\'var\' expression requires exactly one string literal argument.'); + const name = args[1]; + if (!context.scope.has(name)) { + return context.error(`Unknown variable "${name}". Make sure "${name}" has been bound in an enclosing "let" expression before using it.`, 1); + } + return new Var(name, context.scope.get(name)); + } + evaluate(ctx) { + return this.boundExpression.evaluate(ctx); + } + eachChild() { } + outputDefined() { + return false; + } +} + +class At { + constructor(type, index, input) { + this.type = type; + this.index = index; + this.input = input; + } + static parse(args, context) { + if (args.length !== 3) + return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); + const index = context.parse(args[1], 1, NumberType); + const input = context.parse(args[2], 2, array$1(context.expectedType || ValueType)); + if (!index || !input) + return null; + const t = input.type; + return new At(t.itemType, index, input); + } + evaluate(ctx) { + const index = this.index.evaluate(ctx); + const array = this.input.evaluate(ctx); + if (index < 0) { + throw new RuntimeError(`Array index out of bounds: ${index} < 0.`); + } + if (index >= array.length) { + throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`); + } + if (index !== Math.floor(index)) { + throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`); + } + return array[index]; + } + eachChild(fn) { + fn(this.index); + fn(this.input); + } + outputDefined() { + return false; + } +} + +class In { + constructor(needle, haystack) { + this.type = BooleanType; + this.needle = needle; + this.haystack = haystack; + } + static parse(args, context) { + if (args.length !== 3) { + return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); + } + const needle = context.parse(args[1], 1, ValueType); + const haystack = context.parse(args[2], 2, ValueType); + if (!needle || !haystack) + return null; + if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) { + return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(needle.type)} instead`); + } + return new In(needle, haystack); + } + evaluate(ctx) { + const needle = this.needle.evaluate(ctx); + const haystack = this.haystack.evaluate(ctx); + if (!haystack) + return false; + if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) { + throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(typeOf(needle))} instead.`); + } + if (!isValidNativeType(haystack, ['string', 'array'])) { + throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString$1(typeOf(haystack))} instead.`); + } + return haystack.indexOf(needle) >= 0; + } + eachChild(fn) { + fn(this.needle); + fn(this.haystack); + } + outputDefined() { + return true; + } +} + +class IndexOf { + constructor(needle, haystack, fromIndex) { + this.type = NumberType; + this.needle = needle; + this.haystack = haystack; + this.fromIndex = fromIndex; + } + static parse(args, context) { + if (args.length <= 2 || args.length >= 5) { + return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`); + } + const needle = context.parse(args[1], 1, ValueType); + const haystack = context.parse(args[2], 2, ValueType); + if (!needle || !haystack) + return null; + if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) { + return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(needle.type)} instead`); + } + if (args.length === 4) { + const fromIndex = context.parse(args[3], 3, NumberType); + if (!fromIndex) + return null; + return new IndexOf(needle, haystack, fromIndex); + } + else { + return new IndexOf(needle, haystack); + } + } + evaluate(ctx) { + const needle = this.needle.evaluate(ctx); + const haystack = this.haystack.evaluate(ctx); + if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) { + throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(typeOf(needle))} instead.`); + } + let fromIndex; + if (this.fromIndex) { + fromIndex = this.fromIndex.evaluate(ctx); + } + if (isValidNativeType(haystack, ['string'])) { + const rawIndex = haystack.indexOf(needle, fromIndex); + if (rawIndex === -1) { + return -1; + } + else { + // The index may be affected by surrogate pairs, so get the length of the preceding substring. + return [...haystack.slice(0, rawIndex)].length; + } + } + else if (isValidNativeType(haystack, ['array'])) { + return haystack.indexOf(needle, fromIndex); + } + else { + throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString$1(typeOf(haystack))} instead.`); + } + } + eachChild(fn) { + fn(this.needle); + fn(this.haystack); + if (this.fromIndex) { + fn(this.fromIndex); + } + } + outputDefined() { + return false; + } +} + +class Match { + constructor(inputType, outputType, input, cases, outputs, otherwise) { + this.inputType = inputType; + this.type = outputType; + this.input = input; + this.cases = cases; + this.outputs = outputs; + this.otherwise = otherwise; + } + static parse(args, context) { + if (args.length < 5) + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + if (args.length % 2 !== 1) + return context.error('Expected an even number of arguments.'); + let inputType; + let outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + const cases = {}; + const outputs = []; + for (let i = 2; i < args.length - 1; i += 2) { + let labels = args[i]; + const value = args[i + 1]; + if (!Array.isArray(labels)) { + labels = [labels]; + } + const labelContext = context.concat(i); + if (labels.length === 0) { + return labelContext.error('Expected at least one branch label.'); + } + for (const label of labels) { + if (typeof label !== 'number' && typeof label !== 'string') { + return labelContext.error('Branch labels must be numbers or strings.'); + } + else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) { + return labelContext.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`); + } + else if (typeof label === 'number' && Math.floor(label) !== label) { + return labelContext.error('Numeric branch labels must be integer values.'); + } + else if (!inputType) { + inputType = typeOf(label); + } + else if (labelContext.checkSubtype(inputType, typeOf(label))) { + return null; + } + if (typeof cases[String(label)] !== 'undefined') { + return labelContext.error('Branch labels must be unique.'); + } + cases[String(label)] = outputs.length; + } + const result = context.parse(value, i, outputType); + if (!result) + return null; + outputType = outputType || result.type; + outputs.push(result); + } + const input = context.parse(args[1], 1, ValueType); + if (!input) + return null; + const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) + return null; + if (input.type.kind !== 'value' && context.concat(1).checkSubtype(inputType, input.type)) { + return null; + } + return new Match(inputType, outputType, input, cases, outputs, otherwise); + } + evaluate(ctx) { + const input = this.input.evaluate(ctx); + const output = (typeOf(input) === this.inputType && this.outputs[this.cases[input]]) || this.otherwise; + return output.evaluate(ctx); + } + eachChild(fn) { + fn(this.input); + this.outputs.forEach(fn); + fn(this.otherwise); + } + outputDefined() { + return this.outputs.every(out => out.outputDefined()) && this.otherwise.outputDefined(); + } +} + +class Case { + constructor(type, branches, otherwise) { + this.type = type; + this.branches = branches; + this.otherwise = otherwise; + } + static parse(args, context) { + if (args.length < 4) + return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`); + if (args.length % 2 !== 0) + return context.error('Expected an odd number of arguments.'); + let outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + const branches = []; + for (let i = 1; i < args.length - 1; i += 2) { + const test = context.parse(args[i], i, BooleanType); + if (!test) + return null; + const result = context.parse(args[i + 1], i + 1, outputType); + if (!result) + return null; + branches.push([test, result]); + outputType = outputType || result.type; + } + const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) + return null; + if (!outputType) + throw new Error('Can\'t infer output type'); + return new Case(outputType, branches, otherwise); + } + evaluate(ctx) { + for (const [test, expression] of this.branches) { + if (test.evaluate(ctx)) { + return expression.evaluate(ctx); + } + } + return this.otherwise.evaluate(ctx); + } + eachChild(fn) { + for (const [test, expression] of this.branches) { + fn(test); + fn(expression); + } + fn(this.otherwise); + } + outputDefined() { + return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined(); + } +} + +class Slice { + constructor(type, input, beginIndex, endIndex) { + this.type = type; + this.input = input; + this.beginIndex = beginIndex; + this.endIndex = endIndex; + } + static parse(args, context) { + if (args.length <= 2 || args.length >= 5) { + return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`); + } + const input = context.parse(args[1], 1, ValueType); + const beginIndex = context.parse(args[2], 2, NumberType); + if (!input || !beginIndex) + return null; + if (!isValidType(input.type, [array$1(ValueType), StringType, ValueType])) { + return context.error(`Expected first argument to be of type array or string, but found ${toString$1(input.type)} instead`); + } + if (args.length === 4) { + const endIndex = context.parse(args[3], 3, NumberType); + if (!endIndex) + return null; + return new Slice(input.type, input, beginIndex, endIndex); + } + else { + return new Slice(input.type, input, beginIndex); + } + } + evaluate(ctx) { + const input = this.input.evaluate(ctx); + const beginIndex = this.beginIndex.evaluate(ctx); + let endIndex; + if (this.endIndex) { + endIndex = this.endIndex.evaluate(ctx); + } + if (isValidNativeType(input, ['string'])) { + // Indices may be affected by surrogate pairs. + return [...input].slice(beginIndex, endIndex).join(''); + } + else if (isValidNativeType(input, ['array'])) { + return input.slice(beginIndex, endIndex); + } + else { + throw new RuntimeError(`Expected first argument to be of type array or string, but found ${toString$1(typeOf(input))} instead.`); + } + } + eachChild(fn) { + fn(this.input); + fn(this.beginIndex); + if (this.endIndex) { + fn(this.endIndex); + } + } + outputDefined() { + return false; + } +} + +/** + * Returns the index of the last stop <= input, or 0 if it doesn't exist. + * @private + */ +function findStopLessThanOrEqualTo(stops, input) { + const lastIndex = stops.length - 1; + let lowerIndex = 0; + let upperIndex = lastIndex; + let currentIndex = 0; + let currentValue, nextValue; + while (lowerIndex <= upperIndex) { + currentIndex = Math.floor((lowerIndex + upperIndex) / 2); + currentValue = stops[currentIndex]; + nextValue = stops[currentIndex + 1]; + if (currentValue <= input) { + if (currentIndex === lastIndex || input < nextValue) { // Search complete + return currentIndex; + } + lowerIndex = currentIndex + 1; + } + else if (currentValue > input) { + upperIndex = currentIndex - 1; + } + else { + throw new RuntimeError('Input is not a number.'); + } + } + return 0; +} + +class Step { + constructor(type, input, stops) { + this.type = type; + this.input = input; + this.labels = []; + this.outputs = []; + for (const [label, expression] of stops) { + this.labels.push(label); + this.outputs.push(expression); + } + } + static parse(args, context) { + if (args.length - 1 < 4) { + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + } + if ((args.length - 1) % 2 !== 0) { + return context.error('Expected an even number of arguments.'); + } + const input = context.parse(args[1], 1, NumberType); + if (!input) + return null; + const stops = []; + let outputType = null; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + for (let i = 1; i < args.length; i += 2) { + const label = i === 1 ? -Infinity : args[i]; + const value = args[i + 1]; + const labelKey = i; + const valueKey = i + 1; + if (typeof label !== 'number') { + return context.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + const parsed = context.parse(value, valueKey, outputType); + if (!parsed) + return null; + outputType = outputType || parsed.type; + stops.push([label, parsed]); + } + return new Step(outputType, input, stops); + } + evaluate(ctx) { + const labels = this.labels; + const outputs = this.outputs; + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + const value = this.input.evaluate(ctx); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + const stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + const index = findStopLessThanOrEqualTo(labels, value); + return outputs[index].evaluate(ctx); + } + eachChild(fn) { + fn(this.input); + for (const expression of this.outputs) { + fn(expression); + } + } + outputDefined() { + return this.outputs.every(out => out.outputDefined()); + } +} + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var unitbezier = UnitBezier; + +function UnitBezier(p1x, p1y, p2x, p2y) { + // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). + this.cx = 3.0 * p1x; + this.bx = 3.0 * (p2x - p1x) - this.cx; + this.ax = 1.0 - this.cx - this.bx; + + this.cy = 3.0 * p1y; + this.by = 3.0 * (p2y - p1y) - this.cy; + this.ay = 1.0 - this.cy - this.by; + + this.p1x = p1x; + this.p1y = p1y; + this.p2x = p2x; + this.p2y = p2y; +} + +UnitBezier.prototype = { + sampleCurveX: function (t) { + // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. + return ((this.ax * t + this.bx) * t + this.cx) * t; + }, + + sampleCurveY: function (t) { + return ((this.ay * t + this.by) * t + this.cy) * t; + }, + + sampleCurveDerivativeX: function (t) { + return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; + }, + + solveCurveX: function (x, epsilon) { + if (epsilon === undefined) epsilon = 1e-6; + + if (x < 0.0) return 0.0; + if (x > 1.0) return 1.0; + + var t = x; + + // First try a few iterations of Newton's method - normally very fast. + for (var i = 0; i < 8; i++) { + var x2 = this.sampleCurveX(t) - x; + if (Math.abs(x2) < epsilon) return t; + + var d2 = this.sampleCurveDerivativeX(t); + if (Math.abs(d2) < 1e-6) break; + + t = t - x2 / d2; + } + + // Fall back to the bisection method for reliability. + var t0 = 0.0; + var t1 = 1.0; + t = x; + + for (i = 0; i < 20; i++) { + x2 = this.sampleCurveX(t); + if (Math.abs(x2 - x) < epsilon) break; + + if (x > x2) { + t0 = t; + } else { + t1 = t; + } + + t = (t1 - t0) * 0.5 + t0; + } + + return t; + }, + + solve: function (x, epsilon) { + return this.sampleCurveY(this.solveCurveX(x, epsilon)); + } +}; + +var UnitBezier$1 = /*@__PURE__*/getDefaultExportFromCjs(unitbezier); + +/** + * Checks whether the specified color space is one of the supported interpolation color spaces. + * + * @param colorSpace Color space key to verify. + * @returns `true` if the specified color space is one of the supported + * interpolation color spaces, `false` otherwise + */ +function isSupportedInterpolationColorSpace(colorSpace) { + return colorSpace === 'rgb' || colorSpace === 'hcl' || colorSpace === 'lab'; +} +/** + * @param interpolationType Interpolation type + * @returns interpolation fn + * @deprecated use `interpolate[type]` instead + */ +const interpolateFactory = (interpolationType) => { + switch (interpolationType) { + case 'number': return number; + case 'color': return color; + case 'array': return array; + case 'padding': return padding$1; + case 'variableAnchorOffsetCollection': return variableAnchorOffsetCollection; + } +}; +function number(from, to, t) { + return from + t * (to - from); +} +function color(from, to, t, spaceKey = 'rgb') { + switch (spaceKey) { + case 'rgb': { + const [r, g, b, alpha] = array(from.rgb, to.rgb, t); + return new Color(r, g, b, alpha, false); + } + case 'hcl': { + const [hue0, chroma0, light0, alphaF] = from.hcl; + const [hue1, chroma1, light1, alphaT] = to.hcl; + // https://github.com/gka/chroma.js/blob/cd1b3c0926c7a85cbdc3b1453b3a94006de91a92/src/interpolator/_hsx.js + let hue, chroma; + if (!isNaN(hue0) && !isNaN(hue1)) { + let dh = hue1 - hue0; + if (hue1 > hue0 && dh > 180) { + dh -= 360; + } + else if (hue1 < hue0 && hue0 - hue1 > 180) { + dh += 360; + } + hue = hue0 + t * dh; + } + else if (!isNaN(hue0)) { + hue = hue0; + if (light1 === 1 || light1 === 0) + chroma = chroma0; + } + else if (!isNaN(hue1)) { + hue = hue1; + if (light0 === 1 || light0 === 0) + chroma = chroma1; + } + else { + hue = NaN; + } + const [r, g, b, alpha] = hclToRgb([ + hue, + chroma !== null && chroma !== void 0 ? chroma : number(chroma0, chroma1, t), + number(light0, light1, t), + number(alphaF, alphaT, t), + ]); + return new Color(r, g, b, alpha, false); + } + case 'lab': { + const [r, g, b, alpha] = labToRgb(array(from.lab, to.lab, t)); + return new Color(r, g, b, alpha, false); + } + } +} +function array(from, to, t) { + return from.map((d, i) => { + return number(d, to[i], t); + }); +} +function padding$1(from, to, t) { + return new Padding(array(from.values, to.values, t)); +} +function variableAnchorOffsetCollection(from, to, t) { + const fromValues = from.values; + const toValues = to.values; + if (fromValues.length !== toValues.length) { + throw new RuntimeError(`Cannot interpolate values of different length. from: ${from.toString()}, to: ${to.toString()}`); + } + const output = []; + for (let i = 0; i < fromValues.length; i += 2) { + // Anchor entries must match + if (fromValues[i] !== toValues[i]) { + throw new RuntimeError(`Cannot interpolate values containing mismatched anchors. from[${i}]: ${fromValues[i]}, to[${i}]: ${toValues[i]}`); + } + output.push(fromValues[i]); + // Interpolate the offset values for each anchor + const [fx, fy] = fromValues[i + 1]; + const [tx, ty] = toValues[i + 1]; + output.push([number(fx, tx, t), number(fy, ty, t)]); + } + return new VariableAnchorOffsetCollection(output); +} +const interpolate = { + number, + color, + array, + padding: padding$1, + variableAnchorOffsetCollection +}; + +class Interpolate { + constructor(type, operator, interpolation, input, stops) { + this.type = type; + this.operator = operator; + this.interpolation = interpolation; + this.input = input; + this.labels = []; + this.outputs = []; + for (const [label, expression] of stops) { + this.labels.push(label); + this.outputs.push(expression); + } + } + static interpolationFactor(interpolation, input, lower, upper) { + let t = 0; + if (interpolation.name === 'exponential') { + t = exponentialInterpolation(input, interpolation.base, lower, upper); + } + else if (interpolation.name === 'linear') { + t = exponentialInterpolation(input, 1, lower, upper); + } + else if (interpolation.name === 'cubic-bezier') { + const c = interpolation.controlPoints; + const ub = new UnitBezier$1(c[0], c[1], c[2], c[3]); + t = ub.solve(exponentialInterpolation(input, 1, lower, upper)); + } + return t; + } + static parse(args, context) { + let [operator, interpolation, input, ...rest] = args; + if (!Array.isArray(interpolation) || interpolation.length === 0) { + return context.error('Expected an interpolation type expression.', 1); + } + if (interpolation[0] === 'linear') { + interpolation = { name: 'linear' }; + } + else if (interpolation[0] === 'exponential') { + const base = interpolation[1]; + if (typeof base !== 'number') + return context.error('Exponential interpolation requires a numeric base.', 1, 1); + interpolation = { + name: 'exponential', + base + }; + } + else if (interpolation[0] === 'cubic-bezier') { + const controlPoints = interpolation.slice(1); + if (controlPoints.length !== 4 || + controlPoints.some(t => typeof t !== 'number' || t < 0 || t > 1)) { + return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1); + } + interpolation = { + name: 'cubic-bezier', + controlPoints: controlPoints + }; + } + else { + return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0); + } + if (args.length - 1 < 4) { + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + } + if ((args.length - 1) % 2 !== 0) { + return context.error('Expected an even number of arguments.'); + } + input = context.parse(input, 2, NumberType); + if (!input) + return null; + const stops = []; + let outputType = null; + if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') { + outputType = ColorType; + } + else if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + for (let i = 0; i < rest.length; i += 2) { + const label = rest[i]; + const value = rest[i + 1]; + const labelKey = i + 3; + const valueKey = i + 4; + if (typeof label !== 'number') { + return context.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + const parsed = context.parse(value, valueKey, outputType); + if (!parsed) + return null; + outputType = outputType || parsed.type; + stops.push([label, parsed]); + } + if (!verifyType(outputType, NumberType) && + !verifyType(outputType, ColorType) && + !verifyType(outputType, PaddingType) && + !verifyType(outputType, VariableAnchorOffsetCollectionType) && + !verifyType(outputType, array$1(NumberType))) { + return context.error(`Type ${toString$1(outputType)} is not interpolatable.`); + } + return new Interpolate(outputType, operator, interpolation, input, stops); + } + evaluate(ctx) { + const labels = this.labels; + const outputs = this.outputs; + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + const value = this.input.evaluate(ctx); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + const stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + const index = findStopLessThanOrEqualTo(labels, value); + const lower = labels[index]; + const upper = labels[index + 1]; + const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper); + const outputLower = outputs[index].evaluate(ctx); + const outputUpper = outputs[index + 1].evaluate(ctx); + switch (this.operator) { + case 'interpolate': + return interpolate[this.type.kind](outputLower, outputUpper, t); + case 'interpolate-hcl': + return interpolate.color(outputLower, outputUpper, t, 'hcl'); + case 'interpolate-lab': + return interpolate.color(outputLower, outputUpper, t, 'lab'); + } + } + eachChild(fn) { + fn(this.input); + for (const expression of this.outputs) { + fn(expression); + } + } + outputDefined() { + return this.outputs.every(out => out.outputDefined()); + } +} +/** + * Returns a ratio that can be used to interpolate between exponential function + * stops. + * 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, + * and `a` and `b` are constants affording sufficient degrees of freedom to fit + * the function to the given stops. + * + * Here's a bit of algebra that lets us compute `f(x)` directly from the stop + * values without explicitly solving for `a` and `b`: + * + * First stop value: `f(x0) = y0 = a * base^x0 + b` + * Second stop value: `f(x1) = y1 = a * base^x1 + b` + * => `y1 - y0 = a(base^x1 - base^x0)` + * => `a = (y1 - y0)/(base^x1 - base^x0)` + * + * Desired value: `f(x) = y = a * base^x + b` + * => `f(x) = y0 + a * (base^x - base^x0)` + * + * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a + * little algebra: + * ``` + * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) + * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) + * ``` + * + * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have + * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as + * an interpolation factor between the two stops' output values. + * + * (Note: a slightly different form for `ratio`, + * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer + * expensive `Math.pow()` operations.) + * + * @private +*/ +function exponentialInterpolation(input, base, lowerValue, upperValue) { + const difference = upperValue - lowerValue; + const progress = input - lowerValue; + if (difference === 0) { + return 0; + } + else if (base === 1) { + return progress / difference; + } + else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} + +class Coalesce { + constructor(type, args) { + this.type = type; + this.args = args; + } + static parse(args, context) { + if (args.length < 2) { + return context.error('Expectected at least one argument.'); + } + let outputType = null; + const expectedType = context.expectedType; + if (expectedType && expectedType.kind !== 'value') { + outputType = expectedType; + } + const parsedArgs = []; + for (const arg of args.slice(1)) { + const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, { typeAnnotation: 'omit' }); + if (!parsed) + return null; + outputType = outputType || parsed.type; + parsedArgs.push(parsed); + } + if (!outputType) + throw new Error('No output type'); + // Above, we parse arguments without inferred type annotation so that + // they don't produce a runtime error for `null` input, which would + // preempt the desired null-coalescing behavior. + // Thus, if any of our arguments would have needed an annotation, we + // need to wrap the enclosing coalesce expression with it instead. + const needsAnnotation = expectedType && + parsedArgs.some(arg => checkSubtype(expectedType, arg.type)); + return needsAnnotation ? + new Coalesce(ValueType, parsedArgs) : + new Coalesce(outputType, parsedArgs); + } + evaluate(ctx) { + let result = null; + let argCount = 0; + let requestedImageName; + for (const arg of this.args) { + argCount++; + result = arg.evaluate(ctx); + // we need to keep track of the first requested image in a coalesce statement + // if coalesce can't find a valid image, we return the first image name so styleimagemissing can fire + if (result && result instanceof ResolvedImage && !result.available) { + if (!requestedImageName) { + requestedImageName = result.name; + } + result = null; + if (argCount === this.args.length) { + result = requestedImageName; + } + } + if (result !== null) + break; + } + return result; + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return this.args.every(arg => arg.outputDefined()); + } +} + +function isComparableType(op, type) { + if (op === '==' || op === '!=') { + // equality operator + return type.kind === 'boolean' || + type.kind === 'string' || + type.kind === 'number' || + type.kind === 'null' || + type.kind === 'value'; + } + else { + // ordering operator + return type.kind === 'string' || + type.kind === 'number' || + type.kind === 'value'; + } +} +function eq(ctx, a, b) { return a === b; } +function neq(ctx, a, b) { return a !== b; } +function lt(ctx, a, b) { return a < b; } +function gt(ctx, a, b) { return a > b; } +function lteq(ctx, a, b) { return a <= b; } +function gteq(ctx, a, b) { return a >= b; } +function eqCollate(ctx, a, b, c) { return c.compare(a, b) === 0; } +function neqCollate(ctx, a, b, c) { return !eqCollate(ctx, a, b, c); } +function ltCollate(ctx, a, b, c) { return c.compare(a, b) < 0; } +function gtCollate(ctx, a, b, c) { return c.compare(a, b) > 0; } +function lteqCollate(ctx, a, b, c) { return c.compare(a, b) <= 0; } +function gteqCollate(ctx, a, b, c) { return c.compare(a, b) >= 0; } +/** + * Special form for comparison operators, implementing the signatures: + * - (T, T, ?Collator) => boolean + * - (T, value, ?Collator) => boolean + * - (value, T, ?Collator) => boolean + * + * For inequalities, T must be either value, string, or number. For ==/!=, it + * can also be boolean or null. + * + * Equality semantics are equivalent to Javascript's strict equality (===/!==) + * -- i.e., when the arguments' types don't match, == evaluates to false, != to + * true. + * + * When types don't match in an ordering comparison, a runtime error is thrown. + * + * @private + */ +function makeComparison(op, compareBasic, compareWithCollator) { + const isOrderComparison = op !== '==' && op !== '!='; + return class Comparison { + constructor(lhs, rhs, collator) { + this.type = BooleanType; + this.lhs = lhs; + this.rhs = rhs; + this.collator = collator; + this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value'; + } + static parse(args, context) { + if (args.length !== 3 && args.length !== 4) + return context.error('Expected two or three arguments.'); + const op = args[0]; + let lhs = context.parse(args[1], 1, ValueType); + if (!lhs) + return null; + if (!isComparableType(op, lhs.type)) { + return context.concat(1).error(`"${op}" comparisons are not supported for type '${toString$1(lhs.type)}'.`); + } + let rhs = context.parse(args[2], 2, ValueType); + if (!rhs) + return null; + if (!isComparableType(op, rhs.type)) { + return context.concat(2).error(`"${op}" comparisons are not supported for type '${toString$1(rhs.type)}'.`); + } + if (lhs.type.kind !== rhs.type.kind && + lhs.type.kind !== 'value' && + rhs.type.kind !== 'value') { + return context.error(`Cannot compare types '${toString$1(lhs.type)}' and '${toString$1(rhs.type)}'.`); + } + if (isOrderComparison) { + // typing rules specific to less/greater than operators + if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') { + // (value, T) + lhs = new Assertion(rhs.type, [lhs]); + } + else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') { + // (T, value) + rhs = new Assertion(lhs.type, [rhs]); + } + } + let collator = null; + if (args.length === 4) { + if (lhs.type.kind !== 'string' && + rhs.type.kind !== 'string' && + lhs.type.kind !== 'value' && + rhs.type.kind !== 'value') { + return context.error('Cannot use collator to compare non-string types.'); + } + collator = context.parse(args[3], 3, CollatorType); + if (!collator) + return null; + } + return new Comparison(lhs, rhs, collator); + } + evaluate(ctx) { + const lhs = this.lhs.evaluate(ctx); + const rhs = this.rhs.evaluate(ctx); + if (isOrderComparison && this.hasUntypedArgument) { + const lt = typeOf(lhs); + const rt = typeOf(rhs); + // check that type is string or number, and equal + if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) { + throw new RuntimeError(`Expected arguments for "${op}" to be (string, string) or (number, number), but found (${lt.kind}, ${rt.kind}) instead.`); + } + } + if (this.collator && !isOrderComparison && this.hasUntypedArgument) { + const lt = typeOf(lhs); + const rt = typeOf(rhs); + if (lt.kind !== 'string' || rt.kind !== 'string') { + return compareBasic(ctx, lhs, rhs); + } + } + return this.collator ? + compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) : + compareBasic(ctx, lhs, rhs); + } + eachChild(fn) { + fn(this.lhs); + fn(this.rhs); + if (this.collator) { + fn(this.collator); + } + } + outputDefined() { + return true; + } + }; +} +const Equals = makeComparison('==', eq, eqCollate); +const NotEquals = makeComparison('!=', neq, neqCollate); +const LessThan = makeComparison('<', lt, ltCollate); +const GreaterThan = makeComparison('>', gt, gtCollate); +const LessThanOrEqual = makeComparison('<=', lteq, lteqCollate); +const GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate); + +class CollatorExpression { + constructor(caseSensitive, diacriticSensitive, locale) { + this.type = CollatorType; + this.locale = locale; + this.caseSensitive = caseSensitive; + this.diacriticSensitive = diacriticSensitive; + } + static parse(args, context) { + if (args.length !== 2) + return context.error('Expected one argument.'); + const options = args[1]; + if (typeof options !== 'object' || Array.isArray(options)) + return context.error('Collator options argument must be an object.'); + const caseSensitive = context.parse(options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType); + if (!caseSensitive) + return null; + const diacriticSensitive = context.parse(options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType); + if (!diacriticSensitive) + return null; + let locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) + return null; + } + return new CollatorExpression(caseSensitive, diacriticSensitive, locale); + } + evaluate(ctx) { + return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null); + } + eachChild(fn) { + fn(this.caseSensitive); + fn(this.diacriticSensitive); + if (this.locale) { + fn(this.locale); + } + } + outputDefined() { + // Technically the set of possible outputs is the combinatoric set of Collators produced + // by all possible outputs of locale/caseSensitive/diacriticSensitive + // But for the primary use of Collators in comparison operators, we ignore the Collator's + // possible outputs anyway, so we can get away with leaving this false for now. + return false; + } +} + +class NumberFormat { + constructor(number, locale, currency, minFractionDigits, maxFractionDigits) { + this.type = StringType; + this.number = number; + this.locale = locale; + this.currency = currency; + this.minFractionDigits = minFractionDigits; + this.maxFractionDigits = maxFractionDigits; + } + static parse(args, context) { + if (args.length !== 3) + return context.error('Expected two arguments.'); + const number = context.parse(args[1], 1, NumberType); + if (!number) + return null; + const options = args[2]; + if (typeof options !== 'object' || Array.isArray(options)) + return context.error('NumberFormat options argument must be an object.'); + let locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) + return null; + } + let currency = null; + if (options['currency']) { + currency = context.parse(options['currency'], 1, StringType); + if (!currency) + return null; + } + let minFractionDigits = null; + if (options['min-fraction-digits']) { + minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType); + if (!minFractionDigits) + return null; + } + let maxFractionDigits = null; + if (options['max-fraction-digits']) { + maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType); + if (!maxFractionDigits) + return null; + } + return new NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits); + } + evaluate(ctx) { + return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], { + style: this.currency ? 'currency' : 'decimal', + currency: this.currency ? this.currency.evaluate(ctx) : undefined, + minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined, + maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined, + }).format(this.number.evaluate(ctx)); + } + eachChild(fn) { + fn(this.number); + if (this.locale) { + fn(this.locale); + } + if (this.currency) { + fn(this.currency); + } + if (this.minFractionDigits) { + fn(this.minFractionDigits); + } + if (this.maxFractionDigits) { + fn(this.maxFractionDigits); + } + } + outputDefined() { + return false; + } +} + +class FormatExpression { + constructor(sections) { + this.type = FormattedType; + this.sections = sections; + } + static parse(args, context) { + if (args.length < 2) { + return context.error('Expected at least one argument.'); + } + const firstArg = args[1]; + if (!Array.isArray(firstArg) && typeof firstArg === 'object') { + return context.error('First argument must be an image or text section.'); + } + const sections = []; + let nextTokenMayBeObject = false; + for (let i = 1; i <= args.length - 1; ++i) { + const arg = args[i]; + if (nextTokenMayBeObject && typeof arg === 'object' && !Array.isArray(arg)) { + nextTokenMayBeObject = false; + let scale = null; + if (arg['font-scale']) { + scale = context.parse(arg['font-scale'], 1, NumberType); + if (!scale) + return null; + } + let font = null; + if (arg['text-font']) { + font = context.parse(arg['text-font'], 1, array$1(StringType)); + if (!font) + return null; + } + let textColor = null; + if (arg['text-color']) { + textColor = context.parse(arg['text-color'], 1, ColorType); + if (!textColor) + return null; + } + const lastExpression = sections[sections.length - 1]; + lastExpression.scale = scale; + lastExpression.font = font; + lastExpression.textColor = textColor; + } + else { + const content = context.parse(args[i], 1, ValueType); + if (!content) + return null; + const kind = content.type.kind; + if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage') + return context.error('Formatted text type must be \'string\', \'value\', \'image\' or \'null\'.'); + nextTokenMayBeObject = true; + sections.push({ content, scale: null, font: null, textColor: null }); + } + } + return new FormatExpression(sections); + } + evaluate(ctx) { + const evaluateSection = section => { + const evaluatedContent = section.content.evaluate(ctx); + if (typeOf(evaluatedContent) === ResolvedImageType) { + return new FormattedSection('', evaluatedContent, null, null, null); + } + return new FormattedSection(toString(evaluatedContent), null, section.scale ? section.scale.evaluate(ctx) : null, section.font ? section.font.evaluate(ctx).join(',') : null, section.textColor ? section.textColor.evaluate(ctx) : null); + }; + return new Formatted(this.sections.map(evaluateSection)); + } + eachChild(fn) { + for (const section of this.sections) { + fn(section.content); + if (section.scale) { + fn(section.scale); + } + if (section.font) { + fn(section.font); + } + if (section.textColor) { + fn(section.textColor); + } + } + } + outputDefined() { + // Technically the combinatoric set of all children + // Usually, this.text will be undefined anyway + return false; + } +} + +class ImageExpression { + constructor(input) { + this.type = ResolvedImageType; + this.input = input; + } + static parse(args, context) { + if (args.length !== 2) { + return context.error('Expected two arguments.'); + } + const name = context.parse(args[1], 1, StringType); + if (!name) + return context.error('No image name provided.'); + return new ImageExpression(name); + } + evaluate(ctx) { + const evaluatedImageName = this.input.evaluate(ctx); + const value = ResolvedImage.fromString(evaluatedImageName); + if (value && ctx.availableImages) + value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1; + return value; + } + eachChild(fn) { + fn(this.input); + } + outputDefined() { + // The output of image is determined by the list of available images in the evaluation context + return false; + } +} + +class Length { + constructor(input) { + this.type = NumberType; + this.input = input; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`); + const input = context.parse(args[1], 1); + if (!input) + return null; + if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value') + return context.error(`Expected argument of type string or array, but found ${toString$1(input.type)} instead.`); + return new Length(input); + } + evaluate(ctx) { + const input = this.input.evaluate(ctx); + if (typeof input === 'string') { + // The length may be affected by surrogate pairs. + return [...input].length; + } + else if (Array.isArray(input)) { + return input.length; + } + else { + throw new RuntimeError(`Expected value to be of type string or array, but found ${toString$1(typeOf(input))} instead.`); + } + } + eachChild(fn) { + fn(this.input); + } + outputDefined() { + return false; + } +} + +const EXTENT$1 = 8192; +function getTileCoordinates(p, canonical) { + const x = mercatorXfromLng$1(p[0]); + const y = mercatorYfromLat$1(p[1]); + const tilesAtZoom = Math.pow(2, canonical.z); + return [Math.round(x * tilesAtZoom * EXTENT$1), Math.round(y * tilesAtZoom * EXTENT$1)]; +} +function getLngLatFromTileCoord(coord, canonical) { + const tilesAtZoom = Math.pow(2, canonical.z); + const x = (coord[0] / EXTENT$1 + canonical.x) / tilesAtZoom; + const y = (coord[1] / EXTENT$1 + canonical.y) / tilesAtZoom; + return [lngFromMercatorXfromLng(x), latFromMercatorY$1(y)]; +} +function mercatorXfromLng$1(lng) { + return (180 + lng) / 360; +} +function lngFromMercatorXfromLng(mercatorX) { + return mercatorX * 360 - 180; +} +function mercatorYfromLat$1(lat) { + return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360; +} +function latFromMercatorY$1(mercatorY) { + return 360 / Math.PI * Math.atan(Math.exp((180 - mercatorY * 360) * Math.PI / 180)) - 90; +} +function updateBBox(bbox, coord) { + bbox[0] = Math.min(bbox[0], coord[0]); + bbox[1] = Math.min(bbox[1], coord[1]); + bbox[2] = Math.max(bbox[2], coord[0]); + bbox[3] = Math.max(bbox[3], coord[1]); +} +function boxWithinBox(bbox1, bbox2) { + if (bbox1[0] <= bbox2[0]) + return false; + if (bbox1[2] >= bbox2[2]) + return false; + if (bbox1[1] <= bbox2[1]) + return false; + if (bbox1[3] >= bbox2[3]) + return false; + return true; +} +function rayIntersect(p, p1, p2) { + 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]); +} +function pointOnBoundary(p, p1, p2) { + const x1 = p[0] - p1[0]; + const y1 = p[1] - p1[1]; + const x2 = p[0] - p2[0]; + const y2 = p[1] - p2[1]; + return (x1 * y2 - x2 * y1 === 0) && (x1 * x2 <= 0) && (y1 * y2 <= 0); +} +// a, b are end points for line segment1, c and d are end points for line segment2 +function segmentIntersectSegment(a, b, c, d) { + // check if two segments are parallel or not + // precondition is end point a, b is inside polygon, if line a->b is + // parallel to polygon edge c->d, then a->b won't intersect with c->d + const vectorP = [b[0] - a[0], b[1] - a[1]]; + const vectorQ = [d[0] - c[0], d[1] - c[1]]; + if (perp(vectorQ, vectorP) === 0) + return false; + // If lines are intersecting with each other, the relative location should be: + // a and b lie in different sides of segment c->d + // c and d lie in different sides of segment a->b + if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) + return true; + return false; +} +function lineIntersectPolygon(p1, p2, polygon) { + for (const ring of polygon) { + // loop through every edge of the ring + for (let j = 0; j < ring.length - 1; ++j) { + if (segmentIntersectSegment(p1, p2, ring[j], ring[j + 1])) { + return true; + } + } + } + return false; +} +// ray casting algorithm for detecting if point is in polygon +function pointWithinPolygon(point, rings, trueIfOnBoundary = false) { + let inside = false; + for (const ring of rings) { + for (let j = 0; j < ring.length - 1; j++) { + if (pointOnBoundary(point, ring[j], ring[j + 1])) + return trueIfOnBoundary; + if (rayIntersect(point, ring[j], ring[j + 1])) + inside = !inside; + } + } + return inside; +} +function pointWithinPolygons(point, polygons) { + for (const polygon of polygons) { + if (pointWithinPolygon(point, polygon)) + return true; + } + return false; +} +function lineStringWithinPolygon(line, polygon) { + // First, check if geometry points of line segments are all inside polygon + for (const point of line) { + if (!pointWithinPolygon(point, polygon)) { + return false; + } + } + // Second, check if there is line segment intersecting polygon edge + for (let i = 0; i < line.length - 1; ++i) { + if (lineIntersectPolygon(line[i], line[i + 1], polygon)) { + return false; + } + } + return true; +} +function lineStringWithinPolygons(line, polygons) { + for (const polygon of polygons) { + if (lineStringWithinPolygon(line, polygon)) + return true; + } + return false; +} +function perp(v1, v2) { + return (v1[0] * v2[1] - v1[1] * v2[0]); +} +// check if p1 and p2 are in different sides of line segment q1->q2 +function twoSided(p1, p2, q1, q2) { + // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3) + const x1 = p1[0] - q1[0]; + const y1 = p1[1] - q1[1]; + const x2 = p2[0] - q1[0]; + const y2 = p2[1] - q1[1]; + const x3 = q2[0] - q1[0]; + const y3 = q2[1] - q1[1]; + const det1 = (x1 * y3 - x3 * y1); + const det2 = (x2 * y3 - x3 * y2); + if ((det1 > 0 && det2 < 0) || (det1 < 0 && det2 > 0)) + return true; + return false; +} + +function getTilePolygon(coordinates, bbox, canonical) { + const polygon = []; + for (let i = 0; i < coordinates.length; i++) { + const ring = []; + for (let j = 0; j < coordinates[i].length; j++) { + const coord = getTileCoordinates(coordinates[i][j], canonical); + updateBBox(bbox, coord); + ring.push(coord); + } + polygon.push(ring); + } + return polygon; +} +function getTilePolygons(coordinates, bbox, canonical) { + const polygons = []; + for (let i = 0; i < coordinates.length; i++) { + const polygon = getTilePolygon(coordinates[i], bbox, canonical); + polygons.push(polygon); + } + return polygons; +} +function updatePoint(p, bbox, polyBBox, worldSize) { + if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) { + const halfWorldSize = worldSize * 0.5; + let shift = (p[0] - polyBBox[0] > halfWorldSize) ? -worldSize : (polyBBox[0] - p[0] > halfWorldSize) ? worldSize : 0; + if (shift === 0) { + shift = (p[0] - polyBBox[2] > halfWorldSize) ? -worldSize : (polyBBox[2] - p[0] > halfWorldSize) ? worldSize : 0; + } + p[0] += shift; + } + updateBBox(bbox, p); +} +function resetBBox(bbox) { + bbox[0] = bbox[1] = Infinity; + bbox[2] = bbox[3] = -Infinity; +} +function getTilePoints(geometry, pointBBox, polyBBox, canonical) { + const worldSize = Math.pow(2, canonical.z) * EXTENT$1; + const shifts = [canonical.x * EXTENT$1, canonical.y * EXTENT$1]; + const tilePoints = []; + for (const points of geometry) { + for (const point of points) { + const p = [point.x + shifts[0], point.y + shifts[1]]; + updatePoint(p, pointBBox, polyBBox, worldSize); + tilePoints.push(p); + } + } + return tilePoints; +} +function getTileLines(geometry, lineBBox, polyBBox, canonical) { + const worldSize = Math.pow(2, canonical.z) * EXTENT$1; + const shifts = [canonical.x * EXTENT$1, canonical.y * EXTENT$1]; + const tileLines = []; + for (const line of geometry) { + const tileLine = []; + for (const point of line) { + const p = [point.x + shifts[0], point.y + shifts[1]]; + updateBBox(lineBBox, p); + tileLine.push(p); + } + tileLines.push(tileLine); + } + if (lineBBox[2] - lineBBox[0] <= worldSize / 2) { + resetBBox(lineBBox); + for (const line of tileLines) { + for (const p of line) { + updatePoint(p, lineBBox, polyBBox, worldSize); + } + } + } + return tileLines; +} +function pointsWithinPolygons(ctx, polygonGeometry) { + const pointBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const polyBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const canonical = ctx.canonicalID(); + if (polygonGeometry.type === 'Polygon') { + const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) + return false; + for (const point of tilePoints) { + if (!pointWithinPolygon(point, tilePolygon)) + return false; + } + } + if (polygonGeometry.type === 'MultiPolygon') { + const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) + return false; + for (const point of tilePoints) { + if (!pointWithinPolygons(point, tilePolygons)) + return false; + } + } + return true; +} +function linesWithinPolygons(ctx, polygonGeometry) { + const lineBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const polyBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const canonical = ctx.canonicalID(); + if (polygonGeometry.type === 'Polygon') { + const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) + return false; + for (const line of tileLines) { + if (!lineStringWithinPolygon(line, tilePolygon)) + return false; + } + } + if (polygonGeometry.type === 'MultiPolygon') { + const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) + return false; + for (const line of tileLines) { + if (!lineStringWithinPolygons(line, tilePolygons)) + return false; + } + } + return true; +} +class Within { + constructor(geojson, geometries) { + this.type = BooleanType; + this.geojson = geojson; + this.geometries = geometries; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (isValue(args[1])) { + const geojson = args[1]; + if (geojson.type === 'FeatureCollection') { + const polygonsCoords = []; + for (const polygon of geojson.features) { + const { type, coordinates } = polygon.geometry; + if (type === 'Polygon') { + polygonsCoords.push(coordinates); + } + if (type === 'MultiPolygon') { + polygonsCoords.push(...coordinates); + } + } + if (polygonsCoords.length) { + const multipolygonWrapper = { + type: 'MultiPolygon', + coordinates: polygonsCoords + }; + return new Within(geojson, multipolygonWrapper); + } + } + else if (geojson.type === 'Feature') { + const type = geojson.geometry.type; + if (type === 'Polygon' || type === 'MultiPolygon') { + return new Within(geojson, geojson.geometry); + } + } + else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') { + return new Within(geojson, geojson); + } + } + return context.error('\'within\' expression requires valid geojson object that contains polygon geometry type.'); + } + evaluate(ctx) { + if (ctx.geometry() != null && ctx.canonicalID() != null) { + if (ctx.geometryType() === 'Point') { + return pointsWithinPolygons(ctx, this.geometries); + } + else if (ctx.geometryType() === 'LineString') { + return linesWithinPolygons(ctx, this.geometries); + } + } + return false; + } + eachChild() { } + outputDefined() { + return true; + } +} + +let TinyQueue$1 = class TinyQueue { + constructor(data = [], compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) { + this.data = data; + this.length = this.data.length; + this.compare = compare; + + if (this.length > 0) { + for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i); + } + } + + push(item) { + this.data.push(item); + this._up(this.length++); + } + + pop() { + if (this.length === 0) return undefined; + + const top = this.data[0]; + const bottom = this.data.pop(); + + if (--this.length > 0) { + this.data[0] = bottom; + this._down(0); + } + + return top; + } + + peek() { + return this.data[0]; + } + + _up(pos) { + const {data, compare} = this; + const item = data[pos]; + + while (pos > 0) { + const parent = (pos - 1) >> 1; + const current = data[parent]; + if (compare(item, current) >= 0) break; + data[pos] = current; + pos = parent; + } + + data[pos] = item; + } + + _down(pos) { + const {data, compare} = this; + const halfLength = this.length >> 1; + const item = data[pos]; + + while (pos < halfLength) { + let bestChild = (pos << 1) + 1; // initially it is the left child + const right = bestChild + 1; + + if (right < this.length && compare(data[right], data[bestChild]) < 0) { + bestChild = right; + } + if (compare(data[bestChild], item) >= 0) break; + + data[pos] = data[bestChild]; + pos = bestChild; + } + + data[pos] = item; + } +}; + +function quickselect(arr, k, left, right, compare) { + quickselectStep(arr, k, left, right || (arr.length - 1), compare || defaultCompare); +} + +function quickselectStep(arr, k, left, right, compare) { + + while (right > left) { + if (right - left > 600) { + var n = right - left + 1; + var m = k - left + 1; + var z = Math.log(n); + var s = 0.5 * Math.exp(2 * z / 3); + var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + quickselectStep(arr, k, newLeft, newRight, compare); + } + + var t = arr[k]; + var i = left; + var j = right; + + swap$2(arr, left, k); + if (compare(arr[right], t) > 0) swap$2(arr, left, right); + + while (i < j) { + swap$2(arr, i, j); + i++; + j--; + while (compare(arr[i], t) < 0) i++; + while (compare(arr[j], t) > 0) j--; + } + + if (compare(arr[left], t) === 0) swap$2(arr, left, j); + else { + j++; + swap$2(arr, j, right); + } + + if (j <= k) left = j + 1; + if (k <= j) right = j - 1; + } +} + +function swap$2(arr, i, j) { + var tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} + +function defaultCompare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * Classifies an array of rings into polygons with outer rings and holes + * @param rings - the rings to classify + * @param maxRings - the maximum number of rings to include in a polygon, use 0 to include all rings + * @returns an array of polygons with internal rings as holes + */ +function classifyRings$1(rings, maxRings) { + const len = rings.length; + if (len <= 1) + return [rings]; + const polygons = []; + let polygon; + let ccw; + for (const ring of rings) { + const area = calculateSignedArea(ring); + if (area === 0) + continue; + ring.area = Math.abs(area); + if (ccw === undefined) + ccw = area < 0; + if (ccw === area < 0) { + if (polygon) + polygons.push(polygon); + polygon = [ring]; + } + else { + polygon.push(ring); + } + } + if (polygon) + polygons.push(polygon); + // Earcut performance degrades with the # of rings in a polygon. For this + // reason, we limit strip out all but the `maxRings` largest rings. + if (maxRings > 1) { + for (let j = 0; j < polygons.length; j++) { + if (polygons[j].length <= maxRings) + continue; + quickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas); + polygons[j] = polygons[j].slice(0, maxRings); + } + } + return polygons; +} +function compareAreas(a, b) { + return b.area - a.area; +} +/** + * Returns the signed area for the polygon ring. Positive areas are exterior rings and + * have a clockwise winding. Negative areas are interior rings and have a counter clockwise + * ordering. + * + * @param ring - Exterior or interior ring + * @returns Signed area + */ +function calculateSignedArea(ring) { + let sum = 0; + for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + return sum; +} + +// This is taken from https://github.com/mapbox/cheap-ruler/ in order to take only the relevant parts +// Values that define WGS84 ellipsoid model of the Earth +const RE = 6378.137; // equatorial radius +const FE = 1 / 298.257223563; // flattening +const E2 = FE * (2 - FE); +const RAD = Math.PI / 180; +class CheapRuler { + constructor(lat) { + // Curvature formulas from https://en.wikipedia.org/wiki/Earth_radius#Meridional + const m = RAD * RE * 1000; + const coslat = Math.cos(lat * RAD); + const w2 = 1 / (1 - E2 * (1 - coslat * coslat)); + const w = Math.sqrt(w2); + // multipliers for converting longitude and latitude degrees into distance + this.kx = m * w * coslat; // based on normal radius of curvature + this.ky = m * w * w2 * (1 - E2); // based on meridonal radius of curvature + } + /** + * Given two points of the form [longitude, latitude], returns the distance. + * + * @param a - point [longitude, latitude] + * @param b - point [longitude, latitude] + * @returns distance + * @example + * const distance = ruler.distance([30.5, 50.5], [30.51, 50.49]); + * //=distance + */ + distance(a, b) { + const dx = this.wrap(a[0] - b[0]) * this.kx; + const dy = (a[1] - b[1]) * this.ky; + return Math.sqrt(dx * dx + dy * dy); + } + /** + * Returns an object of the form {point, index, t}, where point is closest point on the line + * from the given point, index is the start index of the segment with the closest point, + * and t is a parameter from 0 to 1 that indicates where the closest point is on that segment. + * + * @param line - an array of points that form the line + * @param p - point [longitude, latitude] + * @returns the nearest point, its index in the array and the proportion along the line + * @example + * const point = ruler.pointOnLine(line, [-67.04, 50.5]).point; + * //=point + */ + pointOnLine(line, p) { + let minDist = Infinity; + let minX, minY, minI, minT; + for (let i = 0; i < line.length - 1; i++) { + let x = line[i][0]; + let y = line[i][1]; + let dx = this.wrap(line[i + 1][0] - x) * this.kx; + let dy = (line[i + 1][1] - y) * this.ky; + let t = 0; + if (dx !== 0 || dy !== 0) { + t = (this.wrap(p[0] - x) * this.kx * dx + (p[1] - y) * this.ky * dy) / (dx * dx + dy * dy); + if (t > 1) { + x = line[i + 1][0]; + y = line[i + 1][1]; + } + else if (t > 0) { + x += (dx / this.kx) * t; + y += (dy / this.ky) * t; + } + } + dx = this.wrap(p[0] - x) * this.kx; + dy = (p[1] - y) * this.ky; + const sqDist = dx * dx + dy * dy; + if (sqDist < minDist) { + minDist = sqDist; + minX = x; + minY = y; + minI = i; + minT = t; + } + } + return { + point: [minX, minY], + index: minI, + t: Math.max(0, Math.min(1, minT)) + }; + } + wrap(deg) { + while (deg < -180) + deg += 360; + while (deg > 180) + deg -= 360; + return deg; + } +} + +const MinPointsSize = 100; +const MinLinePointsSize = 50; +function compareDistPair(a, b) { + return b[0] - a[0]; +} +function getRangeSize(range) { + return range[1] - range[0] + 1; +} +function isRangeSafe(range, threshold) { + return range[1] >= range[0] && range[1] < threshold; +} +function splitRange(range, isLine) { + if (range[0] > range[1]) { + return [null, null]; + } + const size = getRangeSize(range); + if (isLine) { + if (size === 2) { + return [range, null]; + } + const size1 = Math.floor(size / 2); + return [[range[0], range[0] + size1], + [range[0] + size1, range[1]]]; + } + if (size === 1) { + return [range, null]; + } + const size1 = Math.floor(size / 2) - 1; + return [[range[0], range[0] + size1], + [range[0] + size1 + 1, range[1]]]; +} +function getBBox(coords, range) { + if (!isRangeSafe(range, coords.length)) { + return [Infinity, Infinity, -Infinity, -Infinity]; + } + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + for (let i = range[0]; i <= range[1]; ++i) { + updateBBox(bbox, coords[i]); + } + return bbox; +} +function getPolygonBBox(polygon) { + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + for (const ring of polygon) { + for (const coord of ring) { + updateBBox(bbox, coord); + } + } + return bbox; +} +function isValidBBox(bbox) { + return bbox[0] !== -Infinity && bbox[1] !== -Infinity && bbox[2] !== Infinity && bbox[3] !== Infinity; +} +// Calculate the distance between two bounding boxes. +// Calculate the delta in x and y direction, and use two fake points {0.0, 0.0} +// and {dx, dy} to calculate the distance. Distance will be 0.0 if bounding box are overlapping. +function bboxToBBoxDistance(bbox1, bbox2, ruler) { + if (!isValidBBox(bbox1) || !isValidBBox(bbox2)) { + return NaN; + } + let dx = 0.0; + let dy = 0.0; + // bbox1 in left side + if (bbox1[2] < bbox2[0]) { + dx = bbox2[0] - bbox1[2]; + } + // bbox1 in right side + if (bbox1[0] > bbox2[2]) { + dx = bbox1[0] - bbox2[2]; + } + // bbox1 in above side + if (bbox1[1] > bbox2[3]) { + dy = bbox1[1] - bbox2[3]; + } + // bbox1 in down side + if (bbox1[3] < bbox2[1]) { + dy = bbox2[1] - bbox1[3]; + } + return ruler.distance([0.0, 0.0], [dx, dy]); +} +function pointToLineDistance(point, line, ruler) { + const nearestPoint = ruler.pointOnLine(line, point); + return ruler.distance(point, nearestPoint.point); +} +function segmentToSegmentDistance(p1, p2, q1, q2, ruler) { + const dist1 = Math.min(pointToLineDistance(p1, [q1, q2], ruler), pointToLineDistance(p2, [q1, q2], ruler)); + const dist2 = Math.min(pointToLineDistance(q1, [p1, p2], ruler), pointToLineDistance(q2, [p1, p2], ruler)); + return Math.min(dist1, dist2); +} +function lineToLineDistance(line1, range1, line2, range2, ruler) { + const rangeSafe = isRangeSafe(range1, line1.length) && isRangeSafe(range2, line2.length); + if (!rangeSafe) { + return Infinity; + } + let dist = Infinity; + for (let i = range1[0]; i < range1[1]; ++i) { + const p1 = line1[i]; + const p2 = line1[i + 1]; + for (let j = range2[0]; j < range2[1]; ++j) { + const q1 = line2[j]; + const q2 = line2[j + 1]; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } + dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); + } + } + return dist; +} +function pointsToPointsDistance(points1, range1, points2, range2, ruler) { + const rangeSafe = isRangeSafe(range1, points1.length) && isRangeSafe(range2, points2.length); + if (!rangeSafe) { + return NaN; + } + let dist = Infinity; + for (let i = range1[0]; i <= range1[1]; ++i) { + for (let j = range2[0]; j <= range2[1]; ++j) { + dist = Math.min(dist, ruler.distance(points1[i], points2[j])); + if (dist === 0.0) { + return dist; + } + } + } + return dist; +} +function pointToPolygonDistance(point, polygon, ruler) { + if (pointWithinPolygon(point, polygon, true)) { + return 0.0; + } + let dist = Infinity; + for (const ring of polygon) { + const front = ring[0]; + const back = ring[ring.length - 1]; + if (front !== back) { + dist = Math.min(dist, pointToLineDistance(point, [back, front], ruler)); + if (dist === 0.0) { + return dist; + } + } + const nearestPoint = ruler.pointOnLine(ring, point); + dist = Math.min(dist, ruler.distance(point, nearestPoint.point)); + if (dist === 0.0) { + return dist; + } + } + return dist; +} +function lineToPolygonDistance(line, range, polygon, ruler) { + if (!isRangeSafe(range, line.length)) { + return NaN; + } + for (let i = range[0]; i <= range[1]; ++i) { + if (pointWithinPolygon(line[i], polygon, true)) { + return 0.0; + } + } + let dist = Infinity; + for (let i = range[0]; i < range[1]; ++i) { + const p1 = line[i]; + const p2 = line[i + 1]; + for (const ring of polygon) { + for (let j = 0, len = ring.length, k = len - 1; j < len; k = j++) { + const q1 = ring[k]; + const q2 = ring[j]; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } + dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); + } + } + } + return dist; +} +function polygonIntersect(poly1, poly2) { + for (const ring of poly1) { + for (const point of ring) { + if (pointWithinPolygon(point, poly2, true)) { + return true; + } + } + } + return false; +} +function polygonToPolygonDistance(polygon1, polygon2, ruler, currentMiniDist = Infinity) { + const bbox1 = getPolygonBBox(polygon1); + const bbox2 = getPolygonBBox(polygon2); + if (currentMiniDist !== Infinity && bboxToBBoxDistance(bbox1, bbox2, ruler) >= currentMiniDist) { + return currentMiniDist; + } + if (boxWithinBox(bbox1, bbox2)) { + if (polygonIntersect(polygon1, polygon2)) { + return 0.0; + } + } + else if (polygonIntersect(polygon2, polygon1)) { + return 0.0; + } + let dist = Infinity; + for (const ring1 of polygon1) { + for (let i = 0, len1 = ring1.length, l = len1 - 1; i < len1; l = i++) { + const p1 = ring1[l]; + const p2 = ring1[i]; + for (const ring2 of polygon2) { + for (let j = 0, len2 = ring2.length, k = len2 - 1; j < len2; k = j++) { + const q1 = ring2[k]; + const q2 = ring2[j]; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } + dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); + } + } + } + } + return dist; +} +function updateQueue(distQueue, miniDist, ruler, points, polyBBox, rangeA) { + if (!rangeA) { + return; + } + const tempDist = bboxToBBoxDistance(getBBox(points, rangeA), polyBBox, ruler); + // Insert new pair to the queue if the bbox distance is less than + // miniDist, The pair with biggest distance will be at the top + if (tempDist < miniDist) { + distQueue.push([tempDist, rangeA, [0, 0]]); + } +} +function updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, range1, range2) { + if (!range1 || !range2) { + return; + } + const tempDist = bboxToBBoxDistance(getBBox(pointSet1, range1), getBBox(pointSet2, range2), ruler); + // Insert new pair to the queue if the bbox distance is less than + // miniDist, The pair with biggest distance will be at the top + if (tempDist < miniDist) { + distQueue.push([tempDist, range1, range2]); + } +} +// Divide and conquer, the time complexity is O(n*lgn), faster than Brute force +// O(n*n) Most of the time, use index for in-place processing. +function pointsToPolygonDistance(points, isLine, polygon, ruler, currentMiniDist = Infinity) { + let miniDist = Math.min(ruler.distance(points[0], polygon[0][0]), currentMiniDist); + if (miniDist === 0.0) { + return miniDist; + } + const distQueue = new TinyQueue$1([[0, [0, points.length - 1], [0, 0]]], compareDistPair); + const polyBBox = getPolygonBBox(polygon); + while (distQueue.length > 0) { + const distPair = distQueue.pop(); + if (distPair[0] >= miniDist) { + continue; + } + const range = distPair[1]; + // In case the set size are relatively small, we could use brute-force directly + const threshold = isLine ? MinLinePointsSize : MinPointsSize; + if (getRangeSize(range) <= threshold) { + if (!isRangeSafe(range, points.length)) { + return NaN; + } + if (isLine) { + const tempDist = lineToPolygonDistance(points, range, polygon, ruler); + if (isNaN(tempDist) || tempDist === 0.0) { + return tempDist; + } + miniDist = Math.min(miniDist, tempDist); + } + else { + for (let i = range[0]; i <= range[1]; ++i) { + const tempDist = pointToPolygonDistance(points[i], polygon, ruler); + miniDist = Math.min(miniDist, tempDist); + if (miniDist === 0.0) { + return 0.0; + } + } + } + } + else { + const newRangesA = splitRange(range, isLine); + updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[0]); + updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[1]); + } + } + return miniDist; +} +function pointSetToPointSetDistance(pointSet1, isLine1, pointSet2, isLine2, ruler, currentMiniDist = Infinity) { + let miniDist = Math.min(currentMiniDist, ruler.distance(pointSet1[0], pointSet2[0])); + if (miniDist === 0.0) { + return miniDist; + } + const distQueue = new TinyQueue$1([[0, [0, pointSet1.length - 1], [0, pointSet2.length - 1]]], compareDistPair); + while (distQueue.length > 0) { + const distPair = distQueue.pop(); + if (distPair[0] >= miniDist) { + continue; + } + const rangeA = distPair[1]; + const rangeB = distPair[2]; + const threshold1 = isLine1 ? MinLinePointsSize : MinPointsSize; + const threshold2 = isLine2 ? MinLinePointsSize : MinPointsSize; + // In case the set size are relatively small, we could use brute-force directly + if (getRangeSize(rangeA) <= threshold1 && getRangeSize(rangeB) <= threshold2) { + if (!isRangeSafe(rangeA, pointSet1.length) && isRangeSafe(rangeB, pointSet2.length)) { + return NaN; + } + let tempDist; + if (isLine1 && isLine2) { + tempDist = lineToLineDistance(pointSet1, rangeA, pointSet2, rangeB, ruler); + miniDist = Math.min(miniDist, tempDist); + } + else if (isLine1 && !isLine2) { + const sublibe = pointSet1.slice(rangeA[0], rangeA[1] + 1); + for (let i = rangeB[0]; i <= rangeB[1]; ++i) { + tempDist = pointToLineDistance(pointSet2[i], sublibe, ruler); + miniDist = Math.min(miniDist, tempDist); + if (miniDist === 0.0) { + return miniDist; + } + } + } + else if (!isLine1 && isLine2) { + const sublibe = pointSet2.slice(rangeB[0], rangeB[1] + 1); + for (let i = rangeA[0]; i <= rangeA[1]; ++i) { + tempDist = pointToLineDistance(pointSet1[i], sublibe, ruler); + miniDist = Math.min(miniDist, tempDist); + if (miniDist === 0.0) { + return miniDist; + } + } + } + else { + tempDist = pointsToPointsDistance(pointSet1, rangeA, pointSet2, rangeB, ruler); + miniDist = Math.min(miniDist, tempDist); + } + } + else { + const newRangesA = splitRange(rangeA, isLine1); + const newRangesB = splitRange(rangeB, isLine2); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[0]); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[1]); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[0]); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[1]); + } + } + return miniDist; +} +function pointToGeometryDistance(ctx, geometries) { + const tilePoints = ctx.geometry(); + const pointPosition = tilePoints.flat().map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); + if (tilePoints.length === 0) { + return NaN; + } + const ruler = new CheapRuler(pointPosition[0][1]); + let dist = Infinity; + for (const geometry of geometries) { + switch (geometry.type) { + case 'Point': + dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, [geometry.coordinates], false, ruler, dist)); + break; + case 'LineString': + dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, geometry.coordinates, true, ruler, dist)); + break; + case 'Polygon': + dist = Math.min(dist, pointsToPolygonDistance(pointPosition, false, geometry.coordinates, ruler, dist)); + break; + } + if (dist === 0.0) { + return dist; + } + } + return dist; +} +function lineStringToGeometryDistance(ctx, geometries) { + const tileLine = ctx.geometry(); + const linePositions = tileLine.flat().map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); + if (tileLine.length === 0) { + return NaN; + } + const ruler = new CheapRuler(linePositions[0][1]); + let dist = Infinity; + for (const geometry of geometries) { + switch (geometry.type) { + case 'Point': + dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, [geometry.coordinates], false, ruler, dist)); + break; + case 'LineString': + dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, geometry.coordinates, true, ruler, dist)); + break; + case 'Polygon': + dist = Math.min(dist, pointsToPolygonDistance(linePositions, true, geometry.coordinates, ruler, dist)); + break; + } + if (dist === 0.0) { + return dist; + } + } + return dist; +} +function polygonToGeometryDistance(ctx, geometries) { + const tilePolygon = ctx.geometry(); + if (tilePolygon.length === 0 || tilePolygon[0].length === 0) { + return NaN; + } + const polygons = classifyRings$1(tilePolygon, 0).map(polygon => { + return polygon.map(ring => { + return ring.map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); + }); + }); + const ruler = new CheapRuler(polygons[0][0][0][1]); + let dist = Infinity; + for (const geometry of geometries) { + for (const polygon of polygons) { + switch (geometry.type) { + case 'Point': + dist = Math.min(dist, pointsToPolygonDistance([geometry.coordinates], false, polygon, ruler, dist)); + break; + case 'LineString': + dist = Math.min(dist, pointsToPolygonDistance(geometry.coordinates, true, polygon, ruler, dist)); + break; + case 'Polygon': + dist = Math.min(dist, polygonToPolygonDistance(polygon, geometry.coordinates, ruler, dist)); + break; + } + if (dist === 0.0) { + return dist; + } + } + } + return dist; +} +function toSimpleGeometry(geometry) { + if (geometry.type === 'MultiPolygon') { + return geometry.coordinates.map(polygon => { + return { + type: 'Polygon', + coordinates: polygon + }; + }); + } + if (geometry.type === 'MultiLineString') { + return geometry.coordinates.map(lineString => { + return { + type: 'LineString', + coordinates: lineString + }; + }); + } + if (geometry.type === 'MultiPoint') { + return geometry.coordinates.map(point => { + return { + type: 'Point', + coordinates: point + }; + }); + } + return [geometry]; +} +class Distance { + constructor(geojson, geometries) { + this.type = NumberType; + this.geojson = geojson; + this.geometries = geometries; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`'distance' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (isValue(args[1])) { + const geojson = args[1]; + if (geojson.type === 'FeatureCollection') { + return new Distance(geojson, geojson.features.map(feature => toSimpleGeometry(feature.geometry)).flat()); + } + else if (geojson.type === 'Feature') { + return new Distance(geojson, toSimpleGeometry(geojson.geometry)); + } + else if ('type' in geojson && 'coordinates' in geojson) { + return new Distance(geojson, toSimpleGeometry(geojson)); + } + } + return context.error('\'distance\' expression requires valid geojson object that contains polygon geometry type.'); + } + evaluate(ctx) { + if (ctx.geometry() != null && ctx.canonicalID() != null) { + if (ctx.geometryType() === 'Point') { + return pointToGeometryDistance(ctx, this.geometries); + } + else if (ctx.geometryType() === 'LineString') { + return lineStringToGeometryDistance(ctx, this.geometries); + } + else if (ctx.geometryType() === 'Polygon') { + return polygonToGeometryDistance(ctx, this.geometries); + } + } + return NaN; + } + eachChild() { } + outputDefined() { + return true; + } +} + +const expressions$1 = { + // special forms + '==': Equals, + '!=': NotEquals, + '>': GreaterThan, + '<': LessThan, + '>=': GreaterThanOrEqual, + '<=': LessThanOrEqual, + 'array': Assertion, + 'at': At, + 'boolean': Assertion, + 'case': Case, + 'coalesce': Coalesce, + 'collator': CollatorExpression, + 'format': FormatExpression, + 'image': ImageExpression, + 'in': In, + 'index-of': IndexOf, + 'interpolate': Interpolate, + 'interpolate-hcl': Interpolate, + 'interpolate-lab': Interpolate, + 'length': Length, + 'let': Let, + 'literal': Literal, + 'match': Match, + 'number': Assertion, + 'number-format': NumberFormat, + 'object': Assertion, + 'slice': Slice, + 'step': Step, + 'string': Assertion, + 'to-boolean': Coercion, + 'to-color': Coercion, + 'to-number': Coercion, + 'to-string': Coercion, + 'var': Var, + 'within': Within, + 'distance': Distance +}; + +class CompoundExpression { + constructor(name, type, evaluate, args) { + this.name = name; + this.type = type; + this._evaluate = evaluate; + this.args = args; + } + evaluate(ctx) { + return this._evaluate(ctx, this.args); + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return false; + } + static parse(args, context) { + const op = args[0]; + const definition = CompoundExpression.definitions[op]; + if (!definition) { + return context.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); + } + // Now check argument types against each signature + const type = Array.isArray(definition) ? + definition[0] : definition.type; + const availableOverloads = Array.isArray(definition) ? + [[definition[1], definition[2]]] : + definition.overloads; + const overloads = availableOverloads.filter(([signature]) => (!Array.isArray(signature) || // varags + signature.length === args.length - 1 // correct param count + )); + let signatureContext = null; + for (const [params, evaluate] of overloads) { + // Use a fresh context for each attempted signature so that, if + // we eventually succeed, we haven't polluted `context.errors`. + signatureContext = new ParsingContext(context.registry, isExpressionConstant, context.path, null, context.scope); + // First parse all the args, potentially coercing to the + // types expected by this overload. + const parsedArgs = []; + let argParseFailed = false; + for (let i = 1; i < args.length; i++) { + const arg = args[i]; + const expectedType = Array.isArray(params) ? + params[i - 1] : + params.type; + const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType); + if (!parsed) { + argParseFailed = true; + break; + } + parsedArgs.push(parsed); + } + if (argParseFailed) { + // Couldn't coerce args of this overload to expected type, move + // on to next one. + continue; + } + if (Array.isArray(params)) { + if (params.length !== parsedArgs.length) { + signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`); + continue; + } + } + for (let i = 0; i < parsedArgs.length; i++) { + const expected = Array.isArray(params) ? params[i] : params.type; + const arg = parsedArgs[i]; + signatureContext.concat(i + 1).checkSubtype(expected, arg.type); + } + if (signatureContext.errors.length === 0) { + return new CompoundExpression(op, type, evaluate, parsedArgs); + } + } + if (overloads.length === 1) { + context.errors.push(...signatureContext.errors); + } + else { + const expected = overloads.length ? overloads : availableOverloads; + const signatures = expected + .map(([params]) => stringifySignature(params)) + .join(' | '); + const actualTypes = []; + // For error message, re-parse arguments without trying to + // apply any coercions + for (let i = 1; i < args.length; i++) { + const parsed = context.parse(args[i], 1 + actualTypes.length); + if (!parsed) + return null; + actualTypes.push(toString$1(parsed.type)); + } + context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`); + } + return null; + } + static register(registry, definitions) { + CompoundExpression.definitions = definitions; + for (const name in definitions) { + registry[name] = CompoundExpression; + } + } +} +function rgba(ctx, [r, g, b, a]) { + r = r.evaluate(ctx); + g = g.evaluate(ctx); + b = b.evaluate(ctx); + const alpha = a ? a.evaluate(ctx) : 1; + const error = validateRGBA(r, g, b, alpha); + if (error) + throw new RuntimeError(error); + return new Color(r / 255, g / 255, b / 255, alpha, false); +} +function has(key, obj) { + return key in obj; +} +function get(key, obj) { + const v = obj[key]; + return typeof v === 'undefined' ? null : v; +} +function binarySearch(v, a, i, j) { + while (i <= j) { + const m = (i + j) >> 1; + if (a[m] === v) + return true; + if (a[m] > v) + j = m - 1; + else + i = m + 1; + } + return false; +} +function varargs(type) { + return { type }; +} +CompoundExpression.register(expressions$1, { + 'error': [ + ErrorType, + [StringType], + (ctx, [v]) => { throw new RuntimeError(v.evaluate(ctx)); } + ], + 'typeof': [ + StringType, + [ValueType], + (ctx, [v]) => toString$1(typeOf(v.evaluate(ctx))) + ], + 'to-rgba': [ + array$1(NumberType, 4), + [ColorType], + (ctx, [v]) => { + const [r, g, b, a] = v.evaluate(ctx).rgb; + return [r * 255, g * 255, b * 255, a]; + }, + ], + 'rgb': [ + ColorType, + [NumberType, NumberType, NumberType], + rgba + ], + 'rgba': [ + ColorType, + [NumberType, NumberType, NumberType, NumberType], + rgba + ], + 'has': { + type: BooleanType, + overloads: [ + [ + [StringType], + (ctx, [key]) => has(key.evaluate(ctx), ctx.properties()) + ], [ + [StringType, ObjectType], + (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx)) + ] + ] + }, + 'get': { + type: ValueType, + overloads: [ + [ + [StringType], + (ctx, [key]) => get(key.evaluate(ctx), ctx.properties()) + ], [ + [StringType, ObjectType], + (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx)) + ] + ] + }, + 'feature-state': [ + ValueType, + [StringType], + (ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {}) + ], + 'properties': [ + ObjectType, + [], + (ctx) => ctx.properties() + ], + 'geometry-type': [ + StringType, + [], + (ctx) => ctx.geometryType() + ], + 'id': [ + ValueType, + [], + (ctx) => ctx.id() + ], + 'zoom': [ + NumberType, + [], + (ctx) => ctx.globals.zoom + ], + 'heatmap-density': [ + NumberType, + [], + (ctx) => ctx.globals.heatmapDensity || 0 + ], + 'line-progress': [ + NumberType, + [], + (ctx) => ctx.globals.lineProgress || 0 + ], + 'accumulated': [ + ValueType, + [], + (ctx) => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated + ], + '+': [ + NumberType, + varargs(NumberType), + (ctx, args) => { + let result = 0; + for (const arg of args) { + result += arg.evaluate(ctx); + } + return result; + } + ], + '*': [ + NumberType, + varargs(NumberType), + (ctx, args) => { + let result = 1; + for (const arg of args) { + result *= arg.evaluate(ctx); + } + return result; + } + ], + '-': { + type: NumberType, + overloads: [ + [ + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx) + ], [ + [NumberType], + (ctx, [a]) => -a.evaluate(ctx) + ] + ] + }, + '/': [ + NumberType, + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx) + ], + '%': [ + NumberType, + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx) + ], + 'ln2': [ + NumberType, + [], + () => Math.LN2 + ], + 'pi': [ + NumberType, + [], + () => Math.PI + ], + 'e': [ + NumberType, + [], + () => Math.E + ], + '^': [ + NumberType, + [NumberType, NumberType], + (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx)) + ], + 'sqrt': [ + NumberType, + [NumberType], + (ctx, [x]) => Math.sqrt(x.evaluate(ctx)) + ], + 'log10': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10 + ], + 'ln': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) + ], + 'log2': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2 + ], + 'sin': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.sin(n.evaluate(ctx)) + ], + 'cos': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.cos(n.evaluate(ctx)) + ], + 'tan': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.tan(n.evaluate(ctx)) + ], + 'asin': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.asin(n.evaluate(ctx)) + ], + 'acos': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.acos(n.evaluate(ctx)) + ], + 'atan': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.atan(n.evaluate(ctx)) + ], + 'min': [ + NumberType, + varargs(NumberType), + (ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx))) + ], + 'max': [ + NumberType, + varargs(NumberType), + (ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx))) + ], + 'abs': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.abs(n.evaluate(ctx)) + ], + 'round': [ + NumberType, + [NumberType], + (ctx, [n]) => { + const v = n.evaluate(ctx); + // Javascript's Math.round() rounds towards +Infinity for halfway + // values, even when they're negative. It's more common to round + // away from 0 (e.g., this is what python and C++ do) + return v < 0 ? -Math.round(-v) : Math.round(v); + } + ], + 'floor': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.floor(n.evaluate(ctx)) + ], + 'ceil': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.ceil(n.evaluate(ctx)) + ], + 'filter-==': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => ctx.properties()[k.value] === v.value + ], + 'filter-id-==': [ + BooleanType, + [ValueType], + (ctx, [v]) => ctx.id() === v.value + ], + 'filter-type-==': [ + BooleanType, + [StringType], + (ctx, [v]) => ctx.geometryType() === v.value + ], + 'filter-<': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a < b; + } + ], + 'filter-id-<': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a < b; + } + ], + 'filter->': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a > b; + } + ], + 'filter-id->': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a > b; + } + ], + 'filter-<=': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a <= b; + } + ], + 'filter-id-<=': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a <= b; + } + ], + 'filter->=': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-id->=': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-has': [ + BooleanType, + [ValueType], + (ctx, [k]) => k.value in ctx.properties() + ], + 'filter-has-id': [ + BooleanType, + [], + (ctx) => (ctx.id() !== null && ctx.id() !== undefined) + ], + 'filter-type-in': [ + BooleanType, + [array$1(StringType)], + (ctx, [v]) => v.value.indexOf(ctx.geometryType()) >= 0 + ], + 'filter-id-in': [ + BooleanType, + [array$1(ValueType)], + (ctx, [v]) => v.value.indexOf(ctx.id()) >= 0 + ], + 'filter-in-small': [ + BooleanType, + [StringType, array$1(ValueType)], + // assumes v is an array literal + (ctx, [k, v]) => v.value.indexOf(ctx.properties()[k.value]) >= 0 + ], + 'filter-in-large': [ + BooleanType, + [StringType, array$1(ValueType)], + // assumes v is a array literal with values sorted in ascending order and of a single type + (ctx, [k, v]) => binarySearch(ctx.properties()[k.value], v.value, 0, v.value.length - 1) + ], + 'all': { + type: BooleanType, + overloads: [ + [ + [BooleanType, BooleanType], + (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx) + ], + [ + varargs(BooleanType), + (ctx, args) => { + for (const arg of args) { + if (!arg.evaluate(ctx)) + return false; + } + return true; + } + ] + ] + }, + 'any': { + type: BooleanType, + overloads: [ + [ + [BooleanType, BooleanType], + (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx) + ], + [ + varargs(BooleanType), + (ctx, args) => { + for (const arg of args) { + if (arg.evaluate(ctx)) + return true; + } + return false; + } + ] + ] + }, + '!': [ + BooleanType, + [BooleanType], + (ctx, [b]) => !b.evaluate(ctx) + ], + 'is-supported-script': [ + BooleanType, + [StringType], + // At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant + (ctx, [s]) => { + const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript; + if (isSupportedScript) { + return isSupportedScript(s.evaluate(ctx)); + } + return true; + } + ], + 'upcase': [ + StringType, + [StringType], + (ctx, [s]) => s.evaluate(ctx).toUpperCase() + ], + 'downcase': [ + StringType, + [StringType], + (ctx, [s]) => s.evaluate(ctx).toLowerCase() + ], + 'concat': [ + StringType, + varargs(ValueType), + (ctx, args) => args.map(arg => toString(arg.evaluate(ctx))).join('') + ], + 'resolved-locale': [ + StringType, + [CollatorType], + (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale() + ] +}); +function stringifySignature(signature) { + if (Array.isArray(signature)) { + return `(${signature.map(toString$1).join(', ')})`; + } + else { + return `(${toString$1(signature.type)}...)`; + } +} +function isExpressionConstant(expression) { + if (expression instanceof Var) { + return isExpressionConstant(expression.boundExpression); + } + else if (expression instanceof CompoundExpression && expression.name === 'error') { + return false; + } + else if (expression instanceof CollatorExpression) { + // Although the results of a Collator expression with fixed arguments + // generally shouldn't change between executions, we can't serialize them + // as constant expressions because results change based on environment. + return false; + } + else if (expression instanceof Within) { + return false; + } + else if (expression instanceof Distance) { + return false; + } + const isTypeAnnotation = expression instanceof Coercion || + expression instanceof Assertion; + let childrenConstant = true; + expression.eachChild(child => { + // We can _almost_ assume that if `expressions` children are constant, + // they would already have been evaluated to Literal values when they + // were parsed. Type annotations are the exception, because they might + // have been inferred and added after a child was parsed. + // So we recurse into isConstant() for the children of type annotations, + // but otherwise simply check whether they are Literals. + if (isTypeAnnotation) { + childrenConstant = childrenConstant && isExpressionConstant(child); + } + else { + childrenConstant = childrenConstant && child instanceof Literal; + } + }); + if (!childrenConstant) { + return false; + } + return isFeatureConstant(expression) && + isGlobalPropertyConstant(expression, ['zoom', 'heatmap-density', 'line-progress', 'accumulated', 'is-supported-script']); +} +function isFeatureConstant(e) { + if (e instanceof CompoundExpression) { + if (e.name === 'get' && e.args.length === 1) { + return false; + } + else if (e.name === 'feature-state') { + return false; + } + else if (e.name === 'has' && e.args.length === 1) { + return false; + } + else if (e.name === 'properties' || + e.name === 'geometry-type' || + e.name === 'id') { + return false; + } + else if (/^filter-/.test(e.name)) { + return false; + } + } + if (e instanceof Within) { + return false; + } + if (e instanceof Distance) { + return false; + } + let result = true; + e.eachChild(arg => { + if (result && !isFeatureConstant(arg)) { + result = false; + } + }); + return result; +} +function isStateConstant(e) { + if (e instanceof CompoundExpression) { + if (e.name === 'feature-state') { + return false; + } + } + let result = true; + e.eachChild(arg => { + if (result && !isStateConstant(arg)) { + result = false; + } + }); + return result; +} +function isGlobalPropertyConstant(e, properties) { + if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) { + return false; + } + let result = true; + e.eachChild((arg) => { + if (result && !isGlobalPropertyConstant(arg, properties)) { + result = false; + } + }); + return result; +} + +function success(value) { + return { result: 'success', value }; +} +function error(value) { + return { result: 'error', value }; +} + +function supportsPropertyExpression(spec) { + return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-data-driven'; +} +function supportsZoomExpression(spec) { + return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1; +} +function supportsInterpolation(spec) { + return !!spec.expression && spec.expression.interpolated; +} + +function getType(val) { + if (val instanceof Number) { + return 'number'; + } + else if (val instanceof String) { + return 'string'; + } + else if (val instanceof Boolean) { + return 'boolean'; + } + else if (Array.isArray(val)) { + return 'array'; + } + else if (val === null) { + return 'null'; + } + else { + return typeof val; + } +} + +function isFunction$1(value) { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} +function identityFunction(x) { + return x; +} +function createFunction(parameters, propertySpec) { + const isColor = propertySpec.type === 'color'; + const zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object'; + const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + const zoomDependent = zoomAndFeatureDependent || !featureDependent; + const type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval'); + if (isColor || propertySpec.type === 'padding') { + const parseFn = isColor ? Color.parse : Padding.parse; + parameters = extendBy({}, parameters); + if (parameters.stops) { + parameters.stops = parameters.stops.map((stop) => { + return [stop[0], parseFn(stop[1])]; + }); + } + if (parameters.default) { + parameters.default = parseFn(parameters.default); + } + else { + parameters.default = parseFn(propertySpec.default); + } + } + if (parameters.colorSpace && !isSupportedInterpolationColorSpace(parameters.colorSpace)) { + throw new Error(`Unknown color space: "${parameters.colorSpace}"`); + } + let innerFun; + let hashedStops; + let categoricalKeyType; + if (type === 'exponential') { + innerFun = evaluateExponentialFunction; + } + else if (type === 'interval') { + innerFun = evaluateIntervalFunction; + } + else if (type === 'categorical') { + innerFun = evaluateCategoricalFunction; + // For categorical functions, generate an Object as a hashmap of the stops for fast searching + hashedStops = Object.create(null); + for (const stop of parameters.stops) { + hashedStops[stop[0]] = stop[1]; + } + // Infer key type based on first stop key-- used to encforce strict type checking later + categoricalKeyType = typeof parameters.stops[0][0]; + } + else if (type === 'identity') { + innerFun = evaluateIdentityFunction; + } + else { + throw new Error(`Unknown function type "${type}"`); + } + if (zoomAndFeatureDependent) { + const featureFunctions = {}; + const zoomStops = []; + for (let s = 0; s < parameters.stops.length; s++) { + const stop = parameters.stops[s]; + const zoom = stop[0].zoom; + if (featureFunctions[zoom] === undefined) { + featureFunctions[zoom] = { + zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default, + stops: [] + }; + zoomStops.push(zoom); + } + featureFunctions[zoom].stops.push([stop[0].value, stop[1]]); + } + const featureFunctionStops = []; + for (const z of zoomStops) { + featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]); + } + const interpolationType = { name: 'linear' }; + return { + kind: 'composite', + interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: featureFunctionStops.map(s => s[0]), + evaluate({ zoom }, properties) { + return evaluateExponentialFunction({ + stops: featureFunctionStops, + base: parameters.base + }, propertySpec, zoom).evaluate(zoom, properties); + } + }; + } + else if (zoomDependent) { + const interpolationType = type === 'exponential' ? + { name: 'exponential', base: parameters.base !== undefined ? parameters.base : 1 } : null; + return { + kind: 'camera', + interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: parameters.stops.map(s => s[0]), + evaluate: ({ zoom }) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType) + }; + } + else { + return { + kind: 'source', + evaluate(_, feature) { + const value = feature && feature.properties ? feature.properties[parameters.property] : undefined; + if (value === undefined) { + return coalesce$1(parameters.default, propertySpec.default); + } + return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType); + } + }; + } +} +function coalesce$1(a, b, c) { + if (a !== undefined) + return a; + if (b !== undefined) + return b; + if (c !== undefined) + return c; +} +function evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) { + const evaluated = typeof input === keyType ? hashedStops[input] : undefined; // Enforce strict typing on input + return coalesce$1(evaluated, parameters.default, propertySpec.default); +} +function evaluateIntervalFunction(parameters, propertySpec, input) { + // Edge cases + if (getType(input) !== 'number') + return coalesce$1(parameters.default, propertySpec.default); + const n = parameters.stops.length; + if (n === 1) + return parameters.stops[0][1]; + if (input <= parameters.stops[0][0]) + return parameters.stops[0][1]; + if (input >= parameters.stops[n - 1][0]) + return parameters.stops[n - 1][1]; + const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); + return parameters.stops[index][1]; +} +function evaluateExponentialFunction(parameters, propertySpec, input) { + const base = parameters.base !== undefined ? parameters.base : 1; + // Edge cases + if (getType(input) !== 'number') + return coalesce$1(parameters.default, propertySpec.default); + const n = parameters.stops.length; + if (n === 1) + return parameters.stops[0][1]; + if (input <= parameters.stops[0][0]) + return parameters.stops[0][1]; + if (input >= parameters.stops[n - 1][0]) + return parameters.stops[n - 1][1]; + const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); + const t = interpolationFactor(input, base, parameters.stops[index][0], parameters.stops[index + 1][0]); + const outputLower = parameters.stops[index][1]; + const outputUpper = parameters.stops[index + 1][1]; + const interp = interpolate[propertySpec.type] || identityFunction; + if (typeof outputLower.evaluate === 'function') { + return { + evaluate(...args) { + const evaluatedLower = outputLower.evaluate.apply(undefined, args); + const evaluatedUpper = outputUpper.evaluate.apply(undefined, args); + // Special case for fill-outline-color, which has no spec default. + if (evaluatedLower === undefined || evaluatedUpper === undefined) { + return undefined; + } + return interp(evaluatedLower, evaluatedUpper, t, parameters.colorSpace); + } + }; + } + return interp(outputLower, outputUpper, t, parameters.colorSpace); +} +function evaluateIdentityFunction(parameters, propertySpec, input) { + switch (propertySpec.type) { + case 'color': + input = Color.parse(input); + break; + case 'formatted': + input = Formatted.fromString(input.toString()); + break; + case 'resolvedImage': + input = ResolvedImage.fromString(input.toString()); + break; + case 'padding': + input = Padding.parse(input); + break; + default: + if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) { + input = undefined; + } + } + return coalesce$1(input, parameters.default, propertySpec.default); +} +/** + * Returns a ratio that can be used to interpolate between exponential function + * stops. + * + * 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, + * and `a` and `b` are constants affording sufficient degrees of freedom to fit + * the function to the given stops. + * + * Here's a bit of algebra that lets us compute `f(x)` directly from the stop + * values without explicitly solving for `a` and `b`: + * + * First stop value: `f(x0) = y0 = a * base^x0 + b` + * Second stop value: `f(x1) = y1 = a * base^x1 + b` + * => `y1 - y0 = a(base^x1 - base^x0)` + * => `a = (y1 - y0)/(base^x1 - base^x0)` + * + * Desired value: `f(x) = y = a * base^x + b` + * => `f(x) = y0 + a * (base^x - base^x0)` + * + * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a + * little algebra: + * ``` + * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) + * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) + * ``` + * + * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have + * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as + * an interpolation factor between the two stops' output values. + * + * (Note: a slightly different form for `ratio`, + * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer + * expensive `Math.pow()` operations.) + * + * @private + */ +function interpolationFactor(input, base, lowerValue, upperValue) { + const difference = upperValue - lowerValue; + const progress = input - lowerValue; + if (difference === 0) { + return 0; + } + else if (base === 1) { + return progress / difference; + } + else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} + +class StyleExpression { + constructor(expression, propertySpec) { + this.expression = expression; + this._warningHistory = {}; + this._evaluator = new EvaluationContext(); + this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null; + this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null; + } + evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + this._evaluator.globals = globals; + this._evaluator.feature = feature; + this._evaluator.featureState = featureState; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection; + return this.expression.evaluate(this._evaluator); + } + evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + this._evaluator.globals = globals; + this._evaluator.feature = feature || null; + this._evaluator.featureState = featureState || null; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection || null; + try { + const val = this.expression.evaluate(this._evaluator); + // eslint-disable-next-line no-self-compare + if (val === null || val === undefined || (typeof val === 'number' && val !== val)) { + return this._defaultValue; + } + if (this._enumValues && !(val in this._enumValues)) { + 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.`); + } + return val; + } + catch (e) { + if (!this._warningHistory[e.message]) { + this._warningHistory[e.message] = true; + if (typeof console !== 'undefined') { + console.warn(e.message); + } + } + return this._defaultValue; + } + } +} +function isExpression(expression) { + return Array.isArray(expression) && expression.length > 0 && + typeof expression[0] === 'string' && expression[0] in expressions$1; +} +/** + * Parse and typecheck the given style spec JSON expression. If + * options.defaultValue is provided, then the resulting StyleExpression's + * `evaluate()` method will handle errors by logging a warning (once per + * message) and returning the default value. Otherwise, it will throw + * evaluation errors. + * + * @private + */ +function createExpression(expression, propertySpec) { + const parser = new ParsingContext(expressions$1, isExpressionConstant, [], propertySpec ? getExpectedType(propertySpec) : undefined); + // For string-valued properties, coerce to string at the top level rather than asserting. + const parsed = parser.parse(expression, undefined, undefined, undefined, propertySpec && propertySpec.type === 'string' ? { typeAnnotation: 'coerce' } : undefined); + if (!parsed) { + return error(parser.errors); + } + return success(new StyleExpression(parsed, propertySpec)); +} +class ZoomConstantExpression { + constructor(kind, expression) { + this.kind = kind; + this._styleExpression = expression; + this.isStateDependent = kind !== 'constant' && !isStateConstant(expression.expression); + } + evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + } + evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + } +} +class ZoomDependentExpression { + constructor(kind, expression, zoomStops, interpolationType) { + this.kind = kind; + this.zoomStops = zoomStops; + this._styleExpression = expression; + this.isStateDependent = kind !== 'camera' && !isStateConstant(expression.expression); + this.interpolationType = interpolationType; + } + evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + } + evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + } + interpolationFactor(input, lower, upper) { + if (this.interpolationType) { + return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper); + } + else { + return 0; + } + } +} +function isZoomExpression(expression) { + return expression._styleExpression !== undefined; +} +function createPropertyExpression(expressionInput, propertySpec) { + const expression = createExpression(expressionInput, propertySpec); + if (expression.result === 'error') { + return expression; + } + const parsed = expression.value.expression; + const isFeatureConstantResult = isFeatureConstant(parsed); + if (!isFeatureConstantResult && !supportsPropertyExpression(propertySpec)) { + return error([new ExpressionParsingError('', 'data expressions not supported')]); + } + const isZoomConstant = isGlobalPropertyConstant(parsed, ['zoom']); + if (!isZoomConstant && !supportsZoomExpression(propertySpec)) { + return error([new ExpressionParsingError('', 'zoom expressions not supported')]); + } + const zoomCurve = findZoomCurve(parsed); + if (!zoomCurve && !isZoomConstant) { + return error([new ExpressionParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]); + } + else if (zoomCurve instanceof ExpressionParsingError) { + return error([zoomCurve]); + } + else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) { + return error([new ExpressionParsingError('', '"interpolate" expressions cannot be used with this property')]); + } + if (!zoomCurve) { + return success(isFeatureConstantResult ? + new ZoomConstantExpression('constant', expression.value) : + new ZoomConstantExpression('source', expression.value)); + } + const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined; + return success(isFeatureConstantResult ? + new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType) : + new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType)); +} +// serialization wrapper for old-style stop functions normalized to the +// expression interface +class StylePropertyFunction { + constructor(parameters, specification) { + this._parameters = parameters; + this._specification = specification; + extendBy(this, createFunction(this._parameters, this._specification)); + } + static deserialize(serialized) { + return new StylePropertyFunction(serialized._parameters, serialized._specification); + } + static serialize(input) { + return { + _parameters: input._parameters, + _specification: input._specification + }; + } +} +function normalizePropertyExpression(value, specification) { + if (isFunction$1(value)) { + return new StylePropertyFunction(value, specification); + } + else if (isExpression(value)) { + const expression = createPropertyExpression(value, specification); + if (expression.result === 'error') { + // this should have been caught in validation + throw new Error(expression.value.map(err => `${err.key}: ${err.message}`).join(', ')); + } + return expression.value; + } + else { + let constant = value; + if (specification.type === 'color' && typeof value === 'string') { + constant = Color.parse(value); + } + else if (specification.type === 'padding' && (typeof value === 'number' || Array.isArray(value))) { + constant = Padding.parse(value); + } + else if (specification.type === 'variableAnchorOffsetCollection' && Array.isArray(value)) { + constant = VariableAnchorOffsetCollection.parse(value); + } + return { + kind: 'constant', + evaluate: () => constant + }; + } +} +// Zoom-dependent expressions may only use ["zoom"] as the input to a top-level "step" or "interpolate" +// expression (collectively referred to as a "curve"). The curve may be wrapped in one or more "let" or +// "coalesce" expressions. +function findZoomCurve(expression) { + let result = null; + if (expression instanceof Let) { + result = findZoomCurve(expression.result); + } + else if (expression instanceof Coalesce) { + for (const arg of expression.args) { + result = findZoomCurve(arg); + if (result) { + break; + } + } + } + else if ((expression instanceof Step || expression instanceof Interpolate) && + expression.input instanceof CompoundExpression && + expression.input.name === 'zoom') { + result = expression; + } + if (result instanceof ExpressionParsingError) { + return result; + } + expression.eachChild((child) => { + const childResult = findZoomCurve(child); + if (childResult instanceof ExpressionParsingError) { + result = childResult; + } + else if (!result && childResult) { + result = new ExpressionParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'); + } + else if (result && childResult && result !== childResult) { + result = new ExpressionParsingError('', 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'); + } + }); + return result; +} +function getExpectedType(spec) { + const types = { + color: ColorType, + string: StringType, + number: NumberType, + enum: StringType, + boolean: BooleanType, + formatted: FormattedType, + padding: PaddingType, + resolvedImage: ResolvedImageType, + variableAnchorOffsetCollection: VariableAnchorOffsetCollectionType + }; + if (spec.type === 'array') { + return array$1(types[spec.value] || ValueType, spec.length); + } + return types[spec.type]; +} +function getDefaultValue(spec) { + if (spec.type === 'color' && isFunction$1(spec.default)) { + // Special case for heatmap-color: it uses the 'default:' to define a + // default color ramp, but createExpression expects a simple value to fall + // back to in case of runtime errors + return new Color(0, 0, 0, 0); + } + else if (spec.type === 'color') { + return Color.parse(spec.default) || null; + } + else if (spec.type === 'padding') { + return Padding.parse(spec.default) || null; + } + else if (spec.type === 'variableAnchorOffsetCollection') { + return VariableAnchorOffsetCollection.parse(spec.default) || null; + } + else if (spec.default === undefined) { + return null; + } + else { + return spec.default; + } +} + +function isExpressionFilter(filter) { + if (filter === true || filter === false) { + return true; + } + if (!Array.isArray(filter) || filter.length === 0) { + return false; + } + switch (filter[0]) { + case 'has': + return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type'; + case 'in': + return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2])); + case '!in': + case '!has': + case 'none': + return false; + case '==': + case '!=': + case '>': + case '>=': + case '<': + case '<=': + return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2])); + case 'any': + case 'all': + for (const f of filter.slice(1)) { + if (!isExpressionFilter(f) && typeof f !== 'boolean') { + return false; + } + } + return true; + default: + return true; + } +} +const filterSpec = { + 'type': 'boolean', + 'default': false, + 'transition': false, + 'property-type': 'data-driven', + 'expression': { + 'interpolated': false, + 'parameters': ['zoom', 'feature'] + } +}; +/** + * Given a filter expressed as nested arrays, return a new function + * that evaluates whether a given feature (with a .properties or .tags property) + * passes its test. + * + * @private + * @param {Array} filter MapLibre filter + * @returns {Function} filter-evaluating function + */ +function createFilter(filter) { + if (filter === null || filter === undefined) { + return { filter: () => true, needGeometry: false }; + } + if (!isExpressionFilter(filter)) { + filter = convertFilter$1(filter); + } + const compiled = createExpression(filter, filterSpec); + if (compiled.result === 'error') { + throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', ')); + } + else { + const needGeometry = geometryNeeded(filter); + return { filter: (globalProperties, feature, canonical) => compiled.value.evaluate(globalProperties, feature, {}, canonical), + needGeometry }; + } +} +// Comparison function to sort numbers and strings +function compare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} +function geometryNeeded(filter) { + if (!Array.isArray(filter)) + return false; + if (filter[0] === 'within' || filter[0] === 'distance') + return true; + for (let index = 1; index < filter.length; index++) { + if (geometryNeeded(filter[index])) + return true; + } + return false; +} +function convertFilter$1(filter) { + if (!filter) + return true; + const op = filter[0]; + if (filter.length <= 1) + return (op !== 'any'); + const converted = op === '==' ? convertComparisonOp$1(filter[1], filter[2], '==') : + op === '!=' ? convertNegation(convertComparisonOp$1(filter[1], filter[2], '==')) : + op === '<' || + op === '>' || + op === '<=' || + op === '>=' ? convertComparisonOp$1(filter[1], filter[2], op) : + op === 'any' ? convertDisjunctionOp(filter.slice(1)) : + op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter$1)) : + op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter$1).map(convertNegation)) : + op === 'in' ? convertInOp$1(filter[1], filter.slice(2)) : + op === '!in' ? convertNegation(convertInOp$1(filter[1], filter.slice(2))) : + op === 'has' ? convertHasOp$1(filter[1]) : + op === '!has' ? convertNegation(convertHasOp$1(filter[1])) : + true; + return converted; +} +function convertComparisonOp$1(property, value, op) { + switch (property) { + case '$type': + return [`filter-type-${op}`, value]; + case '$id': + return [`filter-id-${op}`, value]; + default: + return [`filter-${op}`, property, value]; + } +} +function convertDisjunctionOp(filters) { + return ['any'].concat(filters.map(convertFilter$1)); +} +function convertInOp$1(property, values) { + if (values.length === 0) { + return false; + } + switch (property) { + case '$type': + return ['filter-type-in', ['literal', values]]; + case '$id': + return ['filter-id-in', ['literal', values]]; + default: + if (values.length > 200 && !values.some(v => typeof v !== typeof values[0])) { + return ['filter-in-large', property, ['literal', values.sort(compare)]]; + } + else { + return ['filter-in-small', property, ['literal', values]]; + } + } +} +function convertHasOp$1(property) { + switch (property) { + case '$type': + return true; + case '$id': + return ['filter-has-id']; + default: + return ['filter-has', property]; + } +} +function convertNegation(filter) { + return ['!', filter]; +} + +/* + * Convert the given filter to an expression, storing the expected types for + * any feature properties referenced in expectedTypes. + * + * These expected types are needed in order to construct preflight type checks + * needed for handling 'any' filters. A preflight type check is necessary in + * order to mimic legacy filters' semantics around expected type mismatches. + * For example, consider the legacy filter: + * + * ["any", ["all", [">", "y", 0], [">", "y", 0]], [">", "x", 0]] + * + * Naively, we might convert this to the expression: + * + * ["any", ["all", [">", ["get", "y"], 0], [">", ["get", "z"], 0]], [">", ["get", "x"], 0]] + * + * But if we tried to evaluate this against, say `{x: 1, y: null, z: 0}`, the + * [">", ["get", "y"], 0] would cause an evaluation error, leading to the + * entire filter returning false. Legacy filter semantics, though, ask for + * [">", "y", 0] to simply return `false` when `y` is of the wrong type, + * allowing the subsequent terms of the outer "any" expression to be evaluated + * (resulting, in this case, in a `true` value, because x > 0). + * + * We account for this by inserting a preflight type-checking expression before + * each "any" term, allowing us to avoid evaluating the actual converted filter + * if any type mismatches would cause it to produce an evalaution error: + * + * ["any", + * ["case", + * ["all", ["==", ["typeof", ["get", "y"]], "number"], ["==", ["typeof", ["get", "z"], "number]], + * ["all", [">", ["get", "y"], 0], [">", ["get", "z"], 0]], + * false + * ], + * ["case", + * ["==", ["typeof", ["get", "x"], "number"]], + * [">", ["get", "x"], 0], + * false + * ] + * ] + * + * An alternative, possibly more direct approach would be to use type checks + * in the conversion of each comparison operator, so that the converted version + * of each individual ==, >=, etc. would mimic the legacy filter semantics. The + * downside of this approach is that it can lead to many more type checks than + * would otherwise be necessary: outside the context of an "any" expression, + * bailing out due to a runtime type error (expression semantics) and returning + * false (legacy filter semantics) are equivalent: they cause the filter to + * produce a `false` result. + */ +function convertFilter(filter, expectedTypes = {}) { + if (isExpressionFilter(filter)) + return filter; + if (!filter) + return true; + const legacyFilter = filter; + const legacyOp = legacyFilter[0]; + if (filter.length <= 1) + return (legacyOp !== 'any'); + switch (legacyOp) { + case '==': + case '!=': + case '<': + case '>': + case '<=': + case '>=': { + const [, property, value] = filter; + return convertComparisonOp(property, value, legacyOp, expectedTypes); + } + case 'any': { + const [, ...conditions] = legacyFilter; + const children = conditions.map((f) => { + const types = {}; + const child = convertFilter(f, types); + const typechecks = runtimeTypeChecks(types); + return typechecks === true ? child : ['case', typechecks, child, false]; + }); + return ['any', ...children]; + } + case 'all': { + const [, ...conditions] = legacyFilter; + const children = conditions.map(f => convertFilter(f, expectedTypes)); + return children.length > 1 ? ['all', ...children] : children[0]; + } + case 'none': { + const [, ...conditions] = legacyFilter; + return ['!', convertFilter(['any', ...conditions], {})]; + } + case 'in': { + const [, property, ...values] = legacyFilter; + return convertInOp(property, values); + } + case '!in': { + const [, property, ...values] = legacyFilter; + return convertInOp(property, values, true); + } + case 'has': + return convertHasOp(legacyFilter[1]); + case '!has': + return ['!', convertHasOp(legacyFilter[1])]; + default: + return true; + } +} +// Given a set of feature properties and an expected type for each one, +// construct an boolean expression that tests whether each property has the +// right type. +// E.g.: for {name: 'string', population: 'number'}, return +// [ 'all', +// ['==', ['typeof', ['get', 'name'], 'string']], +// ['==', ['typeof', ['get', 'population'], 'number]] +// ] +function runtimeTypeChecks(expectedTypes) { + const conditions = []; + for (const property in expectedTypes) { + const get = property === '$id' ? ['id'] : ['get', property]; + conditions.push(['==', ['typeof', get], expectedTypes[property]]); + } + if (conditions.length === 0) + return true; + if (conditions.length === 1) + return conditions[0]; + return ['all', ...conditions]; +} +function convertComparisonOp(property, value, op, expectedTypes) { + let get; + if (property === '$type') { + return [op, ['geometry-type'], value]; + } + else if (property === '$id') { + get = ['id']; + } + else { + get = ['get', property]; + } + if (expectedTypes && value !== null) { + const type = typeof value; + expectedTypes[property] = type; + } + if (op === '==' && property !== '$id' && value === null) { + return [ + 'all', + ['has', property], // missing property != null for legacy filters + ['==', get, null] + ]; + } + else if (op === '!=' && property !== '$id' && value === null) { + return [ + 'any', + ['!', ['has', property]], // missing property != null for legacy filters + ['!=', get, null] + ]; + } + return [op, get, value]; +} +function convertInOp(property, values, negate = false) { + if (values.length === 0) + return negate; + let get; + if (property === '$type') { + get = ['geometry-type']; + } + else if (property === '$id') { + get = ['id']; + } + else { + get = ['get', property]; + } + // Determine if the list of values to be searched is homogenously typed. + // If so (and if the type is string or number), then we can use a + // [match, input, [...values], true, false] construction rather than a + // bunch of `==` tests. + let uniformTypes = true; + const type = typeof values[0]; + for (const value of values) { + if (typeof value !== type) { + uniformTypes = false; + break; + } + } + if (uniformTypes && (type === 'string' || type === 'number')) { + // Match expressions must have unique values. + const uniqueValues = values.sort().filter((v, i) => i === 0 || values[i - 1] !== v); + return ['match', get, uniqueValues, !negate, negate]; + } + if (negate) { + return ['all', ...values.map(v => ['!=', get, v])]; + } + else { + return ['any', ...values.map(v => ['==', get, v])]; + } +} +function convertHasOp(property) { + if (property === '$type') { + return true; + } + else if (property === '$id') { + return ['!=', ['id'], null]; + } + else { + return ['has', property]; + } +} + +function convertLiteral(value) { + return typeof value === 'object' ? ['literal', value] : value; +} +function convertFunction(parameters, propertySpec) { + let stops = parameters.stops; + if (!stops) { + // identity function + return convertIdentityFunction(parameters, propertySpec); + } + const zoomAndFeatureDependent = stops && typeof stops[0][0] === 'object'; + const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + const zoomDependent = zoomAndFeatureDependent || !featureDependent; + stops = stops.map((stop) => { + if (!featureDependent && propertySpec.tokens && typeof stop[1] === 'string') { + return [stop[0], convertTokenString(stop[1])]; + } + return [stop[0], convertLiteral(stop[1])]; + }); + if (zoomAndFeatureDependent) { + return convertZoomAndPropertyFunction(parameters, propertySpec, stops); + } + else if (zoomDependent) { + return convertZoomFunction(parameters, propertySpec, stops); + } + else { + return convertPropertyFunction(parameters, propertySpec, stops); + } +} +function convertIdentityFunction(parameters, propertySpec) { + const get = ['get', parameters.property]; + if (parameters.default === undefined) { + // By default, expressions for string-valued properties get coerced. To preserve + // legacy function semantics, insert an explicit assertion instead. + return propertySpec.type === 'string' ? ['string', get] : get; + } + else if (propertySpec.type === 'enum') { + return [ + 'match', + get, + Object.keys(propertySpec.values), + get, + parameters.default + ]; + } + else { + const expression = [propertySpec.type === 'color' ? 'to-color' : propertySpec.type, get, convertLiteral(parameters.default)]; + if (propertySpec.type === 'array') { + expression.splice(1, 0, propertySpec.value, propertySpec.length || null); + } + return expression; + } +} +function getInterpolateOperator(parameters) { + switch (parameters.colorSpace) { + case 'hcl': return 'interpolate-hcl'; + case 'lab': return 'interpolate-lab'; + default: return 'interpolate'; + } +} +function convertZoomAndPropertyFunction(parameters, propertySpec, stops) { + const featureFunctionParameters = {}; + const featureFunctionStops = {}; + const zoomStops = []; + for (let s = 0; s < stops.length; s++) { + const stop = stops[s]; + const zoom = stop[0].zoom; + if (featureFunctionParameters[zoom] === undefined) { + featureFunctionParameters[zoom] = { + zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default, + }; + featureFunctionStops[zoom] = []; + zoomStops.push(zoom); + } + featureFunctionStops[zoom].push([stop[0].value, stop[1]]); + } + // the interpolation type for the zoom dimension of a zoom-and-property + // function is determined directly from the style property specification + // for which it's being used: linear for interpolatable properties, step + // otherwise. + const functionType = getFunctionType({}, propertySpec); + if (functionType === 'exponential') { + const expression = [getInterpolateOperator(parameters), ['linear'], ['zoom']]; + for (const z of zoomStops) { + const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]); + appendStopPair(expression, z, output, false); + } + return expression; + } + else { + const expression = ['step', ['zoom']]; + for (const z of zoomStops) { + const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]); + appendStopPair(expression, z, output, true); + } + fixupDegenerateStepCurve(expression); + return expression; + } +} +function coalesce(a, b) { + if (a !== undefined) + return a; + if (b !== undefined) + return b; +} +function getFallback(parameters, propertySpec) { + const defaultValue = convertLiteral(coalesce(parameters.default, propertySpec.default)); + /* + * Some fields with type: resolvedImage have an undefined default. + * Because undefined is an invalid value for resolvedImage, set fallback to + * an empty string instead of undefined to ensure output + * passes validation. + */ + if (defaultValue === undefined && propertySpec.type === 'resolvedImage') { + return ''; + } + return defaultValue; +} +function convertPropertyFunction(parameters, propertySpec, stops) { + const type = getFunctionType(parameters, propertySpec); + const get = ['get', parameters.property]; + if (type === 'categorical' && typeof stops[0][0] === 'boolean') { + const expression = ['case']; + for (const stop of stops) { + expression.push(['==', get, stop[0]], stop[1]); + } + expression.push(getFallback(parameters, propertySpec)); + return expression; + } + else if (type === 'categorical') { + const expression = ['match', get]; + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], false); + } + expression.push(getFallback(parameters, propertySpec)); + return expression; + } + else if (type === 'interval') { + const expression = ['step', ['number', get]]; + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], true); + } + fixupDegenerateStepCurve(expression); + return parameters.default === undefined ? expression : [ + 'case', + ['==', ['typeof', get], 'number'], + expression, + convertLiteral(parameters.default) + ]; + } + else if (type === 'exponential') { + const base = parameters.base !== undefined ? parameters.base : 1; + const expression = [ + getInterpolateOperator(parameters), + base === 1 ? ['linear'] : ['exponential', base], + ['number', get] + ]; + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], false); + } + return parameters.default === undefined ? expression : [ + 'case', + ['==', ['typeof', get], 'number'], + expression, + convertLiteral(parameters.default) + ]; + } + else { + throw new Error(`Unknown property function type ${type}`); + } +} +function convertZoomFunction(parameters, propertySpec, stops, input = ['zoom']) { + const type = getFunctionType(parameters, propertySpec); + let expression; + let isStep = false; + if (type === 'interval') { + expression = ['step', input]; + isStep = true; + } + else if (type === 'exponential') { + const base = parameters.base !== undefined ? parameters.base : 1; + expression = [getInterpolateOperator(parameters), base === 1 ? ['linear'] : ['exponential', base], input]; + } + else { + throw new Error(`Unknown zoom function type "${type}"`); + } + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], isStep); + } + fixupDegenerateStepCurve(expression); + return expression; +} +function fixupDegenerateStepCurve(expression) { + // degenerate step curve (i.e. a constant function): add a noop stop + if (expression[0] === 'step' && expression.length === 3) { + expression.push(0); + expression.push(expression[3]); + } +} +function appendStopPair(curve, input, output, isStep) { + // Skip duplicate stop values. They were not validated for functions, but they are for expressions. + // https://github.com/mapbox/mapbox-gl-js/issues/4107 + if (curve.length > 3 && input === curve[curve.length - 2]) { + return; + } + // step curves don't get the first input value, as it is redundant. + if (!(isStep && curve.length === 2)) { + curve.push(input); + } + curve.push(output); +} +function getFunctionType(parameters, propertySpec) { + if (parameters.type) { + return parameters.type; + } + else { + return propertySpec.expression.interpolated ? 'exponential' : 'interval'; + } +} +// "String with {name} token" => ["concat", "String with ", ["get", "name"], " token"] +function convertTokenString(s) { + const result = ['concat']; + const re = /{([^{}]+)}/g; + let pos = 0; + for (let match = re.exec(s); match !== null; match = re.exec(s)) { + const literal = s.slice(pos, re.lastIndex - match[0].length); + pos = re.lastIndex; + if (literal.length > 0) + result.push(literal); + result.push(['get', match[1]]); + } + if (result.length === 1) { + return s; + } + if (pos < s.length) { + result.push(s.slice(pos)); + } + else if (result.length === 2) { + return ['to-string', result[1]]; + } + return result; +} + +function getPropertyReference(propertyName) { + for (let i = 0; i < v8Spec.layout.length; i++) { + for (const key in v8Spec[v8Spec.layout[i]]) { + if (key === propertyName) + return v8Spec[v8Spec.layout[i]][key]; + } + } + for (let i = 0; i < v8Spec.paint.length; i++) { + for (const key in v8Spec[v8Spec.paint[i]]) { + if (key === propertyName) + return v8Spec[v8Spec.paint[i]][key]; + } + } + return null; +} +function eachSource(style, callback) { + for (const k in style.sources) { + callback(style.sources[k]); + } +} +function eachLayer(style, callback) { + for (const layer of style.layers) { + callback(layer); + } +} +function eachProperty(style, options, callback) { + function inner(layer, propertyType) { + const properties = layer[propertyType]; + if (!properties) + return; + Object.keys(properties).forEach((key) => { + callback({ + path: [layer.id, propertyType, key], + key, + value: properties[key], + reference: getPropertyReference(key), + set(x) { + properties[key] = x; + } + }); + }); + } + eachLayer(style, (layer) => { + if (options.paint) { + inner(layer, 'paint'); + } + if (options.layout) { + inner(layer, 'layout'); + } + }); +} + +function stringify$1(obj) { + const type = typeof obj; + if (type === 'number' || type === 'boolean' || type === 'string' || obj === undefined || obj === null) + return JSON.stringify(obj); + if (Array.isArray(obj)) { + let str = '['; + for (const val of obj) { + str += `${stringify$1(val)},`; + } + return `${str}]`; + } + const keys = Object.keys(obj).sort(); + let str = '{'; + for (let i = 0; i < keys.length; i++) { + str += `${JSON.stringify(keys[i])}:${stringify$1(obj[keys[i]])},`; + } + return `${str}}`; +} +function getKey(layer) { + let key = ''; + for (const k of refProperties) { + key += `/${stringify$1(layer[k])}`; + } + return key; +} +/** + * Given an array of layers, return an array of arrays of layers where all + * layers in each group have identical layout-affecting properties. These + * are the properties that were formerly used by explicit `ref` mechanism + * for layers: 'type', 'source', 'source-layer', 'minzoom', 'maxzoom', + * 'filter', and 'layout'. + * + * The input is not modified. The output layers are references to the + * input layers. + * + * @private + * @param {Array} layers + * @param {Object} [cachedKeys] - an object to keep already calculated keys. + * @returns {Array>} + */ +function groupByLayout(layers, cachedKeys) { + const groups = {}; + for (let i = 0; i < layers.length; i++) { + const k = (cachedKeys && cachedKeys[layers[i].id]) || getKey(layers[i]); + // update the cache if there is one + if (cachedKeys) + cachedKeys[layers[i].id] = k; + let group = groups[k]; + if (!group) { + group = groups[k] = []; + } + group.push(layers[i]); + } + const result = []; + for (const k in groups) { + result.push(groups[k]); + } + return result; +} + +function emptyStyle() { + const style = {}; + const version = v8Spec['$version']; + for (const styleKey in v8Spec['$root']) { + const spec = v8Spec['$root'][styleKey]; + if (spec.required) { + let value = null; + if (styleKey === 'version') { + value = version; + } + else { + if (spec.type === 'array') { + value = []; + } + else { + value = {}; + } + } + if (value != null) { + style[styleKey] = value; + } + } + } + return style; +} + +function validateConstants(options) { + const key = options.key; + const constants = options.value; + if (constants) { + return [new ValidationError(key, constants, 'constants have been deprecated as of v8')]; + } + else { + return []; + } +} + +// Turn jsonlint-lines-primitives objects into primitive objects +function unbundle(value) { + if (value instanceof Number || value instanceof String || value instanceof Boolean) { + return value.valueOf(); + } + else { + return value; + } +} +function deepUnbundle(value) { + if (Array.isArray(value)) { + return value.map(deepUnbundle); + } + else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) { + const unbundledValue = {}; + for (const key in value) { + unbundledValue[key] = deepUnbundle(value[key]); + } + return unbundledValue; + } + return unbundle(value); +} + +function validateObject(options) { + const key = options.key; + const object = options.value; + const elementSpecs = options.valueSpec || {}; + const elementValidators = options.objectElementValidators || {}; + const style = options.style; + const styleSpec = options.styleSpec; + const validateSpec = options.validateSpec; + let errors = []; + const type = getType(object); + if (type !== 'object') { + return [new ValidationError(key, object, `object expected, ${type} found`)]; + } + for (const objectKey in object) { + const elementSpecKey = objectKey.split('.')[0]; // treat 'paint.*' as 'paint' + const elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*']; + let validateElement; + if (elementValidators[elementSpecKey]) { + validateElement = elementValidators[elementSpecKey]; + } + else if (elementSpecs[elementSpecKey]) { + validateElement = validateSpec; + } + else if (elementValidators['*']) { + validateElement = elementValidators['*']; + } + else if (elementSpecs['*']) { + validateElement = validateSpec; + } + else { + errors.push(new ValidationError(key, object[objectKey], `unknown property "${objectKey}"`)); + continue; + } + errors = errors.concat(validateElement({ + key: (key ? `${key}.` : key) + objectKey, + value: object[objectKey], + valueSpec: elementSpec, + style, + styleSpec, + object, + objectKey, + validateSpec, + }, object)); + } + for (const elementSpecKey in elementSpecs) { + // Don't check `required` when there's a custom validator for that property. + if (elementValidators[elementSpecKey]) { + continue; + } + if (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey]['default'] === undefined && object[elementSpecKey] === undefined) { + errors.push(new ValidationError(key, object, `missing required property "${elementSpecKey}"`)); + } + } + return errors; +} + +function validateArray(options) { + const array = options.value; + const arraySpec = options.valueSpec; + const validateSpec = options.validateSpec; + const style = options.style; + const styleSpec = options.styleSpec; + const key = options.key; + const validateArrayElement = options.arrayElementValidator || validateSpec; + if (getType(array) !== 'array') { + return [new ValidationError(key, array, `array expected, ${getType(array)} found`)]; + } + if (arraySpec.length && array.length !== arraySpec.length) { + return [new ValidationError(key, array, `array length ${arraySpec.length} expected, length ${array.length} found`)]; + } + if (arraySpec['min-length'] && array.length < arraySpec['min-length']) { + return [new ValidationError(key, array, `array length at least ${arraySpec['min-length']} expected, length ${array.length} found`)]; + } + let arrayElementSpec = { + 'type': arraySpec.value, + 'values': arraySpec.values + }; + if (styleSpec.$version < 7) { + arrayElementSpec['function'] = arraySpec.function; + } + if (getType(arraySpec.value) === 'object') { + arrayElementSpec = arraySpec.value; + } + let errors = []; + for (let i = 0; i < array.length; i++) { + errors = errors.concat(validateArrayElement({ + array, + arrayIndex: i, + value: array[i], + valueSpec: arrayElementSpec, + validateSpec: options.validateSpec, + style, + styleSpec, + key: `${key}[${i}]` + })); + } + return errors; +} + +function validateNumber(options) { + const key = options.key; + const value = options.value; + const valueSpec = options.valueSpec; + let type = getType(value); + // eslint-disable-next-line no-self-compare + if (type === 'number' && value !== value) { + type = 'NaN'; + } + if (type !== 'number') { + return [new ValidationError(key, value, `number expected, ${type} found`)]; + } + if ('minimum' in valueSpec && value < valueSpec.minimum) { + return [new ValidationError(key, value, `${value} is less than the minimum value ${valueSpec.minimum}`)]; + } + if ('maximum' in valueSpec && value > valueSpec.maximum) { + return [new ValidationError(key, value, `${value} is greater than the maximum value ${valueSpec.maximum}`)]; + } + return []; +} + +function validateFunction(options) { + const functionValueSpec = options.valueSpec; + const functionType = unbundle(options.value.type); + let stopKeyType; + let stopDomainValues = {}; + let previousStopDomainValue; + let previousStopDomainZoom; + const isZoomFunction = functionType !== 'categorical' && options.value.property === undefined; + const isPropertyFunction = !isZoomFunction; + const isZoomAndPropertyFunction = getType(options.value.stops) === 'array' && + getType(options.value.stops[0]) === 'array' && + getType(options.value.stops[0][0]) === 'object'; + const errors = validateObject({ + key: options.key, + value: options.value, + valueSpec: options.styleSpec.function, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + stops: validateFunctionStops, + default: validateFunctionDefault + } + }); + if (functionType === 'identity' && isZoomFunction) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "property"')); + } + if (functionType !== 'identity' && !options.value.stops) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "stops"')); + } + if (functionType === 'exponential' && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'exponential functions not supported')); + } + if (options.styleSpec.$version >= 8) { + if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'property functions not supported')); + } + else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported')); + } + } + if ((functionType === 'categorical' || isZoomAndPropertyFunction) && options.value.property === undefined) { + errors.push(new ValidationError(options.key, options.value, '"property" property is required')); + } + return errors; + function validateFunctionStops(options) { + if (functionType === 'identity') { + return [new ValidationError(options.key, options.value, 'identity function may not have a "stops" property')]; + } + let errors = []; + const value = options.value; + errors = errors.concat(validateArray({ + key: options.key, + value, + valueSpec: options.valueSpec, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec, + arrayElementValidator: validateFunctionStop + })); + if (getType(value) === 'array' && value.length === 0) { + errors.push(new ValidationError(options.key, value, 'array must have at least one stop')); + } + return errors; + } + function validateFunctionStop(options) { + let errors = []; + const value = options.value; + const key = options.key; + if (getType(value) !== 'array') { + return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; + } + if (value.length !== 2) { + return [new ValidationError(key, value, `array length 2 expected, length ${value.length} found`)]; + } + if (isZoomAndPropertyFunction) { + if (getType(value[0]) !== 'object') { + return [new ValidationError(key, value, `object expected, ${getType(value[0])} found`)]; + } + if (value[0].zoom === undefined) { + return [new ValidationError(key, value, 'object stop key must have zoom')]; + } + if (value[0].value === undefined) { + return [new ValidationError(key, value, 'object stop key must have value')]; + } + if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) { + return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')]; + } + if (unbundle(value[0].zoom) !== previousStopDomainZoom) { + previousStopDomainZoom = unbundle(value[0].zoom); + previousStopDomainValue = undefined; + stopDomainValues = {}; + } + errors = errors.concat(validateObject({ + key: `${key}[0]`, + value: value[0], + valueSpec: { zoom: {} }, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { zoom: validateNumber, value: validateStopDomainValue } + })); + } + else { + errors = errors.concat(validateStopDomainValue({ + key: `${key}[0]`, + value: value[0], + valueSpec: {}, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec + }, value)); + } + if (isExpression(deepUnbundle(value[1]))) { + return errors.concat([new ValidationError(`${key}[1]`, value[1], 'expressions are not allowed in function stops.')]); + } + return errors.concat(options.validateSpec({ + key: `${key}[1]`, + value: value[1], + valueSpec: functionValueSpec, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec + })); + } + function validateStopDomainValue(options, stop) { + const type = getType(options.value); + const value = unbundle(options.value); + const reportValue = options.value !== null ? options.value : stop; + if (!stopKeyType) { + stopKeyType = type; + } + else if (type !== stopKeyType) { + return [new ValidationError(options.key, reportValue, `${type} stop domain type must match previous stop domain type ${stopKeyType}`)]; + } + if (type !== 'number' && type !== 'string' && type !== 'boolean') { + return [new ValidationError(options.key, reportValue, 'stop domain value must be a number, string, or boolean')]; + } + if (type !== 'number' && functionType !== 'categorical') { + let message = `number expected, ${type} found`; + if (supportsPropertyExpression(functionValueSpec) && functionType === undefined) { + message += '\nIf you intended to use a categorical function, specify `"type": "categorical"`.'; + } + return [new ValidationError(options.key, reportValue, message)]; + } + if (functionType === 'categorical' && type === 'number' && (!isFinite(value) || Math.floor(value) !== value)) { + return [new ValidationError(options.key, reportValue, `integer expected, found ${value}`)]; + } + if (functionType !== 'categorical' && type === 'number' && previousStopDomainValue !== undefined && value < previousStopDomainValue) { + return [new ValidationError(options.key, reportValue, 'stop domain values must appear in ascending order')]; + } + else { + previousStopDomainValue = value; + } + if (functionType === 'categorical' && value in stopDomainValues) { + return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')]; + } + else { + stopDomainValues[value] = true; + } + return []; + } + function validateFunctionDefault(options) { + return options.validateSpec({ + key: options.key, + value: options.value, + valueSpec: functionValueSpec, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec + }); + } +} + +function validateExpression(options) { + const expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec); + if (expression.result === 'error') { + return expression.value.map((error) => { + return new ValidationError(`${options.key}${error.key}`, options.value, error.message); + }); + } + const expressionObj = expression.value.expression || expression.value._styleExpression.expression; + if (options.expressionContext === 'property' && (options.propertyKey === 'text-font') && + !expressionObj.outputDefined()) { + return [new ValidationError(options.key, options.value, `Invalid data expression for "${options.propertyKey}". Output values must be contained as literals within the expression.`)]; + } + if (options.expressionContext === 'property' && options.propertyType === 'layout' && + (!isStateConstant(expressionObj))) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with layout properties.')]; + } + if (options.expressionContext === 'filter' && !isStateConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with filters.')]; + } + if (options.expressionContext && options.expressionContext.indexOf('cluster') === 0) { + if (!isGlobalPropertyConstant(expressionObj, ['zoom', 'feature-state'])) { + return [new ValidationError(options.key, options.value, '"zoom" and "feature-state" expressions are not supported with cluster properties.')]; + } + if (options.expressionContext === 'cluster-initial' && !isFeatureConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')]; + } + } + return []; +} + +function validateBoolean(options) { + const value = options.value; + const key = options.key; + const type = getType(value); + if (type !== 'boolean') { + return [new ValidationError(key, value, `boolean expected, ${type} found`)]; + } + return []; +} + +function validateColor(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + if (type !== 'string') { + return [new ValidationError(key, value, `color expected, ${type} found`)]; + } + if (!Color.parse(String(value))) { // cast String object to string primitive + return [new ValidationError(key, value, `color expected, "${value}" found`)]; + } + return []; +} + +function validateEnum(options) { + const key = options.key; + const value = options.value; + const valueSpec = options.valueSpec; + const errors = []; + if (Array.isArray(valueSpec.values)) { // <=v7 + if (valueSpec.values.indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, `expected one of [${valueSpec.values.join(', ')}], ${JSON.stringify(value)} found`)); + } + } + else { // >=v8 + if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, `expected one of [${Object.keys(valueSpec.values).join(', ')}], ${JSON.stringify(value)} found`)); + } + } + return errors; +} + +function validateFilter$1(options) { + if (isExpressionFilter(deepUnbundle(options.value))) { + return validateExpression(extendBy({}, options, { + expressionContext: 'filter', + valueSpec: { value: 'boolean' } + })); + } + else { + return validateNonExpressionFilter(options); + } +} +function validateNonExpressionFilter(options) { + const value = options.value; + const key = options.key; + if (getType(value) !== 'array') { + return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; + } + const styleSpec = options.styleSpec; + let type; + let errors = []; + if (value.length < 1) { + return [new ValidationError(key, value, 'filter array must have at least 1 element')]; + } + errors = errors.concat(validateEnum({ + key: `${key}[0]`, + value: value[0], + valueSpec: styleSpec.filter_operator, + style: options.style, + styleSpec: options.styleSpec + })); + switch (unbundle(value[0])) { + case '<': + case '<=': + case '>': + case '>=': + if (value.length >= 2 && unbundle(value[1]) === '$type') { + errors.push(new ValidationError(key, value, `"$type" cannot be use with operator "${value[0]}"`)); + } + /* falls through */ + case '==': + case '!=': + if (value.length !== 3) { + errors.push(new ValidationError(key, value, `filter array for operator "${value[0]}" must have 3 elements`)); + } + /* falls through */ + case 'in': + case '!in': + if (value.length >= 2) { + type = getType(value[1]); + if (type !== 'string') { + errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); + } + } + for (let i = 2; i < value.length; i++) { + type = getType(value[i]); + if (unbundle(value[1]) === '$type') { + errors = errors.concat(validateEnum({ + key: `${key}[${i}]`, + value: value[i], + valueSpec: styleSpec.geometry_type, + style: options.style, + styleSpec: options.styleSpec + })); + } + else if (type !== 'string' && type !== 'number' && type !== 'boolean') { + errors.push(new ValidationError(`${key}[${i}]`, value[i], `string, number, or boolean expected, ${type} found`)); + } + } + break; + case 'any': + case 'all': + case 'none': + for (let i = 1; i < value.length; i++) { + errors = errors.concat(validateNonExpressionFilter({ + key: `${key}[${i}]`, + value: value[i], + style: options.style, + styleSpec: options.styleSpec + })); + } + break; + case 'has': + case '!has': + type = getType(value[1]); + if (value.length !== 2) { + errors.push(new ValidationError(key, value, `filter array for "${value[0]}" operator must have 2 elements`)); + } + else if (type !== 'string') { + errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); + } + break; + } + return errors; +} + +function validateProperty(options, propertyType) { + const key = options.key; + const validateSpec = options.validateSpec; + const style = options.style; + const styleSpec = options.styleSpec; + const value = options.value; + const propertyKey = options.objectKey; + const layerSpec = styleSpec[`${propertyType}_${options.layerType}`]; + if (!layerSpec) + return []; + const transitionMatch = propertyKey.match(/^(.*)-transition$/); + if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) { + return validateSpec({ + key, + value, + valueSpec: styleSpec.transition, + style, + styleSpec + }); + } + const valueSpec = options.valueSpec || layerSpec[propertyKey]; + if (!valueSpec) { + return [new ValidationError(key, value, `unknown property "${propertyKey}"`)]; + } + let tokenMatch; + if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) { + return [new ValidationError(key, value, `"${propertyKey}" does not support interpolation syntax\n` + + `Use an identity property function instead: \`{ "type": "identity", "property": ${JSON.stringify(tokenMatch[1])} }\`.`)]; + } + const errors = []; + if (options.layerType === 'symbol') { + if (propertyKey === 'text-field' && style && !style.glyphs) { + errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property')); + } + if (propertyKey === 'text-font' && isFunction$1(deepUnbundle(value)) && unbundle(value.type) === 'identity') { + errors.push(new ValidationError(key, value, '"text-font" does not support identity functions')); + } + } + return errors.concat(validateSpec({ + key: options.key, + value, + valueSpec, + style, + styleSpec, + expressionContext: 'property', + propertyType, + propertyKey + })); +} + +function validatePaintProperty$1(options) { + return validateProperty(options, 'paint'); +} + +function validateLayoutProperty$1(options) { + return validateProperty(options, 'layout'); +} + +function validateLayer(options) { + let errors = []; + const layer = options.value; + const key = options.key; + const style = options.style; + const styleSpec = options.styleSpec; + if (!layer.type && !layer.ref) { + errors.push(new ValidationError(key, layer, 'either "type" or "ref" is required')); + } + let type = unbundle(layer.type); + const ref = unbundle(layer.ref); + if (layer.id) { + const layerId = unbundle(layer.id); + for (let i = 0; i < options.arrayIndex; i++) { + const otherLayer = style.layers[i]; + if (unbundle(otherLayer.id) === layerId) { + errors.push(new ValidationError(key, layer.id, `duplicate layer id "${layer.id}", previously used at line ${otherLayer.id.__line__}`)); + } + } + } + if ('ref' in layer) { + ['type', 'source', 'source-layer', 'filter', 'layout'].forEach((p) => { + if (p in layer) { + errors.push(new ValidationError(key, layer[p], `"${p}" is prohibited for ref layers`)); + } + }); + let parent; + style.layers.forEach((layer) => { + if (unbundle(layer.id) === ref) + parent = layer; + }); + if (!parent) { + errors.push(new ValidationError(key, layer.ref, `ref layer "${ref}" not found`)); + } + else if (parent.ref) { + errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer')); + } + else { + type = unbundle(parent.type); + } + } + else if (type !== 'background') { + if (!layer.source) { + errors.push(new ValidationError(key, layer, 'missing required property "source"')); + } + else { + const source = style.sources && style.sources[layer.source]; + const sourceType = source && unbundle(source.type); + if (!source) { + errors.push(new ValidationError(key, layer.source, `source "${layer.source}" not found`)); + } + else if (sourceType === 'vector' && type === 'raster') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a raster source`)); + } + else if (sourceType !== 'raster-dem' && type === 'hillshade') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a raster-dem source`)); + } + else if (sourceType === 'raster' && type !== 'raster') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a vector source`)); + } + else if (sourceType === 'vector' && !layer['source-layer']) { + errors.push(new ValidationError(key, layer, `layer "${layer.id}" must specify a "source-layer"`)); + } + else if (sourceType === 'raster-dem' && type !== 'hillshade') { + errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \'hillshade\'.')); + } + else if (type === 'line' && layer.paint && layer.paint['line-gradient'] && + (sourceType !== 'geojson' || !source.lineMetrics)) { + errors.push(new ValidationError(key, layer, `layer "${layer.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)); + } + } + } + errors = errors.concat(validateObject({ + key, + value: layer, + valueSpec: styleSpec.layer, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + objectElementValidators: { + '*'() { + return []; + }, + // We don't want to enforce the spec's `"requires": true` for backward compatibility with refs; + // the actual requirement is validated above. See https://github.com/mapbox/mapbox-gl-js/issues/5772. + type() { + return options.validateSpec({ + key: `${key}.type`, + value: layer.type, + valueSpec: styleSpec.layer.type, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + object: layer, + objectKey: 'type' + }); + }, + filter: validateFilter$1, + layout(options) { + return validateObject({ + layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + objectElementValidators: { + '*'(options) { + return validateLayoutProperty$1(extendBy({ layerType: type }, options)); + } + } + }); + }, + paint(options) { + return validateObject({ + layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + objectElementValidators: { + '*'(options) { + return validatePaintProperty$1(extendBy({ layerType: type }, options)); + } + } + }); + } + } + })); + return errors; +} + +function validateString(options) { + const value = options.value; + const key = options.key; + const type = getType(value); + if (type !== 'string') { + return [new ValidationError(key, value, `string expected, ${type} found`)]; + } + return []; +} + +function validateRasterDEMSource(options) { + var _a; + const sourceName = (_a = options.sourceName) !== null && _a !== void 0 ? _a : ''; + const rasterDEM = options.value; + const styleSpec = options.styleSpec; + const rasterDEMSpec = styleSpec.source_raster_dem; + const style = options.style; + let errors = []; + const rootType = getType(rasterDEM); + if (rasterDEM === undefined) { + return errors; + } + else if (rootType !== 'object') { + errors.push(new ValidationError('source_raster_dem', rasterDEM, `object expected, ${rootType} found`)); + return errors; + } + const encoding = unbundle(rasterDEM.encoding); + const isCustomEncoding = encoding === 'custom'; + const customEncodingKeys = ['redFactor', 'greenFactor', 'blueFactor', 'baseShift']; + const encodingName = options.value.encoding ? `"${options.value.encoding}"` : 'Default'; + for (const key in rasterDEM) { + if (!isCustomEncoding && customEncodingKeys.includes(key)) { + errors.push(new ValidationError(key, rasterDEM[key], `In "${sourceName}": "${key}" is only valid when "encoding" is set to "custom". ${encodingName} encoding found`)); + } + else if (rasterDEMSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: rasterDEM[key], + valueSpec: rasterDEMSpec[key], + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else { + errors.push(new ValidationError(key, rasterDEM[key], `unknown property "${key}"`)); + } + } + return errors; +} + +const objectElementValidators = { + promoteId: validatePromoteId +}; +function validateSource$1(options) { + const value = options.value; + const key = options.key; + const styleSpec = options.styleSpec; + const style = options.style; + const validateSpec = options.validateSpec; + if (!value.type) { + return [new ValidationError(key, value, '"type" is required')]; + } + const type = unbundle(value.type); + let errors; + switch (type) { + case 'vector': + case 'raster': + errors = validateObject({ + key, + value, + valueSpec: styleSpec[`source_${type.replace('-', '_')}`], + style: options.style, + styleSpec, + objectElementValidators, + validateSpec, + }); + return errors; + case 'raster-dem': + errors = validateRasterDEMSource({ + sourceName: key, + value, + style: options.style, + styleSpec, + validateSpec, + }); + return errors; + case 'geojson': + errors = validateObject({ + key, + value, + valueSpec: styleSpec.source_geojson, + style, + styleSpec, + validateSpec, + objectElementValidators + }); + if (value.cluster) { + for (const prop in value.clusterProperties) { + const [operator, mapExpr] = value.clusterProperties[prop]; + const reduceExpr = typeof operator === 'string' ? [operator, ['accumulated'], ['get', prop]] : operator; + errors.push(...validateExpression({ + key: `${key}.${prop}.map`, + value: mapExpr, + validateSpec, + expressionContext: 'cluster-map' + })); + errors.push(...validateExpression({ + key: `${key}.${prop}.reduce`, + value: reduceExpr, + validateSpec, + expressionContext: 'cluster-reduce' + })); + } + } + return errors; + case 'video': + return validateObject({ + key, + value, + valueSpec: styleSpec.source_video, + style, + validateSpec, + styleSpec + }); + case 'image': + return validateObject({ + key, + value, + valueSpec: styleSpec.source_image, + style, + validateSpec, + styleSpec + }); + case 'canvas': + return [new ValidationError(key, null, 'Please use runtime APIs to add canvas sources, rather than including them in stylesheets.', 'source.canvas')]; + default: + return validateEnum({ + key: `${key}.type`, + value: value.type, + valueSpec: { values: ['vector', 'raster', 'raster-dem', 'geojson', 'video', 'image'] }, + style, + validateSpec, + styleSpec + }); + } +} +function validatePromoteId({ key, value }) { + if (getType(value) === 'string') { + return validateString({ key, value }); + } + else { + const errors = []; + for (const prop in value) { + errors.push(...validateString({ key: `${key}.${prop}`, value: value[prop] })); + } + return errors; + } +} + +function validateLight$1(options) { + const light = options.value; + const styleSpec = options.styleSpec; + const lightSpec = styleSpec.light; + const style = options.style; + let errors = []; + const rootType = getType(light); + if (light === undefined) { + return errors; + } + else if (rootType !== 'object') { + errors = errors.concat([new ValidationError('light', light, `object expected, ${rootType} found`)]); + return errors; + } + for (const key in light) { + const transitionMatch = key.match(/^(.*)-transition$/); + if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) { + errors = errors.concat(options.validateSpec({ + key, + value: light[key], + valueSpec: styleSpec.transition, + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else if (lightSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: light[key], + valueSpec: lightSpec[key], + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, light[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +function validateSky$1(options) { + const sky = options.value; + const styleSpec = options.styleSpec; + const skySpec = styleSpec.sky; + const style = options.style; + const rootType = getType(sky); + if (sky === undefined) { + return []; + } + else if (rootType !== 'object') { + return [new ValidationError('sky', sky, `object expected, ${rootType} found`)]; + } + let errors = []; + for (const key in sky) { + if (skySpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: sky[key], + valueSpec: skySpec[key], + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, sky[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +function validateTerrain$1(options) { + const terrain = options.value; + const styleSpec = options.styleSpec; + const terrainSpec = styleSpec.terrain; + const style = options.style; + let errors = []; + const rootType = getType(terrain); + if (terrain === undefined) { + return errors; + } + else if (rootType !== 'object') { + errors = errors.concat([new ValidationError('terrain', terrain, `object expected, ${rootType} found`)]); + return errors; + } + for (const key in terrain) { + if (terrainSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: terrain[key], + valueSpec: terrainSpec[key], + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, terrain[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +function validateFormatted(options) { + if (validateString(options).length === 0) { + return []; + } + return validateExpression(options); +} + +function validateImage(options) { + if (validateString(options).length === 0) { + return []; + } + return validateExpression(options); +} + +function validatePadding(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + if (type === 'array') { + if (value.length < 1 || value.length > 4) { + return [new ValidationError(key, value, `padding requires 1 to 4 values; ${value.length} values found`)]; + } + const arrayElementSpec = { + type: 'number' + }; + let errors = []; + for (let i = 0; i < value.length; i++) { + errors = errors.concat(options.validateSpec({ + key: `${key}[${i}]`, + value: value[i], + validateSpec: options.validateSpec, + valueSpec: arrayElementSpec + })); + } + return errors; + } + else { + return validateNumber({ + key, + value, + valueSpec: {} + }); + } +} + +function validateVariableAnchorOffsetCollection(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + const styleSpec = options.styleSpec; + if (type !== 'array' || value.length < 1 || value.length % 2 !== 0) { + return [new ValidationError(key, value, 'variableAnchorOffsetCollection requires a non-empty array of even length')]; + } + let errors = []; + for (let i = 0; i < value.length; i += 2) { + // Elements in even positions should be values from text-anchor enum + errors = errors.concat(validateEnum({ + key: `${key}[${i}]`, + value: value[i], + valueSpec: styleSpec['layout_symbol']['text-anchor'] + })); + // Elements in odd positions should be points (2-element numeric arrays) + errors = errors.concat(validateArray({ + key: `${key}[${i + 1}]`, + value: value[i + 1], + valueSpec: { + length: 2, + value: 'number' + }, + validateSpec: options.validateSpec, + style: options.style, + styleSpec + })); + } + return errors; +} + +function validateSprite(options) { + let errors = []; + const sprite = options.value; + const key = options.key; + if (!Array.isArray(sprite)) { + return validateString({ + key, + value: sprite + }); + } + else { + const allSpriteIds = []; + const allSpriteURLs = []; + for (const i in sprite) { + if (sprite[i].id && allSpriteIds.includes(sprite[i].id)) + errors.push(new ValidationError(key, sprite, `all the sprites' ids must be unique, but ${sprite[i].id} is duplicated`)); + allSpriteIds.push(sprite[i].id); + if (sprite[i].url && allSpriteURLs.includes(sprite[i].url)) + errors.push(new ValidationError(key, sprite, `all the sprites' URLs must be unique, but ${sprite[i].url} is duplicated`)); + allSpriteURLs.push(sprite[i].url); + const pairSpec = { + id: { + type: 'string', + required: true, + }, + url: { + type: 'string', + required: true, + } + }; + errors = errors.concat(validateObject({ + key: `${key}[${i}]`, + value: sprite[i], + valueSpec: pairSpec, + validateSpec: options.validateSpec, + })); + } + return errors; + } +} + +function validateProjection(options) { + const projection = options.value; + const styleSpec = options.styleSpec; + const projectionSpec = styleSpec.projection; + const style = options.style; + const rootType = getType(projection); + if (projection === undefined) { + return []; + } + else if (rootType !== 'object') { + return [new ValidationError('projection', projection, `object expected, ${rootType} found`)]; + } + let errors = []; + for (const key in projection) { + if (projectionSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: projection[key], + valueSpec: projectionSpec[key], + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, projection[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +const VALIDATORS = { + '*'() { + return []; + }, + 'array': validateArray, + 'boolean': validateBoolean, + 'number': validateNumber, + 'color': validateColor, + 'constants': validateConstants, + 'enum': validateEnum, + 'filter': validateFilter$1, + 'function': validateFunction, + 'layer': validateLayer, + 'object': validateObject, + 'source': validateSource$1, + 'light': validateLight$1, + 'sky': validateSky$1, + 'terrain': validateTerrain$1, + 'projection': validateProjection, + 'string': validateString, + 'formatted': validateFormatted, + 'resolvedImage': validateImage, + 'padding': validatePadding, + 'variableAnchorOffsetCollection': validateVariableAnchorOffsetCollection, + 'sprite': validateSprite, +}; +/** + * Main recursive validation function used internally. + * You should use `validateStyleMin` in the browser or `validateStyle` in node env. + * @param options - the options object + * @param options.key - string representing location of validation in style tree. Used only + * for more informative error reporting. + * @param options.value - current value from style being evaluated. May be anything from a + * high level object that needs to be descended into deeper or a simple + * scalar value. + * @param options.valueSpec - current spec being evaluated. Tracks value. + * @param options.styleSpec - current full spec being evaluated. + * @param options.validateSpec - the validate function itself + * @param options.style - the style object + * @param options.objectElementValidators - optional object of functions that will be called + * @returns an array of errors, or an empty array if no errors are found. + */ +function validate(options) { + const value = options.value; + const valueSpec = options.valueSpec; + const styleSpec = options.styleSpec; + options.validateSpec = validate; + if (valueSpec.expression && isFunction$1(unbundle(value))) { + return validateFunction(options); + } + else if (valueSpec.expression && isExpression(deepUnbundle(value))) { + return validateExpression(options); + } + else if (valueSpec.type && VALIDATORS[valueSpec.type]) { + return VALIDATORS[valueSpec.type](options); + } + else { + const valid = validateObject(extendBy({}, options, { + valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec + })); + return valid; + } +} + +function validateGlyphsUrl(options) { + const value = options.value; + const key = options.key; + const errors = validateString(options); + if (errors.length) + return errors; + if (value.indexOf('{fontstack}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{fontstack}" token')); + } + if (value.indexOf('{range}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{range}" token')); + } + return errors; +} + +/** + * Validate a MapLibre style against the style specification. + * Use this when running in the browser. + * + * @param style - The style to be validated. + * @param styleSpec - The style specification to validate against. + * If omitted, the latest style spec is used. + * @returns an array of errors, or an empty array if no errors are found. + * @example + * const validate = require('@maplibre/maplibre-gl-style-spec/').validateStyleMin; + * const errors = validate(style); + */ +function validateStyleMin(style, styleSpec = v8Spec) { + let errors = []; + errors = errors.concat(validate({ + key: '', + value: style, + valueSpec: styleSpec.$root, + styleSpec, + style, + validateSpec: validate, + objectElementValidators: { + glyphs: validateGlyphsUrl, + '*'() { + return []; + } + } + })); + if (style['constants']) { + errors = errors.concat(validateConstants({ + key: 'constants', + value: style['constants'], + style, + styleSpec, + validateSpec: validate, + })); + } + return sortErrors(errors); +} +validateStyleMin.source = wrapCleanErrors(injectValidateSpec(validateSource$1)); +validateStyleMin.sprite = wrapCleanErrors(injectValidateSpec(validateSprite)); +validateStyleMin.glyphs = wrapCleanErrors(injectValidateSpec(validateGlyphsUrl)); +validateStyleMin.light = wrapCleanErrors(injectValidateSpec(validateLight$1)); +validateStyleMin.sky = wrapCleanErrors(injectValidateSpec(validateSky$1)); +validateStyleMin.terrain = wrapCleanErrors(injectValidateSpec(validateTerrain$1)); +validateStyleMin.layer = wrapCleanErrors(injectValidateSpec(validateLayer)); +validateStyleMin.filter = wrapCleanErrors(injectValidateSpec(validateFilter$1)); +validateStyleMin.paintProperty = wrapCleanErrors(injectValidateSpec(validatePaintProperty$1)); +validateStyleMin.layoutProperty = wrapCleanErrors(injectValidateSpec(validateLayoutProperty$1)); +function injectValidateSpec(validator) { + return function (options) { + return validator({ + ...options, + validateSpec: validate, + }); + }; +} +function sortErrors(errors) { + return [].concat(errors).sort((a, b) => { + return a.line - b.line; + }); +} +function wrapCleanErrors(inner) { + return function (...args) { + return sortErrors(inner.apply(this, args)); + }; +} + +// Note: This regex matches even invalid JSON strings, but since we’re +// working on the output of `JSON.stringify` we know that only valid strings +// are present (unless the user supplied a weird `options.indent` but in +// that case we don’t care since the output would be invalid anyway). +const stringOrChar = /("(?:[^\\"]|\\.)*")|[:,]/g; + +function stringify(passedObj, options = {}) { + const indent = JSON.stringify( + [1], + undefined, + options.indent === undefined ? 2 : options.indent + ).slice(2, -3); + + const maxLength = + indent === "" + ? Infinity + : options.maxLength === undefined + ? 80 + : options.maxLength; + + let { replacer } = options; + + return (function _stringify(obj, currentIndent, reserved) { + if (obj && typeof obj.toJSON === "function") { + obj = obj.toJSON(); + } + + const string = JSON.stringify(obj, replacer); + + if (string === undefined) { + return string; + } + + const length = maxLength - currentIndent.length - reserved; + + if (string.length <= length) { + const prettified = string.replace( + stringOrChar, + (match, stringLiteral) => { + return stringLiteral || `${match} `; + } + ); + if (prettified.length <= length) { + return prettified; + } + } + + if (replacer != null) { + obj = JSON.parse(string); + replacer = undefined; + } + + if (typeof obj === "object" && obj !== null) { + const nextIndent = currentIndent + indent; + const items = []; + let index = 0; + let start; + let end; + + if (Array.isArray(obj)) { + start = "["; + end = "]"; + const { length } = obj; + for (; index < length; index++) { + items.push( + _stringify(obj[index], nextIndent, index === length - 1 ? 0 : 1) || + "null" + ); + } + } else { + start = "{"; + end = "}"; + const keys = Object.keys(obj); + const { length } = keys; + for (; index < length; index++) { + const key = keys[index]; + const keyPart = `${JSON.stringify(key)}: `; + const value = _stringify( + obj[key], + nextIndent, + keyPart.length + (index === length - 1 ? 0 : 1) + ); + if (value !== undefined) { + items.push(keyPart + value); + } + } + } + + if (items.length > 0) { + return [start, indent + items.join(`,\n${nextIndent}`), end].join( + `\n${currentIndent}` + ); + } + } + + return string; + })(passedObj, "", 0); +} + +function sortKeysBy(obj, reference) { + const result = {}; + for (const key in reference) { + if (obj[key] !== undefined) { + result[key] = obj[key]; + } + } + for (const key in obj) { + if (result[key] === undefined) { + result[key] = obj[key]; + } + } + return result; +} +/** + * Format a MapLibre Style. Returns a stringified style with its keys + * sorted in the same order as the reference style. + * + * The optional `space` argument is passed to + * [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) + * to generate formatted output. + * + * If `space` is unspecified, a default of `2` spaces will be used. + * + * @private + * @param {Object} style a MapLibre Style + * @param {number} [space] space argument to pass to `JSON.stringify` + * @returns {string} stringified formatted JSON + * @example + * var fs = require('fs'); + * var format = require('maplibre-gl-style-spec').format; + * var style = fs.readFileSync('./source.json', 'utf8'); + * fs.writeFileSync('./dest.json', format(style)); + * fs.writeFileSync('./dest.min.json', format(style, 0)); + */ +function format(style, space = 2) { + style = sortKeysBy(style, v8Spec.$root); + if (style.layers) { + style.layers = style.layers.map((layer) => sortKeysBy(layer, v8Spec.layer)); + } + return stringify(style, { indent: space }); +} + +function eachLayout(layer, callback) { + for (const k in layer) { + if (k.indexOf('layout') === 0) { + callback(layer[k], k); + } + } +} +function eachPaint(layer, callback) { + for (const k in layer) { + if (k.indexOf('paint') === 0) { + callback(layer[k], k); + } + } +} +function resolveConstant(style, value) { + if (typeof value === 'string' && value[0] === '@') { + return resolveConstant(style, style.constants[value]); + } + else { + return value; + } +} +function isFunction(value) { + return Array.isArray(value.stops); +} +function renameProperty(obj, from, to) { + obj[to] = obj[from]; + delete obj[from]; +} +function migrateV8(style) { + style.version = 8; + // Rename properties, reverse coordinates in source and layers + eachSource(style, (source) => { + if (source.type === 'video' && source['url'] !== undefined) { + renameProperty(source, 'url', 'urls'); + } + if (source.type === 'video') { + source.coordinates.forEach((coord) => { + return coord.reverse(); + }); + } + }); + eachLayer(style, (layer) => { + eachLayout(layer, (layout) => { + if (layout['symbol-min-distance'] !== undefined) { + renameProperty(layout, 'symbol-min-distance', 'symbol-spacing'); + } + }); + eachPaint(layer, (paint) => { + if (paint['background-image'] !== undefined) { + renameProperty(paint, 'background-image', 'background-pattern'); + } + if (paint['line-image'] !== undefined) { + renameProperty(paint, 'line-image', 'line-pattern'); + } + if (paint['fill-image'] !== undefined) { + renameProperty(paint, 'fill-image', 'fill-pattern'); + } + }); + }); + // Inline Constants + eachProperty(style, { paint: true, layout: true }, (property) => { + const value = resolveConstant(style, property.value); + if (isFunction(value)) { + value.stops.forEach((stop) => { + stop[1] = resolveConstant(style, stop[1]); + }); + } + property.set(value); + }); + delete style['constants']; + eachLayer(style, (layer) => { + // get rid of text-max-size, icon-max-size + // turn text-size, icon-size into layout properties + // https://github.com/mapbox/mapbox-gl-style-spec/issues/255 + eachLayout(layer, (layout) => { + delete layout['text-max-size']; + delete layout['icon-max-size']; + }); + eachPaint(layer, (paint) => { + if (paint['text-size']) { + if (!layer.layout) + layer.layout = {}; + layer.layout['text-size'] = paint['text-size']; + delete paint['text-size']; + } + if (paint['icon-size']) { + if (!layer.layout) + layer.layout = {}; + layer.layout['icon-size'] = paint['icon-size']; + delete paint['icon-size']; + } + }); + }); + function migrateFontStack(font) { + function splitAndTrim(string) { + return string.split(',').map((s) => { + return s.trim(); + }); + } + if (Array.isArray(font)) { + // Assume it's a previously migrated font-array. + return font; + } + else if (typeof font === 'string') { + return splitAndTrim(font); + } + else if (typeof font === 'object') { + font.stops.forEach((stop) => { + stop[1] = splitAndTrim(stop[1]); + }); + return font; + } + else { + throw new Error('unexpected font value'); + } + } + eachLayer(style, (layer) => { + eachLayout(layer, (layout) => { + if (layout['text-font']) { + layout['text-font'] = migrateFontStack(layout['text-font']); + } + }); + }); + // Reverse order of symbol layers. This is an imperfect migration. + // + // The order of a symbol layer in the layers list affects two things: + // - how it is drawn relative to other layers (like oneway arrows below bridges) + // - the placement priority compared to other layers + // + // It's impossible to reverse the placement priority without breaking the draw order + // in some cases. This migration only reverses the order of symbol layers that + // are above all other types of layers. + // + // Symbol layers that are at the top of the map preserve their priority. + // Symbol layers that are below another type (line, fill) of layer preserve their draw order. + let firstSymbolLayer = 0; + for (let i = style.layers.length - 1; i >= 0; i--) { + const layer = style.layers[i]; + if (layer.type !== 'symbol') { + firstSymbolLayer = i + 1; + break; + } + } + const symbolLayers = style.layers.splice(firstSymbolLayer); + symbolLayers.reverse(); + style.layers = style.layers.concat(symbolLayers); + return style; +} + +/** + * Migrate the given style object in place to use expressions. Specifically, + * this will convert (a) "stop" functions, and (b) legacy filters to their + * expression equivalents. + * @param style The style object to migrate. + * @returns The migrated style object. + */ +function expressions(style) { + const converted = []; + eachLayer(style, (layer) => { + if (layer.filter) { + layer.filter = convertFilter(layer.filter); + } + }); + eachProperty(style, { paint: true, layout: true }, ({ path, value, reference, set }) => { + if (isExpression(value)) + return; + if (typeof value === 'object' && !Array.isArray(value)) { + set(convertFunction(value, reference)); + converted.push(path.join('.')); + } + else if (reference.tokens && typeof value === 'string') { + set(convertTokenString(value)); + } + }); + return style; +} + +/** + * Migrate color style values to supported format. + * + * @param colorToMigrate Color value to migrate, could be a string or an expression. + * @returns Color style value in supported format. + */ +function migrateColors(colorToMigrate) { + return JSON.parse(migrateHslColors(JSON.stringify(colorToMigrate))); +} +/** + * Created to migrate from colors supported by the former CSS color parsing + * library `csscolorparser` but not compliant with the CSS Color specification, + * like `hsl(900, 0.15, 90%)`. + * + * @param colorToMigrate Serialized color style value. + * @returns A serialized color style value in which all non-standard hsl color values + * have been converted to a format that complies with the CSS Color specification. + * + * @example + * migrateHslColors('"hsl(900, 0.15, 90%)"'); // returns '"hsl(900, 15%, 90%)"' + * migrateHslColors('"hsla(900, .15, .9)"'); // returns '"hsl(900, 15%, 90%)"' + * migrateHslColors('"hsl(900, 15%, 90%)"'); // returns '"hsl(900, 15%, 90%)"' - no changes + */ +function migrateHslColors(colorToMigrate) { + return colorToMigrate.replace(/"hsla?\((.+?)\)"/gi, (match, hslArgs) => { + const argsMatch = hslArgs.match(/^(.+?)\s*,\s*(.+?)\s*,\s*(.+?)(?:\s*,\s*(.+))?$/i); + if (argsMatch) { + let [h, s, l, a] = argsMatch.slice(1); + [s, l] = [s, l].map(v => v.endsWith('%') ? v : `${parseFloat(v) * 100}%`); + return `"hsl${typeof a === 'string' ? 'a' : ''}(${[h, s, l, a].filter(Boolean).join(',')})"`; + } + return match; + }); +} + +/** + * Migrate a Mapbox/MapLibre GL Style to the latest version. + * + * @param style - a MapLibre Style + * @returns a migrated style + * @example + * const fs = require('fs'); + * csont migrate = require('@maplibre/maplibre-gl-style-spec').migrate; + * const style = fs.readFileSync('./style.json', 'utf8'); + * fs.writeFileSync('./style.json', JSON.stringify(migrate(style))); + */ +function migrate(style) { + let migrated = false; + if (style.version === 7) { + style = migrateV8(style); + migrated = true; + } + if (style.version === 8) { + migrated = !!expressions(style); + migrated = true; + } + eachProperty(style, { paint: true, layout: true }, ({ value, reference, set }) => { + if (reference.type === 'color') { + set(migrateColors(value)); + } + }); + if (!migrated) { + throw new Error(`Cannot migrate from ${style.version}`); + } + return style; +} + +const v8 = v8Spec; +const expression = { + StyleExpression, + StylePropertyFunction, + ZoomConstantExpression, + ZoomDependentExpression, + createExpression, + createPropertyExpression, + isExpression, + isExpressionFilter, + isZoomExpression, + normalizePropertyExpression, +}; +const styleFunction = { + convertFunction, + createFunction, + isFunction: isFunction$1 +}; +const visit = { eachLayer, eachProperty, eachSource }; + +/** + * An error message to use when an operation is aborted + */ +const ABORT_ERROR = 'AbortError'; +/** + * Check if an error is an abort error + * @param error - An error object + * @returns - true if the error is an abort error + */ +function isAbortError(error) { + return error.message === ABORT_ERROR; +} +/** + * Use this when you need to create an abort error. + * @returns An error object with the message "AbortError" + */ +function createAbortError() { + return new Error(ABORT_ERROR); +} + +const config = { + MAX_PARALLEL_IMAGE_REQUESTS: 16, + MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME: 8, + MAX_TILE_CACHE_ZOOM_LEVELS: 5, + REGISTERED_PROTOCOLS: {}, + WORKER_URL: '' +}; + +function getProtocol(url) { + return config.REGISTERED_PROTOCOLS[url.substring(0, url.indexOf('://'))]; +} +/** + * Adds a custom load resource function that will be called when using a URL that starts with a custom url schema. + * This will happen in the main thread, and workers might call it if they don't know how to handle the protocol. + * The example below will be triggered for custom:// urls defined in the sources list in the style definitions. + * The function passed will receive the request parameters and should return with the resulting resource, + * for example a pbf vector tile, non-compressed, represented as ArrayBuffer. + * + * @param customProtocol - the protocol to hook, for example 'custom' + * @param loadFn - the function to use when trying to fetch a tile specified by the customProtocol + * @example + * ```ts + * // This will fetch a file using the fetch API (this is obviously a non interesting example...) + * addProtocol('custom', async (params, abortController) => { + * const t = await fetch(`https://${params.url.split("://")[1]}`); + * if (t.status == 200) { + * const buffer = await t.arrayBuffer(); + * return {data: buffer} + * } else { + * throw new Error(`Tile fetch error: ${t.statusText}`); + * } + * }); + * // the following is an example of a way to return an error when trying to load a tile + * addProtocol('custom2', async (params, abortController) => { + * throw new Error('someErrorMessage')); + * }); + * ``` + */ +function addProtocol(customProtocol, loadFn) { + config.REGISTERED_PROTOCOLS[customProtocol] = loadFn; +} +/** + * Removes a previously added protocol in the main thread. + * + * @param customProtocol - the custom protocol to remove registration for + * @example + * ```ts + * removeProtocol('custom'); + * ``` + */ +function removeProtocol(customProtocol) { + delete config.REGISTERED_PROTOCOLS[customProtocol]; +} + +/** + * This is used to identify the global dispatcher id when sending a message from the worker without a target map id. + */ +const GLOBAL_DISPATCHER_ID = 'global-dispatcher'; +/** + * An error thrown when a HTTP request results in an error response. + */ +class AJAXError extends Error { + /** + * @param status - The response's HTTP status code. + * @param statusText - The response's HTTP status text. + * @param url - The request's URL. + * @param body - The response's body. + */ + constructor(status, statusText, url, body) { + super(`AJAXError: ${statusText} (${status}): ${url}`); + this.status = status; + this.statusText = statusText; + this.url = url; + this.body = body; + } +} +/** + * Ensure that we're sending the correct referrer from blob URL worker bundles. + * For files loaded from the local file system, `location.origin` will be set + * to the string(!) "null" (Firefox), or "file://" (Chrome, Safari, Edge), + * and we will set an empty referrer. Otherwise, we're using the document's URL. + */ +const getReferrer = () => isWorker(self) ? + self.worker && self.worker.referrer : + (window.location.protocol === 'blob:' ? window.parent : window).location.href; +/** + * Determines whether a URL is a file:// URL. This is obviously the case if it begins + * with file://. Relative URLs are also file:// URLs iff the original document was loaded + * via a file:// URL. + * @param url - The URL to check + * @returns `true` if the URL is a file:// URL, `false` otherwise + */ +const isFileURL = url => /^file:/.test(url) || (/^file:/.test(getReferrer()) && !/^\w+:/.test(url)); +function makeFetchRequest(requestParameters, abortController) { + return __awaiter(this, void 0, void 0, function* () { + const request = new Request(requestParameters.url, { + method: requestParameters.method || 'GET', + body: requestParameters.body, + credentials: requestParameters.credentials, + headers: requestParameters.headers, + cache: requestParameters.cache, + referrer: getReferrer(), + signal: abortController.signal + }); + // If the user has already set an Accept header, do not overwrite it here + if (requestParameters.type === 'json' && !request.headers.has('Accept')) { + request.headers.set('Accept', 'application/json'); + } + const response = yield fetch(request); + if (!response.ok) { + const body = yield response.blob(); + throw new AJAXError(response.status, response.statusText, requestParameters.url, body); + } + let parsePromise; + if ((requestParameters.type === 'arrayBuffer' || requestParameters.type === 'image')) { + parsePromise = response.arrayBuffer(); + } + else if (requestParameters.type === 'json') { + parsePromise = response.json(); + } + else { + parsePromise = response.text(); + } + const result = yield parsePromise; + if (abortController.signal.aborted) { + throw createAbortError(); + } + return { data: result, cacheControl: response.headers.get('Cache-Control'), expires: response.headers.get('Expires') }; + }); +} +function makeXMLHttpRequest(requestParameters, abortController) { + return new Promise((resolve, reject) => { + var _a; + const xhr = new XMLHttpRequest(); + xhr.open(requestParameters.method || 'GET', requestParameters.url, true); + if (requestParameters.type === 'arrayBuffer' || requestParameters.type === 'image') { + xhr.responseType = 'arraybuffer'; + } + for (const k in requestParameters.headers) { + xhr.setRequestHeader(k, requestParameters.headers[k]); + } + if (requestParameters.type === 'json') { + xhr.responseType = 'text'; + // Do not overwrite the user-provided Accept header + if (!((_a = requestParameters.headers) === null || _a === void 0 ? void 0 : _a.Accept)) { + xhr.setRequestHeader('Accept', 'application/json'); + } + } + xhr.withCredentials = requestParameters.credentials === 'include'; + xhr.onerror = () => { + reject(new Error(xhr.statusText)); + }; + xhr.onload = () => { + if (abortController.signal.aborted) { + return; + } + if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response !== null) { + let data = xhr.response; + if (requestParameters.type === 'json') { + // We're manually parsing JSON here to get better error messages. + try { + data = JSON.parse(xhr.response); + } + catch (err) { + reject(err); + return; + } + } + resolve({ data, cacheControl: xhr.getResponseHeader('Cache-Control'), expires: xhr.getResponseHeader('Expires') }); + } + else { + const body = new Blob([xhr.response], { type: xhr.getResponseHeader('Content-Type') }); + reject(new AJAXError(xhr.status, xhr.statusText, requestParameters.url, body)); + } + }; + abortController.signal.addEventListener('abort', () => { + xhr.abort(); + reject(createAbortError()); + }); + xhr.send(requestParameters.body); + }); +} +/** + * We're trying to use the Fetch API if possible. However, requests for resources with the file:// URI scheme don't work with the Fetch API. + * In this case we unconditionally use XHR on the current thread since referrers don't matter. + * This method can also use the registered method if `addProtocol` was called. + * @param requestParameters - The request parameters + * @param abortController - The abort controller allowing to cancel the request + * @returns a promise resolving to the response, including cache control and expiry data + */ +const makeRequest = function (requestParameters, abortController) { + if (/:\/\//.test(requestParameters.url) && !(/^https?:|^file:/.test(requestParameters.url))) { + const protocolLoadFn = getProtocol(requestParameters.url); + if (protocolLoadFn) { + return protocolLoadFn(requestParameters, abortController); + } + if (isWorker(self) && self.worker && self.worker.actor) { + return self.worker.actor.sendAsync({ type: "GR" /* MessageType.getResource */, data: requestParameters, targetMapId: GLOBAL_DISPATCHER_ID }, abortController); + } + } + if (!isFileURL(requestParameters.url)) { + if (fetch && Request && AbortController && Object.prototype.hasOwnProperty.call(Request.prototype, 'signal')) { + return makeFetchRequest(requestParameters, abortController); + } + if (isWorker(self) && self.worker && self.worker.actor) { + return self.worker.actor.sendAsync({ type: "GR" /* MessageType.getResource */, data: requestParameters, mustQueue: true, targetMapId: GLOBAL_DISPATCHER_ID }, abortController); + } + } + return makeXMLHttpRequest(requestParameters, abortController); +}; +const getJSON = (requestParameters, abortController) => { + return makeRequest(extend$1(requestParameters, { type: 'json' }), abortController); +}; +const getArrayBuffer = (requestParameters, abortController) => { + return makeRequest(extend$1(requestParameters, { type: 'arrayBuffer' }), abortController); +}; +function sameOrigin(inComingUrl) { + // A relative URL "/foo" or "./foo" will throw exception in URL's ctor, + // try-catch is expansive so just use a heuristic check to avoid it + // also check data URL + if (!inComingUrl || + inComingUrl.indexOf('://') <= 0 || // relative URL + inComingUrl.indexOf('data:image/') === 0 || // data image URL + inComingUrl.indexOf('blob:') === 0) { // blob + return true; + } + const urlObj = new URL(inComingUrl); + const locationObj = window.location; + return urlObj.protocol === locationObj.protocol && urlObj.host === locationObj.host; +} +const getVideo = (urls) => { + const video = window.document.createElement('video'); + video.muted = true; + return new Promise((resolve) => { + video.onloadstart = () => { + resolve(video); + }; + for (const url of urls) { + const s = window.document.createElement('source'); + if (!sameOrigin(url)) { + video.crossOrigin = 'Anonymous'; + } + s.src = url; + video.appendChild(s); + } + }); +}; + +const registry = {}; +/** + * Register the given class as serializable. + * + * @param options - the registration options + */ +function register(name, klass, options = {}) { + if (registry[name]) + throw new Error(`${name} is already registered.`); + Object.defineProperty(klass, '_classRegistryKey', { + value: name, + writeable: false + }); + registry[name] = { + klass, + omit: options.omit || [], + shallow: options.shallow || [] + }; +} +register('Object', Object); +register('TransferableGridIndex', TransferableGridIndex); +register('Color', Color); +register('Error', Error); +register('AJAXError', AJAXError); +register('ResolvedImage', ResolvedImage); +register('StylePropertyFunction', StylePropertyFunction); +register('StyleExpression', StyleExpression, { omit: ['_evaluator'] }); +register('ZoomDependentExpression', ZoomDependentExpression); +register('ZoomConstantExpression', ZoomConstantExpression); +register('CompoundExpression', CompoundExpression, { omit: ['_evaluate'] }); +for (const name in expressions$1) { + if (expressions$1[name]._classRegistryKey) + continue; + register(`Expression_${name}`, expressions$1[name]); +} +function isArrayBuffer(value) { + return value && typeof ArrayBuffer !== 'undefined' && + (value instanceof ArrayBuffer || (value.constructor && value.constructor.name === 'ArrayBuffer')); +} +function getClassRegistryKey(input) { + const klass = input.constructor; + return input.$name || klass._classRegistryKey; +} +function isRegistered(input) { + if (input === null || typeof input !== 'object') { + return false; + } + const classRegistryKey = getClassRegistryKey(input); + if (classRegistryKey && classRegistryKey !== 'Object') { + return true; + } + return false; +} +function isSerializeHandledByBuiltin(input) { + return (!isRegistered(input) && (input === null || + input === undefined || + typeof input === 'boolean' || + typeof input === 'number' || + typeof input === 'string' || + input instanceof Boolean || + input instanceof Number || + input instanceof String || + input instanceof Date || + input instanceof RegExp || + input instanceof Blob || + input instanceof Error || + isArrayBuffer(input) || + isImageBitmap(input) || + ArrayBuffer.isView(input) || + input instanceof ImageData)); +} +/** + * Serialize the given object for transfer to or from a web worker. + * + * For non-builtin types, recursively serialize each property (possibly + * omitting certain properties - see register()), and package the result along + * with the constructor's `name` so that the appropriate constructor can be + * looked up in `deserialize()`. + * + * If a `transferables` array is provided, add any transferable objects (i.e., + * any ArrayBuffers or ArrayBuffer views) to the list. (If a copy is needed, + * this should happen in the client code, before using serialize().) + */ +function serialize(input, transferables) { + if (isSerializeHandledByBuiltin(input)) { + if (isArrayBuffer(input) || isImageBitmap(input)) { + if (transferables) { + transferables.push(input); + } + } + if (ArrayBuffer.isView(input)) { + const view = input; + if (transferables) { + transferables.push(view.buffer); + } + } + if (input instanceof ImageData) { + if (transferables) { + transferables.push(input.data.buffer); + } + } + return input; + } + if (Array.isArray(input)) { + const serialized = []; + for (const item of input) { + serialized.push(serialize(item, transferables)); + } + return serialized; + } + if (typeof input !== 'object') { + throw new Error(`can't serialize object of type ${typeof input}`); + } + const classRegistryKey = getClassRegistryKey(input); + if (!classRegistryKey) { + throw new Error(`can't serialize object of unregistered class ${input.constructor.name}`); + } + if (!registry[classRegistryKey]) + throw new Error(`${classRegistryKey} is not registered.`); + const { klass } = registry[classRegistryKey]; + const properties = klass.serialize ? + // (Temporary workaround) allow a class to provide static + // `serialize()` and `deserialize()` methods to bypass the generic + // approach. + // This temporary workaround lets us use the generic serialization + // approach for objects whose members include instances of dynamic + // StructArray types. Once we refactor StructArray to be static, + // we can remove this complexity. + klass.serialize(input, transferables) : {}; + if (!klass.serialize) { + for (const key in input) { + if (!input.hasOwnProperty(key)) + continue; // eslint-disable-line no-prototype-builtins + if (registry[classRegistryKey].omit.indexOf(key) >= 0) + continue; + const property = input[key]; + properties[key] = registry[classRegistryKey].shallow.indexOf(key) >= 0 ? + property : + serialize(property, transferables); + } + if (input instanceof Error) { + properties.message = input.message; + } + } + else { + if (transferables && properties === transferables[transferables.length - 1]) { + throw new Error('statically serialized object won\'t survive transfer of $name property'); + } + } + if (properties.$name) { + throw new Error('$name property is reserved for worker serialization logic.'); + } + if (classRegistryKey !== 'Object') { + properties.$name = classRegistryKey; + } + return properties; +} +function deserialize(input) { + if (isSerializeHandledByBuiltin(input)) { + return input; + } + if (Array.isArray(input)) { + return input.map(deserialize); + } + if (typeof input !== 'object') { + throw new Error(`can't deserialize object of type ${typeof input}`); + } + const classRegistryKey = getClassRegistryKey(input) || 'Object'; + if (!registry[classRegistryKey]) { + throw new Error(`can't deserialize unregistered class ${classRegistryKey}`); + } + const { klass } = registry[classRegistryKey]; + if (!klass) { + throw new Error(`can't deserialize unregistered class ${classRegistryKey}`); + } + if (klass.deserialize) { + return klass.deserialize(input); + } + const result = Object.create(klass.prototype); + for (const key of Object.keys(input)) { + if (key === '$name') + continue; + const value = input[key]; + result[key] = registry[classRegistryKey].shallow.indexOf(key) >= 0 ? value : deserialize(value); + } + return result; +} + +/** + * Invokes the wrapped function in a non-blocking way when trigger() is called. + * Invocation requests are ignored until the function was actually invoked. + */ +class ThrottledInvoker { + constructor(methodToThrottle) { + this._methodToThrottle = methodToThrottle; + this._triggered = false; + if (typeof MessageChannel !== 'undefined') { + this._channel = new MessageChannel(); + this._channel.port2.onmessage = () => { + this._triggered = false; + this._methodToThrottle(); + }; + } + } + trigger() { + if (this._triggered) { + return; + } + this._triggered = true; + if (this._channel) { + this._channel.port1.postMessage(true); + } + else { + setTimeout(() => { + this._triggered = false; + this._methodToThrottle(); + }, 0); + } + } + remove() { + delete this._channel; + this._methodToThrottle = () => { }; + } +} + +/** + * An implementation of the [Actor design pattern](https://en.wikipedia.org/wiki/Actor_model) + * that maintains the relationship between asynchronous tasks and the objects + * that spin them off - in this case, tasks like parsing parts of styles, + * owned by the styles + */ +class Actor { + /** + * @param target - The target + * @param mapId - A unique identifier for the Map instance using this Actor. + */ + constructor(target, mapId) { + this.target = target; + this.mapId = mapId; + this.resolveRejects = {}; + this.tasks = {}; + this.taskQueue = []; + this.abortControllers = {}; + this.messageHandlers = {}; + this.invoker = new ThrottledInvoker(() => this.process()); + this.subscription = subscribe(this.target, 'message', (message) => this.receive(message), false); + this.globalScope = isWorker(self) ? target : window; + } + registerMessageHandler(type, handler) { + this.messageHandlers[type] = handler; + } + /** + * Sends a message from a main-thread map to a Worker or from a Worker back to + * a main-thread map instance. + * @param message - the message to send + * @param abortController - an optional AbortController to abort the request + * @returns a promise that will be resolved with the response data + */ + sendAsync(message, abortController) { + return new Promise((resolve, reject) => { + // We're using a string ID instead of numbers because they are being used as object keys + // anyway, and thus stringified implicitly. We use random IDs because an actor may receive + // message from multiple other actors which could run in different execution context. A + // linearly increasing ID could produce collisions. + const id = Math.round((Math.random() * 1e18)).toString(36).substring(0, 10); + this.resolveRejects[id] = { + resolve, + reject + }; + if (abortController) { + abortController.signal.addEventListener('abort', () => { + delete this.resolveRejects[id]; + const cancelMessage = { + id, + type: '', + origin: location.origin, + targetMapId: message.targetMapId, + sourceMapId: this.mapId + }; + this.target.postMessage(cancelMessage); + // In case of abort the current behavior is to keep the promise pending. + }, { once: true }); + } + const buffers = []; + const messageToPost = Object.assign(Object.assign({}, message), { id, sourceMapId: this.mapId, origin: location.origin, data: serialize(message.data, buffers) }); + this.target.postMessage(messageToPost, { transfer: buffers }); + }); + } + receive(message) { + const data = message.data; + const id = data.id; + if (data.origin !== 'file://' && location.origin !== 'file://' && data.origin !== 'resource://android' && location.origin !== 'resource://android' && data.origin !== location.origin) { + return; + } + if (data.targetMapId && this.mapId !== data.targetMapId) { + return; + } + if (data.type === '') { + // Remove the original request from the queue. This is only possible if it + // hasn't been kicked off yet. The id will remain in the queue, but because + // there is no associated task, it will be dropped once it's time to execute it. + delete this.tasks[id]; + const abortController = this.abortControllers[id]; + delete this.abortControllers[id]; + if (abortController) { + abortController.abort(); + } + return; + } + if (isWorker(self) || data.mustQueue) { + // In workers, store the tasks that we need to process before actually processing them. This + // is necessary because we want to keep receiving messages, and in particular, + // messages. Some tasks may take a while in the worker thread, so before + // executing the next task in our queue, postMessage preempts this and + // messages can be processed. We're using a MessageChannel object to get throttle the + // process() flow to one at a time. + this.tasks[id] = data; + this.taskQueue.push(id); + this.invoker.trigger(); + return; + } + // In the main thread, process messages immediately so that other work does not slip in + // between getting partial data back from workers. + this.processTask(id, data); + } + process() { + if (this.taskQueue.length === 0) { + return; + } + const id = this.taskQueue.shift(); + const task = this.tasks[id]; + delete this.tasks[id]; + // Schedule another process call if we know there's more to process _before_ invoking the + // current task. This is necessary so that processing continues even if the current task + // doesn't execute successfully. + if (this.taskQueue.length > 0) { + this.invoker.trigger(); + } + if (!task) { + // If the task ID doesn't have associated task data anymore, it was canceled. + return; + } + this.processTask(id, task); + } + processTask(id, task) { + return __awaiter(this, void 0, void 0, function* () { + if (task.type === '') { + // The `completeTask` function in the counterpart actor has been called, and we are now + // resolving or rejecting the promise in the originating actor, if there is one. + const resolveReject = this.resolveRejects[id]; + delete this.resolveRejects[id]; + if (!resolveReject) { + // If we get a response, but don't have a resolve or reject, the request was canceled. + return; + } + if (task.error) { + resolveReject.reject(deserialize(task.error)); + } + else { + resolveReject.resolve(deserialize(task.data)); + } + return; + } + if (!this.messageHandlers[task.type]) { + this.completeTask(id, new Error(`Could not find a registered handler for ${task.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(', ')}`)); + return; + } + const params = deserialize(task.data); + const abortController = new AbortController(); + this.abortControllers[id] = abortController; + try { + const data = yield this.messageHandlers[task.type](task.sourceMapId, params, abortController); + this.completeTask(id, null, data); + } + catch (err) { + this.completeTask(id, err); + } + }); + } + completeTask(id, err, data) { + const buffers = []; + delete this.abortControllers[id]; + const responseMessage = { + id, + type: '', + sourceMapId: this.mapId, + origin: location.origin, + error: err ? serialize(err) : null, + data: serialize(data, buffers) + }; + this.target.postMessage(responseMessage, { transfer: buffers }); + } + remove() { + this.invoker.remove(); + this.subscription.unsubscribe(); + } +} + +function _addEventListener(type, listener, listenerList) { + const listenerExists = listenerList[type] && listenerList[type].indexOf(listener) !== -1; + if (!listenerExists) { + listenerList[type] = listenerList[type] || []; + listenerList[type].push(listener); + } +} +function _removeEventListener(type, listener, listenerList) { + if (listenerList && listenerList[type]) { + const index = listenerList[type].indexOf(listener); + if (index !== -1) { + listenerList[type].splice(index, 1); + } + } +} +/** + * The event class + */ +class Event { + constructor(type, data = {}) { + extend$1(this, data); + this.type = type; + } +} +/** + * An error event + */ +class ErrorEvent extends Event { + constructor(error, data = {}) { + super('error', extend$1({ error }, data)); + } +} +/** + * Methods mixed in to other classes for event capabilities. + * + * @group Event Related + */ +class Evented { + /** + * Adds a listener to a specified event type. + * + * @param type - The event type to add a listen for. + * @param listener - The function to be called when the event is fired. + * The listener function is called with the data object passed to `fire`, + * extended with `target` and `type` properties. + */ + on(type, listener) { + this._listeners = this._listeners || {}; + _addEventListener(type, listener, this._listeners); + return this; + } + /** + * Removes a previously registered event listener. + * + * @param type - The event type to remove listeners for. + * @param listener - The listener function to remove. + */ + off(type, listener) { + _removeEventListener(type, listener, this._listeners); + _removeEventListener(type, listener, this._oneTimeListeners); + return this; + } + /** + * Adds a listener that will be called only once to a specified event type. + * + * The listener will be called first time the event fires after the listener is registered. + * + * @param type - The event type to listen for. + * @param listener - The function to be called when the event is fired the first time. + * @returns `this` or a promise if a listener is not provided + */ + once(type, listener) { + if (!listener) { + return new Promise((resolve) => this.once(type, resolve)); + } + this._oneTimeListeners = this._oneTimeListeners || {}; + _addEventListener(type, listener, this._oneTimeListeners); + return this; + } + fire(event, properties) { + // Compatibility with (type: string, properties: Object) signature from previous versions. + // See https://github.com/mapbox/mapbox-gl-js/issues/6522, + // https://github.com/mapbox/mapbox-gl-draw/issues/766 + if (typeof event === 'string') { + event = new Event(event, properties || {}); + } + const type = event.type; + if (this.listens(type)) { + event.target = this; + // make sure adding or removing listeners inside other listeners won't cause an infinite loop + const listeners = this._listeners && this._listeners[type] ? this._listeners[type].slice() : []; + for (const listener of listeners) { + listener.call(this, event); + } + const oneTimeListeners = this._oneTimeListeners && this._oneTimeListeners[type] ? this._oneTimeListeners[type].slice() : []; + for (const listener of oneTimeListeners) { + _removeEventListener(type, listener, this._oneTimeListeners); + listener.call(this, event); + } + const parent = this._eventedParent; + if (parent) { + extend$1(event, typeof this._eventedParentData === 'function' ? this._eventedParentData() : this._eventedParentData); + parent.fire(event); + } + // To ensure that no error events are dropped, print them to the + // console if they have no listeners. + } + else if (event instanceof ErrorEvent) { + console.error(event.error); + } + return this; + } + /** + * Returns a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type. + * + * @param type - The event type + * @returns `true` if there is at least one registered listener for specified event type, `false` otherwise + */ + listens(type) { + return ((this._listeners && this._listeners[type] && this._listeners[type].length > 0) || + (this._oneTimeListeners && this._oneTimeListeners[type] && this._oneTimeListeners[type].length > 0) || + (this._eventedParent && this._eventedParent.listens(type))); + } + /** + * Bubble all events fired by this instance of Evented to this parent instance of Evented. + */ + setEventedParent(parent, data) { + this._eventedParent = parent; + this._eventedParentData = data; + return this; + } +} + +const validateStyle = validateStyleMin; +const validateSource = validateStyle.source; +const validateLight = validateStyle.light; +const validateSky = validateStyle.sky; +const validateTerrain = validateStyle.terrain; +const validateFilter = validateStyle.filter; +const validatePaintProperty = validateStyle.paintProperty; +const validateLayoutProperty = validateStyle.layoutProperty; +function emitValidationErrors(emitter, errors) { + let hasErrors = false; + if (errors && errors.length) { + for (const error of errors) { + emitter.fire(new ErrorEvent(new Error(error.message))); + hasErrors = true; + } + } + return hasErrors; +} + +class ZoomHistory { + constructor() { + this.first = true; + } + update(z, now) { + const floorZ = Math.floor(z); + if (this.first) { + this.first = false; + this.lastIntegerZoom = floorZ; + this.lastIntegerZoomTime = 0; + this.lastZoom = z; + this.lastFloorZoom = floorZ; + return true; + } + if (this.lastFloorZoom > floorZ) { + this.lastIntegerZoom = floorZ + 1; + this.lastIntegerZoomTime = now; + } + else if (this.lastFloorZoom < floorZ) { + this.lastIntegerZoom = floorZ; + this.lastIntegerZoomTime = now; + } + if (z !== this.lastZoom) { + this.lastZoom = z; + this.lastFloorZoom = floorZ; + return true; + } + return false; + } +} + +// The following table comes from . +// Keep it synchronized with . +const unicodeBlockLookup = { + // 'Basic Latin': (char) => char >= 0x0000 && char <= 0x007F, + 'Latin-1 Supplement': (char) => char >= 0x0080 && char <= 0x00FF, + // 'Latin Extended-A': (char) => char >= 0x0100 && char <= 0x017F, + // 'Latin Extended-B': (char) => char >= 0x0180 && char <= 0x024F, + // 'IPA Extensions': (char) => char >= 0x0250 && char <= 0x02AF, + // 'Spacing Modifier Letters': (char) => char >= 0x02B0 && char <= 0x02FF, + // 'Combining Diacritical Marks': (char) => char >= 0x0300 && char <= 0x036F, + // 'Greek and Coptic': (char) => char >= 0x0370 && char <= 0x03FF, + // 'Cyrillic': (char) => char >= 0x0400 && char <= 0x04FF, + // 'Cyrillic Supplement': (char) => char >= 0x0500 && char <= 0x052F, + // 'Armenian': (char) => char >= 0x0530 && char <= 0x058F, + //'Hebrew': (char) => char >= 0x0590 && char <= 0x05FF, + // 'Arabic': (char) => char >= 0x0600 && char <= 0x06FF, + //'Syriac': (char) => char >= 0x0700 && char <= 0x074F, + // 'Arabic Supplement': (char) => char >= 0x0750 && char <= 0x077F, + // 'Thaana': (char) => char >= 0x0780 && char <= 0x07BF, + // 'NKo': (char) => char >= 0x07C0 && char <= 0x07FF, + // 'Samaritan': (char) => char >= 0x0800 && char <= 0x083F, + // 'Mandaic': (char) => char >= 0x0840 && char <= 0x085F, + // 'Syriac Supplement': (char) => char >= 0x0860 && char <= 0x086F, + // 'Arabic Extended-B': (char) => char >= 0x0870 && char <= 0x089F, + // 'Arabic Extended-A': (char) => char >= 0x08A0 && char <= 0x08FF, + // 'Devanagari': (char) => char >= 0x0900 && char <= 0x097F, + // 'Bengali': (char) => char >= 0x0980 && char <= 0x09FF, + // 'Gurmukhi': (char) => char >= 0x0A00 && char <= 0x0A7F, + // 'Gujarati': (char) => char >= 0x0A80 && char <= 0x0AFF, + // 'Oriya': (char) => char >= 0x0B00 && char <= 0x0B7F, + // 'Tamil': (char) => char >= 0x0B80 && char <= 0x0BFF, + // 'Telugu': (char) => char >= 0x0C00 && char <= 0x0C7F, + // 'Kannada': (char) => char >= 0x0C80 && char <= 0x0CFF, + // 'Malayalam': (char) => char >= 0x0D00 && char <= 0x0D7F, + // 'Sinhala': (char) => char >= 0x0D80 && char <= 0x0DFF, + // 'Thai': (char) => char >= 0x0E00 && char <= 0x0E7F, + // 'Lao': (char) => char >= 0x0E80 && char <= 0x0EFF, + // 'Tibetan': (char) => char >= 0x0F00 && char <= 0x0FFF, + // 'Myanmar': (char) => char >= 0x1000 && char <= 0x109F, + // 'Georgian': (char) => char >= 0x10A0 && char <= 0x10FF, + 'Hangul Jamo': (char) => char >= 0x1100 && char <= 0x11FF, + // 'Ethiopic': (char) => char >= 0x1200 && char <= 0x137F, + // 'Ethiopic Supplement': (char) => char >= 0x1380 && char <= 0x139F, + // 'Cherokee': (char) => char >= 0x13A0 && char <= 0x13FF, + // 'Unified Canadian Aboriginal Syllabics': (char) => char >= 0x1400 && char <= 0x167F, + // 'Ogham': (char) => char >= 0x1680 && char <= 0x169F, + // 'Runic': (char) => char >= 0x16A0 && char <= 0x16FF, + // 'Tagalog': (char) => char >= 0x1700 && char <= 0x171F, + // 'Hanunoo': (char) => char >= 0x1720 && char <= 0x173F, + // 'Buhid': (char) => char >= 0x1740 && char <= 0x175F, + // 'Tagbanwa': (char) => char >= 0x1760 && char <= 0x177F, + 'Khmer': (char) => char >= 0x1780 && char <= 0x17FF, + // 'Mongolian': (char) => char >= 0x1800 && char <= 0x18AF, + // 'Unified Canadian Aboriginal Syllabics Extended': (char) => char >= 0x18B0 && char <= 0x18FF, + // 'Limbu': (char) => char >= 0x1900 && char <= 0x194F, + // 'Tai Le': (char) => char >= 0x1950 && char <= 0x197F, + // 'New Tai Lue': (char) => char >= 0x1980 && char <= 0x19DF, + // 'Khmer Symbols': (char) => char >= 0x19E0 && char <= 0x19FF, + // 'Buginese': (char) => char >= 0x1A00 && char <= 0x1A1F, + // 'Tai Tham': (char) => char >= 0x1A20 && char <= 0x1AAF, + // 'Combining Diacritical Marks Extended': (char) => char >= 0x1AB0 && char <= 0x1AFF, + // 'Balinese': (char) => char >= 0x1B00 && char <= 0x1B7F, + // 'Sundanese': (char) => char >= 0x1B80 && char <= 0x1BBF, + // 'Batak': (char) => char >= 0x1BC0 && char <= 0x1BFF, + // 'Lepcha': (char) => char >= 0x1C00 && char <= 0x1C4F, + // 'Ol Chiki': (char) => char >= 0x1C50 && char <= 0x1C7F, + // 'Cyrillic Extended-C': (char) => char >= 0x1C80 && char <= 0x1C8F, + // 'Georgian Extended': (char) => char >= 0x1C90 && char <= 0x1CBF, + // 'Sundanese Supplement': (char) => char >= 0x1CC0 && char <= 0x1CCF, + // 'Vedic Extensions': (char) => char >= 0x1CD0 && char <= 0x1CFF, + // 'Phonetic Extensions': (char) => char >= 0x1D00 && char <= 0x1D7F, + // 'Phonetic Extensions Supplement': (char) => char >= 0x1D80 && char <= 0x1DBF, + // 'Combining Diacritical Marks Supplement': (char) => char >= 0x1DC0 && char <= 0x1DFF, + // 'Latin Extended Additional': (char) => char >= 0x1E00 && char <= 0x1EFF, + // 'Greek Extended': (char) => char >= 0x1F00 && char <= 0x1FFF, + 'General Punctuation': (char) => char >= 0x2000 && char <= 0x206F, + // 'Superscripts and Subscripts': (char) => char >= 0x2070 && char <= 0x209F, + // 'Currency Symbols': (char) => char >= 0x20A0 && char <= 0x20CF, + // 'Combining Diacritical Marks for Symbols': (char) => char >= 0x20D0 && char <= 0x20FF, + 'Letterlike Symbols': (char) => char >= 0x2100 && char <= 0x214F, + 'Number Forms': (char) => char >= 0x2150 && char <= 0x218F, + // 'Arrows': (char) => char >= 0x2190 && char <= 0x21FF, + // 'Mathematical Operators': (char) => char >= 0x2200 && char <= 0x22FF, + 'Miscellaneous Technical': (char) => char >= 0x2300 && char <= 0x23FF, + 'Control Pictures': (char) => char >= 0x2400 && char <= 0x243F, + 'Optical Character Recognition': (char) => char >= 0x2440 && char <= 0x245F, + 'Enclosed Alphanumerics': (char) => char >= 0x2460 && char <= 0x24FF, + // 'Box Drawing': (char) => char >= 0x2500 && char <= 0x257F, + // 'Block Elements': (char) => char >= 0x2580 && char <= 0x259F, + 'Geometric Shapes': (char) => char >= 0x25A0 && char <= 0x25FF, + 'Miscellaneous Symbols': (char) => char >= 0x2600 && char <= 0x26FF, + // 'Dingbats': (char) => char >= 0x2700 && char <= 0x27BF, + // 'Miscellaneous Mathematical Symbols-A': (char) => char >= 0x27C0 && char <= 0x27EF, + // 'Supplemental Arrows-A': (char) => char >= 0x27F0 && char <= 0x27FF, + // 'Braille Patterns': (char) => char >= 0x2800 && char <= 0x28FF, + // 'Supplemental Arrows-B': (char) => char >= 0x2900 && char <= 0x297F, + // 'Miscellaneous Mathematical Symbols-B': (char) => char >= 0x2980 && char <= 0x29FF, + // 'Supplemental Mathematical Operators': (char) => char >= 0x2A00 && char <= 0x2AFF, + 'Miscellaneous Symbols and Arrows': (char) => char >= 0x2B00 && char <= 0x2BFF, + // 'Glagolitic': (char) => char >= 0x2C00 && char <= 0x2C5F, + // 'Latin Extended-C': (char) => char >= 0x2C60 && char <= 0x2C7F, + // 'Coptic': (char) => char >= 0x2C80 && char <= 0x2CFF, + // 'Georgian Supplement': (char) => char >= 0x2D00 && char <= 0x2D2F, + // 'Tifinagh': (char) => char >= 0x2D30 && char <= 0x2D7F, + // 'Ethiopic Extended': (char) => char >= 0x2D80 && char <= 0x2DDF, + // 'Cyrillic Extended-A': (char) => char >= 0x2DE0 && char <= 0x2DFF, + // 'Supplemental Punctuation': (char) => char >= 0x2E00 && char <= 0x2E7F, + // 'CJK Radicals Supplement': (char) => char >= 0x2E80 && char <= 0x2EFF, + // 'Kangxi Radicals': (char) => char >= 0x2F00 && char <= 0x2FDF, + 'Ideographic Description Characters': (char) => char >= 0x2FF0 && char <= 0x2FFF, + 'CJK Symbols and Punctuation': (char) => char >= 0x3000 && char <= 0x303F, + // 'Hiragana': (char) => char >= 0x3040 && char <= 0x309F, + 'Katakana': (char) => char >= 0x30A0 && char <= 0x30FF, + // 'Bopomofo': (char) => char >= 0x3100 && char <= 0x312F, + // 'Hangul Compatibility Jamo': (char) => char >= 0x3130 && char <= 0x318F, + 'Kanbun': (char) => char >= 0x3190 && char <= 0x319F, + // 'Bopomofo Extended': (char) => char >= 0x31A0 && char <= 0x31BF, + 'CJK Strokes': (char) => char >= 0x31C0 && char <= 0x31EF, + // 'Katakana Phonetic Extensions': (char) => char >= 0x31F0 && char <= 0x31FF, + 'Enclosed CJK Letters and Months': (char) => char >= 0x3200 && char <= 0x32FF, + 'CJK Compatibility': (char) => char >= 0x3300 && char <= 0x33FF, + // 'CJK Unified Ideographs Extension A': (char) => char >= 0x3400 && char <= 0x4DBF, + 'Yijing Hexagram Symbols': (char) => char >= 0x4DC0 && char <= 0x4DFF, + // 'CJK Unified Ideographs': (char) => char >= 0x4E00 && char <= 0x9FFF, + // 'Yi Syllables': (char) => char >= 0xA000 && char <= 0xA48F, + // 'Yi Radicals': (char) => char >= 0xA490 && char <= 0xA4CF, + // 'Lisu': (char) => char >= 0xA4D0 && char <= 0xA4FF, + // 'Vai': (char) => char >= 0xA500 && char <= 0xA63F, + // 'Cyrillic Extended-B': (char) => char >= 0xA640 && char <= 0xA69F, + // 'Bamum': (char) => char >= 0xA6A0 && char <= 0xA6FF, + // 'Modifier Tone Letters': (char) => char >= 0xA700 && char <= 0xA71F, + // 'Latin Extended-D': (char) => char >= 0xA720 && char <= 0xA7FF, + // 'Syloti Nagri': (char) => char >= 0xA800 && char <= 0xA82F, + // 'Common Indic Number Forms': (char) => char >= 0xA830 && char <= 0xA83F, + // 'Phags-pa': (char) => char >= 0xA840 && char <= 0xA87F, + // 'Saurashtra': (char) => char >= 0xA880 && char <= 0xA8DF, + // 'Devanagari Extended': (char) => char >= 0xA8E0 && char <= 0xA8FF, + // 'Kayah Li': (char) => char >= 0xA900 && char <= 0xA92F, + // 'Rejang': (char) => char >= 0xA930 && char <= 0xA95F, + // 'Hangul Jamo Extended-A': (char) => char >= 0xA960 && char <= 0xA97F, + // 'Javanese': (char) => char >= 0xA980 && char <= 0xA9DF, + // 'Myanmar Extended-B': (char) => char >= 0xA9E0 && char <= 0xA9FF, + // 'Cham': (char) => char >= 0xAA00 && char <= 0xAA5F, + // 'Myanmar Extended-A': (char) => char >= 0xAA60 && char <= 0xAA7F, + // 'Tai Viet': (char) => char >= 0xAA80 && char <= 0xAADF, + // 'Meetei Mayek Extensions': (char) => char >= 0xAAE0 && char <= 0xAAFF, + // 'Ethiopic Extended-A': (char) => char >= 0xAB00 && char <= 0xAB2F, + // 'Latin Extended-E': (char) => char >= 0xAB30 && char <= 0xAB6F, + // 'Cherokee Supplement': (char) => char >= 0xAB70 && char <= 0xABBF, + // 'Meetei Mayek': (char) => char >= 0xABC0 && char <= 0xABFF, + // 'Hangul Syllables': (char) => char >= 0xAC00 && char <= 0xD7AF, + // 'Hangul Jamo Extended-B': (char) => char >= 0xD7B0 && char <= 0xD7FF, + // 'High Surrogates': (char) => char >= 0xD800 && char <= 0xDB7F, + // 'High Private Use Surrogates': (char) => char >= 0xDB80 && char <= 0xDBFF, + // 'Low Surrogates': (char) => char >= 0xDC00 && char <= 0xDFFF, + 'Private Use Area': (char) => char >= 0xE000 && char <= 0xF8FF, + // 'CJK Compatibility Ideographs': (char) => char >= 0xF900 && char <= 0xFAFF, + // 'Alphabetic Presentation Forms': (char) => char >= 0xFB00 && char <= 0xFB4F, + // 'Arabic Presentation Forms-A': (char) => char >= 0xFB50 && char <= 0xFDFF, + // 'Variation Selectors': (char) => char >= 0xFE00 && char <= 0xFE0F, + 'Vertical Forms': (char) => char >= 0xFE10 && char <= 0xFE1F, + // 'Combining Half Marks': (char) => char >= 0xFE20 && char <= 0xFE2F, + 'CJK Compatibility Forms': (char) => char >= 0xFE30 && char <= 0xFE4F, + 'Small Form Variants': (char) => char >= 0xFE50 && char <= 0xFE6F, + // 'Arabic Presentation Forms-B': (char) => char >= 0xFE70 && char <= 0xFEFF, + 'Halfwidth and Fullwidth Forms': (char) => char >= 0xFF00 && char <= 0xFFEF + // 'Specials': (char) => char >= 0xFFF0 && char <= 0xFFFF, + // 'Linear B Syllabary': (char) => char >= 0x10000 && char <= 0x1007F, + // 'Linear B Ideograms': (char) => char >= 0x10080 && char <= 0x100FF, + // 'Aegean Numbers': (char) => char >= 0x10100 && char <= 0x1013F, + // 'Ancient Greek Numbers': (char) => char >= 0x10140 && char <= 0x1018F, + // 'Ancient Symbols': (char) => char >= 0x10190 && char <= 0x101CF, + // 'Phaistos Disc': (char) => char >= 0x101D0 && char <= 0x101FF, + // 'Lycian': (char) => char >= 0x10280 && char <= 0x1029F, + // 'Carian': (char) => char >= 0x102A0 && char <= 0x102DF, + // 'Coptic Epact Numbers': (char) => char >= 0x102E0 && char <= 0x102FF, + // 'Old Italic': (char) => char >= 0x10300 && char <= 0x1032F, + // 'Gothic': (char) => char >= 0x10330 && char <= 0x1034F, + // 'Old Permic': (char) => char >= 0x10350 && char <= 0x1037F, + // 'Ugaritic': (char) => char >= 0x10380 && char <= 0x1039F, + // 'Old Persian': (char) => char >= 0x103A0 && char <= 0x103DF, + // 'Deseret': (char) => char >= 0x10400 && char <= 0x1044F, + // 'Shavian': (char) => char >= 0x10450 && char <= 0x1047F, + // 'Osmanya': (char) => char >= 0x10480 && char <= 0x104AF, + // 'Osage': (char) => char >= 0x104B0 && char <= 0x104FF, + // 'Elbasan': (char) => char >= 0x10500 && char <= 0x1052F, + // 'Caucasian Albanian': (char) => char >= 0x10530 && char <= 0x1056F, + // 'Vithkuqi': (char) => char >= 0x10570 && char <= 0x105BF, + // 'Todhri': (char) => char >= 0x105C0 && char <= 0x105FF, + // 'Linear A': (char) => char >= 0x10600 && char <= 0x1077F, + // 'Latin Extended-F': (char) => char >= 0x10780 && char <= 0x107BF, + // 'Cypriot Syllabary': (char) => char >= 0x10800 && char <= 0x1083F, + // 'Imperial Aramaic': (char) => char >= 0x10840 && char <= 0x1085F, + // 'Palmyrene': (char) => char >= 0x10860 && char <= 0x1087F, + // 'Nabataean': (char) => char >= 0x10880 && char <= 0x108AF, + // 'Hatran': (char) => char >= 0x108E0 && char <= 0x108FF, + // 'Phoenician': (char) => char >= 0x10900 && char <= 0x1091F, + // 'Lydian': (char) => char >= 0x10920 && char <= 0x1093F, + // 'Meroitic Hieroglyphs': (char) => char >= 0x10980 && char <= 0x1099F, + // 'Meroitic Cursive': (char) => char >= 0x109A0 && char <= 0x109FF, + // 'Kharoshthi': (char) => char >= 0x10A00 && char <= 0x10A5F, + // 'Old South Arabian': (char) => char >= 0x10A60 && char <= 0x10A7F, + // 'Old North Arabian': (char) => char >= 0x10A80 && char <= 0x10A9F, + // 'Manichaean': (char) => char >= 0x10AC0 && char <= 0x10AFF, + // 'Avestan': (char) => char >= 0x10B00 && char <= 0x10B3F, + // 'Inscriptional Parthian': (char) => char >= 0x10B40 && char <= 0x10B5F, + // 'Inscriptional Pahlavi': (char) => char >= 0x10B60 && char <= 0x10B7F, + // 'Psalter Pahlavi': (char) => char >= 0x10B80 && char <= 0x10BAF, + // 'Old Turkic': (char) => char >= 0x10C00 && char <= 0x10C4F, + // 'Old Hungarian': (char) => char >= 0x10C80 && char <= 0x10CFF, + // 'Hanifi Rohingya': (char) => char >= 0x10D00 && char <= 0x10D3F, + // 'Garay': (char) => char >= 0x10D40 && char <= 0x10D8F, + // 'Rumi Numeral Symbols': (char) => char >= 0x10E60 && char <= 0x10E7F, + // 'Yezidi': (char) => char >= 0x10E80 && char <= 0x10EBF, + // 'Arabic Extended-C': (char) => char >= 0x10EC0 && char <= 0x10EFF, + // 'Old Sogdian': (char) => char >= 0x10F00 && char <= 0x10F2F, + // 'Sogdian': (char) => char >= 0x10F30 && char <= 0x10F6F, + // 'Old Uyghur': (char) => char >= 0x10F70 && char <= 0x10FAF, + // 'Chorasmian': (char) => char >= 0x10FB0 && char <= 0x10FDF, + // 'Elymaic': (char) => char >= 0x10FE0 && char <= 0x10FFF, + // 'Brahmi': (char) => char >= 0x11000 && char <= 0x1107F, + // 'Kaithi': (char) => char >= 0x11080 && char <= 0x110CF, + // 'Sora Sompeng': (char) => char >= 0x110D0 && char <= 0x110FF, + // 'Chakma': (char) => char >= 0x11100 && char <= 0x1114F, + // 'Mahajani': (char) => char >= 0x11150 && char <= 0x1117F, + // 'Sharada': (char) => char >= 0x11180 && char <= 0x111DF, + // 'Sinhala Archaic Numbers': (char) => char >= 0x111E0 && char <= 0x111FF, + // 'Khojki': (char) => char >= 0x11200 && char <= 0x1124F, + // 'Multani': (char) => char >= 0x11280 && char <= 0x112AF, + // 'Khudawadi': (char) => char >= 0x112B0 && char <= 0x112FF, + // 'Grantha': (char) => char >= 0x11300 && char <= 0x1137F, + // 'Tulu-Tigalari': (char) => char >= 0x11380 && char <= 0x113FF, + // 'Newa': (char) => char >= 0x11400 && char <= 0x1147F, + // 'Tirhuta': (char) => char >= 0x11480 && char <= 0x114DF, + // 'Siddham': (char) => char >= 0x11580 && char <= 0x115FF, + // 'Modi': (char) => char >= 0x11600 && char <= 0x1165F, + // 'Mongolian Supplement': (char) => char >= 0x11660 && char <= 0x1167F, + // 'Takri': (char) => char >= 0x11680 && char <= 0x116CF, + // 'Myanmar Extended-C': (char) => char >= 0x116D0 && char <= 0x116FF, + // 'Ahom': (char) => char >= 0x11700 && char <= 0x1174F, + // 'Dogra': (char) => char >= 0x11800 && char <= 0x1184F, + // 'Warang Citi': (char) => char >= 0x118A0 && char <= 0x118FF, + // 'Dives Akuru': (char) => char >= 0x11900 && char <= 0x1195F, + // 'Nandinagari': (char) => char >= 0x119A0 && char <= 0x119FF, + // 'Zanabazar Square': (char) => char >= 0x11A00 && char <= 0x11A4F, + // 'Soyombo': (char) => char >= 0x11A50 && char <= 0x11AAF, + // 'Unified Canadian Aboriginal Syllabics Extended-A': (char) => char >= 0x11AB0 && char <= 0x11ABF, + // 'Pau Cin Hau': (char) => char >= 0x11AC0 && char <= 0x11AFF, + // 'Devanagari Extended-A': (char) => char >= 0x11B00 && char <= 0x11B5F, + // 'Sunuwar': (char) => char >= 0x11BC0 && char <= 0x11BFF, + // 'Bhaiksuki': (char) => char >= 0x11C00 && char <= 0x11C6F, + // 'Marchen': (char) => char >= 0x11C70 && char <= 0x11CBF, + // 'Masaram Gondi': (char) => char >= 0x11D00 && char <= 0x11D5F, + // 'Gunjala Gondi': (char) => char >= 0x11D60 && char <= 0x11DAF, + // 'Makasar': (char) => char >= 0x11EE0 && char <= 0x11EFF, + // 'Kawi': (char) => char >= 0x11F00 && char <= 0x11F5F, + // 'Lisu Supplement': (char) => char >= 0x11FB0 && char <= 0x11FBF, + // 'Tamil Supplement': (char) => char >= 0x11FC0 && char <= 0x11FFF, + // 'Cuneiform': (char) => char >= 0x12000 && char <= 0x123FF, + // 'Cuneiform Numbers and Punctuation': (char) => char >= 0x12400 && char <= 0x1247F, + // 'Early Dynastic Cuneiform': (char) => char >= 0x12480 && char <= 0x1254F, + // 'Cypro-Minoan': (char) => char >= 0x12F90 && char <= 0x12FFF, + // 'Egyptian Hieroglyphs': (char) => char >= 0x13000 && char <= 0x1342F, + // 'Egyptian Hieroglyph Format Controls': (char) => char >= 0x13430 && char <= 0x1345F, + // 'Egyptian Hieroglyphs Extended-A': (char) => char >= 0x13460 && char <= 0x143FF, + // 'Anatolian Hieroglyphs': (char) => char >= 0x14400 && char <= 0x1467F, + // 'Gurung Khema': (char) => char >= 0x16100 && char <= 0x1613F, + // 'Bamum Supplement': (char) => char >= 0x16800 && char <= 0x16A3F, + // 'Mro': (char) => char >= 0x16A40 && char <= 0x16A6F, + // 'Tangsa': (char) => char >= 0x16A70 && char <= 0x16ACF, + // 'Bassa Vah': (char) => char >= 0x16AD0 && char <= 0x16AFF, + // 'Pahawh Hmong': (char) => char >= 0x16B00 && char <= 0x16B8F, + // 'Kirat Rai': (char) => char >= 0x16D40 && char <= 0x16D7F, + // 'Medefaidrin': (char) => char >= 0x16E40 && char <= 0x16E9F, + // 'Miao': (char) => char >= 0x16F00 && char <= 0x16F9F, + // 'Ideographic Symbols and Punctuation': (char) => char >= 0x16FE0 && char <= 0x16FFF, + // 'Tangut': (char) => char >= 0x17000 && char <= 0x187FF, + // 'Tangut Components': (char) => char >= 0x18800 && char <= 0x18AFF, + // 'Khitan Small Script': (char) => char >= 0x18B00 && char <= 0x18CFF, + // 'Tangut Supplement': (char) => char >= 0x18D00 && char <= 0x18D7F, + // 'Kana Extended-B': (char) => char >= 0x1AFF0 && char <= 0x1AFFF, + // 'Kana Supplement': (char) => char >= 0x1B000 && char <= 0x1B0FF, + // 'Kana Extended-A': (char) => char >= 0x1B100 && char <= 0x1B12F, + // 'Small Kana Extension': (char) => char >= 0x1B130 && char <= 0x1B16F, + // 'Nushu': (char) => char >= 0x1B170 && char <= 0x1B2FF, + // 'Duployan': (char) => char >= 0x1BC00 && char <= 0x1BC9F, + // 'Shorthand Format Controls': (char) => char >= 0x1BCA0 && char <= 0x1BCAF, + // 'Symbols for Legacy Computing Supplement': (char) => char >= 0x1CC00 && char <= 0x1CEBF, + // 'Znamenny Musical Notation': (char) => char >= 0x1CF00 && char <= 0x1CFCF, + // 'Byzantine Musical Symbols': (char) => char >= 0x1D000 && char <= 0x1D0FF, + // 'Musical Symbols': (char) => char >= 0x1D100 && char <= 0x1D1FF, + // 'Ancient Greek Musical Notation': (char) => char >= 0x1D200 && char <= 0x1D24F, + // 'Kaktovik Numerals': (char) => char >= 0x1D2C0 && char <= 0x1D2DF, + // 'Mayan Numerals': (char) => char >= 0x1D2E0 && char <= 0x1D2FF, + // 'Tai Xuan Jing Symbols': (char) => char >= 0x1D300 && char <= 0x1D35F, + // 'Counting Rod Numerals': (char) => char >= 0x1D360 && char <= 0x1D37F, + // 'Mathematical Alphanumeric Symbols': (char) => char >= 0x1D400 && char <= 0x1D7FF, + // 'Sutton SignWriting': (char) => char >= 0x1D800 && char <= 0x1DAAF, + // 'Latin Extended-G': (char) => char >= 0x1DF00 && char <= 0x1DFFF, + // 'Glagolitic Supplement': (char) => char >= 0x1E000 && char <= 0x1E02F, + // 'Cyrillic Extended-D': (char) => char >= 0x1E030 && char <= 0x1E08F, + // 'Nyiakeng Puachue Hmong': (char) => char >= 0x1E100 && char <= 0x1E14F, + // 'Toto': (char) => char >= 0x1E290 && char <= 0x1E2BF, + // 'Wancho': (char) => char >= 0x1E2C0 && char <= 0x1E2FF, + // 'Nag Mundari': (char) => char >= 0x1E4D0 && char <= 0x1E4FF, + // 'Ol Onal': (char) => char >= 0x1E5D0 && char <= 0x1E5FF, + // 'Ethiopic Extended-B': (char) => char >= 0x1E7E0 && char <= 0x1E7FF, + // 'Mende Kikakui': (char) => char >= 0x1E800 && char <= 0x1E8DF, + // 'Adlam': (char) => char >= 0x1E900 && char <= 0x1E95F, + // 'Indic Siyaq Numbers': (char) => char >= 0x1EC70 && char <= 0x1ECBF, + // 'Ottoman Siyaq Numbers': (char) => char >= 0x1ED00 && char <= 0x1ED4F, + // 'Arabic Mathematical Alphabetic Symbols': (char) => char >= 0x1EE00 && char <= 0x1EEFF, + // 'Mahjong Tiles': (char) => char >= 0x1F000 && char <= 0x1F02F, + // 'Domino Tiles': (char) => char >= 0x1F030 && char <= 0x1F09F, + // 'Playing Cards': (char) => char >= 0x1F0A0 && char <= 0x1F0FF, + // 'Enclosed Alphanumeric Supplement': (char) => char >= 0x1F100 && char <= 0x1F1FF, + // 'Enclosed Ideographic Supplement': (char) => char >= 0x1F200 && char <= 0x1F2FF, + // 'Miscellaneous Symbols and Pictographs': (char) => char >= 0x1F300 && char <= 0x1F5FF, + // 'Emoticons': (char) => char >= 0x1F600 && char <= 0x1F64F, + // 'Ornamental Dingbats': (char) => char >= 0x1F650 && char <= 0x1F67F, + // 'Transport and Map Symbols': (char) => char >= 0x1F680 && char <= 0x1F6FF, + // 'Alchemical Symbols': (char) => char >= 0x1F700 && char <= 0x1F77F, + // 'Geometric Shapes Extended': (char) => char >= 0x1F780 && char <= 0x1F7FF, + // 'Supplemental Arrows-C': (char) => char >= 0x1F800 && char <= 0x1F8FF, + // 'Supplemental Symbols and Pictographs': (char) => char >= 0x1F900 && char <= 0x1F9FF, + // 'Chess Symbols': (char) => char >= 0x1FA00 && char <= 0x1FA6F, + // 'Symbols and Pictographs Extended-A': (char) => char >= 0x1FA70 && char <= 0x1FAFF, + // 'Symbols for Legacy Computing': (char) => char >= 0x1FB00 && char <= 0x1FBFF, + // 'CJK Unified Ideographs Extension B': (char) => char >= 0x20000 && char <= 0x2A6DF, + // 'CJK Unified Ideographs Extension C': (char) => char >= 0x2A700 && char <= 0x2B73F, + // 'CJK Unified Ideographs Extension D': (char) => char >= 0x2B740 && char <= 0x2B81F, + // 'CJK Unified Ideographs Extension E': (char) => char >= 0x2B820 && char <= 0x2CEAF, + // 'CJK Unified Ideographs Extension F': (char) => char >= 0x2CEB0 && char <= 0x2EBEF, + // 'CJK Unified Ideographs Extension I': (char) => char >= 0x2EBF0 && char <= 0x2EE5F, + // 'CJK Unified Ideographs Extension G': (char) => char >= 0x30000 && char <= 0x3134F, + // 'CJK Unified Ideographs Extension H': (char) => char >= 0x31350 && char <= 0x323AF, + // 'CJK Compatibility Ideographs Supplement': (char) => char >= 0x2F800 && char <= 0x2FA1F, + // 'Tags': (char) => char >= 0xE0000 && char <= 0xE007F, + // 'Variation Selectors Supplement': (char) => char >= 0xE0100 && char <= 0xE01EF, + // 'Supplementary Private Use Area-A': (char) => char >= 0xF0000 && char <= 0xFFFFF, + // 'Supplementary Private Use Area-B': (char) => char >= 0x100000 && char <= 0x10FFFF, +}; + +/* eslint-disable new-cap */ +function allowsIdeographicBreaking(chars) { + for (const char of chars) { + if (!charAllowsIdeographicBreaking(char.charCodeAt(0))) + return false; + } + return true; +} +function allowsVerticalWritingMode(chars) { + for (const char of chars) { + if (charHasUprightVerticalOrientation(char.charCodeAt(0))) + return true; + } + return false; +} +function allowsLetterSpacing(chars) { + for (const char of chars) { + if (!charAllowsLetterSpacing(char.charCodeAt(0))) + return false; + } + return true; +} +/** + * Returns a regular expression matching the given script codes, excluding any + * code that the execution environment lacks support for in regular expressions. + */ +function sanitizedRegExpFromScriptCodes(scriptCodes) { + const supportedPropertyEscapes = scriptCodes.map(code => { + try { + return new RegExp(`\\p{sc=${code}}`, 'u').source; + } + catch (e) { + return null; + } + }).filter(pe => pe); + return new RegExp(supportedPropertyEscapes.join('|'), 'u'); +} +/** + * ISO 15924 script codes of scripts that disallow letter spacing as of Unicode + * 16.0.0. + * + * In general, cursive scripts are incompatible with letter spacing. + */ +const cursiveScriptCodes = [ + 'Arab', // Arabic + 'Dupl', // Duployan + 'Mong', // Mongolian + 'Ougr', // Old Uyghur + 'Syrc', // Syriac +]; +const cursiveScriptRegExp = sanitizedRegExpFromScriptCodes(cursiveScriptCodes); +function charAllowsLetterSpacing(char) { + return !cursiveScriptRegExp.test(String.fromCodePoint(char)); +} +/** + * ISO 15924 script codes of scripts that allow ideographic line breaking beyond + * the CJKV scripts that are considered ideographic in Unicode 16.0.0. + */ +const ideographicBreakingScriptCodes = [ + 'Bopo', // Bopomofo + 'Hani', // Han + 'Hira', // Hiragana + 'Kana', // Katakana + 'Kits', // Khitan Small Script + 'Nshu', // Nushu + 'Tang', // Tangut + 'Yiii', // Yi +]; +const ideographicBreakingRegExp = sanitizedRegExpFromScriptCodes(ideographicBreakingScriptCodes); +function charAllowsIdeographicBreaking(char) { + // Return early for characters outside all ideographic ranges. + if (char < 0x2E80) + return false; + if (unicodeBlockLookup['CJK Compatibility Forms'](char)) + return true; + if (unicodeBlockLookup['CJK Compatibility'](char)) + return true; + if (unicodeBlockLookup['CJK Strokes'](char)) + return true; + if (unicodeBlockLookup['CJK Symbols and Punctuation'](char)) + return true; + if (unicodeBlockLookup['Enclosed CJK Letters and Months'](char)) + return true; + if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) + return true; + if (unicodeBlockLookup['Ideographic Description Characters'](char)) + return true; + if (unicodeBlockLookup['Vertical Forms'](char)) + return true; + return ideographicBreakingRegExp.test(String.fromCodePoint(char)); +} +// The following logic comes from +// . +// Keep it synchronized with +// . +// The data file denotes with “U” or “Tu” any codepoint that may be drawn +// upright in vertical text but does not distinguish between upright and +// “neutral” characters. +// Blocks in the Unicode supplementary planes are excluded from this module due +// to . +/** + * Returns true if the given Unicode codepoint identifies a character with + * upright orientation. + * + * A character has upright orientation if it is drawn upright (unrotated) + * whether the line is oriented horizontally or vertically, even if both + * adjacent characters can be rotated. For example, a Chinese character is + * always drawn upright. An uprightly oriented character causes an adjacent + * “neutral” character to be drawn upright as well. + */ +function charHasUprightVerticalOrientation(char) { + if (char === 0x02EA /* modifier letter yin departing tone mark */ || + char === 0x02EB /* modifier letter yang departing tone mark */) { + return true; + } + // Return early for characters outside all ranges whose characters remain + // upright in vertical writing mode. + if (char < 0x1100) + return false; + if (unicodeBlockLookup['CJK Compatibility Forms'](char)) { + if (!((char >= 0xFE49 /* dashed overline */ && char <= 0xFE4F) /* wavy low line */)) { + return true; + } + } + if (unicodeBlockLookup['CJK Compatibility'](char)) + return true; + if (unicodeBlockLookup['CJK Strokes'](char)) + return true; + if (unicodeBlockLookup['CJK Symbols and Punctuation'](char)) { + if (!((char >= 0x3008 /* left angle bracket */ && char <= 0x3011) /* right black lenticular bracket */) && + !((char >= 0x3014 /* left tortoise shell bracket */ && char <= 0x301F) /* low double prime quotation mark */) && + char !== 0x3030 /* wavy dash */) { + return true; + } + } + if (unicodeBlockLookup['Enclosed CJK Letters and Months'](char)) + return true; + if (unicodeBlockLookup['Ideographic Description Characters'](char)) + return true; + if (unicodeBlockLookup['Kanbun'](char)) + return true; + if (unicodeBlockLookup['Katakana'](char)) { + if (char !== 0x30FC /* katakana-hiragana prolonged sound mark */) { + return true; + } + } + if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) { + if (char !== 0xFF08 /* fullwidth left parenthesis */ && + char !== 0xFF09 /* fullwidth right parenthesis */ && + char !== 0xFF0D /* fullwidth hyphen-minus */ && + !((char >= 0xFF1A /* fullwidth colon */ && char <= 0xFF1E) /* fullwidth greater-than sign */) && + char !== 0xFF3B /* fullwidth left square bracket */ && + char !== 0xFF3D /* fullwidth right square bracket */ && + char !== 0xFF3F /* fullwidth low line */ && + !(char >= 0xFF5B /* fullwidth left curly bracket */ && char <= 0xFFDF) && + char !== 0xFFE3 /* fullwidth macron */ && + !(char >= 0xFFE8 /* halfwidth forms light vertical */ && char <= 0xFFEF)) { + return true; + } + } + if (unicodeBlockLookup['Small Form Variants'](char)) { + if (!((char >= 0xFE58 /* small em dash */ && char <= 0xFE5E) /* small right tortoise shell bracket */) && + !((char >= 0xFE63 /* small hyphen-minus */ && char <= 0xFE66) /* small equals sign */)) { + return true; + } + } + if (unicodeBlockLookup['Vertical Forms'](char)) + return true; + if (unicodeBlockLookup['Yijing Hexagram Symbols'](char)) + return true; + if ( /* Canadian Aboriginal *//\p{sc=Cans}/u.test(String.fromCodePoint(char))) + return true; + if ( /* Hangul *//\p{sc=Hang}/u.test(String.fromCodePoint(char))) + return true; + if (ideographicBreakingRegExp.test(String.fromCodePoint(char))) + return true; + return false; +} +/** + * Returns true if the given Unicode codepoint identifies a character with + * neutral orientation. + * + * A character has neutral orientation if it may be drawn rotated or unrotated + * when the line is oriented vertically, depending on the orientation of the + * adjacent characters. For example, along a vertically oriented line, the vulgar + * fraction ½ is drawn upright among Chinese characters but rotated among Latin + * letters. A neutrally oriented character does not influence whether an + * adjacent character is drawn upright or rotated. + */ +function charHasNeutralVerticalOrientation(char) { + if (unicodeBlockLookup['Latin-1 Supplement'](char)) { + if (char === 0x00A7 /* section sign */ || + char === 0x00A9 /* copyright sign */ || + char === 0x00AE /* registered sign */ || + char === 0x00B1 /* plus-minus sign */ || + char === 0x00BC /* vulgar fraction one quarter */ || + char === 0x00BD /* vulgar fraction one half */ || + char === 0x00BE /* vulgar fraction three quarters */ || + char === 0x00D7 /* multiplication sign */ || + char === 0x00F7 /* division sign */) { + return true; + } + } + if (unicodeBlockLookup['General Punctuation'](char)) { + if (char === 0x2016 /* double vertical line */ || + char === 0x2020 /* dagger */ || + char === 0x2021 /* double dagger */ || + char === 0x2030 /* per mille sign */ || + char === 0x2031 /* per ten thousand sign */ || + char === 0x203B /* reference mark */ || + char === 0x203C /* double exclamation mark */ || + char === 0x2042 /* asterism */ || + char === 0x2047 /* double question mark */ || + char === 0x2048 /* question exclamation mark */ || + char === 0x2049 /* exclamation question mark */ || + char === 0x2051 /* two asterisks aligned vertically */) { + return true; + } + } + if (unicodeBlockLookup['Letterlike Symbols'](char)) + return true; + if (unicodeBlockLookup['Number Forms'](char)) + return true; + if (unicodeBlockLookup['Miscellaneous Technical'](char)) { + if ((char >= 0x2300 /* diameter sign */ && char <= 0x2307 /* wavy line */) || + (char >= 0x230C /* bottom right crop */ && char <= 0x231F /* bottom right corner */) || + (char >= 0x2324 /* up arrowhead between two horizontal bars */ && char <= 0x2328 /* keyboard */) || + char === 0x232B /* erase to the left */ || + (char >= 0x237D /* shouldered open box */ && char <= 0x239A /* clear screen symbol */) || + (char >= 0x23BE /* dentistry symbol light vertical and top right */ && char <= 0x23CD /* square foot */) || + char === 0x23CF /* eject symbol */ || + (char >= 0x23D1 /* metrical breve */ && char <= 0x23DB /* fuse */) || + (char >= 0x23E2 /* white trapezium */ && char <= 0x23FF)) { + return true; + } + } + if (unicodeBlockLookup['Control Pictures'](char) && char !== 0x2423 /* open box */) + return true; + if (unicodeBlockLookup['Optical Character Recognition'](char)) + return true; + if (unicodeBlockLookup['Enclosed Alphanumerics'](char)) + return true; + if (unicodeBlockLookup['Geometric Shapes'](char)) + return true; + if (unicodeBlockLookup['Miscellaneous Symbols'](char)) { + if (!((char >= 0x261A /* black left pointing index */ && char <= 0x261F) /* white down pointing index */)) { + return true; + } + } + if (unicodeBlockLookup['Miscellaneous Symbols and Arrows'](char)) { + if ((char >= 0x2B12 /* square with top half black */ && char <= 0x2B2F /* white vertical ellipse */) || + (char >= 0x2B50 /* white medium star */ && char <= 0x2B59 /* heavy circled saltire */) || + (char >= 0x2BB8 /* upwards white arrow from bar with horizontal bar */ && char <= 0x2BEB)) { + return true; + } + } + if (unicodeBlockLookup['CJK Symbols and Punctuation'](char)) + return true; + if (unicodeBlockLookup['Katakana'](char)) + return true; + if (unicodeBlockLookup['Private Use Area'](char)) + return true; + if (unicodeBlockLookup['CJK Compatibility Forms'](char)) + return true; + if (unicodeBlockLookup['Small Form Variants'](char)) + return true; + if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) + return true; + if (char === 0x221E /* infinity */ || + char === 0x2234 /* therefore */ || + char === 0x2235 /* because */ || + (char >= 0x2700 /* black safety scissors */ && char <= 0x2767 /* rotated floral heart bullet */) || + (char >= 0x2776 /* dingbat negative circled digit one */ && char <= 0x2793 /* dingbat negative circled sans-serif number ten */) || + char === 0xFFFC /* object replacement character */ || + char === 0xFFFD /* replacement character */) { + return true; + } + return false; +} +/** + * Returns true if the given Unicode codepoint identifies a character with + * rotated orientation. + * + * A character has rotated orientation if it is drawn rotated when the line is + * oriented vertically, even if both adjacent characters are upright. For + * example, a Latin letter is drawn rotated along a vertical line. A rotated + * character causes an adjacent “neutral” character to be drawn rotated as well. + */ +function charHasRotatedVerticalOrientation(char) { + return !(charHasUprightVerticalOrientation(char) || + charHasNeutralVerticalOrientation(char)); +} +function charInComplexShapingScript(char) { + return /\p{sc=Arab}/u.test(String.fromCodePoint(char)); +} +/** + * ISO 15924 script codes of scripts that are primarily written horizontally + * right-to-left according to Unicode 16.0.0. + */ +const rtlScriptCodes = [ + 'Adlm', // Adlam + 'Arab', // Arabic + 'Armi', // Imperial Aramaic + 'Avst', // Avestan + 'Chrs', // Chorasmian + 'Cprt', // Cypriot + 'Egyp', // Egyptian Hieroglyphs + 'Elym', // Elymaic + 'Gara', // Garay + 'Hatr', // Hatran + 'Hebr', // Hebrew + 'Hung', // Old Hungarian + 'Khar', // Kharoshthi + 'Lydi', // Lydian + 'Mand', // Mandaic + 'Mani', // Manichaean + 'Mend', // Mende Kikakui + 'Merc', // Meroitic Cursive + 'Mero', // Meroitic Hieroglyphs + 'Narb', // Old North Arabian + 'Nbat', // Nabataean + 'Nkoo', // NKo + 'Orkh', // Old Turkic + 'Palm', // Palmyrene + 'Phli', // Inscriptional Pahlavi + 'Phlp', // Psalter Pahlavi + 'Phnx', // Phoenician + 'Prti', // Inscriptional Parthian + 'Rohg', // Hanifi Rohingya + 'Samr', // Samaritan + 'Sarb', // Old South Arabian + 'Sogo', // Old Sogdian + 'Syrc', // Syriac + 'Thaa', // Thaana + 'Todr', // Todhri + 'Yezi', // Yezidi +]; +const rtlScriptRegExp = sanitizedRegExpFromScriptCodes(rtlScriptCodes); +function charInRTLScript(char) { + return rtlScriptRegExp.test(String.fromCodePoint(char)); +} +function charInSupportedScript(char, canRenderRTL) { + // This is a rough heuristic: whether we "can render" a script + // actually depends on the properties of the font being used + // and whether differences from the ideal rendering are considered + // semantically significant. + // Even in Latin script, we "can't render" combinations such as the fi + // ligature, but we don't consider that semantically significant. + if (!canRenderRTL && charInRTLScript(char)) { + return false; + } + if ((char >= 0x0900 && char <= 0x0DFF) || + // Main blocks for Indic scripts and Sinhala + (char >= 0x0F00 && char <= 0x109F) || + // Main blocks for Tibetan and Myanmar + unicodeBlockLookup['Khmer'](char)) { + // These blocks cover common scripts that require + // complex text shaping, based on unicode script metadata: + // https://www.unicode.org/repos/cldr/trunk/common/properties/scriptMetadata.txt + // where "Web Rank <= 32" "Shaping Required = YES" + return false; + } + return true; +} +function stringContainsRTLText(chars) { + for (const char of chars) { + if (charInRTLScript(char.charCodeAt(0))) { + return true; + } + } + return false; +} +function isStringInSupportedScript(chars, canRenderRTL) { + for (const char of chars) { + if (!charInSupportedScript(char.charCodeAt(0), canRenderRTL)) { + return false; + } + } + return true; +} + +class RTLWorkerPlugin { + constructor() { + this.applyArabicShaping = null; + this.processBidirectionalText = null; + this.processStyledBidirectionalText = null; + this.pluginStatus = 'unavailable'; + this.pluginURL = null; + } + setState(state) { + this.pluginStatus = state.pluginStatus; + this.pluginURL = state.pluginURL; + } + getState() { + return { + pluginStatus: this.pluginStatus, + pluginURL: this.pluginURL + }; + } + setMethods(rtlTextPlugin) { + this.applyArabicShaping = rtlTextPlugin.applyArabicShaping; + this.processBidirectionalText = rtlTextPlugin.processBidirectionalText; + this.processStyledBidirectionalText = rtlTextPlugin.processStyledBidirectionalText; + } + isParsed() { + return this.applyArabicShaping != null && + this.processBidirectionalText != null && + this.processStyledBidirectionalText != null; + } + getPluginURL() { + return this.pluginURL; + } + getRTLTextPluginStatus() { + return this.pluginStatus; + } +} +const rtlWorkerPlugin = new RTLWorkerPlugin(); + +/** + * @internal + * A parameter that can be evaluated to a value + */ +class EvaluationParameters { + // "options" may also be another EvaluationParameters to copy, see CrossFadedProperty.possiblyEvaluate + constructor(zoom, options) { + this.zoom = zoom; + if (options) { + this.now = options.now; + this.fadeDuration = options.fadeDuration; + this.zoomHistory = options.zoomHistory; + this.transition = options.transition; + } + else { + this.now = 0; + this.fadeDuration = 0; + this.zoomHistory = new ZoomHistory(); + this.transition = {}; + } + } + isSupportedScript(str) { + return isStringInSupportedScript(str, rtlWorkerPlugin.getRTLTextPluginStatus() === 'loaded'); + } + crossFadingFactor() { + if (this.fadeDuration === 0) { + return 1; + } + else { + return Math.min((this.now - this.zoomHistory.lastIntegerZoomTime) / this.fadeDuration, 1); + } + } + getCrossfadeParameters() { + const z = this.zoom; + const fraction = z - Math.floor(z); + const t = this.crossFadingFactor(); + return z > this.zoomHistory.lastIntegerZoom ? + { fromScale: 2, toScale: 1, t: fraction + (1 - fraction) * t } : + { fromScale: 0.5, toScale: 1, t: 1 - (1 - t) * fraction }; + } +} + +/** + * @internal + * `PropertyValue` represents the value part of a property key-value unit. It's used to represent both + * paint and layout property values, and regardless of whether or not their property supports data-driven + * expressions. + * + * `PropertyValue` stores the raw input value as seen in a style or a runtime styling API call, i.e. one of the + * following: + * + * * A constant value of the type appropriate for the property + * * A function which produces a value of that type (but functions are quasi-deprecated in favor of expressions) + * * An expression which produces a value of that type + * * "undefined"/"not present", in which case the property is assumed to take on its default value. + * + * In addition to storing the original input value, `PropertyValue` also stores a normalized representation, + * effectively treating functions as if they are expressions, and constant or default values as if they are + * (constant) expressions. + */ +class PropertyValue { + constructor(property, value) { + this.property = property; + this.value = value; + this.expression = normalizePropertyExpression(value === undefined ? property.specification.default : value, property.specification); + } + isDataDriven() { + return this.expression.kind === 'source' || this.expression.kind === 'composite'; + } + possiblyEvaluate(parameters, canonical, availableImages) { + return this.property.possiblyEvaluate(this, parameters, canonical, availableImages); + } +} +/** + * @internal + * Paint properties are _transitionable_: they can change in a fluid manner, interpolating or cross-fading between + * old and new value. The duration of the transition, and the delay before it begins, is configurable. + * + * `TransitionablePropertyValue` is a compositional class that stores both the property value and that transition + * configuration. + * + * A `TransitionablePropertyValue` can calculate the next step in the evaluation chain for paint property values: + * `TransitioningPropertyValue`. + */ +class TransitionablePropertyValue { + constructor(property) { + this.property = property; + this.value = new PropertyValue(property, undefined); + } + transitioned(parameters, prior) { + return new TransitioningPropertyValue(this.property, this.value, prior, extend$1({}, parameters.transition, this.transition), parameters.now); + } + untransitioned() { + return new TransitioningPropertyValue(this.property, this.value, null, {}, 0); + } +} +/** + * @internal + * `Transitionable` stores a map of all (property name, `TransitionablePropertyValue`) pairs for paint properties of a + * given layer type. It can calculate the `TransitioningPropertyValue`s for all of them at once, producing a + * `Transitioning` instance for the same set of properties. + */ +class Transitionable { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultTransitionablePropertyValues); + } + getValue(name) { + return clone$9(this._values[name].value.value); + } + setValue(name, value) { + if (!Object.prototype.hasOwnProperty.call(this._values, name)) { + this._values[name] = new TransitionablePropertyValue(this._values[name].property); + } + // Note that we do not _remove_ an own property in the case where a value is being reset + // to the default: the transition might still be non-default. + this._values[name].value = new PropertyValue(this._values[name].property, value === null ? undefined : clone$9(value)); + } + getTransition(name) { + return clone$9(this._values[name].transition); + } + setTransition(name, value) { + if (!Object.prototype.hasOwnProperty.call(this._values, name)) { + this._values[name] = new TransitionablePropertyValue(this._values[name].property); + } + this._values[name].transition = clone$9(value) || undefined; + } + serialize() { + const result = {}; + for (const property of Object.keys(this._values)) { + const value = this.getValue(property); + if (value !== undefined) { + result[property] = value; + } + const transition = this.getTransition(property); + if (transition !== undefined) { + result[`${property}-transition`] = transition; + } + } + return result; + } + transitioned(parameters, prior) { + const result = new Transitioning(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].transitioned(parameters, prior._values[property]); + } + return result; + } + untransitioned() { + const result = new Transitioning(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].untransitioned(); + } + return result; + } +} +/** + * @internal + * `TransitioningPropertyValue` implements the first of two intermediate steps in the evaluation chain of a paint + * property value. In this step, transitions between old and new values are handled: as long as the transition is in + * progress, `TransitioningPropertyValue` maintains a reference to the prior value, and interpolates between it and + * the new value based on the current time and the configured transition duration and delay. The product is the next + * step in the evaluation chain: the "possibly evaluated" result type `R`. See below for more on this concept. + */ +class TransitioningPropertyValue { + constructor(property, value, prior, transition, now) { + this.property = property; + this.value = value; + this.begin = now + transition.delay || 0; + this.end = this.begin + transition.duration || 0; + if (property.specification.transition && (transition.delay || transition.duration)) { + this.prior = prior; + } + } + possiblyEvaluate(parameters, canonical, availableImages) { + const now = parameters.now || 0; + const finalValue = this.value.possiblyEvaluate(parameters, canonical, availableImages); + const prior = this.prior; + if (!prior) { + // No prior value. + return finalValue; + } + else if (now > this.end) { + // Transition from prior value is now complete. + this.prior = null; + return finalValue; + } + else if (this.value.isDataDriven()) { + // Transitions to data-driven properties are not supported. + // We snap immediately to the data-driven value so that, when we perform layout, + // we see the data-driven function and can use it to populate vertex buffers. + this.prior = null; + return finalValue; + } + else if (now < this.begin) { + // Transition hasn't started yet. + return prior.possiblyEvaluate(parameters, canonical, availableImages); + } + else { + // Interpolate between recursively-calculated prior value and final. + const t = (now - this.begin) / (this.end - this.begin); + return this.property.interpolate(prior.possiblyEvaluate(parameters, canonical, availableImages), finalValue, easeCubicInOut(t)); + } + } +} +/** + * @internal + * `Transitioning` stores a map of all (property name, `TransitioningPropertyValue`) pairs for paint properties of a + * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a + * `PossiblyEvaluated` instance for the same set of properties. + */ +class Transitioning { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultTransitioningPropertyValues); + } + possiblyEvaluate(parameters, canonical, availableImages) { + const result = new PossiblyEvaluated(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages); + } + return result; + } + hasTransition() { + for (const property of Object.keys(this._values)) { + if (this._values[property].prior) { + return true; + } + } + return false; + } +} +// ------- Layout ------- +/** + * Because layout properties are not transitionable, they have a simpler representation and evaluation chain than + * paint properties: `PropertyValue`s are possibly evaluated, producing possibly evaluated values, which are then + * fully evaluated. + * + * `Layout` stores a map of all (property name, `PropertyValue`) pairs for layout properties of a + * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a + * `PossiblyEvaluated` instance for the same set of properties. + */ +class Layout { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultPropertyValues); + } + hasValue(name) { + return this._values[name].value !== undefined; + } + getValue(name) { + return clone$9(this._values[name].value); + } + setValue(name, value) { + this._values[name] = new PropertyValue(this._values[name].property, value === null ? undefined : clone$9(value)); + } + serialize() { + const result = {}; + for (const property of Object.keys(this._values)) { + const value = this.getValue(property); + if (value !== undefined) { + result[property] = value; + } + } + return result; + } + possiblyEvaluate(parameters, canonical, availableImages) { + const result = new PossiblyEvaluated(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages); + } + return result; + } +} +/** + * @internal + * `PossiblyEvaluatedPropertyValue` is used for data-driven paint and layout property values. It holds a + * `PossiblyEvaluatedValue` and the `GlobalProperties` that were used to generate it. You're not allowed to supply + * a different set of `GlobalProperties` when performing the final evaluation because they would be ignored in the + * case where the input value was a constant or camera function. + */ +class PossiblyEvaluatedPropertyValue { + constructor(property, value, parameters) { + this.property = property; + this.value = value; + this.parameters = parameters; + } + isConstant() { + return this.value.kind === 'constant'; + } + constantOr(value) { + if (this.value.kind === 'constant') { + return this.value.value; + } + else { + return value; + } + } + evaluate(feature, featureState, canonical, availableImages) { + return this.property.evaluate(this.value, this.parameters, feature, featureState, canonical, availableImages); + } +} +/** + * @internal + * `PossiblyEvaluated` stores a map of all (property name, `R`) pairs for paint or layout properties of a + * given layer type. + */ +class PossiblyEvaluated { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultPossiblyEvaluatedValues); + } + get(name) { + return this._values[name]; + } +} +/** + * @internal + * An implementation of `Property` for properties that do not permit data-driven (source or composite) expressions. + * This restriction allows us to declare statically that the result of possibly evaluating this kind of property + * is in fact always the scalar type `T`, and can be used without further evaluating the value on a per-feature basis. + */ +class DataConstantProperty { + constructor(specification) { + this.specification = specification; + } + possiblyEvaluate(value, parameters) { + if (value.isDataDriven()) + throw new Error('Value should not be data driven'); + return value.expression.evaluate(parameters); + } + interpolate(a, b, t) { + const interpolationType = this.specification.type; + const interpolationFn = interpolate[interpolationType]; + if (interpolationFn) { + return interpolationFn(a, b, t); + } + else { + return a; + } + } +} +/** + * @internal + * An implementation of `Property` for properties that permit data-driven (source or composite) expressions. + * The result of possibly evaluating this kind of property is `PossiblyEvaluatedPropertyValue`; obtaining + * a scalar value `T` requires further evaluation on a per-feature basis. + */ +class DataDrivenProperty { + constructor(specification, overrides) { + this.specification = specification; + this.overrides = overrides; + } + possiblyEvaluate(value, parameters, canonical, availableImages) { + if (value.expression.kind === 'constant' || value.expression.kind === 'camera') { + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: value.expression.evaluate(parameters, null, {}, canonical, availableImages) }, parameters); + } + else { + return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters); + } + } + interpolate(a, b, t) { + // If either possibly-evaluated value is non-constant, give up: we aren't able to interpolate data-driven values. + if (a.value.kind !== 'constant' || b.value.kind !== 'constant') { + return a; + } + // Special case hack solely for fill-outline-color. The undefined value is subsequently handled in + // FillStyleLayer#recalculate, which sets fill-outline-color to the fill-color value if the former + // is a PossiblyEvaluatedPropertyValue containing a constant undefined value. In addition to the + // return value here, the other source of a PossiblyEvaluatedPropertyValue containing a constant + // undefined value is the "default value" for fill-outline-color held in + // `Properties#defaultPossiblyEvaluatedValues`, which serves as the prototype of + // `PossiblyEvaluated#_values`. + if (a.value.value === undefined || b.value.value === undefined) { + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: undefined }, a.parameters); + } + const interpolationType = this.specification.type; + const interpolationFn = interpolate[interpolationType]; + if (interpolationFn) { + const interpolatedValue = interpolationFn(a.value.value, b.value.value, t); + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: interpolatedValue }, a.parameters); + } + else { + return a; + } + } + evaluate(value, parameters, feature, featureState, canonical, availableImages) { + if (value.kind === 'constant') { + return value.value; + } + else { + return value.evaluate(parameters, feature, featureState, canonical, availableImages); + } + } +} +/** + * @internal + * An implementation of `Property` for data driven `line-pattern` which are transitioned by cross-fading + * rather than interpolation. + */ +class CrossFadedDataDrivenProperty extends DataDrivenProperty { + possiblyEvaluate(value, parameters, canonical, availableImages) { + if (value.value === undefined) { + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: undefined }, parameters); + } + else if (value.expression.kind === 'constant') { + const evaluatedValue = value.expression.evaluate(parameters, null, {}, canonical, availableImages); + const isImageExpression = value.property.specification.type === 'resolvedImage'; + const constantValue = isImageExpression && typeof evaluatedValue !== 'string' ? evaluatedValue.name : evaluatedValue; + const constant = this._calculate(constantValue, constantValue, constantValue, parameters); + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: constant }, parameters); + } + else if (value.expression.kind === 'camera') { + const cameraVal = this._calculate(value.expression.evaluate({ zoom: parameters.zoom - 1.0 }), value.expression.evaluate({ zoom: parameters.zoom }), value.expression.evaluate({ zoom: parameters.zoom + 1.0 }), parameters); + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: cameraVal }, parameters); + } + else { + // source or composite expression + return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters); + } + } + evaluate(value, globals, feature, featureState, canonical, availableImages) { + if (value.kind === 'source') { + const constant = value.evaluate(globals, feature, featureState, canonical, availableImages); + return this._calculate(constant, constant, constant, globals); + } + else if (value.kind === 'composite') { + return this._calculate(value.evaluate({ zoom: Math.floor(globals.zoom) - 1.0 }, feature, featureState), value.evaluate({ zoom: Math.floor(globals.zoom) }, feature, featureState), value.evaluate({ zoom: Math.floor(globals.zoom) + 1.0 }, feature, featureState), globals); + } + else { + return value.value; + } + } + _calculate(min, mid, max, parameters) { + const z = parameters.zoom; + return z > parameters.zoomHistory.lastIntegerZoom ? { from: min, to: mid } : { from: max, to: mid }; + } + interpolate(a) { + return a; + } +} +/** + * @internal + * An implementation of `Property` for `*-pattern` and `line-dasharray`, which are transitioned by cross-fading + * rather than interpolation. + */ +class CrossFadedProperty { + constructor(specification) { + this.specification = specification; + } + possiblyEvaluate(value, parameters, canonical, availableImages) { + if (value.value === undefined) { + return undefined; + } + else if (value.expression.kind === 'constant') { + const constant = value.expression.evaluate(parameters, null, {}, canonical, availableImages); + return this._calculate(constant, constant, constant, parameters); + } + else { + return this._calculate(value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom - 1.0), parameters)), value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom), parameters)), value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom + 1.0), parameters)), parameters); + } + } + _calculate(min, mid, max, parameters) { + const z = parameters.zoom; + return z > parameters.zoomHistory.lastIntegerZoom ? { from: min, to: mid } : { from: max, to: mid }; + } + interpolate(a) { + return a; + } +} +/** + * @internal + * An implementation of `Property` for `heatmap-color` and `line-gradient`. Interpolation is a no-op, and + * evaluation returns a boolean value in order to indicate its presence, but the real + * evaluation happens in StyleLayer classes. + */ +class ColorRampProperty { + constructor(specification) { + this.specification = specification; + } + possiblyEvaluate(value, parameters, canonical, availableImages) { + return !!value.expression.evaluate(parameters, null, {}, canonical, availableImages); + } + interpolate() { return false; } +} +/** + * @internal + * `Properties` holds objects containing default values for the layout or paint property set of a given + * layer type. These objects are immutable, and they are used as the prototypes for the `_values` members of + * `Transitionable`, `Transitioning`, `Layout`, and `PossiblyEvaluated`. This allows these classes to avoid + * doing work in the common case where a property has no explicit value set and should be considered to take + * on the default value: using `for (const property of Object.keys(this._values))`, they can iterate over + * only the _own_ properties of `_values`, skipping repeated calculation of transitions and possible/final + * evaluations for defaults, the result of which will always be the same. + */ +class Properties { + constructor(properties) { + this.properties = properties; + this.defaultPropertyValues = {}; + this.defaultTransitionablePropertyValues = {}; + this.defaultTransitioningPropertyValues = {}; + this.defaultPossiblyEvaluatedValues = {}; + this.overridableProperties = []; + for (const property in properties) { + const prop = properties[property]; + if (prop.specification.overridable) { + this.overridableProperties.push(property); + } + const defaultPropertyValue = this.defaultPropertyValues[property] = + new PropertyValue(prop, undefined); + const defaultTransitionablePropertyValue = this.defaultTransitionablePropertyValues[property] = + new TransitionablePropertyValue(prop); + this.defaultTransitioningPropertyValues[property] = + defaultTransitionablePropertyValue.untransitioned(); + this.defaultPossiblyEvaluatedValues[property] = + defaultPropertyValue.possiblyEvaluate({}); + } + } +} +register('DataDrivenProperty', DataDrivenProperty); +register('DataConstantProperty', DataConstantProperty); +register('CrossFadedDataDrivenProperty', CrossFadedDataDrivenProperty); +register('CrossFadedProperty', CrossFadedProperty); +register('ColorRampProperty', ColorRampProperty); + +const TRANSITION_SUFFIX = '-transition'; +/** + * A base class for style layers + */ +class StyleLayer extends Evented { + constructor(layer, properties) { + super(); + this.id = layer.id; + this.type = layer.type; + this._featureFilter = { filter: () => true, needGeometry: false }; + if (layer.type === 'custom') + return; + layer = layer; + this.metadata = layer.metadata; + this.minzoom = layer.minzoom; + this.maxzoom = layer.maxzoom; + if (layer.type !== 'background') { + this.source = layer.source; + this.sourceLayer = layer['source-layer']; + this.filter = layer.filter; + } + if (properties.layout) { + this._unevaluatedLayout = new Layout(properties.layout); + } + if (properties.paint) { + this._transitionablePaint = new Transitionable(properties.paint); + for (const property in layer.paint) { + this.setPaintProperty(property, layer.paint[property], { validate: false }); + } + for (const property in layer.layout) { + this.setLayoutProperty(property, layer.layout[property], { validate: false }); + } + this._transitioningPaint = this._transitionablePaint.untransitioned(); + //$FlowFixMe + this.paint = new PossiblyEvaluated(properties.paint); + } + } + getCrossfadeParameters() { + return this._crossfadeParameters; + } + getLayoutProperty(name) { + if (name === 'visibility') { + return this.visibility; + } + return this._unevaluatedLayout.getValue(name); + } + setLayoutProperty(name, value, options = {}) { + if (value !== null && value !== undefined) { + const key = `layers.${this.id}.layout.${name}`; + if (this._validate(validateLayoutProperty, key, name, value, options)) { + return; + } + } + if (name === 'visibility') { + this.visibility = value; + return; + } + this._unevaluatedLayout.setValue(name, value); + } + getPaintProperty(name) { + if (name.endsWith(TRANSITION_SUFFIX)) { + return this._transitionablePaint.getTransition(name.slice(0, -TRANSITION_SUFFIX.length)); + } + else { + return this._transitionablePaint.getValue(name); + } + } + setPaintProperty(name, value, options = {}) { + if (value !== null && value !== undefined) { + const key = `layers.${this.id}.paint.${name}`; + if (this._validate(validatePaintProperty, key, name, value, options)) { + return false; + } + } + if (name.endsWith(TRANSITION_SUFFIX)) { + this._transitionablePaint.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), value || undefined); + return false; + } + else { + const transitionable = this._transitionablePaint._values[name]; + const isCrossFadedProperty = transitionable.property.specification['property-type'] === 'cross-faded-data-driven'; + const wasDataDriven = transitionable.value.isDataDriven(); + const oldValue = transitionable.value; + this._transitionablePaint.setValue(name, value); + this._handleSpecialPaintPropertyUpdate(name); + const newValue = this._transitionablePaint._values[name].value; + const isDataDriven = newValue.isDataDriven(); + // if a cross-faded value is changed, we need to make sure the new icons get added to each tile's iconAtlas + // so a call to _updateLayer is necessary, and we return true from this function so it gets called in + // Style#setPaintProperty + return isDataDriven || wasDataDriven || isCrossFadedProperty || this._handleOverridablePaintPropertyUpdate(name, oldValue, newValue); + } + } + _handleSpecialPaintPropertyUpdate(_) { + // No-op; can be overridden by derived classes. + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) { + // No-op; can be overridden by derived classes. + return false; + } + isHidden(zoom) { + if (this.minzoom && zoom < this.minzoom) + return true; + if (this.maxzoom && zoom >= this.maxzoom) + return true; + return this.visibility === 'none'; + } + updateTransitions(parameters) { + this._transitioningPaint = this._transitionablePaint.transitioned(parameters, this._transitioningPaint); + } + hasTransition() { + return this._transitioningPaint.hasTransition(); + } + recalculate(parameters, availableImages) { + if (parameters.getCrossfadeParameters) { + this._crossfadeParameters = parameters.getCrossfadeParameters(); + } + if (this._unevaluatedLayout) { + this.layout = this._unevaluatedLayout.possiblyEvaluate(parameters, undefined, availableImages); + } + this.paint = this._transitioningPaint.possiblyEvaluate(parameters, undefined, availableImages); + } + serialize() { + const output = { + 'id': this.id, + 'type': this.type, + 'source': this.source, + 'source-layer': this.sourceLayer, + 'metadata': this.metadata, + 'minzoom': this.minzoom, + 'maxzoom': this.maxzoom, + 'filter': this.filter, + 'layout': this._unevaluatedLayout && this._unevaluatedLayout.serialize(), + 'paint': this._transitionablePaint && this._transitionablePaint.serialize() + }; + if (this.visibility) { + output.layout = output.layout || {}; + output.layout.visibility = this.visibility; + } + return filterObject(output, (value, key) => { + return value !== undefined && + !(key === 'layout' && !Object.keys(value).length) && + !(key === 'paint' && !Object.keys(value).length); + }); + } + _validate(validate, key, name, value, options = {}) { + if (options && options.validate === false) { + return false; + } + return emitValidationErrors(this, validate.call(validateStyle, { + key, + layerType: this.type, + objectKey: name, + value, + styleSpec: v8Spec, + // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407 + style: { glyphs: true, sprite: true } + })); + } + is3D() { + return false; + } + isTileClipped() { + return false; + } + hasOffscreenPass() { + return false; + } + resize() { + // noop + } + isStateDependent() { + for (const property in this.paint._values) { + const value = this.paint.get(property); + if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) { + continue; + } + if ((value.value.kind === 'source' || value.value.kind === 'composite') && + value.value.isStateDependent) { + return true; + } + } + return false; + } +} + +// Note: all "sizes" are measured in bytes +/** + * @internal + * A view type size + */ +const viewTypes = { + 'Int8': Int8Array, + 'Uint8': Uint8Array, + 'Int16': Int16Array, + 'Uint16': Uint16Array, + 'Int32': Int32Array, + 'Uint32': Uint32Array, + 'Float32': Float32Array +}; +/** @internal */ +class Struct { + /** + * @param structArray - The StructArray the struct is stored in + * @param index - The index of the struct in the StructArray. + */ + constructor(structArray, index) { + this._structArray = structArray; + this._pos1 = index * this.size; + this._pos2 = this._pos1 / 2; + this._pos4 = this._pos1 / 4; + this._pos8 = this._pos1 / 8; + } +} +const DEFAULT_CAPACITY = 128; +const RESIZE_MULTIPLIER = 5; +/** + * @internal + * `StructArray` provides an abstraction over `ArrayBuffer` and `TypedArray` + * making it behave like an array of typed structs. + * + * Conceptually, a StructArray is comprised of elements, i.e., instances of its + * associated struct type. Each particular struct type, together with an + * alignment size, determines the memory layout of a StructArray whose elements + * are of that type. Thus, for each such layout that we need, we have + * a corresponding StructArrayLayout class, inheriting from StructArray and + * implementing `emplaceBack()` and `_refreshViews()`. + * + * In some cases, where we need to access particular elements of a StructArray, + * we implement a more specific subclass that inherits from one of the + * StructArrayLayouts and adds a `get(i): T` accessor that returns a structured + * object whose properties are proxies into the underlying memory space for the + * i-th element. This affords the convenience of working with (seemingly) plain + * Javascript objects without the overhead of serializing/deserializing them + * into ArrayBuffers for efficient web worker transfer. + */ +class StructArray { + constructor() { + this.isTransferred = false; + this.capacity = -1; + this.resize(0); + } + /** + * Serialize a StructArray instance. Serializes both the raw data and the + * metadata needed to reconstruct the StructArray base class during + * deserialization. + */ + static serialize(array, transferables) { + array._trim(); + if (transferables) { + array.isTransferred = true; + transferables.push(array.arrayBuffer); + } + return { + length: array.length, + arrayBuffer: array.arrayBuffer, + }; + } + static deserialize(input) { + const structArray = Object.create(this.prototype); + structArray.arrayBuffer = input.arrayBuffer; + structArray.length = input.length; + structArray.capacity = input.arrayBuffer.byteLength / structArray.bytesPerElement; + structArray._refreshViews(); + return structArray; + } + /** + * Resize the array to discard unused capacity. + */ + _trim() { + if (this.length !== this.capacity) { + this.capacity = this.length; + this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement); + this._refreshViews(); + } + } + /** + * Resets the length of the array to 0 without de-allocating capacity. + */ + clear() { + this.length = 0; + } + /** + * Resize the array. + * If `n` is greater than the current length then additional elements with undefined values are added. + * If `n` is less than the current length then the array will be reduced to the first `n` elements. + * @param n - The new size of the array. + */ + resize(n) { + this.reserve(n); + this.length = n; + } + /** + * Indicate a planned increase in size, so that any necessary allocation may + * be done once, ahead of time. + * @param n - The expected size of the array. + */ + reserve(n) { + if (n > this.capacity) { + this.capacity = Math.max(n, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY); + this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement); + const oldUint8Array = this.uint8; + this._refreshViews(); + if (oldUint8Array) + this.uint8.set(oldUint8Array); + } + } + /** + * Create TypedArray views for the current ArrayBuffer. + */ + _refreshViews() { + throw new Error('_refreshViews() must be implemented by each concrete StructArray layout'); + } +} +/** + * Given a list of member fields, create a full StructArrayLayout, in + * particular calculating the correct byte offset for each field. This data + * is used at build time to generate StructArrayLayout_*#emplaceBack() and + * other accessors, and at runtime for binding vertex buffer attributes. + */ +function createLayout(members, alignment = 1) { + let offset = 0; + let maxSize = 0; + const layoutMembers = members.map((member) => { + const typeSize = sizeOf(member.type); + const memberOffset = offset = align$1(offset, Math.max(alignment, typeSize)); + const components = member.components || 1; + maxSize = Math.max(maxSize, typeSize); + offset += typeSize * components; + return { + name: member.name, + type: member.type, + components, + offset: memberOffset, + }; + }); + const size = align$1(offset, Math.max(maxSize, alignment)); + return { + members: layoutMembers, + size, + alignment + }; +} +function sizeOf(type) { + return viewTypes[type].BYTES_PER_ELEMENT; +} +function align$1(offset, size) { + return Math.ceil(offset / size) * size; +} + +// This file is generated. Edit build/generate-struct-arrays.ts, then run `npm run codegen`. +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * + */ +class StructArrayLayout2i4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1); + } + emplace(i, v0, v1) { + const o2 = i * 2; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + return i; + } +} +StructArrayLayout2i4.prototype.bytesPerElement = 4; +register('StructArrayLayout2i4', StructArrayLayout2i4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[3] + * + */ +class StructArrayLayout3i6 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o2 = i * 3; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + return i; + } +} +StructArrayLayout3i6.prototype.bytesPerElement = 6; +register('StructArrayLayout3i6', StructArrayLayout3i6); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[4] + * + */ +class StructArrayLayout4i8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3); + } + emplace(i, v0, v1, v2, v3) { + const o2 = i * 4; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + return i; + } +} +StructArrayLayout4i8.prototype.bytesPerElement = 8; +register('StructArrayLayout4i8', StructArrayLayout4i8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Int16[4] + * + */ +class StructArrayLayout2i4i12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o2 = i * 6; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + return i; + } +} +StructArrayLayout2i4i12.prototype.bytesPerElement = 12; +register('StructArrayLayout2i4i12', StructArrayLayout2i4i12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Uint8[4] + * + */ +class StructArrayLayout2i4ub8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o2 = i * 4; + const o1 = i * 8; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.uint8[o1 + 4] = v2; + this.uint8[o1 + 5] = v3; + this.uint8[o1 + 6] = v4; + this.uint8[o1 + 7] = v5; + return i; + } +} +StructArrayLayout2i4ub8.prototype.bytesPerElement = 8; +register('StructArrayLayout2i4ub8', StructArrayLayout2i4ub8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[2] + * + */ +class StructArrayLayout2f8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1); + } + emplace(i, v0, v1) { + const o4 = i * 2; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + return i; + } +} +StructArrayLayout2f8.prototype.bytesPerElement = 8; +register('StructArrayLayout2f8', StructArrayLayout2f8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[10] + * + */ +class StructArrayLayout10ui20 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) { + const o2 = i * 10; + this.uint16[o2 + 0] = v0; + this.uint16[o2 + 1] = v1; + this.uint16[o2 + 2] = v2; + this.uint16[o2 + 3] = v3; + this.uint16[o2 + 4] = v4; + this.uint16[o2 + 5] = v5; + this.uint16[o2 + 6] = v6; + this.uint16[o2 + 7] = v7; + this.uint16[o2 + 8] = v8; + this.uint16[o2 + 9] = v9; + return i; + } +} +StructArrayLayout10ui20.prototype.bytesPerElement = 20; +register('StructArrayLayout10ui20', StructArrayLayout10ui20); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[4] + * [8] - Uint16[4] + * [16] - Int16[4] + * + */ +class StructArrayLayout4i4ui4i24 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) { + const o2 = i * 12; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.uint16[o2 + 4] = v4; + this.uint16[o2 + 5] = v5; + this.uint16[o2 + 6] = v6; + this.uint16[o2 + 7] = v7; + this.int16[o2 + 8] = v8; + this.int16[o2 + 9] = v9; + this.int16[o2 + 10] = v10; + this.int16[o2 + 11] = v11; + return i; + } +} +StructArrayLayout4i4ui4i24.prototype.bytesPerElement = 24; +register('StructArrayLayout4i4ui4i24', StructArrayLayout4i4ui4i24); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[3] + * + */ +class StructArrayLayout3f12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o4 = i * 3; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + return i; + } +} +StructArrayLayout3f12.prototype.bytesPerElement = 12; +register('StructArrayLayout3f12', StructArrayLayout3f12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint32[1] + * + */ +class StructArrayLayout1ul4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + } + emplaceBack(v0) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0); + } + emplace(i, v0) { + const o4 = i * 1; + this.uint32[o4 + 0] = v0; + return i; + } +} +StructArrayLayout1ul4.prototype.bytesPerElement = 4; +register('StructArrayLayout1ul4', StructArrayLayout1ul4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[6] + * [12] - Uint32[1] + * [16] - Uint16[2] + * + */ +class StructArrayLayout6i1ul2ui20 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8) { + const o2 = i * 10; + const o4 = i * 5; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + this.uint32[o4 + 3] = v6; + this.uint16[o2 + 8] = v7; + this.uint16[o2 + 9] = v8; + return i; + } +} +StructArrayLayout6i1ul2ui20.prototype.bytesPerElement = 20; +register('StructArrayLayout6i1ul2ui20', StructArrayLayout6i1ul2ui20); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Int16[2] + * [8] - Int16[2] + * + */ +class StructArrayLayout2i2i2i12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o2 = i * 6; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + return i; + } +} +StructArrayLayout2i2i2i12.prototype.bytesPerElement = 12; +register('StructArrayLayout2i2i2i12', StructArrayLayout2i2i2i12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[2] + * [8] - Float32[1] + * [12] - Int16[2] + * + */ +class StructArrayLayout2f1f2i16 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4); + } + emplace(i, v0, v1, v2, v3, v4) { + const o4 = i * 4; + const o2 = i * 8; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + this.int16[o2 + 6] = v3; + this.int16[o2 + 7] = v4; + return i; + } +} +StructArrayLayout2f1f2i16.prototype.bytesPerElement = 16; +register('StructArrayLayout2f1f2i16', StructArrayLayout2f1f2i16); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint8[2] + * [4] - Float32[2] + * [12] - Int16[2] + * + */ +class StructArrayLayout2ub2f2i16 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o1 = i * 16; + const o4 = i * 4; + const o2 = i * 8; + this.uint8[o1 + 0] = v0; + this.uint8[o1 + 1] = v1; + this.float32[o4 + 1] = v2; + this.float32[o4 + 2] = v3; + this.int16[o2 + 6] = v4; + this.int16[o2 + 7] = v5; + return i; + } +} +StructArrayLayout2ub2f2i16.prototype.bytesPerElement = 16; +register('StructArrayLayout2ub2f2i16', StructArrayLayout2ub2f2i16); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[3] + * + */ +class StructArrayLayout3ui6 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o2 = i * 3; + this.uint16[o2 + 0] = v0; + this.uint16[o2 + 1] = v1; + this.uint16[o2 + 2] = v2; + return i; + } +} +StructArrayLayout3ui6.prototype.bytesPerElement = 6; +register('StructArrayLayout3ui6', StructArrayLayout3ui6); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Uint16[2] + * [8] - Uint32[3] + * [20] - Uint16[3] + * [28] - Float32[2] + * [36] - Uint8[3] + * [40] - Uint32[1] + * [44] - Int16[1] + * + */ +class StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) { + const o2 = i * 24; + const o4 = i * 12; + const o1 = i * 48; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.uint16[o2 + 2] = v2; + this.uint16[o2 + 3] = v3; + this.uint32[o4 + 2] = v4; + this.uint32[o4 + 3] = v5; + this.uint32[o4 + 4] = v6; + this.uint16[o2 + 10] = v7; + this.uint16[o2 + 11] = v8; + this.uint16[o2 + 12] = v9; + this.float32[o4 + 7] = v10; + this.float32[o4 + 8] = v11; + this.uint8[o1 + 36] = v12; + this.uint8[o1 + 37] = v13; + this.uint8[o1 + 38] = v14; + this.uint32[o4 + 10] = v15; + this.int16[o2 + 22] = v16; + return i; + } +} +StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48.prototype.bytesPerElement = 48; +register('StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48', StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[8] + * [16] - Uint16[15] + * [48] - Uint32[1] + * [52] - Float32[2] + * [60] - Uint16[2] + * + */ +class StructArrayLayout8i15ui1ul2f2ui64 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(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) { + const i = this.length; + this.resize(i + 1); + 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); + } + 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) { + const o2 = i * 32; + const o4 = i * 16; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + this.int16[o2 + 6] = v6; + this.int16[o2 + 7] = v7; + this.uint16[o2 + 8] = v8; + this.uint16[o2 + 9] = v9; + this.uint16[o2 + 10] = v10; + this.uint16[o2 + 11] = v11; + this.uint16[o2 + 12] = v12; + this.uint16[o2 + 13] = v13; + this.uint16[o2 + 14] = v14; + this.uint16[o2 + 15] = v15; + this.uint16[o2 + 16] = v16; + this.uint16[o2 + 17] = v17; + this.uint16[o2 + 18] = v18; + this.uint16[o2 + 19] = v19; + this.uint16[o2 + 20] = v20; + this.uint16[o2 + 21] = v21; + this.uint16[o2 + 22] = v22; + this.uint32[o4 + 12] = v23; + this.float32[o4 + 13] = v24; + this.float32[o4 + 14] = v25; + this.uint16[o2 + 30] = v26; + this.uint16[o2 + 31] = v27; + return i; + } +} +StructArrayLayout8i15ui1ul2f2ui64.prototype.bytesPerElement = 64; +register('StructArrayLayout8i15ui1ul2f2ui64', StructArrayLayout8i15ui1ul2f2ui64); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[1] + * + */ +class StructArrayLayout1f4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0); + } + emplace(i, v0) { + const o4 = i * 1; + this.float32[o4 + 0] = v0; + return i; + } +} +StructArrayLayout1f4.prototype.bytesPerElement = 4; +register('StructArrayLayout1f4', StructArrayLayout1f4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[1] + * [4] - Float32[2] + * + */ +class StructArrayLayout1ui2f12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o2 = i * 6; + const o4 = i * 3; + this.uint16[o2 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + return i; + } +} +StructArrayLayout1ui2f12.prototype.bytesPerElement = 12; +register('StructArrayLayout1ui2f12', StructArrayLayout1ui2f12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint32[1] + * [4] - Uint16[2] + * + */ +class StructArrayLayout1ul2ui8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o4 = i * 2; + const o2 = i * 4; + this.uint32[o4 + 0] = v0; + this.uint16[o2 + 2] = v1; + this.uint16[o2 + 3] = v2; + return i; + } +} +StructArrayLayout1ul2ui8.prototype.bytesPerElement = 8; +register('StructArrayLayout1ul2ui8', StructArrayLayout1ul2ui8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[2] + * + */ +class StructArrayLayout2ui4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1); + } + emplace(i, v0, v1) { + const o2 = i * 2; + this.uint16[o2 + 0] = v0; + this.uint16[o2 + 1] = v1; + return i; + } +} +StructArrayLayout2ui4.prototype.bytesPerElement = 4; +register('StructArrayLayout2ui4', StructArrayLayout2ui4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[1] + * + */ +class StructArrayLayout1ui2 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0); + } + emplace(i, v0) { + const o2 = i * 1; + this.uint16[o2 + 0] = v0; + return i; + } +} +StructArrayLayout1ui2.prototype.bytesPerElement = 2; +register('StructArrayLayout1ui2', StructArrayLayout1ui2); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[4] + * + */ +class StructArrayLayout4f16 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3); + } + emplace(i, v0, v1, v2, v3) { + const o4 = i * 4; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + this.float32[o4 + 3] = v3; + return i; + } +} +StructArrayLayout4f16.prototype.bytesPerElement = 16; +register('StructArrayLayout4f16', StructArrayLayout4f16); +/** @internal */ +class CollisionBoxStruct extends Struct { + get anchorPointX() { return this._structArray.int16[this._pos2 + 0]; } + get anchorPointY() { return this._structArray.int16[this._pos2 + 1]; } + get x1() { return this._structArray.int16[this._pos2 + 2]; } + get y1() { return this._structArray.int16[this._pos2 + 3]; } + get x2() { return this._structArray.int16[this._pos2 + 4]; } + get y2() { return this._structArray.int16[this._pos2 + 5]; } + get featureIndex() { return this._structArray.uint32[this._pos4 + 3]; } + get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 8]; } + get bucketIndex() { return this._structArray.uint16[this._pos2 + 9]; } + get anchorPoint() { return new Point$3(this.anchorPointX, this.anchorPointY); } +} +CollisionBoxStruct.prototype.size = 20; +/** @internal */ +class CollisionBoxArray extends StructArrayLayout6i1ul2ui20 { + /** + * Return the CollisionBoxStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new CollisionBoxStruct(this, index); + } +} +register('CollisionBoxArray', CollisionBoxArray); +/** @internal */ +class PlacedSymbolStruct extends Struct { + get anchorX() { return this._structArray.int16[this._pos2 + 0]; } + get anchorY() { return this._structArray.int16[this._pos2 + 1]; } + get glyphStartIndex() { return this._structArray.uint16[this._pos2 + 2]; } + get numGlyphs() { return this._structArray.uint16[this._pos2 + 3]; } + get vertexStartIndex() { return this._structArray.uint32[this._pos4 + 2]; } + get lineStartIndex() { return this._structArray.uint32[this._pos4 + 3]; } + get lineLength() { return this._structArray.uint32[this._pos4 + 4]; } + get segment() { return this._structArray.uint16[this._pos2 + 10]; } + get lowerSize() { return this._structArray.uint16[this._pos2 + 11]; } + get upperSize() { return this._structArray.uint16[this._pos2 + 12]; } + get lineOffsetX() { return this._structArray.float32[this._pos4 + 7]; } + get lineOffsetY() { return this._structArray.float32[this._pos4 + 8]; } + get writingMode() { return this._structArray.uint8[this._pos1 + 36]; } + get placedOrientation() { return this._structArray.uint8[this._pos1 + 37]; } + set placedOrientation(x) { this._structArray.uint8[this._pos1 + 37] = x; } + get hidden() { return this._structArray.uint8[this._pos1 + 38]; } + set hidden(x) { this._structArray.uint8[this._pos1 + 38] = x; } + get crossTileID() { return this._structArray.uint32[this._pos4 + 10]; } + set crossTileID(x) { this._structArray.uint32[this._pos4 + 10] = x; } + get associatedIconIndex() { return this._structArray.int16[this._pos2 + 22]; } +} +PlacedSymbolStruct.prototype.size = 48; +/** @internal */ +class PlacedSymbolArray extends StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 { + /** + * Return the PlacedSymbolStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new PlacedSymbolStruct(this, index); + } +} +register('PlacedSymbolArray', PlacedSymbolArray); +/** @internal */ +class SymbolInstanceStruct extends Struct { + get anchorX() { return this._structArray.int16[this._pos2 + 0]; } + get anchorY() { return this._structArray.int16[this._pos2 + 1]; } + get rightJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 2]; } + get centerJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 3]; } + get leftJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 4]; } + get verticalPlacedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 5]; } + get placedIconSymbolIndex() { return this._structArray.int16[this._pos2 + 6]; } + get verticalPlacedIconSymbolIndex() { return this._structArray.int16[this._pos2 + 7]; } + get key() { return this._structArray.uint16[this._pos2 + 8]; } + get textBoxStartIndex() { return this._structArray.uint16[this._pos2 + 9]; } + get textBoxEndIndex() { return this._structArray.uint16[this._pos2 + 10]; } + get verticalTextBoxStartIndex() { return this._structArray.uint16[this._pos2 + 11]; } + get verticalTextBoxEndIndex() { return this._structArray.uint16[this._pos2 + 12]; } + get iconBoxStartIndex() { return this._structArray.uint16[this._pos2 + 13]; } + get iconBoxEndIndex() { return this._structArray.uint16[this._pos2 + 14]; } + get verticalIconBoxStartIndex() { return this._structArray.uint16[this._pos2 + 15]; } + get verticalIconBoxEndIndex() { return this._structArray.uint16[this._pos2 + 16]; } + get featureIndex() { return this._structArray.uint16[this._pos2 + 17]; } + get numHorizontalGlyphVertices() { return this._structArray.uint16[this._pos2 + 18]; } + get numVerticalGlyphVertices() { return this._structArray.uint16[this._pos2 + 19]; } + get numIconVertices() { return this._structArray.uint16[this._pos2 + 20]; } + get numVerticalIconVertices() { return this._structArray.uint16[this._pos2 + 21]; } + get useRuntimeCollisionCircles() { return this._structArray.uint16[this._pos2 + 22]; } + get crossTileID() { return this._structArray.uint32[this._pos4 + 12]; } + set crossTileID(x) { this._structArray.uint32[this._pos4 + 12] = x; } + get textBoxScale() { return this._structArray.float32[this._pos4 + 13]; } + get collisionCircleDiameter() { return this._structArray.float32[this._pos4 + 14]; } + get textAnchorOffsetStartIndex() { return this._structArray.uint16[this._pos2 + 30]; } + get textAnchorOffsetEndIndex() { return this._structArray.uint16[this._pos2 + 31]; } +} +SymbolInstanceStruct.prototype.size = 64; +/** @internal */ +class SymbolInstanceArray extends StructArrayLayout8i15ui1ul2f2ui64 { + /** + * Return the SymbolInstanceStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new SymbolInstanceStruct(this, index); + } +} +register('SymbolInstanceArray', SymbolInstanceArray); +/** @internal */ +class GlyphOffsetArray extends StructArrayLayout1f4 { + getoffsetX(index) { return this.float32[index * 1 + 0]; } +} +register('GlyphOffsetArray', GlyphOffsetArray); +/** @internal */ +class SymbolLineVertexArray extends StructArrayLayout3i6 { + getx(index) { return this.int16[index * 3 + 0]; } + gety(index) { return this.int16[index * 3 + 1]; } + gettileUnitDistanceFromAnchor(index) { return this.int16[index * 3 + 2]; } +} +register('SymbolLineVertexArray', SymbolLineVertexArray); +/** @internal */ +class TextAnchorOffsetStruct extends Struct { + get textAnchor() { return this._structArray.uint16[this._pos2 + 0]; } + get textOffset0() { return this._structArray.float32[this._pos4 + 1]; } + get textOffset1() { return this._structArray.float32[this._pos4 + 2]; } +} +TextAnchorOffsetStruct.prototype.size = 12; +/** @internal */ +class TextAnchorOffsetArray extends StructArrayLayout1ui2f12 { + /** + * Return the TextAnchorOffsetStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new TextAnchorOffsetStruct(this, index); + } +} +register('TextAnchorOffsetArray', TextAnchorOffsetArray); +/** @internal */ +class FeatureIndexStruct extends Struct { + get featureIndex() { return this._structArray.uint32[this._pos4 + 0]; } + get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 2]; } + get bucketIndex() { return this._structArray.uint16[this._pos2 + 3]; } +} +FeatureIndexStruct.prototype.size = 8; +/** @internal */ +class FeatureIndexArray extends StructArrayLayout1ul2ui8 { + /** + * Return the FeatureIndexStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new FeatureIndexStruct(this, index); + } +} +register('FeatureIndexArray', FeatureIndexArray); +class PosArray extends StructArrayLayout2i4 { +} +class Pos3dArray extends StructArrayLayout3i6 { +} +class RasterBoundsArray extends StructArrayLayout4i8 { +} +class CircleLayoutArray extends StructArrayLayout2i4 { +} +class FillLayoutArray extends StructArrayLayout2i4 { +} +class FillExtrusionLayoutArray extends StructArrayLayout2i4i12 { +} +class HeatmapLayoutArray extends StructArrayLayout2i4 { +} +class LineLayoutArray extends StructArrayLayout2i4ub8 { +} +class LineExtLayoutArray extends StructArrayLayout2f8 { +} +class PatternLayoutArray extends StructArrayLayout10ui20 { +} +class SymbolLayoutArray extends StructArrayLayout4i4ui4i24 { +} +class SymbolDynamicLayoutArray extends StructArrayLayout3f12 { +} +class SymbolOpacityArray extends StructArrayLayout1ul4 { +} +class CollisionBoxLayoutArray extends StructArrayLayout2i2i2i12 { +} +class CollisionCircleLayoutArray extends StructArrayLayout2f1f2i16 { +} +class CollisionVertexArray extends StructArrayLayout2ub2f2i16 { +} +class QuadTriangleArray extends StructArrayLayout3ui6 { +} +class TriangleIndexArray extends StructArrayLayout3ui6 { +} +class LineIndexArray extends StructArrayLayout2ui4 { +} +class LineStripIndexArray extends StructArrayLayout1ui2 { +} + +const layout$6 = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' } +], 4); +const { members: members$4, size: size$4, alignment: alignment$4 } = layout$6; + +/** + * @internal + * Used for calculations on vector segments + */ +class SegmentVector { + constructor(segments = []) { + this.segments = segments; + } + prepareSegment(numVertices, layoutVertexArray, indexArray, sortKey) { + let segment = this.segments[this.segments.length - 1]; + if (numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) + warnOnce(`Max vertices per segment is ${SegmentVector.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${numVertices}`); + if (!segment || segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH || segment.sortKey !== sortKey) { + segment = { + vertexOffset: layoutVertexArray.length, + primitiveOffset: indexArray.length, + vertexLength: 0, + primitiveLength: 0 + }; + if (sortKey !== undefined) + segment.sortKey = sortKey; + this.segments.push(segment); + } + return segment; + } + get() { + return this.segments; + } + destroy() { + for (const segment of this.segments) { + for (const k in segment.vaos) { + segment.vaos[k].destroy(); + } + } + } + static simpleSegment(vertexOffset, primitiveOffset, vertexLength, primitiveLength) { + return new SegmentVector([{ + vertexOffset, + primitiveOffset, + vertexLength, + primitiveLength, + vaos: {}, + sortKey: 0 + }]); + } +} +/** + * The maximum size of a vertex array. This limit is imposed by WebGL's 16 bit + * addressing of vertex buffers. + */ +SegmentVector.MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1; +register('SegmentVector', SegmentVector); + +/** + * Packs two numbers, interpreted as 8-bit unsigned integers, into a single + * float. Unpack them in the shader using the `unpack_float()` function, + * defined in _prelude.vertex.glsl + */ +function packUint8ToFloat(a, b) { + // coerce a and b to 8-bit ints + a = clamp$1(Math.floor(a), 0, 255); + b = clamp$1(Math.floor(b), 0, 255); + return 256 * a + b; +} + +const patternAttributes = createLayout([ + // [tl.x, tl.y, br.x, br.y] + { name: 'a_pattern_from', components: 4, type: 'Uint16' }, + { name: 'a_pattern_to', components: 4, type: 'Uint16' }, + { name: 'a_pixel_ratio_from', components: 1, type: 'Uint16' }, + { name: 'a_pixel_ratio_to', components: 1, type: 'Uint16' }, +]); + +var murmurhashJs$1 = {exports: {}}; + +var murmurhash3_gc$2 = {exports: {}}; + +/** + * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} key ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ +var murmurhash3_gc = murmurhash3_gc$2.exports; + +(function (module) { + function murmurhash3_32_gc(key, seed) { + var remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i; + + remainder = key.length & 3; // key.length % 4 + bytes = key.length - remainder; + h1 = seed; + c1 = 0xcc9e2d51; + c2 = 0x1b873593; + i = 0; + + while (i < bytes) { + k1 = + ((key.charCodeAt(i) & 0xff)) | + ((key.charCodeAt(++i) & 0xff) << 8) | + ((key.charCodeAt(++i) & 0xff) << 16) | + ((key.charCodeAt(++i) & 0xff) << 24); + ++i; + + k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff; + + h1 ^= k1; + h1 = (h1 << 13) | (h1 >>> 19); + h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff; + h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16)); + } + + k1 = 0; + + switch (remainder) { + case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; + case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; + case 1: k1 ^= (key.charCodeAt(i) & 0xff); + + k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; + h1 ^= k1; + } + + h1 ^= key.length; + + h1 ^= h1 >>> 16; + h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; + h1 ^= h1 >>> 13; + h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff; + h1 ^= h1 >>> 16; + + return h1 >>> 0; + } + + if('object' !== "undefined") { + module.exports = murmurhash3_32_gc; + } +} (murmurhash3_gc$2)); + +var murmurhash3_gcExports = murmurhash3_gc$2.exports; +var murmurhash3_gc$1 = /*@__PURE__*/getDefaultExportFromCjs$1(murmurhash3_gcExports); + +var murmurhash2_gc$2 = {exports: {}}; + +/** + * JS Implementation of MurmurHash2 + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} str ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ +var murmurhash2_gc = murmurhash2_gc$2.exports; + +(function (module) { + function murmurhash2_32_gc(str, seed) { + var + l = str.length, + h = seed ^ l, + i = 0, + k; + + while (l >= 4) { + k = + ((str.charCodeAt(i) & 0xff)) | + ((str.charCodeAt(++i) & 0xff) << 8) | + ((str.charCodeAt(++i) & 0xff) << 16) | + ((str.charCodeAt(++i) & 0xff) << 24); + + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + k ^= k >>> 24; + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; + + l -= 4; + ++i; + } + + switch (l) { + case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; + case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; + case 1: h ^= (str.charCodeAt(i) & 0xff); + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + } + + h ^= h >>> 13; + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + h ^= h >>> 15; + + return h >>> 0; + } + + if('object' !== undefined) { + module.exports = murmurhash2_32_gc; + } +} (murmurhash2_gc$2)); + +var murmurhash2_gcExports = murmurhash2_gc$2.exports; +var murmurhash2_gc$1 = /*@__PURE__*/getDefaultExportFromCjs$1(murmurhash2_gcExports); + +var murmurhashJs = murmurhashJs$1.exports; + +var murmur3 = murmurhash3_gcExports; +var murmur2 = murmurhash2_gcExports; + +murmurhashJs$1.exports = murmur3; +var murmur3_1 = murmurhashJs$1.exports.murmur3 = murmur3; +var murmur2_1 = murmurhashJs$1.exports.murmur2 = murmur2; + +var murmurhashJsExports = murmurhashJs$1.exports; +var murmur3$1 = /*@__PURE__*/getDefaultExportFromCjs$1(murmurhashJsExports); + +// A transferable data structure that maps feature ids to their indices and buffer offsets +class FeaturePositionMap { + constructor() { + this.ids = []; + this.positions = []; + this.indexed = false; + } + add(id, index, start, end) { + this.ids.push(getNumericId(id)); + this.positions.push(index, start, end); + } + getPositions(id) { + if (!this.indexed) + throw new Error('Trying to get index, but feature positions are not indexed'); + const intId = getNumericId(id); + // binary search for the first occurrence of id in this.ids; + // relies on ids/positions being sorted by id, which happens in serialization + let i = 0; + let j = this.ids.length - 1; + while (i < j) { + const m = (i + j) >> 1; + if (this.ids[m] >= intId) { + j = m; + } + else { + i = m + 1; + } + } + const positions = []; + while (this.ids[i] === intId) { + const index = this.positions[3 * i]; + const start = this.positions[3 * i + 1]; + const end = this.positions[3 * i + 2]; + positions.push({ index, start, end }); + i++; + } + return positions; + } + static serialize(map, transferables) { + const ids = new Float64Array(map.ids); + const positions = new Uint32Array(map.positions); + sort$1(ids, positions, 0, ids.length - 1); + if (transferables) { + transferables.push(ids.buffer, positions.buffer); + } + return { ids, positions }; + } + static deserialize(obj) { + const map = new FeaturePositionMap(); + // after transferring, we only use these arrays statically (no pushes), + // so TypedArray vs Array distinction that flow points out doesn't matter + map.ids = obj.ids; + map.positions = obj.positions; + map.indexed = true; + return map; + } +} +function getNumericId(value) { + const numValue = +value; + if (!isNaN(numValue) && numValue <= Number.MAX_SAFE_INTEGER) { + return numValue; + } + return murmur3$1(String(value)); +} +// custom quicksort that sorts ids, indices and offsets together (by ids) +// uses Hoare partitioning & manual tail call optimization to avoid worst case scenarios +function sort$1(ids, positions, left, right) { + while (left < right) { + const pivot = ids[(left + right) >> 1]; + let i = left - 1; + let j = right + 1; + while (true) { + do + i++; + while (ids[i] < pivot); + do + j--; + while (ids[j] > pivot); + if (i >= j) + break; + swap$1(ids, i, j); + swap$1(positions, 3 * i, 3 * j); + swap$1(positions, 3 * i + 1, 3 * j + 1); + swap$1(positions, 3 * i + 2, 3 * j + 2); + } + if (j - left < right - j) { + sort$1(ids, positions, left, j); + left = j + 1; + } + else { + sort$1(ids, positions, j + 1, right); + right = j; + } + } +} +function swap$1(arr, i, j) { + const tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} +register('FeaturePositionMap', FeaturePositionMap); + +/** + * @internal + * A base uniform abstract class + */ +class Uniform { + constructor(context, location) { + this.gl = context.gl; + this.location = location; + } +} +class Uniform1i extends Uniform { + constructor(context, location) { + super(context, location); + this.current = 0; + } + set(v) { + if (this.current !== v) { + this.current = v; + this.gl.uniform1i(this.location, v); + } + } +} +class Uniform1f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = 0; + } + set(v) { + if (this.current !== v) { + this.current = v; + this.gl.uniform1f(this.location, v); + } + } +} +class Uniform2f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = [0, 0]; + } + set(v) { + if (v[0] !== this.current[0] || v[1] !== this.current[1]) { + this.current = v; + this.gl.uniform2f(this.location, v[0], v[1]); + } + } +} +class Uniform3f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = [0, 0, 0]; + } + set(v) { + if (v[0] !== this.current[0] || v[1] !== this.current[1] || v[2] !== this.current[2]) { + this.current = v; + this.gl.uniform3f(this.location, v[0], v[1], v[2]); + } + } +} +class Uniform4f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = [0, 0, 0, 0]; + } + set(v) { + if (v[0] !== this.current[0] || v[1] !== this.current[1] || + v[2] !== this.current[2] || v[3] !== this.current[3]) { + this.current = v; + this.gl.uniform4f(this.location, v[0], v[1], v[2], v[3]); + } + } +} +class UniformColor extends Uniform { + constructor(context, location) { + super(context, location); + this.current = Color.transparent; + } + set(v) { + if (v.r !== this.current.r || v.g !== this.current.g || + v.b !== this.current.b || v.a !== this.current.a) { + this.current = v; + this.gl.uniform4f(this.location, v.r, v.g, v.b, v.a); + } + } +} +const emptyMat4 = new Float32Array(16); +class UniformMatrix4f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = emptyMat4; + } + set(v) { + // The vast majority of matrix comparisons that will trip this set + // happen at i=12 or i=0, so we check those first to avoid lots of + // unnecessary iteration: + if (v[12] !== this.current[12] || v[0] !== this.current[0]) { + this.current = v; + this.gl.uniformMatrix4fv(this.location, false, v); + return; + } + for (let i = 1; i < 16; i++) { + if (v[i] !== this.current[i]) { + this.current = v; + this.gl.uniformMatrix4fv(this.location, false, v); + break; + } + } + } +} + +function packColor(color) { + return [ + packUint8ToFloat(255 * color.r, 255 * color.g), + packUint8ToFloat(255 * color.b, 255 * color.a) + ]; +} +class ConstantBinder { + constructor(value, names, type) { + this.value = value; + this.uniformNames = names.map(name => `u_${name}`); + this.type = type; + } + setUniform(uniform, globals, currentValue) { + uniform.set(currentValue.constantOr(this.value)); + } + getBinding(context, location, _) { + return (this.type === 'color') ? + new UniformColor(context, location) : + new Uniform1f(context, location); + } +} +class CrossFadedConstantBinder { + constructor(value, names) { + this.uniformNames = names.map(name => `u_${name}`); + this.patternFrom = null; + this.patternTo = null; + this.pixelRatioFrom = 1.0; + this.pixelRatioTo = 1.0; + } + setConstantPatternPositions(posTo, posFrom) { + this.pixelRatioFrom = posFrom.pixelRatio; + this.pixelRatioTo = posTo.pixelRatio; + this.patternFrom = posFrom.tlbr; + this.patternTo = posTo.tlbr; + } + setUniform(uniform, globals, currentValue, uniformName) { + const pos = uniformName === 'u_pattern_to' ? this.patternTo : + uniformName === 'u_pattern_from' ? this.patternFrom : + uniformName === 'u_pixel_ratio_to' ? this.pixelRatioTo : + uniformName === 'u_pixel_ratio_from' ? this.pixelRatioFrom : null; + if (pos) + uniform.set(pos); + } + getBinding(context, location, name) { + return name.substr(0, 9) === 'u_pattern' ? + new Uniform4f(context, location) : + new Uniform1f(context, location); + } +} +class SourceExpressionBinder { + constructor(expression, names, type, PaintVertexArray) { + this.expression = expression; + this.type = type; + this.maxValue = 0; + this.paintVertexAttributes = names.map((name) => ({ + name: `a_${name}`, + type: 'Float32', + components: type === 'color' ? 2 : 1, + offset: 0 + })); + this.paintVertexArray = new PaintVertexArray(); + } + populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection) { + const start = this.paintVertexArray.length; + const value = this.expression.evaluate(new EvaluationParameters(0), feature, {}, canonical, [], formattedSection); + this.paintVertexArray.resize(newLength); + this._setPaintValue(start, newLength, value); + } + updatePaintArray(start, end, feature, featureState) { + const value = this.expression.evaluate({ zoom: 0 }, feature, featureState); + this._setPaintValue(start, end, value); + } + _setPaintValue(start, end, value) { + if (this.type === 'color') { + const color = packColor(value); + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, color[0], color[1]); + } + } + else { + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, value); + } + this.maxValue = Math.max(this.maxValue, Math.abs(value)); + } + } + upload(context) { + if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) { + if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) { + this.paintVertexBuffer.updateData(this.paintVertexArray); + } + else { + this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent); + } + } + } + destroy() { + if (this.paintVertexBuffer) { + this.paintVertexBuffer.destroy(); + } + } +} +class CompositeExpressionBinder { + constructor(expression, names, type, useIntegerZoom, zoom, PaintVertexArray) { + this.expression = expression; + this.uniformNames = names.map(name => `u_${name}_t`); + this.type = type; + this.useIntegerZoom = useIntegerZoom; + this.zoom = zoom; + this.maxValue = 0; + this.paintVertexAttributes = names.map((name) => ({ + name: `a_${name}`, + type: 'Float32', + components: type === 'color' ? 4 : 2, + offset: 0 + })); + this.paintVertexArray = new PaintVertexArray(); + } + populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection) { + const min = this.expression.evaluate(new EvaluationParameters(this.zoom), feature, {}, canonical, [], formattedSection); + const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1), feature, {}, canonical, [], formattedSection); + const start = this.paintVertexArray.length; + this.paintVertexArray.resize(newLength); + this._setPaintValue(start, newLength, min, max); + } + updatePaintArray(start, end, feature, featureState) { + const min = this.expression.evaluate({ zoom: this.zoom }, feature, featureState); + const max = this.expression.evaluate({ zoom: this.zoom + 1 }, feature, featureState); + this._setPaintValue(start, end, min, max); + } + _setPaintValue(start, end, min, max) { + if (this.type === 'color') { + const minColor = packColor(min); + const maxColor = packColor(max); + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, minColor[0], minColor[1], maxColor[0], maxColor[1]); + } + } + else { + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, min, max); + } + this.maxValue = Math.max(this.maxValue, Math.abs(min), Math.abs(max)); + } + } + upload(context) { + if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) { + if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) { + this.paintVertexBuffer.updateData(this.paintVertexArray); + } + else { + this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent); + } + } + } + destroy() { + if (this.paintVertexBuffer) { + this.paintVertexBuffer.destroy(); + } + } + setUniform(uniform, globals) { + const currentZoom = this.useIntegerZoom ? Math.floor(globals.zoom) : globals.zoom; + const factor = clamp$1(this.expression.interpolationFactor(currentZoom, this.zoom, this.zoom + 1), 0, 1); + uniform.set(factor); + } + getBinding(context, location, _) { + return new Uniform1f(context, location); + } +} +class CrossFadedCompositeBinder { + constructor(expression, type, useIntegerZoom, zoom, PaintVertexArray, layerId) { + this.expression = expression; + this.type = type; + this.useIntegerZoom = useIntegerZoom; + this.zoom = zoom; + this.layerId = layerId; + this.zoomInPaintVertexArray = new PaintVertexArray(); + this.zoomOutPaintVertexArray = new PaintVertexArray(); + } + populatePaintArray(length, feature, imagePositions) { + const start = this.zoomInPaintVertexArray.length; + this.zoomInPaintVertexArray.resize(length); + this.zoomOutPaintVertexArray.resize(length); + this._setPaintValues(start, length, feature.patterns && feature.patterns[this.layerId], imagePositions); + } + updatePaintArray(start, end, feature, featureState, imagePositions) { + this._setPaintValues(start, end, feature.patterns && feature.patterns[this.layerId], imagePositions); + } + _setPaintValues(start, end, patterns, positions) { + if (!positions || !patterns) + return; + const { min, mid, max } = patterns; + const imageMin = positions[min]; + const imageMid = positions[mid]; + const imageMax = positions[max]; + if (!imageMin || !imageMid || !imageMax) + return; + // We populate two paint arrays because, for cross-faded properties, we don't know which direction + // we're cross-fading to at layout time. In order to keep vertex attributes to a minimum and not pass + // unnecessary vertex data to the shaders, we determine which to upload at draw time. + for (let i = start; i < end; i++) { + this.zoomInPaintVertexArray.emplace(i, imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1], imageMin.tl[0], imageMin.tl[1], imageMin.br[0], imageMin.br[1], imageMid.pixelRatio, imageMin.pixelRatio); + this.zoomOutPaintVertexArray.emplace(i, imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1], imageMax.tl[0], imageMax.tl[1], imageMax.br[0], imageMax.br[1], imageMid.pixelRatio, imageMax.pixelRatio); + } + } + upload(context) { + if (this.zoomInPaintVertexArray && this.zoomInPaintVertexArray.arrayBuffer && this.zoomOutPaintVertexArray && this.zoomOutPaintVertexArray.arrayBuffer) { + this.zoomInPaintVertexBuffer = context.createVertexBuffer(this.zoomInPaintVertexArray, patternAttributes.members, this.expression.isStateDependent); + this.zoomOutPaintVertexBuffer = context.createVertexBuffer(this.zoomOutPaintVertexArray, patternAttributes.members, this.expression.isStateDependent); + } + } + destroy() { + if (this.zoomOutPaintVertexBuffer) + this.zoomOutPaintVertexBuffer.destroy(); + if (this.zoomInPaintVertexBuffer) + this.zoomInPaintVertexBuffer.destroy(); + } +} +/** + * @internal + * ProgramConfiguration contains the logic for binding style layer properties and tile + * layer feature data into GL program uniforms and vertex attributes. + * + * Non-data-driven property values are bound to shader uniforms. Data-driven property + * values are bound to vertex attributes. In order to support a uniform GLSL syntax over + * both, [Mapbox GL Shaders](https://github.com/mapbox/mapbox-gl-shaders) defines a `#pragma` + * abstraction, which ProgramConfiguration is responsible for implementing. At runtime, + * it examines the attributes of a particular layer, combines this with fixed knowledge + * about how layers of the particular type are implemented, and determines which uniforms + * and vertex attributes will be required. It can then substitute the appropriate text + * into the shader source code, create and link a program, and bind the uniforms and + * vertex attributes in preparation for drawing. + * + * When a vector tile is parsed, this same configuration information is used to + * populate the attribute buffers needed for data-driven styling using the zoom + * level and feature property data. + */ +class ProgramConfiguration { + constructor(layer, zoom, filterProperties) { + this.binders = {}; + this._buffers = []; + const keys = []; + for (const property in layer.paint._values) { + if (!filterProperties(property)) + continue; + const value = layer.paint.get(property); + if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) { + continue; + } + const names = paintAttributeNames(property, layer.type); + const expression = value.value; + const type = value.property.specification.type; + const useIntegerZoom = value.property.useIntegerZoom; + const propType = value.property.specification['property-type']; + const isCrossFaded = propType === 'cross-faded' || propType === 'cross-faded-data-driven'; + if (expression.kind === 'constant') { + this.binders[property] = isCrossFaded ? + new CrossFadedConstantBinder(expression.value, names) : + new ConstantBinder(expression.value, names, type); + keys.push(`/u_${property}`); + } + else if (expression.kind === 'source' || isCrossFaded) { + const StructArrayLayout = layoutType(property, type, 'source'); + this.binders[property] = isCrossFaded ? + new CrossFadedCompositeBinder(expression, type, useIntegerZoom, zoom, StructArrayLayout, layer.id) : + new SourceExpressionBinder(expression, names, type, StructArrayLayout); + keys.push(`/a_${property}`); + } + else { + const StructArrayLayout = layoutType(property, type, 'composite'); + this.binders[property] = new CompositeExpressionBinder(expression, names, type, useIntegerZoom, zoom, StructArrayLayout); + keys.push(`/z_${property}`); + } + } + this.cacheKey = keys.sort().join(''); + } + getMaxValue(property) { + const binder = this.binders[property]; + return binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder ? binder.maxValue : 0; + } + populatePaintArrays(newLength, feature, imagePositions, canonical, formattedSection) { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) + binder.populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection); + } + } + setConstantPatternPositions(posTo, posFrom) { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof CrossFadedConstantBinder) + binder.setConstantPatternPositions(posTo, posFrom); + } + } + updatePaintArrays(featureStates, featureMap, vtLayer, layer, imagePositions) { + let dirty = false; + for (const id in featureStates) { + const positions = featureMap.getPositions(id); + for (const pos of positions) { + const feature = vtLayer.feature(pos.index); + for (const property in this.binders) { + const binder = this.binders[property]; + if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || + binder instanceof CrossFadedCompositeBinder) && binder.expression.isStateDependent === true) { + //AHM: Remove after https://github.com/mapbox/mapbox-gl-js/issues/6255 + const value = layer.paint.get(property); + binder.expression = value.value; + binder.updatePaintArray(pos.start, pos.end, feature, featureStates[id], imagePositions); + dirty = true; + } + } + } + } + return dirty; + } + defines() { + const result = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder) { + result.push(...binder.uniformNames.map(name => `#define HAS_UNIFORM_${name}`)); + } + } + return result; + } + getBinderAttributes() { + const result = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) { + for (let i = 0; i < binder.paintVertexAttributes.length; i++) { + result.push(binder.paintVertexAttributes[i].name); + } + } + else if (binder instanceof CrossFadedCompositeBinder) { + for (let i = 0; i < patternAttributes.members.length; i++) { + result.push(patternAttributes.members[i].name); + } + } + } + return result; + } + getBinderUniforms() { + const uniforms = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) { + for (const uniformName of binder.uniformNames) { + uniforms.push(uniformName); + } + } + } + return uniforms; + } + getPaintVertexBuffers() { + return this._buffers; + } + getUniforms(context, locations) { + const uniforms = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) { + for (const name of binder.uniformNames) { + if (locations[name]) { + const binding = binder.getBinding(context, locations[name], name); + uniforms.push({ name, property, binding }); + } + } + } + } + return uniforms; + } + setUniforms(context, binderUniforms, properties, globals) { + // Uniform state bindings are owned by the Program, but we set them + // from within the ProgramConfiguration's binder members. + for (const { name, property, binding } of binderUniforms) { + this.binders[property].setUniform(binding, globals, properties.get(property), name); + } + } + updatePaintBuffers(crossfade) { + this._buffers = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (crossfade && binder instanceof CrossFadedCompositeBinder) { + const patternVertexBuffer = crossfade.fromScale === 2 ? binder.zoomInPaintVertexBuffer : binder.zoomOutPaintVertexBuffer; + if (patternVertexBuffer) + this._buffers.push(patternVertexBuffer); + } + else if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) && binder.paintVertexBuffer) { + this._buffers.push(binder.paintVertexBuffer); + } + } + } + upload(context) { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) + binder.upload(context); + } + this.updatePaintBuffers(); + } + destroy() { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) + binder.destroy(); + } + } +} +class ProgramConfigurationSet { + constructor(layers, zoom, filterProperties = () => true) { + this.programConfigurations = {}; + for (const layer of layers) { + this.programConfigurations[layer.id] = new ProgramConfiguration(layer, zoom, filterProperties); + } + this.needsUpload = false; + this._featureMap = new FeaturePositionMap(); + this._bufferOffset = 0; + } + populatePaintArrays(length, feature, index, imagePositions, canonical, formattedSection) { + for (const key in this.programConfigurations) { + this.programConfigurations[key].populatePaintArrays(length, feature, imagePositions, canonical, formattedSection); + } + if (feature.id !== undefined) { + this._featureMap.add(feature.id, index, this._bufferOffset, length); + } + this._bufferOffset = length; + this.needsUpload = true; + } + updatePaintArrays(featureStates, vtLayer, layers, imagePositions) { + for (const layer of layers) { + this.needsUpload = this.programConfigurations[layer.id].updatePaintArrays(featureStates, this._featureMap, vtLayer, layer, imagePositions) || this.needsUpload; + } + } + get(layerId) { + return this.programConfigurations[layerId]; + } + upload(context) { + if (!this.needsUpload) + return; + for (const layerId in this.programConfigurations) { + this.programConfigurations[layerId].upload(context); + } + this.needsUpload = false; + } + destroy() { + for (const layerId in this.programConfigurations) { + this.programConfigurations[layerId].destroy(); + } + } +} +function paintAttributeNames(property, type) { + const attributeNameExceptions = { + 'text-opacity': ['opacity'], + 'icon-opacity': ['opacity'], + 'text-color': ['fill_color'], + 'icon-color': ['fill_color'], + 'text-halo-color': ['halo_color'], + 'icon-halo-color': ['halo_color'], + 'text-halo-blur': ['halo_blur'], + 'icon-halo-blur': ['halo_blur'], + 'text-halo-width': ['halo_width'], + 'icon-halo-width': ['halo_width'], + 'line-gap-width': ['gapwidth'], + 'line-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'], + 'fill-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'], + 'fill-extrusion-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'], + }; + return attributeNameExceptions[property] || [property.replace(`${type}-`, '').replace(/-/g, '_')]; +} +function getLayoutException(property) { + const propertyExceptions = { + 'line-pattern': { + 'source': PatternLayoutArray, + 'composite': PatternLayoutArray + }, + 'fill-pattern': { + 'source': PatternLayoutArray, + 'composite': PatternLayoutArray + }, + 'fill-extrusion-pattern': { + 'source': PatternLayoutArray, + 'composite': PatternLayoutArray + } + }; + return propertyExceptions[property]; +} +function layoutType(property, type, binderType) { + const defaultLayouts = { + 'color': { + 'source': StructArrayLayout2f8, + 'composite': StructArrayLayout4f16 + }, + 'number': { + 'source': StructArrayLayout1f4, + 'composite': StructArrayLayout2f8 + } + }; + const layoutException = getLayoutException(property); + return layoutException && layoutException[binderType] || defaultLayouts[type][binderType]; +} +register('ConstantBinder', ConstantBinder); +register('CrossFadedConstantBinder', CrossFadedConstantBinder); +register('SourceExpressionBinder', SourceExpressionBinder); +register('CrossFadedCompositeBinder', CrossFadedCompositeBinder); +register('CompositeExpressionBinder', CompositeExpressionBinder); +register('ProgramConfiguration', ProgramConfiguration, { omit: ['_buffers'] }); +register('ProgramConfigurationSet', ProgramConfigurationSet); + +/** + * The maximum value of a coordinate in the internal tile coordinate system. Coordinates of + * all source features normalized to this extent upon load. + * + * The value is a consequence of the following: + * + * * Vertex buffer store positions as signed 16 bit integers. + * * One bit is lost for signedness to support tile buffers. + * * One bit is lost because the line vertex buffer used to pack 1 bit of other data into the int. + * * One bit is lost to support features extending past the extent on the right edge of the tile. + * * This leaves us with 2^13 = 8192 + */ +const EXTENT = 8192; + +// These bounds define the minimum and maximum supported coordinate values. +// While visible coordinates are within [0, EXTENT], tiles may theoretically +// contain coordinates within [-Infinity, Infinity]. Our range is limited by the +// number of bits used to represent the coordinate. +const BITS = 15; +const MAX = Math.pow(2, BITS - 1) - 1; +const MIN = -MAX - 1; +/** + * Loads a geometry from a VectorTileFeature and scales it to the common extent + * used internally. + * @param feature - the vector tile feature to load + */ +function loadGeometry(feature) { + const scale = EXTENT / feature.extent; + const geometry = feature.loadGeometry(); + for (let r = 0; r < geometry.length; r++) { + const ring = geometry[r]; + for (let p = 0; p < ring.length; p++) { + const point = ring[p]; + // round here because mapbox-gl-native uses integers to represent + // points and we need to do the same to avoid renering differences. + const x = Math.round(point.x * scale); + const y = Math.round(point.y * scale); + point.x = clamp$1(x, MIN, MAX); + point.y = clamp$1(y, MIN, MAX); + if (x < point.x || x > point.x + 1 || y < point.y || y > point.y + 1) { + // warn when exceeding allowed extent except for the 1-px-off case + // https://github.com/mapbox/mapbox-gl-js/issues/8992 + warnOnce('Geometry exceeds allowed extent, reduce your vector tile buffer size'); + } + } + } + return geometry; +} + +/** + * Construct a new feature based on a VectorTileFeature for expression evaluation, the geometry of which + * will be loaded based on necessity. + * @param feature - the feature to evaluate + * @param needGeometry - if set to true this will load the geometry + */ +function toEvaluationFeature(feature, needGeometry) { + return { type: feature.type, + id: feature.id, + properties: feature.properties, + geometry: needGeometry ? loadGeometry(feature) : [] }; +} + +function addCircleVertex(layoutVertexArray, x, y, extrudeX, extrudeY) { + layoutVertexArray.emplaceBack((x * 2) + ((extrudeX + 1) / 2), (y * 2) + ((extrudeY + 1) / 2)); +} +/** + * @internal + * Circles are represented by two triangles. + * + * Each corner has a pos that is the center of the circle and an extrusion + * vector that is where it points. + */ +class CircleBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.layoutVertexArray = new CircleLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.segments = new SegmentVector(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + const styleLayer = this.layers[0]; + const bucketFeatures = []; + let circleSortKey = null; + let sortFeaturesByKey = false; + // Heatmap layers are handled in this bucket and have no evaluated properties, so we check our access + if (styleLayer.type === 'circle') { + circleSortKey = styleLayer.layout.get('circle-sort-key'); + sortFeaturesByKey = !circleSortKey.isConstant(); + } + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const sortKey = sortFeaturesByKey ? + circleSortKey.evaluate(evaluationFeature, {}, canonical) : + undefined; + const bucketFeature = { + id, + properties: feature.properties, + type: feature.type, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + patterns: {}, + sortKey + }; + bucketFeatures.push(bucketFeature); + } + if (sortFeaturesByKey) { + bucketFeatures.sort((a, b) => a.sortKey - b.sortKey); + } + for (const bucketFeature of bucketFeatures) { + const { geometry, index, sourceLayerIndex } = bucketFeature; + const feature = features[index].feature; + this.addFeature(bucketFeature, geometry, index, canonical); + options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + isEmpty() { + return this.layoutVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$4); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + } + addFeature(feature, geometry, index, canonical) { + for (const ring of geometry) { + for (const point of ring) { + const x = point.x; + const y = point.y; + // Do not include points that are outside the tile boundaries. + if (x < 0 || x >= EXTENT || y < 0 || y >= EXTENT) + continue; + // this geometry will be of the Point type, and we'll derive + // two triangles from it. + // + // ┌─────────┐ + // │ 3 2 │ + // │ │ + // │ 0 1 │ + // └─────────┘ + const segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray, feature.sortKey); + const index = segment.vertexLength; + addCircleVertex(this.layoutVertexArray, x, y, -1, -1); + addCircleVertex(this.layoutVertexArray, x, y, 1, -1); + addCircleVertex(this.layoutVertexArray, x, y, 1, 1); + addCircleVertex(this.layoutVertexArray, x, y, -1, 1); + this.indexArray.emplaceBack(index, index + 1, index + 2); + this.indexArray.emplaceBack(index, index + 3, index + 2); + segment.vertexLength += 4; + segment.primitiveLength += 2; + } + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, {}, canonical); + } +} +register('CircleBucket', CircleBucket, { omit: ['layers'] }); + +function polygonIntersectsPolygon(polygonA, polygonB) { + for (let i = 0; i < polygonA.length; i++) { + if (polygonContainsPoint(polygonB, polygonA[i])) + return true; + } + for (let i = 0; i < polygonB.length; i++) { + if (polygonContainsPoint(polygonA, polygonB[i])) + return true; + } + if (lineIntersectsLine(polygonA, polygonB)) + return true; + return false; +} +function polygonIntersectsBufferedPoint(polygon, point, radius) { + if (polygonContainsPoint(polygon, point)) + return true; + if (pointIntersectsBufferedLine(point, polygon, radius)) + return true; + return false; +} +function polygonIntersectsMultiPolygon(polygon, multiPolygon) { + if (polygon.length === 1) { + return multiPolygonContainsPoint(multiPolygon, polygon[0]); + } + for (let m = 0; m < multiPolygon.length; m++) { + const ring = multiPolygon[m]; + for (let n = 0; n < ring.length; n++) { + if (polygonContainsPoint(polygon, ring[n])) + return true; + } + } + for (let i = 0; i < polygon.length; i++) { + if (multiPolygonContainsPoint(multiPolygon, polygon[i])) + return true; + } + for (let k = 0; k < multiPolygon.length; k++) { + if (lineIntersectsLine(polygon, multiPolygon[k])) + return true; + } + return false; +} +function polygonIntersectsBufferedMultiLine(polygon, multiLine, radius) { + for (let i = 0; i < multiLine.length; i++) { + const line = multiLine[i]; + if (polygon.length >= 3) { + for (let k = 0; k < line.length; k++) { + if (polygonContainsPoint(polygon, line[k])) + return true; + } + } + if (lineIntersectsBufferedLine(polygon, line, radius)) + return true; + } + return false; +} +function lineIntersectsBufferedLine(lineA, lineB, radius) { + if (lineA.length > 1) { + if (lineIntersectsLine(lineA, lineB)) + return true; + // Check whether any point in either line is within radius of the other line + for (let j = 0; j < lineB.length; j++) { + if (pointIntersectsBufferedLine(lineB[j], lineA, radius)) + return true; + } + } + for (let k = 0; k < lineA.length; k++) { + if (pointIntersectsBufferedLine(lineA[k], lineB, radius)) + return true; + } + return false; +} +function lineIntersectsLine(lineA, lineB) { + if (lineA.length === 0 || lineB.length === 0) + return false; + for (let i = 0; i < lineA.length - 1; i++) { + const a0 = lineA[i]; + const a1 = lineA[i + 1]; + for (let j = 0; j < lineB.length - 1; j++) { + const b0 = lineB[j]; + const b1 = lineB[j + 1]; + if (lineSegmentIntersectsLineSegment(a0, a1, b0, b1)) + return true; + } + } + return false; +} +function lineSegmentIntersectsLineSegment(a0, a1, b0, b1) { + return isCounterClockwise(a0, b0, b1) !== isCounterClockwise(a1, b0, b1) && + isCounterClockwise(a0, a1, b0) !== isCounterClockwise(a0, a1, b1); +} +function pointIntersectsBufferedLine(p, line, radius) { + const radiusSquared = radius * radius; + if (line.length === 1) + return p.distSqr(line[0]) < radiusSquared; + for (let i = 1; i < line.length; i++) { + // Find line segments that have a distance <= radius^2 to p + // In that case, we treat the line as "containing point p". + const v = line[i - 1], w = line[i]; + if (distToSegmentSquared(p, v, w) < radiusSquared) + return true; + } + return false; +} +// Code from https://stackoverflow.com/a/1501725/331379. +function distToSegmentSquared(p, v, w) { + const l2 = v.distSqr(w); + if (l2 === 0) + return p.distSqr(v); + const t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2; + if (t < 0) + return p.distSqr(v); + if (t > 1) + return p.distSqr(w); + return p.distSqr(w.sub(v)._mult(t)._add(v)); +} +// point in polygon ray casting algorithm +function multiPolygonContainsPoint(rings, p) { + let c = false, ring, p1, p2; + for (let k = 0; k < rings.length; k++) { + ring = rings[k]; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + 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)) { + c = !c; + } + } + } + return c; +} +function polygonContainsPoint(ring, p) { + let c = false; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const p1 = ring[i]; + const p2 = ring[j]; + 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)) { + c = !c; + } + } + return c; +} +function polygonIntersectsBox(ring, boxX1, boxY1, boxX2, boxY2) { + for (const p of ring) { + if (boxX1 <= p.x && + boxY1 <= p.y && + boxX2 >= p.x && + boxY2 >= p.y) + return true; + } + const corners = [ + new Point$3(boxX1, boxY1), + new Point$3(boxX1, boxY2), + new Point$3(boxX2, boxY2), + new Point$3(boxX2, boxY1) + ]; + if (ring.length > 2) { + for (const corner of corners) { + if (polygonContainsPoint(ring, corner)) + return true; + } + } + for (let i = 0; i < ring.length - 1; i++) { + const p1 = ring[i]; + const p2 = ring[i + 1]; + if (edgeIntersectsBox(p1, p2, corners)) + return true; + } + return false; +} +function edgeIntersectsBox(e1, e2, corners) { + const tl = corners[0]; + const br = corners[2]; + // the edge and box do not intersect in either the x or y dimensions + if (((e1.x < tl.x) && (e2.x < tl.x)) || + ((e1.x > br.x) && (e2.x > br.x)) || + ((e1.y < tl.y) && (e2.y < tl.y)) || + ((e1.y > br.y) && (e2.y > br.y))) + return false; + // check if all corners of the box are on the same side of the edge + const dir = isCounterClockwise(e1, e2, corners[0]); + return dir !== isCounterClockwise(e1, e2, corners[1]) || + dir !== isCounterClockwise(e1, e2, corners[2]) || + dir !== isCounterClockwise(e1, e2, corners[3]); +} + +function getMaximumPaintValue(property, layer, bucket) { + const value = layer.paint.get(property).value; + if (value.kind === 'constant') { + return value.value; + } + else { + return bucket.programConfigurations.get(layer.id).getMaxValue(property); + } +} +function translateDistance(translate) { + return Math.sqrt(translate[0] * translate[0] + translate[1] * translate[1]); +} +function translate$4(queryGeometry, translate, translateAnchor, bearing, pixelsToTileUnits) { + if (!translate[0] && !translate[1]) { + return queryGeometry; + } + const pt = Point$3.convert(translate)._mult(pixelsToTileUnits); + if (translateAnchor === 'viewport') { + pt._rotate(-bearing); + } + const translated = []; + for (let i = 0; i < queryGeometry.length; i++) { + const point = queryGeometry[i]; + translated.push(point.sub(pt)); + } + return translated; +} +function offsetLine(rings, offset) { + const newRings = []; + for (let ringIndex = 0; ringIndex < rings.length; ringIndex++) { + const ring = rings[ringIndex]; + const newRing = []; + for (let index = 0; index < ring.length; index++) { + const a = ring[index - 1]; + const b = ring[index]; + const c = ring[index + 1]; + const aToB = index === 0 ? new Point$3(0, 0) : b.sub(a)._unit()._perp(); + const bToC = index === ring.length - 1 ? new Point$3(0, 0) : c.sub(b)._unit()._perp(); + const extrude = aToB._add(bToC)._unit(); + const cosHalfAngle = extrude.x * bToC.x + extrude.y * bToC.y; + if (cosHalfAngle !== 0) { + extrude._mult(1 / cosHalfAngle); + } + newRing.push(extrude._mult(offset)._add(b)); + } + newRings.push(newRing); + } + return newRings; +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout$5; +const getLayout$3 = () => layout$5 = layout$5 || new Properties({ + "circle-sort-key": new DataDrivenProperty(v8Spec["layout_circle"]["circle-sort-key"]), +}); +let paint$8; +const getPaint$8 = () => paint$8 = paint$8 || new Properties({ + "circle-radius": new DataDrivenProperty(v8Spec["paint_circle"]["circle-radius"]), + "circle-color": new DataDrivenProperty(v8Spec["paint_circle"]["circle-color"]), + "circle-blur": new DataDrivenProperty(v8Spec["paint_circle"]["circle-blur"]), + "circle-opacity": new DataDrivenProperty(v8Spec["paint_circle"]["circle-opacity"]), + "circle-translate": new DataConstantProperty(v8Spec["paint_circle"]["circle-translate"]), + "circle-translate-anchor": new DataConstantProperty(v8Spec["paint_circle"]["circle-translate-anchor"]), + "circle-pitch-scale": new DataConstantProperty(v8Spec["paint_circle"]["circle-pitch-scale"]), + "circle-pitch-alignment": new DataConstantProperty(v8Spec["paint_circle"]["circle-pitch-alignment"]), + "circle-stroke-width": new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-width"]), + "circle-stroke-color": new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-color"]), + "circle-stroke-opacity": new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-opacity"]), +}); +var properties$8 = ({ get paint() { return getPaint$8(); }, get layout() { return getLayout$3(); } }); + +/** + * Common utilities + * @module glMatrix + */ +// Configuration Constants +var EPSILON = 0.000001; +var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; +var RANDOM = Math.random; +/** + * Sets the type of array used when creating new vectors and matrices + * + * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array + */ + +function setMatrixArrayType(type) { + ARRAY_TYPE = type; +} +var degree = Math.PI / 180; +/** + * Convert Degree To Radian + * + * @param {Number} a Angle in Degrees + */ + +function toRadian(a) { + return a * degree; +} +/** + * Tests whether or not the arguments have approximately the same value, within an absolute + * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less + * than or equal to 1.0, and a relative tolerance is used for larger values) + * + * @param {Number} a The first number to test. + * @param {Number} b The second number to test. + * @returns {Boolean} True if the numbers are approximately equal, false otherwise. + */ + +function equals$a(a, b) { + return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b)); +} +if (!Math.hypot) Math.hypot = function () { + var y = 0, + i = arguments.length; + + while (i--) { + y += arguments[i] * arguments[i]; + } + + return Math.sqrt(y); +}; + +var common = /*#__PURE__*/Object.freeze({ +__proto__: null, +get ARRAY_TYPE () { return ARRAY_TYPE; }, +EPSILON: EPSILON, +RANDOM: RANDOM, +equals: equals$a, +setMatrixArrayType: setMatrixArrayType, +toRadian: toRadian +}); + +/** + * 2x2 Matrix + * @module mat2 + */ + +/** + * Creates a new identity mat2 + * + * @returns {mat2} a new 2x2 matrix + */ + +function create$8() { + var out = new ARRAY_TYPE(4); + + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + } + + out[0] = 1; + out[3] = 1; + return out; +} +/** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param {ReadonlyMat2} a matrix to clone + * @returns {mat2} a new 2x2 matrix + */ + +function clone$8(a) { + var out = new ARRAY_TYPE(4); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +} +/** + * Copy the values from one mat2 to another + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the source matrix + * @returns {mat2} out + */ + +function copy$8(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +} +/** + * Set a mat2 to the identity matrix + * + * @param {mat2} out the receiving matrix + * @returns {mat2} out + */ + +function identity$5(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +} +/** + * Create a new mat2 with the given values + * + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m10 Component in column 1, row 0 position (index 2) + * @param {Number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out A new 2x2 matrix + */ + +function fromValues$8(m00, m01, m10, m11) { + var out = new ARRAY_TYPE(4); + out[0] = m00; + out[1] = m01; + out[2] = m10; + out[3] = m11; + return out; +} +/** + * Set the components of a mat2 to the given values + * + * @param {mat2} out the receiving matrix + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m10 Component in column 1, row 0 position (index 2) + * @param {Number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out + */ + +function set$8(out, m00, m01, m10, m11) { + out[0] = m00; + out[1] = m01; + out[2] = m10; + out[3] = m11; + return out; +} +/** + * Transpose the values of a mat2 + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the source matrix + * @returns {mat2} out + */ + +function transpose$2(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache + // some values + if (out === a) { + var a1 = a[1]; + out[1] = a[2]; + out[2] = a1; + } else { + out[0] = a[0]; + out[1] = a[2]; + out[2] = a[1]; + out[3] = a[3]; + } + + return out; +} +/** + * Inverts a mat2 + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the source matrix + * @returns {mat2} out + */ + +function invert$5(out, a) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; // Calculate the determinant + + var det = a0 * a3 - a2 * a1; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = a3 * det; + out[1] = -a1 * det; + out[2] = -a2 * det; + out[3] = a0 * det; + return out; +} +/** + * Calculates the adjugate of a mat2 + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the source matrix + * @returns {mat2} out + */ + +function adjoint$2(out, a) { + // Caching this value is nessecary if out == a + var a0 = a[0]; + out[0] = a[3]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = a0; + return out; +} +/** + * Calculates the determinant of a mat2 + * + * @param {ReadonlyMat2} a the source matrix + * @returns {Number} determinant of a + */ + +function determinant$3(a) { + return a[0] * a[3] - a[2] * a[1]; +} +/** + * Multiplies two mat2's + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the first operand + * @param {ReadonlyMat2} b the second operand + * @returns {mat2} out + */ + +function multiply$8(out, a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + out[0] = a0 * b0 + a2 * b1; + out[1] = a1 * b0 + a3 * b1; + out[2] = a0 * b2 + a2 * b3; + out[3] = a1 * b2 + a3 * b3; + return out; +} +/** + * Rotates a mat2 by the given angle + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + +function rotate$4(out, a, rad) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var s = Math.sin(rad); + var c = Math.cos(rad); + out[0] = a0 * c + a2 * s; + out[1] = a1 * c + a3 * s; + out[2] = a0 * -s + a2 * c; + out[3] = a1 * -s + a3 * c; + return out; +} +/** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the matrix to rotate + * @param {ReadonlyVec2} v the vec2 to scale the matrix by + * @returns {mat2} out + **/ + +function scale$8(out, a, v) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var v0 = v[0], + v1 = v[1]; + out[0] = a0 * v0; + out[1] = a1 * v0; + out[2] = a2 * v1; + out[3] = a3 * v1; + return out; +} +/** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.rotate(dest, dest, rad); + * + * @param {mat2} out mat2 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + +function fromRotation$4(out, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + out[0] = c; + out[1] = s; + out[2] = -s; + out[3] = c; + return out; +} +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.scale(dest, dest, vec); + * + * @param {mat2} out mat2 receiving operation result + * @param {ReadonlyVec2} v Scaling vector + * @returns {mat2} out + */ + +function fromScaling$3(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = v[1]; + return out; +} +/** + * Returns a string representation of a mat2 + * + * @param {ReadonlyMat2} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ + +function str$8(a) { + return "mat2(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ")"; +} +/** + * Returns Frobenius norm of a mat2 + * + * @param {ReadonlyMat2} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ + +function frob$3(a) { + return Math.hypot(a[0], a[1], a[2], a[3]); +} +/** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param {ReadonlyMat2} L the lower triangular matrix + * @param {ReadonlyMat2} D the diagonal matrix + * @param {ReadonlyMat2} U the upper triangular matrix + * @param {ReadonlyMat2} a the input matrix to factorize + */ + +function LDU(L, D, U, a) { + L[2] = a[2] / a[0]; + U[0] = a[0]; + U[1] = a[1]; + U[3] = a[3] - L[2] * U[1]; + return [L, D, U]; +} +/** + * Adds two mat2's + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the first operand + * @param {ReadonlyMat2} b the second operand + * @returns {mat2} out + */ + +function add$8(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + return out; +} +/** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the first operand + * @param {ReadonlyMat2} b the second operand + * @returns {mat2} out + */ + +function subtract$6(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + return out; +} +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyMat2} a The first matrix. + * @param {ReadonlyMat2} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function exactEquals$8(a, b) { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3]; +} +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {ReadonlyMat2} a The first matrix. + * @param {ReadonlyMat2} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function equals$9(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)); +} +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat2} out + */ + +function multiplyScalar$3(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + return out; +} +/** + * Adds two mat2's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2} out the receiving vector + * @param {ReadonlyMat2} a the first operand + * @param {ReadonlyMat2} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat2} out + */ + +function multiplyScalarAndAdd$3(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + return out; +} +/** + * Alias for {@link mat2.multiply} + * @function + */ + +var mul$8 = multiply$8; +/** + * Alias for {@link mat2.subtract} + * @function + */ + +var sub$6 = subtract$6; + +var mat2 = /*#__PURE__*/Object.freeze({ +__proto__: null, +LDU: LDU, +add: add$8, +adjoint: adjoint$2, +clone: clone$8, +copy: copy$8, +create: create$8, +determinant: determinant$3, +equals: equals$9, +exactEquals: exactEquals$8, +frob: frob$3, +fromRotation: fromRotation$4, +fromScaling: fromScaling$3, +fromValues: fromValues$8, +identity: identity$5, +invert: invert$5, +mul: mul$8, +multiply: multiply$8, +multiplyScalar: multiplyScalar$3, +multiplyScalarAndAdd: multiplyScalarAndAdd$3, +rotate: rotate$4, +scale: scale$8, +set: set$8, +str: str$8, +sub: sub$6, +subtract: subtract$6, +transpose: transpose$2 +}); + +/** + * 2x3 Matrix + * @module mat2d + * @description + * A mat2d contains six elements defined as: + *
+ * [a, b,
+ *  c, d,
+ *  tx, ty]
+ * 
+ * This is a short form for the 3x3 matrix: + *
+ * [a, b, 0,
+ *  c, d, 0,
+ *  tx, ty, 1]
+ * 
+ * The last column is ignored so the array is shorter and operations are faster. + */ + +/** + * Creates a new identity mat2d + * + * @returns {mat2d} a new 2x3 matrix + */ + +function create$7() { + var out = new ARRAY_TYPE(6); + + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + out[4] = 0; + out[5] = 0; + } + + out[0] = 1; + out[3] = 1; + return out; +} +/** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param {ReadonlyMat2d} a matrix to clone + * @returns {mat2d} a new 2x3 matrix + */ + +function clone$7(a) { + var out = new ARRAY_TYPE(6); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + return out; +} +/** + * Copy the values from one mat2d to another + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the source matrix + * @returns {mat2d} out + */ + +function copy$7(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + return out; +} +/** + * Set a mat2d to the identity matrix + * + * @param {mat2d} out the receiving matrix + * @returns {mat2d} out + */ + +function identity$4(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = 0; + out[5] = 0; + return out; +} +/** + * Create a new mat2d with the given values + * + * @param {Number} a Component A (index 0) + * @param {Number} b Component B (index 1) + * @param {Number} c Component C (index 2) + * @param {Number} d Component D (index 3) + * @param {Number} tx Component TX (index 4) + * @param {Number} ty Component TY (index 5) + * @returns {mat2d} A new mat2d + */ + +function fromValues$7(a, b, c, d, tx, ty) { + var out = new ARRAY_TYPE(6); + out[0] = a; + out[1] = b; + out[2] = c; + out[3] = d; + out[4] = tx; + out[5] = ty; + return out; +} +/** + * Set the components of a mat2d to the given values + * + * @param {mat2d} out the receiving matrix + * @param {Number} a Component A (index 0) + * @param {Number} b Component B (index 1) + * @param {Number} c Component C (index 2) + * @param {Number} d Component D (index 3) + * @param {Number} tx Component TX (index 4) + * @param {Number} ty Component TY (index 5) + * @returns {mat2d} out + */ + +function set$7(out, a, b, c, d, tx, ty) { + out[0] = a; + out[1] = b; + out[2] = c; + out[3] = d; + out[4] = tx; + out[5] = ty; + return out; +} +/** + * Inverts a mat2d + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the source matrix + * @returns {mat2d} out + */ + +function invert$4(out, a) { + var aa = a[0], + ab = a[1], + ac = a[2], + ad = a[3]; + var atx = a[4], + aty = a[5]; + var det = aa * ad - ab * ac; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = ad * det; + out[1] = -ab * det; + out[2] = -ac * det; + out[3] = aa * det; + out[4] = (ac * aty - ad * atx) * det; + out[5] = (ab * atx - aa * aty) * det; + return out; +} +/** + * Calculates the determinant of a mat2d + * + * @param {ReadonlyMat2d} a the source matrix + * @returns {Number} determinant of a + */ + +function determinant$2(a) { + return a[0] * a[3] - a[1] * a[2]; +} +/** + * Multiplies two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the first operand + * @param {ReadonlyMat2d} b the second operand + * @returns {mat2d} out + */ + +function multiply$7(out, a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5]; + out[0] = a0 * b0 + a2 * b1; + out[1] = a1 * b0 + a3 * b1; + out[2] = a0 * b2 + a2 * b3; + out[3] = a1 * b2 + a3 * b3; + out[4] = a0 * b4 + a2 * b5 + a4; + out[5] = a1 * b4 + a3 * b5 + a5; + return out; +} +/** + * Rotates a mat2d by the given angle + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + +function rotate$3(out, a, rad) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var s = Math.sin(rad); + var c = Math.cos(rad); + out[0] = a0 * c + a2 * s; + out[1] = a1 * c + a3 * s; + out[2] = a0 * -s + a2 * c; + out[3] = a1 * -s + a3 * c; + out[4] = a4; + out[5] = a5; + return out; +} +/** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to translate + * @param {ReadonlyVec2} v the vec2 to scale the matrix by + * @returns {mat2d} out + **/ + +function scale$7(out, a, v) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var v0 = v[0], + v1 = v[1]; + out[0] = a0 * v0; + out[1] = a1 * v0; + out[2] = a2 * v1; + out[3] = a3 * v1; + out[4] = a4; + out[5] = a5; + return out; +} +/** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to translate + * @param {ReadonlyVec2} v the vec2 to translate the matrix by + * @returns {mat2d} out + **/ + +function translate$3(out, a, v) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var v0 = v[0], + v1 = v[1]; + out[0] = a0; + out[1] = a1; + out[2] = a2; + out[3] = a3; + out[4] = a0 * v0 + a2 * v1 + a4; + out[5] = a1 * v0 + a3 * v1 + a5; + return out; +} +/** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.rotate(dest, dest, rad); + * + * @param {mat2d} out mat2d receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + +function fromRotation$3(out, rad) { + var s = Math.sin(rad), + c = Math.cos(rad); + out[0] = c; + out[1] = s; + out[2] = -s; + out[3] = c; + out[4] = 0; + out[5] = 0; + return out; +} +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.scale(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {ReadonlyVec2} v Scaling vector + * @returns {mat2d} out + */ + +function fromScaling$2(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = v[1]; + out[4] = 0; + out[5] = 0; + return out; +} +/** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.translate(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {ReadonlyVec2} v Translation vector + * @returns {mat2d} out + */ + +function fromTranslation$3(out, v) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = v[0]; + out[5] = v[1]; + return out; +} +/** + * Returns a string representation of a mat2d + * + * @param {ReadonlyMat2d} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ + +function str$7(a) { + return "mat2d(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ")"; +} +/** + * Returns Frobenius norm of a mat2d + * + * @param {ReadonlyMat2d} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ + +function frob$2(a) { + return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], 1); +} +/** + * Adds two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the first operand + * @param {ReadonlyMat2d} b the second operand + * @returns {mat2d} out + */ + +function add$7(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + out[4] = a[4] + b[4]; + out[5] = a[5] + b[5]; + return out; +} +/** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the first operand + * @param {ReadonlyMat2d} b the second operand + * @returns {mat2d} out + */ + +function subtract$5(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + out[4] = a[4] - b[4]; + out[5] = a[5] - b[5]; + return out; +} +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat2d} out + */ + +function multiplyScalar$2(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + out[4] = a[4] * b; + out[5] = a[5] * b; + return out; +} +/** + * Adds two mat2d's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2d} out the receiving vector + * @param {ReadonlyMat2d} a the first operand + * @param {ReadonlyMat2d} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat2d} out + */ + +function multiplyScalarAndAdd$2(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + out[4] = a[4] + b[4] * scale; + out[5] = a[5] + b[5] * scale; + return out; +} +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyMat2d} a The first matrix. + * @param {ReadonlyMat2d} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function exactEquals$7(a, b) { + 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]; +} +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {ReadonlyMat2d} a The first matrix. + * @param {ReadonlyMat2d} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function equals$8(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)); +} +/** + * Alias for {@link mat2d.multiply} + * @function + */ + +var mul$7 = multiply$7; +/** + * Alias for {@link mat2d.subtract} + * @function + */ + +var sub$5 = subtract$5; + +var mat2d = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$7, +clone: clone$7, +copy: copy$7, +create: create$7, +determinant: determinant$2, +equals: equals$8, +exactEquals: exactEquals$7, +frob: frob$2, +fromRotation: fromRotation$3, +fromScaling: fromScaling$2, +fromTranslation: fromTranslation$3, +fromValues: fromValues$7, +identity: identity$4, +invert: invert$4, +mul: mul$7, +multiply: multiply$7, +multiplyScalar: multiplyScalar$2, +multiplyScalarAndAdd: multiplyScalarAndAdd$2, +rotate: rotate$3, +scale: scale$7, +set: set$7, +str: str$7, +sub: sub$5, +subtract: subtract$5, +translate: translate$3 +}); + +/** + * 3x3 Matrix + * @module mat3 + */ + +/** + * Creates a new identity mat3 + * + * @returns {mat3} a new 3x3 matrix + */ + +function create$6() { + var out = new ARRAY_TYPE(9); + + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[5] = 0; + out[6] = 0; + out[7] = 0; + } + + out[0] = 1; + out[4] = 1; + out[8] = 1; + return out; +} +/** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {ReadonlyMat4} a the source 4x4 matrix + * @returns {mat3} out + */ + +function fromMat4$1(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[4]; + out[4] = a[5]; + out[5] = a[6]; + out[6] = a[8]; + out[7] = a[9]; + out[8] = a[10]; + return out; +} +/** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param {ReadonlyMat3} a matrix to clone + * @returns {mat3} a new 3x3 matrix + */ + +function clone$6(a) { + var out = new ARRAY_TYPE(9); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +} +/** + * Copy the values from one mat3 to another + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the source matrix + * @returns {mat3} out + */ + +function copy$6(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +} +/** + * Create a new mat3 with the given values + * + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m10 Component in column 1, row 0 position (index 3) + * @param {Number} m11 Component in column 1, row 1 position (index 4) + * @param {Number} m12 Component in column 1, row 2 position (index 5) + * @param {Number} m20 Component in column 2, row 0 position (index 6) + * @param {Number} m21 Component in column 2, row 1 position (index 7) + * @param {Number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} A new mat3 + */ + +function fromValues$6(m00, m01, m02, m10, m11, m12, m20, m21, m22) { + var out = new ARRAY_TYPE(9); + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m10; + out[4] = m11; + out[5] = m12; + out[6] = m20; + out[7] = m21; + out[8] = m22; + return out; +} +/** + * Set the components of a mat3 to the given values + * + * @param {mat3} out the receiving matrix + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m10 Component in column 1, row 0 position (index 3) + * @param {Number} m11 Component in column 1, row 1 position (index 4) + * @param {Number} m12 Component in column 1, row 2 position (index 5) + * @param {Number} m20 Component in column 2, row 0 position (index 6) + * @param {Number} m21 Component in column 2, row 1 position (index 7) + * @param {Number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} out + */ + +function set$6(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) { + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m10; + out[4] = m11; + out[5] = m12; + out[6] = m20; + out[7] = m21; + out[8] = m22; + return out; +} +/** + * Set a mat3 to the identity matrix + * + * @param {mat3} out the receiving matrix + * @returns {mat3} out + */ + +function identity$3(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 1; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +} +/** + * Transpose the values of a mat3 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the source matrix + * @returns {mat3} out + */ + +function transpose$1(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a[1], + a02 = a[2], + a12 = a[5]; + out[1] = a[3]; + out[2] = a[6]; + out[3] = a01; + out[5] = a[7]; + out[6] = a02; + out[7] = a12; + } else { + out[0] = a[0]; + out[1] = a[3]; + out[2] = a[6]; + out[3] = a[1]; + out[4] = a[4]; + out[5] = a[7]; + out[6] = a[2]; + out[7] = a[5]; + out[8] = a[8]; + } + + return out; +} +/** + * Inverts a mat3 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the source matrix + * @returns {mat3} out + */ + +function invert$3(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2]; + var a10 = a[3], + a11 = a[4], + a12 = a[5]; + var a20 = a[6], + a21 = a[7], + a22 = a[8]; + var b01 = a22 * a11 - a12 * a21; + var b11 = -a22 * a10 + a12 * a20; + var b21 = a21 * a10 - a11 * a20; // Calculate the determinant + + var det = a00 * b01 + a01 * b11 + a02 * b21; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = b01 * det; + out[1] = (-a22 * a01 + a02 * a21) * det; + out[2] = (a12 * a01 - a02 * a11) * det; + out[3] = b11 * det; + out[4] = (a22 * a00 - a02 * a20) * det; + out[5] = (-a12 * a00 + a02 * a10) * det; + out[6] = b21 * det; + out[7] = (-a21 * a00 + a01 * a20) * det; + out[8] = (a11 * a00 - a01 * a10) * det; + return out; +} +/** + * Calculates the adjugate of a mat3 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the source matrix + * @returns {mat3} out + */ + +function adjoint$1(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2]; + var a10 = a[3], + a11 = a[4], + a12 = a[5]; + var a20 = a[6], + a21 = a[7], + a22 = a[8]; + out[0] = a11 * a22 - a12 * a21; + out[1] = a02 * a21 - a01 * a22; + out[2] = a01 * a12 - a02 * a11; + out[3] = a12 * a20 - a10 * a22; + out[4] = a00 * a22 - a02 * a20; + out[5] = a02 * a10 - a00 * a12; + out[6] = a10 * a21 - a11 * a20; + out[7] = a01 * a20 - a00 * a21; + out[8] = a00 * a11 - a01 * a10; + return out; +} +/** + * Calculates the determinant of a mat3 + * + * @param {ReadonlyMat3} a the source matrix + * @returns {Number} determinant of a + */ + +function determinant$1(a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2]; + var a10 = a[3], + a11 = a[4], + a12 = a[5]; + var a20 = a[6], + a21 = a[7], + a22 = a[8]; + return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); +} +/** + * Multiplies two mat3's + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the first operand + * @param {ReadonlyMat3} b the second operand + * @returns {mat3} out + */ + +function multiply$6(out, a, b) { + var a00 = a[0], + a01 = a[1], + a02 = a[2]; + var a10 = a[3], + a11 = a[4], + a12 = a[5]; + var a20 = a[6], + a21 = a[7], + a22 = a[8]; + var b00 = b[0], + b01 = b[1], + b02 = b[2]; + var b10 = b[3], + b11 = b[4], + b12 = b[5]; + var b20 = b[6], + b21 = b[7], + b22 = b[8]; + out[0] = b00 * a00 + b01 * a10 + b02 * a20; + out[1] = b00 * a01 + b01 * a11 + b02 * a21; + out[2] = b00 * a02 + b01 * a12 + b02 * a22; + out[3] = b10 * a00 + b11 * a10 + b12 * a20; + out[4] = b10 * a01 + b11 * a11 + b12 * a21; + out[5] = b10 * a02 + b11 * a12 + b12 * a22; + out[6] = b20 * a00 + b21 * a10 + b22 * a20; + out[7] = b20 * a01 + b21 * a11 + b22 * a21; + out[8] = b20 * a02 + b21 * a12 + b22 * a22; + return out; +} +/** + * Translate a mat3 by the given vector + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the matrix to translate + * @param {ReadonlyVec2} v vector to translate by + * @returns {mat3} out + */ + +function translate$2(out, a, v) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a10 = a[3], + a11 = a[4], + a12 = a[5], + a20 = a[6], + a21 = a[7], + a22 = a[8], + x = v[0], + y = v[1]; + out[0] = a00; + out[1] = a01; + out[2] = a02; + out[3] = a10; + out[4] = a11; + out[5] = a12; + out[6] = x * a00 + y * a10 + a20; + out[7] = x * a01 + y * a11 + a21; + out[8] = x * a02 + y * a12 + a22; + return out; +} +/** + * Rotates a mat3 by the given angle + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + +function rotate$2(out, a, rad) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a10 = a[3], + a11 = a[4], + a12 = a[5], + a20 = a[6], + a21 = a[7], + a22 = a[8], + s = Math.sin(rad), + c = Math.cos(rad); + out[0] = c * a00 + s * a10; + out[1] = c * a01 + s * a11; + out[2] = c * a02 + s * a12; + out[3] = c * a10 - s * a00; + out[4] = c * a11 - s * a01; + out[5] = c * a12 - s * a02; + out[6] = a20; + out[7] = a21; + out[8] = a22; + return out; +} +/** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the matrix to rotate + * @param {ReadonlyVec2} v the vec2 to scale the matrix by + * @returns {mat3} out + **/ + +function scale$6(out, a, v) { + var x = v[0], + y = v[1]; + out[0] = x * a[0]; + out[1] = x * a[1]; + out[2] = x * a[2]; + out[3] = y * a[3]; + out[4] = y * a[4]; + out[5] = y * a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +} +/** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.translate(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {ReadonlyVec2} v Translation vector + * @returns {mat3} out + */ + +function fromTranslation$2(out, v) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 1; + out[5] = 0; + out[6] = v[0]; + out[7] = v[1]; + out[8] = 1; + return out; +} +/** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.rotate(dest, dest, rad); + * + * @param {mat3} out mat3 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + +function fromRotation$2(out, rad) { + var s = Math.sin(rad), + c = Math.cos(rad); + out[0] = c; + out[1] = s; + out[2] = 0; + out[3] = -s; + out[4] = c; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +} +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.scale(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {ReadonlyVec2} v Scaling vector + * @returns {mat3} out + */ + +function fromScaling$1(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = v[1]; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +} +/** + * Copies the values from a mat2d into a mat3 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to copy + * @returns {mat3} out + **/ + +function fromMat2d(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = 0; + out[3] = a[2]; + out[4] = a[3]; + out[5] = 0; + out[6] = a[4]; + out[7] = a[5]; + out[8] = 1; + return out; +} +/** + * Calculates a 3x3 matrix from the given quaternion + * + * @param {mat3} out mat3 receiving operation result + * @param {ReadonlyQuat} q Quaternion to create matrix from + * + * @returns {mat3} out + */ + +function fromQuat$1(out, q) { + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var yx = y * x2; + var yy = y * y2; + var zx = z * x2; + var zy = z * y2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + out[0] = 1 - yy - zz; + out[3] = yx - wz; + out[6] = zx + wy; + out[1] = yx + wz; + out[4] = 1 - xx - zz; + out[7] = zy - wx; + out[2] = zx - wy; + out[5] = zy + wx; + out[8] = 1 - xx - yy; + return out; +} +/** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param {mat3} out mat3 receiving operation result + * @param {ReadonlyMat4} a Mat4 to derive the normal matrix from + * + * @returns {mat3} out + */ + +function normalFromMat4(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; // Calculate the determinant + + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + return out; +} +/** + * Generates a 2D projection matrix with the given bounds + * + * @param {mat3} out mat3 frustum matrix will be written into + * @param {number} width Width of your gl context + * @param {number} height Height of gl context + * @returns {mat3} out + */ + +function projection(out, width, height) { + out[0] = 2 / width; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = -2 / height; + out[5] = 0; + out[6] = -1; + out[7] = 1; + out[8] = 1; + return out; +} +/** + * Returns a string representation of a mat3 + * + * @param {ReadonlyMat3} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ + +function str$6(a) { + return "mat3(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ", " + a[6] + ", " + a[7] + ", " + a[8] + ")"; +} +/** + * Returns Frobenius norm of a mat3 + * + * @param {ReadonlyMat3} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ + +function frob$1(a) { + return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]); +} +/** + * Adds two mat3's + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the first operand + * @param {ReadonlyMat3} b the second operand + * @returns {mat3} out + */ + +function add$6(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + out[4] = a[4] + b[4]; + out[5] = a[5] + b[5]; + out[6] = a[6] + b[6]; + out[7] = a[7] + b[7]; + out[8] = a[8] + b[8]; + return out; +} +/** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the first operand + * @param {ReadonlyMat3} b the second operand + * @returns {mat3} out + */ + +function subtract$4(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + out[4] = a[4] - b[4]; + out[5] = a[5] - b[5]; + out[6] = a[6] - b[6]; + out[7] = a[7] - b[7]; + out[8] = a[8] - b[8]; + return out; +} +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat3} out + */ + +function multiplyScalar$1(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + out[4] = a[4] * b; + out[5] = a[5] * b; + out[6] = a[6] * b; + out[7] = a[7] * b; + out[8] = a[8] * b; + return out; +} +/** + * Adds two mat3's after multiplying each element of the second operand by a scalar value. + * + * @param {mat3} out the receiving vector + * @param {ReadonlyMat3} a the first operand + * @param {ReadonlyMat3} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat3} out + */ + +function multiplyScalarAndAdd$1(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + out[4] = a[4] + b[4] * scale; + out[5] = a[5] + b[5] * scale; + out[6] = a[6] + b[6] * scale; + out[7] = a[7] + b[7] * scale; + out[8] = a[8] + b[8] * scale; + return out; +} +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyMat3} a The first matrix. + * @param {ReadonlyMat3} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function exactEquals$6(a, b) { + 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]; +} +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {ReadonlyMat3} a The first matrix. + * @param {ReadonlyMat3} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function equals$7(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5], + a6 = a[6], + a7 = a[7], + a8 = a[8]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)); +} +/** + * Alias for {@link mat3.multiply} + * @function + */ + +var mul$6 = multiply$6; +/** + * Alias for {@link mat3.subtract} + * @function + */ + +var sub$4 = subtract$4; + +var mat3 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$6, +adjoint: adjoint$1, +clone: clone$6, +copy: copy$6, +create: create$6, +determinant: determinant$1, +equals: equals$7, +exactEquals: exactEquals$6, +frob: frob$1, +fromMat2d: fromMat2d, +fromMat4: fromMat4$1, +fromQuat: fromQuat$1, +fromRotation: fromRotation$2, +fromScaling: fromScaling$1, +fromTranslation: fromTranslation$2, +fromValues: fromValues$6, +identity: identity$3, +invert: invert$3, +mul: mul$6, +multiply: multiply$6, +multiplyScalar: multiplyScalar$1, +multiplyScalarAndAdd: multiplyScalarAndAdd$1, +normalFromMat4: normalFromMat4, +projection: projection, +rotate: rotate$2, +scale: scale$6, +set: set$6, +str: str$6, +sub: sub$4, +subtract: subtract$4, +translate: translate$2, +transpose: transpose$1 +}); + +/** + * 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied. + * @module mat4 + */ + +/** + * Creates a new identity mat4 + * + * @returns {mat4} a new 4x4 matrix + */ + +function create$5() { + var out = new ARRAY_TYPE(16); + + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + } + + out[0] = 1; + out[5] = 1; + out[10] = 1; + out[15] = 1; + return out; +} +/** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param {ReadonlyMat4} a matrix to clone + * @returns {mat4} a new 4x4 matrix + */ + +function clone$5(a) { + var out = new ARRAY_TYPE(16); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +/** + * Copy the values from one mat4 to another + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function copy$5(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +/** + * Create a new mat4 with the given values + * + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m03 Component in column 0, row 3 position (index 3) + * @param {Number} m10 Component in column 1, row 0 position (index 4) + * @param {Number} m11 Component in column 1, row 1 position (index 5) + * @param {Number} m12 Component in column 1, row 2 position (index 6) + * @param {Number} m13 Component in column 1, row 3 position (index 7) + * @param {Number} m20 Component in column 2, row 0 position (index 8) + * @param {Number} m21 Component in column 2, row 1 position (index 9) + * @param {Number} m22 Component in column 2, row 2 position (index 10) + * @param {Number} m23 Component in column 2, row 3 position (index 11) + * @param {Number} m30 Component in column 3, row 0 position (index 12) + * @param {Number} m31 Component in column 3, row 1 position (index 13) + * @param {Number} m32 Component in column 3, row 2 position (index 14) + * @param {Number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} A new mat4 + */ + +function fromValues$5(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { + var out = new ARRAY_TYPE(16); + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m03; + out[4] = m10; + out[5] = m11; + out[6] = m12; + out[7] = m13; + out[8] = m20; + out[9] = m21; + out[10] = m22; + out[11] = m23; + out[12] = m30; + out[13] = m31; + out[14] = m32; + out[15] = m33; + return out; +} +/** + * Set the components of a mat4 to the given values + * + * @param {mat4} out the receiving matrix + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m03 Component in column 0, row 3 position (index 3) + * @param {Number} m10 Component in column 1, row 0 position (index 4) + * @param {Number} m11 Component in column 1, row 1 position (index 5) + * @param {Number} m12 Component in column 1, row 2 position (index 6) + * @param {Number} m13 Component in column 1, row 3 position (index 7) + * @param {Number} m20 Component in column 2, row 0 position (index 8) + * @param {Number} m21 Component in column 2, row 1 position (index 9) + * @param {Number} m22 Component in column 2, row 2 position (index 10) + * @param {Number} m23 Component in column 2, row 3 position (index 11) + * @param {Number} m30 Component in column 3, row 0 position (index 12) + * @param {Number} m31 Component in column 3, row 1 position (index 13) + * @param {Number} m32 Component in column 3, row 2 position (index 14) + * @param {Number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} out + */ + +function set$5(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m03; + out[4] = m10; + out[5] = m11; + out[6] = m12; + out[7] = m13; + out[8] = m20; + out[9] = m21; + out[10] = m22; + out[11] = m23; + out[12] = m30; + out[13] = m31; + out[14] = m32; + out[15] = m33; + return out; +} +/** + * Set a mat4 to the identity matrix + * + * @param {mat4} out the receiving matrix + * @returns {mat4} out + */ + +function identity$2(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Transpose the values of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function transpose(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a12 = a[6], + a13 = a[7]; + var a23 = a[11]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a01; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a02; + out[9] = a12; + out[11] = a[14]; + out[12] = a03; + out[13] = a13; + out[14] = a23; + } else { + out[0] = a[0]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a[1]; + out[5] = a[5]; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a[2]; + out[9] = a[6]; + out[10] = a[10]; + out[11] = a[14]; + out[12] = a[3]; + out[13] = a[7]; + out[14] = a[11]; + out[15] = a[15]; + } + + return out; +} +/** + * Inverts a mat4 + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function invert$2(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; // Calculate the determinant + + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + return out; +} +/** + * Calculates the adjugate of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function adjoint(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; + out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22); + out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); + out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12); + out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); + out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); + out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22); + out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); + out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12); + out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21); + out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); + out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11); + out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); + out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); + out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21); + out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); + out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11); + return out; +} +/** + * Calculates the determinant of a mat4 + * + * @param {ReadonlyMat4} a the source matrix + * @returns {Number} determinant of a + */ + +function determinant(a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; // Calculate the determinant + + return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; +} +/** + * Multiplies two mat4s + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the first operand + * @param {ReadonlyMat4} b the second operand + * @returns {mat4} out + */ + +function multiply$5(out, a, b) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; // Cache only the current line of the second matrix + + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[4]; + b1 = b[5]; + b2 = b[6]; + b3 = b[7]; + out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[8]; + b1 = b[9]; + b2 = b[10]; + b3 = b[11]; + out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[12]; + b1 = b[13]; + b2 = b[14]; + b3 = b[15]; + out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + return out; +} +/** + * Translate a mat4 by the given vector + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to translate + * @param {ReadonlyVec3} v vector to translate by + * @returns {mat4} out + */ + +function translate$1(out, a, v) { + var x = v[0], + y = v[1], + z = v[2]; + var a00, a01, a02, a03; + var a10, a11, a12, a13; + var a20, a21, a22, a23; + + if (a === out) { + out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + } else { + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; + out[0] = a00; + out[1] = a01; + out[2] = a02; + out[3] = a03; + out[4] = a10; + out[5] = a11; + out[6] = a12; + out[7] = a13; + out[8] = a20; + out[9] = a21; + out[10] = a22; + out[11] = a23; + out[12] = a00 * x + a10 * y + a20 * z + a[12]; + out[13] = a01 * x + a11 * y + a21 * z + a[13]; + out[14] = a02 * x + a12 * y + a22 * z + a[14]; + out[15] = a03 * x + a13 * y + a23 * z + a[15]; + } + + return out; +} +/** + * Scales the mat4 by the dimensions in the given vec3 not using vectorization + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to scale + * @param {ReadonlyVec3} v the vec3 to scale the matrix by + * @returns {mat4} out + **/ + +function scale$5(out, a, v) { + var x = v[0], + y = v[1], + z = v[2]; + out[0] = a[0] * x; + out[1] = a[1] * x; + out[2] = a[2] * x; + out[3] = a[3] * x; + out[4] = a[4] * y; + out[5] = a[5] * y; + out[6] = a[6] * y; + out[7] = a[7] * y; + out[8] = a[8] * z; + out[9] = a[9] * z; + out[10] = a[10] * z; + out[11] = a[11] * z; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +/** + * Rotates a mat4 by the given angle around the given axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @param {ReadonlyVec3} axis the axis to rotate around + * @returns {mat4} out + */ + +function rotate$1(out, a, rad, axis) { + var x = axis[0], + y = axis[1], + z = axis[2]; + var len = Math.hypot(x, y, z); + var s, c, t; + var a00, a01, a02, a03; + var a10, a11, a12, a13; + var a20, a21, a22, a23; + var b00, b01, b02; + var b10, b11, b12; + var b20, b21, b22; + + if (len < EPSILON) { + return null; + } + + len = 1 / len; + x *= len; + y *= len; + z *= len; + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; // Construct the elements of the rotation matrix + + b00 = x * x * t + c; + b01 = y * x * t + z * s; + b02 = z * x * t - y * s; + b10 = x * y * t - z * s; + b11 = y * y * t + c; + b12 = z * y * t + x * s; + b20 = x * z * t + y * s; + b21 = y * z * t - x * s; + b22 = z * z * t + c; // Perform rotation-specific matrix multiplication + + out[0] = a00 * b00 + a10 * b01 + a20 * b02; + out[1] = a01 * b00 + a11 * b01 + a21 * b02; + out[2] = a02 * b00 + a12 * b01 + a22 * b02; + out[3] = a03 * b00 + a13 * b01 + a23 * b02; + out[4] = a00 * b10 + a10 * b11 + a20 * b12; + out[5] = a01 * b10 + a11 * b11 + a21 * b12; + out[6] = a02 * b10 + a12 * b11 + a22 * b12; + out[7] = a03 * b10 + a13 * b11 + a23 * b12; + out[8] = a00 * b20 + a10 * b21 + a20 * b22; + out[9] = a01 * b20 + a11 * b21 + a21 * b22; + out[10] = a02 * b20 + a12 * b21 + a22 * b22; + out[11] = a03 * b20 + a13 * b21 + a23 * b22; + + if (a !== out) { + // If the source and destination differ, copy the unchanged last row + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + + return out; +} +/** + * Rotates a matrix by the given angle around the X axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function rotateX$3(out, a, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + if (a !== out) { + // If the source and destination differ, copy the unchanged rows + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } // Perform axis-specific matrix multiplication + + + out[4] = a10 * c + a20 * s; + out[5] = a11 * c + a21 * s; + out[6] = a12 * c + a22 * s; + out[7] = a13 * c + a23 * s; + out[8] = a20 * c - a10 * s; + out[9] = a21 * c - a11 * s; + out[10] = a22 * c - a12 * s; + out[11] = a23 * c - a13 * s; + return out; +} +/** + * Rotates a matrix by the given angle around the Y axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function rotateY$3(out, a, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + if (a !== out) { + // If the source and destination differ, copy the unchanged rows + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } // Perform axis-specific matrix multiplication + + + out[0] = a00 * c - a20 * s; + out[1] = a01 * c - a21 * s; + out[2] = a02 * c - a22 * s; + out[3] = a03 * c - a23 * s; + out[8] = a00 * s + a20 * c; + out[9] = a01 * s + a21 * c; + out[10] = a02 * s + a22 * c; + out[11] = a03 * s + a23 * c; + return out; +} +/** + * Rotates a matrix by the given angle around the Z axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function rotateZ$3(out, a, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + if (a !== out) { + // If the source and destination differ, copy the unchanged last row + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } // Perform axis-specific matrix multiplication + + + out[0] = a00 * c + a10 * s; + out[1] = a01 * c + a11 * s; + out[2] = a02 * c + a12 * s; + out[3] = a03 * c + a13 * s; + out[4] = a10 * c - a00 * s; + out[5] = a11 * c - a01 * s; + out[6] = a12 * c - a02 * s; + out[7] = a13 * c - a03 * s; + return out; +} +/** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {ReadonlyVec3} v Translation vector + * @returns {mat4} out + */ + +function fromTranslation$1(out, v) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; +} +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {ReadonlyVec3} v Scaling vector + * @returns {mat4} out + */ + +function fromScaling(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = v[1]; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = v[2]; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from a given angle around a given axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotate(dest, dest, rad, axis); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @param {ReadonlyVec3} axis the axis to rotate around + * @returns {mat4} out + */ + +function fromRotation$1(out, rad, axis) { + var x = axis[0], + y = axis[1], + z = axis[2]; + var len = Math.hypot(x, y, z); + var s, c, t; + + if (len < EPSILON) { + return null; + } + + len = 1 / len; + x *= len; + y *= len; + z *= len; + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; // Perform rotation-specific matrix multiplication + + out[0] = x * x * t + c; + out[1] = y * x * t + z * s; + out[2] = z * x * t - y * s; + out[3] = 0; + out[4] = x * y * t - z * s; + out[5] = y * y * t + c; + out[6] = z * y * t + x * s; + out[7] = 0; + out[8] = x * z * t + y * s; + out[9] = y * z * t - x * s; + out[10] = z * z * t + c; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from the given angle around the X axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateX(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function fromXRotation(out, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); // Perform axis-specific matrix multiplication + + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = c; + out[6] = s; + out[7] = 0; + out[8] = 0; + out[9] = -s; + out[10] = c; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from the given angle around the Y axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateY(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function fromYRotation(out, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); // Perform axis-specific matrix multiplication + + out[0] = c; + out[1] = 0; + out[2] = -s; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = s; + out[9] = 0; + out[10] = c; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from the given angle around the Z axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateZ(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function fromZRotation(out, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); // Perform axis-specific matrix multiplication + + out[0] = c; + out[1] = s; + out[2] = 0; + out[3] = 0; + out[4] = -s; + out[5] = c; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * let quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @param {ReadonlyVec3} v Translation vector + * @returns {mat4} out + */ + +function fromRotationTranslation$1(out, q, v) { + // Quaternion math + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; +} +/** + * Creates a new mat4 from a dual quat. + * + * @param {mat4} out Matrix + * @param {ReadonlyQuat2} a Dual Quaternion + * @returns {mat4} mat4 receiving operation result + */ + +function fromQuat2(out, a) { + var translation = new ARRAY_TYPE(3); + var bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3], + ax = a[4], + ay = a[5], + az = a[6], + aw = a[7]; + var magnitude = bx * bx + by * by + bz * bz + bw * bw; //Only scale if it makes sense + + if (magnitude > 0) { + translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude; + translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude; + translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude; + } else { + translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2; + translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2; + translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2; + } + + fromRotationTranslation$1(out, a, translation); + return out; +} +/** + * Returns the translation vector component of a transformation + * matrix. If a matrix is built with fromRotationTranslation, + * the returned vector will be the same as the translation vector + * originally supplied. + * @param {vec3} out Vector to receive translation component + * @param {ReadonlyMat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + +function getTranslation$1(out, mat) { + out[0] = mat[12]; + out[1] = mat[13]; + out[2] = mat[14]; + return out; +} +/** + * Returns the scaling factor component of a transformation + * matrix. If a matrix is built with fromRotationTranslationScale + * with a normalized Quaternion paramter, the returned vector will be + * the same as the scaling vector + * originally supplied. + * @param {vec3} out Vector to receive scaling factor component + * @param {ReadonlyMat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + +function getScaling(out, mat) { + var m11 = mat[0]; + var m12 = mat[1]; + var m13 = mat[2]; + var m21 = mat[4]; + var m22 = mat[5]; + var m23 = mat[6]; + var m31 = mat[8]; + var m32 = mat[9]; + var m33 = mat[10]; + out[0] = Math.hypot(m11, m12, m13); + out[1] = Math.hypot(m21, m22, m23); + out[2] = Math.hypot(m31, m32, m33); + return out; +} +/** + * Returns a quaternion representing the rotational component + * of a transformation matrix. If a matrix is built with + * fromRotationTranslation, the returned quaternion will be the + * same as the quaternion originally supplied. + * @param {quat} out Quaternion to receive the rotation component + * @param {ReadonlyMat4} mat Matrix to be decomposed (input) + * @return {quat} out + */ + +function getRotation(out, mat) { + var scaling = new ARRAY_TYPE(3); + getScaling(scaling, mat); + var is1 = 1 / scaling[0]; + var is2 = 1 / scaling[1]; + var is3 = 1 / scaling[2]; + var sm11 = mat[0] * is1; + var sm12 = mat[1] * is2; + var sm13 = mat[2] * is3; + var sm21 = mat[4] * is1; + var sm22 = mat[5] * is2; + var sm23 = mat[6] * is3; + var sm31 = mat[8] * is1; + var sm32 = mat[9] * is2; + var sm33 = mat[10] * is3; + var trace = sm11 + sm22 + sm33; + var S = 0; + + if (trace > 0) { + S = Math.sqrt(trace + 1.0) * 2; + out[3] = 0.25 * S; + out[0] = (sm23 - sm32) / S; + out[1] = (sm31 - sm13) / S; + out[2] = (sm12 - sm21) / S; + } else if (sm11 > sm22 && sm11 > sm33) { + S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2; + out[3] = (sm23 - sm32) / S; + out[0] = 0.25 * S; + out[1] = (sm12 + sm21) / S; + out[2] = (sm31 + sm13) / S; + } else if (sm22 > sm33) { + S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2; + out[3] = (sm31 - sm13) / S; + out[0] = (sm12 + sm21) / S; + out[1] = 0.25 * S; + out[2] = (sm23 + sm32) / S; + } else { + S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2; + out[3] = (sm12 - sm21) / S; + out[0] = (sm31 + sm13) / S; + out[1] = (sm23 + sm32) / S; + out[2] = 0.25 * S; + } + + return out; +} +/** + * Creates a matrix from a quaternion rotation, vector translation and vector scale + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * let quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @param {ReadonlyVec3} v Translation vector + * @param {ReadonlyVec3} s Scaling vector + * @returns {mat4} out + */ + +function fromRotationTranslationScale(out, q, v, s) { + // Quaternion math + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + var sx = s[0]; + var sy = s[1]; + var sz = s[2]; + out[0] = (1 - (yy + zz)) * sx; + out[1] = (xy + wz) * sx; + out[2] = (xz - wy) * sx; + out[3] = 0; + out[4] = (xy - wz) * sy; + out[5] = (1 - (xx + zz)) * sy; + out[6] = (yz + wx) * sy; + out[7] = 0; + out[8] = (xz + wy) * sz; + out[9] = (yz - wx) * sz; + out[10] = (1 - (xx + yy)) * sz; + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; +} +/** + * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * mat4.translate(dest, origin); + * let quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * mat4.translate(dest, negativeOrigin); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @param {ReadonlyVec3} v Translation vector + * @param {ReadonlyVec3} s Scaling vector + * @param {ReadonlyVec3} o The origin vector around which to scale and rotate + * @returns {mat4} out + */ + +function fromRotationTranslationScaleOrigin(out, q, v, s, o) { + // Quaternion math + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + var sx = s[0]; + var sy = s[1]; + var sz = s[2]; + var ox = o[0]; + var oy = o[1]; + var oz = o[2]; + var out0 = (1 - (yy + zz)) * sx; + var out1 = (xy + wz) * sx; + var out2 = (xz - wy) * sx; + var out4 = (xy - wz) * sy; + var out5 = (1 - (xx + zz)) * sy; + var out6 = (yz + wx) * sy; + var out8 = (xz + wy) * sz; + var out9 = (yz - wx) * sz; + var out10 = (1 - (xx + yy)) * sz; + out[0] = out0; + out[1] = out1; + out[2] = out2; + out[3] = 0; + out[4] = out4; + out[5] = out5; + out[6] = out6; + out[7] = 0; + out[8] = out8; + out[9] = out9; + out[10] = out10; + out[11] = 0; + out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz); + out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz); + out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz); + out[15] = 1; + return out; +} +/** + * Calculates a 4x4 matrix from the given quaternion + * + * @param {mat4} out mat4 receiving operation result + * @param {ReadonlyQuat} q Quaternion to create matrix from + * + * @returns {mat4} out + */ + +function fromQuat(out, q) { + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var yx = y * x2; + var yy = y * y2; + var zx = z * x2; + var zy = z * y2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + out[0] = 1 - yy - zz; + out[1] = yx + wz; + out[2] = zx - wy; + out[3] = 0; + out[4] = yx - wz; + out[5] = 1 - xx - zz; + out[6] = zy + wx; + out[7] = 0; + out[8] = zx + wy; + out[9] = zy - wx; + out[10] = 1 - xx - yy; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Generates a frustum matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Number} left Left bound of the frustum + * @param {Number} right Right bound of the frustum + * @param {Number} bottom Bottom bound of the frustum + * @param {Number} top Top bound of the frustum + * @param {Number} near Near bound of the frustum + * @param {Number} far Far bound of the frustum + * @returns {mat4} out + */ + +function frustum(out, left, right, bottom, top, near, far) { + var rl = 1 / (right - left); + var tb = 1 / (top - bottom); + var nf = 1 / (near - far); + out[0] = near * 2 * rl; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = near * 2 * tb; + out[6] = 0; + out[7] = 0; + out[8] = (right + left) * rl; + out[9] = (top + bottom) * tb; + out[10] = (far + near) * nf; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = far * near * 2 * nf; + out[15] = 0; + return out; +} +/** + * Generates a perspective projection matrix with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1], + * which matches WebGL/OpenGL's clip volume. + * Passing null/undefined/no value for far will generate infinite projection matrix. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} fovy Vertical field of view in radians + * @param {number} aspect Aspect ratio. typically viewport width/height + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum, can be null or Infinity + * @returns {mat4} out + */ + +function perspectiveNO(out, fovy, aspect, near, far) { + var f = 1.0 / Math.tan(fovy / 2), + nf; + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[15] = 0; + + if (far != null && far !== Infinity) { + nf = 1 / (near - far); + out[10] = (far + near) * nf; + out[14] = 2 * far * near * nf; + } else { + out[10] = -1; + out[14] = -2 * near; + } + + return out; +} +/** + * Alias for {@link mat4.perspectiveNO} + * @function + */ + +var perspective = perspectiveNO; +/** + * Generates a perspective projection matrix suitable for WebGPU with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1], + * which matches WebGPU/Vulkan/DirectX/Metal's clip volume. + * Passing null/undefined/no value for far will generate infinite projection matrix. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} fovy Vertical field of view in radians + * @param {number} aspect Aspect ratio. typically viewport width/height + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum, can be null or Infinity + * @returns {mat4} out + */ + +function perspectiveZO(out, fovy, aspect, near, far) { + var f = 1.0 / Math.tan(fovy / 2), + nf; + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[15] = 0; + + if (far != null && far !== Infinity) { + nf = 1 / (near - far); + out[10] = far * nf; + out[14] = far * near * nf; + } else { + out[10] = -1; + out[14] = -near; + } + + return out; +} +/** + * Generates a perspective projection matrix with the given field of view. + * This is primarily useful for generating projection matrices to be used + * with the still experiemental WebVR API. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + +function perspectiveFromFieldOfView(out, fov, near, far) { + var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0); + var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0); + var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0); + var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0); + var xScale = 2.0 / (leftTan + rightTan); + var yScale = 2.0 / (upTan + downTan); + out[0] = xScale; + out[1] = 0.0; + out[2] = 0.0; + out[3] = 0.0; + out[4] = 0.0; + out[5] = yScale; + out[6] = 0.0; + out[7] = 0.0; + out[8] = -((leftTan - rightTan) * xScale * 0.5); + out[9] = (upTan - downTan) * yScale * 0.5; + out[10] = far / (near - far); + out[11] = -1.0; + out[12] = 0.0; + out[13] = 0.0; + out[14] = far * near / (near - far); + out[15] = 0.0; + return out; +} +/** + * Generates a orthogonal projection matrix with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1], + * which matches WebGL/OpenGL's clip volume. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} left Left bound of the frustum + * @param {number} right Right bound of the frustum + * @param {number} bottom Bottom bound of the frustum + * @param {number} top Top bound of the frustum + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + +function orthoNO(out, left, right, bottom, top, near, far) { + var lr = 1 / (left - right); + var bt = 1 / (bottom - top); + var nf = 1 / (near - far); + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 2 * nf; + out[11] = 0; + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = (far + near) * nf; + out[15] = 1; + return out; +} +/** + * Alias for {@link mat4.orthoNO} + * @function + */ + +var ortho = orthoNO; +/** + * Generates a orthogonal projection matrix with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1], + * which matches WebGPU/Vulkan/DirectX/Metal's clip volume. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} left Left bound of the frustum + * @param {number} right Right bound of the frustum + * @param {number} bottom Bottom bound of the frustum + * @param {number} top Top bound of the frustum + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + +function orthoZO(out, left, right, bottom, top, near, far) { + var lr = 1 / (left - right); + var bt = 1 / (bottom - top); + var nf = 1 / (near - far); + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = nf; + out[11] = 0; + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = near * nf; + out[15] = 1; + return out; +} +/** + * Generates a look-at matrix with the given eye position, focal point, and up axis. + * If you want a matrix that actually makes an object look at another object, you should use targetTo instead. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {ReadonlyVec3} eye Position of the viewer + * @param {ReadonlyVec3} center Point the viewer is looking at + * @param {ReadonlyVec3} up vec3 pointing up + * @returns {mat4} out + */ + +function lookAt(out, eye, center, up) { + var x0, x1, x2, y0, y1, y2, z0, z1, z2, len; + var eyex = eye[0]; + var eyey = eye[1]; + var eyez = eye[2]; + var upx = up[0]; + var upy = up[1]; + var upz = up[2]; + var centerx = center[0]; + var centery = center[1]; + var centerz = center[2]; + + if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) { + return identity$2(out); + } + + z0 = eyex - centerx; + z1 = eyey - centery; + z2 = eyez - centerz; + len = 1 / Math.hypot(z0, z1, z2); + z0 *= len; + z1 *= len; + z2 *= len; + x0 = upy * z2 - upz * z1; + x1 = upz * z0 - upx * z2; + x2 = upx * z1 - upy * z0; + len = Math.hypot(x0, x1, x2); + + if (!len) { + x0 = 0; + x1 = 0; + x2 = 0; + } else { + len = 1 / len; + x0 *= len; + x1 *= len; + x2 *= len; + } + + y0 = z1 * x2 - z2 * x1; + y1 = z2 * x0 - z0 * x2; + y2 = z0 * x1 - z1 * x0; + len = Math.hypot(y0, y1, y2); + + if (!len) { + y0 = 0; + y1 = 0; + y2 = 0; + } else { + len = 1 / len; + y0 *= len; + y1 *= len; + y2 *= len; + } + + out[0] = x0; + out[1] = y0; + out[2] = z0; + out[3] = 0; + out[4] = x1; + out[5] = y1; + out[6] = z1; + out[7] = 0; + out[8] = x2; + out[9] = y2; + out[10] = z2; + out[11] = 0; + out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); + out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); + out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); + out[15] = 1; + return out; +} +/** + * Generates a matrix that makes something look at something else. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {ReadonlyVec3} eye Position of the viewer + * @param {ReadonlyVec3} center Point the viewer is looking at + * @param {ReadonlyVec3} up vec3 pointing up + * @returns {mat4} out + */ + +function targetTo(out, eye, target, up) { + var eyex = eye[0], + eyey = eye[1], + eyez = eye[2], + upx = up[0], + upy = up[1], + upz = up[2]; + var z0 = eyex - target[0], + z1 = eyey - target[1], + z2 = eyez - target[2]; + var len = z0 * z0 + z1 * z1 + z2 * z2; + + if (len > 0) { + len = 1 / Math.sqrt(len); + z0 *= len; + z1 *= len; + z2 *= len; + } + + var x0 = upy * z2 - upz * z1, + x1 = upz * z0 - upx * z2, + x2 = upx * z1 - upy * z0; + len = x0 * x0 + x1 * x1 + x2 * x2; + + if (len > 0) { + len = 1 / Math.sqrt(len); + x0 *= len; + x1 *= len; + x2 *= len; + } + + out[0] = x0; + out[1] = x1; + out[2] = x2; + out[3] = 0; + out[4] = z1 * x2 - z2 * x1; + out[5] = z2 * x0 - z0 * x2; + out[6] = z0 * x1 - z1 * x0; + out[7] = 0; + out[8] = z0; + out[9] = z1; + out[10] = z2; + out[11] = 0; + out[12] = eyex; + out[13] = eyey; + out[14] = eyez; + out[15] = 1; + return out; +} +/** + * Returns a string representation of a mat4 + * + * @param {ReadonlyMat4} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ + +function str$5(a) { + 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] + ")"; +} +/** + * Returns Frobenius norm of a mat4 + * + * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ + +function frob(a) { + 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]); +} +/** + * Adds two mat4's + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the first operand + * @param {ReadonlyMat4} b the second operand + * @returns {mat4} out + */ + +function add$5(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + out[4] = a[4] + b[4]; + out[5] = a[5] + b[5]; + out[6] = a[6] + b[6]; + out[7] = a[7] + b[7]; + out[8] = a[8] + b[8]; + out[9] = a[9] + b[9]; + out[10] = a[10] + b[10]; + out[11] = a[11] + b[11]; + out[12] = a[12] + b[12]; + out[13] = a[13] + b[13]; + out[14] = a[14] + b[14]; + out[15] = a[15] + b[15]; + return out; +} +/** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the first operand + * @param {ReadonlyMat4} b the second operand + * @returns {mat4} out + */ + +function subtract$3(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + out[4] = a[4] - b[4]; + out[5] = a[5] - b[5]; + out[6] = a[6] - b[6]; + out[7] = a[7] - b[7]; + out[8] = a[8] - b[8]; + out[9] = a[9] - b[9]; + out[10] = a[10] - b[10]; + out[11] = a[11] - b[11]; + out[12] = a[12] - b[12]; + out[13] = a[13] - b[13]; + out[14] = a[14] - b[14]; + out[15] = a[15] - b[15]; + return out; +} +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat4} out + */ + +function multiplyScalar(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + out[4] = a[4] * b; + out[5] = a[5] * b; + out[6] = a[6] * b; + out[7] = a[7] * b; + out[8] = a[8] * b; + out[9] = a[9] * b; + out[10] = a[10] * b; + out[11] = a[11] * b; + out[12] = a[12] * b; + out[13] = a[13] * b; + out[14] = a[14] * b; + out[15] = a[15] * b; + return out; +} +/** + * Adds two mat4's after multiplying each element of the second operand by a scalar value. + * + * @param {mat4} out the receiving vector + * @param {ReadonlyMat4} a the first operand + * @param {ReadonlyMat4} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat4} out + */ + +function multiplyScalarAndAdd(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + out[4] = a[4] + b[4] * scale; + out[5] = a[5] + b[5] * scale; + out[6] = a[6] + b[6] * scale; + out[7] = a[7] + b[7] * scale; + out[8] = a[8] + b[8] * scale; + out[9] = a[9] + b[9] * scale; + out[10] = a[10] + b[10] * scale; + out[11] = a[11] + b[11] * scale; + out[12] = a[12] + b[12] * scale; + out[13] = a[13] + b[13] * scale; + out[14] = a[14] + b[14] * scale; + out[15] = a[15] + b[15] * scale; + return out; +} +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyMat4} a The first matrix. + * @param {ReadonlyMat4} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function exactEquals$5(a, b) { + 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]; +} +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {ReadonlyMat4} a The first matrix. + * @param {ReadonlyMat4} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function equals$6(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var a4 = a[4], + a5 = a[5], + a6 = a[6], + a7 = a[7]; + var a8 = a[8], + a9 = a[9], + a10 = a[10], + a11 = a[11]; + var a12 = a[12], + a13 = a[13], + a14 = a[14], + a15 = a[15]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + var b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7]; + var b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11]; + var b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15)); +} +/** + * Alias for {@link mat4.multiply} + * @function + */ + +var mul$5 = multiply$5; +/** + * Alias for {@link mat4.subtract} + * @function + */ + +var sub$3 = subtract$3; + +var mat4 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$5, +adjoint: adjoint, +clone: clone$5, +copy: copy$5, +create: create$5, +determinant: determinant, +equals: equals$6, +exactEquals: exactEquals$5, +frob: frob, +fromQuat: fromQuat, +fromQuat2: fromQuat2, +fromRotation: fromRotation$1, +fromRotationTranslation: fromRotationTranslation$1, +fromRotationTranslationScale: fromRotationTranslationScale, +fromRotationTranslationScaleOrigin: fromRotationTranslationScaleOrigin, +fromScaling: fromScaling, +fromTranslation: fromTranslation$1, +fromValues: fromValues$5, +fromXRotation: fromXRotation, +fromYRotation: fromYRotation, +fromZRotation: fromZRotation, +frustum: frustum, +getRotation: getRotation, +getScaling: getScaling, +getTranslation: getTranslation$1, +identity: identity$2, +invert: invert$2, +lookAt: lookAt, +mul: mul$5, +multiply: multiply$5, +multiplyScalar: multiplyScalar, +multiplyScalarAndAdd: multiplyScalarAndAdd, +ortho: ortho, +orthoNO: orthoNO, +orthoZO: orthoZO, +perspective: perspective, +perspectiveFromFieldOfView: perspectiveFromFieldOfView, +perspectiveNO: perspectiveNO, +perspectiveZO: perspectiveZO, +rotate: rotate$1, +rotateX: rotateX$3, +rotateY: rotateY$3, +rotateZ: rotateZ$3, +scale: scale$5, +set: set$5, +str: str$5, +sub: sub$3, +subtract: subtract$3, +targetTo: targetTo, +translate: translate$1, +transpose: transpose +}); + +/** + * 3 Dimensional Vector + * @module vec3 + */ + +/** + * Creates a new, empty vec3 + * + * @returns {vec3} a new 3D vector + */ + +function create$4() { + var out = new ARRAY_TYPE(3); + + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + } + + return out; +} +/** + * Creates a new vec3 initialized with values from an existing vector + * + * @param {ReadonlyVec3} a vector to clone + * @returns {vec3} a new 3D vector + */ + +function clone$4(a) { + var out = new ARRAY_TYPE(3); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + return out; +} +/** + * Calculates the length of a vec3 + * + * @param {ReadonlyVec3} a vector to calculate length of + * @returns {Number} length of a + */ + +function length$4(a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + return Math.hypot(x, y, z); +} +/** + * Creates a new vec3 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @returns {vec3} a new 3D vector + */ + +function fromValues$4(x, y, z) { + var out = new ARRAY_TYPE(3); + out[0] = x; + out[1] = y; + out[2] = z; + return out; +} +/** + * Copy the values from one vec3 to another + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the source vector + * @returns {vec3} out + */ + +function copy$4(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + return out; +} +/** + * Set the components of a vec3 to the given values + * + * @param {vec3} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @returns {vec3} out + */ + +function set$4(out, x, y, z) { + out[0] = x; + out[1] = y; + out[2] = z; + return out; +} +/** + * Adds two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function add$4(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + return out; +} +/** + * Subtracts vector b from vector a + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function subtract$2(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + return out; +} +/** + * Multiplies two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function multiply$4(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + out[2] = a[2] * b[2]; + return out; +} +/** + * Divides two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function divide$2(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + out[2] = a[2] / b[2]; + return out; +} +/** + * Math.ceil the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to ceil + * @returns {vec3} out + */ + +function ceil$2(out, a) { + out[0] = Math.ceil(a[0]); + out[1] = Math.ceil(a[1]); + out[2] = Math.ceil(a[2]); + return out; +} +/** + * Math.floor the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to floor + * @returns {vec3} out + */ + +function floor$2(out, a) { + out[0] = Math.floor(a[0]); + out[1] = Math.floor(a[1]); + out[2] = Math.floor(a[2]); + return out; +} +/** + * Returns the minimum of two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function min$2(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + out[2] = Math.min(a[2], b[2]); + return out; +} +/** + * Returns the maximum of two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function max$2(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + out[2] = Math.max(a[2], b[2]); + return out; +} +/** + * Math.round the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to round + * @returns {vec3} out + */ + +function round$2(out, a) { + out[0] = Math.round(a[0]); + out[1] = Math.round(a[1]); + out[2] = Math.round(a[2]); + return out; +} +/** + * Scales a vec3 by a scalar number + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec3} out + */ + +function scale$4(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + return out; +} +/** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec3} out + */ + +function scaleAndAdd$2(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + return out; +} +/** + * Calculates the euclidian distance between two vec3's + * + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {Number} distance between a and b + */ + +function distance$2(a, b) { + var x = b[0] - a[0]; + var y = b[1] - a[1]; + var z = b[2] - a[2]; + return Math.hypot(x, y, z); +} +/** + * Calculates the squared euclidian distance between two vec3's + * + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {Number} squared distance between a and b + */ + +function squaredDistance$2(a, b) { + var x = b[0] - a[0]; + var y = b[1] - a[1]; + var z = b[2] - a[2]; + return x * x + y * y + z * z; +} +/** + * Calculates the squared length of a vec3 + * + * @param {ReadonlyVec3} a vector to calculate squared length of + * @returns {Number} squared length of a + */ + +function squaredLength$4(a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + return x * x + y * y + z * z; +} +/** + * Negates the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to negate + * @returns {vec3} out + */ + +function negate$2(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + return out; +} +/** + * Returns the inverse of the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to invert + * @returns {vec3} out + */ + +function inverse$2(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + out[2] = 1.0 / a[2]; + return out; +} +/** + * Normalize a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to normalize + * @returns {vec3} out + */ + +function normalize$4(out, a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + var len = x * x + y * y + z * z; + + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + } + + out[0] = a[0] * len; + out[1] = a[1] * len; + out[2] = a[2] * len; + return out; +} +/** + * Calculates the dot product of two vec3's + * + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {Number} dot product of a and b + */ + +function dot$5(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +} +/** + * Computes the cross product of two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function cross$2(out, a, b) { + var ax = a[0], + ay = a[1], + az = a[2]; + var bx = b[0], + by = b[1], + bz = b[2]; + out[0] = ay * bz - az * by; + out[1] = az * bx - ax * bz; + out[2] = ax * by - ay * bx; + return out; +} +/** + * Performs a linear interpolation between two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec3} out + */ + +function lerp$4(out, a, b, t) { + var ax = a[0]; + var ay = a[1]; + var az = a[2]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + out[2] = az + t * (b[2] - az); + return out; +} +/** + * Performs a hermite interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @param {ReadonlyVec3} c the third operand + * @param {ReadonlyVec3} d the fourth operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec3} out + */ + +function hermite(out, a, b, c, d, t) { + var factorTimes2 = t * t; + var factor1 = factorTimes2 * (2 * t - 3) + 1; + var factor2 = factorTimes2 * (t - 2) + t; + var factor3 = factorTimes2 * (t - 1); + var factor4 = factorTimes2 * (3 - 2 * t); + out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4; + out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4; + out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4; + return out; +} +/** + * Performs a bezier interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @param {ReadonlyVec3} c the third operand + * @param {ReadonlyVec3} d the fourth operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec3} out + */ + +function bezier(out, a, b, c, d, t) { + var inverseFactor = 1 - t; + var inverseFactorTimesTwo = inverseFactor * inverseFactor; + var factorTimes2 = t * t; + var factor1 = inverseFactorTimesTwo * inverseFactor; + var factor2 = 3 * t * inverseFactorTimesTwo; + var factor3 = 3 * factorTimes2 * inverseFactor; + var factor4 = factorTimes2 * t; + out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4; + out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4; + out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4; + return out; +} +/** + * Generates a random vector with the given scale + * + * @param {vec3} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec3} out + */ + +function random$3(out, scale) { + scale = scale || 1.0; + var r = RANDOM() * 2.0 * Math.PI; + var z = RANDOM() * 2.0 - 1.0; + var zScale = Math.sqrt(1.0 - z * z) * scale; + out[0] = Math.cos(r) * zScale; + out[1] = Math.sin(r) * zScale; + out[2] = z * scale; + return out; +} +/** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to transform + * @param {ReadonlyMat4} m matrix to transform with + * @returns {vec3} out + */ + +function transformMat4$2(out, a, m) { + var x = a[0], + y = a[1], + z = a[2]; + var w = m[3] * x + m[7] * y + m[11] * z + m[15]; + w = w || 1.0; + out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w; + out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w; + out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w; + return out; +} +/** + * Transforms the vec3 with a mat3. + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to transform + * @param {ReadonlyMat3} m the 3x3 matrix to transform with + * @returns {vec3} out + */ + +function transformMat3$1(out, a, m) { + var x = a[0], + y = a[1], + z = a[2]; + out[0] = x * m[0] + y * m[3] + z * m[6]; + out[1] = x * m[1] + y * m[4] + z * m[7]; + out[2] = x * m[2] + y * m[5] + z * m[8]; + return out; +} +/** + * Transforms the vec3 with a quat + * Can also be used for dual quaternions. (Multiply it with the real part) + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to transform + * @param {ReadonlyQuat} q quaternion to transform with + * @returns {vec3} out + */ + +function transformQuat$1(out, a, q) { + // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed + var qx = q[0], + qy = q[1], + qz = q[2], + qw = q[3]; + var x = a[0], + y = a[1], + z = a[2]; // var qvec = [qx, qy, qz]; + // var uv = vec3.cross([], qvec, a); + + var uvx = qy * z - qz * y, + uvy = qz * x - qx * z, + uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv); + + var uuvx = qy * uvz - qz * uvy, + uuvy = qz * uvx - qx * uvz, + uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w); + + var w2 = qw * 2; + uvx *= w2; + uvy *= w2; + uvz *= w2; // vec3.scale(uuv, uuv, 2); + + uuvx *= 2; + uuvy *= 2; + uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv)); + + out[0] = x + uvx + uuvx; + out[1] = y + uvy + uuvy; + out[2] = z + uvz + uuvz; + return out; +} +/** + * Rotate a 3D vector around the x-axis + * @param {vec3} out The receiving vec3 + * @param {ReadonlyVec3} a The vec3 point to rotate + * @param {ReadonlyVec3} b The origin of the rotation + * @param {Number} rad The angle of rotation in radians + * @returns {vec3} out + */ + +function rotateX$2(out, a, b, rad) { + var p = [], + r = []; //Translate point to the origin + + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; //perform rotation + + r[0] = p[0]; + r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad); + r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position + + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + return out; +} +/** + * Rotate a 3D vector around the y-axis + * @param {vec3} out The receiving vec3 + * @param {ReadonlyVec3} a The vec3 point to rotate + * @param {ReadonlyVec3} b The origin of the rotation + * @param {Number} rad The angle of rotation in radians + * @returns {vec3} out + */ + +function rotateY$2(out, a, b, rad) { + var p = [], + r = []; //Translate point to the origin + + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; //perform rotation + + r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad); + r[1] = p[1]; + r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position + + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + return out; +} +/** + * Rotate a 3D vector around the z-axis + * @param {vec3} out The receiving vec3 + * @param {ReadonlyVec3} a The vec3 point to rotate + * @param {ReadonlyVec3} b The origin of the rotation + * @param {Number} rad The angle of rotation in radians + * @returns {vec3} out + */ + +function rotateZ$2(out, a, b, rad) { + var p = [], + r = []; //Translate point to the origin + + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; //perform rotation + + r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad); + r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad); + r[2] = p[2]; //translate to correct position + + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + return out; +} +/** + * Get the angle between two 3D vectors + * @param {ReadonlyVec3} a The first operand + * @param {ReadonlyVec3} b The second operand + * @returns {Number} The angle in radians + */ + +function angle$1(a, b) { + var ax = a[0], + ay = a[1], + az = a[2], + bx = b[0], + by = b[1], + bz = b[2], + mag1 = Math.sqrt(ax * ax + ay * ay + az * az), + mag2 = Math.sqrt(bx * bx + by * by + bz * bz), + mag = mag1 * mag2, + cosine = mag && dot$5(a, b) / mag; + return Math.acos(Math.min(Math.max(cosine, -1), 1)); +} +/** + * Set the components of a vec3 to zero + * + * @param {vec3} out the receiving vector + * @returns {vec3} out + */ + +function zero$2(out) { + out[0] = 0.0; + out[1] = 0.0; + out[2] = 0.0; + return out; +} +/** + * Returns a string representation of a vector + * + * @param {ReadonlyVec3} a vector to represent as a string + * @returns {String} string representation of the vector + */ + +function str$4(a) { + return "vec3(" + a[0] + ", " + a[1] + ", " + a[2] + ")"; +} +/** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyVec3} a The first vector. + * @param {ReadonlyVec3} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function exactEquals$4(a, b) { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; +} +/** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {ReadonlyVec3} a The first vector. + * @param {ReadonlyVec3} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function equals$5(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2]; + var b0 = b[0], + b1 = b[1], + b2 = b[2]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)); +} +/** + * Alias for {@link vec3.subtract} + * @function + */ + +var sub$2 = subtract$2; +/** + * Alias for {@link vec3.multiply} + * @function + */ + +var mul$4 = multiply$4; +/** + * Alias for {@link vec3.divide} + * @function + */ + +var div$2 = divide$2; +/** + * Alias for {@link vec3.distance} + * @function + */ + +var dist$2 = distance$2; +/** + * Alias for {@link vec3.squaredDistance} + * @function + */ + +var sqrDist$2 = squaredDistance$2; +/** + * Alias for {@link vec3.length} + * @function + */ + +var len$4 = length$4; +/** + * Alias for {@link vec3.squaredLength} + * @function + */ + +var sqrLen$4 = squaredLength$4; +/** + * Perform some operation over an array of vec3s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ + +var forEach$2 = function () { + var vec = create$4(); + return function (a, stride, offset, count, fn, arg) { + var i, l; + + if (!stride) { + stride = 3; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min(count * stride + offset, a.length); + } else { + l = a.length; + } + + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + vec[2] = a[i + 2]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + a[i + 2] = vec[2]; + } + + return a; + }; +}(); + +var vec3 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$4, +angle: angle$1, +bezier: bezier, +ceil: ceil$2, +clone: clone$4, +copy: copy$4, +create: create$4, +cross: cross$2, +dist: dist$2, +distance: distance$2, +div: div$2, +divide: divide$2, +dot: dot$5, +equals: equals$5, +exactEquals: exactEquals$4, +floor: floor$2, +forEach: forEach$2, +fromValues: fromValues$4, +hermite: hermite, +inverse: inverse$2, +len: len$4, +length: length$4, +lerp: lerp$4, +max: max$2, +min: min$2, +mul: mul$4, +multiply: multiply$4, +negate: negate$2, +normalize: normalize$4, +random: random$3, +rotateX: rotateX$2, +rotateY: rotateY$2, +rotateZ: rotateZ$2, +round: round$2, +scale: scale$4, +scaleAndAdd: scaleAndAdd$2, +set: set$4, +sqrDist: sqrDist$2, +sqrLen: sqrLen$4, +squaredDistance: squaredDistance$2, +squaredLength: squaredLength$4, +str: str$4, +sub: sub$2, +subtract: subtract$2, +transformMat3: transformMat3$1, +transformMat4: transformMat4$2, +transformQuat: transformQuat$1, +zero: zero$2 +}); + +/** + * 4 Dimensional Vector + * @module vec4 + */ + +/** + * Creates a new, empty vec4 + * + * @returns {vec4} a new 4D vector + */ + +function create$3() { + var out = new ARRAY_TYPE(4); + + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 0; + } + + return out; +} +/** + * Creates a new vec4 initialized with values from an existing vector + * + * @param {ReadonlyVec4} a vector to clone + * @returns {vec4} a new 4D vector + */ + +function clone$3(a) { + var out = new ARRAY_TYPE(4); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +} +/** + * Creates a new vec4 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {vec4} a new 4D vector + */ + +function fromValues$3(x, y, z, w) { + var out = new ARRAY_TYPE(4); + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = w; + return out; +} +/** + * Copy the values from one vec4 to another + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the source vector + * @returns {vec4} out + */ + +function copy$3(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +} +/** + * Set the components of a vec4 to the given values + * + * @param {vec4} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {vec4} out + */ + +function set$3(out, x, y, z, w) { + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = w; + return out; +} +/** + * Adds two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function add$3(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + return out; +} +/** + * Subtracts vector b from vector a + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function subtract$1(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + return out; +} +/** + * Multiplies two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function multiply$3(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + out[2] = a[2] * b[2]; + out[3] = a[3] * b[3]; + return out; +} +/** + * Divides two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function divide$1(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + out[2] = a[2] / b[2]; + out[3] = a[3] / b[3]; + return out; +} +/** + * Math.ceil the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to ceil + * @returns {vec4} out + */ + +function ceil$1(out, a) { + out[0] = Math.ceil(a[0]); + out[1] = Math.ceil(a[1]); + out[2] = Math.ceil(a[2]); + out[3] = Math.ceil(a[3]); + return out; +} +/** + * Math.floor the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to floor + * @returns {vec4} out + */ + +function floor$1(out, a) { + out[0] = Math.floor(a[0]); + out[1] = Math.floor(a[1]); + out[2] = Math.floor(a[2]); + out[3] = Math.floor(a[3]); + return out; +} +/** + * Returns the minimum of two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function min$1(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + out[2] = Math.min(a[2], b[2]); + out[3] = Math.min(a[3], b[3]); + return out; +} +/** + * Returns the maximum of two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function max$1(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + out[2] = Math.max(a[2], b[2]); + out[3] = Math.max(a[3], b[3]); + return out; +} +/** + * Math.round the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to round + * @returns {vec4} out + */ + +function round$1(out, a) { + out[0] = Math.round(a[0]); + out[1] = Math.round(a[1]); + out[2] = Math.round(a[2]); + out[3] = Math.round(a[3]); + return out; +} +/** + * Scales a vec4 by a scalar number + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec4} out + */ + +function scale$3(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + return out; +} +/** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec4} out + */ + +function scaleAndAdd$1(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + return out; +} +/** + * Calculates the euclidian distance between two vec4's + * + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {Number} distance between a and b + */ + +function distance$1(a, b) { + var x = b[0] - a[0]; + var y = b[1] - a[1]; + var z = b[2] - a[2]; + var w = b[3] - a[3]; + return Math.hypot(x, y, z, w); +} +/** + * Calculates the squared euclidian distance between two vec4's + * + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {Number} squared distance between a and b + */ + +function squaredDistance$1(a, b) { + var x = b[0] - a[0]; + var y = b[1] - a[1]; + var z = b[2] - a[2]; + var w = b[3] - a[3]; + return x * x + y * y + z * z + w * w; +} +/** + * Calculates the length of a vec4 + * + * @param {ReadonlyVec4} a vector to calculate length of + * @returns {Number} length of a + */ + +function length$3(a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + var w = a[3]; + return Math.hypot(x, y, z, w); +} +/** + * Calculates the squared length of a vec4 + * + * @param {ReadonlyVec4} a vector to calculate squared length of + * @returns {Number} squared length of a + */ + +function squaredLength$3(a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + var w = a[3]; + return x * x + y * y + z * z + w * w; +} +/** + * Negates the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to negate + * @returns {vec4} out + */ + +function negate$1(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = -a[3]; + return out; +} +/** + * Returns the inverse of the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to invert + * @returns {vec4} out + */ + +function inverse$1(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + out[2] = 1.0 / a[2]; + out[3] = 1.0 / a[3]; + return out; +} +/** + * Normalize a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to normalize + * @returns {vec4} out + */ + +function normalize$3(out, a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + var w = a[3]; + var len = x * x + y * y + z * z + w * w; + + if (len > 0) { + len = 1 / Math.sqrt(len); + } + + out[0] = x * len; + out[1] = y * len; + out[2] = z * len; + out[3] = w * len; + return out; +} +/** + * Calculates the dot product of two vec4's + * + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {Number} dot product of a and b + */ + +function dot$4(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; +} +/** + * Returns the cross-product of three vectors in a 4-dimensional space + * + * @param {ReadonlyVec4} result the receiving vector + * @param {ReadonlyVec4} U the first vector + * @param {ReadonlyVec4} V the second vector + * @param {ReadonlyVec4} W the third vector + * @returns {vec4} result + */ + +function cross$1(out, u, v, w) { + var A = v[0] * w[1] - v[1] * w[0], + B = v[0] * w[2] - v[2] * w[0], + C = v[0] * w[3] - v[3] * w[0], + D = v[1] * w[2] - v[2] * w[1], + E = v[1] * w[3] - v[3] * w[1], + F = v[2] * w[3] - v[3] * w[2]; + var G = u[0]; + var H = u[1]; + var I = u[2]; + var J = u[3]; + out[0] = H * F - I * E + J * D; + out[1] = -(G * F) + I * C - J * B; + out[2] = G * E - H * C + J * A; + out[3] = -(G * D) + H * B - I * A; + return out; +} +/** + * Performs a linear interpolation between two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec4} out + */ + +function lerp$3(out, a, b, t) { + var ax = a[0]; + var ay = a[1]; + var az = a[2]; + var aw = a[3]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + out[2] = az + t * (b[2] - az); + out[3] = aw + t * (b[3] - aw); + return out; +} +/** + * Generates a random vector with the given scale + * + * @param {vec4} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec4} out + */ + +function random$2(out, scale) { + scale = scale || 1.0; // Marsaglia, George. Choosing a Point from the Surface of a + // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646. + // http://projecteuclid.org/euclid.aoms/1177692644; + + var v1, v2, v3, v4; + var s1, s2; + + do { + v1 = RANDOM() * 2 - 1; + v2 = RANDOM() * 2 - 1; + s1 = v1 * v1 + v2 * v2; + } while (s1 >= 1); + + do { + v3 = RANDOM() * 2 - 1; + v4 = RANDOM() * 2 - 1; + s2 = v3 * v3 + v4 * v4; + } while (s2 >= 1); + + var d = Math.sqrt((1 - s1) / s2); + out[0] = scale * v1; + out[1] = scale * v2; + out[2] = scale * v3 * d; + out[3] = scale * v4 * d; + return out; +} +/** + * Transforms the vec4 with a mat4. + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the vector to transform + * @param {ReadonlyMat4} m matrix to transform with + * @returns {vec4} out + */ + +function transformMat4$1(out, a, m) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w; + out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w; + out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w; + out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w; + return out; +} +/** + * Transforms the vec4 with a quat + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the vector to transform + * @param {ReadonlyQuat} q quaternion to transform with + * @returns {vec4} out + */ + +function transformQuat(out, a, q) { + var x = a[0], + y = a[1], + z = a[2]; + var qx = q[0], + qy = q[1], + qz = q[2], + qw = q[3]; // calculate quat * vec + + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; + var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat + + out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy; + out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz; + out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx; + out[3] = a[3]; + return out; +} +/** + * Set the components of a vec4 to zero + * + * @param {vec4} out the receiving vector + * @returns {vec4} out + */ + +function zero$1(out) { + out[0] = 0.0; + out[1] = 0.0; + out[2] = 0.0; + out[3] = 0.0; + return out; +} +/** + * Returns a string representation of a vector + * + * @param {ReadonlyVec4} a vector to represent as a string + * @returns {String} string representation of the vector + */ + +function str$3(a) { + return "vec4(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ")"; +} +/** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyVec4} a The first vector. + * @param {ReadonlyVec4} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function exactEquals$3(a, b) { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3]; +} +/** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {ReadonlyVec4} a The first vector. + * @param {ReadonlyVec4} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function equals$4(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)); +} +/** + * Alias for {@link vec4.subtract} + * @function + */ + +var sub$1 = subtract$1; +/** + * Alias for {@link vec4.multiply} + * @function + */ + +var mul$3 = multiply$3; +/** + * Alias for {@link vec4.divide} + * @function + */ + +var div$1 = divide$1; +/** + * Alias for {@link vec4.distance} + * @function + */ + +var dist$1 = distance$1; +/** + * Alias for {@link vec4.squaredDistance} + * @function + */ + +var sqrDist$1 = squaredDistance$1; +/** + * Alias for {@link vec4.length} + * @function + */ + +var len$3 = length$3; +/** + * Alias for {@link vec4.squaredLength} + * @function + */ + +var sqrLen$3 = squaredLength$3; +/** + * Perform some operation over an array of vec4s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ + +var forEach$1 = function () { + var vec = create$3(); + return function (a, stride, offset, count, fn, arg) { + var i, l; + + if (!stride) { + stride = 4; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min(count * stride + offset, a.length); + } else { + l = a.length; + } + + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + vec[2] = a[i + 2]; + vec[3] = a[i + 3]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + a[i + 2] = vec[2]; + a[i + 3] = vec[3]; + } + + return a; + }; +}(); + +var vec4 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$3, +ceil: ceil$1, +clone: clone$3, +copy: copy$3, +create: create$3, +cross: cross$1, +dist: dist$1, +distance: distance$1, +div: div$1, +divide: divide$1, +dot: dot$4, +equals: equals$4, +exactEquals: exactEquals$3, +floor: floor$1, +forEach: forEach$1, +fromValues: fromValues$3, +inverse: inverse$1, +len: len$3, +length: length$3, +lerp: lerp$3, +max: max$1, +min: min$1, +mul: mul$3, +multiply: multiply$3, +negate: negate$1, +normalize: normalize$3, +random: random$2, +round: round$1, +scale: scale$3, +scaleAndAdd: scaleAndAdd$1, +set: set$3, +sqrDist: sqrDist$1, +sqrLen: sqrLen$3, +squaredDistance: squaredDistance$1, +squaredLength: squaredLength$3, +str: str$3, +sub: sub$1, +subtract: subtract$1, +transformMat4: transformMat4$1, +transformQuat: transformQuat, +zero: zero$1 +}); + +/** + * Quaternion + * @module quat + */ + +/** + * Creates a new identity quat + * + * @returns {quat} a new quaternion + */ + +function create$2() { + var out = new ARRAY_TYPE(4); + + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + } + + out[3] = 1; + return out; +} +/** + * Set a quat to the identity quaternion + * + * @param {quat} out the receiving quaternion + * @returns {quat} out + */ + +function identity$1(out) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +} +/** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyVec3} axis the axis around which to rotate + * @param {Number} rad the angle in radians + * @returns {quat} out + **/ + +function setAxisAngle(out, axis, rad) { + rad = rad * 0.5; + var s = Math.sin(rad); + out[0] = s * axis[0]; + out[1] = s * axis[1]; + out[2] = s * axis[2]; + out[3] = Math.cos(rad); + return out; +} +/** + * Gets the rotation axis and angle for a given + * quaternion. If a quaternion is created with + * setAxisAngle, this method will return the same + * values as providied in the original parameter list + * OR functionally equivalent values. + * Example: The quaternion formed by axis [0, 0, 1] and + * angle -90 is the same as the quaternion formed by + * [0, 0, 1] and 270. This method favors the latter. + * @param {vec3} out_axis Vector receiving the axis of rotation + * @param {ReadonlyQuat} q Quaternion to be decomposed + * @return {Number} Angle, in radians, of the rotation + */ + +function getAxisAngle(out_axis, q) { + var rad = Math.acos(q[3]) * 2.0; + var s = Math.sin(rad / 2.0); + + if (s > EPSILON) { + out_axis[0] = q[0] / s; + out_axis[1] = q[1] / s; + out_axis[2] = q[2] / s; + } else { + // If s is zero, return any axis (no rotation - axis does not matter) + out_axis[0] = 1; + out_axis[1] = 0; + out_axis[2] = 0; + } + + return rad; +} +/** + * Gets the angular distance between two unit quaternions + * + * @param {ReadonlyQuat} a Origin unit quaternion + * @param {ReadonlyQuat} b Destination unit quaternion + * @return {Number} Angle, in radians, between the two quaternions + */ + +function getAngle(a, b) { + var dotproduct = dot$3(a, b); + return Math.acos(2 * dotproduct * dotproduct - 1); +} +/** + * Multiplies two quat's + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @returns {quat} out + */ + +function multiply$2(out, a, b) { + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var bx = b[0], + by = b[1], + bz = b[2], + bw = b[3]; + out[0] = ax * bw + aw * bx + ay * bz - az * by; + out[1] = ay * bw + aw * by + az * bx - ax * bz; + out[2] = az * bw + aw * bz + ax * by - ay * bx; + out[3] = aw * bw - ax * bx - ay * by - az * bz; + return out; +} +/** + * Rotates a quaternion by the given angle about the X axis + * + * @param {quat} out quat receiving operation result + * @param {ReadonlyQuat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ + +function rotateX$1(out, a, rad) { + rad *= 0.5; + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var bx = Math.sin(rad), + bw = Math.cos(rad); + out[0] = ax * bw + aw * bx; + out[1] = ay * bw + az * bx; + out[2] = az * bw - ay * bx; + out[3] = aw * bw - ax * bx; + return out; +} +/** + * Rotates a quaternion by the given angle about the Y axis + * + * @param {quat} out quat receiving operation result + * @param {ReadonlyQuat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ + +function rotateY$1(out, a, rad) { + rad *= 0.5; + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var by = Math.sin(rad), + bw = Math.cos(rad); + out[0] = ax * bw - az * by; + out[1] = ay * bw + aw * by; + out[2] = az * bw + ax * by; + out[3] = aw * bw - ay * by; + return out; +} +/** + * Rotates a quaternion by the given angle about the Z axis + * + * @param {quat} out quat receiving operation result + * @param {ReadonlyQuat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ + +function rotateZ$1(out, a, rad) { + rad *= 0.5; + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var bz = Math.sin(rad), + bw = Math.cos(rad); + out[0] = ax * bw + ay * bz; + out[1] = ay * bw - ax * bz; + out[2] = az * bw + aw * bz; + out[3] = aw * bw - az * bz; + return out; +} +/** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate W component of + * @returns {quat} out + */ + +function calculateW(out, a) { + var x = a[0], + y = a[1], + z = a[2]; + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z)); + return out; +} +/** + * Calculate the exponential of a unit quaternion. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate the exponential of + * @returns {quat} out + */ + +function exp(out, a) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + var r = Math.sqrt(x * x + y * y + z * z); + var et = Math.exp(w); + var s = r > 0 ? et * Math.sin(r) / r : 0; + out[0] = x * s; + out[1] = y * s; + out[2] = z * s; + out[3] = et * Math.cos(r); + return out; +} +/** + * Calculate the natural logarithm of a unit quaternion. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate the exponential of + * @returns {quat} out + */ + +function ln(out, a) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + var r = Math.sqrt(x * x + y * y + z * z); + var t = r > 0 ? Math.atan2(r, w) / r : 0; + out[0] = x * t; + out[1] = y * t; + out[2] = z * t; + out[3] = 0.5 * Math.log(x * x + y * y + z * z + w * w); + return out; +} +/** + * Calculate the scalar power of a unit quaternion. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate the exponential of + * @param {Number} b amount to scale the quaternion by + * @returns {quat} out + */ + +function pow(out, a, b) { + ln(out, a); + scale$2(out, out, b); + exp(out, out); + return out; +} +/** + * Performs a spherical linear interpolation between two quat + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {quat} out + */ + +function slerp(out, a, b, t) { + // benchmarks: + // http://jsperf.com/quaternion-slerp-implementations + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var bx = b[0], + by = b[1], + bz = b[2], + bw = b[3]; + var omega, cosom, sinom, scale0, scale1; // calc cosine + + cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary) + + if (cosom < 0.0) { + cosom = -cosom; + bx = -bx; + by = -by; + bz = -bz; + bw = -bw; + } // calculate coefficients + + + if (1.0 - cosom > EPSILON) { + // standard case (slerp) + omega = Math.acos(cosom); + sinom = Math.sin(omega); + scale0 = Math.sin((1.0 - t) * omega) / sinom; + scale1 = Math.sin(t * omega) / sinom; + } else { + // "from" and "to" quaternions are very close + // ... so we can do a linear interpolation + scale0 = 1.0 - t; + scale1 = t; + } // calculate final values + + + out[0] = scale0 * ax + scale1 * bx; + out[1] = scale0 * ay + scale1 * by; + out[2] = scale0 * az + scale1 * bz; + out[3] = scale0 * aw + scale1 * bw; + return out; +} +/** + * Generates a random unit quaternion + * + * @param {quat} out the receiving quaternion + * @returns {quat} out + */ + +function random$1(out) { + // Implementation of http://planning.cs.uiuc.edu/node198.html + // TODO: Calling random 3 times is probably not the fastest solution + var u1 = RANDOM(); + var u2 = RANDOM(); + var u3 = RANDOM(); + var sqrt1MinusU1 = Math.sqrt(1 - u1); + var sqrtU1 = Math.sqrt(u1); + out[0] = sqrt1MinusU1 * Math.sin(2.0 * Math.PI * u2); + out[1] = sqrt1MinusU1 * Math.cos(2.0 * Math.PI * u2); + out[2] = sqrtU1 * Math.sin(2.0 * Math.PI * u3); + out[3] = sqrtU1 * Math.cos(2.0 * Math.PI * u3); + return out; +} +/** + * Calculates the inverse of a quat + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate inverse of + * @returns {quat} out + */ + +function invert$1(out, a) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; + var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 + + out[0] = -a0 * invDot; + out[1] = -a1 * invDot; + out[2] = -a2 * invDot; + out[3] = a3 * invDot; + return out; +} +/** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate conjugate of + * @returns {quat} out + */ + +function conjugate$1(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = a[3]; + return out; +} +/** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyMat3} m rotation matrix + * @returns {quat} out + * @function + */ + +function fromMat3(out, m) { + // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes + // article "Quaternion Calculus and Fast Animation". + var fTrace = m[0] + m[4] + m[8]; + var fRoot; + + if (fTrace > 0.0) { + // |w| > 1/2, may as well choose w > 1/2 + fRoot = Math.sqrt(fTrace + 1.0); // 2w + + out[3] = 0.5 * fRoot; + fRoot = 0.5 / fRoot; // 1/(4w) + + out[0] = (m[5] - m[7]) * fRoot; + out[1] = (m[6] - m[2]) * fRoot; + out[2] = (m[1] - m[3]) * fRoot; + } else { + // |w| <= 1/2 + var i = 0; + if (m[4] > m[0]) i = 1; + if (m[8] > m[i * 3 + i]) i = 2; + var j = (i + 1) % 3; + var k = (i + 2) % 3; + fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0); + out[i] = 0.5 * fRoot; + fRoot = 0.5 / fRoot; + out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot; + out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot; + out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot; + } + + return out; +} +/** + * Creates a quaternion from the given euler angle x, y, z. + * + * @param {quat} out the receiving quaternion + * @param {x} Angle to rotate around X axis in degrees. + * @param {y} Angle to rotate around Y axis in degrees. + * @param {z} Angle to rotate around Z axis in degrees. + * @returns {quat} out + * @function + */ + +function fromEuler(out, x, y, z) { + var halfToRad = 0.5 * Math.PI / 180.0; + x *= halfToRad; + y *= halfToRad; + z *= halfToRad; + var sx = Math.sin(x); + var cx = Math.cos(x); + var sy = Math.sin(y); + var cy = Math.cos(y); + var sz = Math.sin(z); + var cz = Math.cos(z); + out[0] = sx * cy * cz - cx * sy * sz; + out[1] = cx * sy * cz + sx * cy * sz; + out[2] = cx * cy * sz - sx * sy * cz; + out[3] = cx * cy * cz + sx * sy * sz; + return out; +} +/** + * Returns a string representation of a quatenion + * + * @param {ReadonlyQuat} a vector to represent as a string + * @returns {String} string representation of the vector + */ + +function str$2(a) { + return "quat(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ")"; +} +/** + * Creates a new quat initialized with values from an existing quaternion + * + * @param {ReadonlyQuat} a quaternion to clone + * @returns {quat} a new quaternion + * @function + */ + +var clone$2 = clone$3; +/** + * Creates a new quat initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {quat} a new quaternion + * @function + */ + +var fromValues$2 = fromValues$3; +/** + * Copy the values from one quat to another + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the source quaternion + * @returns {quat} out + * @function + */ + +var copy$2 = copy$3; +/** + * Set the components of a quat to the given values + * + * @param {quat} out the receiving quaternion + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {quat} out + * @function + */ + +var set$2 = set$3; +/** + * Adds two quat's + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @returns {quat} out + * @function + */ + +var add$2 = add$3; +/** + * Alias for {@link quat.multiply} + * @function + */ + +var mul$2 = multiply$2; +/** + * Scales a quat by a scalar number + * + * @param {quat} out the receiving vector + * @param {ReadonlyQuat} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {quat} out + * @function + */ + +var scale$2 = scale$3; +/** + * Calculates the dot product of two quat's + * + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @returns {Number} dot product of a and b + * @function + */ + +var dot$3 = dot$4; +/** + * Performs a linear interpolation between two quat's + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {quat} out + * @function + */ + +var lerp$2 = lerp$3; +/** + * Calculates the length of a quat + * + * @param {ReadonlyQuat} a vector to calculate length of + * @returns {Number} length of a + */ + +var length$2 = length$3; +/** + * Alias for {@link quat.length} + * @function + */ + +var len$2 = length$2; +/** + * Calculates the squared length of a quat + * + * @param {ReadonlyQuat} a vector to calculate squared length of + * @returns {Number} squared length of a + * @function + */ + +var squaredLength$2 = squaredLength$3; +/** + * Alias for {@link quat.squaredLength} + * @function + */ + +var sqrLen$2 = squaredLength$2; +/** + * Normalize a quat + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quaternion to normalize + * @returns {quat} out + * @function + */ + +var normalize$2 = normalize$3; +/** + * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyQuat} a The first quaternion. + * @param {ReadonlyQuat} b The second quaternion. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +var exactEquals$2 = exactEquals$3; +/** + * Returns whether or not the quaternions have approximately the same elements in the same position. + * + * @param {ReadonlyQuat} a The first vector. + * @param {ReadonlyQuat} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +var equals$3 = equals$4; +/** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {ReadonlyVec3} a the initial vector + * @param {ReadonlyVec3} b the destination vector + * @returns {quat} out + */ + +var rotationTo = function () { + var tmpvec3 = create$4(); + var xUnitVec3 = fromValues$4(1, 0, 0); + var yUnitVec3 = fromValues$4(0, 1, 0); + return function (out, a, b) { + var dot = dot$5(a, b); + + if (dot < -0.999999) { + cross$2(tmpvec3, xUnitVec3, a); + if (len$4(tmpvec3) < 0.000001) cross$2(tmpvec3, yUnitVec3, a); + normalize$4(tmpvec3, tmpvec3); + setAxisAngle(out, tmpvec3, Math.PI); + return out; + } else if (dot > 0.999999) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; + } else { + cross$2(tmpvec3, a, b); + out[0] = tmpvec3[0]; + out[1] = tmpvec3[1]; + out[2] = tmpvec3[2]; + out[3] = 1 + dot; + return normalize$2(out, out); + } + }; +}(); +/** + * Performs a spherical linear interpolation with two control points + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @param {ReadonlyQuat} c the third operand + * @param {ReadonlyQuat} d the fourth operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {quat} out + */ + +var sqlerp = function () { + var temp1 = create$2(); + var temp2 = create$2(); + return function (out, a, b, c, d, t) { + slerp(temp1, a, d, t); + slerp(temp2, b, c, t); + slerp(out, temp1, temp2, 2 * t * (1 - t)); + return out; + }; +}(); +/** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {ReadonlyVec3} view the vector representing the viewing direction + * @param {ReadonlyVec3} right the vector representing the local "right" direction + * @param {ReadonlyVec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + +var setAxes = function () { + var matr = create$6(); + return function (out, view, right, up) { + matr[0] = right[0]; + matr[3] = right[1]; + matr[6] = right[2]; + matr[1] = up[0]; + matr[4] = up[1]; + matr[7] = up[2]; + matr[2] = -view[0]; + matr[5] = -view[1]; + matr[8] = -view[2]; + return normalize$2(out, fromMat3(out, matr)); + }; +}(); + +var quat = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$2, +calculateW: calculateW, +clone: clone$2, +conjugate: conjugate$1, +copy: copy$2, +create: create$2, +dot: dot$3, +equals: equals$3, +exactEquals: exactEquals$2, +exp: exp, +fromEuler: fromEuler, +fromMat3: fromMat3, +fromValues: fromValues$2, +getAngle: getAngle, +getAxisAngle: getAxisAngle, +identity: identity$1, +invert: invert$1, +len: len$2, +length: length$2, +lerp: lerp$2, +ln: ln, +mul: mul$2, +multiply: multiply$2, +normalize: normalize$2, +pow: pow, +random: random$1, +rotateX: rotateX$1, +rotateY: rotateY$1, +rotateZ: rotateZ$1, +rotationTo: rotationTo, +scale: scale$2, +set: set$2, +setAxes: setAxes, +setAxisAngle: setAxisAngle, +slerp: slerp, +sqlerp: sqlerp, +sqrLen: sqrLen$2, +squaredLength: squaredLength$2, +str: str$2 +}); + +/** + * Dual Quaternion
+ * Format: [real, dual]
+ * Quaternion format: XYZW
+ * Make sure to have normalized dual quaternions, otherwise the functions may not work as intended.
+ * @module quat2 + */ + +/** + * Creates a new identity dual quat + * + * @returns {quat2} a new dual quaternion [real -> rotation, dual -> translation] + */ + +function create$1() { + var dq = new ARRAY_TYPE(8); + + if (ARRAY_TYPE != Float32Array) { + dq[0] = 0; + dq[1] = 0; + dq[2] = 0; + dq[4] = 0; + dq[5] = 0; + dq[6] = 0; + dq[7] = 0; + } + + dq[3] = 1; + return dq; +} +/** + * Creates a new quat initialized with values from an existing quaternion + * + * @param {ReadonlyQuat2} a dual quaternion to clone + * @returns {quat2} new dual quaternion + * @function + */ + +function clone$1(a) { + var dq = new ARRAY_TYPE(8); + dq[0] = a[0]; + dq[1] = a[1]; + dq[2] = a[2]; + dq[3] = a[3]; + dq[4] = a[4]; + dq[5] = a[5]; + dq[6] = a[6]; + dq[7] = a[7]; + return dq; +} +/** + * Creates a new dual quat initialized with the given values + * + * @param {Number} x1 X component + * @param {Number} y1 Y component + * @param {Number} z1 Z component + * @param {Number} w1 W component + * @param {Number} x2 X component + * @param {Number} y2 Y component + * @param {Number} z2 Z component + * @param {Number} w2 W component + * @returns {quat2} new dual quaternion + * @function + */ + +function fromValues$1(x1, y1, z1, w1, x2, y2, z2, w2) { + var dq = new ARRAY_TYPE(8); + dq[0] = x1; + dq[1] = y1; + dq[2] = z1; + dq[3] = w1; + dq[4] = x2; + dq[5] = y2; + dq[6] = z2; + dq[7] = w2; + return dq; +} +/** + * Creates a new dual quat from the given values (quat and translation) + * + * @param {Number} x1 X component + * @param {Number} y1 Y component + * @param {Number} z1 Z component + * @param {Number} w1 W component + * @param {Number} x2 X component (translation) + * @param {Number} y2 Y component (translation) + * @param {Number} z2 Z component (translation) + * @returns {quat2} new dual quaternion + * @function + */ + +function fromRotationTranslationValues(x1, y1, z1, w1, x2, y2, z2) { + var dq = new ARRAY_TYPE(8); + dq[0] = x1; + dq[1] = y1; + dq[2] = z1; + dq[3] = w1; + var ax = x2 * 0.5, + ay = y2 * 0.5, + az = z2 * 0.5; + dq[4] = ax * w1 + ay * z1 - az * y1; + dq[5] = ay * w1 + az * x1 - ax * z1; + dq[6] = az * w1 + ax * y1 - ay * x1; + dq[7] = -ax * x1 - ay * y1 - az * z1; + return dq; +} +/** + * Creates a dual quat from a quaternion and a translation + * + * @param {ReadonlyQuat2} dual quaternion receiving operation result + * @param {ReadonlyQuat} q a normalized quaternion + * @param {ReadonlyVec3} t tranlation vector + * @returns {quat2} dual quaternion receiving operation result + * @function + */ + +function fromRotationTranslation(out, q, t) { + var ax = t[0] * 0.5, + ay = t[1] * 0.5, + az = t[2] * 0.5, + bx = q[0], + by = q[1], + bz = q[2], + bw = q[3]; + out[0] = bx; + out[1] = by; + out[2] = bz; + out[3] = bw; + out[4] = ax * bw + ay * bz - az * by; + out[5] = ay * bw + az * bx - ax * bz; + out[6] = az * bw + ax * by - ay * bx; + out[7] = -ax * bx - ay * by - az * bz; + return out; +} +/** + * Creates a dual quat from a translation + * + * @param {ReadonlyQuat2} dual quaternion receiving operation result + * @param {ReadonlyVec3} t translation vector + * @returns {quat2} dual quaternion receiving operation result + * @function + */ + +function fromTranslation(out, t) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = t[0] * 0.5; + out[5] = t[1] * 0.5; + out[6] = t[2] * 0.5; + out[7] = 0; + return out; +} +/** + * Creates a dual quat from a quaternion + * + * @param {ReadonlyQuat2} dual quaternion receiving operation result + * @param {ReadonlyQuat} q the quaternion + * @returns {quat2} dual quaternion receiving operation result + * @function + */ + +function fromRotation(out, q) { + out[0] = q[0]; + out[1] = q[1]; + out[2] = q[2]; + out[3] = q[3]; + out[4] = 0; + out[5] = 0; + out[6] = 0; + out[7] = 0; + return out; +} +/** + * Creates a new dual quat from a matrix (4x4) + * + * @param {quat2} out the dual quaternion + * @param {ReadonlyMat4} a the matrix + * @returns {quat2} dual quat receiving operation result + * @function + */ + +function fromMat4(out, a) { + //TODO Optimize this + var outer = create$2(); + getRotation(outer, a); + var t = new ARRAY_TYPE(3); + getTranslation$1(t, a); + fromRotationTranslation(out, outer, t); + return out; +} +/** + * Copy the values from one dual quat to another + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the source dual quaternion + * @returns {quat2} out + * @function + */ + +function copy$1(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + return out; +} +/** + * Set a dual quat to the identity dual quaternion + * + * @param {quat2} out the receiving quaternion + * @returns {quat2} out + */ + +function identity(out) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = 0; + out[5] = 0; + out[6] = 0; + out[7] = 0; + return out; +} +/** + * Set the components of a dual quat to the given values + * + * @param {quat2} out the receiving quaternion + * @param {Number} x1 X component + * @param {Number} y1 Y component + * @param {Number} z1 Z component + * @param {Number} w1 W component + * @param {Number} x2 X component + * @param {Number} y2 Y component + * @param {Number} z2 Z component + * @param {Number} w2 W component + * @returns {quat2} out + * @function + */ + +function set$1(out, x1, y1, z1, w1, x2, y2, z2, w2) { + out[0] = x1; + out[1] = y1; + out[2] = z1; + out[3] = w1; + out[4] = x2; + out[5] = y2; + out[6] = z2; + out[7] = w2; + return out; +} +/** + * Gets the real part of a dual quat + * @param {quat} out real part + * @param {ReadonlyQuat2} a Dual Quaternion + * @return {quat} real part + */ + +var getReal = copy$2; +/** + * Gets the dual part of a dual quat + * @param {quat} out dual part + * @param {ReadonlyQuat2} a Dual Quaternion + * @return {quat} dual part + */ + +function getDual(out, a) { + out[0] = a[4]; + out[1] = a[5]; + out[2] = a[6]; + out[3] = a[7]; + return out; +} +/** + * Set the real component of a dual quat to the given quaternion + * + * @param {quat2} out the receiving quaternion + * @param {ReadonlyQuat} q a quaternion representing the real part + * @returns {quat2} out + * @function + */ + +var setReal = copy$2; +/** + * Set the dual component of a dual quat to the given quaternion + * + * @param {quat2} out the receiving quaternion + * @param {ReadonlyQuat} q a quaternion representing the dual part + * @returns {quat2} out + * @function + */ + +function setDual(out, q) { + out[4] = q[0]; + out[5] = q[1]; + out[6] = q[2]; + out[7] = q[3]; + return out; +} +/** + * Gets the translation of a normalized dual quat + * @param {vec3} out translation + * @param {ReadonlyQuat2} a Dual Quaternion to be decomposed + * @return {vec3} translation + */ + +function getTranslation(out, a) { + var ax = a[4], + ay = a[5], + az = a[6], + aw = a[7], + bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3]; + out[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2; + out[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2; + out[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2; + return out; +} +/** + * Translates a dual quat by the given vector + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to translate + * @param {ReadonlyVec3} v vector to translate by + * @returns {quat2} out + */ + +function translate(out, a, v) { + var ax1 = a[0], + ay1 = a[1], + az1 = a[2], + aw1 = a[3], + bx1 = v[0] * 0.5, + by1 = v[1] * 0.5, + bz1 = v[2] * 0.5, + ax2 = a[4], + ay2 = a[5], + az2 = a[6], + aw2 = a[7]; + out[0] = ax1; + out[1] = ay1; + out[2] = az1; + out[3] = aw1; + out[4] = aw1 * bx1 + ay1 * bz1 - az1 * by1 + ax2; + out[5] = aw1 * by1 + az1 * bx1 - ax1 * bz1 + ay2; + out[6] = aw1 * bz1 + ax1 * by1 - ay1 * bx1 + az2; + out[7] = -ax1 * bx1 - ay1 * by1 - az1 * bz1 + aw2; + return out; +} +/** + * Rotates a dual quat around the X axis + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {number} rad how far should the rotation be + * @returns {quat2} out + */ + +function rotateX(out, a, rad) { + var bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3], + ax = a[4], + ay = a[5], + az = a[6], + aw = a[7], + ax1 = ax * bw + aw * bx + ay * bz - az * by, + ay1 = ay * bw + aw * by + az * bx - ax * bz, + az1 = az * bw + aw * bz + ax * by - ay * bx, + aw1 = aw * bw - ax * bx - ay * by - az * bz; + rotateX$1(out, a, rad); + bx = out[0]; + by = out[1]; + bz = out[2]; + bw = out[3]; + out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; + out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; + out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; + out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; + return out; +} +/** + * Rotates a dual quat around the Y axis + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {number} rad how far should the rotation be + * @returns {quat2} out + */ + +function rotateY(out, a, rad) { + var bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3], + ax = a[4], + ay = a[5], + az = a[6], + aw = a[7], + ax1 = ax * bw + aw * bx + ay * bz - az * by, + ay1 = ay * bw + aw * by + az * bx - ax * bz, + az1 = az * bw + aw * bz + ax * by - ay * bx, + aw1 = aw * bw - ax * bx - ay * by - az * bz; + rotateY$1(out, a, rad); + bx = out[0]; + by = out[1]; + bz = out[2]; + bw = out[3]; + out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; + out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; + out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; + out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; + return out; +} +/** + * Rotates a dual quat around the Z axis + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {number} rad how far should the rotation be + * @returns {quat2} out + */ + +function rotateZ(out, a, rad) { + var bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3], + ax = a[4], + ay = a[5], + az = a[6], + aw = a[7], + ax1 = ax * bw + aw * bx + ay * bz - az * by, + ay1 = ay * bw + aw * by + az * bx - ax * bz, + az1 = az * bw + aw * bz + ax * by - ay * bx, + aw1 = aw * bw - ax * bx - ay * by - az * bz; + rotateZ$1(out, a, rad); + bx = out[0]; + by = out[1]; + bz = out[2]; + bw = out[3]; + out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; + out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; + out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; + out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; + return out; +} +/** + * Rotates a dual quat by a given quaternion (a * q) + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {ReadonlyQuat} q quaternion to rotate by + * @returns {quat2} out + */ + +function rotateByQuatAppend(out, a, q) { + var qx = q[0], + qy = q[1], + qz = q[2], + qw = q[3], + ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + out[0] = ax * qw + aw * qx + ay * qz - az * qy; + out[1] = ay * qw + aw * qy + az * qx - ax * qz; + out[2] = az * qw + aw * qz + ax * qy - ay * qx; + out[3] = aw * qw - ax * qx - ay * qy - az * qz; + ax = a[4]; + ay = a[5]; + az = a[6]; + aw = a[7]; + out[4] = ax * qw + aw * qx + ay * qz - az * qy; + out[5] = ay * qw + aw * qy + az * qx - ax * qz; + out[6] = az * qw + aw * qz + ax * qy - ay * qx; + out[7] = aw * qw - ax * qx - ay * qy - az * qz; + return out; +} +/** + * Rotates a dual quat by a given quaternion (q * a) + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat} q quaternion to rotate by + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @returns {quat2} out + */ + +function rotateByQuatPrepend(out, q, a) { + var qx = q[0], + qy = q[1], + qz = q[2], + qw = q[3], + bx = a[0], + by = a[1], + bz = a[2], + bw = a[3]; + out[0] = qx * bw + qw * bx + qy * bz - qz * by; + out[1] = qy * bw + qw * by + qz * bx - qx * bz; + out[2] = qz * bw + qw * bz + qx * by - qy * bx; + out[3] = qw * bw - qx * bx - qy * by - qz * bz; + bx = a[4]; + by = a[5]; + bz = a[6]; + bw = a[7]; + out[4] = qx * bw + qw * bx + qy * bz - qz * by; + out[5] = qy * bw + qw * by + qz * bx - qx * bz; + out[6] = qz * bw + qw * bz + qx * by - qy * bx; + out[7] = qw * bw - qx * bx - qy * by - qz * bz; + return out; +} +/** + * Rotates a dual quat around a given axis. Does the normalisation automatically + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {ReadonlyVec3} axis the axis to rotate around + * @param {Number} rad how far the rotation should be + * @returns {quat2} out + */ + +function rotateAroundAxis(out, a, axis, rad) { + //Special case for rad = 0 + if (Math.abs(rad) < EPSILON) { + return copy$1(out, a); + } + + var axisLength = Math.hypot(axis[0], axis[1], axis[2]); + rad = rad * 0.5; + var s = Math.sin(rad); + var bx = s * axis[0] / axisLength; + var by = s * axis[1] / axisLength; + var bz = s * axis[2] / axisLength; + var bw = Math.cos(rad); + var ax1 = a[0], + ay1 = a[1], + az1 = a[2], + aw1 = a[3]; + out[0] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; + out[1] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; + out[2] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; + out[3] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; + var ax = a[4], + ay = a[5], + az = a[6], + aw = a[7]; + out[4] = ax * bw + aw * bx + ay * bz - az * by; + out[5] = ay * bw + aw * by + az * bx - ax * bz; + out[6] = az * bw + aw * bz + ax * by - ay * bx; + out[7] = aw * bw - ax * bx - ay * by - az * bz; + return out; +} +/** + * Adds two dual quat's + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the first operand + * @param {ReadonlyQuat2} b the second operand + * @returns {quat2} out + * @function + */ + +function add$1(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + out[4] = a[4] + b[4]; + out[5] = a[5] + b[5]; + out[6] = a[6] + b[6]; + out[7] = a[7] + b[7]; + return out; +} +/** + * Multiplies two dual quat's + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the first operand + * @param {ReadonlyQuat2} b the second operand + * @returns {quat2} out + */ + +function multiply$1(out, a, b) { + var ax0 = a[0], + ay0 = a[1], + az0 = a[2], + aw0 = a[3], + bx1 = b[4], + by1 = b[5], + bz1 = b[6], + bw1 = b[7], + ax1 = a[4], + ay1 = a[5], + az1 = a[6], + aw1 = a[7], + bx0 = b[0], + by0 = b[1], + bz0 = b[2], + bw0 = b[3]; + out[0] = ax0 * bw0 + aw0 * bx0 + ay0 * bz0 - az0 * by0; + out[1] = ay0 * bw0 + aw0 * by0 + az0 * bx0 - ax0 * bz0; + out[2] = az0 * bw0 + aw0 * bz0 + ax0 * by0 - ay0 * bx0; + out[3] = aw0 * bw0 - ax0 * bx0 - ay0 * by0 - az0 * bz0; + out[4] = ax0 * bw1 + aw0 * bx1 + ay0 * bz1 - az0 * by1 + ax1 * bw0 + aw1 * bx0 + ay1 * bz0 - az1 * by0; + out[5] = ay0 * bw1 + aw0 * by1 + az0 * bx1 - ax0 * bz1 + ay1 * bw0 + aw1 * by0 + az1 * bx0 - ax1 * bz0; + out[6] = az0 * bw1 + aw0 * bz1 + ax0 * by1 - ay0 * bx1 + az1 * bw0 + aw1 * bz0 + ax1 * by0 - ay1 * bx0; + out[7] = aw0 * bw1 - ax0 * bx1 - ay0 * by1 - az0 * bz1 + aw1 * bw0 - ax1 * bx0 - ay1 * by0 - az1 * bz0; + return out; +} +/** + * Alias for {@link quat2.multiply} + * @function + */ + +var mul$1 = multiply$1; +/** + * Scales a dual quat by a scalar number + * + * @param {quat2} out the receiving dual quat + * @param {ReadonlyQuat2} a the dual quat to scale + * @param {Number} b amount to scale the dual quat by + * @returns {quat2} out + * @function + */ + +function scale$1(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + out[4] = a[4] * b; + out[5] = a[5] * b; + out[6] = a[6] * b; + out[7] = a[7] * b; + return out; +} +/** + * Calculates the dot product of two dual quat's (The dot product of the real parts) + * + * @param {ReadonlyQuat2} a the first operand + * @param {ReadonlyQuat2} b the second operand + * @returns {Number} dot product of a and b + * @function + */ + +var dot$2 = dot$3; +/** + * Performs a linear interpolation between two dual quats's + * NOTE: The resulting dual quaternions won't always be normalized (The error is most noticeable when t = 0.5) + * + * @param {quat2} out the receiving dual quat + * @param {ReadonlyQuat2} a the first operand + * @param {ReadonlyQuat2} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {quat2} out + */ + +function lerp$1(out, a, b, t) { + var mt = 1 - t; + if (dot$2(a, b) < 0) t = -t; + out[0] = a[0] * mt + b[0] * t; + out[1] = a[1] * mt + b[1] * t; + out[2] = a[2] * mt + b[2] * t; + out[3] = a[3] * mt + b[3] * t; + out[4] = a[4] * mt + b[4] * t; + out[5] = a[5] * mt + b[5] * t; + out[6] = a[6] * mt + b[6] * t; + out[7] = a[7] * mt + b[7] * t; + return out; +} +/** + * Calculates the inverse of a dual quat. If they are normalized, conjugate is cheaper + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a dual quat to calculate inverse of + * @returns {quat2} out + */ + +function invert(out, a) { + var sqlen = squaredLength$1(a); + out[0] = -a[0] / sqlen; + out[1] = -a[1] / sqlen; + out[2] = -a[2] / sqlen; + out[3] = a[3] / sqlen; + out[4] = -a[4] / sqlen; + out[5] = -a[5] / sqlen; + out[6] = -a[6] / sqlen; + out[7] = a[7] / sqlen; + return out; +} +/** + * Calculates the conjugate of a dual quat + * If the dual quaternion is normalized, this function is faster than quat2.inverse and produces the same result. + * + * @param {quat2} out the receiving quaternion + * @param {ReadonlyQuat2} a quat to calculate conjugate of + * @returns {quat2} out + */ + +function conjugate(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = a[3]; + out[4] = -a[4]; + out[5] = -a[5]; + out[6] = -a[6]; + out[7] = a[7]; + return out; +} +/** + * Calculates the length of a dual quat + * + * @param {ReadonlyQuat2} a dual quat to calculate length of + * @returns {Number} length of a + * @function + */ + +var length$1 = length$2; +/** + * Alias for {@link quat2.length} + * @function + */ + +var len$1 = length$1; +/** + * Calculates the squared length of a dual quat + * + * @param {ReadonlyQuat2} a dual quat to calculate squared length of + * @returns {Number} squared length of a + * @function + */ + +var squaredLength$1 = squaredLength$2; +/** + * Alias for {@link quat2.squaredLength} + * @function + */ + +var sqrLen$1 = squaredLength$1; +/** + * Normalize a dual quat + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a dual quaternion to normalize + * @returns {quat2} out + * @function + */ + +function normalize$1(out, a) { + var magnitude = squaredLength$1(a); + + if (magnitude > 0) { + magnitude = Math.sqrt(magnitude); + var a0 = a[0] / magnitude; + var a1 = a[1] / magnitude; + var a2 = a[2] / magnitude; + var a3 = a[3] / magnitude; + var b0 = a[4]; + var b1 = a[5]; + var b2 = a[6]; + var b3 = a[7]; + var a_dot_b = a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3; + out[0] = a0; + out[1] = a1; + out[2] = a2; + out[3] = a3; + out[4] = (b0 - a0 * a_dot_b) / magnitude; + out[5] = (b1 - a1 * a_dot_b) / magnitude; + out[6] = (b2 - a2 * a_dot_b) / magnitude; + out[7] = (b3 - a3 * a_dot_b) / magnitude; + } + + return out; +} +/** + * Returns a string representation of a dual quatenion + * + * @param {ReadonlyQuat2} a dual quaternion to represent as a string + * @returns {String} string representation of the dual quat + */ + +function str$1(a) { + return "quat2(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ", " + a[6] + ", " + a[7] + ")"; +} +/** + * Returns whether or not the dual quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyQuat2} a the first dual quaternion. + * @param {ReadonlyQuat2} b the second dual quaternion. + * @returns {Boolean} true if the dual quaternions are equal, false otherwise. + */ + +function exactEquals$1(a, b) { + 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]; +} +/** + * Returns whether or not the dual quaternions have approximately the same elements in the same position. + * + * @param {ReadonlyQuat2} a the first dual quat. + * @param {ReadonlyQuat2} b the second dual quat. + * @returns {Boolean} true if the dual quats are equal, false otherwise. + */ + +function equals$2(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5], + a6 = a[6], + a7 = a[7]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)); +} + +var quat2 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$1, +clone: clone$1, +conjugate: conjugate, +copy: copy$1, +create: create$1, +dot: dot$2, +equals: equals$2, +exactEquals: exactEquals$1, +fromMat4: fromMat4, +fromRotation: fromRotation, +fromRotationTranslation: fromRotationTranslation, +fromRotationTranslationValues: fromRotationTranslationValues, +fromTranslation: fromTranslation, +fromValues: fromValues$1, +getDual: getDual, +getReal: getReal, +getTranslation: getTranslation, +identity: identity, +invert: invert, +len: len$1, +length: length$1, +lerp: lerp$1, +mul: mul$1, +multiply: multiply$1, +normalize: normalize$1, +rotateAroundAxis: rotateAroundAxis, +rotateByQuatAppend: rotateByQuatAppend, +rotateByQuatPrepend: rotateByQuatPrepend, +rotateX: rotateX, +rotateY: rotateY, +rotateZ: rotateZ, +scale: scale$1, +set: set$1, +setDual: setDual, +setReal: setReal, +sqrLen: sqrLen$1, +squaredLength: squaredLength$1, +str: str$1, +translate: translate +}); + +/** + * 2 Dimensional Vector + * @module vec2 + */ + +/** + * Creates a new, empty vec2 + * + * @returns {vec2} a new 2D vector + */ + +function create() { + var out = new ARRAY_TYPE(2); + + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + } + + return out; +} +/** + * Creates a new vec2 initialized with values from an existing vector + * + * @param {ReadonlyVec2} a vector to clone + * @returns {vec2} a new 2D vector + */ + +function clone(a) { + var out = new ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; +} +/** + * Creates a new vec2 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @returns {vec2} a new 2D vector + */ + +function fromValues(x, y) { + var out = new ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; +} +/** + * Copy the values from one vec2 to another + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the source vector + * @returns {vec2} out + */ + +function copy(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; +} +/** + * Set the components of a vec2 to the given values + * + * @param {vec2} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @returns {vec2} out + */ + +function set(out, x, y) { + out[0] = x; + out[1] = y; + return out; +} +/** + * Adds two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function add(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; +} +/** + * Subtracts vector b from vector a + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function subtract(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; +} +/** + * Multiplies two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function multiply(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; +} +/** + * Divides two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function divide(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; +} +/** + * Math.ceil the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to ceil + * @returns {vec2} out + */ + +function ceil(out, a) { + out[0] = Math.ceil(a[0]); + out[1] = Math.ceil(a[1]); + return out; +} +/** + * Math.floor the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to floor + * @returns {vec2} out + */ + +function floor(out, a) { + out[0] = Math.floor(a[0]); + out[1] = Math.floor(a[1]); + return out; +} +/** + * Returns the minimum of two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function min(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + return out; +} +/** + * Returns the maximum of two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function max(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + return out; +} +/** + * Math.round the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to round + * @returns {vec2} out + */ + +function round(out, a) { + out[0] = Math.round(a[0]); + out[1] = Math.round(a[1]); + return out; +} +/** + * Scales a vec2 by a scalar number + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec2} out + */ + +function scale(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; +} +/** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec2} out + */ + +function scaleAndAdd(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + return out; +} +/** + * Calculates the euclidian distance between two vec2's + * + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {Number} distance between a and b + */ + +function distance(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return Math.hypot(x, y); +} +/** + * Calculates the squared euclidian distance between two vec2's + * + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {Number} squared distance between a and b + */ + +function squaredDistance(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return x * x + y * y; +} +/** + * Calculates the length of a vec2 + * + * @param {ReadonlyVec2} a vector to calculate length of + * @returns {Number} length of a + */ + +function length(a) { + var x = a[0], + y = a[1]; + return Math.hypot(x, y); +} +/** + * Calculates the squared length of a vec2 + * + * @param {ReadonlyVec2} a vector to calculate squared length of + * @returns {Number} squared length of a + */ + +function squaredLength(a) { + var x = a[0], + y = a[1]; + return x * x + y * y; +} +/** + * Negates the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to negate + * @returns {vec2} out + */ + +function negate(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; +} +/** + * Returns the inverse of the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to invert + * @returns {vec2} out + */ + +function inverse(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + return out; +} +/** + * Normalize a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to normalize + * @returns {vec2} out + */ + +function normalize(out, a) { + var x = a[0], + y = a[1]; + var len = x * x + y * y; + + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + } + + out[0] = a[0] * len; + out[1] = a[1] * len; + return out; +} +/** + * Calculates the dot product of two vec2's + * + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {Number} dot product of a and b + */ + +function dot$1(a, b) { + return a[0] * b[0] + a[1] * b[1]; +} +/** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec3} out + */ + +function cross(out, a, b) { + var z = a[0] * b[1] - a[1] * b[0]; + out[0] = out[1] = 0; + out[2] = z; + return out; +} +/** + * Performs a linear interpolation between two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec2} out + */ + +function lerp(out, a, b, t) { + var ax = a[0], + ay = a[1]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + return out; +} +/** + * Generates a random vector with the given scale + * + * @param {vec2} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec2} out + */ + +function random(out, scale) { + scale = scale || 1.0; + var r = RANDOM() * 2.0 * Math.PI; + out[0] = Math.cos(r) * scale; + out[1] = Math.sin(r) * scale; + return out; +} +/** + * Transforms the vec2 with a mat2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to transform + * @param {ReadonlyMat2} m matrix to transform with + * @returns {vec2} out + */ + +function transformMat2(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[2] * y; + out[1] = m[1] * x + m[3] * y; + return out; +} +/** + * Transforms the vec2 with a mat2d + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to transform + * @param {ReadonlyMat2d} m matrix to transform with + * @returns {vec2} out + */ + +function transformMat2d(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[2] * y + m[4]; + out[1] = m[1] * x + m[3] * y + m[5]; + return out; +} +/** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to transform + * @param {ReadonlyMat3} m matrix to transform with + * @returns {vec2} out + */ + +function transformMat3(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[3] * y + m[6]; + out[1] = m[1] * x + m[4] * y + m[7]; + return out; +} +/** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to transform + * @param {ReadonlyMat4} m matrix to transform with + * @returns {vec2} out + */ + +function transformMat4(out, a, m) { + var x = a[0]; + var y = a[1]; + out[0] = m[0] * x + m[4] * y + m[12]; + out[1] = m[1] * x + m[5] * y + m[13]; + return out; +} +/** + * Rotate a 2D vector + * @param {vec2} out The receiving vec2 + * @param {ReadonlyVec2} a The vec2 point to rotate + * @param {ReadonlyVec2} b The origin of the rotation + * @param {Number} rad The angle of rotation in radians + * @returns {vec2} out + */ + +function rotate(out, a, b, rad) { + //Translate point to the origin + var p0 = a[0] - b[0], + p1 = a[1] - b[1], + sinC = Math.sin(rad), + cosC = Math.cos(rad); //perform rotation and translate to correct position + + out[0] = p0 * cosC - p1 * sinC + b[0]; + out[1] = p0 * sinC + p1 * cosC + b[1]; + return out; +} +/** + * Get the angle between two 2D vectors + * @param {ReadonlyVec2} a The first operand + * @param {ReadonlyVec2} b The second operand + * @returns {Number} The angle in radians + */ + +function angle(a, b) { + var x1 = a[0], + y1 = a[1], + x2 = b[0], + y2 = b[1], + // mag is the product of the magnitudes of a and b + mag = Math.sqrt(x1 * x1 + y1 * y1) * Math.sqrt(x2 * x2 + y2 * y2), + // mag &&.. short circuits if mag == 0 + cosine = mag && (x1 * x2 + y1 * y2) / mag; // Math.min(Math.max(cosine, -1), 1) clamps the cosine between -1 and 1 + + return Math.acos(Math.min(Math.max(cosine, -1), 1)); +} +/** + * Set the components of a vec2 to zero + * + * @param {vec2} out the receiving vector + * @returns {vec2} out + */ + +function zero(out) { + out[0] = 0.0; + out[1] = 0.0; + return out; +} +/** + * Returns a string representation of a vector + * + * @param {ReadonlyVec2} a vector to represent as a string + * @returns {String} string representation of the vector + */ + +function str(a) { + return "vec2(" + a[0] + ", " + a[1] + ")"; +} +/** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) + * + * @param {ReadonlyVec2} a The first vector. + * @param {ReadonlyVec2} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function exactEquals(a, b) { + return a[0] === b[0] && a[1] === b[1]; +} +/** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {ReadonlyVec2} a The first vector. + * @param {ReadonlyVec2} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function equals$1(a, b) { + var a0 = a[0], + a1 = a[1]; + var b0 = b[0], + b1 = b[1]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)); +} +/** + * Alias for {@link vec2.length} + * @function + */ + +var len = length; +/** + * Alias for {@link vec2.subtract} + * @function + */ + +var sub = subtract; +/** + * Alias for {@link vec2.multiply} + * @function + */ + +var mul = multiply; +/** + * Alias for {@link vec2.divide} + * @function + */ + +var div = divide; +/** + * Alias for {@link vec2.distance} + * @function + */ + +var dist = distance; +/** + * Alias for {@link vec2.squaredDistance} + * @function + */ + +var sqrDist = squaredDistance; +/** + * Alias for {@link vec2.squaredLength} + * @function + */ + +var sqrLen = squaredLength; +/** + * Perform some operation over an array of vec2s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ + +var forEach = function () { + var vec = create(); + return function (a, stride, offset, count, fn, arg) { + var i, l; + + if (!stride) { + stride = 2; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min(count * stride + offset, a.length); + } else { + l = a.length; + } + + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + } + + return a; + }; +}(); + +var vec2 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add, +angle: angle, +ceil: ceil, +clone: clone, +copy: copy, +create: create, +cross: cross, +dist: dist, +distance: distance, +div: div, +divide: divide, +dot: dot$1, +equals: equals$1, +exactEquals: exactEquals, +floor: floor, +forEach: forEach, +fromValues: fromValues, +inverse: inverse, +len: len, +length: length, +lerp: lerp, +max: max, +min: min, +mul: mul, +multiply: multiply, +negate: negate, +normalize: normalize, +random: random, +rotate: rotate, +round: round, +scale: scale, +scaleAndAdd: scaleAndAdd, +set: set, +sqrDist: sqrDist, +sqrLen: sqrLen, +squaredDistance: squaredDistance, +squaredLength: squaredLength, +str: str, +sub: sub, +subtract: subtract, +transformMat2: transformMat2, +transformMat2d: transformMat2d, +transformMat3: transformMat3, +transformMat4: transformMat4, +zero: zero +}); + +/** + * A style layer that defines a circle + */ +class CircleStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$8); + } + createBucket(parameters) { + return new CircleBucket(parameters); + } + queryRadius(bucket) { + const circleBucket = bucket; + return getMaximumPaintValue('circle-radius', this, circleBucket) + + getMaximumPaintValue('circle-stroke-width', this, circleBucket) + + translateDistance(this.paint.get('circle-translate')); + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits, pixelPosMatrix) { + const translatedPolygon = translate$4(queryGeometry, this.paint.get('circle-translate'), this.paint.get('circle-translate-anchor'), transform.angle, pixelsToTileUnits); + const radius = this.paint.get('circle-radius').evaluate(feature, featureState); + const stroke = this.paint.get('circle-stroke-width').evaluate(feature, featureState); + const size = radius + stroke; + // For pitch-alignment: map, compare feature geometry to query geometry in the plane of the tile + // // Otherwise, compare geometry in the plane of the viewport + // // A circle with fixed scaling relative to the viewport gets larger in tile space as it moves into the distance + // // A circle with fixed scaling relative to the map gets smaller in viewport space as it moves into the distance + const alignWithMap = this.paint.get('circle-pitch-alignment') === 'map'; + const transformedPolygon = alignWithMap ? translatedPolygon : projectQueryGeometry$1(translatedPolygon, pixelPosMatrix); + const transformedSize = alignWithMap ? size * pixelsToTileUnits : size; + for (const ring of geometry) { + for (const point of ring) { + const transformedPoint = alignWithMap ? point : projectPoint(point, pixelPosMatrix); + let adjustedSize = transformedSize; + const projectedCenter = transformMat4$1([], [point.x, point.y, 0, 1], pixelPosMatrix); + if (this.paint.get('circle-pitch-scale') === 'viewport' && this.paint.get('circle-pitch-alignment') === 'map') { + adjustedSize *= projectedCenter[3] / transform.cameraToCenterDistance; + } + else if (this.paint.get('circle-pitch-scale') === 'map' && this.paint.get('circle-pitch-alignment') === 'viewport') { + adjustedSize *= transform.cameraToCenterDistance / projectedCenter[3]; + } + if (polygonIntersectsBufferedPoint(transformedPolygon, transformedPoint, adjustedSize)) + return true; + } + } + return false; + } +} +function projectPoint(p, pixelPosMatrix) { + const point = transformMat4$1([], [p.x, p.y, 0, 1], pixelPosMatrix); + return new Point$3(point[0] / point[3], point[1] / point[3]); +} +function projectQueryGeometry$1(queryGeometry, pixelPosMatrix) { + return queryGeometry.map((p) => { + return projectPoint(p, pixelPosMatrix); + }); +} + +class HeatmapBucket extends CircleBucket { +} +register('HeatmapBucket', HeatmapBucket, { omit: ['layers'] }); + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$7; +const getPaint$7 = () => paint$7 = paint$7 || new Properties({ + "heatmap-radius": new DataDrivenProperty(v8Spec["paint_heatmap"]["heatmap-radius"]), + "heatmap-weight": new DataDrivenProperty(v8Spec["paint_heatmap"]["heatmap-weight"]), + "heatmap-intensity": new DataConstantProperty(v8Spec["paint_heatmap"]["heatmap-intensity"]), + "heatmap-color": new ColorRampProperty(v8Spec["paint_heatmap"]["heatmap-color"]), + "heatmap-opacity": new DataConstantProperty(v8Spec["paint_heatmap"]["heatmap-opacity"]), +}); +var properties$7 = ({ get paint() { return getPaint$7(); } }); + +function createImage(image, { width, height }, channels, data) { + if (!data) { + data = new Uint8Array(width * height * channels); + } + else if (data instanceof Uint8ClampedArray) { + data = new Uint8Array(data.buffer); + } + else if (data.length !== width * height * channels) { + throw new RangeError(`mismatched image size. expected: ${data.length} but got: ${width * height * channels}`); + } + image.width = width; + image.height = height; + image.data = data; + return image; +} +function resizeImage(image, { width, height }, channels) { + if (width === image.width && height === image.height) { + return; + } + const newImage = createImage({}, { width, height }, channels); + copyImage(image, newImage, { x: 0, y: 0 }, { x: 0, y: 0 }, { + width: Math.min(image.width, width), + height: Math.min(image.height, height) + }, channels); + image.width = width; + image.height = height; + image.data = newImage.data; +} +function copyImage(srcImg, dstImg, srcPt, dstPt, size, channels) { + if (size.width === 0 || size.height === 0) { + return dstImg; + } + if (size.width > srcImg.width || + size.height > srcImg.height || + srcPt.x > srcImg.width - size.width || + srcPt.y > srcImg.height - size.height) { + throw new RangeError('out of range source coordinates for image copy'); + } + if (size.width > dstImg.width || + size.height > dstImg.height || + dstPt.x > dstImg.width - size.width || + dstPt.y > dstImg.height - size.height) { + throw new RangeError('out of range destination coordinates for image copy'); + } + const srcData = srcImg.data; + const dstData = dstImg.data; + if (srcData === dstData) + throw new Error('srcData equals dstData, so image is already copied'); + for (let y = 0; y < size.height; y++) { + const srcOffset = ((srcPt.y + y) * srcImg.width + srcPt.x) * channels; + const dstOffset = ((dstPt.y + y) * dstImg.width + dstPt.x) * channels; + for (let i = 0; i < size.width * channels; i++) { + dstData[dstOffset + i] = srcData[srcOffset + i]; + } + } + return dstImg; +} +/** + * An image with alpha color value + */ +class AlphaImage { + constructor(size, data) { + createImage(this, size, 1, data); + } + resize(size) { + resizeImage(this, size, 1); + } + clone() { + return new AlphaImage({ width: this.width, height: this.height }, new Uint8Array(this.data)); + } + static copy(srcImg, dstImg, srcPt, dstPt, size) { + copyImage(srcImg, dstImg, srcPt, dstPt, size, 1); + } +} +/** + * An object to store image data not premultiplied, because ImageData is not premultiplied. + * UNPACK_PREMULTIPLY_ALPHA_WEBGL must be used when uploading to a texture. + */ +class RGBAImage { + constructor(size, data) { + createImage(this, size, 4, data); + } + resize(size) { + resizeImage(this, size, 4); + } + replace(data, copy) { + if (copy) { + this.data.set(data); + } + else if (data instanceof Uint8ClampedArray) { + this.data = new Uint8Array(data.buffer); + } + else { + this.data = data; + } + } + clone() { + return new RGBAImage({ width: this.width, height: this.height }, new Uint8Array(this.data)); + } + static copy(srcImg, dstImg, srcPt, dstPt, size) { + copyImage(srcImg, dstImg, srcPt, dstPt, size, 4); + } +} +register('AlphaImage', AlphaImage); +register('RGBAImage', RGBAImage); + +/** + * Given an expression that should evaluate to a color ramp, + * return a RGBA image representing that ramp expression. + */ +function renderColorRamp(params) { + const evaluationGlobals = {}; + const width = params.resolution || 256; + const height = params.clips ? params.clips.length : 1; + const image = params.image || new RGBAImage({ width, height }); + if (!isPowerOfTwo(width)) + throw new Error(`width is not a power of 2 - ${width}`); + const renderPixel = (stride, index, progress) => { + evaluationGlobals[params.evaluationKey] = progress; + const pxColor = params.expression.evaluate(evaluationGlobals); + // the colors are being unpremultiplied because Color uses + // premultiplied values, and the Texture class expects unpremultiplied ones + image.data[stride + index + 0] = Math.floor(pxColor.r * 255 / pxColor.a); + image.data[stride + index + 1] = Math.floor(pxColor.g * 255 / pxColor.a); + image.data[stride + index + 2] = Math.floor(pxColor.b * 255 / pxColor.a); + image.data[stride + index + 3] = Math.floor(pxColor.a * 255); + }; + if (!params.clips) { + for (let i = 0, j = 0; i < width; i++, j += 4) { + const progress = i / (width - 1); + renderPixel(0, j, progress); + } + } + else { + for (let clip = 0, stride = 0; clip < height; ++clip, stride += width * 4) { + for (let i = 0, j = 0; i < width; i++, j += 4) { + // Remap progress between clips + const progress = i / (width - 1); + const { start, end } = params.clips[clip]; + const evaluationProgress = start * (1 - progress) + end * progress; + renderPixel(stride, j, evaluationProgress); + } + } + } + return image; +} + +const HEATMAP_FULL_RENDER_FBO_KEY = 'big-fb'; +/** + * A style layer that defines a heatmap + */ +class HeatmapStyleLayer extends StyleLayer { + createBucket(options) { + return new HeatmapBucket(options); + } + constructor(layer) { + super(layer, properties$7); + this.heatmapFbos = new Map(); + // make sure color ramp texture is generated for default heatmap color too + this._updateColorRamp(); + } + _handleSpecialPaintPropertyUpdate(name) { + if (name === 'heatmap-color') { + this._updateColorRamp(); + } + } + _updateColorRamp() { + const expression = this._transitionablePaint._values['heatmap-color'].value.expression; + this.colorRamp = renderColorRamp({ + expression, + evaluationKey: 'heatmapDensity', + image: this.colorRamp + }); + this.colorRampTexture = null; + } + resize() { + if (this.heatmapFbos.has(HEATMAP_FULL_RENDER_FBO_KEY)) { + this.heatmapFbos.delete(HEATMAP_FULL_RENDER_FBO_KEY); + } + } + queryRadius() { + return 0; + } + queryIntersectsFeature() { + return false; + } + hasOffscreenPass() { + return this.paint.get('heatmap-opacity') !== 0 && this.visibility !== 'none'; + } +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$6; +const getPaint$6 = () => paint$6 = paint$6 || new Properties({ + "hillshade-illumination-direction": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-illumination-direction"]), + "hillshade-illumination-anchor": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-illumination-anchor"]), + "hillshade-exaggeration": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-exaggeration"]), + "hillshade-shadow-color": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-shadow-color"]), + "hillshade-highlight-color": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-highlight-color"]), + "hillshade-accent-color": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-accent-color"]), +}); +var properties$6 = ({ get paint() { return getPaint$6(); } }); + +class HillshadeStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$6); + } + hasOffscreenPass() { + return this.paint.get('hillshade-exaggeration') !== 0 && this.visibility !== 'none'; + } +} + +const layout$4 = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' } +], 4); +const { members: members$3, size: size$3, alignment: alignment$3 } = layout$4; + +function earcut(data, holeIndices, dim = 2) { + + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data.length; + let outerNode = linkedList(data, 0, outerLen, dim, true); + const triangles = []; + + if (!outerNode || outerNode.next === outerNode.prev) return triangles; + + let minX, minY, invSize; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = Infinity; + minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + + for (let i = dim; i < outerLen; i += dim) { + const x = data[i]; + const y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + let last; + + if (clockwise === (signedArea$1(data, start, end, dim) > 0)) { + for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); + } else { + for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + let p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + + let stop = ear; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + const prev = ear.prev; + const next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + triangles.push(prev.i, ear.i, next.i); // cut off the triangle + + removeNode(ear); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + const a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + let p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, invSize) { + const a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + // z-order range for the current triangle bbox; + const minZ = zOrder(x0, y0, minX, minY, invSize), + maxZ = zOrder(x1, y1, minX, minY, invSize); + + let p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles) { + let p = start; + do { + const a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i, p.i, b.i); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return filterPoints(p); +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + let a = start; + do { + let b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + let c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + const queue = []; + + for (let i = 0, len = holeIndices.length; i < len; i++) { + const start = holeIndices[i] * dim; + const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + const list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (let i = 0; i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + const bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + + const bridgeReverse = splitPolygon(bridge, hole); + + // filter collinear points around the cuts + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + let p = outerNode; + const hx = hole.x; + const hy = hole.y; + let qx = -Infinity; + let m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + const stop = m; + const mx = m.x; + const my = m.y; + let tanMin = Infinity; + + p = m; + + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if (locallyInside(p, hole) && + (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } while (p !== stop); + + return m; +} + +// whether sector in vertex m contains sector in vertex p in the same coordinates +function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, invSize) { + let p = start; + do { + if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + let numMerges; + let inSize = 1; + + do { + let p = list; + let e; + list = null; + let tail = null; + numMerges = 0; + + while (p) { + numMerges++; + let q = p; + let pSize = 0; + for (let i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + let qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + let p = start, + leftmost = start; + do { + if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && + (ax - px) * (by - py) >= (bx - px) * (ay - py) && + (bx - px) * (cy - py) >= (cx - px) * (by - py); +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges + (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors + equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + const o1 = sign(area(p1, q1, p2)); + const o2 = sign(area(p1, q1, q2)); + const o3 = sign(area(p2, q2, p1)); + const o4 = sign(area(p2, q2, q1)); + + if (o1 !== o2 && o3 !== o4) return true; // general case + + if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + + return false; +} + +// for collinear points p, q, r, check if point q lies on segment pr +function onSegment(p, q, r) { + 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); +} + +function sign(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + let p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + let p = a; + let inside = false; + const px = (a.x + b.x) / 2; + const py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + const a2 = createNode(a.i, a.x, a.y), + b2 = createNode(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + const p = createNode(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function createNode(i, x, y) { + return { + i, // vertex index in coordinates array + x, y, // vertex coordinates + prev: null, // previous and next vertex nodes in a polygon ring + next: null, + z: 0, // z-order curve value + prevZ: null, // previous and next nodes in z-order + nextZ: null, + steiner: false // indicates whether this is a steiner point + }; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +function deviation(data, holeIndices, dim, triangles) { + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + let polygonArea = Math.abs(signedArea$1(data, 0, outerLen, dim)); + if (hasHoles) { + for (let i = 0, len = holeIndices.length; i < len; i++) { + const start = holeIndices[i] * dim; + const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea$1(data, start, end, dim)); + } + } + + let trianglesArea = 0; + for (let i = 0; i < triangles.length; i += 3) { + const a = triangles[i] * dim; + const b = triangles[i + 1] * dim; + const c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +} + +function signedArea$1(data, start, end, dim) { + let sum = 0; + for (let i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +function flatten(data) { + const vertices = []; + const holes = []; + const dimensions = data[0][0].length; + let holeIndex = 0; + let prevLen = 0; + + for (const ring of data) { + for (const p of ring) { + for (let d = 0; d < dimensions; d++) vertices.push(p[d]); + } + if (prevLen) { + holeIndex += prevLen; + holes.push(holeIndex); + } + prevLen = ring.length; + } + return {vertices, holes, dimensions}; +} + +function hasPattern(type, layers, options) { + const patterns = options.patternDependencies; + let hasPattern = false; + for (const layer of layers) { + const patternProperty = layer.paint.get(`${type}-pattern`); + if (!patternProperty.isConstant()) { + hasPattern = true; + } + const constantPattern = patternProperty.constantOr(null); + if (constantPattern) { + hasPattern = true; + patterns[constantPattern.to] = true; + patterns[constantPattern.from] = true; + } + } + return hasPattern; +} +function addPatternDependencies(type, layers, patternFeature, zoom, options) { + const patterns = options.patternDependencies; + for (const layer of layers) { + const patternProperty = layer.paint.get(`${type}-pattern`); + const patternPropertyValue = patternProperty.value; + if (patternPropertyValue.kind !== 'constant') { + let min = patternPropertyValue.evaluate({ zoom: zoom - 1 }, patternFeature, {}, options.availableImages); + let mid = patternPropertyValue.evaluate({ zoom }, patternFeature, {}, options.availableImages); + let max = patternPropertyValue.evaluate({ zoom: zoom + 1 }, patternFeature, {}, options.availableImages); + min = min && min.name ? min.name : min; + mid = mid && mid.name ? mid.name : mid; + max = max && max.name ? max.name : max; + // add to patternDependencies + patterns[min] = true; + patterns[mid] = true; + patterns[max] = true; + // save for layout + patternFeature.patterns[layer.id] = { min, mid, max }; + } + } + return patternFeature; +} + +const EARCUT_MAX_RINGS$1 = 500; +class FillBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.patternFeatures = []; + this.layoutVertexArray = new FillLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.indexArray2 = new LineIndexArray(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.segments = new SegmentVector(); + this.segments2 = new SegmentVector(); + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + this.hasPattern = hasPattern('fill', this.layers, options); + const fillSortKey = this.layers[0].layout.get('fill-sort-key'); + const sortFeaturesByKey = !fillSortKey.isConstant(); + const bucketFeatures = []; + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const sortKey = sortFeaturesByKey ? + fillSortKey.evaluate(evaluationFeature, {}, canonical, options.availableImages) : + undefined; + const bucketFeature = { + id, + properties: feature.properties, + type: feature.type, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + patterns: {}, + sortKey + }; + bucketFeatures.push(bucketFeature); + } + if (sortFeaturesByKey) { + bucketFeatures.sort((a, b) => a.sortKey - b.sortKey); + } + for (const bucketFeature of bucketFeatures) { + const { geometry, index, sourceLayerIndex } = bucketFeature; + if (this.hasPattern) { + const patternFeature = addPatternDependencies('fill', this.layers, bucketFeature, this.zoom, options); + // pattern features are added only once the pattern is loaded into the image atlas + // so are stored during populate until later updated with positions by tile worker in addFeatures + this.patternFeatures.push(patternFeature); + } + else { + this.addFeature(bucketFeature, geometry, index, canonical, {}); + } + const feature = features[index].feature; + options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + addFeatures(options, canonical, imagePositions) { + for (const feature of this.patternFeatures) { + this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions); + } + } + isEmpty() { + return this.layoutVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$3); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + this.indexBuffer2 = context.createIndexBuffer(this.indexArray2); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.indexBuffer2.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + this.segments2.destroy(); + } + addFeature(feature, geometry, index, canonical, imagePositions) { + for (const polygon of classifyRings$1(geometry, EARCUT_MAX_RINGS$1)) { + let numVertices = 0; + for (const ring of polygon) { + numVertices += ring.length; + } + const triangleSegment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray); + const triangleIndex = triangleSegment.vertexLength; + const flattened = []; + const holeIndices = []; + for (const ring of polygon) { + if (ring.length === 0) { + continue; + } + if (ring !== polygon[0]) { + holeIndices.push(flattened.length / 2); + } + const lineSegment = this.segments2.prepareSegment(ring.length, this.layoutVertexArray, this.indexArray2); + const lineIndex = lineSegment.vertexLength; + this.layoutVertexArray.emplaceBack(ring[0].x, ring[0].y); + this.indexArray2.emplaceBack(lineIndex + ring.length - 1, lineIndex); + flattened.push(ring[0].x); + flattened.push(ring[0].y); + for (let i = 1; i < ring.length; i++) { + this.layoutVertexArray.emplaceBack(ring[i].x, ring[i].y); + this.indexArray2.emplaceBack(lineIndex + i - 1, lineIndex + i); + flattened.push(ring[i].x); + flattened.push(ring[i].y); + } + lineSegment.vertexLength += ring.length; + lineSegment.primitiveLength += ring.length; + } + const indices = earcut(flattened, holeIndices); + for (let i = 0; i < indices.length; i += 3) { + this.indexArray.emplaceBack(triangleIndex + indices[i], triangleIndex + indices[i + 1], triangleIndex + indices[i + 2]); + } + triangleSegment.vertexLength += numVertices; + triangleSegment.primitiveLength += indices.length / 3; + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical); + } +} +register('FillBucket', FillBucket, { omit: ['layers', 'patternFeatures'] }); + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout$3; +const getLayout$2 = () => layout$3 = layout$3 || new Properties({ + "fill-sort-key": new DataDrivenProperty(v8Spec["layout_fill"]["fill-sort-key"]), +}); +let paint$5; +const getPaint$5 = () => paint$5 = paint$5 || new Properties({ + "fill-antialias": new DataConstantProperty(v8Spec["paint_fill"]["fill-antialias"]), + "fill-opacity": new DataDrivenProperty(v8Spec["paint_fill"]["fill-opacity"]), + "fill-color": new DataDrivenProperty(v8Spec["paint_fill"]["fill-color"]), + "fill-outline-color": new DataDrivenProperty(v8Spec["paint_fill"]["fill-outline-color"]), + "fill-translate": new DataConstantProperty(v8Spec["paint_fill"]["fill-translate"]), + "fill-translate-anchor": new DataConstantProperty(v8Spec["paint_fill"]["fill-translate-anchor"]), + "fill-pattern": new CrossFadedDataDrivenProperty(v8Spec["paint_fill"]["fill-pattern"]), +}); +var properties$5 = ({ get paint() { return getPaint$5(); }, get layout() { return getLayout$2(); } }); + +class FillStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$5); + } + recalculate(parameters, availableImages) { + super.recalculate(parameters, availableImages); + const outlineColor = this.paint._values['fill-outline-color']; + if (outlineColor.value.kind === 'constant' && outlineColor.value.value === undefined) { + this.paint._values['fill-outline-color'] = this.paint._values['fill-color']; + } + } + createBucket(parameters) { + return new FillBucket(parameters); + } + queryRadius() { + return translateDistance(this.paint.get('fill-translate')); + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits) { + const translatedPolygon = translate$4(queryGeometry, this.paint.get('fill-translate'), this.paint.get('fill-translate-anchor'), transform.angle, pixelsToTileUnits); + return polygonIntersectsMultiPolygon(translatedPolygon, geometry); + } + isTileClipped() { + return true; + } +} + +const layout$2 = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' }, + { name: 'a_normal_ed', components: 4, type: 'Int16' }, +], 4); +const centroidAttributes = createLayout([ + { name: 'a_centroid', components: 2, type: 'Int16' } +], 4); +const { members: members$2, size: size$2, alignment: alignment$2 } = layout$2; + +var vectorTile = {}; + +'use strict'; + +var Point$1 = pointGeometry; + +var vectortilefeature = VectorTileFeature$3; + +function VectorTileFeature$3(pbf, end, extent, keys, values) { + // Public + this.properties = {}; + this.extent = extent; + this.type = 0; + + // Private + this._pbf = pbf; + this._geometry = -1; + this._keys = keys; + this._values = values; + + pbf.readFields(readFeature, this, end); +} + +function readFeature(tag, feature, pbf) { + if (tag == 1) feature.id = pbf.readVarint(); + else if (tag == 2) readTag(pbf, feature); + else if (tag == 3) feature.type = pbf.readVarint(); + else if (tag == 4) feature._geometry = pbf.pos; +} + +function readTag(pbf, feature) { + var end = pbf.readVarint() + pbf.pos; + + while (pbf.pos < end) { + var key = feature._keys[pbf.readVarint()], + value = feature._values[pbf.readVarint()]; + feature.properties[key] = value; + } +} + +VectorTileFeature$3.types = ['Unknown', 'Point', 'LineString', 'Polygon']; + +VectorTileFeature$3.prototype.loadGeometry = function() { + var pbf = this._pbf; + pbf.pos = this._geometry; + + var end = pbf.readVarint() + pbf.pos, + cmd = 1, + length = 0, + x = 0, + y = 0, + lines = [], + line; + + while (pbf.pos < end) { + if (length <= 0) { + var cmdLen = pbf.readVarint(); + cmd = cmdLen & 0x7; + length = cmdLen >> 3; + } + + length--; + + if (cmd === 1 || cmd === 2) { + x += pbf.readSVarint(); + y += pbf.readSVarint(); + + if (cmd === 1) { // moveTo + if (line) lines.push(line); + line = []; + } + + line.push(new Point$1(x, y)); + + } else if (cmd === 7) { + + // Workaround for https://github.com/mapbox/mapnik-vector-tile/issues/90 + if (line) { + line.push(line[0].clone()); // closePolygon + } + + } else { + throw new Error('unknown command ' + cmd); + } + } + + if (line) lines.push(line); + + return lines; +}; + +VectorTileFeature$3.prototype.bbox = function() { + var pbf = this._pbf; + pbf.pos = this._geometry; + + var end = pbf.readVarint() + pbf.pos, + cmd = 1, + length = 0, + x = 0, + y = 0, + x1 = Infinity, + x2 = -Infinity, + y1 = Infinity, + y2 = -Infinity; + + while (pbf.pos < end) { + if (length <= 0) { + var cmdLen = pbf.readVarint(); + cmd = cmdLen & 0x7; + length = cmdLen >> 3; + } + + length--; + + if (cmd === 1 || cmd === 2) { + x += pbf.readSVarint(); + y += pbf.readSVarint(); + if (x < x1) x1 = x; + if (x > x2) x2 = x; + if (y < y1) y1 = y; + if (y > y2) y2 = y; + + } else if (cmd !== 7) { + throw new Error('unknown command ' + cmd); + } + } + + return [x1, y1, x2, y2]; +}; + +VectorTileFeature$3.prototype.toGeoJSON = function(x, y, z) { + var size = this.extent * Math.pow(2, z), + x0 = this.extent * x, + y0 = this.extent * y, + coords = this.loadGeometry(), + type = VectorTileFeature$3.types[this.type], + i, j; + + function project(line) { + for (var j = 0; j < line.length; j++) { + var p = line[j], y2 = 180 - (p.y + y0) * 360 / size; + line[j] = [ + (p.x + x0) * 360 / size - 180, + 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90 + ]; + } + } + + switch (this.type) { + case 1: + var points = []; + for (i = 0; i < coords.length; i++) { + points[i] = coords[i][0]; + } + coords = points; + project(coords); + break; + + case 2: + for (i = 0; i < coords.length; i++) { + project(coords[i]); + } + break; + + case 3: + coords = classifyRings(coords); + for (i = 0; i < coords.length; i++) { + for (j = 0; j < coords[i].length; j++) { + project(coords[i][j]); + } + } + break; + } + + if (coords.length === 1) { + coords = coords[0]; + } else { + type = 'Multi' + type; + } + + var result = { + type: "Feature", + geometry: { + type: type, + coordinates: coords + }, + properties: this.properties + }; + + if ('id' in this) { + result.id = this.id; + } + + return result; +}; + +// classifies an array of rings into polygons with outer rings and holes + +function classifyRings(rings) { + var len = rings.length; + + if (len <= 1) return [rings]; + + var polygons = [], + polygon, + ccw; + + for (var i = 0; i < len; i++) { + var area = signedArea(rings[i]); + if (area === 0) continue; + + if (ccw === undefined) ccw = area < 0; + + if (ccw === area < 0) { + if (polygon) polygons.push(polygon); + polygon = [rings[i]]; + + } else { + polygon.push(rings[i]); + } + } + if (polygon) polygons.push(polygon); + + return polygons; +} + +function signedArea(ring) { + var sum = 0; + for (var i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + return sum; +} + +var vectortilefeature$1 = /*@__PURE__*/getDefaultExportFromCjs$1(vectortilefeature); + +'use strict'; + +var VectorTileFeature$2 = vectortilefeature; + +var vectortilelayer = VectorTileLayer$2; + +function VectorTileLayer$2(pbf, end) { + // Public + this.version = 1; + this.name = null; + this.extent = 4096; + this.length = 0; + + // Private + this._pbf = pbf; + this._keys = []; + this._values = []; + this._features = []; + + pbf.readFields(readLayer, this, end); + + this.length = this._features.length; +} + +function readLayer(tag, layer, pbf) { + if (tag === 15) layer.version = pbf.readVarint(); + else if (tag === 1) layer.name = pbf.readString(); + else if (tag === 5) layer.extent = pbf.readVarint(); + else if (tag === 2) layer._features.push(pbf.pos); + else if (tag === 3) layer._keys.push(pbf.readString()); + else if (tag === 4) layer._values.push(readValueMessage(pbf)); +} + +function readValueMessage(pbf) { + var value = null, + end = pbf.readVarint() + pbf.pos; + + while (pbf.pos < end) { + var tag = pbf.readVarint() >> 3; + + value = tag === 1 ? pbf.readString() : + tag === 2 ? pbf.readFloat() : + tag === 3 ? pbf.readDouble() : + tag === 4 ? pbf.readVarint64() : + tag === 5 ? pbf.readVarint() : + tag === 6 ? pbf.readSVarint() : + tag === 7 ? pbf.readBoolean() : null; + } + + return value; +} + +// return feature `i` from this layer as a `VectorTileFeature` +VectorTileLayer$2.prototype.feature = function(i) { + if (i < 0 || i >= this._features.length) throw new Error('feature index out of bounds'); + + this._pbf.pos = this._features[i]; + + var end = this._pbf.readVarint() + this._pbf.pos; + return new VectorTileFeature$2(this._pbf, end, this.extent, this._keys, this._values); +}; + +var vectortilelayer$1 = /*@__PURE__*/getDefaultExportFromCjs$1(vectortilelayer); + +'use strict'; + +var VectorTileLayer$1 = vectortilelayer; + +var vectortile = VectorTile$1; + +function VectorTile$1(pbf, end) { + this.layers = pbf.readFields(readTile, {}, end); +} + +function readTile(tag, layers, pbf) { + if (tag === 3) { + var layer = new VectorTileLayer$1(pbf, pbf.readVarint() + pbf.pos); + if (layer.length) layers[layer.name] = layer; + } +} + +var vectortile$1 = /*@__PURE__*/getDefaultExportFromCjs$1(vectortile); + +var VectorTile = vectorTile.VectorTile = vectortile; +var VectorTileFeature$1 = vectorTile.VectorTileFeature = vectortilefeature; +var VectorTileLayer = vectorTile.VectorTileLayer = vectortilelayer; + +const vectorTileFeatureTypes$2 = vectorTile.VectorTileFeature.types; +const EARCUT_MAX_RINGS = 500; +const FACTOR = Math.pow(2, 13); +function addVertex$1(vertexArray, x, y, nx, ny, nz, t, e) { + vertexArray.emplaceBack( + // a_pos + x, y, + // a_normal_ed: 3-component normal and 1-component edgedistance + Math.floor(nx * FACTOR) * 2 + t, ny * FACTOR * 2, nz * FACTOR * 2, + // edgedistance (used for wrapping patterns around extrusion sides) + Math.round(e)); +} +class FillExtrusionBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.layoutVertexArray = new FillExtrusionLayoutArray(); + this.centroidVertexArray = new PosArray(); + this.indexArray = new TriangleIndexArray(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.segments = new SegmentVector(); + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + this.features = []; + this.hasPattern = hasPattern('fill-extrusion', this.layers, options); + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const bucketFeature = { + id, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + properties: feature.properties, + type: feature.type, + patterns: {} + }; + if (this.hasPattern) { + this.features.push(addPatternDependencies('fill-extrusion', this.layers, bucketFeature, this.zoom, options)); + } + else { + this.addFeature(bucketFeature, bucketFeature.geometry, index, canonical, {}); + } + options.featureIndex.insert(feature, bucketFeature.geometry, index, sourceLayerIndex, this.index, true); + } + } + addFeatures(options, canonical, imagePositions) { + for (const feature of this.features) { + const { geometry } = feature; + this.addFeature(feature, geometry, feature.index, canonical, imagePositions); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + isEmpty() { + return this.layoutVertexArray.length === 0 && this.centroidVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$2); + this.centroidVertexBuffer = context.createVertexBuffer(this.centroidVertexArray, centroidAttributes.members, true); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + this.centroidVertexBuffer.destroy(); + } + addFeature(feature, geometry, index, canonical, imagePositions) { + for (const polygon of classifyRings$1(geometry, EARCUT_MAX_RINGS)) { + const centroid = { x: 0, y: 0, vertexCount: 0 }; + let numVertices = 0; + for (const ring of polygon) { + numVertices += ring.length; + } + let segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray); + for (const ring of polygon) { + if (ring.length === 0) { + continue; + } + if (isEntirelyOutside(ring)) { + continue; + } + let edgeDistance = 0; + for (let p = 0; p < ring.length; p++) { + const p1 = ring[p]; + if (p >= 1) { + const p2 = ring[p - 1]; + if (!isBoundaryEdge(p1, p2)) { + if (segment.vertexLength + 4 > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) { + segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray); + } + const perp = p1.sub(p2)._perp()._unit(); + const dist = p2.dist(p1); + if (edgeDistance + dist > 32768) + edgeDistance = 0; + addVertex$1(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 0, edgeDistance); + addVertex$1(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 1, edgeDistance); + centroid.x += 2 * p1.x; + centroid.y += 2 * p1.y; + centroid.vertexCount += 2; + edgeDistance += dist; + addVertex$1(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 0, edgeDistance); + addVertex$1(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 1, edgeDistance); + centroid.x += 2 * p2.x; + centroid.y += 2 * p2.y; + centroid.vertexCount += 2; + const bottomRight = segment.vertexLength; + // ┌──────┐ + // │ 0 1 │ Counter-clockwise winding order. + // │ │ Triangle 1: 0 => 2 => 1 + // │ 2 3 │ Triangle 2: 1 => 2 => 3 + // └──────┘ + this.indexArray.emplaceBack(bottomRight, bottomRight + 2, bottomRight + 1); + this.indexArray.emplaceBack(bottomRight + 1, bottomRight + 2, bottomRight + 3); + segment.vertexLength += 4; + segment.primitiveLength += 2; + } + } + } + } + if (segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) { + segment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray); + } + //Only triangulate and draw the area of the feature if it is a polygon + //Other feature types (e.g. LineString) do not have area, so triangulation is pointless / undefined + if (vectorTileFeatureTypes$2[feature.type] !== 'Polygon') + continue; + const flattened = []; + const holeIndices = []; + const triangleIndex = segment.vertexLength; + for (const ring of polygon) { + if (ring.length === 0) { + continue; + } + if (ring !== polygon[0]) { + holeIndices.push(flattened.length / 2); + } + for (let i = 0; i < ring.length; i++) { + const p = ring[i]; + addVertex$1(this.layoutVertexArray, p.x, p.y, 0, 0, 1, 1, 0); + centroid.x += p.x; + centroid.y += p.y; + centroid.vertexCount += 1; + flattened.push(p.x); + flattened.push(p.y); + } + } + const indices = earcut(flattened, holeIndices); + for (let j = 0; j < indices.length; j += 3) { + // Counter-clockwise winding order. + this.indexArray.emplaceBack(triangleIndex + indices[j], triangleIndex + indices[j + 2], triangleIndex + indices[j + 1]); + } + segment.primitiveLength += indices.length / 3; + segment.vertexLength += numVertices; + // remember polygon centroid to calculate elevation in GPU + for (let i = 0; i < centroid.vertexCount; i++) { + const averageX = Math.floor(centroid.x / centroid.vertexCount); + const averageY = Math.floor(centroid.y / centroid.vertexCount); + this.centroidVertexArray.emplaceBack(averageX, averageY); + } + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical); + } +} +register('FillExtrusionBucket', FillExtrusionBucket, { omit: ['layers', 'features'] }); +function isBoundaryEdge(p1, p2) { + return (p1.x === p2.x && (p1.x < 0 || p1.x > EXTENT)) || + (p1.y === p2.y && (p1.y < 0 || p1.y > EXTENT)); +} +function isEntirelyOutside(ring) { + return ring.every(p => p.x < 0) || + ring.every(p => p.x > EXTENT) || + ring.every(p => p.y < 0) || + ring.every(p => p.y > EXTENT); +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$4; +const getPaint$4 = () => paint$4 = paint$4 || new Properties({ + "fill-extrusion-opacity": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-opacity"]), + "fill-extrusion-color": new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-color"]), + "fill-extrusion-translate": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-translate"]), + "fill-extrusion-translate-anchor": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]), + "fill-extrusion-pattern": new CrossFadedDataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-pattern"]), + "fill-extrusion-height": new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-height"]), + "fill-extrusion-base": new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-base"]), + "fill-extrusion-vertical-gradient": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"]), +}); +var properties$4 = ({ get paint() { return getPaint$4(); } }); + +class Point3D extends Point$3 { +} +class FillExtrusionStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$4); + } + createBucket(parameters) { + return new FillExtrusionBucket(parameters); + } + queryRadius() { + return translateDistance(this.paint.get('fill-extrusion-translate')); + } + is3D() { + return true; + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits, pixelPosMatrix) { + const translatedPolygon = translate$4(queryGeometry, this.paint.get('fill-extrusion-translate'), this.paint.get('fill-extrusion-translate-anchor'), transform.angle, pixelsToTileUnits); + const height = this.paint.get('fill-extrusion-height').evaluate(feature, featureState); + const base = this.paint.get('fill-extrusion-base').evaluate(feature, featureState); + const projectedQueryGeometry = projectQueryGeometry(translatedPolygon, pixelPosMatrix, transform, 0); + const projected = projectExtrusion(geometry, base, height, pixelPosMatrix); + const projectedBase = projected[0]; + const projectedTop = projected[1]; + return checkIntersection(projectedBase, projectedTop, projectedQueryGeometry); + } +} +function dot(a, b) { + return a.x * b.x + a.y * b.y; +} +function getIntersectionDistance(projectedQueryGeometry, projectedFace) { + if (projectedQueryGeometry.length === 1) { + // For point queries calculate the z at which the point intersects the face + // using barycentric coordinates. + // Find the barycentric coordinates of the projected point within the first + // triangle of the face, using only the xy plane. It doesn't matter if the + // point is outside the first triangle because all the triangles in the face + // are in the same plane. + // + // Check whether points are coincident and use other points if they are. + let i = 0; + const a = projectedFace[i++]; + let b; + while (!b || a.equals(b)) { + b = projectedFace[i++]; + if (!b) + return Infinity; + } + // Loop until point `c` is not colinear with points `a` and `b`. + for (; i < projectedFace.length; i++) { + const c = projectedFace[i]; + const p = projectedQueryGeometry[0]; + const ab = b.sub(a); + const ac = c.sub(a); + const ap = p.sub(a); + const dotABAB = dot(ab, ab); + const dotABAC = dot(ab, ac); + const dotACAC = dot(ac, ac); + const dotAPAB = dot(ap, ab); + const dotAPAC = dot(ap, ac); + const denom = dotABAB * dotACAC - dotABAC * dotABAC; + const v = (dotACAC * dotAPAB - dotABAC * dotAPAC) / denom; + const w = (dotABAB * dotAPAC - dotABAC * dotAPAB) / denom; + const u = 1 - v - w; + // Use the barycentric weighting along with the original triangle z coordinates to get the point of intersection. + const distance = a.z * u + b.z * v + c.z * w; + if (isFinite(distance)) + return distance; + } + return Infinity; + } + else { + // The counts as closest is less clear when the query is a box. This + // returns the distance to the nearest point on the face, whether it is + // within the query or not. It could be more correct to return the + // distance to the closest point within the query box but this would be + // more complicated and expensive to calculate with little benefit. + let closestDistance = Infinity; + for (const p of projectedFace) { + closestDistance = Math.min(closestDistance, p.z); + } + return closestDistance; + } +} +function checkIntersection(projectedBase, projectedTop, projectedQueryGeometry) { + let closestDistance = Infinity; + if (polygonIntersectsMultiPolygon(projectedQueryGeometry, projectedTop)) { + closestDistance = getIntersectionDistance(projectedQueryGeometry, projectedTop[0]); + } + for (let r = 0; r < projectedTop.length; r++) { + const ringTop = projectedTop[r]; + const ringBase = projectedBase[r]; + for (let p = 0; p < ringTop.length - 1; p++) { + const topA = ringTop[p]; + const topB = ringTop[p + 1]; + const baseA = ringBase[p]; + const baseB = ringBase[p + 1]; + const face = [topA, topB, baseB, baseA, topA]; + if (polygonIntersectsPolygon(projectedQueryGeometry, face)) { + closestDistance = Math.min(closestDistance, getIntersectionDistance(projectedQueryGeometry, face)); + } + } + } + return closestDistance === Infinity ? false : closestDistance; +} +/* + * Project the geometry using matrix `m`. This is essentially doing + * `vec4.transformMat4([], [p.x, p.y, z, 1], m)` but the multiplication + * is inlined so that parts of the projection that are the same across + * different points can only be done once. This produced a measurable + * performance improvement. + */ +function projectExtrusion(geometry, zBase, zTop, m) { + const projectedBase = []; + const projectedTop = []; + const baseXZ = m[8] * zBase; + const baseYZ = m[9] * zBase; + const baseZZ = m[10] * zBase; + const baseWZ = m[11] * zBase; + const topXZ = m[8] * zTop; + const topYZ = m[9] * zTop; + const topZZ = m[10] * zTop; + const topWZ = m[11] * zTop; + for (const r of geometry) { + const ringBase = []; + const ringTop = []; + for (const p of r) { + const x = p.x; + const y = p.y; + const sX = m[0] * x + m[4] * y + m[12]; + const sY = m[1] * x + m[5] * y + m[13]; + const sZ = m[2] * x + m[6] * y + m[14]; + const sW = m[3] * x + m[7] * y + m[15]; + const baseX = sX + baseXZ; + const baseY = sY + baseYZ; + const baseZ = sZ + baseZZ; + const baseW = sW + baseWZ; + const topX = sX + topXZ; + const topY = sY + topYZ; + const topZ = sZ + topZZ; + const topW = sW + topWZ; + const b = new Point$3(baseX / baseW, baseY / baseW); + b.z = baseZ / baseW; + ringBase.push(b); + const t = new Point$3(topX / topW, topY / topW); + t.z = topZ / topW; + ringTop.push(t); + } + projectedBase.push(ringBase); + projectedTop.push(ringTop); + } + return [projectedBase, projectedTop]; +} +function projectQueryGeometry(queryGeometry, pixelPosMatrix, transform, z) { + const projectedQueryGeometry = []; + for (const p of queryGeometry) { + const v = [p.x, p.y, z, 1]; + transformMat4$1(v, v, pixelPosMatrix); + projectedQueryGeometry.push(new Point$3(v[0] / v[3], v[1] / v[3])); + } + return projectedQueryGeometry; +} + +const lineLayoutAttributes = createLayout([ + { name: 'a_pos_normal', components: 2, type: 'Int16' }, + { name: 'a_data', components: 4, type: 'Uint8' } +], 4); +const { members: members$1, size: size$1, alignment: alignment$1 } = lineLayoutAttributes; + +const lineLayoutAttributesExt = createLayout([ + { name: 'a_uv_x', components: 1, type: 'Float32' }, + { name: 'a_split_index', components: 1, type: 'Float32' }, +]); +const { members, size, alignment } = lineLayoutAttributesExt; + +const vectorTileFeatureTypes$1 = vectorTile.VectorTileFeature.types; +// NOTE ON EXTRUDE SCALE: +// scale the extrusion vector so that the normal length is this value. +// contains the "texture" normals (-1..1). this is distinct from the extrude +// normals for line joins, because the x-value remains 0 for the texture +// normal array, while the extrude normal actually moves the vertex to create +// the acute/bevelled line join. +const EXTRUDE_SCALE = 63; +/* + * Sharp corners cause dashed lines to tilt because the distance along the line + * is the same at both the inner and outer corners. To improve the appearance of + * dashed lines we add extra points near sharp corners so that a smaller part + * of the line is tilted. + * + * COS_HALF_SHARP_CORNER controls how sharp a corner has to be for us to add an + * extra vertex. The default is 75 degrees. + * + * The newly created vertices are placed SHARP_CORNER_OFFSET pixels from the corner. + */ +const COS_HALF_SHARP_CORNER = Math.cos(75 / 2 * (Math.PI / 180)); +const SHARP_CORNER_OFFSET = 15; +// Angle per triangle for approximating round line joins. +const DEG_PER_TRIANGLE = 20; +// The number of bits that is used to store the line distance in the buffer. +const LINE_DISTANCE_BUFFER_BITS = 15; +// We don't have enough bits for the line distance as we'd like to have, so +// use this value to scale the line distance (in tile units) down to a smaller +// value. This lets us store longer distances while sacrificing precision. +const LINE_DISTANCE_SCALE = 1 / 2; +// The maximum line distance, in tile units, that fits in the buffer. +const MAX_LINE_DISTANCE = Math.pow(2, LINE_DISTANCE_BUFFER_BITS - 1) / LINE_DISTANCE_SCALE; +/** + * @internal + * Line bucket class + */ +class LineBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.patternFeatures = []; + this.lineClipsArray = []; + this.gradients = {}; + this.layers.forEach(layer => { + this.gradients[layer.id] = {}; + }); + this.layoutVertexArray = new LineLayoutArray(); + this.layoutVertexArray2 = new LineExtLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.segments = new SegmentVector(); + this.maxLineLength = 0; + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + this.hasPattern = hasPattern('line', this.layers, options); + const lineSortKey = this.layers[0].layout.get('line-sort-key'); + const sortFeaturesByKey = !lineSortKey.isConstant(); + const bucketFeatures = []; + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const sortKey = sortFeaturesByKey ? + lineSortKey.evaluate(evaluationFeature, {}, canonical) : + undefined; + const bucketFeature = { + id, + properties: feature.properties, + type: feature.type, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + patterns: {}, + sortKey + }; + bucketFeatures.push(bucketFeature); + } + if (sortFeaturesByKey) { + bucketFeatures.sort((a, b) => { + return (a.sortKey) - (b.sortKey); + }); + } + for (const bucketFeature of bucketFeatures) { + const { geometry, index, sourceLayerIndex } = bucketFeature; + if (this.hasPattern) { + const patternBucketFeature = addPatternDependencies('line', this.layers, bucketFeature, this.zoom, options); + // pattern features are added only once the pattern is loaded into the image atlas + // so are stored during populate until later updated with positions by tile worker in addFeatures + this.patternFeatures.push(patternBucketFeature); + } + else { + this.addFeature(bucketFeature, geometry, index, canonical, {}); + } + const feature = features[index].feature; + options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + addFeatures(options, canonical, imagePositions) { + for (const feature of this.patternFeatures) { + this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions); + } + } + isEmpty() { + return this.layoutVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + if (this.layoutVertexArray2.length !== 0) { + this.layoutVertexBuffer2 = context.createVertexBuffer(this.layoutVertexArray2, members); + } + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$1); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + } + lineFeatureClips(feature) { + if (!!feature.properties && Object.prototype.hasOwnProperty.call(feature.properties, 'mapbox_clip_start') && Object.prototype.hasOwnProperty.call(feature.properties, 'mapbox_clip_end')) { + const start = +feature.properties['mapbox_clip_start']; + const end = +feature.properties['mapbox_clip_end']; + return { start, end }; + } + } + addFeature(feature, geometry, index, canonical, imagePositions) { + const layout = this.layers[0].layout; + const join = layout.get('line-join').evaluate(feature, {}); + const cap = layout.get('line-cap'); + const miterLimit = layout.get('line-miter-limit'); + const roundLimit = layout.get('line-round-limit'); + this.lineClips = this.lineFeatureClips(feature); + for (const line of geometry) { + this.addLine(line, feature, join, cap, miterLimit, roundLimit); + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical); + } + addLine(vertices, feature, join, cap, miterLimit, roundLimit) { + this.distance = 0; + this.scaledDistance = 0; + this.totalDistance = 0; + if (this.lineClips) { + this.lineClipsArray.push(this.lineClips); + // Calculate the total distance, in tile units, of this tiled line feature + for (let i = 0; i < vertices.length - 1; i++) { + this.totalDistance += vertices[i].dist(vertices[i + 1]); + } + this.updateScaledDistance(); + this.maxLineLength = Math.max(this.maxLineLength, this.totalDistance); + } + const isPolygon = vectorTileFeatureTypes$1[feature.type] === 'Polygon'; + // If the line has duplicate vertices at the ends, adjust start/length to remove them. + let len = vertices.length; + while (len >= 2 && vertices[len - 1].equals(vertices[len - 2])) { + len--; + } + let first = 0; + while (first < len - 1 && vertices[first].equals(vertices[first + 1])) { + first++; + } + // Ignore invalid geometry. + if (len < (isPolygon ? 3 : 2)) + return; + if (join === 'bevel') + miterLimit = 1.05; + const sharpCornerOffset = this.overscaling <= 16 ? + SHARP_CORNER_OFFSET * EXTENT / (512 * this.overscaling) : + 0; + // we could be more precise, but it would only save a negligible amount of space + const segment = this.segments.prepareSegment(len * 10, this.layoutVertexArray, this.indexArray); + let currentVertex; + let prevVertex; + let nextVertex; + let prevNormal; + let nextNormal; + // the last two vertices added + this.e1 = this.e2 = -1; + if (isPolygon) { + currentVertex = vertices[len - 2]; + nextNormal = vertices[first].sub(currentVertex)._unit()._perp(); + } + for (let i = first; i < len; i++) { + nextVertex = i === len - 1 ? + (isPolygon ? vertices[first + 1] : undefined) : // if it's a polygon, treat the last vertex like the first + vertices[i + 1]; // just the next vertex + // if two consecutive vertices exist, skip the current one + if (nextVertex && vertices[i].equals(nextVertex)) + continue; + if (nextNormal) + prevNormal = nextNormal; + if (currentVertex) + prevVertex = currentVertex; + currentVertex = vertices[i]; + // Calculate the normal towards the next vertex in this line. In case + // there is no next vertex, pretend that the line is continuing straight, + // meaning that we are just using the previous normal. + nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal; + // If we still don't have a previous normal, this is the beginning of a + // non-closed line, so we're doing a straight "join". + prevNormal = prevNormal || nextNormal; + // Determine the normal of the join extrusion. It is the angle bisector + // of the segments between the previous line and the next line. + // In the case of 180° angles, the prev and next normals cancel each other out: + // prevNormal + nextNormal = (0, 0), its magnitude is 0, so the unit vector would be + // undefined. In that case, we're keeping the joinNormal at (0, 0), so that the cosHalfAngle + // below will also become 0 and miterLength will become Infinity. + let joinNormal = prevNormal.add(nextNormal); + if (joinNormal.x !== 0 || joinNormal.y !== 0) { + joinNormal._unit(); + } + /* joinNormal prevNormal + * ↖ ↑ + * .________. prevVertex + * | + * nextNormal ← | currentVertex + * | + * nextVertex ! + * + */ + // calculate cosines of the angle (and its half) using dot product + const cosAngle = prevNormal.x * nextNormal.x + prevNormal.y * nextNormal.y; + const cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y; + // Calculate the length of the miter (the ratio of the miter to the width) + // as the inverse of cosine of the angle between next and join normals + const miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity; + // approximate angle from cosine + const approxAngle = 2 * Math.sqrt(2 - 2 * cosHalfAngle); + const isSharpCorner = cosHalfAngle < COS_HALF_SHARP_CORNER && prevVertex && nextVertex; + const lineTurnsLeft = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0; + if (isSharpCorner && i > first) { + const prevSegmentLength = currentVertex.dist(prevVertex); + if (prevSegmentLength > 2 * sharpCornerOffset) { + const newPrevVertex = currentVertex.sub(currentVertex.sub(prevVertex)._mult(sharpCornerOffset / prevSegmentLength)._round()); + this.updateDistance(prevVertex, newPrevVertex); + this.addCurrentVertex(newPrevVertex, prevNormal, 0, 0, segment); + prevVertex = newPrevVertex; + } + } + // The join if a middle vertex, otherwise the cap. + const middleVertex = prevVertex && nextVertex; + let currentJoin = middleVertex ? join : isPolygon ? 'butt' : cap; + if (middleVertex && currentJoin === 'round') { + if (miterLength < roundLimit) { + currentJoin = 'miter'; + } + else if (miterLength <= 2) { + currentJoin = 'fakeround'; + } + } + if (currentJoin === 'miter' && miterLength > miterLimit) { + currentJoin = 'bevel'; + } + if (currentJoin === 'bevel') { + // The maximum extrude length is 128 / 63 = 2 times the width of the line + // so if miterLength >= 2 we need to draw a different type of bevel here. + if (miterLength > 2) + currentJoin = 'flipbevel'; + // If the miterLength is really small and the line bevel wouldn't be visible, + // just draw a miter join to save a triangle. + if (miterLength < miterLimit) + currentJoin = 'miter'; + } + // Calculate how far along the line the currentVertex is + if (prevVertex) + this.updateDistance(prevVertex, currentVertex); + if (currentJoin === 'miter') { + joinNormal._mult(miterLength); + this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); + } + else if (currentJoin === 'flipbevel') { + // miter is too big, flip the direction to make a beveled join + if (miterLength > 100) { + // Almost parallel lines + joinNormal = nextNormal.mult(-1); + } + else { + const bevelLength = miterLength * prevNormal.add(nextNormal).mag() / prevNormal.sub(nextNormal).mag(); + joinNormal._perp()._mult(bevelLength * (lineTurnsLeft ? -1 : 1)); + } + this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); + this.addCurrentVertex(currentVertex, joinNormal.mult(-1), 0, 0, segment); + } + else if (currentJoin === 'bevel' || currentJoin === 'fakeround') { + const offset = -Math.sqrt(miterLength * miterLength - 1); + const offsetA = lineTurnsLeft ? offset : 0; + const offsetB = lineTurnsLeft ? 0 : offset; + // Close previous segment with a bevel + if (prevVertex) { + this.addCurrentVertex(currentVertex, prevNormal, offsetA, offsetB, segment); + } + if (currentJoin === 'fakeround') { + // The join angle is sharp enough that a round join would be visible. + // Bevel joins fill the gap between segments with a single pie slice triangle. + // Create a round join by adding multiple pie slices. The join isn't actually round, but + // it looks like it is at the sizes we render lines at. + // pick the number of triangles for approximating round join by based on the angle between normals + const n = Math.round((approxAngle * 180 / Math.PI) / DEG_PER_TRIANGLE); + for (let m = 1; m < n; m++) { + let t = m / n; + if (t !== 0.5) { + // approximate spherical interpolation https://observablehq.com/@mourner/approximating-geometric-slerp + const t2 = t - 0.5; + const A = 1.0904 + cosAngle * (-3.2452 + cosAngle * (3.55645 - cosAngle * 1.43519)); + const B = 0.848013 + cosAngle * (-1.06021 + cosAngle * 0.215638); + t = t + t * t2 * (t - 1) * (A * t2 * t2 + B); + } + const extrude = nextNormal.sub(prevNormal)._mult(t)._add(prevNormal)._unit()._mult(lineTurnsLeft ? -1 : 1); + this.addHalfVertex(currentVertex, extrude.x, extrude.y, false, lineTurnsLeft, 0, segment); + } + } + if (nextVertex) { + // Start next segment + this.addCurrentVertex(currentVertex, nextNormal, -offsetA, -offsetB, segment); + } + } + else if (currentJoin === 'butt') { + this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); // butt cap + } + else if (currentJoin === 'square') { + const offset = prevVertex ? 1 : -1; // closing or starting square cap + this.addCurrentVertex(currentVertex, joinNormal, offset, offset, segment); + } + else if (currentJoin === 'round') { + if (prevVertex) { + // Close previous segment with butt + this.addCurrentVertex(currentVertex, prevNormal, 0, 0, segment); + // Add round cap or linejoin at end of segment + this.addCurrentVertex(currentVertex, prevNormal, 1, 1, segment, true); + } + if (nextVertex) { + // Add round cap before first segment + this.addCurrentVertex(currentVertex, nextNormal, -1, -1, segment, true); + // Start next segment with a butt + this.addCurrentVertex(currentVertex, nextNormal, 0, 0, segment); + } + } + if (isSharpCorner && i < len - 1) { + const nextSegmentLength = currentVertex.dist(nextVertex); + if (nextSegmentLength > 2 * sharpCornerOffset) { + const newCurrentVertex = currentVertex.add(nextVertex.sub(currentVertex)._mult(sharpCornerOffset / nextSegmentLength)._round()); + this.updateDistance(currentVertex, newCurrentVertex); + this.addCurrentVertex(newCurrentVertex, nextNormal, 0, 0, segment); + currentVertex = newCurrentVertex; + } + } + } + } + /** + * Add two vertices to the buffers. + * + * @param p - the line vertex to add buffer vertices for + * @param normal - vertex normal + * @param endLeft - extrude to shift the left vertex along the line + * @param endRight - extrude to shift the left vertex along the line + * @param segment - the segment object to add the vertex to + * @param round - whether this is a round cap + */ + addCurrentVertex(p, normal, endLeft, endRight, segment, round = false) { + // left and right extrude vectors, perpendicularly shifted by endLeft/endRight + const leftX = normal.x + normal.y * endLeft; + const leftY = normal.y - normal.x * endLeft; + const rightX = -normal.x + normal.y * endRight; + const rightY = -normal.y - normal.x * endRight; + this.addHalfVertex(p, leftX, leftY, round, false, endLeft, segment); + this.addHalfVertex(p, rightX, rightY, round, true, -endRight, segment); + // There is a maximum "distance along the line" that we can store in the buffers. + // When we get close to the distance, reset it to zero and add the vertex again with + // a distance of zero. The max distance is determined by the number of bits we allocate + // to `linesofar`. + if (this.distance > MAX_LINE_DISTANCE / 2 && this.totalDistance === 0) { + this.distance = 0; + this.updateScaledDistance(); + this.addCurrentVertex(p, normal, endLeft, endRight, segment, round); + } + } + addHalfVertex({ x, y }, extrudeX, extrudeY, round, up, dir, segment) { + const totalDistance = this.lineClips ? this.scaledDistance * (MAX_LINE_DISTANCE - 1) : this.scaledDistance; + // scale down so that we can store longer distances while sacrificing precision. + const linesofarScaled = totalDistance * LINE_DISTANCE_SCALE; + this.layoutVertexArray.emplaceBack( + // a_pos_normal + // Encode round/up the least significant bits + (x << 1) + (round ? 1 : 0), (y << 1) + (up ? 1 : 0), + // a_data + // add 128 to store a byte in an unsigned byte + Math.round(EXTRUDE_SCALE * extrudeX) + 128, Math.round(EXTRUDE_SCALE * extrudeY) + 128, + // Encode the -1/0/1 direction value into the first two bits of .z of a_data. + // Combine it with the lower 6 bits of `linesofarScaled` (shifted by 2 bits to make + // room for the direction value). The upper 8 bits of `linesofarScaled` are placed in + // the `w` component. + ((dir === 0 ? 0 : (dir < 0 ? -1 : 1)) + 1) | ((linesofarScaled & 0x3F) << 2), linesofarScaled >> 6); + // Constructs a second vertex buffer with higher precision line progress + if (this.lineClips) { + const progressRealigned = this.scaledDistance - this.lineClips.start; + const endClipRealigned = this.lineClips.end - this.lineClips.start; + const uvX = progressRealigned / endClipRealigned; + this.layoutVertexArray2.emplaceBack(uvX, this.lineClipsArray.length); + } + const e = segment.vertexLength++; + if (this.e1 >= 0 && this.e2 >= 0) { + this.indexArray.emplaceBack(this.e1, this.e2, e); + segment.primitiveLength++; + } + if (up) { + this.e2 = e; + } + else { + this.e1 = e; + } + } + updateScaledDistance() { + // Knowing the ratio of the full linestring covered by this tiled feature, as well + // as the total distance (in tile units) of this tiled feature, and the distance + // (in tile units) of the current vertex, we can determine the relative distance + // of this vertex along the full linestring feature and scale it to [0, 2^15) + this.scaledDistance = this.lineClips ? + this.lineClips.start + (this.lineClips.end - this.lineClips.start) * this.distance / this.totalDistance : + this.distance; + } + updateDistance(prev, next) { + this.distance += prev.dist(next); + this.updateScaledDistance(); + } +} +register('LineBucket', LineBucket, { omit: ['layers', 'patternFeatures'] }); + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout$1; +const getLayout$1 = () => layout$1 = layout$1 || new Properties({ + "line-cap": new DataConstantProperty(v8Spec["layout_line"]["line-cap"]), + "line-join": new DataDrivenProperty(v8Spec["layout_line"]["line-join"]), + "line-miter-limit": new DataConstantProperty(v8Spec["layout_line"]["line-miter-limit"]), + "line-round-limit": new DataConstantProperty(v8Spec["layout_line"]["line-round-limit"]), + "line-sort-key": new DataDrivenProperty(v8Spec["layout_line"]["line-sort-key"]), +}); +let paint$3; +const getPaint$3 = () => paint$3 = paint$3 || new Properties({ + "line-opacity": new DataDrivenProperty(v8Spec["paint_line"]["line-opacity"]), + "line-color": new DataDrivenProperty(v8Spec["paint_line"]["line-color"]), + "line-translate": new DataConstantProperty(v8Spec["paint_line"]["line-translate"]), + "line-translate-anchor": new DataConstantProperty(v8Spec["paint_line"]["line-translate-anchor"]), + "line-width": new DataDrivenProperty(v8Spec["paint_line"]["line-width"]), + "line-gap-width": new DataDrivenProperty(v8Spec["paint_line"]["line-gap-width"]), + "line-offset": new DataDrivenProperty(v8Spec["paint_line"]["line-offset"]), + "line-blur": new DataDrivenProperty(v8Spec["paint_line"]["line-blur"]), + "line-dasharray": new CrossFadedProperty(v8Spec["paint_line"]["line-dasharray"]), + "line-pattern": new CrossFadedDataDrivenProperty(v8Spec["paint_line"]["line-pattern"]), + "line-gradient": new ColorRampProperty(v8Spec["paint_line"]["line-gradient"]), +}); +var properties$3 = ({ get paint() { return getPaint$3(); }, get layout() { return getLayout$1(); } }); + +class LineFloorwidthProperty extends DataDrivenProperty { + possiblyEvaluate(value, parameters) { + parameters = new EvaluationParameters(Math.floor(parameters.zoom), { + now: parameters.now, + fadeDuration: parameters.fadeDuration, + zoomHistory: parameters.zoomHistory, + transition: parameters.transition + }); + return super.possiblyEvaluate(value, parameters); + } + evaluate(value, globals, feature, featureState) { + globals = extend$1({}, globals, { zoom: Math.floor(globals.zoom) }); + return super.evaluate(value, globals, feature, featureState); + } +} +let lineFloorwidthProperty; +class LineStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$3); + this.gradientVersion = 0; + if (!lineFloorwidthProperty) { + lineFloorwidthProperty = + new LineFloorwidthProperty(properties$3.paint.properties['line-width'].specification); + lineFloorwidthProperty.useIntegerZoom = true; + } + } + _handleSpecialPaintPropertyUpdate(name) { + if (name === 'line-gradient') { + const expression = this.gradientExpression(); + if (isZoomExpression(expression)) { + this.stepInterpolant = expression._styleExpression.expression instanceof Step; + } + else { + this.stepInterpolant = false; + } + this.gradientVersion = (this.gradientVersion + 1) % Number.MAX_SAFE_INTEGER; + } + } + gradientExpression() { + return this._transitionablePaint._values['line-gradient'].value.expression; + } + recalculate(parameters, availableImages) { + super.recalculate(parameters, availableImages); + this.paint._values['line-floorwidth'] = + lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values['line-width'].value, parameters); + } + createBucket(parameters) { + return new LineBucket(parameters); + } + queryRadius(bucket) { + const lineBucket = bucket; + const width = getLineWidth(getMaximumPaintValue('line-width', this, lineBucket), getMaximumPaintValue('line-gap-width', this, lineBucket)); + const offset = getMaximumPaintValue('line-offset', this, lineBucket); + return width / 2 + Math.abs(offset) + translateDistance(this.paint.get('line-translate')); + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits) { + const translatedPolygon = translate$4(queryGeometry, this.paint.get('line-translate'), this.paint.get('line-translate-anchor'), transform.angle, pixelsToTileUnits); + const halfWidth = pixelsToTileUnits / 2 * getLineWidth(this.paint.get('line-width').evaluate(feature, featureState), this.paint.get('line-gap-width').evaluate(feature, featureState)); + const lineOffset = this.paint.get('line-offset').evaluate(feature, featureState); + if (lineOffset) { + geometry = offsetLine(geometry, lineOffset * pixelsToTileUnits); + } + return polygonIntersectsBufferedMultiLine(translatedPolygon, geometry, halfWidth); + } + isTileClipped() { + return true; + } +} +function getLineWidth(lineWidth, lineGapWidth) { + if (lineGapWidth > 0) { + return lineGapWidth + 2 * lineWidth; + } + else { + return lineWidth; + } +} + +const symbolLayoutAttributes = createLayout([ + { name: 'a_pos_offset', components: 4, type: 'Int16' }, + { name: 'a_data', components: 4, type: 'Uint16' }, + { name: 'a_pixeloffset', components: 4, type: 'Int16' } +], 4); +const dynamicLayoutAttributes = createLayout([ + { name: 'a_projected_pos', components: 3, type: 'Float32' } +], 4); +const placementOpacityAttributes = createLayout([ + { name: 'a_fade_opacity', components: 1, type: 'Uint32' } +], 4); +const collisionVertexAttributes = createLayout([ + { name: 'a_placed', components: 2, type: 'Uint8' }, + { name: 'a_shift', components: 2, type: 'Float32' }, + { name: 'a_box_real', components: 2, type: 'Int16' }, +]); +const collisionBox = createLayout([ + // the box is centered around the anchor point + { type: 'Int16', name: 'anchorPointX' }, + { type: 'Int16', name: 'anchorPointY' }, + // distances to the edges from the anchor + { type: 'Int16', name: 'x1' }, + { type: 'Int16', name: 'y1' }, + { type: 'Int16', name: 'x2' }, + { type: 'Int16', name: 'y2' }, + // the index of the feature in the original vectortile + { type: 'Uint32', name: 'featureIndex' }, + // the source layer the feature appears in + { type: 'Uint16', name: 'sourceLayerIndex' }, + // the bucket the feature appears in + { type: 'Uint16', name: 'bucketIndex' }, +]); +const collisionBoxLayout = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' }, + { name: 'a_anchor_pos', components: 2, type: 'Int16' }, + { name: 'a_extrude', components: 2, type: 'Int16' } +], 4); +const collisionCircleLayout = createLayout([ + { name: 'a_pos', components: 2, type: 'Float32' }, + { name: 'a_radius', components: 1, type: 'Float32' }, + { name: 'a_flags', components: 2, type: 'Int16' } +], 4); +const quadTriangle = createLayout([ + { name: 'triangle', components: 3, type: 'Uint16' }, +]); +const placement = createLayout([ + { type: 'Int16', name: 'anchorX' }, + { type: 'Int16', name: 'anchorY' }, + { type: 'Uint16', name: 'glyphStartIndex' }, + { type: 'Uint16', name: 'numGlyphs' }, + { type: 'Uint32', name: 'vertexStartIndex' }, + { type: 'Uint32', name: 'lineStartIndex' }, + { type: 'Uint32', name: 'lineLength' }, + { type: 'Uint16', name: 'segment' }, + { type: 'Uint16', name: 'lowerSize' }, + { type: 'Uint16', name: 'upperSize' }, + { type: 'Float32', name: 'lineOffsetX' }, + { type: 'Float32', name: 'lineOffsetY' }, + { type: 'Uint8', name: 'writingMode' }, + { type: 'Uint8', name: 'placedOrientation' }, + { type: 'Uint8', name: 'hidden' }, + { type: 'Uint32', name: 'crossTileID' }, + { type: 'Int16', name: 'associatedIconIndex' } +]); +const symbolInstance = createLayout([ + { type: 'Int16', name: 'anchorX' }, + { type: 'Int16', name: 'anchorY' }, + { type: 'Int16', name: 'rightJustifiedTextSymbolIndex' }, + { type: 'Int16', name: 'centerJustifiedTextSymbolIndex' }, + { type: 'Int16', name: 'leftJustifiedTextSymbolIndex' }, + { type: 'Int16', name: 'verticalPlacedTextSymbolIndex' }, + { type: 'Int16', name: 'placedIconSymbolIndex' }, + { type: 'Int16', name: 'verticalPlacedIconSymbolIndex' }, + { type: 'Uint16', name: 'key' }, + { type: 'Uint16', name: 'textBoxStartIndex' }, + { type: 'Uint16', name: 'textBoxEndIndex' }, + { type: 'Uint16', name: 'verticalTextBoxStartIndex' }, + { type: 'Uint16', name: 'verticalTextBoxEndIndex' }, + { type: 'Uint16', name: 'iconBoxStartIndex' }, + { type: 'Uint16', name: 'iconBoxEndIndex' }, + { type: 'Uint16', name: 'verticalIconBoxStartIndex' }, + { type: 'Uint16', name: 'verticalIconBoxEndIndex' }, + { type: 'Uint16', name: 'featureIndex' }, + { type: 'Uint16', name: 'numHorizontalGlyphVertices' }, + { type: 'Uint16', name: 'numVerticalGlyphVertices' }, + { type: 'Uint16', name: 'numIconVertices' }, + { type: 'Uint16', name: 'numVerticalIconVertices' }, + { type: 'Uint16', name: 'useRuntimeCollisionCircles' }, + { type: 'Uint32', name: 'crossTileID' }, + { type: 'Float32', name: 'textBoxScale' }, + { type: 'Float32', name: 'collisionCircleDiameter' }, + { type: 'Uint16', name: 'textAnchorOffsetStartIndex' }, + { type: 'Uint16', name: 'textAnchorOffsetEndIndex' } +]); +const glyphOffset = createLayout([ + { type: 'Float32', name: 'offsetX' } +]); +const lineVertex = createLayout([ + { type: 'Int16', name: 'x' }, + { type: 'Int16', name: 'y' }, + { type: 'Int16', name: 'tileUnitDistanceFromAnchor' } +]); +const textAnchorOffset = createLayout([ + { type: 'Uint16', name: 'textAnchor' }, + { type: 'Float32', components: 2, name: 'textOffset' } +]); + +function transformTextInternal(text, layer, feature) { + const transform = layer.layout.get('text-transform').evaluate(feature, {}); + if (transform === 'uppercase') { + text = text.toLocaleUpperCase(); + } + else if (transform === 'lowercase') { + text = text.toLocaleLowerCase(); + } + if (rtlWorkerPlugin.applyArabicShaping) { + text = rtlWorkerPlugin.applyArabicShaping(text); + } + return text; +} +function transformText(text, layer, feature) { + text.sections.forEach(section => { + section.text = transformTextInternal(section.text, layer, feature); + }); + return text; +} + +function mergeLines(features) { + const leftIndex = {}; + const rightIndex = {}; + const mergedFeatures = []; + let mergedIndex = 0; + function add(k) { + mergedFeatures.push(features[k]); + mergedIndex++; + } + function mergeFromRight(leftKey, rightKey, geom) { + const i = rightIndex[leftKey]; + delete rightIndex[leftKey]; + rightIndex[rightKey] = i; + mergedFeatures[i].geometry[0].pop(); + mergedFeatures[i].geometry[0] = mergedFeatures[i].geometry[0].concat(geom[0]); + return i; + } + function mergeFromLeft(leftKey, rightKey, geom) { + const i = leftIndex[rightKey]; + delete leftIndex[rightKey]; + leftIndex[leftKey] = i; + mergedFeatures[i].geometry[0].shift(); + mergedFeatures[i].geometry[0] = geom[0].concat(mergedFeatures[i].geometry[0]); + return i; + } + function getKey(text, geom, onRight) { + const point = onRight ? geom[0][geom[0].length - 1] : geom[0][0]; + return `${text}:${point.x}:${point.y}`; + } + for (let k = 0; k < features.length; k++) { + const feature = features[k]; + const geom = feature.geometry; + const text = feature.text ? feature.text.toString() : null; + if (!text) { + add(k); + continue; + } + const leftKey = getKey(text, geom), rightKey = getKey(text, geom, true); + if ((leftKey in rightIndex) && (rightKey in leftIndex) && (rightIndex[leftKey] !== leftIndex[rightKey])) { + // found lines with the same text adjacent to both ends of the current line, merge all three + const j = mergeFromLeft(leftKey, rightKey, geom); + const i = mergeFromRight(leftKey, rightKey, mergedFeatures[j].geometry); + delete leftIndex[leftKey]; + delete rightIndex[rightKey]; + rightIndex[getKey(text, mergedFeatures[i].geometry, true)] = i; + mergedFeatures[j].geometry = null; + } + else if (leftKey in rightIndex) { + // found mergeable line adjacent to the start of the current line, merge + mergeFromRight(leftKey, rightKey, geom); + } + else if (rightKey in leftIndex) { + // found mergeable line adjacent to the end of the current line, merge + mergeFromLeft(leftKey, rightKey, geom); + } + else { + // no adjacent lines, add as a new item + add(k); + leftIndex[leftKey] = mergedIndex - 1; + rightIndex[rightKey] = mergedIndex - 1; + } + } + return mergedFeatures.filter((f) => f.geometry); +} + +const verticalizedCharacterMap = { + '!': '︕', + '#': '#', + '$': '$', + '%': '%', + '&': '&', + '(': '︵', + ')': '︶', + '*': '*', + '+': '+', + ',': '︐', + '-': '︲', + '.': '・', + '/': '/', + ':': '︓', + ';': '︔', + '<': '︿', + '=': '=', + '>': '﹀', + '?': '︖', + '@': '@', + '[': '﹇', + '\\': '\', + ']': '﹈', + '^': '^', + '_': '︳', + '`': '`', + '{': '︷', + '|': '―', + '}': '︸', + '~': '~', + '¢': '¢', + '£': '£', + '¥': '¥', + '¦': '¦', + '¬': '¬', + '¯': ' ̄', + '–': '︲', + '—': '︱', + '‘': '﹃', + '’': '﹄', + '“': '﹁', + '”': '﹂', + '…': '︙', + '‧': '・', + '₩': '₩', + '、': '︑', + '。': '︒', + '〈': '︿', + '〉': '﹀', + '《': '︽', + '》': '︾', + '「': '﹁', + '」': '﹂', + '『': '﹃', + '』': '﹄', + '【': '︻', + '】': '︼', + '〔': '︹', + '〕': '︺', + '〖': '︗', + '〗': '︘', + '!': '︕', + '(': '︵', + ')': '︶', + ',': '︐', + '-': '︲', + '.': '・', + ':': '︓', + ';': '︔', + '<': '︿', + '>': '﹀', + '?': '︖', + '[': '﹇', + ']': '﹈', + '_': '︳', + '{': '︷', + '|': '―', + '}': '︸', + '⦅': '︵', + '⦆': '︶', + '。': '︒', + '「': '﹁', + '」': '﹂' +}; +function verticalizePunctuation(input) { + let output = ''; + for (let i = 0; i < input.length; i++) { + const nextCharCode = input.charCodeAt(i + 1) || null; + const prevCharCode = input.charCodeAt(i - 1) || null; + const canReplacePunctuation = ((!nextCharCode || !charHasRotatedVerticalOrientation(nextCharCode) || verticalizedCharacterMap[input[i + 1]]) && + (!prevCharCode || !charHasRotatedVerticalOrientation(prevCharCode) || verticalizedCharacterMap[input[i - 1]])); + if (canReplacePunctuation && verticalizedCharacterMap[input[i]]) { + output += verticalizedCharacterMap[input[i]]; + } + else { + output += input[i]; + } + } + return output; +} + +// ONE_EM constant used to go between "em" units used in style spec and "points" used internally for layout +var ONE_EM = 24; + +var ieee754$1 = {}; + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + +var read = ieee754$1.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = (nBytes * 8) - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +}; + +var write = ieee754$1.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = (nBytes * 8) - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +}; + +'use strict'; + +var pbf = Pbf$1; + +var ieee754 = ieee754$1; + +function Pbf$1(buf) { + this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0); + this.pos = 0; + this.type = 0; + this.length = this.buf.length; +} + +Pbf$1.Varint = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum +Pbf$1.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64 +Pbf$1.Bytes = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields +Pbf$1.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32 + +var SHIFT_LEFT_32 = (1 << 16) * (1 << 16), + SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32; + +// Threshold chosen based on both benchmarking and knowledge about browser string +// data structures (which currently switch structure types at 12 bytes or more) +var TEXT_DECODER_MIN_LENGTH = 12; +var utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8'); + +Pbf$1.prototype = { + + destroy: function() { + this.buf = null; + }, + + // === READING ================================================================= + + readFields: function(readField, result, end) { + end = end || this.length; + + while (this.pos < end) { + var val = this.readVarint(), + tag = val >> 3, + startPos = this.pos; + + this.type = val & 0x7; + readField(tag, result, this); + + if (this.pos === startPos) this.skip(val); + } + return result; + }, + + readMessage: function(readField, result) { + return this.readFields(readField, result, this.readVarint() + this.pos); + }, + + readFixed32: function() { + var val = readUInt32(this.buf, this.pos); + this.pos += 4; + return val; + }, + + readSFixed32: function() { + var val = readInt32(this.buf, this.pos); + this.pos += 4; + return val; + }, + + // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed) + + readFixed64: function() { + var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; + this.pos += 8; + return val; + }, + + readSFixed64: function() { + var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; + this.pos += 8; + return val; + }, + + readFloat: function() { + var val = ieee754.read(this.buf, this.pos, true, 23, 4); + this.pos += 4; + return val; + }, + + readDouble: function() { + var val = ieee754.read(this.buf, this.pos, true, 52, 8); + this.pos += 8; + return val; + }, + + readVarint: function(isSigned) { + var buf = this.buf, + val, b; + + b = buf[this.pos++]; val = b & 0x7f; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val; + b = buf[this.pos]; val |= (b & 0x0f) << 28; + + return readVarintRemainder(val, isSigned, this); + }, + + readVarint64: function() { // for compatibility with v2.0.1 + return this.readVarint(true); + }, + + readSVarint: function() { + var num = this.readVarint(); + return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding + }, + + readBoolean: function() { + return Boolean(this.readVarint()); + }, + + readString: function() { + var end = this.readVarint() + this.pos; + var pos = this.pos; + this.pos = end; + + if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) { + // longer strings are fast with the built-in browser TextDecoder API + return readUtf8TextDecoder(this.buf, pos, end); + } + // short strings are fast with our custom implementation + return readUtf8(this.buf, pos, end); + }, + + readBytes: function() { + var end = this.readVarint() + this.pos, + buffer = this.buf.subarray(this.pos, end); + this.pos = end; + return buffer; + }, + + // verbose for performance reasons; doesn't affect gzipped size + + readPackedVarint: function(arr, isSigned) { + if (this.type !== Pbf$1.Bytes) return arr.push(this.readVarint(isSigned)); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readVarint(isSigned)); + return arr; + }, + readPackedSVarint: function(arr) { + if (this.type !== Pbf$1.Bytes) return arr.push(this.readSVarint()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSVarint()); + return arr; + }, + readPackedBoolean: function(arr) { + if (this.type !== Pbf$1.Bytes) return arr.push(this.readBoolean()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readBoolean()); + return arr; + }, + readPackedFloat: function(arr) { + if (this.type !== Pbf$1.Bytes) return arr.push(this.readFloat()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFloat()); + return arr; + }, + readPackedDouble: function(arr) { + if (this.type !== Pbf$1.Bytes) return arr.push(this.readDouble()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readDouble()); + return arr; + }, + readPackedFixed32: function(arr) { + if (this.type !== Pbf$1.Bytes) return arr.push(this.readFixed32()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFixed32()); + return arr; + }, + readPackedSFixed32: function(arr) { + if (this.type !== Pbf$1.Bytes) return arr.push(this.readSFixed32()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSFixed32()); + return arr; + }, + readPackedFixed64: function(arr) { + if (this.type !== Pbf$1.Bytes) return arr.push(this.readFixed64()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFixed64()); + return arr; + }, + readPackedSFixed64: function(arr) { + if (this.type !== Pbf$1.Bytes) return arr.push(this.readSFixed64()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSFixed64()); + return arr; + }, + + skip: function(val) { + var type = val & 0x7; + if (type === Pbf$1.Varint) while (this.buf[this.pos++] > 0x7f) {} + else if (type === Pbf$1.Bytes) this.pos = this.readVarint() + this.pos; + else if (type === Pbf$1.Fixed32) this.pos += 4; + else if (type === Pbf$1.Fixed64) this.pos += 8; + else throw new Error('Unimplemented type: ' + type); + }, + + // === WRITING ================================================================= + + writeTag: function(tag, type) { + this.writeVarint((tag << 3) | type); + }, + + realloc: function(min) { + var length = this.length || 16; + + while (length < this.pos + min) length *= 2; + + if (length !== this.length) { + var buf = new Uint8Array(length); + buf.set(this.buf); + this.buf = buf; + this.length = length; + } + }, + + finish: function() { + this.length = this.pos; + this.pos = 0; + return this.buf.subarray(0, this.length); + }, + + writeFixed32: function(val) { + this.realloc(4); + writeInt32(this.buf, val, this.pos); + this.pos += 4; + }, + + writeSFixed32: function(val) { + this.realloc(4); + writeInt32(this.buf, val, this.pos); + this.pos += 4; + }, + + writeFixed64: function(val) { + this.realloc(8); + writeInt32(this.buf, val & -1, this.pos); + writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4); + this.pos += 8; + }, + + writeSFixed64: function(val) { + this.realloc(8); + writeInt32(this.buf, val & -1, this.pos); + writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4); + this.pos += 8; + }, + + writeVarint: function(val) { + val = +val || 0; + + if (val > 0xfffffff || val < 0) { + writeBigVarint(val, this); + return; + } + + this.realloc(4); + + this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = (val >>> 7) & 0x7f; + }, + + writeSVarint: function(val) { + this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2); + }, + + writeBoolean: function(val) { + this.writeVarint(Boolean(val)); + }, + + writeString: function(str) { + str = String(str); + this.realloc(str.length * 4); + + this.pos++; // reserve 1 byte for short string length + + var startPos = this.pos; + // write the string directly to the buffer and see how much was written + this.pos = writeUtf8(this.buf, str, this.pos); + var len = this.pos - startPos; + + if (len >= 0x80) makeRoomForExtraLength(startPos, len, this); + + // finally, write the message length in the reserved place and restore the position + this.pos = startPos - 1; + this.writeVarint(len); + this.pos += len; + }, + + writeFloat: function(val) { + this.realloc(4); + ieee754.write(this.buf, val, this.pos, true, 23, 4); + this.pos += 4; + }, + + writeDouble: function(val) { + this.realloc(8); + ieee754.write(this.buf, val, this.pos, true, 52, 8); + this.pos += 8; + }, + + writeBytes: function(buffer) { + var len = buffer.length; + this.writeVarint(len); + this.realloc(len); + for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i]; + }, + + writeRawMessage: function(fn, obj) { + this.pos++; // reserve 1 byte for short message length + + // write the message directly to the buffer and see how much was written + var startPos = this.pos; + fn(obj, this); + var len = this.pos - startPos; + + if (len >= 0x80) makeRoomForExtraLength(startPos, len, this); + + // finally, write the message length in the reserved place and restore the position + this.pos = startPos - 1; + this.writeVarint(len); + this.pos += len; + }, + + writeMessage: function(tag, fn, obj) { + this.writeTag(tag, Pbf$1.Bytes); + this.writeRawMessage(fn, obj); + }, + + writePackedVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedVarint, arr); }, + writePackedSVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSVarint, arr); }, + writePackedBoolean: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedBoolean, arr); }, + writePackedFloat: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFloat, arr); }, + writePackedDouble: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedDouble, arr); }, + writePackedFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed32, arr); }, + writePackedSFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr); }, + writePackedFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed64, arr); }, + writePackedSFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr); }, + + writeBytesField: function(tag, buffer) { + this.writeTag(tag, Pbf$1.Bytes); + this.writeBytes(buffer); + }, + writeFixed32Field: function(tag, val) { + this.writeTag(tag, Pbf$1.Fixed32); + this.writeFixed32(val); + }, + writeSFixed32Field: function(tag, val) { + this.writeTag(tag, Pbf$1.Fixed32); + this.writeSFixed32(val); + }, + writeFixed64Field: function(tag, val) { + this.writeTag(tag, Pbf$1.Fixed64); + this.writeFixed64(val); + }, + writeSFixed64Field: function(tag, val) { + this.writeTag(tag, Pbf$1.Fixed64); + this.writeSFixed64(val); + }, + writeVarintField: function(tag, val) { + this.writeTag(tag, Pbf$1.Varint); + this.writeVarint(val); + }, + writeSVarintField: function(tag, val) { + this.writeTag(tag, Pbf$1.Varint); + this.writeSVarint(val); + }, + writeStringField: function(tag, str) { + this.writeTag(tag, Pbf$1.Bytes); + this.writeString(str); + }, + writeFloatField: function(tag, val) { + this.writeTag(tag, Pbf$1.Fixed32); + this.writeFloat(val); + }, + writeDoubleField: function(tag, val) { + this.writeTag(tag, Pbf$1.Fixed64); + this.writeDouble(val); + }, + writeBooleanField: function(tag, val) { + this.writeVarintField(tag, Boolean(val)); + } +}; + +function readVarintRemainder(l, s, p) { + var buf = p.buf, + h, b; + + b = buf[p.pos++]; h = (b & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s); + + throw new Error('Expected varint not more than 10 bytes'); +} + +function readPackedEnd(pbf) { + return pbf.type === Pbf$1.Bytes ? + pbf.readVarint() + pbf.pos : pbf.pos + 1; +} + +function toNum(low, high, isSigned) { + if (isSigned) { + return high * 0x100000000 + (low >>> 0); + } + + return ((high >>> 0) * 0x100000000) + (low >>> 0); +} + +function writeBigVarint(val, pbf) { + var low, high; + + if (val >= 0) { + low = (val % 0x100000000) | 0; + high = (val / 0x100000000) | 0; + } else { + low = ~(-val % 0x100000000); + high = ~(-val / 0x100000000); + + if (low ^ 0xffffffff) { + low = (low + 1) | 0; + } else { + low = 0; + high = (high + 1) | 0; + } + } + + if (val >= 0x10000000000000000 || val < -0x10000000000000000) { + throw new Error('Given varint doesn\'t fit into 10 bytes'); + } + + pbf.realloc(10); + + writeBigVarintLow(low, high, pbf); + writeBigVarintHigh(high, pbf); +} + +function writeBigVarintLow(low, high, pbf) { + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos] = low & 0x7f; +} + +function writeBigVarintHigh(high, pbf) { + var lsb = (high & 0x07) << 4; + + pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f; +} + +function makeRoomForExtraLength(startPos, len, pbf) { + var extraLen = + len <= 0x3fff ? 1 : + len <= 0x1fffff ? 2 : + len <= 0xfffffff ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7)); + + // if 1 byte isn't enough for encoding message length, shift the data to the right + pbf.realloc(extraLen); + for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i]; +} + +function writePackedVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]); } +function writePackedSVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); } +function writePackedFloat(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); } +function writePackedDouble(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); } +function writePackedBoolean(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); } +function writePackedFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); } +function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); } +function writePackedFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); } +function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); } + +// Buffer code below from https://github.com/feross/buffer, MIT-licensed + +function readUInt32(buf, pos) { + return ((buf[pos]) | + (buf[pos + 1] << 8) | + (buf[pos + 2] << 16)) + + (buf[pos + 3] * 0x1000000); +} + +function writeInt32(buf, val, pos) { + buf[pos] = val; + buf[pos + 1] = (val >>> 8); + buf[pos + 2] = (val >>> 16); + buf[pos + 3] = (val >>> 24); +} + +function readInt32(buf, pos) { + return ((buf[pos]) | + (buf[pos + 1] << 8) | + (buf[pos + 2] << 16)) + + (buf[pos + 3] << 24); +} + +function readUtf8(buf, pos, end) { + var str = ''; + var i = pos; + + while (i < end) { + var b0 = buf[i]; + var c = null; // codepoint + var bytesPerSequence = + b0 > 0xEF ? 4 : + b0 > 0xDF ? 3 : + b0 > 0xBF ? 2 : 1; + + if (i + bytesPerSequence > end) break; + + var b1, b2, b3; + + if (bytesPerSequence === 1) { + if (b0 < 0x80) { + c = b0; + } + } else if (bytesPerSequence === 2) { + b1 = buf[i + 1]; + if ((b1 & 0xC0) === 0x80) { + c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F); + if (c <= 0x7F) { + c = null; + } + } + } else if (bytesPerSequence === 3) { + b1 = buf[i + 1]; + b2 = buf[i + 2]; + if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) { + c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F); + if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) { + c = null; + } + } + } else if (bytesPerSequence === 4) { + b1 = buf[i + 1]; + b2 = buf[i + 2]; + b3 = buf[i + 3]; + if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) { + c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F); + if (c <= 0xFFFF || c >= 0x110000) { + c = null; + } + } + } + + if (c === null) { + c = 0xFFFD; + bytesPerSequence = 1; + + } else if (c > 0xFFFF) { + c -= 0x10000; + str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800); + c = 0xDC00 | c & 0x3FF; + } + + str += String.fromCharCode(c); + i += bytesPerSequence; + } + + return str; +} + +function readUtf8TextDecoder(buf, pos, end) { + return utf8TextDecoder.decode(buf.subarray(pos, end)); +} + +function writeUtf8(buf, str, pos) { + for (var i = 0, c, lead; i < str.length; i++) { + c = str.charCodeAt(i); // code point + + if (c > 0xD7FF && c < 0xE000) { + if (lead) { + if (c < 0xDC00) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + lead = c; + continue; + } else { + c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000; + lead = null; + } + } else { + if (c > 0xDBFF || (i + 1 === str.length)) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + } else { + lead = c; + } + continue; + } + } else if (lead) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + lead = null; + } + + if (c < 0x80) { + buf[pos++] = c; + } else { + if (c < 0x800) { + buf[pos++] = c >> 0x6 | 0xC0; + } else { + if (c < 0x10000) { + buf[pos++] = c >> 0xC | 0xE0; + } else { + buf[pos++] = c >> 0x12 | 0xF0; + buf[pos++] = c >> 0xC & 0x3F | 0x80; + } + buf[pos++] = c >> 0x6 & 0x3F | 0x80; + } + buf[pos++] = c & 0x3F | 0x80; + } + } + return pos; +} + +var Protobuf = /*@__PURE__*/getDefaultExportFromCjs$1(pbf); + +const border$1 = 3; +function readFontstacks(tag, glyphs, pbf) { + if (tag === 1) { + pbf.readMessage(readFontstack, glyphs); + } +} +function readFontstack(tag, glyphs, pbf) { + if (tag === 3) { + const { id, bitmap, width, height, left, top, advance } = pbf.readMessage(readGlyph, {}); + glyphs.push({ + id, + bitmap: new AlphaImage({ + width: width + 2 * border$1, + height: height + 2 * border$1 + }, bitmap), + metrics: { width, height, left, top, advance } + }); + } +} +function readGlyph(tag, glyph, pbf) { + if (tag === 1) + glyph.id = pbf.readVarint(); + else if (tag === 2) + glyph.bitmap = pbf.readBytes(); + else if (tag === 3) + glyph.width = pbf.readVarint(); + else if (tag === 4) + glyph.height = pbf.readVarint(); + else if (tag === 5) + glyph.left = pbf.readSVarint(); + else if (tag === 6) + glyph.top = pbf.readSVarint(); + else if (tag === 7) + glyph.advance = pbf.readVarint(); +} +function parseGlyphPbf(data) { + return new Protobuf(data).readFields(readFontstacks, []); +} +const GLYPH_PBF_BORDER = border$1; + +function potpack(boxes) { + + // calculate total box area and maximum box width + let area = 0; + let maxWidth = 0; + + for (const box of boxes) { + area += box.w * box.h; + maxWidth = Math.max(maxWidth, box.w); + } + + // sort the boxes for insertion by height, descending + boxes.sort((a, b) => b.h - a.h); + + // aim for a squarish resulting container, + // slightly adjusted for sub-100% space utilization + const startWidth = Math.max(Math.ceil(Math.sqrt(area / 0.95)), maxWidth); + + // start with a single empty space, unbounded at the bottom + const spaces = [{x: 0, y: 0, w: startWidth, h: Infinity}]; + + let width = 0; + let height = 0; + + for (const box of boxes) { + // look through spaces backwards so that we check smaller spaces first + for (let i = spaces.length - 1; i >= 0; i--) { + const space = spaces[i]; + + // look for empty spaces that can accommodate the current box + if (box.w > space.w || box.h > space.h) continue; + + // found the space; add the box to its top-left corner + // |-------|-------| + // | box | | + // |_______| | + // | space | + // |_______________| + box.x = space.x; + box.y = space.y; + + height = Math.max(height, box.y + box.h); + width = Math.max(width, box.x + box.w); + + if (box.w === space.w && box.h === space.h) { + // space matches the box exactly; remove it + const last = spaces.pop(); + if (i < spaces.length) spaces[i] = last; + + } else if (box.h === space.h) { + // space matches the box height; update it accordingly + // |-------|---------------| + // | box | updated space | + // |_______|_______________| + space.x += box.w; + space.w -= box.w; + + } else if (box.w === space.w) { + // space matches the box width; update it accordingly + // |---------------| + // | box | + // |_______________| + // | updated space | + // |_______________| + space.y += box.h; + space.h -= box.h; + + } else { + // otherwise the box splits the space into two spaces + // |-------|-----------| + // | box | new space | + // |_______|___________| + // | updated space | + // |___________________| + spaces.push({ + x: space.x + box.w, + y: space.y, + w: space.w - box.w, + h: box.h + }); + space.y += box.h; + space.h -= box.h; + } + break; + } + } + + return { + w: width, // container width + h: height, // container height + fill: (area / (width * height)) || 0 // space utilization + }; +} + +/* eslint-disable key-spacing */ +const IMAGE_PADDING = 1; +class ImagePosition { + constructor(paddedRect, { pixelRatio, version, stretchX, stretchY, content, textFitWidth, textFitHeight }) { + this.paddedRect = paddedRect; + this.pixelRatio = pixelRatio; + this.stretchX = stretchX; + this.stretchY = stretchY; + this.content = content; + this.version = version; + this.textFitWidth = textFitWidth; + this.textFitHeight = textFitHeight; + } + get tl() { + return [ + this.paddedRect.x + IMAGE_PADDING, + this.paddedRect.y + IMAGE_PADDING + ]; + } + get br() { + return [ + this.paddedRect.x + this.paddedRect.w - IMAGE_PADDING, + this.paddedRect.y + this.paddedRect.h - IMAGE_PADDING + ]; + } + get tlbr() { + return this.tl.concat(this.br); + } + get displaySize() { + return [ + (this.paddedRect.w - IMAGE_PADDING * 2) / this.pixelRatio, + (this.paddedRect.h - IMAGE_PADDING * 2) / this.pixelRatio + ]; + } +} +/** + * A class holding all the images + */ +class ImageAtlas { + constructor(icons, patterns) { + const iconPositions = {}, patternPositions = {}; + this.haveRenderCallbacks = []; + const bins = []; + this.addImages(icons, iconPositions, bins); + this.addImages(patterns, patternPositions, bins); + const { w, h } = potpack(bins); + const image = new RGBAImage({ width: w || 1, height: h || 1 }); + for (const id in icons) { + const src = icons[id]; + const bin = iconPositions[id].paddedRect; + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x: bin.x + IMAGE_PADDING, y: bin.y + IMAGE_PADDING }, src.data); + } + for (const id in patterns) { + const src = patterns[id]; + const bin = patternPositions[id].paddedRect; + const x = bin.x + IMAGE_PADDING, y = bin.y + IMAGE_PADDING, w = src.data.width, h = src.data.height; + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x, y }, src.data); + // Add 1 pixel wrapped padding on each side of the image. + RGBAImage.copy(src.data, image, { x: 0, y: h - 1 }, { x, y: y - 1 }, { width: w, height: 1 }); // T + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x, y: y + h }, { width: w, height: 1 }); // B + RGBAImage.copy(src.data, image, { x: w - 1, y: 0 }, { x: x - 1, y }, { width: 1, height: h }); // L + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x: x + w, y }, { width: 1, height: h }); // R + } + this.image = image; + this.iconPositions = iconPositions; + this.patternPositions = patternPositions; + } + addImages(images, positions, bins) { + for (const id in images) { + const src = images[id]; + const bin = { + x: 0, + y: 0, + w: src.data.width + 2 * IMAGE_PADDING, + h: src.data.height + 2 * IMAGE_PADDING, + }; + bins.push(bin); + positions[id] = new ImagePosition(bin, src); + if (src.hasRenderCallback) { + this.haveRenderCallbacks.push(id); + } + } + } + patchUpdatedImages(imageManager, texture) { + imageManager.dispatchRenderCallbacks(this.haveRenderCallbacks); + for (const name in imageManager.updatedImages) { + this.patchUpdatedImage(this.iconPositions[name], imageManager.getImage(name), texture); + this.patchUpdatedImage(this.patternPositions[name], imageManager.getImage(name), texture); + } + } + patchUpdatedImage(position, image, texture) { + if (!position || !image) + return; + if (position.version === image.version) + return; + position.version = image.version; + const [x, y] = position.tl; + texture.update(image.data, undefined, { x, y }); + } +} +register('ImagePosition', ImagePosition); +register('ImageAtlas', ImageAtlas); + +var WritingMode; +(function (WritingMode) { + WritingMode[WritingMode["none"] = 0] = "none"; + WritingMode[WritingMode["horizontal"] = 1] = "horizontal"; + WritingMode[WritingMode["vertical"] = 2] = "vertical"; + WritingMode[WritingMode["horizontalOnly"] = 3] = "horizontalOnly"; +})(WritingMode || (WritingMode = {})); +const SHAPING_DEFAULT_OFFSET = -17; +function isEmpty(positionedLines) { + for (const line of positionedLines) { + if (line.positionedGlyphs.length !== 0) { + return false; + } + } + return true; +} +// Max number of images in label is 6401 U+E000–U+F8FF that covers +// Basic Multilingual Plane Unicode Private Use Area (PUA). +const PUAbegin = 0xE000; +const PUAend = 0xF8FF; +class SectionOptions { + constructor() { + this.scale = 1.0; + this.fontStack = ''; + this.imageName = null; + } + static forText(scale, fontStack) { + const textOptions = new SectionOptions(); + textOptions.scale = scale || 1; + textOptions.fontStack = fontStack; + return textOptions; + } + static forImage(imageName) { + const imageOptions = new SectionOptions(); + imageOptions.imageName = imageName; + return imageOptions; + } +} +class TaggedString { + constructor() { + this.text = ''; + this.sectionIndex = []; + this.sections = []; + this.imageSectionID = null; + } + static fromFeature(text, defaultFontStack) { + const result = new TaggedString(); + for (let i = 0; i < text.sections.length; i++) { + const section = text.sections[i]; + if (!section.image) { + result.addTextSection(section, defaultFontStack); + } + else { + result.addImageSection(section); + } + } + return result; + } + length() { + return this.text.length; + } + getSection(index) { + return this.sections[this.sectionIndex[index]]; + } + getSectionIndex(index) { + return this.sectionIndex[index]; + } + getCharCode(index) { + return this.text.charCodeAt(index); + } + verticalizePunctuation() { + this.text = verticalizePunctuation(this.text); + } + trim() { + let beginningWhitespace = 0; + for (let i = 0; i < this.text.length && whitespace[this.text.charCodeAt(i)]; i++) { + beginningWhitespace++; + } + let trailingWhitespace = this.text.length; + for (let i = this.text.length - 1; i >= 0 && i >= beginningWhitespace && whitespace[this.text.charCodeAt(i)]; i--) { + trailingWhitespace--; + } + this.text = this.text.substring(beginningWhitespace, trailingWhitespace); + this.sectionIndex = this.sectionIndex.slice(beginningWhitespace, trailingWhitespace); + } + substring(start, end) { + const substring = new TaggedString(); + substring.text = this.text.substring(start, end); + substring.sectionIndex = this.sectionIndex.slice(start, end); + substring.sections = this.sections; + return substring; + } + toString() { + return this.text; + } + getMaxScale() { + return this.sectionIndex.reduce((max, index) => Math.max(max, this.sections[index].scale), 0); + } + addTextSection(section, defaultFontStack) { + this.text += section.text; + this.sections.push(SectionOptions.forText(section.scale, section.fontStack || defaultFontStack)); + const index = this.sections.length - 1; + for (let i = 0; i < section.text.length; ++i) { + this.sectionIndex.push(index); + } + } + addImageSection(section) { + const imageName = section.image ? section.image.name : ''; + if (imageName.length === 0) { + warnOnce('Can\'t add FormattedSection with an empty image.'); + return; + } + const nextImageSectionCharCode = this.getNextImageSectionCharCode(); + if (!nextImageSectionCharCode) { + warnOnce(`Reached maximum number of images ${PUAend - PUAbegin + 2}`); + return; + } + this.text += String.fromCharCode(nextImageSectionCharCode); + this.sections.push(SectionOptions.forImage(imageName)); + this.sectionIndex.push(this.sections.length - 1); + } + getNextImageSectionCharCode() { + if (!this.imageSectionID) { + this.imageSectionID = PUAbegin; + return this.imageSectionID; + } + if (this.imageSectionID >= PUAend) + return null; + return ++this.imageSectionID; + } +} +function breakLines(input, lineBreakPoints) { + const lines = []; + const text = input.text; + let start = 0; + for (const lineBreak of lineBreakPoints) { + lines.push(input.substring(start, lineBreak)); + start = lineBreak; + } + if (start < text.length) { + lines.push(input.substring(start, text.length)); + } + return lines; +} +function shapeText(text, glyphMap, glyphPositions, imagePositions, defaultFontStack, maxWidth, lineHeight, textAnchor, textJustify, spacing, translate, writingMode, allowVerticalPlacement, layoutTextSize, layoutTextSizeThisZoom) { + const logicalInput = TaggedString.fromFeature(text, defaultFontStack); + if (writingMode === WritingMode.vertical) { + logicalInput.verticalizePunctuation(); + } + let lines; + const { processBidirectionalText, processStyledBidirectionalText } = rtlWorkerPlugin; + if (processBidirectionalText && logicalInput.sections.length === 1) { + // Bidi doesn't have to be style-aware + lines = []; + const untaggedLines = processBidirectionalText(logicalInput.toString(), determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + for (const line of untaggedLines) { + const taggedLine = new TaggedString(); + taggedLine.text = line; + taggedLine.sections = logicalInput.sections; + for (let i = 0; i < line.length; i++) { + taggedLine.sectionIndex.push(0); + } + lines.push(taggedLine); + } + } + else if (processStyledBidirectionalText) { + // Need version of mapbox-gl-rtl-text with style support for combining RTL text + // with formatting + lines = []; + const processedLines = processStyledBidirectionalText(logicalInput.text, logicalInput.sectionIndex, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + for (const line of processedLines) { + const taggedLine = new TaggedString(); + taggedLine.text = line[0]; + taggedLine.sectionIndex = line[1]; + taggedLine.sections = logicalInput.sections; + lines.push(taggedLine); + } + } + else { + lines = breakLines(logicalInput, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + } + const positionedLines = []; + const shaping = { + positionedLines, + text: logicalInput.toString(), + top: translate[1], + bottom: translate[1], + left: translate[0], + right: translate[0], + writingMode, + iconsInText: false, + verticalizable: false + }; + shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom); + if (isEmpty(positionedLines)) + return false; + return shaping; +} +// using computed properties due to https://github.com/facebook/flow/issues/380 +/* eslint no-useless-computed-key: 0 */ +const whitespace = { + [0x09]: true, // tab + [0x0a]: true, // newline + [0x0b]: true, // vertical tab + [0x0c]: true, // form feed + [0x0d]: true, // carriage return + [0x20]: true, // space +}; +const breakable = { + [0x0a]: true, // newline + [0x20]: true, // space + [0x26]: true, // ampersand + [0x29]: true, // right parenthesis + [0x2b]: true, // plus sign + [0x2d]: true, // hyphen-minus + [0x2f]: true, // solidus + [0xad]: true, // soft hyphen + [0xb7]: true, // middle dot + [0x200b]: true, // zero-width space + [0x2010]: true, // hyphen + [0x2013]: true, // en dash + [0x2027]: true // interpunct + // Many other characters may be reasonable breakpoints + // Consider "neutral orientation" characters at scriptDetection.charHasNeutralVerticalOrientation + // See https://github.com/mapbox/mapbox-gl-js/issues/3658 +}; +// Allow breaks depending on the following character +const breakableBefore = { + [0x28]: true, // left parenthesis +}; +function getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize) { + if (!section.imageName) { + const positions = glyphMap[section.fontStack]; + const glyph = positions && positions[codePoint]; + if (!glyph) + return 0; + return glyph.metrics.advance * section.scale + spacing; + } + else { + const imagePosition = imagePositions[section.imageName]; + if (!imagePosition) + return 0; + return imagePosition.displaySize[0] * section.scale * ONE_EM / layoutTextSize + spacing; + } +} +function determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) { + let totalWidth = 0; + for (let index = 0; index < logicalInput.length(); index++) { + const section = logicalInput.getSection(index); + totalWidth += getGlyphAdvance(logicalInput.getCharCode(index), section, glyphMap, imagePositions, spacing, layoutTextSize); + } + const lineCount = Math.max(1, Math.ceil(totalWidth / maxWidth)); + return totalWidth / lineCount; +} +function calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) { + const raggedness = Math.pow(lineWidth - targetWidth, 2); + if (isLastBreak) { + // Favor finals lines shorter than average over longer than average + if (lineWidth < targetWidth) { + return raggedness / 2; + } + else { + return raggedness * 2; + } + } + return raggedness + Math.abs(penalty) * penalty; +} +function calculatePenalty(codePoint, nextCodePoint, penalizableIdeographicBreak) { + let penalty = 0; + // Force break on newline + if (codePoint === 0x0a) { + penalty -= 10000; + } + // Penalize breaks between characters that allow ideographic breaking because + // they are less preferable than breaks at spaces (or zero width spaces). + if (penalizableIdeographicBreak) { + penalty += 150; + } + // Penalize open parenthesis at end of line + if (codePoint === 0x28 || codePoint === 0xff08) { + penalty += 50; + } + // Penalize close parenthesis at beginning of line + if (nextCodePoint === 0x29 || nextCodePoint === 0xff09) { + penalty += 50; + } + return penalty; +} +function evaluateBreak(breakIndex, breakX, targetWidth, potentialBreaks, penalty, isLastBreak) { + // We could skip evaluating breaks where the line length (breakX - priorBreak.x) > maxWidth + // ...but in fact we allow lines longer than maxWidth (if there's no break points) + // ...and when targetWidth and maxWidth are close, strictly enforcing maxWidth can give + // more lopsided results. + let bestPriorBreak = null; + let bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak); + for (const potentialBreak of potentialBreaks) { + const lineWidth = breakX - potentialBreak.x; + const breakBadness = calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness; + if (breakBadness <= bestBreakBadness) { + bestPriorBreak = potentialBreak; + bestBreakBadness = breakBadness; + } + } + return { + index: breakIndex, + x: breakX, + priorBreak: bestPriorBreak, + badness: bestBreakBadness + }; +} +function leastBadBreaks(lastLineBreak) { + if (!lastLineBreak) { + return []; + } + return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index); +} +function determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) { + if (!logicalInput) + return []; + const potentialLineBreaks = []; + const targetWidth = determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize); + const hasServerSuggestedBreakpoints = logicalInput.text.indexOf('\u200b') >= 0; + let currentX = 0; + for (let i = 0; i < logicalInput.length(); i++) { + const section = logicalInput.getSection(i); + const codePoint = logicalInput.getCharCode(i); + if (!whitespace[codePoint]) + currentX += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize); + // Ideographic characters, spaces, and word-breaking punctuation that often appear without + // surrounding spaces. + if ((i < logicalInput.length() - 1)) { + const ideographicBreak = charAllowsIdeographicBreaking(codePoint); + if (breakable[codePoint] || ideographicBreak || section.imageName || (i !== logicalInput.length() - 2 && breakableBefore[logicalInput.getCharCode(i + 1)])) { + potentialLineBreaks.push(evaluateBreak(i + 1, currentX, targetWidth, potentialLineBreaks, calculatePenalty(codePoint, logicalInput.getCharCode(i + 1), ideographicBreak && hasServerSuggestedBreakpoints), false)); + } + } + } + return leastBadBreaks(evaluateBreak(logicalInput.length(), currentX, targetWidth, potentialLineBreaks, 0, true)); +} +function getAnchorAlignment(anchor) { + let horizontalAlign = 0.5, verticalAlign = 0.5; + switch (anchor) { + case 'right': + case 'top-right': + case 'bottom-right': + horizontalAlign = 1; + break; + case 'left': + case 'top-left': + case 'bottom-left': + horizontalAlign = 0; + break; + } + switch (anchor) { + case 'bottom': + case 'bottom-right': + case 'bottom-left': + verticalAlign = 1; + break; + case 'top': + case 'top-right': + case 'top-left': + verticalAlign = 0; + break; + } + return { horizontalAlign, verticalAlign }; +} +function shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom) { + let x = 0; + let y = SHAPING_DEFAULT_OFFSET; + let maxLineLength = 0; + let maxLineHeight = 0; + const justify = textJustify === 'right' ? 1 : + textJustify === 'left' ? 0 : 0.5; + let lineIndex = 0; + for (const line of lines) { + line.trim(); + const lineMaxScale = line.getMaxScale(); + const maxLineOffset = (lineMaxScale - 1) * ONE_EM; + const positionedLine = { positionedGlyphs: [], lineOffset: 0 }; + shaping.positionedLines[lineIndex] = positionedLine; + const positionedGlyphs = positionedLine.positionedGlyphs; + let lineOffset = 0.0; + if (!line.length()) { + y += lineHeight; // Still need a line feed after empty line + ++lineIndex; + continue; + } + for (let i = 0; i < line.length(); i++) { + const section = line.getSection(i); + const sectionIndex = line.getSectionIndex(i); + const codePoint = line.getCharCode(i); + let baselineOffset = 0.0; + let metrics = null; + let rect = null; + let imageName = null; + let verticalAdvance = ONE_EM; + const vertical = !(writingMode === WritingMode.horizontal || + // Don't verticalize glyphs that have no upright orientation if vertical placement is disabled. + (!allowVerticalPlacement && !charHasUprightVerticalOrientation(codePoint)) || + // If vertical placement is enabled, don't verticalize glyphs that + // are from complex text layout script, or whitespaces. + (allowVerticalPlacement && (whitespace[codePoint] || charInComplexShapingScript(codePoint)))); + if (!section.imageName) { + const positions = glyphPositions[section.fontStack]; + const glyphPosition = positions && positions[codePoint]; + if (glyphPosition && glyphPosition.rect) { + rect = glyphPosition.rect; + metrics = glyphPosition.metrics; + } + else { + const glyphs = glyphMap[section.fontStack]; + const glyph = glyphs && glyphs[codePoint]; + if (!glyph) + continue; + metrics = glyph.metrics; + } + // We don't know the baseline, but since we're laying out + // at 24 points, we can calculate how much it will move when + // we scale up or down. + baselineOffset = (lineMaxScale - section.scale) * ONE_EM; + } + else { + const imagePosition = imagePositions[section.imageName]; + if (!imagePosition) + continue; + imageName = section.imageName; + shaping.iconsInText = shaping.iconsInText || true; + rect = imagePosition.paddedRect; + const size = imagePosition.displaySize; + // If needed, allow to set scale factor for an image using + // alias "image-scale" that could be alias for "font-scale" + // when FormattedSection is an image section. + section.scale = section.scale * ONE_EM / layoutTextSizeThisZoom; + metrics = { width: size[0], + height: size[1], + left: IMAGE_PADDING, + top: -GLYPH_PBF_BORDER, + advance: vertical ? size[1] : size[0] }; + // Difference between one EM and an image size. + // Aligns bottom of an image to a baseline level. + const imageOffset = ONE_EM - size[1] * section.scale; + baselineOffset = maxLineOffset + imageOffset; + verticalAdvance = metrics.advance; + // Difference between height of an image and one EM at max line scale. + // Pushes current line down if an image size is over 1 EM at max line scale. + const offset = vertical ? size[0] * section.scale - ONE_EM * lineMaxScale : + size[1] * section.scale - ONE_EM * lineMaxScale; + if (offset > 0 && offset > lineOffset) { + lineOffset = offset; + } + } + if (!vertical) { + positionedGlyphs.push({ glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect }); + x += metrics.advance * section.scale + spacing; + } + else { + shaping.verticalizable = true; + positionedGlyphs.push({ glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect }); + x += verticalAdvance * section.scale + spacing; + } + } + // Only justify if we placed at least one glyph + if (positionedGlyphs.length !== 0) { + const lineLength = x - spacing; + maxLineLength = Math.max(lineLength, maxLineLength); + justifyLine(positionedGlyphs, 0, positionedGlyphs.length - 1, justify, lineOffset); + } + x = 0; + const currentLineHeight = lineHeight * lineMaxScale + lineOffset; + positionedLine.lineOffset = Math.max(lineOffset, maxLineOffset); + y += currentLineHeight; + maxLineHeight = Math.max(currentLineHeight, maxLineHeight); + ++lineIndex; + } + // Calculate the bounding box and justify / align text block. + const height = y - SHAPING_DEFAULT_OFFSET; + const { horizontalAlign, verticalAlign } = getAnchorAlignment(textAnchor); + align(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, height, lines.length); + shaping.top += -verticalAlign * height; + shaping.bottom = shaping.top + height; + shaping.left += -horizontalAlign * maxLineLength; + shaping.right = shaping.left + maxLineLength; +} +// justify right = 1, left = 0, center = 0.5 +function justifyLine(positionedGlyphs, start, end, justify, lineOffset) { + if (!justify && !lineOffset) + return; + const lastPositionedGlyph = positionedGlyphs[end]; + const lastAdvance = lastPositionedGlyph.metrics.advance * lastPositionedGlyph.scale; + const lineIndent = (positionedGlyphs[end].x + lastAdvance) * justify; + for (let j = start; j <= end; j++) { + positionedGlyphs[j].x -= lineIndent; + positionedGlyphs[j].y += lineOffset; + } +} +function align(positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, blockHeight, lineCount) { + const shiftX = (justify - horizontalAlign) * maxLineLength; + let shiftY = 0; + if (maxLineHeight !== lineHeight) { + shiftY = -blockHeight * verticalAlign - SHAPING_DEFAULT_OFFSET; + } + else { + shiftY = (-verticalAlign * lineCount + 0.5) * lineHeight; + } + for (const line of positionedLines) { + for (const positionedGlyph of line.positionedGlyphs) { + positionedGlyph.x += shiftX; + positionedGlyph.y += shiftY; + } + } +} +function shapeIcon(image, iconOffset, iconAnchor) { + const { horizontalAlign, verticalAlign } = getAnchorAlignment(iconAnchor); + const dx = iconOffset[0]; + const dy = iconOffset[1]; + const x1 = dx - image.displaySize[0] * horizontalAlign; + const x2 = x1 + image.displaySize[0]; + const y1 = dy - image.displaySize[1] * verticalAlign; + const y2 = y1 + image.displaySize[1]; + return { image, top: y1, bottom: y2, left: x1, right: x2 }; +} +/** + * Called after a PositionedIcon has already been run through fitIconToText, + * but needs further adjustment to apply textFitWidth and textFitHeight. + * @param shapedIcon - The icon that will be adjusted. + * @returns Extents of the shapedIcon with text fit adjustments if necessary. + */ +function applyTextFit(shapedIcon) { + var _a, _b; + // Assume shapedIcon.image is set or this wouldn't be called. + // Size of the icon after it was adjusted using stretchX and Y + let iconLeft = shapedIcon.left; + let iconTop = shapedIcon.top; + let iconWidth = shapedIcon.right - iconLeft; + let iconHeight = shapedIcon.bottom - iconTop; + // Size of the original content area + const contentWidth = shapedIcon.image.content[2] - shapedIcon.image.content[0]; + const contentHeight = shapedIcon.image.content[3] - shapedIcon.image.content[1]; + const textFitWidth = (_a = shapedIcon.image.textFitWidth) !== null && _a !== void 0 ? _a : "stretchOrShrink" /* TextFit.stretchOrShrink */; + const textFitHeight = (_b = shapedIcon.image.textFitHeight) !== null && _b !== void 0 ? _b : "stretchOrShrink" /* TextFit.stretchOrShrink */; + const contentAspectRatio = contentWidth / contentHeight; + // Scale to the proportional axis first note that height takes precedence if + // both axes are set to proportional. + if (textFitHeight === "proportional" /* TextFit.proportional */) { + if ((textFitWidth === "stretchOnly" /* TextFit.stretchOnly */ && iconWidth / iconHeight < contentAspectRatio) || textFitWidth === "proportional" /* TextFit.proportional */) { + // Push the width of the icon back out to match the content aspect ratio + const newIconWidth = Math.ceil(iconHeight * contentAspectRatio); + iconLeft *= newIconWidth / iconWidth; + iconWidth = newIconWidth; + } + } + else if (textFitWidth === "proportional" /* TextFit.proportional */) { + if (textFitHeight === "stretchOnly" /* TextFit.stretchOnly */ && contentAspectRatio !== 0 && iconWidth / iconHeight > contentAspectRatio) { + // Push the height of the icon back out to match the content aspect ratio + const newIconHeight = Math.ceil(iconWidth / contentAspectRatio); + iconTop *= newIconHeight / iconHeight; + iconHeight = newIconHeight; + } + } + else { + // If neither textFitHeight nor textFitWidth are proportional then + // there is no effect since the content rectangle should be precisely + // matched to the content + } + return { x1: iconLeft, y1: iconTop, x2: iconLeft + iconWidth, y2: iconTop + iconHeight }; +} +function fitIconToText(shapedIcon, shapedText, textFit, padding, iconOffset, fontScale) { + const image = shapedIcon.image; + let collisionPadding; + if (image.content) { + const content = image.content; + const pixelRatio = image.pixelRatio || 1; + collisionPadding = [ + content[0] / pixelRatio, + content[1] / pixelRatio, + image.displaySize[0] - content[2] / pixelRatio, + image.displaySize[1] - content[3] / pixelRatio + ]; + } + // We don't respect the icon-anchor, because icon-text-fit is set. Instead, + // the icon will be centered on the text, then stretched in the given + // dimensions. + const textLeft = shapedText.left * fontScale; + const textRight = shapedText.right * fontScale; + let top, right, bottom, left; + if (textFit === 'width' || textFit === 'both') { + // Stretched horizontally to the text width + left = iconOffset[0] + textLeft - padding[3]; + right = iconOffset[0] + textRight + padding[1]; + } + else { + // Centered on the text + left = iconOffset[0] + (textLeft + textRight - image.displaySize[0]) / 2; + right = left + image.displaySize[0]; + } + const textTop = shapedText.top * fontScale; + const textBottom = shapedText.bottom * fontScale; + if (textFit === 'height' || textFit === 'both') { + // Stretched vertically to the text height + top = iconOffset[1] + textTop - padding[0]; + bottom = iconOffset[1] + textBottom + padding[2]; + } + else { + // Centered on the text + top = iconOffset[1] + (textTop + textBottom - image.displaySize[1]) / 2; + bottom = top + image.displaySize[1]; + } + return { image, top, right, bottom, left, collisionPadding }; +} + +const MAX_GLYPH_ICON_SIZE = 255; +const SIZE_PACK_FACTOR = 128; +const MAX_PACKED_SIZE = MAX_GLYPH_ICON_SIZE * SIZE_PACK_FACTOR; +// For {text,icon}-size, get the bucket-level data that will be needed by +// the painter to set symbol-size-related uniforms +function getSizeData(tileZoom, value) { + const { expression } = value; + if (expression.kind === 'constant') { + const layoutSize = expression.evaluate(new EvaluationParameters(tileZoom + 1)); + return { kind: 'constant', layoutSize }; + } + else if (expression.kind === 'source') { + return { kind: 'source' }; + } + else { + const { zoomStops, interpolationType } = expression; + // calculate covering zoom stops for zoom-dependent values + let lower = 0; + while (lower < zoomStops.length && zoomStops[lower] <= tileZoom) + lower++; + lower = Math.max(0, lower - 1); + let upper = lower; + while (upper < zoomStops.length && zoomStops[upper] < tileZoom + 1) + upper++; + upper = Math.min(zoomStops.length - 1, upper); + const minZoom = zoomStops[lower]; + const maxZoom = zoomStops[upper]; + // We'd like to be able to use CameraExpression or CompositeExpression in these + // return types rather than ExpressionSpecification, but the former are not + // transferrable across Web Worker boundaries. + if (expression.kind === 'composite') { + return { kind: 'composite', minZoom, maxZoom, interpolationType }; + } + // for camera functions, also save off the function values + // evaluated at the covering zoom levels + const minSize = expression.evaluate(new EvaluationParameters(minZoom)); + const maxSize = expression.evaluate(new EvaluationParameters(maxZoom)); + return { kind: 'camera', minZoom, maxZoom, minSize, maxSize, interpolationType }; + } +} +function evaluateSizeForFeature(sizeData, { uSize, uSizeT }, { lowerSize, upperSize }) { + if (sizeData.kind === 'source') { + return lowerSize / SIZE_PACK_FACTOR; + } + else if (sizeData.kind === 'composite') { + return interpolate.number(lowerSize / SIZE_PACK_FACTOR, upperSize / SIZE_PACK_FACTOR, uSizeT); + } + return uSize; +} +function evaluateSizeForZoom(sizeData, zoom) { + let uSizeT = 0; + let uSize = 0; + if (sizeData.kind === 'constant') { + uSize = sizeData.layoutSize; + } + else if (sizeData.kind !== 'source') { + const { interpolationType, minZoom, maxZoom } = sizeData; + // Even though we could get the exact value of the camera function + // at z = tr.zoom, we intentionally do not: instead, we interpolate + // between the camera function values at a pair of zoom stops covering + // [tileZoom, tileZoom + 1] in order to be consistent with this + // restriction on composite functions + const t = !interpolationType ? 0 : clamp$1(Interpolate.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1); + if (sizeData.kind === 'camera') { + uSize = interpolate.number(sizeData.minSize, sizeData.maxSize, t); + } + else { + uSizeT = t; + } + } + return { uSizeT, uSize }; +} + +function getOverlapMode(layout, overlapProp, allowOverlapProp) { + let result = 'never'; + const overlap = layout.get(overlapProp); + if (overlap) { + // if -overlap is set, use it + result = overlap; + } + else if (layout.get(allowOverlapProp)) { + // fall back to -allow-overlap, with false='never', true='always' + result = 'always'; + } + return result; +} + +const vectorTileFeatureTypes = vectorTile.VectorTileFeature.types; +// Opacity arrays are frequently updated but don't contain a lot of information, so we pack them +// tight. Each Uint32 is actually four duplicate Uint8s for the four corners of a glyph +// 7 bits are for the current opacity, and the lowest bit is the target opacity +// actually defined in symbol_attributes.js +// const placementOpacityAttributes = [ +// { name: 'a_fade_opacity', components: 1, type: 'Uint32' } +// ]; +const shaderOpacityAttributes = [ + { name: 'a_fade_opacity', components: 1, type: 'Uint8', offset: 0 } +]; +function addVertex(array, anchorX, anchorY, ox, oy, tx, ty, sizeVertex, isSDF, pixelOffsetX, pixelOffsetY, minFontScaleX, minFontScaleY) { + const aSizeX = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[0])) : 0; + const aSizeY = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[1])) : 0; + array.emplaceBack( + // a_pos_offset + anchorX, anchorY, Math.round(ox * 32), Math.round(oy * 32), + // a_data + tx, // x coordinate of symbol on glyph atlas texture + ty, // y coordinate of symbol on glyph atlas texture + (aSizeX << 1) + (isSDF ? 1 : 0), aSizeY, pixelOffsetX * 16, pixelOffsetY * 16, minFontScaleX * 256, minFontScaleY * 256); +} +function addDynamicAttributes(dynamicLayoutVertexArray, p, angle) { + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); +} +function containsRTLText(formattedText) { + for (const section of formattedText.sections) { + if (stringContainsRTLText(section.text)) { + return true; + } + } + return false; +} +class SymbolBuffers { + constructor(programConfigurations) { + this.layoutVertexArray = new SymbolLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.programConfigurations = programConfigurations; + this.segments = new SegmentVector(); + this.dynamicLayoutVertexArray = new SymbolDynamicLayoutArray(); + this.opacityVertexArray = new SymbolOpacityArray(); + this.hasVisibleVertices = false; + this.placedSymbolArray = new PlacedSymbolArray(); + } + isEmpty() { + return this.layoutVertexArray.length === 0 && + this.indexArray.length === 0 && + this.dynamicLayoutVertexArray.length === 0 && + this.opacityVertexArray.length === 0; + } + upload(context, dynamicIndexBuffer, upload, update) { + if (this.isEmpty()) { + return; + } + if (upload) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members); + this.indexBuffer = context.createIndexBuffer(this.indexArray, dynamicIndexBuffer); + this.dynamicLayoutVertexBuffer = context.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, true); + this.opacityVertexBuffer = context.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, true); + // This is a performance hack so that we can write to opacityVertexArray with uint32s + // even though the shaders read uint8s + this.opacityVertexBuffer.itemSize = 1; + } + if (upload || update) { + this.programConfigurations.upload(context); + } + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + this.dynamicLayoutVertexBuffer.destroy(); + this.opacityVertexBuffer.destroy(); + } +} +register('SymbolBuffers', SymbolBuffers); +class CollisionBuffers { + constructor(LayoutArray, layoutAttributes, IndexArray) { + this.layoutVertexArray = new LayoutArray(); + this.layoutAttributes = layoutAttributes; + this.indexArray = new IndexArray(); + this.segments = new SegmentVector(); + this.collisionVertexArray = new CollisionVertexArray(); + } + upload(context) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + this.collisionVertexBuffer = context.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, true); + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.segments.destroy(); + this.collisionVertexBuffer.destroy(); + } +} +register('CollisionBuffers', CollisionBuffers); +/** + * @internal + * Unlike other buckets, which simply implement #addFeature with type-specific + * logic for (essentially) triangulating feature geometries, SymbolBucket + * requires specialized behavior: + * + * 1. WorkerTile#parse(), the logical owner of the bucket creation process, + * calls SymbolBucket#populate(), which resolves text and icon tokens on + * each feature, adds each glyphs and symbols needed to the passed-in + * collections options.glyphDependencies and options.iconDependencies, and + * stores the feature data for use in subsequent step (this.features). + * + * 2. WorkerTile asynchronously requests from the main thread all of the glyphs + * and icons needed (by this bucket and any others). When glyphs and icons + * have been received, the WorkerTile creates a CollisionIndex and invokes: + * + * 3. performSymbolLayout(bucket, stacks, icons) perform texts shaping and + * layout on a Symbol Bucket. This step populates: + * `this.symbolInstances`: metadata on generated symbols + * `this.collisionBoxArray`: collision data for use by foreground + * `this.text`: SymbolBuffers for text symbols + * `this.icons`: SymbolBuffers for icons + * `this.iconCollisionBox`: Debug SymbolBuffers for icon collision boxes + * `this.textCollisionBox`: Debug SymbolBuffers for text collision boxes + * The results are sent to the foreground for rendering + * + * 4. placement.ts is run on the foreground, + * and uses the CollisionIndex along with current camera settings to determine + * which symbols can actually show on the map. Collided symbols are hidden + * using a dynamic "OpacityVertexArray". + */ +class SymbolBucket { + constructor(options) { + this.collisionBoxArray = options.collisionBoxArray; + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.pixelRatio = options.pixelRatio; + this.sourceLayerIndex = options.sourceLayerIndex; + this.hasPattern = false; + this.hasRTLText = false; + this.sortKeyRanges = []; + this.collisionCircleArray = []; + this.placementInvProjMatrix = identity$2([]); + this.placementViewportMatrix = identity$2([]); + const layer = this.layers[0]; + const unevaluatedLayoutValues = layer._unevaluatedLayout._values; + this.textSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['text-size']); + this.iconSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['icon-size']); + const layout = this.layers[0].layout; + const sortKey = layout.get('symbol-sort-key'); + const zOrder = layout.get('symbol-z-order'); + this.canOverlap = + getOverlapMode(layout, 'text-overlap', 'text-allow-overlap') !== 'never' || + getOverlapMode(layout, 'icon-overlap', 'icon-allow-overlap') !== 'never' || + layout.get('text-ignore-placement') || + layout.get('icon-ignore-placement'); + this.sortFeaturesByKey = zOrder !== 'viewport-y' && !sortKey.isConstant(); + const zOrderByViewportY = zOrder === 'viewport-y' || (zOrder === 'auto' && !this.sortFeaturesByKey); + this.sortFeaturesByY = zOrderByViewportY && this.canOverlap; + if (layout.get('symbol-placement') === 'point') { + this.writingModes = layout.get('text-writing-mode').map(wm => WritingMode[wm]); + } + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + this.sourceID = options.sourceID; + } + createArrays() { + this.text = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^text/.test(property))); + this.icon = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^icon/.test(property))); + this.glyphOffsetArray = new GlyphOffsetArray(); + this.lineVertexArray = new SymbolLineVertexArray(); + this.symbolInstances = new SymbolInstanceArray(); + this.textAnchorOffsets = new TextAnchorOffsetArray(); + } + calculateGlyphDependencies(text, stack, textAlongLine, allowVerticalPlacement, doesAllowVerticalWritingMode) { + for (let i = 0; i < text.length; i++) { + stack[text.charCodeAt(i)] = true; + if ((textAlongLine || allowVerticalPlacement) && doesAllowVerticalWritingMode) { + const verticalChar = verticalizedCharacterMap[text.charAt(i)]; + if (verticalChar) { + stack[verticalChar.charCodeAt(0)] = true; + } + } + } + } + populate(features, options, canonical) { + const layer = this.layers[0]; + const layout = layer.layout; + const textFont = layout.get('text-font'); + const textField = layout.get('text-field'); + const iconImage = layout.get('icon-image'); + const hasText = (textField.value.kind !== 'constant' || + (textField.value.value instanceof Formatted && !textField.value.value.isEmpty()) || + textField.value.value.toString().length > 0) && + (textFont.value.kind !== 'constant' || textFont.value.value.length > 0); + // we should always resolve the icon-image value if the property was defined in the style + // this allows us to fire the styleimagemissing event if image evaluation returns null + // the only way to distinguish between null returned from a coalesce statement with no valid images + // and null returned because icon-image wasn't defined is to check whether or not iconImage.parameters is an empty object + const hasIcon = iconImage.value.kind !== 'constant' || !!iconImage.value.value || Object.keys(iconImage.parameters).length > 0; + const symbolSortKey = layout.get('symbol-sort-key'); + this.features = []; + if (!hasText && !hasIcon) { + return; + } + const icons = options.iconDependencies; + const stacks = options.glyphDependencies; + const availableImages = options.availableImages; + const globalProperties = new EvaluationParameters(this.zoom); + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = layer._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) { + continue; + } + if (!needGeometry) + evaluationFeature.geometry = loadGeometry(feature); + let text; + if (hasText) { + // Expression evaluation will automatically coerce to Formatted + // but plain string token evaluation skips that pathway so do the + // conversion here. + const resolvedTokens = layer.getValueAndResolveTokens('text-field', evaluationFeature, canonical, availableImages); + const formattedText = Formatted.factory(resolvedTokens); + // on this instance: if hasRTLText is already true, all future calls to containsRTLText can be skipped. + const bucketHasRTLText = this.hasRTLText = (this.hasRTLText || containsRTLText(formattedText)); + if (!bucketHasRTLText || // non-rtl text so can proceed safely + rtlWorkerPlugin.getRTLTextPluginStatus() === 'unavailable' || // We don't intend to lazy-load the rtl text plugin, so proceed with incorrect shaping + bucketHasRTLText && rtlWorkerPlugin.isParsed() // Use the rtlText plugin to shape text + ) { + text = transformText(formattedText, layer, evaluationFeature); + } + } + let icon; + if (hasIcon) { + // Expression evaluation will automatically coerce to Image + // but plain string token evaluation skips that pathway so do the + // conversion here. + const resolvedTokens = layer.getValueAndResolveTokens('icon-image', evaluationFeature, canonical, availableImages); + if (resolvedTokens instanceof ResolvedImage) { + icon = resolvedTokens; + } + else { + icon = ResolvedImage.fromString(resolvedTokens); + } + } + if (!text && !icon) { + continue; + } + const sortKey = this.sortFeaturesByKey ? + symbolSortKey.evaluate(evaluationFeature, {}, canonical) : + undefined; + const symbolFeature = { + id, + text, + icon, + index, + sourceLayerIndex, + geometry: evaluationFeature.geometry, + properties: feature.properties, + type: vectorTileFeatureTypes[feature.type], + sortKey + }; + this.features.push(symbolFeature); + if (icon) { + icons[icon.name] = true; + } + if (text) { + const fontStack = textFont.evaluate(evaluationFeature, {}, canonical).join(','); + const textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point'; + this.allowVerticalPlacement = this.writingModes && this.writingModes.indexOf(WritingMode.vertical) >= 0; + for (const section of text.sections) { + if (!section.image) { + const doesAllowVerticalWritingMode = allowsVerticalWritingMode(text.toString()); + const sectionFont = section.fontStack || fontStack; + const sectionStack = stacks[sectionFont] = stacks[sectionFont] || {}; + this.calculateGlyphDependencies(section.text, sectionStack, textAlongLine, this.allowVerticalPlacement, doesAllowVerticalWritingMode); + } + else { + // Add section image to the list of dependencies. + icons[section.image.name] = true; + } + } + } + } + if (layout.get('symbol-placement') === 'line') { + // Merge adjacent lines with the same text to improve labelling. + // It's better to place labels on one long line than on many short segments. + this.features = mergeLines(this.features); + } + if (this.sortFeaturesByKey) { + this.features.sort((a, b) => { + // a.sortKey is always a number when sortFeaturesByKey is true + return a.sortKey - b.sortKey; + }); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.text.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions); + this.icon.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions); + } + isEmpty() { + // When the bucket encounters only rtl-text but the plugin isn't loaded, no symbol instances will be created. + // In order for the bucket to be serialized, and not discarded as an empty bucket both checks are necessary. + return this.symbolInstances.length === 0 && !this.hasRTLText; + } + uploadPending() { + return !this.uploaded || this.text.programConfigurations.needsUpload || this.icon.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded && this.hasDebugData()) { + this.textCollisionBox.upload(context); + this.iconCollisionBox.upload(context); + } + this.text.upload(context, this.sortFeaturesByY, !this.uploaded, this.text.programConfigurations.needsUpload); + this.icon.upload(context, this.sortFeaturesByY, !this.uploaded, this.icon.programConfigurations.needsUpload); + this.uploaded = true; + } + destroyDebugData() { + this.textCollisionBox.destroy(); + this.iconCollisionBox.destroy(); + } + destroy() { + this.text.destroy(); + this.icon.destroy(); + if (this.hasDebugData()) { + this.destroyDebugData(); + } + } + addToLineVertexArray(anchor, line) { + const lineStartIndex = this.lineVertexArray.length; + if (anchor.segment !== undefined) { + let sumForwardLength = anchor.dist(line[anchor.segment + 1]); + let sumBackwardLength = anchor.dist(line[anchor.segment]); + const vertices = {}; + for (let i = anchor.segment + 1; i < line.length; i++) { + vertices[i] = { x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumForwardLength }; + if (i < line.length - 1) { + sumForwardLength += line[i + 1].dist(line[i]); + } + } + for (let i = anchor.segment || 0; i >= 0; i--) { + vertices[i] = { x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumBackwardLength }; + if (i > 0) { + sumBackwardLength += line[i - 1].dist(line[i]); + } + } + for (let i = 0; i < line.length; i++) { + const vertex = vertices[i]; + this.lineVertexArray.emplaceBack(vertex.x, vertex.y, vertex.tileUnitDistanceFromAnchor); + } + } + return { + lineStartIndex, + lineLength: this.lineVertexArray.length - lineStartIndex + }; + } + addSymbols(arrays, quads, sizeVertex, lineOffset, alongLine, feature, writingMode, labelAnchor, lineStartIndex, lineLength, associatedIconIndex, canonical) { + const indexArray = arrays.indexArray; + const layoutVertexArray = arrays.layoutVertexArray; + const segment = arrays.segments.prepareSegment(4 * quads.length, layoutVertexArray, indexArray, this.canOverlap ? feature.sortKey : undefined); + const glyphOffsetArrayStart = this.glyphOffsetArray.length; + const vertexStartIndex = segment.vertexLength; + const angle = (this.allowVerticalPlacement && writingMode === WritingMode.vertical) ? Math.PI / 2 : 0; + const sections = feature.text && feature.text.sections; + for (let i = 0; i < quads.length; i++) { + const { tl, tr, bl, br, tex, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, glyphOffset, isSDF, sectionIndex } = quads[i]; + const index = segment.vertexLength; + const y = glyphOffset[1]; + addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY); + 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); + 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); + 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); + addDynamicAttributes(arrays.dynamicLayoutVertexArray, labelAnchor, angle); + indexArray.emplaceBack(index, index + 1, index + 2); + indexArray.emplaceBack(index + 1, index + 2, index + 3); + segment.vertexLength += 4; + segment.primitiveLength += 2; + this.glyphOffsetArray.emplaceBack(glyphOffset[0]); + if (i === quads.length - 1 || sectionIndex !== quads[i + 1].sectionIndex) { + arrays.programConfigurations.populatePaintArrays(layoutVertexArray.length, feature, feature.index, {}, canonical, sections && sections[sectionIndex]); + } + } + arrays.placedSymbolArray.emplaceBack(labelAnchor.x, labelAnchor.y, glyphOffsetArrayStart, this.glyphOffsetArray.length - glyphOffsetArrayStart, vertexStartIndex, lineStartIndex, lineLength, labelAnchor.segment, sizeVertex ? sizeVertex[0] : 0, sizeVertex ? sizeVertex[1] : 0, lineOffset[0], lineOffset[1], writingMode, + // placedOrientation is null initially; will be updated to horizontal(1)/vertical(2) if placed + 0, false, + // The crossTileID is only filled/used on the foreground for dynamic text anchors + 0, associatedIconIndex); + } + _addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, point, anchorX, anchorY, extrude) { + collisionVertexArray.emplaceBack(0, 0); + return layoutVertexArray.emplaceBack( + // pos + point.x, point.y, + // a_anchor_pos + anchorX, anchorY, + // extrude + Math.round(extrude.x), Math.round(extrude.y)); + } + addCollisionDebugVertices(x1, y1, x2, y2, arrays, boxAnchorPoint, symbolInstance) { + const segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray); + const index = segment.vertexLength; + const layoutVertexArray = arrays.layoutVertexArray; + const collisionVertexArray = arrays.collisionVertexArray; + const anchorX = symbolInstance.anchorX; + const anchorY = symbolInstance.anchorY; + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$3(x1, y1)); + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$3(x2, y1)); + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$3(x2, y2)); + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$3(x1, y2)); + segment.vertexLength += 4; + const indexArray = arrays.indexArray; + indexArray.emplaceBack(index, index + 1); + indexArray.emplaceBack(index + 1, index + 2); + indexArray.emplaceBack(index + 2, index + 3); + indexArray.emplaceBack(index + 3, index); + segment.primitiveLength += 4; + } + addDebugCollisionBoxes(startIndex, endIndex, symbolInstance, isText) { + for (let b = startIndex; b < endIndex; b++) { + const box = this.collisionBoxArray.get(b); + const x1 = box.x1; + const y1 = box.y1; + const x2 = box.x2; + const y2 = box.y2; + this.addCollisionDebugVertices(x1, y1, x2, y2, isText ? this.textCollisionBox : this.iconCollisionBox, box.anchorPoint, symbolInstance); + } + } + generateCollisionDebugBuffers() { + if (this.hasDebugData()) { + this.destroyDebugData(); + } + this.textCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray); + this.iconCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray); + for (let i = 0; i < this.symbolInstances.length; i++) { + const symbolInstance = this.symbolInstances.get(i); + this.addDebugCollisionBoxes(symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance, true); + this.addDebugCollisionBoxes(symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance, true); + this.addDebugCollisionBoxes(symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance, false); + this.addDebugCollisionBoxes(symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance, false); + } + } + // These flat arrays are meant to be quicker to iterate over than the source + // CollisionBoxArray + _deserializeCollisionBoxesForSymbol(collisionBoxArray, textStartIndex, textEndIndex, verticalTextStartIndex, verticalTextEndIndex, iconStartIndex, iconEndIndex, verticalIconStartIndex, verticalIconEndIndex) { + const collisionArrays = {}; + for (let k = textStartIndex; k < textEndIndex; k++) { + const box = collisionBoxArray.get(k); + collisionArrays.textBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.textFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + for (let k = verticalTextStartIndex; k < verticalTextEndIndex; k++) { + const box = collisionBoxArray.get(k); + collisionArrays.verticalTextBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.verticalTextFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + for (let k = iconStartIndex; k < iconEndIndex; k++) { + // An icon can only have one box now, so this indexing is a bit vestigial... + const box = collisionBoxArray.get(k); + collisionArrays.iconBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.iconFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + for (let k = verticalIconStartIndex; k < verticalIconEndIndex; k++) { + // An icon can only have one box now, so this indexing is a bit vestigial... + const box = collisionBoxArray.get(k); + collisionArrays.verticalIconBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.verticalIconFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + return collisionArrays; + } + deserializeCollisionBoxes(collisionBoxArray) { + this.collisionArrays = []; + for (let i = 0; i < this.symbolInstances.length; i++) { + const symbolInstance = this.symbolInstances.get(i); + this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(collisionBoxArray, symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex)); + } + } + hasTextData() { + return this.text.segments.get().length > 0; + } + hasIconData() { + return this.icon.segments.get().length > 0; + } + hasDebugData() { + return this.textCollisionBox && this.iconCollisionBox; + } + hasTextCollisionBoxData() { + return this.hasDebugData() && this.textCollisionBox.segments.get().length > 0; + } + hasIconCollisionBoxData() { + return this.hasDebugData() && this.iconCollisionBox.segments.get().length > 0; + } + addIndicesForPlacedSymbol(iconOrText, placedSymbolIndex) { + const placedSymbol = iconOrText.placedSymbolArray.get(placedSymbolIndex); + const endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4; + for (let vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) { + iconOrText.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2); + iconOrText.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3); + } + } + getSortedSymbolIndexes(angle) { + if (this.sortedAngle === angle && this.symbolInstanceIndexes !== undefined) { + return this.symbolInstanceIndexes; + } + const sin = Math.sin(angle); + const cos = Math.cos(angle); + const rotatedYs = []; + const featureIndexes = []; + const result = []; + for (let i = 0; i < this.symbolInstances.length; ++i) { + result.push(i); + const symbolInstance = this.symbolInstances.get(i); + rotatedYs.push(Math.round(sin * symbolInstance.anchorX + cos * symbolInstance.anchorY) | 0); + featureIndexes.push(symbolInstance.featureIndex); + } + result.sort((aIndex, bIndex) => { + return (rotatedYs[aIndex] - rotatedYs[bIndex]) || + (featureIndexes[bIndex] - featureIndexes[aIndex]); + }); + return result; + } + addToSortKeyRanges(symbolInstanceIndex, sortKey) { + const last = this.sortKeyRanges[this.sortKeyRanges.length - 1]; + if (last && last.sortKey === sortKey) { + last.symbolInstanceEnd = symbolInstanceIndex + 1; + } + else { + this.sortKeyRanges.push({ + sortKey, + symbolInstanceStart: symbolInstanceIndex, + symbolInstanceEnd: symbolInstanceIndex + 1 + }); + } + } + sortFeatures(angle) { + if (!this.sortFeaturesByY) + return; + if (this.sortedAngle === angle) + return; + // The current approach to sorting doesn't sort across segments so don't try. + // Sorting within segments separately seemed not to be worth the complexity. + if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1) + return; + // If the symbols are allowed to overlap sort them by their vertical screen position. + // The index array buffer is rewritten to reference the (unchanged) vertices in the + // sorted order. + // To avoid sorting the actual symbolInstance array we sort an array of indexes. + this.symbolInstanceIndexes = this.getSortedSymbolIndexes(angle); + this.sortedAngle = angle; + this.text.indexArray.clear(); + this.icon.indexArray.clear(); + this.featureSortOrder = []; + for (const i of this.symbolInstanceIndexes) { + const symbolInstance = this.symbolInstances.get(i); + this.featureSortOrder.push(symbolInstance.featureIndex); + [ + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.leftJustifiedTextSymbolIndex + ].forEach((index, i, array) => { + // Only add a given index the first time it shows up, + // to avoid duplicate opacity entries when multiple justifications + // share the same glyphs. + if (index >= 0 && array.indexOf(index) === i) { + this.addIndicesForPlacedSymbol(this.text, index); + } + }); + if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) { + this.addIndicesForPlacedSymbol(this.text, symbolInstance.verticalPlacedTextSymbolIndex); + } + if (symbolInstance.placedIconSymbolIndex >= 0) { + this.addIndicesForPlacedSymbol(this.icon, symbolInstance.placedIconSymbolIndex); + } + if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) { + this.addIndicesForPlacedSymbol(this.icon, symbolInstance.verticalPlacedIconSymbolIndex); + } + } + if (this.text.indexBuffer) + this.text.indexBuffer.updateData(this.text.indexArray); + if (this.icon.indexBuffer) + this.icon.indexBuffer.updateData(this.icon.indexArray); + } +} +register('SymbolBucket', SymbolBucket, { + omit: ['layers', 'collisionBoxArray', 'features', 'compareText'] +}); +// this constant is based on the size of StructArray indexes used in a symbol +// bucket--namely, glyphOffsetArrayStart +// eg the max valid UInt16 is 65,535 +// See https://github.com/mapbox/mapbox-gl-js/issues/2907 for motivation +// lineStartIndex and textBoxStartIndex could potentially be concerns +// but we expect there to be many fewer boxes/lines than glyphs +SymbolBucket.MAX_GLYPHS = 65535; +SymbolBucket.addDynamicAttributes = addDynamicAttributes; + +/** + * Replace tokens in a string template with values in an object + * + * @param properties - a key/value relationship between tokens and replacements + * @param text - the template string + * @returns the template with tokens replaced + */ +function resolveTokens(properties, text) { + return text.replace(/{([^{}]+)}/g, (match, key) => { + return properties && key in properties ? String(properties[key]) : ''; + }); +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout; +const getLayout = () => layout = layout || new Properties({ + "symbol-placement": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-placement"]), + "symbol-spacing": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-spacing"]), + "symbol-avoid-edges": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-avoid-edges"]), + "symbol-sort-key": new DataDrivenProperty(v8Spec["layout_symbol"]["symbol-sort-key"]), + "symbol-z-order": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-z-order"]), + "icon-allow-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["icon-allow-overlap"]), + "icon-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["icon-overlap"]), + "icon-ignore-placement": new DataConstantProperty(v8Spec["layout_symbol"]["icon-ignore-placement"]), + "icon-optional": new DataConstantProperty(v8Spec["layout_symbol"]["icon-optional"]), + "icon-rotation-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["icon-rotation-alignment"]), + "icon-size": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-size"]), + "icon-text-fit": new DataConstantProperty(v8Spec["layout_symbol"]["icon-text-fit"]), + "icon-text-fit-padding": new DataConstantProperty(v8Spec["layout_symbol"]["icon-text-fit-padding"]), + "icon-image": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-image"]), + "icon-rotate": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-rotate"]), + "icon-padding": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-padding"]), + "icon-keep-upright": new DataConstantProperty(v8Spec["layout_symbol"]["icon-keep-upright"]), + "icon-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-offset"]), + "icon-anchor": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-anchor"]), + "icon-pitch-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["icon-pitch-alignment"]), + "text-pitch-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["text-pitch-alignment"]), + "text-rotation-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["text-rotation-alignment"]), + "text-field": new DataDrivenProperty(v8Spec["layout_symbol"]["text-field"]), + "text-font": new DataDrivenProperty(v8Spec["layout_symbol"]["text-font"]), + "text-size": new DataDrivenProperty(v8Spec["layout_symbol"]["text-size"]), + "text-max-width": new DataDrivenProperty(v8Spec["layout_symbol"]["text-max-width"]), + "text-line-height": new DataConstantProperty(v8Spec["layout_symbol"]["text-line-height"]), + "text-letter-spacing": new DataDrivenProperty(v8Spec["layout_symbol"]["text-letter-spacing"]), + "text-justify": new DataDrivenProperty(v8Spec["layout_symbol"]["text-justify"]), + "text-radial-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["text-radial-offset"]), + "text-variable-anchor": new DataConstantProperty(v8Spec["layout_symbol"]["text-variable-anchor"]), + "text-variable-anchor-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["text-variable-anchor-offset"]), + "text-anchor": new DataDrivenProperty(v8Spec["layout_symbol"]["text-anchor"]), + "text-max-angle": new DataConstantProperty(v8Spec["layout_symbol"]["text-max-angle"]), + "text-writing-mode": new DataConstantProperty(v8Spec["layout_symbol"]["text-writing-mode"]), + "text-rotate": new DataDrivenProperty(v8Spec["layout_symbol"]["text-rotate"]), + "text-padding": new DataConstantProperty(v8Spec["layout_symbol"]["text-padding"]), + "text-keep-upright": new DataConstantProperty(v8Spec["layout_symbol"]["text-keep-upright"]), + "text-transform": new DataDrivenProperty(v8Spec["layout_symbol"]["text-transform"]), + "text-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["text-offset"]), + "text-allow-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["text-allow-overlap"]), + "text-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["text-overlap"]), + "text-ignore-placement": new DataConstantProperty(v8Spec["layout_symbol"]["text-ignore-placement"]), + "text-optional": new DataConstantProperty(v8Spec["layout_symbol"]["text-optional"]), +}); +let paint$2; +const getPaint$2 = () => paint$2 = paint$2 || new Properties({ + "icon-opacity": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-opacity"]), + "icon-color": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-color"]), + "icon-halo-color": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-color"]), + "icon-halo-width": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-width"]), + "icon-halo-blur": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-blur"]), + "icon-translate": new DataConstantProperty(v8Spec["paint_symbol"]["icon-translate"]), + "icon-translate-anchor": new DataConstantProperty(v8Spec["paint_symbol"]["icon-translate-anchor"]), + "text-opacity": new DataDrivenProperty(v8Spec["paint_symbol"]["text-opacity"]), + "text-color": new DataDrivenProperty(v8Spec["paint_symbol"]["text-color"], { runtimeType: ColorType, getOverride: (o) => o.textColor, hasOverride: (o) => !!o.textColor }), + "text-halo-color": new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-color"]), + "text-halo-width": new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-width"]), + "text-halo-blur": new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-blur"]), + "text-translate": new DataConstantProperty(v8Spec["paint_symbol"]["text-translate"]), + "text-translate-anchor": new DataConstantProperty(v8Spec["paint_symbol"]["text-translate-anchor"]), +}); +var properties$2 = ({ get paint() { return getPaint$2(); }, get layout() { return getLayout(); } }); + +// This is an internal expression class. It is only used in GL JS and +// has GL JS dependencies which can break the standalone style-spec module +class FormatSectionOverride { + constructor(defaultValue) { + if (defaultValue.property.overrides === undefined) + throw new Error('overrides must be provided to instantiate FormatSectionOverride class'); + this.type = defaultValue.property.overrides ? defaultValue.property.overrides.runtimeType : NullType; + this.defaultValue = defaultValue; + } + evaluate(ctx) { + if (ctx.formattedSection) { + const overrides = this.defaultValue.property.overrides; + if (overrides && overrides.hasOverride(ctx.formattedSection)) { + return overrides.getOverride(ctx.formattedSection); + } + } + if (ctx.feature && ctx.featureState) { + return this.defaultValue.evaluate(ctx.feature, ctx.featureState); + } + return this.defaultValue.property.specification.default; + } + eachChild(fn) { + if (!this.defaultValue.isConstant()) { + const expr = this.defaultValue.value; + fn(expr._styleExpression.expression); + } + } + // Cannot be statically evaluated, as the output depends on the evaluation context. + outputDefined() { + return false; + } + serialize() { + return null; + } +} +register('FormatSectionOverride', FormatSectionOverride, { omit: ['defaultValue'] }); + +class SymbolStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$2); + } + recalculate(parameters, availableImages) { + super.recalculate(parameters, availableImages); + if (this.layout.get('icon-rotation-alignment') === 'auto') { + if (this.layout.get('symbol-placement') !== 'point') { + this.layout._values['icon-rotation-alignment'] = 'map'; + } + else { + this.layout._values['icon-rotation-alignment'] = 'viewport'; + } + } + if (this.layout.get('text-rotation-alignment') === 'auto') { + if (this.layout.get('symbol-placement') !== 'point') { + this.layout._values['text-rotation-alignment'] = 'map'; + } + else { + this.layout._values['text-rotation-alignment'] = 'viewport'; + } + } + // If unspecified, `*-pitch-alignment` inherits `*-rotation-alignment` + if (this.layout.get('text-pitch-alignment') === 'auto') { + this.layout._values['text-pitch-alignment'] = this.layout.get('text-rotation-alignment') === 'map' ? 'map' : 'viewport'; + } + if (this.layout.get('icon-pitch-alignment') === 'auto') { + this.layout._values['icon-pitch-alignment'] = this.layout.get('icon-rotation-alignment'); + } + if (this.layout.get('symbol-placement') === 'point') { + const writingModes = this.layout.get('text-writing-mode'); + if (writingModes) { + // remove duplicates, preserving order + const deduped = []; + for (const m of writingModes) { + if (deduped.indexOf(m) < 0) + deduped.push(m); + } + this.layout._values['text-writing-mode'] = deduped; + } + else { + this.layout._values['text-writing-mode'] = ['horizontal']; + } + } + this._setPaintOverrides(); + } + getValueAndResolveTokens(name, feature, canonical, availableImages) { + const value = this.layout.get(name).evaluate(feature, {}, canonical, availableImages); + const unevaluated = this._unevaluatedLayout._values[name]; + if (!unevaluated.isDataDriven() && !isExpression(unevaluated.value) && value) { + return resolveTokens(feature.properties, value); + } + return value; + } + createBucket(parameters) { + return new SymbolBucket(parameters); + } + queryRadius() { + return 0; + } + queryIntersectsFeature() { + throw new Error('Should take a different path in FeatureIndex'); + } + _setPaintOverrides() { + for (const overridable of properties$2.paint.overridableProperties) { + if (!SymbolStyleLayer.hasPaintOverride(this.layout, overridable)) { + continue; + } + const overridden = this.paint.get(overridable); + const override = new FormatSectionOverride(overridden); + const styleExpression = new StyleExpression(override, overridden.property.specification); + let expression = null; + if (overridden.value.kind === 'constant' || overridden.value.kind === 'source') { + expression = new ZoomConstantExpression('source', styleExpression); + } + else { + expression = new ZoomDependentExpression('composite', styleExpression, overridden.value.zoomStops); + } + this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overridden.property, expression, overridden.parameters); + } + } + _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) { + if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) { + return false; + } + return SymbolStyleLayer.hasPaintOverride(this.layout, name); + } + static hasPaintOverride(layout, propertyName) { + const textField = layout.get('text-field'); + const property = properties$2.paint.properties[propertyName]; + let hasOverrides = false; + const checkSections = (sections) => { + for (const section of sections) { + if (property.overrides && property.overrides.hasOverride(section)) { + hasOverrides = true; + return; + } + } + }; + if (textField.value.kind === 'constant' && textField.value.value instanceof Formatted) { + checkSections(textField.value.value.sections); + } + else if (textField.value.kind === 'source') { + const checkExpression = (expression) => { + if (hasOverrides) + return; + if (expression instanceof Literal && typeOf(expression.value) === FormattedType) { + const formatted = expression.value; + checkSections(formatted.sections); + } + else if (expression instanceof FormatExpression) { + checkSections(expression.sections); + } + else { + expression.eachChild(checkExpression); + } + }; + const expr = textField.value; + if (expr._styleExpression) { + checkExpression(expr._styleExpression.expression); + } + } + return hasOverrides; + } +} +function getIconPadding(layout, feature, canonical, pixelRatio = 1) { + // Support text-padding in addition to icon-padding? Unclear how to apply asymmetric text-padding to the radius for collision circles. + const result = layout.get('icon-padding').evaluate(feature, {}, canonical); + const values = result && result.values; + return [ + values[0] * pixelRatio, + values[1] * pixelRatio, + values[2] * pixelRatio, + values[3] * pixelRatio, + ]; +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$1; +const getPaint$1 = () => paint$1 = paint$1 || new Properties({ + "background-color": new DataConstantProperty(v8Spec["paint_background"]["background-color"]), + "background-pattern": new CrossFadedProperty(v8Spec["paint_background"]["background-pattern"]), + "background-opacity": new DataConstantProperty(v8Spec["paint_background"]["background-opacity"]), +}); +var properties$1 = ({ get paint() { return getPaint$1(); } }); + +class BackgroundStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$1); + } +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint; +const getPaint = () => paint = paint || new Properties({ + "raster-opacity": new DataConstantProperty(v8Spec["paint_raster"]["raster-opacity"]), + "raster-hue-rotate": new DataConstantProperty(v8Spec["paint_raster"]["raster-hue-rotate"]), + "raster-brightness-min": new DataConstantProperty(v8Spec["paint_raster"]["raster-brightness-min"]), + "raster-brightness-max": new DataConstantProperty(v8Spec["paint_raster"]["raster-brightness-max"]), + "raster-saturation": new DataConstantProperty(v8Spec["paint_raster"]["raster-saturation"]), + "raster-contrast": new DataConstantProperty(v8Spec["paint_raster"]["raster-contrast"]), + "raster-resampling": new DataConstantProperty(v8Spec["paint_raster"]["raster-resampling"]), + "raster-fade-duration": new DataConstantProperty(v8Spec["paint_raster"]["raster-fade-duration"]), +}); +var properties = ({ get paint() { return getPaint(); } }); + +class RasterStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties); + } +} + +function validateCustomStyleLayer(layerObject) { + const errors = []; + const id = layerObject.id; + if (id === undefined) { + errors.push({ + message: `layers.${id}: missing required property "id"` + }); + } + if (layerObject.render === undefined) { + errors.push({ + message: `layers.${id}: missing required method "render"` + }); + } + if (layerObject.renderingMode && + layerObject.renderingMode !== '2d' && + layerObject.renderingMode !== '3d') { + errors.push({ + message: `layers.${id}: property "renderingMode" must be either "2d" or "3d"` + }); + } + return errors; +} +class CustomStyleLayer extends StyleLayer { + constructor(implementation) { + super(implementation, {}); + this.onAdd = (map) => { + if (this.implementation.onAdd) { + this.implementation.onAdd(map, map.painter.context.gl); + } + }; + this.onRemove = (map) => { + if (this.implementation.onRemove) { + this.implementation.onRemove(map, map.painter.context.gl); + } + }; + this.implementation = implementation; + } + is3D() { + return this.implementation.renderingMode === '3d'; + } + hasOffscreenPass() { + return this.implementation.prerender !== undefined; + } + recalculate() { } + updateTransitions() { } + hasTransition() { return false; } + serialize() { + throw new Error('Custom layers cannot be serialized'); + } +} + +function createStyleLayer(layer) { + if (layer.type === 'custom') { + return new CustomStyleLayer(layer); + } + switch (layer.type) { + case 'background': + return new BackgroundStyleLayer(layer); + case 'circle': + return new CircleStyleLayer(layer); + case 'fill': + return new FillStyleLayer(layer); + case 'fill-extrusion': + return new FillExtrusionStyleLayer(layer); + case 'heatmap': + return new HeatmapStyleLayer(layer); + case 'hillshade': + return new HillshadeStyleLayer(layer); + case 'line': + return new LineStyleLayer(layer); + case 'raster': + return new RasterStyleLayer(layer); + case 'symbol': + return new SymbolStyleLayer(layer); + } +} + +class StyleLayerIndex { + constructor(layerConfigs) { + this.keyCache = {}; + if (layerConfigs) { + this.replace(layerConfigs); + } + } + replace(layerConfigs) { + this._layerConfigs = {}; + this._layers = {}; + this.update(layerConfigs, []); + } + update(layerConfigs, removedIds) { + for (const layerConfig of layerConfigs) { + this._layerConfigs[layerConfig.id] = layerConfig; + const layer = this._layers[layerConfig.id] = createStyleLayer(layerConfig); + layer._featureFilter = createFilter(layer.filter); + if (this.keyCache[layerConfig.id]) + delete this.keyCache[layerConfig.id]; + } + for (const id of removedIds) { + delete this.keyCache[id]; + delete this._layerConfigs[id]; + delete this._layers[id]; + } + this.familiesBySource = {}; + const groups = groupByLayout(Object.values(this._layerConfigs), this.keyCache); + for (const layerConfigs of groups) { + const layers = layerConfigs.map((layerConfig) => this._layers[layerConfig.id]); + const layer = layers[0]; + if (layer.visibility === 'none') { + continue; + } + const sourceId = layer.source || ''; + let sourceGroup = this.familiesBySource[sourceId]; + if (!sourceGroup) { + sourceGroup = this.familiesBySource[sourceId] = {}; + } + const sourceLayerId = layer.sourceLayer || '_geojsonTileLayer'; + let sourceLayerFamilies = sourceGroup[sourceLayerId]; + if (!sourceLayerFamilies) { + sourceLayerFamilies = sourceGroup[sourceLayerId] = []; + } + sourceLayerFamilies.push(layers); + } + } +} + +class DictionaryCoder { + constructor(strings) { + this._stringToNumber = {}; + this._numberToString = []; + for (let i = 0; i < strings.length; i++) { + const string = strings[i]; + this._stringToNumber[string] = i; + this._numberToString[i] = string; + } + } + encode(string) { + return this._stringToNumber[string]; + } + decode(n) { + if (n >= this._numberToString.length) + throw new Error(`Out of bounds. Index requested n=${n} can't be >= this._numberToString.length ${this._numberToString.length}`); + return this._numberToString[n]; + } +} + +/** + * A geojson feature + */ +class GeoJSONFeature { + constructor(vectorTileFeature, z, x, y, id) { + this.type = 'Feature'; + this._vectorTileFeature = vectorTileFeature; + vectorTileFeature._z = z; + vectorTileFeature._x = x; + vectorTileFeature._y = y; + this.properties = vectorTileFeature.properties; + this.id = id; + } + get geometry() { + if (this._geometry === undefined) { + this._geometry = this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x, this._vectorTileFeature._y, this._vectorTileFeature._z).geometry; + } + return this._geometry; + } + set geometry(g) { + this._geometry = g; + } + toJSON() { + const json = { + geometry: this.geometry + }; + for (const i in this) { + if (i === '_geometry' || i === '_vectorTileFeature') + continue; + json[i] = (this)[i]; + } + return json; + } +} + +/** + * An in memory index class to allow fast interaction with features + */ +class FeatureIndex { + constructor(tileID, promoteId) { + this.tileID = tileID; + this.x = tileID.canonical.x; + this.y = tileID.canonical.y; + this.z = tileID.canonical.z; + this.grid = new TransferableGridIndex(EXTENT, 16, 0); + this.grid3D = new TransferableGridIndex(EXTENT, 16, 0); + this.featureIndexArray = new FeatureIndexArray(); + this.promoteId = promoteId; + } + insert(feature, geometry, featureIndex, sourceLayerIndex, bucketIndex, is3D) { + const key = this.featureIndexArray.length; + this.featureIndexArray.emplaceBack(featureIndex, sourceLayerIndex, bucketIndex); + const grid = is3D ? this.grid3D : this.grid; + for (let r = 0; r < geometry.length; r++) { + const ring = geometry[r]; + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + for (let i = 0; i < ring.length; i++) { + const p = ring[i]; + bbox[0] = Math.min(bbox[0], p.x); + bbox[1] = Math.min(bbox[1], p.y); + bbox[2] = Math.max(bbox[2], p.x); + bbox[3] = Math.max(bbox[3], p.y); + } + if (bbox[0] < EXTENT && + bbox[1] < EXTENT && + bbox[2] >= 0 && + bbox[3] >= 0) { + grid.insert(key, bbox[0], bbox[1], bbox[2], bbox[3]); + } + } + } + loadVTLayers() { + if (!this.vtLayers) { + this.vtLayers = new vectorTile.VectorTile(new Protobuf(this.rawTileData)).layers; + this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : ['_geojsonTileLayer']); + } + return this.vtLayers; + } + // Finds non-symbol features in this tile at a particular position. + query(args, styleLayers, serializedLayers, sourceFeatureState) { + this.loadVTLayers(); + const params = args.params || {}, pixelsToTileUnits = EXTENT / args.tileSize / args.scale, filter = createFilter(params.filter); + const queryGeometry = args.queryGeometry; + const queryPadding = args.queryPadding * pixelsToTileUnits; + const bounds = getBounds(queryGeometry); + const matching = this.grid.query(bounds.minX - queryPadding, bounds.minY - queryPadding, bounds.maxX + queryPadding, bounds.maxY + queryPadding); + const cameraBounds = getBounds(args.cameraQueryGeometry); + const matching3D = this.grid3D.query(cameraBounds.minX - queryPadding, cameraBounds.minY - queryPadding, cameraBounds.maxX + queryPadding, cameraBounds.maxY + queryPadding, (bx1, by1, bx2, by2) => { + return polygonIntersectsBox(args.cameraQueryGeometry, bx1 - queryPadding, by1 - queryPadding, bx2 + queryPadding, by2 + queryPadding); + }); + for (const key of matching3D) { + matching.push(key); + } + matching.sort(topDownFeatureComparator); + const result = {}; + let previousIndex; + for (let k = 0; k < matching.length; k++) { + const index = matching[k]; + // don't check the same feature more than once + if (index === previousIndex) + continue; + previousIndex = index; + const match = this.featureIndexArray.get(index); + let featureGeometry = null; + this.loadMatchingFeature(result, match.bucketIndex, match.sourceLayerIndex, match.featureIndex, filter, params.layers, params.availableImages, styleLayers, serializedLayers, sourceFeatureState, (feature, styleLayer, featureState) => { + if (!featureGeometry) { + featureGeometry = loadGeometry(feature); + } + return styleLayer.queryIntersectsFeature(queryGeometry, feature, featureState, featureGeometry, this.z, args.transform, pixelsToTileUnits, args.pixelPosMatrix); + }); + } + return result; + } + loadMatchingFeature(result, bucketIndex, sourceLayerIndex, featureIndex, filter, filterLayerIDs, availableImages, styleLayers, serializedLayers, sourceFeatureState, intersectionTest) { + const layerIDs = this.bucketLayerIDs[bucketIndex]; + if (filterLayerIDs && !arraysIntersect(filterLayerIDs, layerIDs)) + return; + const sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex); + const sourceLayer = this.vtLayers[sourceLayerName]; + const feature = sourceLayer.feature(featureIndex); + if (filter.needGeometry) { + const evaluationFeature = toEvaluationFeature(feature, true); + if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) { + return; + } + } + else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) { + return; + } + const id = this.getId(feature, sourceLayerName); + for (let l = 0; l < layerIDs.length; l++) { + const layerID = layerIDs[l]; + if (filterLayerIDs && filterLayerIDs.indexOf(layerID) < 0) { + continue; + } + const styleLayer = styleLayers[layerID]; + if (!styleLayer) + continue; + let featureState = {}; + if (id && sourceFeatureState) { + // `feature-state` expression evaluation requires feature state to be available + featureState = sourceFeatureState.getState(styleLayer.sourceLayer || '_geojsonTileLayer', id); + } + const serializedLayer = extend$1({}, serializedLayers[layerID]); + serializedLayer.paint = evaluateProperties(serializedLayer.paint, styleLayer.paint, feature, featureState, availableImages); + serializedLayer.layout = evaluateProperties(serializedLayer.layout, styleLayer.layout, feature, featureState, availableImages); + const intersectionZ = !intersectionTest || intersectionTest(feature, styleLayer, featureState); + if (!intersectionZ) { + // Only applied for non-symbol features + continue; + } + const geojsonFeature = new GeoJSONFeature(feature, this.z, this.x, this.y, id); + geojsonFeature.layer = serializedLayer; + let layerResult = result[layerID]; + if (layerResult === undefined) { + layerResult = result[layerID] = []; + } + layerResult.push({ featureIndex, feature: geojsonFeature, intersectionZ }); + } + } + // Given a set of symbol indexes that have already been looked up, + // return a matching set of GeoJSONFeatures + lookupSymbolFeatures(symbolFeatureIndexes, serializedLayers, bucketIndex, sourceLayerIndex, filterSpec, filterLayerIDs, availableImages, styleLayers) { + const result = {}; + this.loadVTLayers(); + const filter = createFilter(filterSpec); + for (const symbolFeatureIndex of symbolFeatureIndexes) { + this.loadMatchingFeature(result, bucketIndex, sourceLayerIndex, symbolFeatureIndex, filter, filterLayerIDs, availableImages, styleLayers, serializedLayers); + } + return result; + } + hasLayer(id) { + for (const layerIDs of this.bucketLayerIDs) { + for (const layerID of layerIDs) { + if (id === layerID) + return true; + } + } + return false; + } + getId(feature, sourceLayerId) { + let id = feature.id; + if (this.promoteId) { + const propName = typeof this.promoteId === 'string' ? this.promoteId : this.promoteId[sourceLayerId]; + id = feature.properties[propName]; + if (typeof id === 'boolean') + id = Number(id); + } + return id; + } +} +register('FeatureIndex', FeatureIndex, { omit: ['rawTileData', 'sourceLayerCoder'] }); +function evaluateProperties(serializedProperties, styleLayerProperties, feature, featureState, availableImages) { + return mapObject(serializedProperties, (property, key) => { + const prop = styleLayerProperties instanceof PossiblyEvaluated ? styleLayerProperties.get(key) : null; + return prop && prop.evaluate ? prop.evaluate(feature, featureState, availableImages) : prop; + }); +} +function getBounds(geometry) { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const p of geometry) { + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + return { minX, minY, maxX, maxY }; +} +function topDownFeatureComparator(a, b) { + return b - a; +} + +class Anchor extends Point$3 { + constructor(x, y, angle, segment) { + super(x, y); + this.angle = angle; + if (segment !== undefined) { + this.segment = segment; + } + } + clone() { + return new Anchor(this.x, this.y, this.angle, this.segment); + } +} +register('Anchor', Anchor); + +/** + * Labels placed around really sharp angles aren't readable. Check if any + * part of the potential label has a combined angle that is too big. + * + * @param line - The line to check + * @param anchor - The point on the line around which the label is anchored. + * @param labelLength - The length of the label in geometry units. + * @param windowSize - The check fails if the combined angles within a part of the line that is `windowSize` long is too big. + * @param maxAngle - The maximum combined angle that any window along the label is allowed to have. + * + * @returns whether the label should be placed + */ +function checkMaxAngle(line, anchor, labelLength, windowSize, maxAngle) { + // horizontal labels and labels with length 0 always pass + if (anchor.segment === undefined || labelLength === 0) + return true; + let p = anchor; + let index = anchor.segment + 1; + let anchorDistance = 0; + // move backwards along the line to the first segment the label appears on + while (anchorDistance > -labelLength / 2) { + index--; + // there isn't enough room for the label after the beginning of the line + if (index < 0) + return false; + anchorDistance -= line[index].dist(p); + p = line[index]; + } + anchorDistance += line[index].dist(line[index + 1]); + index++; + // store recent corners and their total angle difference + const recentCorners = []; + let recentAngleDelta = 0; + // move forwards by the length of the label and check angles along the way + while (anchorDistance < labelLength / 2) { + const prev = line[index - 1]; + const current = line[index]; + const next = line[index + 1]; + // there isn't enough room for the label before the end of the line + if (!next) + return false; + let angleDelta = prev.angleTo(current) - current.angleTo(next); + // restrict angle to -pi..pi range + angleDelta = Math.abs(((angleDelta + 3 * Math.PI) % (Math.PI * 2)) - Math.PI); + recentCorners.push({ + distance: anchorDistance, + angleDelta + }); + recentAngleDelta += angleDelta; + // remove corners that are far enough away from the list of recent anchors + while (anchorDistance - recentCorners[0].distance > windowSize) { + recentAngleDelta -= recentCorners.shift().angleDelta; + } + // the sum of angles within the window area exceeds the maximum allowed value. check fails. + if (recentAngleDelta > maxAngle) + return false; + index++; + anchorDistance += current.dist(next); + } + // no part of the line had an angle greater than the maximum allowed. check passes. + return true; +} + +function getLineLength(line) { + let lineLength = 0; + for (let k = 0; k < line.length - 1; k++) { + lineLength += line[k].dist(line[k + 1]); + } + return lineLength; +} +function getAngleWindowSize(shapedText, glyphSize, boxScale) { + return shapedText ? + 3 / 5 * glyphSize * boxScale : + 0; +} +function getShapedLabelLength(shapedText, shapedIcon) { + return Math.max(shapedText ? shapedText.right - shapedText.left : 0, shapedIcon ? shapedIcon.right - shapedIcon.left : 0); +} +function getCenterAnchor(line, maxAngle, shapedText, shapedIcon, glyphSize, boxScale) { + const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); + const labelLength = getShapedLabelLength(shapedText, shapedIcon) * boxScale; + let prevDistance = 0; + const centerDistance = getLineLength(line) / 2; + for (let i = 0; i < line.length - 1; i++) { + const a = line[i], b = line[i + 1]; + const segmentDistance = a.dist(b); + if (prevDistance + segmentDistance > centerDistance) { + // The center is on this segment + const t = (centerDistance - prevDistance) / segmentDistance, x = interpolate.number(a.x, b.x, t), y = interpolate.number(a.y, b.y, t); + const anchor = new Anchor(x, y, b.angleTo(a), i); + anchor._round(); + if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { + return anchor; + } + else { + return; + } + } + prevDistance += segmentDistance; + } +} +function getAnchors(line, spacing, maxAngle, shapedText, shapedIcon, glyphSize, boxScale, overscaling, tileExtent) { + // Resample a line to get anchor points for labels and check that each + // potential label passes text-max-angle check and has enough room to fit + // on the line. + const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); + const shapedLabelLength = getShapedLabelLength(shapedText, shapedIcon); + const labelLength = shapedLabelLength * boxScale; + // Is the line continued from outside the tile boundary? + const isLineContinued = line[0].x === 0 || line[0].x === tileExtent || line[0].y === 0 || line[0].y === tileExtent; + // Is the label long, relative to the spacing? + // If so, adjust the spacing so there is always a minimum space of `spacing / 4` between label edges. + if (spacing - labelLength < spacing / 4) { + spacing = labelLength + spacing / 4; + } + // Offset the first anchor by: + // Either half the label length plus a fixed extra offset if the line is not continued + // Or half the spacing if the line is continued. + // For non-continued lines, add a bit of fixed extra offset to avoid collisions at T intersections. + const fixedExtraOffset = glyphSize * 2; + const offset = !isLineContinued ? + ((shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling) % spacing : + (spacing / 2 * overscaling) % spacing; + return resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, false, tileExtent); +} +function resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, placeAtMiddle, tileExtent) { + const halfLabelLength = labelLength / 2; + const lineLength = getLineLength(line); + let distance = 0, markedDistance = offset - spacing; + let anchors = []; + for (let i = 0; i < line.length - 1; i++) { + const a = line[i], b = line[i + 1]; + const segmentDist = a.dist(b), angle = b.angleTo(a); + while (markedDistance + spacing < distance + segmentDist) { + markedDistance += spacing; + const t = (markedDistance - distance) / segmentDist, x = interpolate.number(a.x, b.x, t), y = interpolate.number(a.y, b.y, t); + // Check that the point is within the tile boundaries and that + // the label would fit before the beginning and end of the line + // if placed at this point. + if (x >= 0 && x < tileExtent && y >= 0 && y < tileExtent && + markedDistance - halfLabelLength >= 0 && + markedDistance + halfLabelLength <= lineLength) { + const anchor = new Anchor(x, y, angle, i); + anchor._round(); + if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { + anchors.push(anchor); + } + } + } + distance += segmentDist; + } + if (!placeAtMiddle && !anchors.length && !isLineContinued) { + // The first attempt at finding anchors at which labels can be placed failed. + // Try again, but this time just try placing one anchor at the middle of the line. + // This has the most effect for short lines in overscaled tiles, since the + // initial offset used in overscaled tiles is calculated to align labels with positions in + // parent tiles instead of placing the label as close to the beginning as possible. + anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, true, tileExtent); + } + return anchors; +} + +/** + * Returns the part of a multiline that intersects with the provided rectangular box. + * + * @param lines - the lines to check + * @param x1 - the left edge of the box + * @param y1 - the top edge of the box + * @param x2 - the right edge of the box + * @param y2 - the bottom edge of the box + * @returns lines + */ +function clipLine$1(lines, x1, y1, x2, y2) { + const clippedLines = []; + for (let l = 0; l < lines.length; l++) { + const line = lines[l]; + let clippedLine; + for (let i = 0; i < line.length - 1; i++) { + let p0 = line[i]; + let p1 = line[i + 1]; + if (p0.x < x1 && p1.x < x1) { + continue; + } + else if (p0.x < x1) { + p0 = new Point$3(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); + } + else if (p1.x < x1) { + p1 = new Point$3(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); + } + if (p0.y < y1 && p1.y < y1) { + continue; + } + else if (p0.y < y1) { + p0 = new Point$3(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); + } + else if (p1.y < y1) { + p1 = new Point$3(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); + } + if (p0.x >= x2 && p1.x >= x2) { + continue; + } + else if (p0.x >= x2) { + p0 = new Point$3(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); + } + else if (p1.x >= x2) { + p1 = new Point$3(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); + } + if (p0.y >= y2 && p1.y >= y2) { + continue; + } + else if (p0.y >= y2) { + p0 = new Point$3(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); + } + else if (p1.y >= y2) { + p1 = new Point$3(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); + } + if (!clippedLine || !p0.equals(clippedLine[clippedLine.length - 1])) { + clippedLine = [p0]; + clippedLines.push(clippedLine); + } + clippedLine.push(p1); + } + } + return clippedLines; +} + +// If you have a 10px icon that isn't perfectly aligned to the pixel grid it will cover 11 actual +// pixels. The quad needs to be padded to account for this, otherwise they'll look slightly clipped +// on one edge in some cases. +const border = IMAGE_PADDING; +/** + * Create the quads used for rendering an icon. + */ +function getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit) { + const quads = []; + const image = shapedIcon.image; + const pixelRatio = image.pixelRatio; + const imageWidth = image.paddedRect.w - 2 * border; + const imageHeight = image.paddedRect.h - 2 * border; + let icon = { + x1: shapedIcon.left, + y1: shapedIcon.top, + x2: shapedIcon.right, + y2: shapedIcon.bottom + }; + const stretchX = image.stretchX || [[0, imageWidth]]; + const stretchY = image.stretchY || [[0, imageHeight]]; + const reduceRanges = (sum, range) => sum + range[1] - range[0]; + const stretchWidth = stretchX.reduce(reduceRanges, 0); + const stretchHeight = stretchY.reduce(reduceRanges, 0); + const fixedWidth = imageWidth - stretchWidth; + const fixedHeight = imageHeight - stretchHeight; + let stretchOffsetX = 0; + let stretchContentWidth = stretchWidth; + let stretchOffsetY = 0; + let stretchContentHeight = stretchHeight; + let fixedOffsetX = 0; + let fixedContentWidth = fixedWidth; + let fixedOffsetY = 0; + let fixedContentHeight = fixedHeight; + if (image.content && hasIconTextFit) { + const content = image.content; + const contentWidth = content[2] - content[0]; + const contentHeight = content[3] - content[1]; + // Constrict content area to fit target aspect ratio + if (image.textFitWidth || image.textFitHeight) { + icon = applyTextFit(shapedIcon); + } + stretchOffsetX = sumWithinRange(stretchX, 0, content[0]); + stretchOffsetY = sumWithinRange(stretchY, 0, content[1]); + stretchContentWidth = sumWithinRange(stretchX, content[0], content[2]); + stretchContentHeight = sumWithinRange(stretchY, content[1], content[3]); + fixedOffsetX = content[0] - stretchOffsetX; + fixedOffsetY = content[1] - stretchOffsetY; + fixedContentWidth = contentWidth - stretchContentWidth; + fixedContentHeight = contentHeight - stretchContentHeight; + } + const iconLeft = icon.x1; + const iconTop = icon.y1; + const iconWidth = icon.x2 - iconLeft; + const iconHeight = icon.y2 - iconTop; + const makeBox = (left, top, right, bottom) => { + const leftEm = getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, iconLeft); + const leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth); + const topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, iconTop); + const topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight); + const rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, iconLeft); + const rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth); + const bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, iconTop); + const bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight); + const tl = new Point$3(leftEm, topEm); + const tr = new Point$3(rightEm, topEm); + const br = new Point$3(rightEm, bottomEm); + const bl = new Point$3(leftEm, bottomEm); + const pixelOffsetTL = new Point$3(leftPx / pixelRatio, topPx / pixelRatio); + const pixelOffsetBR = new Point$3(rightPx / pixelRatio, bottomPx / pixelRatio); + const angle = iconRotate * Math.PI / 180; + if (angle) { + const sin = Math.sin(angle), cos = Math.cos(angle), matrix = [cos, -sin, sin, cos]; + tl._matMult(matrix); + tr._matMult(matrix); + bl._matMult(matrix); + br._matMult(matrix); + } + const x1 = left.stretch + left.fixed; + const x2 = right.stretch + right.fixed; + const y1 = top.stretch + top.fixed; + const y2 = bottom.stretch + bottom.fixed; + const subRect = { + x: image.paddedRect.x + border + x1, + y: image.paddedRect.y + border + y1, + w: x2 - x1, + h: y2 - y1 + }; + const minFontScaleX = fixedContentWidth / pixelRatio / iconWidth; + const minFontScaleY = fixedContentHeight / pixelRatio / iconHeight; + // Icon quad is padded, so texture coordinates also need to be padded. + return { tl, tr, bl, br, tex: subRect, writingMode: undefined, glyphOffset: [0, 0], sectionIndex: 0, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, isSDF: isSDFIcon }; + }; + if (!hasIconTextFit || (!image.stretchX && !image.stretchY)) { + quads.push(makeBox({ fixed: 0, stretch: -1 }, { fixed: 0, stretch: -1 }, { fixed: 0, stretch: imageWidth + 1 }, { fixed: 0, stretch: imageHeight + 1 })); + } + else { + const xCuts = stretchZonesToCuts(stretchX, fixedWidth, stretchWidth); + const yCuts = stretchZonesToCuts(stretchY, fixedHeight, stretchHeight); + for (let xi = 0; xi < xCuts.length - 1; xi++) { + const x1 = xCuts[xi]; + const x2 = xCuts[xi + 1]; + for (let yi = 0; yi < yCuts.length - 1; yi++) { + const y1 = yCuts[yi]; + const y2 = yCuts[yi + 1]; + quads.push(makeBox(x1, y1, x2, y2)); + } + } + } + return quads; +} +function sumWithinRange(ranges, min, max) { + let sum = 0; + for (const range of ranges) { + sum += Math.max(min, Math.min(max, range[1])) - Math.max(min, Math.min(max, range[0])); + } + return sum; +} +function stretchZonesToCuts(stretchZones, fixedSize, stretchSize) { + const cuts = [{ fixed: -border, stretch: 0 }]; + for (const [c1, c2] of stretchZones) { + const last = cuts[cuts.length - 1]; + cuts.push({ + fixed: c1 - last.stretch, + stretch: last.stretch + }); + cuts.push({ + fixed: c1 - last.stretch, + stretch: last.stretch + (c2 - c1) + }); + } + cuts.push({ + fixed: fixedSize + border, + stretch: stretchSize + }); + return cuts; +} +function getEmOffset(stretchOffset, stretchSize, iconSize, iconOffset) { + return stretchOffset / stretchSize * iconSize + iconOffset; +} +function getPxOffset(fixedOffset, fixedSize, stretchOffset, stretchSize) { + return fixedOffset - fixedSize * stretchOffset / stretchSize; +} +/** + * Create the quads used for rendering a text label. + */ +function getGlyphQuads(anchor, shaping, textOffset, layer, alongLine, feature, imageMap, allowVerticalPlacement) { + const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}) * Math.PI / 180; + const quads = []; + for (const line of shaping.positionedLines) { + for (const positionedGlyph of line.positionedGlyphs) { + if (!positionedGlyph.rect) + continue; + const textureRect = positionedGlyph.rect || {}; + // The rects have an additional buffer that is not included in their size. + const glyphPadding = 1.0; + let rectBuffer = GLYPH_PBF_BORDER + glyphPadding; + let isSDF = true; + let pixelRatio = 1.0; + let lineOffset = 0.0; + const rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical; + const halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2; + // Align images and scaled glyphs in the middle of a vertical line. + if (allowVerticalPlacement && shaping.verticalizable) { + const scaledGlyphOffset = (positionedGlyph.scale - 1) * ONE_EM; + const imageOffset = (ONE_EM - positionedGlyph.metrics.width * positionedGlyph.scale) / 2; + lineOffset = line.lineOffset / 2 - (positionedGlyph.imageName ? -imageOffset : scaledGlyphOffset); + } + if (positionedGlyph.imageName) { + const image = imageMap[positionedGlyph.imageName]; + isSDF = image.sdf; + pixelRatio = image.pixelRatio; + rectBuffer = IMAGE_PADDING / pixelRatio; + } + const glyphOffset = alongLine ? + [positionedGlyph.x + halfAdvance, positionedGlyph.y] : + [0, 0]; + let builtInOffset = alongLine ? + [0, 0] : + [positionedGlyph.x + halfAdvance + textOffset[0], positionedGlyph.y + textOffset[1] - lineOffset]; + let verticalizedLabelOffset = [0, 0]; + if (rotateVerticalGlyph) { + // Vertical POI labels that are rotated 90deg CW and whose glyphs must preserve upright orientation + // need to be rotated 90deg CCW. After a quad is rotated, it is translated to the original built-in offset. + verticalizedLabelOffset = builtInOffset; + builtInOffset = [0, 0]; + } + const textureScale = positionedGlyph.metrics.isDoubleResolution ? 2 : 1; + const x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0]; + const y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1]; + const x2 = x1 + textureRect.w / textureScale * positionedGlyph.scale / pixelRatio; + const y2 = y1 + textureRect.h / textureScale * positionedGlyph.scale / pixelRatio; + const tl = new Point$3(x1, y1); + const tr = new Point$3(x2, y1); + const bl = new Point$3(x1, y2); + const br = new Point$3(x2, y2); + if (rotateVerticalGlyph) { + // Vertical-supporting glyphs are laid out in 24x24 point boxes (1 square em) + // In horizontal orientation, the y values for glyphs are below the midline + // and we use a "yOffset" of -17 to pull them up to the middle. + // By rotating counter-clockwise around the point at the center of the left + // edge of a 24x24 layout box centered below the midline, we align the center + // of the glyphs with the horizontal midline, so the yOffset is no longer + // necessary, but we also pull the glyph to the left along the x axis. + // The y coordinate includes baseline yOffset, thus needs to be accounted + // for when glyph is rotated and translated. + const center = new Point$3(-halfAdvance, halfAdvance - SHAPING_DEFAULT_OFFSET); + const verticalRotation = -Math.PI / 2; + // xHalfWidthOffsetCorrection is a difference between full-width and half-width + // advance, should be 0 for full-width glyphs and will pull up half-width glyphs. + const xHalfWidthOffsetCorrection = ONE_EM / 2 - halfAdvance; + const yImageOffsetCorrection = positionedGlyph.imageName ? xHalfWidthOffsetCorrection : 0.0; + const halfWidthOffsetCorrection = new Point$3(5 - SHAPING_DEFAULT_OFFSET - xHalfWidthOffsetCorrection, -yImageOffsetCorrection); + const verticalOffsetCorrection = new Point$3(...verticalizedLabelOffset); + tl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + tr._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + bl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + br._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + } + if (textRotate) { + const sin = Math.sin(textRotate), cos = Math.cos(textRotate), matrix = [cos, -sin, sin, cos]; + tl._matMult(matrix); + tr._matMult(matrix); + bl._matMult(matrix); + br._matMult(matrix); + } + const pixelOffsetTL = new Point$3(0, 0); + const pixelOffsetBR = new Point$3(0, 0); + const minFontScaleX = 0; + const minFontScaleY = 0; + quads.push({ tl, tr, bl, br, tex: textureRect, writingMode: shaping.writingMode, glyphOffset, sectionIndex: positionedGlyph.sectionIndex, isSDF, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY }); + } + } + return quads; +} + +/** + * A CollisionFeature represents the area of the tile covered by a single label. + * It is used with CollisionIndex to check if the label overlaps with any + * previous labels. A CollisionFeature is mostly just a set of CollisionBox + * objects. + */ +class CollisionFeature { + /** + * Create a CollisionFeature, adding its collision box data to the given collisionBoxArray in the process. + * For line aligned labels a collision circle diameter is computed instead. + * + * @param anchor - The point along the line around which the label is anchored. + * @param shaped - The text or icon shaping results. + * @param boxScale - A magic number used to convert from glyph metrics units to geometry units. + * @param padding - The amount of padding to add around the label edges. + * @param alignLine - Whether the label is aligned with the line or the viewport. + */ + constructor(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaped, boxScale, padding, alignLine, rotate) { + var _a; + this.boxStartIndex = collisionBoxArray.length; + if (alignLine) { + // Compute height of the shape in glyph metrics and apply collision padding. + // Note that the pixel based 'text-padding' is applied at runtime + let top = shaped.top; + let bottom = shaped.bottom; + const collisionPadding = shaped.collisionPadding; + if (collisionPadding) { + top -= collisionPadding[1]; + bottom += collisionPadding[3]; + } + let height = bottom - top; + if (height > 0) { + // set minimum box height to avoid very many small labels + height = Math.max(10, height); + this.circleDiameter = height; + } + } + else { + const icon = ((_a = shaped.image) === null || _a === void 0 ? void 0 : _a.content) && (shaped.image.textFitWidth || shaped.image.textFitHeight) ? + applyTextFit(shaped) : + { + x1: shaped.left, + y1: shaped.top, + x2: shaped.right, + y2: shaped.bottom + }; + // margin is in CSS order: [top, right, bottom, left] + icon.y1 = icon.y1 * boxScale - padding[0]; + icon.y2 = icon.y2 * boxScale + padding[2]; + icon.x1 = icon.x1 * boxScale - padding[3]; + icon.x2 = icon.x2 * boxScale + padding[1]; + const collisionPadding = shaped.collisionPadding; + if (collisionPadding) { + icon.x1 -= collisionPadding[0] * boxScale; + icon.y1 -= collisionPadding[1] * boxScale; + icon.x2 += collisionPadding[2] * boxScale; + icon.y2 += collisionPadding[3] * boxScale; + } + if (rotate) { + // Account for *-rotate in point collision boxes + // See https://github.com/mapbox/mapbox-gl-js/issues/6075 + // Doesn't account for icon-text-fit + const tl = new Point$3(icon.x1, icon.y1); + const tr = new Point$3(icon.x2, icon.y1); + const bl = new Point$3(icon.x1, icon.y2); + const br = new Point$3(icon.x2, icon.y2); + const rotateRadians = rotate * Math.PI / 180; + tl._rotate(rotateRadians); + tr._rotate(rotateRadians); + bl._rotate(rotateRadians); + br._rotate(rotateRadians); + // Collision features require an "on-axis" geometry, + // so take the envelope of the rotated geometry + // (may be quite large for wide labels rotated 45 degrees) + icon.x1 = Math.min(tl.x, tr.x, bl.x, br.x); + icon.x2 = Math.max(tl.x, tr.x, bl.x, br.x); + icon.y1 = Math.min(tl.y, tr.y, bl.y, br.y); + icon.y2 = Math.max(tl.y, tr.y, bl.y, br.y); + } + collisionBoxArray.emplaceBack(anchor.x, anchor.y, icon.x1, icon.y1, icon.x2, icon.y2, featureIndex, sourceLayerIndex, bucketIndex); + } + this.boxEndIndex = collisionBoxArray.length; + } +} + +class TinyQueue { + constructor(data = [], compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) { + this.data = data; + this.length = this.data.length; + this.compare = compare; + + if (this.length > 0) { + for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i); + } + } + + push(item) { + this.data.push(item); + this._up(this.length++); + } + + pop() { + if (this.length === 0) return undefined; + + const top = this.data[0]; + const bottom = this.data.pop(); + + if (--this.length > 0) { + this.data[0] = bottom; + this._down(0); + } + + return top; + } + + peek() { + return this.data[0]; + } + + _up(pos) { + const {data, compare} = this; + const item = data[pos]; + + while (pos > 0) { + const parent = (pos - 1) >> 1; + const current = data[parent]; + if (compare(item, current) >= 0) break; + data[pos] = current; + pos = parent; + } + + data[pos] = item; + } + + _down(pos) { + const {data, compare} = this; + const halfLength = this.length >> 1; + const item = data[pos]; + + while (pos < halfLength) { + let bestChild = (pos << 1) + 1; // initially it is the left child + const right = bestChild + 1; + + if (right < this.length && compare(data[right], data[bestChild]) < 0) { + bestChild = right; + } + if (compare(data[bestChild], item) >= 0) break; + + data[pos] = data[bestChild]; + pos = bestChild; + } + + data[pos] = item; + } +} + +/** + * Finds an approximation of a polygon's Pole Of Inaccessibility https://en.wikipedia.org/wiki/Pole_of_inaccessibility + * This is a copy of https://github.com/mapbox/polylabel adapted to use Points + * + * @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 + * @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 + * @param debug - Print some statistics to the console during execution + * @returns Pole of Inaccessibility. + */ +function findPoleOfInaccessibility(polygonRings, precision = 1, debug = false) { + // find the bounding box of the outer ring + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + const outerRing = polygonRings[0]; + for (let i = 0; i < outerRing.length; i++) { + const p = outerRing[i]; + if (!i || p.x < minX) + minX = p.x; + if (!i || p.y < minY) + minY = p.y; + if (!i || p.x > maxX) + maxX = p.x; + if (!i || p.y > maxY) + maxY = p.y; + } + const width = maxX - minX; + const height = maxY - minY; + const cellSize = Math.min(width, height); + let h = cellSize / 2; + // a priority queue of cells in order of their "potential" (max distance to polygon) + const cellQueue = new TinyQueue([], compareMax); + if (cellSize === 0) + return new Point$3(minX, minY); + // cover polygon with initial cells + for (let x = minX; x < maxX; x += cellSize) { + for (let y = minY; y < maxY; y += cellSize) { + cellQueue.push(new Cell(x + h, y + h, h, polygonRings)); + } + } + // take centroid as the first best guess + let bestCell = getCentroidCell(polygonRings); + let numProbes = cellQueue.length; + while (cellQueue.length) { + // pick the most promising cell from the queue + const cell = cellQueue.pop(); + // update the best cell if we found a better one + if (cell.d > bestCell.d || !bestCell.d) { + bestCell = cell; + if (debug) + console.log('found best %d after %d probes', Math.round(1e4 * cell.d) / 1e4, numProbes); + } + // do not drill down further if there's no chance of a better solution + if (cell.max - bestCell.d <= precision) + continue; + // split the cell into four cells + h = cell.h / 2; + cellQueue.push(new Cell(cell.p.x - h, cell.p.y - h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x + h, cell.p.y - h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x - h, cell.p.y + h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x + h, cell.p.y + h, h, polygonRings)); + numProbes += 4; + } + if (debug) { + console.log(`num probes: ${numProbes}`); + console.log(`best distance: ${bestCell.d}`); + } + return bestCell.p; +} +function compareMax(a, b) { + return b.max - a.max; +} +function Cell(x, y, h, polygon) { + this.p = new Point$3(x, y); + this.h = h; // half the cell size + this.d = pointToPolygonDist(this.p, polygon); // distance from cell center to polygon + this.max = this.d + this.h * Math.SQRT2; // max distance to polygon within a cell +} +// signed distance from point to polygon outline (negative if point is outside) +function pointToPolygonDist(p, polygon) { + let inside = false; + let minDistSq = Infinity; + for (let k = 0; k < polygon.length; k++) { + const ring = polygon[k]; + for (let i = 0, len = ring.length, j = len - 1; i < len; j = i++) { + const a = ring[i]; + const b = ring[j]; + if ((a.y > p.y !== b.y > p.y) && + (p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x)) + inside = !inside; + minDistSq = Math.min(minDistSq, distToSegmentSquared(p, a, b)); + } + } + return (inside ? 1 : -1) * Math.sqrt(minDistSq); +} +// get polygon centroid +function getCentroidCell(polygon) { + let area = 0; + let x = 0; + let y = 0; + const points = polygon[0]; + for (let i = 0, len = points.length, j = len - 1; i < len; j = i++) { + const a = points[i]; + const b = points[j]; + const f = a.x * b.y - b.x * a.y; + x += (a.x + b.x) * f; + y += (a.y + b.y) * f; + area += f * 3; + } + return new Cell(x / area, y / area, 0, polygon); +} + +var TextAnchorEnum; +(function (TextAnchorEnum) { + TextAnchorEnum[TextAnchorEnum["center"] = 1] = "center"; + TextAnchorEnum[TextAnchorEnum["left"] = 2] = "left"; + TextAnchorEnum[TextAnchorEnum["right"] = 3] = "right"; + TextAnchorEnum[TextAnchorEnum["top"] = 4] = "top"; + TextAnchorEnum[TextAnchorEnum["bottom"] = 5] = "bottom"; + TextAnchorEnum[TextAnchorEnum["top-left"] = 6] = "top-left"; + TextAnchorEnum[TextAnchorEnum["top-right"] = 7] = "top-right"; + TextAnchorEnum[TextAnchorEnum["bottom-left"] = 8] = "bottom-left"; + TextAnchorEnum[TextAnchorEnum["bottom-right"] = 9] = "bottom-right"; +})(TextAnchorEnum || (TextAnchorEnum = {})); +// The radial offset is to the edge of the text box +// In the horizontal direction, the edge of the text box is where glyphs start +// But in the vertical direction, the glyphs appear to "start" at the baseline +// We don't actually load baseline data, but we assume an offset of ONE_EM - 17 +// (see "yOffset" in shaping.js) +const baselineOffset = 7; +const INVALID_TEXT_OFFSET = Number.POSITIVE_INFINITY; +function evaluateVariableOffset(anchor, offset) { + function fromRadialOffset(anchor, radialOffset) { + let x = 0, y = 0; + if (radialOffset < 0) + radialOffset = 0; // Ignore negative offset. + // solve for r where r^2 + r^2 = radialOffset^2 + const hypotenuse = radialOffset / Math.SQRT2; + switch (anchor) { + case 'top-right': + case 'top-left': + y = hypotenuse - baselineOffset; + break; + case 'bottom-right': + case 'bottom-left': + y = -hypotenuse + baselineOffset; + break; + case 'bottom': + y = -radialOffset + baselineOffset; + break; + case 'top': + y = radialOffset - baselineOffset; + break; + } + switch (anchor) { + case 'top-right': + case 'bottom-right': + x = -hypotenuse; + break; + case 'top-left': + case 'bottom-left': + x = hypotenuse; + break; + case 'left': + x = radialOffset; + break; + case 'right': + x = -radialOffset; + break; + } + return [x, y]; + } + function fromTextOffset(anchor, offsetX, offsetY) { + let x = 0, y = 0; + // Use absolute offset values. + offsetX = Math.abs(offsetX); + offsetY = Math.abs(offsetY); + switch (anchor) { + case 'top-right': + case 'top-left': + case 'top': + y = offsetY - baselineOffset; + break; + case 'bottom-right': + case 'bottom-left': + case 'bottom': + y = -offsetY + baselineOffset; + break; + } + switch (anchor) { + case 'top-right': + case 'bottom-right': + case 'right': + x = -offsetX; + break; + case 'top-left': + case 'bottom-left': + case 'left': + x = offsetX; + break; + } + return [x, y]; + } + return (offset[1] !== INVALID_TEXT_OFFSET) ? fromTextOffset(anchor, offset[0], offset[1]) : fromRadialOffset(anchor, offset[0]); +} +// Helper to support both text-variable-anchor and text-variable-anchor-offset. Offset values converted from EMs to PXs +function getTextVariableAnchorOffset(layer, feature, canonical) { + var _a; + const layout = layer.layout; + // If style specifies text-variable-anchor-offset, just return it + const variableAnchorOffset = (_a = layout.get('text-variable-anchor-offset')) === null || _a === void 0 ? void 0 : _a.evaluate(feature, {}, canonical); + if (variableAnchorOffset) { + const sourceValues = variableAnchorOffset.values; + const destValues = []; + // Convert offsets from EM to PX, and apply baseline shift + for (let i = 0; i < sourceValues.length; i += 2) { + const anchor = destValues[i] = sourceValues[i]; + const offset = sourceValues[i + 1].map(t => t * ONE_EM); + if (anchor.startsWith('top')) { + offset[1] -= baselineOffset; + } + else if (anchor.startsWith('bottom')) { + offset[1] += baselineOffset; + } + destValues[i + 1] = offset; + } + return new VariableAnchorOffsetCollection(destValues); + } + // If style specifies text-variable-anchor, convert to the new format + const variableAnchor = layout.get('text-variable-anchor'); + if (variableAnchor) { + let textOffset; + const unevaluatedLayout = layer._unevaluatedLayout; + // The style spec says don't use `text-offset` and `text-radial-offset` together + // but doesn't actually specify what happens if you use both. We go with the radial offset. + if (unevaluatedLayout.getValue('text-radial-offset') !== undefined) { + textOffset = [layout.get('text-radial-offset').evaluate(feature, {}, canonical) * ONE_EM, INVALID_TEXT_OFFSET]; + } + else { + textOffset = layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM); + } + const anchorOffsets = []; + for (const anchor of variableAnchor) { + anchorOffsets.push(anchor, evaluateVariableOffset(anchor, textOffset)); + } + return new VariableAnchorOffsetCollection(anchorOffsets); + } + return null; +} + +function performSymbolLayout(args) { + args.bucket.createArrays(); + const tileSize = 512 * args.bucket.overscaling; + args.bucket.tilePixelRatio = EXTENT / tileSize; + args.bucket.compareText = {}; + args.bucket.iconsNeedLinear = false; + const layer = args.bucket.layers[0]; + const layout = layer.layout; + const unevaluatedLayoutValues = layer._unevaluatedLayout._values; + const sizes = { + // Filled in below, if *SizeData.kind is 'composite' + // compositeIconSizes: undefined, + // compositeTextSizes: undefined, + layoutIconSize: unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical), + layoutTextSize: unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical), + textMaxSize: unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(18)) + }; + if (args.bucket.textSizeData.kind === 'composite') { + const { minZoom, maxZoom } = args.bucket.textSizeData; + sizes.compositeTextSizes = [ + unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical), + unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical) + ]; + } + if (args.bucket.iconSizeData.kind === 'composite') { + const { minZoom, maxZoom } = args.bucket.iconSizeData; + sizes.compositeIconSizes = [ + unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical), + unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical) + ]; + } + const lineHeight = layout.get('text-line-height') * ONE_EM; + const textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point'; + const keepUpright = layout.get('text-keep-upright'); + const textSize = layout.get('text-size'); + for (const feature of args.bucket.features) { + const fontstack = layout.get('text-font').evaluate(feature, {}, args.canonical).join(','); + const layoutTextSizeThisZoom = textSize.evaluate(feature, {}, args.canonical); + const layoutTextSize = sizes.layoutTextSize.evaluate(feature, {}, args.canonical); + const layoutIconSize = sizes.layoutIconSize.evaluate(feature, {}, args.canonical); + const shapedTextOrientations = { + horizontal: {}, + vertical: undefined + }; + const text = feature.text; + let textOffset = [0, 0]; + if (text) { + const unformattedText = text.toString(); + const spacing = layout.get('text-letter-spacing').evaluate(feature, {}, args.canonical) * ONE_EM; + const spacingIfAllowed = allowsLetterSpacing(unformattedText) ? spacing : 0; + const textAnchor = layout.get('text-anchor').evaluate(feature, {}, args.canonical); + const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, args.canonical); + if (!variableAnchorOffset) { + const radialOffset = layout.get('text-radial-offset').evaluate(feature, {}, args.canonical); + // Layers with variable anchors use the `text-radial-offset` property and the [x, y] offset vector + // is calculated at placement time instead of layout time + if (radialOffset) { + // The style spec says don't use `text-offset` and `text-radial-offset` together + // but doesn't actually specify what happens if you use both. We go with the radial offset. + textOffset = evaluateVariableOffset(textAnchor, [radialOffset * ONE_EM, INVALID_TEXT_OFFSET]); + } + else { + textOffset = layout.get('text-offset').evaluate(feature, {}, args.canonical).map(t => t * ONE_EM); + } + } + let textJustify = textAlongLine ? + 'center' : + layout.get('text-justify').evaluate(feature, {}, args.canonical); + const symbolPlacement = layout.get('symbol-placement'); + const maxWidth = symbolPlacement === 'point' ? + layout.get('text-max-width').evaluate(feature, {}, args.canonical) * ONE_EM : + Infinity; + const addVerticalShapingForPointLabelIfNeeded = () => { + if (args.bucket.allowVerticalPlacement && allowsVerticalWritingMode(unformattedText)) { + // Vertical POI label placement is meant to be used for scripts that support vertical + // writing mode, thus, default left justification is used. If Latin + // scripts would need to be supported, this should take into account other justifications. + shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, 'left', spacingIfAllowed, textOffset, WritingMode.vertical, true, layoutTextSize, layoutTextSizeThisZoom); + } + }; + // If this layer uses text-variable-anchor, generate shapings for all justification possibilities. + if (!textAlongLine && variableAnchorOffset) { + const justifications = new Set(); + if (textJustify === 'auto') { + for (let i = 0; i < variableAnchorOffset.values.length; i += 2) { + justifications.add(getAnchorJustification(variableAnchorOffset.values[i])); + } + } + else { + justifications.add(textJustify); + } + let singleLine = false; + for (const justification of justifications) { + if (shapedTextOrientations.horizontal[justification]) + continue; + if (singleLine) { + // If the shaping for the first justification was only a single line, we + // can re-use it for the other justifications + shapedTextOrientations.horizontal[justification] = shapedTextOrientations.horizontal[0]; + } + else { + // If using text-variable-anchor for the layer, we use a center anchor for all shapings and apply + // the offsets for the anchor in the placement step. + const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, 'center', justification, spacingIfAllowed, textOffset, WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom); + if (shaping) { + shapedTextOrientations.horizontal[justification] = shaping; + singleLine = shaping.positionedLines.length === 1; + } + } + } + addVerticalShapingForPointLabelIfNeeded(); + } + else { + if (textJustify === 'auto') { + textJustify = getAnchorJustification(textAnchor); + } + // Horizontal point or line label. + const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom); + if (shaping) + shapedTextOrientations.horizontal[textJustify] = shaping; + // Vertical point label (if allowVerticalPlacement is enabled). + addVerticalShapingForPointLabelIfNeeded(); + // Verticalized line label. + if (allowsVerticalWritingMode(unformattedText) && textAlongLine && keepUpright) { + shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, WritingMode.vertical, false, layoutTextSize, layoutTextSizeThisZoom); + } + } + } + let shapedIcon; + let isSDFIcon = false; + if (feature.icon && feature.icon.name) { + const image = args.imageMap[feature.icon.name]; + if (image) { + shapedIcon = shapeIcon(args.imagePositions[feature.icon.name], layout.get('icon-offset').evaluate(feature, {}, args.canonical), layout.get('icon-anchor').evaluate(feature, {}, args.canonical)); + // null/undefined SDF property treated same as default (false) + isSDFIcon = !!image.sdf; + if (args.bucket.sdfIcons === undefined) { + args.bucket.sdfIcons = isSDFIcon; + } + else if (args.bucket.sdfIcons !== isSDFIcon) { + warnOnce('Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer'); + } + if (image.pixelRatio !== args.bucket.pixelRatio) { + args.bucket.iconsNeedLinear = true; + } + else if (layout.get('icon-rotate').constantOr(1) !== 0) { + args.bucket.iconsNeedLinear = true; + } + } + } + const shapedText = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical; + args.bucket.iconsInText = shapedText ? shapedText.iconsInText : false; + if (shapedText || shapedIcon) { + addFeature$1(args.bucket, feature, shapedTextOrientations, shapedIcon, args.imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, args.canonical); + } + } + if (args.showCollisionBoxes) { + args.bucket.generateCollisionDebugBuffers(); + } +} +// Choose the justification that matches the direction of the TextAnchor +function getAnchorJustification(anchor) { + switch (anchor) { + case 'right': + case 'top-right': + case 'bottom-right': + return 'right'; + case 'left': + case 'top-left': + case 'bottom-left': + return 'left'; + } + return 'center'; +} +/** + * Given a feature and its shaped text and icon data, add a 'symbol + * instance' for each _possible_ placement of the symbol feature. + * (At render timePlaceSymbols#place() selects which of these instances to + * show or hide based on collisions with symbols in other layers.) + */ +function addFeature$1(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, canonical) { + // To reduce the number of labels that jump around when zooming we need + // to use a text-size value that is the same for all zoom levels. + // bucket calculates text-size at a high zoom level so that all tiles can + // use the same value when calculating anchor positions. + let textMaxSize = sizes.textMaxSize.evaluate(feature, {}); + if (textMaxSize === undefined) { + textMaxSize = layoutTextSize; + } + const layout = bucket.layers[0].layout; + const iconOffset = layout.get('icon-offset').evaluate(feature, {}, canonical); + const defaultHorizontalShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal); + const glyphSize = 24, fontScale = layoutTextSize / glyphSize, textBoxScale = bucket.tilePixelRatio * fontScale, textMaxBoxScale = bucket.tilePixelRatio * textMaxSize / glyphSize, iconBoxScale = bucket.tilePixelRatio * layoutIconSize, symbolMinDistance = bucket.tilePixelRatio * layout.get('symbol-spacing'), textPadding = layout.get('text-padding') * bucket.tilePixelRatio, iconPadding = getIconPadding(layout, feature, canonical, bucket.tilePixelRatio), textMaxAngle = layout.get('text-max-angle') / 180 * Math.PI, textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point', iconAlongLine = layout.get('icon-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point', symbolPlacement = layout.get('symbol-placement'), textRepeatDistance = symbolMinDistance / 2; + const iconTextFit = layout.get('icon-text-fit'); + let verticallyShapedIcon; + // Adjust shaped icon size when icon-text-fit is used. + if (shapedIcon && iconTextFit !== 'none') { + if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) { + verticallyShapedIcon = fitIconToText(shapedIcon, shapedTextOrientations.vertical, iconTextFit, layout.get('icon-text-fit-padding'), iconOffset, fontScale); + } + if (defaultHorizontalShaping) { + shapedIcon = fitIconToText(shapedIcon, defaultHorizontalShaping, iconTextFit, layout.get('icon-text-fit-padding'), iconOffset, fontScale); + } + } + const addSymbolAtAnchor = (line, anchor) => { + if (anchor.x < 0 || anchor.x >= EXTENT || anchor.y < 0 || anchor.y >= EXTENT) { + // Symbol layers are drawn across tile boundaries, We filter out symbols + // outside our tile boundaries (which may be included in vector tile buffers) + // to prevent double-drawing symbols. + return; + } + addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, bucket.layers[0], bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex, bucket.index, textBoxScale, [textPadding, textPadding, textPadding, textPadding], textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, canonical, layoutTextSize); + }; + if (symbolPlacement === 'line') { + for (const line of clipLine$1(feature.geometry, 0, 0, EXTENT, EXTENT)) { + const anchors = getAnchors(line, symbolMinDistance, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale, bucket.overscaling, EXTENT); + for (const anchor of anchors) { + const shapedText = defaultHorizontalShaping; + if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) { + addSymbolAtAnchor(line, anchor); + } + } + } + } + else if (symbolPlacement === 'line-center') { + // No clipping, multiple lines per feature are allowed + // "lines" with only one point are ignored as in clipLines + for (const line of feature.geometry) { + if (line.length > 1) { + const anchor = getCenterAnchor(line, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale); + if (anchor) { + addSymbolAtAnchor(line, anchor); + } + } + } + } + else if (feature.type === 'Polygon') { + for (const polygon of classifyRings$1(feature.geometry, 0)) { + // 16 here represents 2 pixels + const poi = findPoleOfInaccessibility(polygon, 16); + addSymbolAtAnchor(polygon[0], new Anchor(poi.x, poi.y, 0)); + } + } + else if (feature.type === 'LineString') { + // https://github.com/mapbox/mapbox-gl-js/issues/3808 + for (const line of feature.geometry) { + addSymbolAtAnchor(line, new Anchor(line[0].x, line[0].y, 0)); + } + } + else if (feature.type === 'Point') { + for (const points of feature.geometry) { + for (const point of points) { + addSymbolAtAnchor([point], new Anchor(point.x, point.y, 0)); + } + } + } +} +function addTextVariableAnchorOffsets(textAnchorOffsets, variableAnchorOffset) { + const startIndex = textAnchorOffsets.length; + const values = variableAnchorOffset === null || variableAnchorOffset === void 0 ? void 0 : variableAnchorOffset.values; + if ((values === null || values === void 0 ? void 0 : values.length) > 0) { + for (let i = 0; i < values.length; i += 2) { + const anchor = TextAnchorEnum[values[i]]; + const offset = values[i + 1]; + textAnchorOffsets.emplaceBack(anchor, offset[0], offset[1]); + } + } + return [startIndex, textAnchorOffsets.length]; +} +function addTextVertices(bucket, anchor, shapedText, imageMap, layer, textAlongLine, feature, textOffset, lineArray, writingMode, placementTypes, placedTextSymbolIndices, placedIconIndex, sizes, canonical) { + const glyphQuads = getGlyphQuads(anchor, shapedText, textOffset, layer, textAlongLine, feature, imageMap, bucket.allowVerticalPlacement); + const sizeData = bucket.textSizeData; + let textSizeData = null; + if (sizeData.kind === 'source') { + textSizeData = [ + SIZE_PACK_FACTOR * layer.layout.get('text-size').evaluate(feature, {}) + ]; + if (textSizeData[0] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`); + } + } + else if (sizeData.kind === 'composite') { + textSizeData = [ + SIZE_PACK_FACTOR * sizes.compositeTextSizes[0].evaluate(feature, {}, canonical), + SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical) + ]; + if (textSizeData[0] > MAX_PACKED_SIZE || textSizeData[1] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`); + } + } + bucket.addSymbols(bucket.text, glyphQuads, textSizeData, textOffset, textAlongLine, feature, writingMode, anchor, lineArray.lineStartIndex, lineArray.lineLength, placedIconIndex, canonical); + // The placedSymbolArray is used at render time in drawTileSymbols + // These indices allow access to the array at collision detection time + for (const placementType of placementTypes) { + placedTextSymbolIndices[placementType] = bucket.text.placedSymbolArray.length - 1; + } + return glyphQuads.length * 4; +} +function getDefaultHorizontalShaping(horizontalShaping) { + // We don't care which shaping we get because this is used for collision purposes + // and all the justifications have the same collision box + for (const justification in horizontalShaping) { + return horizontalShaping[justification]; + } + return null; +} +/** + * Add a single label & icon placement. + */ +function addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, layer, collisionBoxArray, featureIndex, sourceLayerIndex, bucketIndex, textBoxScale, textPadding, textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, canonical, layoutTextSize) { + const lineArray = bucket.addToLineVertexArray(anchor, line); + let textCollisionFeature, iconCollisionFeature, verticalTextCollisionFeature, verticalIconCollisionFeature; + let numIconVertices = 0; + let numVerticalIconVertices = 0; + let numHorizontalGlyphVertices = 0; + let numVerticalGlyphVertices = 0; + let placedIconSymbolIndex = -1; + let verticalPlacedIconSymbolIndex = -1; + const placedTextSymbolIndices = {}; + let key = murmur3$1(''); + if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) { + const textRotation = layer.layout.get('text-rotate').evaluate(feature, {}, canonical); + const verticalTextRotation = textRotation + 90.0; + const verticalShaping = shapedTextOrientations.vertical; + verticalTextCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textBoxScale, textPadding, textAlongLine, verticalTextRotation); + if (verticallyShapedIcon) { + verticalIconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconBoxScale, iconPadding, textAlongLine, verticalTextRotation); + } + } + //Place icon first, so text can have a reference to its index in the placed symbol array. + //Text symbols can lazily shift at render-time because of variable anchor placement. + //If the style specifies an `icon-text-fit` then the icon would have to shift along with it. + // For more info check `updateVariableAnchors` in `draw_symbol.js` . + if (shapedIcon) { + const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {}); + const hasIconTextFit = layer.layout.get('icon-text-fit') !== 'none'; + const iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit); + const verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit) : undefined; + iconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconBoxScale, iconPadding, /*align boxes to line*/ false, iconRotate); + numIconVertices = iconQuads.length * 4; + const sizeData = bucket.iconSizeData; + let iconSizeData = null; + if (sizeData.kind === 'source') { + iconSizeData = [ + SIZE_PACK_FACTOR * layer.layout.get('icon-size').evaluate(feature, {}) + ]; + if (iconSizeData[0] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`); + } + } + else if (sizeData.kind === 'composite') { + iconSizeData = [ + SIZE_PACK_FACTOR * sizes.compositeIconSizes[0].evaluate(feature, {}, canonical), + SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical) + ]; + if (iconSizeData[0] > MAX_PACKED_SIZE || iconSizeData[1] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`); + } + } + bucket.addSymbols(bucket.icon, iconQuads, iconSizeData, iconOffset, iconAlongLine, feature, WritingMode.none, anchor, lineArray.lineStartIndex, lineArray.lineLength, + // The icon itself does not have an associated symbol since the text isn't placed yet + -1, canonical); + placedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; + if (verticalIconQuads) { + numVerticalIconVertices = verticalIconQuads.length * 4; + bucket.addSymbols(bucket.icon, verticalIconQuads, iconSizeData, iconOffset, iconAlongLine, feature, WritingMode.vertical, anchor, lineArray.lineStartIndex, lineArray.lineLength, + // The icon itself does not have an associated symbol since the text isn't placed yet + -1, canonical); + verticalPlacedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; + } + } + const justifications = Object.keys(shapedTextOrientations.horizontal); + for (const justification of justifications) { + const shaping = shapedTextOrientations.horizontal[justification]; + if (!textCollisionFeature) { + key = murmur3$1(shaping.text); + const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}, canonical); + // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature + // We're counting on all versions having similar dimensions + textCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textBoxScale, textPadding, textAlongLine, textRotate); + } + const singleLine = shaping.positionedLines.length === 1; + numHorizontalGlyphVertices += addTextVertices(bucket, anchor, shaping, imageMap, layer, textAlongLine, feature, textOffset, lineArray, shapedTextOrientations.vertical ? WritingMode.horizontal : WritingMode.horizontalOnly, singleLine ? justifications : [justification], placedTextSymbolIndices, placedIconSymbolIndex, sizes, canonical); + if (singleLine) { + break; + } + } + if (shapedTextOrientations.vertical) { + numVerticalGlyphVertices += addTextVertices(bucket, anchor, shapedTextOrientations.vertical, imageMap, layer, textAlongLine, feature, textOffset, lineArray, WritingMode.vertical, ['vertical'], placedTextSymbolIndices, verticalPlacedIconSymbolIndex, sizes, canonical); + } + const textBoxStartIndex = textCollisionFeature ? textCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const textBoxEndIndex = textCollisionFeature ? textCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + const verticalTextBoxStartIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const verticalTextBoxEndIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + const iconBoxStartIndex = iconCollisionFeature ? iconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const iconBoxEndIndex = iconCollisionFeature ? iconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + const verticalIconBoxStartIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const verticalIconBoxEndIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + // Check if runtime collision circles should be used for any of the collision features. + // It is enough to choose the tallest feature shape as circles are always placed on a line. + // All measurements are in glyph metrics and later converted into pixels using proper font size "layoutTextSize" + let collisionCircleDiameter = -1; + const getCollisionCircleHeight = (feature, prevHeight) => { + if (feature && feature.circleDiameter) + return Math.max(feature.circleDiameter, prevHeight); + return prevHeight; + }; + collisionCircleDiameter = getCollisionCircleHeight(textCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(verticalTextCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(iconCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(verticalIconCollisionFeature, collisionCircleDiameter); + const useRuntimeCollisionCircles = (collisionCircleDiameter > -1) ? 1 : 0; + // Convert circle collision height into pixels + if (useRuntimeCollisionCircles) + collisionCircleDiameter *= layoutTextSize / ONE_EM; + if (bucket.glyphOffsetArray.length >= SymbolBucket.MAX_GLYPHS) + warnOnce('Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907'); + if (feature.sortKey !== undefined) { + bucket.addToSortKeyRanges(bucket.symbolInstances.length, feature.sortKey); + } + const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, canonical); + const [textAnchorOffsetStartIndex, textAnchorOffsetEndIndex] = addTextVariableAnchorOffsets(bucket.textAnchorOffsets, variableAnchorOffset); + bucket.symbolInstances.emplaceBack(anchor.x, anchor.y, placedTextSymbolIndices.right >= 0 ? placedTextSymbolIndices.right : -1, placedTextSymbolIndices.center >= 0 ? placedTextSymbolIndices.center : -1, placedTextSymbolIndices.left >= 0 ? placedTextSymbolIndices.left : -1, placedTextSymbolIndices.vertical || -1, placedIconSymbolIndex, verticalPlacedIconSymbolIndex, key, textBoxStartIndex, textBoxEndIndex, verticalTextBoxStartIndex, verticalTextBoxEndIndex, iconBoxStartIndex, iconBoxEndIndex, verticalIconBoxStartIndex, verticalIconBoxEndIndex, featureIndex, numHorizontalGlyphVertices, numVerticalGlyphVertices, numIconVertices, numVerticalIconVertices, useRuntimeCollisionCircles, 0, textBoxScale, collisionCircleDiameter, textAnchorOffsetStartIndex, textAnchorOffsetEndIndex); +} +function anchorIsTooClose(bucket, text, repeatDistance, anchor) { + const compareText = bucket.compareText; + if (!(text in compareText)) { + compareText[text] = []; + } + else { + const otherAnchors = compareText[text]; + for (let k = otherAnchors.length - 1; k >= 0; k--) { + if (anchor.dist(otherAnchors[k]) < repeatDistance) { + // If it's within repeatDistance of one anchor, stop looking + return true; + } + } + } + // If anchor is not within repeatDistance of any other anchor, add to array + compareText[text].push(anchor); + return false; +} + +const padding = 1; +class GlyphAtlas { + constructor(stacks) { + const positions = {}; + const bins = []; + for (const stack in stacks) { + const glyphs = stacks[stack]; + const stackPositions = positions[stack] = {}; + for (const id in glyphs) { + const src = glyphs[+id]; + if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) + continue; + const bin = { + x: 0, + y: 0, + w: src.bitmap.width + 2 * padding, + h: src.bitmap.height + 2 * padding + }; + bins.push(bin); + stackPositions[id] = { rect: bin, metrics: src.metrics }; + } + } + const { w, h } = potpack(bins); + const image = new AlphaImage({ width: w || 1, height: h || 1 }); + for (const stack in stacks) { + const glyphs = stacks[stack]; + for (const id in glyphs) { + const src = glyphs[+id]; + if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) + continue; + const bin = positions[stack][id].rect; + AlphaImage.copy(src.bitmap, image, { x: 0, y: 0 }, { x: bin.x + padding, y: bin.y + padding }, src.bitmap); + } + } + this.image = image; + this.positions = positions; + } +} +register('GlyphAtlas', GlyphAtlas); + +/** + * getURL + * + * @param {String} baseUrl Base url of the WMS server + * @param {String} layer Layer name + * @param {Number} x Tile coordinate x + * @param {Number} y Tile coordinate y + * @param {Number} z Tile zoom + * @param {Object} [options] + * @param {String} [options.format='image/png'] + * @param {String} [options.service='WMS'] + * @param {String} [options.version='1.1.1'] + * @param {String} [options.request='GetMap'] + * @param {String} [options.srs='EPSG:3857'] + * @param {Number} [options.width='256'] + * @param {Number} [options.height='256'] + * @returns {String} url + * @example + * var baseUrl = 'http://geodata.state.nj.us/imagerywms/Natural2015'; + * var layer = 'Natural2015'; + * var url = whoots.getURL(baseUrl, layer, 154308, 197167, 19); + */ +function getURL(baseUrl, layer, x, y, z, options) { + options = options || {}; + + var url = baseUrl + '?' + [ + 'bbox=' + getTileBBox(x, y, z), + 'format=' + (options.format || 'image/png'), + 'service=' + (options.service || 'WMS'), + 'version=' + (options.version || '1.1.1'), + 'request=' + (options.request || 'GetMap'), + 'srs=' + (options.srs || 'EPSG:3857'), + 'width=' + (options.width || 256), + 'height=' + (options.height || 256), + 'layers=' + layer + ].join('&'); + + return url; +} + + +/** + * getTileBBox + * + * @param {Number} x Tile coordinate x + * @param {Number} y Tile coordinate y + * @param {Number} z Tile zoom + * @returns {String} String of the bounding box + */ +function getTileBBox(x, y, z) { + // for Google/OSM tile scheme we need to alter the y + y = (Math.pow(2, z) - y - 1); + + var min = getMercCoords(x * 256, y * 256, z), + max = getMercCoords((x + 1) * 256, (y + 1) * 256, z); + + return min[0] + ',' + min[1] + ',' + max[0] + ',' + max[1]; +} + + +/** + * getMercCoords + * + * @param {Number} x Pixel coordinate x + * @param {Number} y Pixel coordinate y + * @param {Number} z Tile zoom + * @returns {Array} [x, y] + */ +function getMercCoords(x, y, z) { + var resolution = (2 * Math.PI * 6378137 / 256) / Math.pow(2, z), + merc_x = (x * resolution - 2 * Math.PI * 6378137 / 2.0), + merc_y = (y * resolution - 2 * Math.PI * 6378137 / 2.0); + + return [merc_x, merc_y]; +} + +/* +* Approximate radius of the earth in meters. +* 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 +* 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 +*/ +const earthRadius = 6371008.8; +/** + * A `LngLat` object represents a given longitude and latitude coordinate, measured in degrees. + * These coordinates are based on the [WGS84 (EPSG:4326) standard](https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84). + * + * MapLibre GL JS uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match the + * [GeoJSON specification](https://tools.ietf.org/html/rfc7946). + * + * Note that any MapLibre GL JS method that accepts a `LngLat` object as an argument or option + * can also accept an `Array` of two numbers and will perform an implicit conversion. + * This flexible type is documented as {@link LngLatLike}. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let ll = new LngLat(-123.9749, 40.7736); + * ll.lng; // = -123.9749 + * ``` + * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/) + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Create a timeline animation](https://maplibre.org/maplibre-gl-js/docs/examples/timeline-animation/) + */ +class LngLat { + /** + * @param lng - Longitude, measured in degrees. + * @param lat - Latitude, measured in degrees. + */ + constructor(lng, lat) { + if (isNaN(lng) || isNaN(lat)) { + throw new Error(`Invalid LngLat object: (${lng}, ${lat})`); + } + this.lng = +lng; + this.lat = +lat; + if (this.lat > 90 || this.lat < -90) { + throw new Error('Invalid LngLat latitude value: must be between -90 and 90'); + } + } + /** + * Returns a new `LngLat` object whose longitude is wrapped to the range (-180, 180). + * + * @returns The wrapped `LngLat` object. + * @example + * ```ts + * let ll = new LngLat(286.0251, 40.7736); + * let wrapped = ll.wrap(); + * wrapped.lng; // = -73.9749 + * ``` + */ + wrap() { + return new LngLat(wrap$1(this.lng, -180, 180), this.lat); + } + /** + * Returns the coordinates represented as an array of two numbers. + * + * @returns The coordinates represented as an array of longitude and latitude. + * @example + * ```ts + * let ll = new LngLat(-73.9749, 40.7736); + * ll.toArray(); // = [-73.9749, 40.7736] + * ``` + */ + toArray() { + return [this.lng, this.lat]; + } + /** + * Returns the coordinates represent as a string. + * + * @returns The coordinates represented as a string of the format `'LngLat(lng, lat)'`. + * @example + * ```ts + * let ll = new LngLat(-73.9749, 40.7736); + * ll.toString(); // = "LngLat(-73.9749, 40.7736)" + * ``` + */ + toString() { + return `LngLat(${this.lng}, ${this.lat})`; + } + /** + * Returns the approximate distance between a pair of coordinates in meters + * Uses the Haversine Formula (from R.W. Sinnott, "Virtues of the Haversine", Sky and Telescope, vol. 68, no. 2, 1984, p. 159) + * + * @param lngLat - coordinates to compute the distance to + * @returns Distance in meters between the two coordinates. + * @example + * ```ts + * let new_york = new LngLat(-74.0060, 40.7128); + * let los_angeles = new LngLat(-118.2437, 34.0522); + * new_york.distanceTo(los_angeles); // = 3935751.690893987, "true distance" using a non-spherical approximation is ~3966km + * ``` + */ + distanceTo(lngLat) { + const rad = Math.PI / 180; + const lat1 = this.lat * rad; + const lat2 = lngLat.lat * rad; + const a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((lngLat.lng - this.lng) * rad); + const maxMeters = earthRadius * Math.acos(Math.min(a, 1)); + return maxMeters; + } + /** + * Converts an array of two numbers or an object with `lng` and `lat` or `lon` and `lat` properties + * to a `LngLat` object. + * + * If a `LngLat` object is passed in, the function returns it unchanged. + * + * @param input - An array of two numbers or object to convert, or a `LngLat` object to return. + * @returns A new `LngLat` object, if a conversion occurred, or the original `LngLat` object. + * @example + * ```ts + * let arr = [-73.9749, 40.7736]; + * let ll = LngLat.convert(arr); + * ll; // = LngLat {lng: -73.9749, lat: 40.7736} + * ``` + */ + static convert(input) { + if (input instanceof LngLat) { + return input; + } + if (Array.isArray(input) && (input.length === 2 || input.length === 3)) { + return new LngLat(Number(input[0]), Number(input[1])); + } + if (!Array.isArray(input) && typeof input === 'object' && input !== null) { + return new LngLat( + // flow can't refine this to have one of lng or lat, so we have to cast to any + Number('lng' in input ? input.lng : input.lon), Number(input.lat)); + } + throw new Error('`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]'); + } +} + +/* + * The average circumference of the world in meters. + */ +const earthCircumference = 2 * Math.PI * earthRadius; // meters +/* + * The circumference at a line of latitude in meters. + */ +function circumferenceAtLatitude(latitude) { + return earthCircumference * Math.cos(latitude * Math.PI / 180); +} +function mercatorXfromLng(lng) { + return (180 + lng) / 360; +} +function mercatorYfromLat(lat) { + return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360; +} +function mercatorZfromAltitude(altitude, lat) { + return altitude / circumferenceAtLatitude(lat); +} +function lngFromMercatorX(x) { + return x * 360 - 180; +} +function latFromMercatorY(y) { + const y2 = 180 - y * 360; + return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90; +} +function altitudeFromMercatorZ(z, y) { + return z * circumferenceAtLatitude(latFromMercatorY(y)); +} +/** + * Determine the Mercator scale factor for a given latitude, see + * https://en.wikipedia.org/wiki/Mercator_projection#Scale_factor + * + * At the equator the scale factor will be 1, which increases at higher latitudes. + * + * @param lat - Latitude + * @returns scale factor + */ +function mercatorScale(lat) { + return 1 / Math.cos(lat * Math.PI / 180); +} +/** + * A `MercatorCoordinate` object represents a projected three dimensional position. + * + * `MercatorCoordinate` uses the web mercator projection ([EPSG:3857](https://epsg.io/3857)) with slightly different units: + * + * - the size of 1 unit is the width of the projected world instead of the "mercator meter" + * - the origin of the coordinate space is at the north-west corner instead of the middle + * + * For example, `MercatorCoordinate(0, 0, 0)` is the north-west corner of the mercator world and + * `MercatorCoordinate(1, 1, 0)` is the south-east corner. If you are familiar with + * [vector tiles](https://github.com/mapbox/vector-tile-spec) it may be helpful to think + * of the coordinate space as the `0/0/0` tile with an extent of `1`. + * + * The `z` dimension of `MercatorCoordinate` is conformal. A cube in the mercator coordinate space would be rendered as a cube. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let nullIsland = new MercatorCoordinate(0.5, 0.5, 0); + * ``` + * @see [Add a custom style layer](https://maplibre.org/maplibre-gl-js/docs/examples/custom-style-layer/) + */ +class MercatorCoordinate { + /** + * @param x - The x component of the position. + * @param y - The y component of the position. + * @param z - The z component of the position. + */ + constructor(x, y, z = 0) { + this.x = +x; + this.y = +y; + this.z = +z; + } + /** + * Project a `LngLat` to a `MercatorCoordinate`. + * + * @param lngLatLike - The location to project. + * @param altitude - The altitude in meters of the position. + * @returns The projected mercator coordinate. + * @example + * ```ts + * let coord = MercatorCoordinate.fromLngLat({ lng: 0, lat: 0}, 0); + * coord; // MercatorCoordinate(0.5, 0.5, 0) + * ``` + */ + static fromLngLat(lngLatLike, altitude = 0) { + const lngLat = LngLat.convert(lngLatLike); + return new MercatorCoordinate(mercatorXfromLng(lngLat.lng), mercatorYfromLat(lngLat.lat), mercatorZfromAltitude(altitude, lngLat.lat)); + } + /** + * Returns the `LngLat` for the coordinate. + * + * @returns The `LngLat` object. + * @example + * ```ts + * let coord = new MercatorCoordinate(0.5, 0.5, 0); + * let lngLat = coord.toLngLat(); // LngLat(0, 0) + * ``` + */ + toLngLat() { + return new LngLat(lngFromMercatorX(this.x), latFromMercatorY(this.y)); + } + /** + * Returns the altitude in meters of the coordinate. + * + * @returns The altitude in meters. + * @example + * ```ts + * let coord = new MercatorCoordinate(0, 0, 0.02); + * coord.toAltitude(); // 6914.281956295339 + * ``` + */ + toAltitude() { + return altitudeFromMercatorZ(this.z, this.y); + } + /** + * Returns the distance of 1 meter in `MercatorCoordinate` units at this latitude. + * + * For coordinates in real world units using meters, this naturally provides the scale + * to transform into `MercatorCoordinate`s. + * + * @returns Distance of 1 meter in `MercatorCoordinate` units. + */ + meterInMercatorCoordinateUnits() { + // 1 meter / circumference at equator in meters * Mercator projection scale factor at this latitude + return 1 / earthCircumference * mercatorScale(latFromMercatorY(this.y)); + } +} + +/** + * Returns true if a given tile zoom (Z), X, and Y are in the bounds of the world. + * Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive). + * X and Y bounds are 0 (inclusive) to their respective zoom-dependent maxima (exclusive). + * + * @param zoom - the tile zoom (Z) + * @param x - the tile X + * @param y - the tile Y + * @returns `true` if a given tile zoom, X, and Y are in the bounds of the world. + */ +function isInBoundsForTileZoomXY(zoom, x, y) { + return !(zoom < MIN_TILE_ZOOM || + zoom > MAX_TILE_ZOOM || + y < 0 || + y >= Math.pow(2, zoom) || + x < 0 || + x >= Math.pow(2, zoom)); +} +/** + * Returns true if a given zoom and `LngLat` are in the bounds of the world. + * Does not wrap `LngLat` when checking if in bounds. + * Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive). + * `LngLat` bounds are the mercator world's north-west corner (inclusive) to its south-east corner (exclusive). + * + * @param zoom - the tile zoom (Z) + * @param LngLat - the `LngLat` object containing the longitude and latitude + * @returns `true` if a given zoom and `LngLat` are in the bounds of the world. + */ +function isInBoundsForZoomLngLat(zoom, lnglat) { + const { x, y } = MercatorCoordinate.fromLngLat(lnglat); + return !(zoom < MIN_TILE_ZOOM || + zoom > MAX_TILE_ZOOM || + y < 0 || + y >= 1 || + x < 0 || + x >= 1); +} + +/** + * A canonical way to define a tile ID + */ +class CanonicalTileID { + constructor(z, x, y) { + if (!isInBoundsForTileZoomXY(z, x, y)) { + throw new Error(`x=${x}, y=${y}, z=${z} outside of bounds. 0<=x<${Math.pow(2, z)}, 0<=y<${Math.pow(2, z)} ${MIN_TILE_ZOOM}<=z<=${MAX_TILE_ZOOM} `); + } + this.z = z; + this.x = x; + this.y = y; + this.key = calculateKey(0, z, z, x, y); + } + equals(id) { + return this.z === id.z && this.x === id.x && this.y === id.y; + } + // given a list of urls, choose a url template and return a tile URL + url(urls, pixelRatio, scheme) { + const bbox = getTileBBox(this.x, this.y, this.z); + const quadkey = getQuadkey(this.z, this.x, this.y); + return urls[(this.x + this.y) % urls.length] + .replace(/{prefix}/g, (this.x % 16).toString(16) + (this.y % 16).toString(16)) + .replace(/{z}/g, String(this.z)) + .replace(/{x}/g, String(this.x)) + .replace(/{y}/g, String(scheme === 'tms' ? (Math.pow(2, this.z) - this.y - 1) : this.y)) + .replace(/{ratio}/g, pixelRatio > 1 ? '@2x' : '') + .replace(/{quadkey}/g, quadkey) + .replace(/{bbox-epsg-3857}/g, bbox); + } + isChildOf(parent) { + const dz = this.z - parent.z; + return dz > 0 && parent.x === (this.x >> dz) && parent.y === (this.y >> dz); + } + getTilePoint(coord) { + const tilesAtZoom = Math.pow(2, this.z); + return new Point$3((coord.x * tilesAtZoom - this.x) * EXTENT, (coord.y * tilesAtZoom - this.y) * EXTENT); + } + toString() { + return `${this.z}/${this.x}/${this.y}`; + } +} +/** + * @internal + * An unwrapped tile identifier + */ +class UnwrappedTileID { + constructor(wrap, canonical) { + this.wrap = wrap; + this.canonical = canonical; + this.key = calculateKey(wrap, canonical.z, canonical.z, canonical.x, canonical.y); + } +} +/** + * An overscaled tile identifier + */ +class OverscaledTileID { + constructor(overscaledZ, wrap, z, x, y) { + if (overscaledZ < z) + throw new Error(`overscaledZ should be >= z; overscaledZ = ${overscaledZ}; z = ${z}`); + this.overscaledZ = overscaledZ; + this.wrap = wrap; + this.canonical = new CanonicalTileID(z, +x, +y); + this.key = calculateKey(wrap, overscaledZ, z, x, y); + } + clone() { + return new OverscaledTileID(this.overscaledZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } + equals(id) { + return this.overscaledZ === id.overscaledZ && this.wrap === id.wrap && this.canonical.equals(id.canonical); + } + scaledTo(targetZ) { + if (targetZ > this.overscaledZ) + throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`); + const zDifference = this.canonical.z - targetZ; + if (targetZ > this.canonical.z) { + return new OverscaledTileID(targetZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } + else { + return new OverscaledTileID(targetZ, this.wrap, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference); + } + } + /* + * calculateScaledKey is an optimization: + * when withWrap == true, implements the same as this.scaledTo(z).key, + * when withWrap == false, implements the same as this.scaledTo(z).wrapped().key. + */ + calculateScaledKey(targetZ, withWrap) { + if (targetZ > this.overscaledZ) + throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`); + const zDifference = this.canonical.z - targetZ; + if (targetZ > this.canonical.z) { + return calculateKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y); + } + else { + return calculateKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference); + } + } + isChildOf(parent) { + if (parent.wrap !== this.wrap) { + // We can't be a child if we're in a different world copy + return false; + } + const zDifference = this.canonical.z - parent.canonical.z; + // We're first testing for z == 0, to avoid a 32 bit shift, which is undefined. + return parent.overscaledZ === 0 || (parent.overscaledZ < this.overscaledZ && + parent.canonical.x === (this.canonical.x >> zDifference) && + parent.canonical.y === (this.canonical.y >> zDifference)); + } + children(sourceMaxZoom) { + if (this.overscaledZ >= sourceMaxZoom) { + // return a single tile coord representing a an overscaled tile + return [new OverscaledTileID(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)]; + } + const z = this.canonical.z + 1; + const x = this.canonical.x * 2; + const y = this.canonical.y * 2; + return [ + new OverscaledTileID(z, this.wrap, z, x, y), + new OverscaledTileID(z, this.wrap, z, x + 1, y), + new OverscaledTileID(z, this.wrap, z, x, y + 1), + new OverscaledTileID(z, this.wrap, z, x + 1, y + 1) + ]; + } + isLessThan(rhs) { + if (this.wrap < rhs.wrap) + return true; + if (this.wrap > rhs.wrap) + return false; + if (this.overscaledZ < rhs.overscaledZ) + return true; + if (this.overscaledZ > rhs.overscaledZ) + return false; + if (this.canonical.x < rhs.canonical.x) + return true; + if (this.canonical.x > rhs.canonical.x) + return false; + if (this.canonical.y < rhs.canonical.y) + return true; + return false; + } + wrapped() { + return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y); + } + unwrapTo(wrap) { + return new OverscaledTileID(this.overscaledZ, wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } + overscaleFactor() { + return Math.pow(2, this.overscaledZ - this.canonical.z); + } + toUnwrapped() { + return new UnwrappedTileID(this.wrap, this.canonical); + } + toString() { + return `${this.overscaledZ}/${this.canonical.x}/${this.canonical.y}`; + } + getTilePoint(coord) { + return this.canonical.getTilePoint(new MercatorCoordinate(coord.x - this.wrap, coord.y)); + } +} +function calculateKey(wrap, overscaledZ, z, x, y) { + wrap *= 2; + if (wrap < 0) + wrap = wrap * -1 - 1; + const dim = 1 << z; + return (dim * dim * wrap + dim * y + x).toString(36) + z.toString(36) + overscaledZ.toString(36); +} +function getQuadkey(z, x, y) { + let quadkey = '', mask; + for (let i = z; i > 0; i--) { + mask = 1 << (i - 1); + quadkey += ((x & mask ? 1 : 0) + (y & mask ? 2 : 0)); + } + return quadkey; +} +register('CanonicalTileID', CanonicalTileID); +register('OverscaledTileID', OverscaledTileID, { omit: ['posMatrix'] }); + +class WorkerTile { + constructor(params) { + this.tileID = new OverscaledTileID(params.tileID.overscaledZ, params.tileID.wrap, params.tileID.canonical.z, params.tileID.canonical.x, params.tileID.canonical.y); + this.uid = params.uid; + this.zoom = params.zoom; + this.pixelRatio = params.pixelRatio; + this.tileSize = params.tileSize; + this.source = params.source; + this.overscaling = this.tileID.overscaleFactor(); + this.showCollisionBoxes = params.showCollisionBoxes; + this.collectResourceTiming = !!params.collectResourceTiming; + this.returnDependencies = !!params.returnDependencies; + this.promoteId = params.promoteId; + this.inFlightDependencies = []; + } + parse(data, layerIndex, availableImages, actor) { + return __awaiter(this, void 0, void 0, function* () { + this.status = 'parsing'; + this.data = data; + this.collisionBoxArray = new CollisionBoxArray(); + const sourceLayerCoder = new DictionaryCoder(Object.keys(data.layers).sort()); + const featureIndex = new FeatureIndex(this.tileID, this.promoteId); + featureIndex.bucketLayerIDs = []; + const buckets = {}; + const options = { + featureIndex, + iconDependencies: {}, + patternDependencies: {}, + glyphDependencies: {}, + availableImages + }; + const layerFamilies = layerIndex.familiesBySource[this.source]; + for (const sourceLayerId in layerFamilies) { + const sourceLayer = data.layers[sourceLayerId]; + if (!sourceLayer) { + continue; + } + if (sourceLayer.version === 1) { + warnOnce(`Vector tile source "${this.source}" layer "${sourceLayerId}" ` + + 'does not use vector tile spec v2 and therefore may have some rendering errors.'); + } + const sourceLayerIndex = sourceLayerCoder.encode(sourceLayerId); + const features = []; + for (let index = 0; index < sourceLayer.length; index++) { + const feature = sourceLayer.feature(index); + const id = featureIndex.getId(feature, sourceLayerId); + features.push({ feature, id, index, sourceLayerIndex }); + } + for (const family of layerFamilies[sourceLayerId]) { + const layer = family[0]; + if (layer.source !== this.source) { + warnOnce(`layer.source = ${layer.source} does not equal this.source = ${this.source}`); + } + if (layer.minzoom && this.zoom < Math.floor(layer.minzoom)) + continue; + if (layer.maxzoom && this.zoom >= layer.maxzoom) + continue; + if (layer.visibility === 'none') + continue; + recalculateLayers(family, this.zoom, availableImages); + const bucket = buckets[layer.id] = layer.createBucket({ + index: featureIndex.bucketLayerIDs.length, + layers: family, + zoom: this.zoom, + pixelRatio: this.pixelRatio, + overscaling: this.overscaling, + collisionBoxArray: this.collisionBoxArray, + sourceLayerIndex, + sourceID: this.source + }); + bucket.populate(features, options, this.tileID.canonical); + featureIndex.bucketLayerIDs.push(family.map((l) => l.id)); + } + } + // options.glyphDependencies looks like: {"SomeFontName":{"10":true,"32":true}} + // this line makes an object like: {"SomeFontName":[10,32]} + const stacks = mapObject(options.glyphDependencies, (glyphs) => Object.keys(glyphs).map(Number)); + this.inFlightDependencies.forEach((request) => request === null || request === void 0 ? void 0 : request.abort()); + this.inFlightDependencies = []; + let getGlyphsPromise = Promise.resolve({}); + if (Object.keys(stacks).length) { + const abortController = new AbortController(); + this.inFlightDependencies.push(abortController); + getGlyphsPromise = actor.sendAsync({ type: "GG" /* MessageType.getGlyphs */, data: { stacks, source: this.source, tileID: this.tileID, type: 'glyphs' } }, abortController); + } + const icons = Object.keys(options.iconDependencies); + let getIconsPromise = Promise.resolve({}); + let getIconBackgroundsPromise = Promise.resolve({}); + if (icons.length) { + const abortController = new AbortController(); + this.inFlightDependencies.push(abortController); + getIconsPromise = actor.sendAsync({ type: "GI" /* MessageType.getImages */, data: { icons, source: this.source, tileID: this.tileID, type: 'icons' } }, abortController); + // If there are MSDF icons we also need to add the background + const msdfIcons = icons.filter(i => i.includes('msdf')); + const backgroundIcons = msdfIcons.map(i => i.replace('msdf', 'msdf-backgrounds')); + if (backgroundIcons.length) { + getIconBackgroundsPromise = actor.sendAsync({ type: "GI" /* MessageType.getImages */, data: { icons: backgroundIcons, source: this.source, tileID: this.tileID, type: 'icons' } }, abortController); + } + } + const patterns = Object.keys(options.patternDependencies); + let getPatternsPromise = Promise.resolve({}); + if (patterns.length) { + const abortController = new AbortController(); + this.inFlightDependencies.push(abortController); + getPatternsPromise = actor.sendAsync({ type: "GI" /* MessageType.getImages */, data: { icons: patterns, source: this.source, tileID: this.tileID, type: 'patterns' } }, abortController); + } + const [glyphMap, iconMap, iconBackgroundsMap, patternMap] = yield Promise.all([getGlyphsPromise, getIconsPromise, getIconBackgroundsPromise, getPatternsPromise]); + const glyphAtlas = new GlyphAtlas(glyphMap); + const imageAtlas = new ImageAtlas(iconMap, patternMap); + const imageBackgroundsAtlas = new ImageAtlas(iconBackgroundsMap, {}); + for (const key in buckets) { + const bucket = buckets[key]; + if (bucket instanceof SymbolBucket) { + recalculateLayers(bucket.layers, this.zoom, availableImages); + performSymbolLayout({ + bucket, + glyphMap, + glyphPositions: glyphAtlas.positions, + imageMap: iconMap, + imagePositions: imageAtlas.iconPositions, + showCollisionBoxes: this.showCollisionBoxes, + canonical: this.tileID.canonical + }); + } + else if (bucket.hasPattern && + (bucket instanceof LineBucket || + bucket instanceof FillBucket || + bucket instanceof FillExtrusionBucket)) { + recalculateLayers(bucket.layers, this.zoom, availableImages); + bucket.addFeatures(options, this.tileID.canonical, imageAtlas.patternPositions); + } + } + this.status = 'done'; + return { + buckets: Object.values(buckets).filter(b => !b.isEmpty()), + featureIndex, + collisionBoxArray: this.collisionBoxArray, + glyphAtlasImage: glyphAtlas.image, + imageAtlas, + imageBackgroundsAtlas, + // Only used for benchmarking: + glyphMap: this.returnDependencies ? glyphMap : null, + iconMap: this.returnDependencies ? iconMap : null, + glyphPositions: this.returnDependencies ? glyphAtlas.positions : null + }; + }); + } +} +function recalculateLayers(layers, zoom, availableImages) { + // Layers are shared and may have been used by a WorkerTile with a different zoom. + const parameters = new EvaluationParameters(zoom); + for (const layer of layers) { + layer.recalculate(parameters, availableImages); + } +} + +var PerformanceMarkers; +(function (PerformanceMarkers) { + PerformanceMarkers["create"] = "create"; + PerformanceMarkers["load"] = "load"; + PerformanceMarkers["fullLoad"] = "fullLoad"; +})(PerformanceMarkers || (PerformanceMarkers = {})); +let lastFrameTime = null; +let frameTimes = []; +const minFramerateTarget = 60; +const frameTimeTarget = 1000 / minFramerateTarget; +const loadTimeKey = 'loadTime'; +const fullLoadTimeKey = 'fullLoadTime'; +const PerformanceUtils = { + mark(marker) { + performance.mark(marker); + }, + frame(timestamp) { + const currTimestamp = timestamp; + if (lastFrameTime != null) { + const frameTime = currTimestamp - lastFrameTime; + frameTimes.push(frameTime); + } + lastFrameTime = currTimestamp; + }, + clearMetrics() { + lastFrameTime = null; + frameTimes = []; + performance.clearMeasures(loadTimeKey); + performance.clearMeasures(fullLoadTimeKey); + for (const marker in PerformanceMarkers) { + performance.clearMarks(PerformanceMarkers[marker]); + } + }, + getPerformanceMetrics() { + performance.measure(loadTimeKey, PerformanceMarkers.create, PerformanceMarkers.load); + performance.measure(fullLoadTimeKey, PerformanceMarkers.create, PerformanceMarkers.fullLoad); + const loadTime = performance.getEntriesByName(loadTimeKey)[0].duration; + const fullLoadTime = performance.getEntriesByName(fullLoadTimeKey)[0].duration; + const totalFrames = frameTimes.length; + const avgFrameTime = frameTimes.reduce((prev, curr) => prev + curr, 0) / totalFrames / 1000; + const fps = 1 / avgFrameTime; + // count frames that missed our framerate target + const droppedFrames = frameTimes + .filter((frameTime) => frameTime > frameTimeTarget) + .reduce((acc, curr) => { + return acc + (curr - frameTimeTarget) / frameTimeTarget; + }, 0); + const percentDroppedFrames = (droppedFrames / (totalFrames + droppedFrames)) * 100; + return { + loadTime, + fullLoadTime, + fps, + percentDroppedFrames, + totalFrames + }; + } +}; +/** + * @internal + * Safe wrapper for the performance resource timing API in web workers with graceful degradation + */ +class RequestPerformance { + constructor(request) { + this._marks = { + start: [request.url, 'start'].join('#'), + end: [request.url, 'end'].join('#'), + measure: request.url.toString() + }; + performance.mark(this._marks.start); + } + finish() { + performance.mark(this._marks.end); + let resourceTimingData = performance.getEntriesByName(this._marks.measure); + // fallback if web worker implementation of perf.getEntriesByName returns empty + if (resourceTimingData.length === 0) { + performance.measure(this._marks.measure, this._marks.start, this._marks.end); + resourceTimingData = performance.getEntriesByName(this._marks.measure); + // cleanup + performance.clearMarks(this._marks.start); + performance.clearMarks(this._marks.end); + performance.clearMeasures(this._marks.measure); + } + return resourceTimingData; + } +} +var performance$1 = performance; + +/** + * The {@link WorkerSource} implementation that supports {@link VectorTileSource}. + * This class is designed to be easily reused to support custom source types + * for data formats that can be parsed/converted into an in-memory VectorTile + * representation. To do so, override its `loadVectorTile` method. + */ +class VectorTileWorkerSource { + /** + * @param loadVectorData - Optional method for custom loading of a VectorTile + * object based on parameters passed from the main-thread Source. See + * {@link VectorTileWorkerSource#loadTile}. The default implementation simply + * loads the pbf at `params.url`. + */ + constructor(actor, layerIndex, availableImages) { + this.actor = actor; + this.layerIndex = layerIndex; + this.availableImages = availableImages; + this.fetching = {}; + this.loading = {}; + this.loaded = {}; + } + /** + * Loads a vector tile + */ + loadVectorTile(params, abortController) { + return __awaiter(this, void 0, void 0, function* () { + const response = yield getArrayBuffer(params.request, abortController); + try { + const vectorTile$1 = new vectorTile.VectorTile(new Protobuf(response.data)); + return { + vectorTile: vectorTile$1, + rawData: response.data, + cacheControl: response.cacheControl, + expires: response.expires + }; + } + catch (ex) { + const bytes = new Uint8Array(response.data); + const isGzipped = bytes[0] === 0x1f && bytes[1] === 0x8b; + let errorMessage = `Unable to parse the tile at ${params.request.url}, `; + if (isGzipped) { + errorMessage += 'please make sure the data is not gzipped and that you have configured the relevant header in the server'; + } + else { + errorMessage += `got error: ${ex.message}`; + } + throw new Error(errorMessage); + } + }); + } + /** + * Implements {@link WorkerSource#loadTile}. Delegates to + * {@link VectorTileWorkerSource#loadVectorData} (which by default expects + * a `params.url` property) for fetching and producing a VectorTile object. + */ + loadTile(params) { + return __awaiter(this, void 0, void 0, function* () { + const tileUid = params.uid; + const perf = (params && params.request && params.request.collectResourceTiming) ? + new RequestPerformance(params.request) : false; + const workerTile = new WorkerTile(params); + this.loading[tileUid] = workerTile; + const abortController = new AbortController(); + workerTile.abort = abortController; + try { + const response = yield this.loadVectorTile(params, abortController); + delete this.loading[tileUid]; + if (!response) { + return null; + } + const rawTileData = response.rawData; + const cacheControl = {}; + if (response.expires) + cacheControl.expires = response.expires; + if (response.cacheControl) + cacheControl.cacheControl = response.cacheControl; + const resourceTiming = {}; + if (perf) { + const resourceTimingData = perf.finish(); + // it's necessary to eval the result of getEntriesByName() here via parse/stringify + // late evaluation in the main thread causes TypeError: illegal invocation + if (resourceTimingData) + resourceTiming.resourceTiming = JSON.parse(JSON.stringify(resourceTimingData)); + } + workerTile.vectorTile = response.vectorTile; + const parsePromise = workerTile.parse(response.vectorTile, this.layerIndex, this.availableImages, this.actor); + this.loaded[tileUid] = workerTile; + // keep the original fetching state so that reload tile can pick it up if the original parse is cancelled by reloads' parse + this.fetching[tileUid] = { rawTileData, cacheControl, resourceTiming }; + try { + const result = yield parsePromise; + // Transferring a copy of rawTileData because the worker needs to retain its copy. + return extend$1({ rawTileData: rawTileData.slice(0) }, result, cacheControl, resourceTiming); + } + finally { + delete this.fetching[tileUid]; + } + } + catch (err) { + delete this.loading[tileUid]; + workerTile.status = 'done'; + this.loaded[tileUid] = workerTile; + throw err; + } + }); + } + /** + * Implements {@link WorkerSource#reloadTile}. + */ + reloadTile(params) { + return __awaiter(this, void 0, void 0, function* () { + const uid = params.uid; + if (!this.loaded || !this.loaded[uid]) { + throw new Error('Should not be trying to reload a tile that was never loaded or has been removed'); + } + const workerTile = this.loaded[uid]; + workerTile.showCollisionBoxes = params.showCollisionBoxes; + if (workerTile.status === 'parsing') { + const result = yield workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor); + // if we have cancelled the original parse, make sure to pass the rawTileData from the original fetch + let parseResult; + if (this.fetching[uid]) { + const { rawTileData, cacheControl, resourceTiming } = this.fetching[uid]; + delete this.fetching[uid]; + parseResult = extend$1({ rawTileData: rawTileData.slice(0) }, result, cacheControl, resourceTiming); + } + else { + parseResult = result; + } + return parseResult; + } + // if there was no vector tile data on the initial load, don't try and re-parse tile + if (workerTile.status === 'done' && workerTile.vectorTile) { + // this seems like a missing case where cache control is lost? see #3309 + return workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor); + } + }); + } + /** + * Implements {@link WorkerSource#abortTile}. + */ + abortTile(params) { + return __awaiter(this, void 0, void 0, function* () { + const loading = this.loading; + const uid = params.uid; + if (loading && loading[uid] && loading[uid].abort) { + loading[uid].abort.abort(); + delete loading[uid]; + } + }); + } + /** + * Implements {@link WorkerSource#removeTile}. + */ + removeTile(params) { + return __awaiter(this, void 0, void 0, function* () { + if (this.loaded && this.loaded[params.uid]) { + delete this.loaded[params.uid]; + } + }); + } +} + +/** + * DEMData is a data structure for decoding, backfilling, and storing elevation data for processing in the hillshade shaders + * data can be populated either from a pngraw image tile or from serialized data sent back from a worker. When data is initially + * loaded from a image tile, we decode the pixel values using the appropriate decoding formula, but we store the + * elevation data as an Int32 value. we add 65536 (2^16) to eliminate negative values and enable the use of + * integer overflow when creating the texture used in the hillshadePrepare step. + * + * DEMData also handles the backfilling of data from a tile's neighboring tiles. This is necessary because we use a pixel's 8 + * surrounding pixel values to compute the slope at that pixel, and we cannot accurately calculate the slope at pixels on a + * tile's edge without backfilling from neighboring tiles. + */ +class DEMData { + /** + * Constructs a `DEMData` object + * @param uid - the tile's unique id + * @param data - RGBAImage data has uniform 1px padding on all sides: square tile edge size defines stride + // and dim is calculated as stride - 2. + * @param encoding - the encoding type of the data + * @param redFactor - the red channel factor used to unpack the data, used for `custom` encoding only + * @param greenFactor - the green channel factor used to unpack the data, used for `custom` encoding only + * @param blueFactor - the blue channel factor used to unpack the data, used for `custom` encoding only + * @param baseShift - the base shift used to unpack the data, used for `custom` encoding only + */ + constructor(uid, data, encoding, redFactor = 1.0, greenFactor = 1.0, blueFactor = 1.0, baseShift = 0.0) { + this.uid = uid; + if (data.height !== data.width) + throw new RangeError('DEM tiles must be square'); + if (encoding && !['mapbox', 'terrarium', 'custom'].includes(encoding)) { + warnOnce(`"${encoding}" is not a valid encoding type. Valid types include "mapbox", "terrarium" and "custom".`); + return; + } + this.stride = data.height; + const dim = this.dim = data.height - 2; + this.data = new Uint32Array(data.data.buffer); + switch (encoding) { + case 'terrarium': + // unpacking formula for mapzen terrarium: + // https://aws.amazon.com/public-datasets/terrain/ + this.redFactor = 256.0; + this.greenFactor = 1.0; + this.blueFactor = 1.0 / 256.0; + this.baseShift = 32768.0; + break; + case 'custom': + this.redFactor = redFactor; + this.greenFactor = greenFactor; + this.blueFactor = blueFactor; + this.baseShift = baseShift; + break; + case 'mapbox': + default: + // unpacking formula for mapbox.terrain-rgb: + // https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb + this.redFactor = 6553.6; + this.greenFactor = 25.6; + this.blueFactor = 0.1; + this.baseShift = 10000.0; + break; + } + // in order to avoid flashing seams between tiles, here we are initially populating a 1px border of pixels around the image + // with the data of the nearest pixel from the image. this data is eventually replaced when the tile's neighboring + // tiles are loaded and the accurate data can be backfilled using DEMData#backfillBorder + for (let x = 0; x < dim; x++) { + // left vertical border + this.data[this._idx(-1, x)] = this.data[this._idx(0, x)]; + // right vertical border + this.data[this._idx(dim, x)] = this.data[this._idx(dim - 1, x)]; + // left horizontal border + this.data[this._idx(x, -1)] = this.data[this._idx(x, 0)]; + // right horizontal border + this.data[this._idx(x, dim)] = this.data[this._idx(x, dim - 1)]; + } + // corners + this.data[this._idx(-1, -1)] = this.data[this._idx(0, 0)]; + this.data[this._idx(dim, -1)] = this.data[this._idx(dim - 1, 0)]; + this.data[this._idx(-1, dim)] = this.data[this._idx(0, dim - 1)]; + this.data[this._idx(dim, dim)] = this.data[this._idx(dim - 1, dim - 1)]; + // calculate min/max values + this.min = Number.MAX_SAFE_INTEGER; + this.max = Number.MIN_SAFE_INTEGER; + for (let x = 0; x < dim; x++) { + for (let y = 0; y < dim; y++) { + const ele = this.get(x, y); + if (ele > this.max) + this.max = ele; + if (ele < this.min) + this.min = ele; + } + } + } + get(x, y) { + const pixels = new Uint8Array(this.data.buffer); + const index = this._idx(x, y) * 4; + return this.unpack(pixels[index], pixels[index + 1], pixels[index + 2]); + } + getUnpackVector() { + return [this.redFactor, this.greenFactor, this.blueFactor, this.baseShift]; + } + _idx(x, y) { + if (x < -1 || x >= this.dim + 1 || y < -1 || y >= this.dim + 1) + throw new RangeError('out of range source coordinates for DEM data'); + return (y + 1) * this.stride + (x + 1); + } + unpack(r, g, b) { + return (r * this.redFactor + g * this.greenFactor + b * this.blueFactor - this.baseShift); + } + getPixels() { + return new RGBAImage({ width: this.stride, height: this.stride }, new Uint8Array(this.data.buffer)); + } + backfillBorder(borderTile, dx, dy) { + if (this.dim !== borderTile.dim) + throw new Error('dem dimension mismatch'); + let xMin = dx * this.dim, xMax = dx * this.dim + this.dim, yMin = dy * this.dim, yMax = dy * this.dim + this.dim; + switch (dx) { + case -1: + xMin = xMax - 1; + break; + case 1: + xMax = xMin + 1; + break; + } + switch (dy) { + case -1: + yMin = yMax - 1; + break; + case 1: + yMax = yMin + 1; + break; + } + const ox = -dx * this.dim; + const oy = -dy * this.dim; + for (let y = yMin; y < yMax; y++) { + for (let x = xMin; x < xMax; x++) { + this.data[this._idx(x, y)] = borderTile.data[this._idx(x + ox, y + oy)]; + } + } + } +} +register('DEMData', DEMData); + +class RasterDEMTileWorkerSource { + constructor() { + this.loaded = {}; + } + loadTile(params) { + return __awaiter(this, void 0, void 0, function* () { + const { uid, encoding, rawImageData, redFactor, greenFactor, blueFactor, baseShift } = params; + const width = rawImageData.width + 2; + const height = rawImageData.height + 2; + const imagePixels = isImageBitmap(rawImageData) ? + new RGBAImage({ width, height }, yield getImageData(rawImageData, -1, -1, width, height)) : + rawImageData; + const dem = new DEMData(uid, imagePixels, encoding, redFactor, greenFactor, blueFactor, baseShift); + this.loaded = this.loaded || {}; + this.loaded[uid] = dem; + return dem; + }); + } + removeTile(params) { + const loaded = this.loaded, uid = params.uid; + if (loaded && loaded[uid]) { + delete loaded[uid]; + } + } +} + +var geojsonRewind = rewind$1; + +function rewind$1(gj, outer) { + var type = gj && gj.type, i; + + if (type === 'FeatureCollection') { + for (i = 0; i < gj.features.length; i++) rewind$1(gj.features[i], outer); + + } else if (type === 'GeometryCollection') { + for (i = 0; i < gj.geometries.length; i++) rewind$1(gj.geometries[i], outer); + + } else if (type === 'Feature') { + rewind$1(gj.geometry, outer); + + } else if (type === 'Polygon') { + rewindRings(gj.coordinates, outer); + + } else if (type === 'MultiPolygon') { + for (i = 0; i < gj.coordinates.length; i++) rewindRings(gj.coordinates[i], outer); + } + + return gj; +} + +function rewindRings(rings, outer) { + if (rings.length === 0) return; + + rewindRing(rings[0], outer); + for (var i = 1; i < rings.length; i++) { + rewindRing(rings[i], !outer); + } +} + +function rewindRing(ring, dir) { + var area = 0, err = 0; + for (var i = 0, len = ring.length, j = len - 1; i < len; j = i++) { + var k = (ring[i][0] - ring[j][0]) * (ring[j][1] + ring[i][1]); + var m = area + k; + err += Math.abs(area) >= Math.abs(k) ? area - m + k : k - m + area; + area = m; + } + if (area + err >= 0 !== !!dir) ring.reverse(); +} + +var rewind$2 = /*@__PURE__*/getDefaultExportFromCjs$1(geojsonRewind); + +const toGeoJSON = vectorTile.VectorTileFeature.prototype.toGeoJSON; +let FeatureWrapper$1 = class FeatureWrapper { + constructor(feature) { + this._feature = feature; + this.extent = EXTENT; + this.type = feature.type; + this.properties = feature.tags; + // If the feature has a top-level `id` property, copy it over, but only + // if it can be coerced to an integer, because this wrapper is used for + // serializing geojson feature data into vector tile PBF data, and the + // vector tile spec only supports integer values for feature ids -- + // allowing non-integer values here results in a non-compliant PBF + // that causes an exception when it is parsed with vector-tile-js + if ('id' in feature && !isNaN(feature.id)) { + this.id = parseInt(feature.id, 10); + } + } + loadGeometry() { + if (this._feature.type === 1) { + const geometry = []; + for (const point of this._feature.geometry) { + geometry.push([new Point$3(point[0], point[1])]); + } + return geometry; + } + else { + const geometry = []; + for (const ring of this._feature.geometry) { + const newRing = []; + for (const point of ring) { + newRing.push(new Point$3(point[0], point[1])); + } + geometry.push(newRing); + } + return geometry; + } + } + toGeoJSON(x, y, z) { + return toGeoJSON.call(this, x, y, z); + } +}; +let GeoJSONWrapper$2 = class GeoJSONWrapper { + constructor(features) { + this.layers = { '_geojsonTileLayer': this }; + this.name = '_geojsonTileLayer'; + this.extent = EXTENT; + this.length = features.length; + this._features = features; + } + feature(i) { + return new FeatureWrapper$1(this._features[i]); + } +}; + +var vtPbf$1 = {exports: {}}; + +'use strict'; + +var Point = pointGeometry; +var VectorTileFeature = vectorTile.VectorTileFeature; + +var geojson_wrapper = GeoJSONWrapper$1; + +// conform to vectortile api +function GeoJSONWrapper$1 (features, options) { + this.options = options || {}; + this.features = features; + this.length = features.length; +} + +GeoJSONWrapper$1.prototype.feature = function (i) { + return new FeatureWrapper(this.features[i], this.options.extent) +}; + +function FeatureWrapper (feature, extent) { + this.id = typeof feature.id === 'number' ? feature.id : undefined; + this.type = feature.type; + this.rawGeometry = feature.type === 1 ? [feature.geometry] : feature.geometry; + this.properties = feature.tags; + this.extent = extent || 4096; +} + +FeatureWrapper.prototype.loadGeometry = function () { + var rings = this.rawGeometry; + this.geometry = []; + + for (var i = 0; i < rings.length; i++) { + var ring = rings[i]; + var newRing = []; + for (var j = 0; j < ring.length; j++) { + newRing.push(new Point(ring[j][0], ring[j][1])); + } + this.geometry.push(newRing); + } + return this.geometry +}; + +FeatureWrapper.prototype.bbox = function () { + if (!this.geometry) this.loadGeometry(); + + var rings = this.geometry; + var x1 = Infinity; + var x2 = -Infinity; + var y1 = Infinity; + var y2 = -Infinity; + + for (var i = 0; i < rings.length; i++) { + var ring = rings[i]; + + for (var j = 0; j < ring.length; j++) { + var coord = ring[j]; + + x1 = Math.min(x1, coord.x); + x2 = Math.max(x2, coord.x); + y1 = Math.min(y1, coord.y); + y2 = Math.max(y2, coord.y); + } + } + + return [x1, y1, x2, y2] +}; + +FeatureWrapper.prototype.toGeoJSON = VectorTileFeature.prototype.toGeoJSON; + +var geojson_wrapper$1 = /*@__PURE__*/getDefaultExportFromCjs$1(geojson_wrapper); + +var vtPbf = vtPbf$1.exports; + +var Pbf = pbf; +var GeoJSONWrapper = geojson_wrapper; + +vtPbf$1.exports = fromVectorTileJs; +var fromVectorTileJs_1 = vtPbf$1.exports.fromVectorTileJs = fromVectorTileJs; +var fromGeojsonVt_1 = vtPbf$1.exports.fromGeojsonVt = fromGeojsonVt; +var GeoJSONWrapper_1 = vtPbf$1.exports.GeoJSONWrapper = GeoJSONWrapper; + +/** + * Serialize a vector-tile-js-created tile to pbf + * + * @param {Object} tile + * @return {Buffer} uncompressed, pbf-serialized tile data + */ +function fromVectorTileJs (tile) { + var out = new Pbf(); + writeTile(tile, out); + return out.finish() +} + +/** + * Serialized a geojson-vt-created tile to pbf. + * + * @param {Object} layers - An object mapping layer names to geojson-vt-created vector tile objects + * @param {Object} [options] - An object specifying the vector-tile specification version and extent that were used to create `layers`. + * @param {Number} [options.version=1] - Version of vector-tile spec used + * @param {Number} [options.extent=4096] - Extent of the vector tile + * @return {Buffer} uncompressed, pbf-serialized tile data + */ +function fromGeojsonVt (layers, options) { + options = options || {}; + var l = {}; + for (var k in layers) { + l[k] = new GeoJSONWrapper(layers[k].features, options); + l[k].name = k; + l[k].version = options.version; + l[k].extent = options.extent; + } + return fromVectorTileJs({ layers: l }) +} + +function writeTile (tile, pbf) { + for (var key in tile.layers) { + pbf.writeMessage(3, writeLayer, tile.layers[key]); + } +} + +function writeLayer (layer, pbf) { + pbf.writeVarintField(15, layer.version || 1); + pbf.writeStringField(1, layer.name || ''); + pbf.writeVarintField(5, layer.extent || 4096); + + var i; + var context = { + keys: [], + values: [], + keycache: {}, + valuecache: {} + }; + + for (i = 0; i < layer.length; i++) { + context.feature = layer.feature(i); + pbf.writeMessage(2, writeFeature, context); + } + + var keys = context.keys; + for (i = 0; i < keys.length; i++) { + pbf.writeStringField(3, keys[i]); + } + + var values = context.values; + for (i = 0; i < values.length; i++) { + pbf.writeMessage(4, writeValue, values[i]); + } +} + +function writeFeature (context, pbf) { + var feature = context.feature; + + if (feature.id !== undefined) { + pbf.writeVarintField(1, feature.id); + } + + pbf.writeMessage(2, writeProperties, context); + pbf.writeVarintField(3, feature.type); + pbf.writeMessage(4, writeGeometry, feature); +} + +function writeProperties (context, pbf) { + var feature = context.feature; + var keys = context.keys; + var values = context.values; + var keycache = context.keycache; + var valuecache = context.valuecache; + + for (var key in feature.properties) { + var value = feature.properties[key]; + + var keyIndex = keycache[key]; + if (value === null) continue // don't encode null value properties + + if (typeof keyIndex === 'undefined') { + keys.push(key); + keyIndex = keys.length - 1; + keycache[key] = keyIndex; + } + pbf.writeVarint(keyIndex); + + var type = typeof value; + if (type !== 'string' && type !== 'boolean' && type !== 'number') { + value = JSON.stringify(value); + } + var valueKey = type + ':' + value; + var valueIndex = valuecache[valueKey]; + if (typeof valueIndex === 'undefined') { + values.push(value); + valueIndex = values.length - 1; + valuecache[valueKey] = valueIndex; + } + pbf.writeVarint(valueIndex); + } +} + +function command (cmd, length) { + return (length << 3) + (cmd & 0x7) +} + +function zigzag (num) { + return (num << 1) ^ (num >> 31) +} + +function writeGeometry (feature, pbf) { + var geometry = feature.loadGeometry(); + var type = feature.type; + var x = 0; + var y = 0; + var rings = geometry.length; + for (var r = 0; r < rings; r++) { + var ring = geometry[r]; + var count = 1; + if (type === 1) { + count = ring.length; + } + pbf.writeVarint(command(1, count)); // moveto + // do not write polygon closing path as lineto + var lineCount = type === 3 ? ring.length - 1 : ring.length; + for (var i = 0; i < lineCount; i++) { + if (i === 1 && type !== 1) { + pbf.writeVarint(command(2, lineCount - 1)); // lineto + } + var dx = ring[i].x - x; + var dy = ring[i].y - y; + pbf.writeVarint(zigzag(dx)); + pbf.writeVarint(zigzag(dy)); + x += dx; + y += dy; + } + if (type === 3) { + pbf.writeVarint(command(7, 1)); // closepath + } + } +} + +function writeValue (value, pbf) { + var type = typeof value; + if (type === 'string') { + pbf.writeStringField(1, value); + } else if (type === 'boolean') { + pbf.writeBooleanField(7, value); + } else if (type === 'number') { + if (value % 1 !== 0) { + pbf.writeDoubleField(3, value); + } else if (value < 0) { + pbf.writeSVarintField(6, value); + } else { + pbf.writeVarintField(5, value); + } + } +} + +var vtPbfExports = vtPbf$1.exports; +var vtpbf = /*@__PURE__*/getDefaultExportFromCjs$1(vtPbfExports); + +const ARRAY_TYPES = [ + Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, + Int32Array, Uint32Array, Float32Array, Float64Array +]; + +/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */ + +const VERSION = 1; // serialized format version +const HEADER_SIZE = 8; + +class KDBush { + + /** + * Creates an index from raw `ArrayBuffer` data. + * @param {ArrayBuffer} data + */ + static from(data) { + if (!(data instanceof ArrayBuffer)) { + throw new Error('Data must be an instance of ArrayBuffer.'); + } + const [magic, versionAndType] = new Uint8Array(data, 0, 2); + if (magic !== 0xdb) { + throw new Error('Data does not appear to be in a KDBush format.'); + } + const version = versionAndType >> 4; + if (version !== VERSION) { + throw new Error(`Got v${version} data when expected v${VERSION}.`); + } + const ArrayType = ARRAY_TYPES[versionAndType & 0x0f]; + if (!ArrayType) { + throw new Error('Unrecognized array type.'); + } + const [nodeSize] = new Uint16Array(data, 2, 1); + const [numItems] = new Uint32Array(data, 4, 1); + + return new KDBush(numItems, nodeSize, ArrayType, data); + } + + /** + * Creates an index that will hold a given number of items. + * @param {number} numItems + * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default). + * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default). + * @param {ArrayBuffer} [data] (For internal use only) + */ + constructor(numItems, nodeSize = 64, ArrayType = Float64Array, data) { + if (isNaN(numItems) || numItems < 0) throw new Error(`Unpexpected numItems value: ${numItems}.`); + + this.numItems = +numItems; + this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535); + this.ArrayType = ArrayType; + this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array; + + const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType); + const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT; + const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT; + const padCoords = (8 - idsByteSize % 8) % 8; + + if (arrayTypeIndex < 0) { + throw new Error(`Unexpected typed array class: ${ArrayType}.`); + } + + if (data && (data instanceof ArrayBuffer)) { // reconstruct an index from a buffer + this.data = data; + this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems); + this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2); + this._pos = numItems * 2; + this._finished = true; + } else { // initialize a new index + this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords); + this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems); + this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2); + this._pos = 0; + this._finished = false; + + // set header + new Uint8Array(this.data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]); + new Uint16Array(this.data, 2, 1)[0] = nodeSize; + new Uint32Array(this.data, 4, 1)[0] = numItems; + } + } + + /** + * Add a point to the index. + * @param {number} x + * @param {number} y + * @returns {number} An incremental index associated with the added item (starting from `0`). + */ + add(x, y) { + const index = this._pos >> 1; + this.ids[index] = index; + this.coords[this._pos++] = x; + this.coords[this._pos++] = y; + return index; + } + + /** + * Perform indexing of the added points. + */ + finish() { + const numAdded = this._pos >> 1; + if (numAdded !== this.numItems) { + throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`); + } + // kd-sort both arrays for efficient search + sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0); + + this._finished = true; + return this; + } + + /** + * Search the index for items within a given bounding box. + * @param {number} minX + * @param {number} minY + * @param {number} maxX + * @param {number} maxY + * @returns {number[]} An array of indices correponding to the found items. + */ + range(minX, minY, maxX, maxY) { + if (!this._finished) throw new Error('Data not yet indexed - call index.finish().'); + + const {ids, coords, nodeSize} = this; + const stack = [0, ids.length - 1, 0]; + const result = []; + + // recursively search for items in range in the kd-sorted arrays + while (stack.length) { + const axis = stack.pop() || 0; + const right = stack.pop() || 0; + const left = stack.pop() || 0; + + // if we reached "tree node", search linearly + if (right - left <= nodeSize) { + for (let i = left; i <= right; i++) { + const x = coords[2 * i]; + const y = coords[2 * i + 1]; + if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]); + } + continue; + } + + // otherwise find the middle index + const m = (left + right) >> 1; + + // include the middle item if it's in range + const x = coords[2 * m]; + const y = coords[2 * m + 1]; + if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]); + + // queue search in halves that intersect the query + if (axis === 0 ? minX <= x : minY <= y) { + stack.push(left); + stack.push(m - 1); + stack.push(1 - axis); + } + if (axis === 0 ? maxX >= x : maxY >= y) { + stack.push(m + 1); + stack.push(right); + stack.push(1 - axis); + } + } + + return result; + } + + /** + * Search the index for items within a given radius. + * @param {number} qx + * @param {number} qy + * @param {number} r Query radius. + * @returns {number[]} An array of indices correponding to the found items. + */ + within(qx, qy, r) { + if (!this._finished) throw new Error('Data not yet indexed - call index.finish().'); + + const {ids, coords, nodeSize} = this; + const stack = [0, ids.length - 1, 0]; + const result = []; + const r2 = r * r; + + // recursively search for items within radius in the kd-sorted arrays + while (stack.length) { + const axis = stack.pop() || 0; + const right = stack.pop() || 0; + const left = stack.pop() || 0; + + // if we reached "tree node", search linearly + if (right - left <= nodeSize) { + for (let i = left; i <= right; i++) { + if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]); + } + continue; + } + + // otherwise find the middle index + const m = (left + right) >> 1; + + // include the middle item if it's in range + const x = coords[2 * m]; + const y = coords[2 * m + 1]; + if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]); + + // queue search in halves that intersect the query + if (axis === 0 ? qx - r <= x : qy - r <= y) { + stack.push(left); + stack.push(m - 1); + stack.push(1 - axis); + } + if (axis === 0 ? qx + r >= x : qy + r >= y) { + stack.push(m + 1); + stack.push(right); + stack.push(1 - axis); + } + } + + return result; + } +} + +/** + * @param {Uint16Array | Uint32Array} ids + * @param {InstanceType} coords + * @param {number} nodeSize + * @param {number} left + * @param {number} right + * @param {number} axis + */ +function sort(ids, coords, nodeSize, left, right, axis) { + if (right - left <= nodeSize) return; + + const m = (left + right) >> 1; // middle index + + // sort ids and coords around the middle index so that the halves lie + // either left/right or top/bottom correspondingly (taking turns) + select(ids, coords, m, left, right, axis); + + // recursively kd-sort first half and second half on the opposite axis + sort(ids, coords, nodeSize, left, m - 1, 1 - axis); + sort(ids, coords, nodeSize, m + 1, right, 1 - axis); +} + +/** + * Custom Floyd-Rivest selection algorithm: sort ids and coords so that + * [left..k-1] items are smaller than k-th item (on either x or y axis) + * @param {Uint16Array | Uint32Array} ids + * @param {InstanceType} coords + * @param {number} k + * @param {number} left + * @param {number} right + * @param {number} axis + */ +function select(ids, coords, k, left, right, axis) { + + while (right > left) { + if (right - left > 600) { + const n = right - left + 1; + const m = k - left + 1; + const z = Math.log(n); + const s = 0.5 * Math.exp(2 * z / 3); + const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + const newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + select(ids, coords, k, newLeft, newRight, axis); + } + + const t = coords[2 * k + axis]; + let i = left; + let j = right; + + swapItem(ids, coords, left, k); + if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right); + + while (i < j) { + swapItem(ids, coords, i, j); + i++; + j--; + while (coords[2 * i + axis] < t) i++; + while (coords[2 * j + axis] > t) j--; + } + + if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j); + else { + j++; + swapItem(ids, coords, j, right); + } + + if (j <= k) left = j + 1; + if (k <= j) right = j - 1; + } +} + +/** + * @param {Uint16Array | Uint32Array} ids + * @param {InstanceType} coords + * @param {number} i + * @param {number} j + */ +function swapItem(ids, coords, i, j) { + swap(ids, i, j); + swap(coords, 2 * i, 2 * j); + swap(coords, 2 * i + 1, 2 * j + 1); +} + +/** + * @param {InstanceType} arr + * @param {number} i + * @param {number} j + */ +function swap(arr, i, j) { + const tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} + +/** + * @param {number} ax + * @param {number} ay + * @param {number} bx + * @param {number} by + */ +function sqDist(ax, ay, bx, by) { + const dx = ax - bx; + const dy = ay - by; + return dx * dx + dy * dy; +} + +const defaultOptions$1 = { + minZoom: 0, // min zoom to generate clusters on + maxZoom: 16, // max zoom level to cluster the points on + minPoints: 2, // minimum points to form a cluster + radius: 40, // cluster radius in pixels + extent: 512, // tile extent (radius is calculated relative to it) + nodeSize: 64, // size of the KD-tree leaf node, affects performance + log: false, // whether to log timing info + + // whether to generate numeric ids for input features (in vector tiles) + generateId: false, + + // a reduce function for calculating custom cluster properties + reduce: null, // (accumulated, props) => { accumulated.sum += props.sum; } + + // properties to use for individual points when running the reducer + map: props => props // props => ({sum: props.my_value}) +}; + +const fround = Math.fround || (tmp => ((x) => { tmp[0] = +x; return tmp[0]; }))(new Float32Array(1)); + +const OFFSET_ZOOM = 2; +const OFFSET_ID = 3; +const OFFSET_PARENT = 4; +const OFFSET_NUM = 5; +const OFFSET_PROP = 6; + +class Supercluster { + constructor(options) { + this.options = Object.assign(Object.create(defaultOptions$1), options); + this.trees = new Array(this.options.maxZoom + 1); + this.stride = this.options.reduce ? 7 : 6; + this.clusterProps = []; + } + + load(points) { + const {log, minZoom, maxZoom} = this.options; + + if (log) console.time('total time'); + + const timerId = `prepare ${ points.length } points`; + if (log) console.time(timerId); + + this.points = points; + + // generate a cluster object for each point and index input points into a KD-tree + const data = []; + + for (let i = 0; i < points.length; i++) { + const p = points[i]; + if (!p.geometry) continue; + + const [lng, lat] = p.geometry.coordinates; + const x = fround(lngX(lng)); + const y = fround(latY(lat)); + // store internal point/cluster data in flat numeric arrays for performance + data.push( + x, y, // projected point coordinates + Infinity, // the last zoom the point was processed at + i, // index of the source feature in the original input array + -1, // parent cluster id + 1 // number of points in a cluster + ); + if (this.options.reduce) data.push(0); // noop + } + let tree = this.trees[maxZoom + 1] = this._createTree(data); + + if (log) console.timeEnd(timerId); + + // cluster points on max zoom, then cluster the results on previous zoom, etc.; + // results in a cluster hierarchy across zoom levels + for (let z = maxZoom; z >= minZoom; z--) { + const now = +Date.now(); + + // create a new set of clusters for the zoom and index them with a KD-tree + tree = this.trees[z] = this._createTree(this._cluster(tree, z)); + + if (log) console.log('z%d: %d clusters in %dms', z, tree.numItems, +Date.now() - now); + } + + if (log) console.timeEnd('total time'); + + return this; + } + + getClusters(bbox, zoom) { + let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180; + const minLat = Math.max(-90, Math.min(90, bbox[1])); + let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180; + const maxLat = Math.max(-90, Math.min(90, bbox[3])); + + if (bbox[2] - bbox[0] >= 360) { + minLng = -180; + maxLng = 180; + } else if (minLng > maxLng) { + const easternHem = this.getClusters([minLng, minLat, 180, maxLat], zoom); + const westernHem = this.getClusters([-180, minLat, maxLng, maxLat], zoom); + return easternHem.concat(westernHem); + } + + const tree = this.trees[this._limitZoom(zoom)]; + const ids = tree.range(lngX(minLng), latY(maxLat), lngX(maxLng), latY(minLat)); + const data = tree.data; + const clusters = []; + for (const id of ids) { + const k = this.stride * id; + clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]); + } + return clusters; + } + + getChildren(clusterId) { + const originId = this._getOriginId(clusterId); + const originZoom = this._getOriginZoom(clusterId); + const errorMsg = 'No cluster with the specified id.'; + + const tree = this.trees[originZoom]; + if (!tree) throw new Error(errorMsg); + + const data = tree.data; + if (originId * this.stride >= data.length) throw new Error(errorMsg); + + const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1)); + const x = data[originId * this.stride]; + const y = data[originId * this.stride + 1]; + const ids = tree.within(x, y, r); + const children = []; + for (const id of ids) { + const k = id * this.stride; + if (data[k + OFFSET_PARENT] === clusterId) { + children.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]); + } + } + + if (children.length === 0) throw new Error(errorMsg); + + return children; + } + + getLeaves(clusterId, limit, offset) { + limit = limit || 10; + offset = offset || 0; + + const leaves = []; + this._appendLeaves(leaves, clusterId, limit, offset, 0); + + return leaves; + } + + getTile(z, x, y) { + const tree = this.trees[this._limitZoom(z)]; + const z2 = Math.pow(2, z); + const {extent, radius} = this.options; + const p = radius / extent; + const top = (y - p) / z2; + const bottom = (y + 1 + p) / z2; + + const tile = { + features: [] + }; + + this._addTileFeatures( + tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), + tree.data, x, y, z2, tile); + + if (x === 0) { + this._addTileFeatures( + tree.range(1 - p / z2, top, 1, bottom), + tree.data, z2, y, z2, tile); + } + if (x === z2 - 1) { + this._addTileFeatures( + tree.range(0, top, p / z2, bottom), + tree.data, -1, y, z2, tile); + } + + return tile.features.length ? tile : null; + } + + getClusterExpansionZoom(clusterId) { + let expansionZoom = this._getOriginZoom(clusterId) - 1; + while (expansionZoom <= this.options.maxZoom) { + const children = this.getChildren(clusterId); + expansionZoom++; + if (children.length !== 1) break; + clusterId = children[0].properties.cluster_id; + } + return expansionZoom; + } + + _appendLeaves(result, clusterId, limit, offset, skipped) { + const children = this.getChildren(clusterId); + + for (const child of children) { + const props = child.properties; + + if (props && props.cluster) { + if (skipped + props.point_count <= offset) { + // skip the whole cluster + skipped += props.point_count; + } else { + // enter the cluster + skipped = this._appendLeaves(result, props.cluster_id, limit, offset, skipped); + // exit the cluster + } + } else if (skipped < offset) { + // skip a single point + skipped++; + } else { + // add a single point + result.push(child); + } + if (result.length === limit) break; + } + + return skipped; + } + + _createTree(data) { + const tree = new KDBush(data.length / this.stride | 0, this.options.nodeSize, Float32Array); + for (let i = 0; i < data.length; i += this.stride) tree.add(data[i], data[i + 1]); + tree.finish(); + tree.data = data; + return tree; + } + + _addTileFeatures(ids, data, x, y, z2, tile) { + for (const i of ids) { + const k = i * this.stride; + const isCluster = data[k + OFFSET_NUM] > 1; + + let tags, px, py; + if (isCluster) { + tags = getClusterProperties(data, k, this.clusterProps); + px = data[k]; + py = data[k + 1]; + } else { + const p = this.points[data[k + OFFSET_ID]]; + tags = p.properties; + const [lng, lat] = p.geometry.coordinates; + px = lngX(lng); + py = latY(lat); + } + + const f = { + type: 1, + geometry: [[ + Math.round(this.options.extent * (px * z2 - x)), + Math.round(this.options.extent * (py * z2 - y)) + ]], + tags + }; + + // assign id + let id; + if (isCluster || this.options.generateId) { + // optionally generate id for points + id = data[k + OFFSET_ID]; + } else { + // keep id if already assigned + id = this.points[data[k + OFFSET_ID]].id; + } + + if (id !== undefined) f.id = id; + + tile.features.push(f); + } + } + + _limitZoom(z) { + return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1)); + } + + _cluster(tree, zoom) { + const {radius, extent, reduce, minPoints} = this.options; + const r = radius / (extent * Math.pow(2, zoom)); + const data = tree.data; + const nextData = []; + const stride = this.stride; + + // loop through each point + for (let i = 0; i < data.length; i += stride) { + // if we've already visited the point at this zoom level, skip it + if (data[i + OFFSET_ZOOM] <= zoom) continue; + data[i + OFFSET_ZOOM] = zoom; + + // find all nearby points + const x = data[i]; + const y = data[i + 1]; + const neighborIds = tree.within(data[i], data[i + 1], r); + + const numPointsOrigin = data[i + OFFSET_NUM]; + let numPoints = numPointsOrigin; + + // count the number of points in a potential cluster + for (const neighborId of neighborIds) { + const k = neighborId * stride; + // filter out neighbors that are already processed + if (data[k + OFFSET_ZOOM] > zoom) numPoints += data[k + OFFSET_NUM]; + } + + // if there were neighbors to merge, and there are enough points to form a cluster + if (numPoints > numPointsOrigin && numPoints >= minPoints) { + let wx = x * numPointsOrigin; + let wy = y * numPointsOrigin; + + let clusterProperties; + let clusterPropIndex = -1; + + // encode both zoom and point index on which the cluster originated -- offset by total length of features + const id = ((i / stride | 0) << 5) + (zoom + 1) + this.points.length; + + for (const neighborId of neighborIds) { + const k = neighborId * stride; + + if (data[k + OFFSET_ZOOM] <= zoom) continue; + data[k + OFFSET_ZOOM] = zoom; // save the zoom (so it doesn't get processed twice) + + const numPoints2 = data[k + OFFSET_NUM]; + wx += data[k] * numPoints2; // accumulate coordinates for calculating weighted center + wy += data[k + 1] * numPoints2; + + data[k + OFFSET_PARENT] = id; + + if (reduce) { + if (!clusterProperties) { + clusterProperties = this._map(data, i, true); + clusterPropIndex = this.clusterProps.length; + this.clusterProps.push(clusterProperties); + } + reduce(clusterProperties, this._map(data, k)); + } + } + + data[i + OFFSET_PARENT] = id; + nextData.push(wx / numPoints, wy / numPoints, Infinity, id, -1, numPoints); + if (reduce) nextData.push(clusterPropIndex); + + } else { // left points as unclustered + for (let j = 0; j < stride; j++) nextData.push(data[i + j]); + + if (numPoints > 1) { + for (const neighborId of neighborIds) { + const k = neighborId * stride; + if (data[k + OFFSET_ZOOM] <= zoom) continue; + data[k + OFFSET_ZOOM] = zoom; + for (let j = 0; j < stride; j++) nextData.push(data[k + j]); + } + } + } + } + + return nextData; + } + + // get index of the point from which the cluster originated + _getOriginId(clusterId) { + return (clusterId - this.points.length) >> 5; + } + + // get zoom of the point from which the cluster originated + _getOriginZoom(clusterId) { + return (clusterId - this.points.length) % 32; + } + + _map(data, i, clone) { + if (data[i + OFFSET_NUM] > 1) { + const props = this.clusterProps[data[i + OFFSET_PROP]]; + return clone ? Object.assign({}, props) : props; + } + const original = this.points[data[i + OFFSET_ID]].properties; + const result = this.options.map(original); + return clone && result === original ? Object.assign({}, result) : result; + } +} + +function getClusterJSON(data, i, clusterProps) { + return { + type: 'Feature', + id: data[i + OFFSET_ID], + properties: getClusterProperties(data, i, clusterProps), + geometry: { + type: 'Point', + coordinates: [xLng(data[i]), yLat(data[i + 1])] + } + }; +} + +function getClusterProperties(data, i, clusterProps) { + const count = data[i + OFFSET_NUM]; + const abbrev = + count >= 10000 ? `${Math.round(count / 1000) }k` : + count >= 1000 ? `${Math.round(count / 100) / 10 }k` : count; + const propIndex = data[i + OFFSET_PROP]; + const properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]); + return Object.assign(properties, { + cluster: true, + cluster_id: data[i + OFFSET_ID], + point_count: count, + point_count_abbreviated: abbrev + }); +} + +// longitude/latitude to spherical mercator in [0..1] range +function lngX(lng) { + return lng / 360 + 0.5; +} +function latY(lat) { + const sin = Math.sin(lat * Math.PI / 180); + const y = (0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI); + return y < 0 ? 0 : y > 1 ? 1 : y; +} + +// spherical mercator to longitude/latitude +function xLng(x) { + return (x - 0.5) * 360; +} +function yLat(y) { + const y2 = (180 - y * 360) * Math.PI / 180; + return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90; +} + +// calculate simplification data using optimized Douglas-Peucker algorithm + +function simplify(coords, first, last, sqTolerance) { + let maxSqDist = sqTolerance; + const mid = first + ((last - first) >> 1); + let minPosToMid = last - first; + let index; + + const ax = coords[first]; + const ay = coords[first + 1]; + const bx = coords[last]; + const by = coords[last + 1]; + + for (let i = first + 3; i < last; i += 3) { + const d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by); + + if (d > maxSqDist) { + index = i; + maxSqDist = d; + + } else if (d === maxSqDist) { + // a workaround to ensure we choose a pivot close to the middle of the list, + // reducing recursion depth, for certain degenerate inputs + // https://github.com/mapbox/geojson-vt/issues/104 + const posToMid = Math.abs(i - mid); + if (posToMid < minPosToMid) { + index = i; + minPosToMid = posToMid; + } + } + } + + if (maxSqDist > sqTolerance) { + if (index - first > 3) simplify(coords, first, index, sqTolerance); + coords[index + 2] = maxSqDist; + if (last - index > 3) simplify(coords, index, last, sqTolerance); + } +} + +// square distance from a point to a segment +function getSqSegDist(px, py, x, y, bx, by) { + + let dx = bx - x; + let dy = by - y; + + if (dx !== 0 || dy !== 0) { + + const t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy); + + if (t > 1) { + x = bx; + y = by; + + } else if (t > 0) { + x += dx * t; + y += dy * t; + } + } + + dx = px - x; + dy = py - y; + + return dx * dx + dy * dy; +} + +function createFeature(id, type, geom, tags) { + const feature = { + id: id == null ? null : id, + type, + geometry: geom, + tags, + minX: Infinity, + minY: Infinity, + maxX: -Infinity, + maxY: -Infinity + }; + + if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') { + calcLineBBox(feature, geom); + + } else if (type === 'Polygon') { + // the outer ring (ie [0]) contains all inner rings + calcLineBBox(feature, geom[0]); + + } else if (type === 'MultiLineString') { + for (const line of geom) { + calcLineBBox(feature, line); + } + + } else if (type === 'MultiPolygon') { + for (const polygon of geom) { + // the outer ring (ie [0]) contains all inner rings + calcLineBBox(feature, polygon[0]); + } + } + + return feature; +} + +function calcLineBBox(feature, geom) { + for (let i = 0; i < geom.length; i += 3) { + feature.minX = Math.min(feature.minX, geom[i]); + feature.minY = Math.min(feature.minY, geom[i + 1]); + feature.maxX = Math.max(feature.maxX, geom[i]); + feature.maxY = Math.max(feature.maxY, geom[i + 1]); + } +} + +// converts GeoJSON feature into an intermediate projected JSON vector format with simplification data + +function convert(data, options) { + const features = []; + if (data.type === 'FeatureCollection') { + for (let i = 0; i < data.features.length; i++) { + convertFeature(features, data.features[i], options, i); + } + + } else if (data.type === 'Feature') { + convertFeature(features, data, options); + + } else { + // single geometry or a geometry collection + convertFeature(features, {geometry: data}, options); + } + + return features; +} + +function convertFeature(features, geojson, options, index) { + if (!geojson.geometry) return; + + const coords = geojson.geometry.coordinates; + if (coords && coords.length === 0) return; + + const type = geojson.geometry.type; + const tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2); + let geometry = []; + let id = geojson.id; + if (options.promoteId) { + id = geojson.properties[options.promoteId]; + } else if (options.generateId) { + id = index || 0; + } + if (type === 'Point') { + convertPoint(coords, geometry); + + } else if (type === 'MultiPoint') { + for (const p of coords) { + convertPoint(p, geometry); + } + + } else if (type === 'LineString') { + convertLine(coords, geometry, tolerance, false); + + } else if (type === 'MultiLineString') { + if (options.lineMetrics) { + // explode into linestrings to be able to track metrics + for (const line of coords) { + geometry = []; + convertLine(line, geometry, tolerance, false); + features.push(createFeature(id, 'LineString', geometry, geojson.properties)); + } + return; + } else { + convertLines(coords, geometry, tolerance, false); + } + + } else if (type === 'Polygon') { + convertLines(coords, geometry, tolerance, true); + + } else if (type === 'MultiPolygon') { + for (const polygon of coords) { + const newPolygon = []; + convertLines(polygon, newPolygon, tolerance, true); + geometry.push(newPolygon); + } + } else if (type === 'GeometryCollection') { + for (const singleGeometry of geojson.geometry.geometries) { + convertFeature(features, { + id, + geometry: singleGeometry, + properties: geojson.properties + }, options, index); + } + return; + } else { + throw new Error('Input data is not a valid GeoJSON object.'); + } + + features.push(createFeature(id, type, geometry, geojson.properties)); +} + +function convertPoint(coords, out) { + out.push(projectX(coords[0]), projectY(coords[1]), 0); +} + +function convertLine(ring, out, tolerance, isPolygon) { + let x0, y0; + let size = 0; + + for (let j = 0; j < ring.length; j++) { + const x = projectX(ring[j][0]); + const y = projectY(ring[j][1]); + + out.push(x, y, 0); + + if (j > 0) { + if (isPolygon) { + size += (x0 * y - x * y0) / 2; // area + } else { + size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)); // length + } + } + x0 = x; + y0 = y; + } + + const last = out.length - 3; + out[2] = 1; + simplify(out, 0, last, tolerance); + out[last + 2] = 1; + + out.size = Math.abs(size); + out.start = 0; + out.end = out.size; +} + +function convertLines(rings, out, tolerance, isPolygon) { + for (let i = 0; i < rings.length; i++) { + const geom = []; + convertLine(rings[i], geom, tolerance, isPolygon); + out.push(geom); + } +} + +function projectX(x) { + return x / 360 + 0.5; +} + +function projectY(y) { + const sin = Math.sin(y * Math.PI / 180); + const y2 = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI; + return y2 < 0 ? 0 : y2 > 1 ? 1 : y2; +} + +/* clip features between two vertical or horizontal axis-parallel lines: + * | | + * ___|___ | / + * / | \____|____/ + * | | + * + * k1 and k2 are the line coordinates + * axis: 0 for x, 1 for y + * minAll and maxAll: minimum and maximum coordinate value for all features + */ +function clip(features, scale, k1, k2, axis, minAll, maxAll, options) { + k1 /= scale; + k2 /= scale; + + if (minAll >= k1 && maxAll < k2) return features; // trivial accept + else if (maxAll < k1 || minAll >= k2) return null; // trivial reject + + const clipped = []; + + for (const feature of features) { + const geometry = feature.geometry; + let type = feature.type; + + const min = axis === 0 ? feature.minX : feature.minY; + const max = axis === 0 ? feature.maxX : feature.maxY; + + if (min >= k1 && max < k2) { // trivial accept + clipped.push(feature); + continue; + } else if (max < k1 || min >= k2) { // trivial reject + continue; + } + + let newGeometry = []; + + if (type === 'Point' || type === 'MultiPoint') { + clipPoints(geometry, newGeometry, k1, k2, axis); + + } else if (type === 'LineString') { + clipLine(geometry, newGeometry, k1, k2, axis, false, options.lineMetrics); + + } else if (type === 'MultiLineString') { + clipLines(geometry, newGeometry, k1, k2, axis, false); + + } else if (type === 'Polygon') { + clipLines(geometry, newGeometry, k1, k2, axis, true); + + } else if (type === 'MultiPolygon') { + for (const polygon of geometry) { + const newPolygon = []; + clipLines(polygon, newPolygon, k1, k2, axis, true); + if (newPolygon.length) { + newGeometry.push(newPolygon); + } + } + } + + if (newGeometry.length) { + if (options.lineMetrics && type === 'LineString') { + for (const line of newGeometry) { + clipped.push(createFeature(feature.id, type, line, feature.tags)); + } + continue; + } + + if (type === 'LineString' || type === 'MultiLineString') { + if (newGeometry.length === 1) { + type = 'LineString'; + newGeometry = newGeometry[0]; + } else { + type = 'MultiLineString'; + } + } + if (type === 'Point' || type === 'MultiPoint') { + type = newGeometry.length === 3 ? 'Point' : 'MultiPoint'; + } + + clipped.push(createFeature(feature.id, type, newGeometry, feature.tags)); + } + } + + return clipped.length ? clipped : null; +} + +function clipPoints(geom, newGeom, k1, k2, axis) { + for (let i = 0; i < geom.length; i += 3) { + const a = geom[i + axis]; + + if (a >= k1 && a <= k2) { + addPoint(newGeom, geom[i], geom[i + 1], geom[i + 2]); + } + } +} + +function clipLine(geom, newGeom, k1, k2, axis, isPolygon, trackMetrics) { + + let slice = newSlice(geom); + const intersect = axis === 0 ? intersectX : intersectY; + let len = geom.start; + let segLen, t; + + for (let i = 0; i < geom.length - 3; i += 3) { + const ax = geom[i]; + const ay = geom[i + 1]; + const az = geom[i + 2]; + const bx = geom[i + 3]; + const by = geom[i + 4]; + const a = axis === 0 ? ax : ay; + const b = axis === 0 ? bx : by; + let exited = false; + + if (trackMetrics) segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2)); + + if (a < k1) { + // ---|--> | (line enters the clip region from the left) + if (b > k1) { + t = intersect(slice, ax, ay, bx, by, k1); + if (trackMetrics) slice.start = len + segLen * t; + } + } else if (a > k2) { + // | <--|--- (line enters the clip region from the right) + if (b < k2) { + t = intersect(slice, ax, ay, bx, by, k2); + if (trackMetrics) slice.start = len + segLen * t; + } + } else { + addPoint(slice, ax, ay, az); + } + if (b < k1 && a >= k1) { + // <--|--- | or <--|-----|--- (line exits the clip region on the left) + t = intersect(slice, ax, ay, bx, by, k1); + exited = true; + } + if (b > k2 && a <= k2) { + // | ---|--> or ---|-----|--> (line exits the clip region on the right) + t = intersect(slice, ax, ay, bx, by, k2); + exited = true; + } + + if (!isPolygon && exited) { + if (trackMetrics) slice.end = len + segLen * t; + newGeom.push(slice); + slice = newSlice(geom); + } + + if (trackMetrics) len += segLen; + } + + // add the last point + let last = geom.length - 3; + const ax = geom[last]; + const ay = geom[last + 1]; + const az = geom[last + 2]; + const a = axis === 0 ? ax : ay; + if (a >= k1 && a <= k2) addPoint(slice, ax, ay, az); + + // close the polygon if its endpoints are not the same after clipping + last = slice.length - 3; + if (isPolygon && last >= 3 && (slice[last] !== slice[0] || slice[last + 1] !== slice[1])) { + addPoint(slice, slice[0], slice[1], slice[2]); + } + + // add the final slice + if (slice.length) { + newGeom.push(slice); + } +} + +function newSlice(line) { + const slice = []; + slice.size = line.size; + slice.start = line.start; + slice.end = line.end; + return slice; +} + +function clipLines(geom, newGeom, k1, k2, axis, isPolygon) { + for (const line of geom) { + clipLine(line, newGeom, k1, k2, axis, isPolygon, false); + } +} + +function addPoint(out, x, y, z) { + out.push(x, y, z); +} + +function intersectX(out, ax, ay, bx, by, x) { + const t = (x - ax) / (bx - ax); + addPoint(out, x, ay + (by - ay) * t, 1); + return t; +} + +function intersectY(out, ax, ay, bx, by, y) { + const t = (y - ay) / (by - ay); + addPoint(out, ax + (bx - ax) * t, y, 1); + return t; +} + +function wrap(features, options) { + const buffer = options.buffer / options.extent; + let merged = features; + const left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options); // left world copy + const right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2, options); // right world copy + + if (left || right) { + merged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2, options) || []; // center world copy + + if (left) merged = shiftFeatureCoords(left, 1).concat(merged); // merge left into center + if (right) merged = merged.concat(shiftFeatureCoords(right, -1)); // merge right into center + } + + return merged; +} + +function shiftFeatureCoords(features, offset) { + const newFeatures = []; + + for (let i = 0; i < features.length; i++) { + const feature = features[i]; + const type = feature.type; + + let newGeometry; + + if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') { + newGeometry = shiftCoords(feature.geometry, offset); + + } else if (type === 'MultiLineString' || type === 'Polygon') { + newGeometry = []; + for (const line of feature.geometry) { + newGeometry.push(shiftCoords(line, offset)); + } + } else if (type === 'MultiPolygon') { + newGeometry = []; + for (const polygon of feature.geometry) { + const newPolygon = []; + for (const line of polygon) { + newPolygon.push(shiftCoords(line, offset)); + } + newGeometry.push(newPolygon); + } + } + + newFeatures.push(createFeature(feature.id, type, newGeometry, feature.tags)); + } + + return newFeatures; +} + +function shiftCoords(points, offset) { + const newPoints = []; + newPoints.size = points.size; + + if (points.start !== undefined) { + newPoints.start = points.start; + newPoints.end = points.end; + } + + for (let i = 0; i < points.length; i += 3) { + newPoints.push(points[i] + offset, points[i + 1], points[i + 2]); + } + return newPoints; +} + +// Transforms the coordinates of each feature in the given tile from +// mercator-projected space into (extent x extent) tile space. +function transformTile(tile, extent) { + if (tile.transformed) return tile; + + const z2 = 1 << tile.z; + const tx = tile.x; + const ty = tile.y; + + for (const feature of tile.features) { + const geom = feature.geometry; + const type = feature.type; + + feature.geometry = []; + + if (type === 1) { + for (let j = 0; j < geom.length; j += 2) { + feature.geometry.push(transformPoint(geom[j], geom[j + 1], extent, z2, tx, ty)); + } + } else { + for (let j = 0; j < geom.length; j++) { + const ring = []; + for (let k = 0; k < geom[j].length; k += 2) { + ring.push(transformPoint(geom[j][k], geom[j][k + 1], extent, z2, tx, ty)); + } + feature.geometry.push(ring); + } + } + } + + tile.transformed = true; + + return tile; +} + +function transformPoint(x, y, extent, z2, tx, ty) { + return [ + Math.round(extent * (x * z2 - tx)), + Math.round(extent * (y * z2 - ty))]; +} + +function createTile(features, z, tx, ty, options) { + const tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent); + const tile = { + features: [], + numPoints: 0, + numSimplified: 0, + numFeatures: features.length, + source: null, + x: tx, + y: ty, + z, + transformed: false, + minX: 2, + minY: 1, + maxX: -1, + maxY: 0 + }; + for (const feature of features) { + addFeature(tile, feature, tolerance, options); + } + return tile; +} + +function addFeature(tile, feature, tolerance, options) { + const geom = feature.geometry; + const type = feature.type; + const simplified = []; + + tile.minX = Math.min(tile.minX, feature.minX); + tile.minY = Math.min(tile.minY, feature.minY); + tile.maxX = Math.max(tile.maxX, feature.maxX); + tile.maxY = Math.max(tile.maxY, feature.maxY); + + if (type === 'Point' || type === 'MultiPoint') { + for (let i = 0; i < geom.length; i += 3) { + simplified.push(geom[i], geom[i + 1]); + tile.numPoints++; + tile.numSimplified++; + } + + } else if (type === 'LineString') { + addLine(simplified, geom, tile, tolerance, false, false); + + } else if (type === 'MultiLineString' || type === 'Polygon') { + for (let i = 0; i < geom.length; i++) { + addLine(simplified, geom[i], tile, tolerance, type === 'Polygon', i === 0); + } + + } else if (type === 'MultiPolygon') { + + for (let k = 0; k < geom.length; k++) { + const polygon = geom[k]; + for (let i = 0; i < polygon.length; i++) { + addLine(simplified, polygon[i], tile, tolerance, true, i === 0); + } + } + } + + if (simplified.length) { + let tags = feature.tags || null; + + if (type === 'LineString' && options.lineMetrics) { + tags = {}; + for (const key in feature.tags) tags[key] = feature.tags[key]; + tags['mapbox_clip_start'] = geom.start / geom.size; + tags['mapbox_clip_end'] = geom.end / geom.size; + } + + const tileFeature = { + geometry: simplified, + type: type === 'Polygon' || type === 'MultiPolygon' ? 3 : + (type === 'LineString' || type === 'MultiLineString' ? 2 : 1), + tags + }; + if (feature.id !== null) { + tileFeature.id = feature.id; + } + tile.features.push(tileFeature); + } +} + +function addLine(result, geom, tile, tolerance, isPolygon, isOuter) { + const sqTolerance = tolerance * tolerance; + + if (tolerance > 0 && (geom.size < (isPolygon ? sqTolerance : tolerance))) { + tile.numPoints += geom.length / 3; + return; + } + + const ring = []; + + for (let i = 0; i < geom.length; i += 3) { + if (tolerance === 0 || geom[i + 2] > sqTolerance) { + tile.numSimplified++; + ring.push(geom[i], geom[i + 1]); + } + tile.numPoints++; + } + + if (isPolygon) rewind(ring, isOuter); + + result.push(ring); +} + +function rewind(ring, clockwise) { + let area = 0; + for (let i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) { + area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]); + } + if (area > 0 === clockwise) { + for (let i = 0, len = ring.length; i < len / 2; i += 2) { + const x = ring[i]; + const y = ring[i + 1]; + ring[i] = ring[len - 2 - i]; + ring[i + 1] = ring[len - 1 - i]; + ring[len - 2 - i] = x; + ring[len - 1 - i] = y; + } + } +} + +const defaultOptions = { + maxZoom: 14, // max zoom to preserve detail on + indexMaxZoom: 5, // max zoom in the tile index + indexMaxPoints: 100000, // max number of points per tile in the tile index + tolerance: 3, // simplification tolerance (higher means simpler) + extent: 4096, // tile extent + buffer: 64, // tile buffer on each side + lineMetrics: false, // whether to calculate line metrics + promoteId: null, // name of a feature property to be promoted to feature.id + generateId: false, // whether to generate feature ids. Cannot be used with promoteId + debug: 0 // logging level (0, 1 or 2) +}; + +class GeoJSONVT { + constructor(data, options) { + options = this.options = extend(Object.create(defaultOptions), options); + + const debug = options.debug; + + if (debug) console.time('preprocess data'); + + if (options.maxZoom < 0 || options.maxZoom > 24) throw new Error('maxZoom should be in the 0-24 range'); + if (options.promoteId && options.generateId) throw new Error('promoteId and generateId cannot be used together.'); + + // projects and adds simplification info + let features = convert(data, options); + + // tiles and tileCoords are part of the public API + this.tiles = {}; + this.tileCoords = []; + + if (debug) { + console.timeEnd('preprocess data'); + console.log('index: maxZoom: %d, maxPoints: %d', options.indexMaxZoom, options.indexMaxPoints); + console.time('generate tiles'); + this.stats = {}; + this.total = 0; + } + + // wraps features (ie extreme west and extreme east) + features = wrap(features, options); + + // start slicing from the top tile down + if (features.length) this.splitTile(features, 0, 0, 0); + + if (debug) { + if (features.length) console.log('features: %d, points: %d', this.tiles[0].numFeatures, this.tiles[0].numPoints); + console.timeEnd('generate tiles'); + console.log('tiles generated:', this.total, JSON.stringify(this.stats)); + } + } + + // splits features from a parent tile to sub-tiles. + // z, x, and y are the coordinates of the parent tile + // cz, cx, and cy are the coordinates of the target tile + // + // If no target tile is specified, splitting stops when we reach the maximum + // zoom or the number of points is low as specified in the options. + splitTile(features, z, x, y, cz, cx, cy) { + + const stack = [features, z, x, y]; + const options = this.options; + const debug = options.debug; + + // avoid recursion by using a processing queue + while (stack.length) { + y = stack.pop(); + x = stack.pop(); + z = stack.pop(); + features = stack.pop(); + + const z2 = 1 << z; + const id = toID(z, x, y); + let tile = this.tiles[id]; + + if (!tile) { + if (debug > 1) console.time('creation'); + + tile = this.tiles[id] = createTile(features, z, x, y, options); + this.tileCoords.push({z, x, y}); + + if (debug) { + if (debug > 1) { + console.log('tile z%d-%d-%d (features: %d, points: %d, simplified: %d)', + z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified); + console.timeEnd('creation'); + } + const key = `z${ z}`; + this.stats[key] = (this.stats[key] || 0) + 1; + this.total++; + } + } + + // save reference to original geometry in tile so that we can drill down later if we stop now + tile.source = features; + + // if it's the first-pass tiling + if (cz == null) { + // stop tiling if we reached max zoom, or if the tile is too simple + if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints) continue; + // if a drilldown to a specific tile + } else if (z === options.maxZoom || z === cz) { + // stop tiling if we reached base zoom or our target tile zoom + continue; + } else if (cz != null) { + // stop tiling if it's not an ancestor of the target tile + const zoomSteps = cz - z; + if (x !== cx >> zoomSteps || y !== cy >> zoomSteps) continue; + } + + // if we slice further down, no need to keep source geometry + tile.source = null; + + if (features.length === 0) continue; + + if (debug > 1) console.time('clipping'); + + // values we'll use for clipping + const k1 = 0.5 * options.buffer / options.extent; + const k2 = 0.5 - k1; + const k3 = 0.5 + k1; + const k4 = 1 + k1; + + let tl = null; + let bl = null; + let tr = null; + let br = null; + + let left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options); + let right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX, options); + features = null; + + if (left) { + tl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options); + bl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options); + left = null; + } + + if (right) { + tr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options); + br = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options); + right = null; + } + + if (debug > 1) console.timeEnd('clipping'); + + stack.push(tl || [], z + 1, x * 2, y * 2); + stack.push(bl || [], z + 1, x * 2, y * 2 + 1); + stack.push(tr || [], z + 1, x * 2 + 1, y * 2); + stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1); + } + } + + getTile(z, x, y) { + z = +z; + x = +x; + y = +y; + + const options = this.options; + const {extent, debug} = options; + + if (z < 0 || z > 24) return null; + + const z2 = 1 << z; + x = (x + z2) & (z2 - 1); // wrap tile x coordinate + + const id = toID(z, x, y); + if (this.tiles[id]) return transformTile(this.tiles[id], extent); + + if (debug > 1) console.log('drilling down to z%d-%d-%d', z, x, y); + + let z0 = z; + let x0 = x; + let y0 = y; + let parent; + + while (!parent && z0 > 0) { + z0--; + x0 = x0 >> 1; + y0 = y0 >> 1; + parent = this.tiles[toID(z0, x0, y0)]; + } + + if (!parent || !parent.source) return null; + + // if we found a parent tile containing the original geometry, we can drill down from it + if (debug > 1) { + console.log('found parent tile z%d-%d-%d', z0, x0, y0); + console.time('drilling down'); + } + this.splitTile(parent.source, z0, x0, y0, z, x, y); + if (debug > 1) console.timeEnd('drilling down'); + + return this.tiles[id] ? transformTile(this.tiles[id], extent) : null; + } +} + +function toID(z, x, y) { + return (((1 << z) * y + x) * 32) + z; +} + +function extend(dest, src) { + for (const i in src) dest[i] = src[i]; + return dest; +} + +function geojsonvt(data, options) { + return new GeoJSONVT(data, options); +} + +function getFeatureId(feature, promoteId) { + return promoteId ? feature.properties[promoteId] : feature.id; +} +function isUpdateableGeoJSON(data, promoteId) { + // null can be updated + if (data == null) { + return true; + } + // a single feature with an id can be updated, need to explicitly check against null because 0 is a valid feature id that is falsy + if (data.type === 'Feature') { + return getFeatureId(data, promoteId) != null; + } + // a feature collection can be updated if every feature has an id, and the ids are all unique + // this prevents us from silently dropping features if ids get reused + if (data.type === 'FeatureCollection') { + const seenIds = new Set(); + for (const feature of data.features) { + const id = getFeatureId(feature, promoteId); + if (id == null) { + return false; + } + if (seenIds.has(id)) { + return false; + } + seenIds.add(id); + } + return true; + } + return false; +} +function toUpdateable(data, promoteId) { + const result = new Map(); + if (data == null) { + // empty result + } + else if (data.type === 'Feature') { + result.set(getFeatureId(data, promoteId), data); + } + else { + for (const feature of data.features) { + result.set(getFeatureId(feature, promoteId), feature); + } + } + return result; +} +// mutates updateable +function applySourceDiff(updateable, diff, promoteId) { + var _a, _b, _c, _d; + if (diff.removeAll) { + updateable.clear(); + } + if (diff.remove) { + for (const id of diff.remove) { + updateable.delete(id); + } + } + if (diff.add) { + for (const feature of diff.add) { + const id = getFeatureId(feature, promoteId); + if (id != null) { + updateable.set(id, feature); + } + } + } + if (diff.update) { + for (const update of diff.update) { + let feature = updateable.get(update.id); + if (feature == null) { + continue; + } + // be careful to clone the feature and/or properties objects to avoid mutating our input + const cloneFeature = update.newGeometry || update.removeAllProperties; + // note: removeAllProperties gives us a new properties object, so we can skip the clone step + const cloneProperties = !update.removeAllProperties && (((_a = update.removeProperties) === null || _a === void 0 ? void 0 : _a.length) > 0 || ((_b = update.addOrUpdateProperties) === null || _b === void 0 ? void 0 : _b.length) > 0); + if (cloneFeature || cloneProperties) { + feature = Object.assign({}, feature); + updateable.set(update.id, feature); + if (cloneProperties) { + feature.properties = Object.assign({}, feature.properties); + } + } + if (update.newGeometry) { + feature.geometry = update.newGeometry; + } + if (update.removeAllProperties) { + feature.properties = {}; + } + else if (((_c = update.removeProperties) === null || _c === void 0 ? void 0 : _c.length) > 0) { + for (const prop of update.removeProperties) { + if (Object.prototype.hasOwnProperty.call(feature.properties, prop)) { + delete feature.properties[prop]; + } + } + } + if (((_d = update.addOrUpdateProperties) === null || _d === void 0 ? void 0 : _d.length) > 0) { + for (const { key, value } of update.addOrUpdateProperties) { + feature.properties[key] = value; + } + } + } + } +} + +/** + * The {@link WorkerSource} implementation that supports {@link GeoJSONSource}. + * This class is designed to be easily reused to support custom source types + * for data formats that can be parsed/converted into an in-memory GeoJSON + * representation. To do so, create it with + * `new GeoJSONWorkerSource(actor, layerIndex, customLoadGeoJSONFunction)`. + * For a full example, see [mapbox-gl-topojson](https://github.com/developmentseed/mapbox-gl-topojson). + */ +class GeoJSONWorkerSource extends VectorTileWorkerSource { + constructor() { + super(...arguments); + this._dataUpdateable = new Map(); + } + loadVectorTile(params, _abortController) { + return __awaiter(this, void 0, void 0, function* () { + const canonical = params.tileID.canonical; + if (!this._geoJSONIndex) { + throw new Error('Unable to parse the data into a cluster or geojson'); + } + const geoJSONTile = this._geoJSONIndex.getTile(canonical.z, canonical.x, canonical.y); + if (!geoJSONTile) { + return null; + } + const geojsonWrapper = new GeoJSONWrapper$2(geoJSONTile.features); + // Encode the geojson-vt tile into binary vector tile form. This + // is a convenience that allows `FeatureIndex` to operate the same way + // across `VectorTileSource` and `GeoJSONSource` data. + let pbf = vtpbf(geojsonWrapper); + if (pbf.byteOffset !== 0 || pbf.byteLength !== pbf.buffer.byteLength) { + // Compatibility with node Buffer (https://github.com/mapbox/pbf/issues/35) + pbf = new Uint8Array(pbf); + } + return { + vectorTile: geojsonWrapper, + rawData: pbf.buffer + }; + }); + } + /** + * Fetches (if appropriate), parses, and index geojson data into tiles. This + * preparatory method must be called before {@link GeoJSONWorkerSource#loadTile} + * can correctly serve up tiles. + * + * Defers to {@link GeoJSONWorkerSource#loadAndProcessGeoJSON} for the pre-processing. + * + * When a `loadData` request comes in while a previous one is being processed, + * the previous one is aborted. + * + * @param params - the parameters + * @returns a promise that resolves when the data is loaded and parsed into a GeoJSON object + */ + loadData(params) { + return __awaiter(this, void 0, void 0, function* () { + var _a; + (_a = this._pendingRequest) === null || _a === void 0 ? void 0 : _a.abort(); + const perf = (params && params.request && params.request.collectResourceTiming) ? + new RequestPerformance(params.request) : false; + this._pendingRequest = new AbortController(); + try { + this._pendingData = this.loadAndProcessGeoJSON(params, this._pendingRequest); + this._geoJSONIndex = params.cluster ? + new Supercluster(getSuperclusterOptions(params)).load((yield this._pendingData).features) : + geojsonvt(yield this._pendingData, params.geojsonVtOptions); + this.loaded = {}; + const result = {}; + if (perf) { + const resourceTimingData = perf.finish(); + // it's necessary to eval the result of getEntriesByName() here via parse/stringify + // late evaluation in the main thread causes TypeError: illegal invocation + if (resourceTimingData) { + result.resourceTiming = {}; + result.resourceTiming[params.source] = JSON.parse(JSON.stringify(resourceTimingData)); + } + } + return result; + } + catch (err) { + delete this._pendingRequest; + if (isAbortError(err)) { + return { abandoned: true }; + } + throw err; + } + }); + } + /** + * Allows to get the source's actual GeoJSON. + * + * @returns a promise which is resolved with the source's actual GeoJSON + */ + getData() { + return __awaiter(this, void 0, void 0, function* () { + return this._pendingData; + }); + } + /** + * Implements {@link WorkerSource#reloadTile}. + * + * If the tile is loaded, uses the implementation in VectorTileWorkerSource. + * Otherwise, such as after a setData() call, we load the tile fresh. + * + * @param params - the parameters + * @returns A promise that resolves when the tile is reloaded + */ + reloadTile(params) { + const loaded = this.loaded, uid = params.uid; + if (loaded && loaded[uid]) { + return super.reloadTile(params); + } + else { + return this.loadTile(params); + } + } + /** + * Fetch, parse and process GeoJSON according to the given params. + * + * Defers to {@link GeoJSONWorkerSource#loadGeoJSON} for the fetching and parsing. + * + * @param params - the parameters + * @param abortController - the abort controller that allows aborting this operation + * @returns a promise that is resolved with the processes GeoJSON + */ + loadAndProcessGeoJSON(params, abortController) { + return __awaiter(this, void 0, void 0, function* () { + let data = yield this.loadGeoJSON(params, abortController); + delete this._pendingRequest; + if (typeof data !== 'object') { + throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`); + } + rewind$2(data, true); + if (params.filter) { + const compiled = createExpression(params.filter, { type: 'boolean', 'property-type': 'data-driven', overridable: false, transition: false }); + if (compiled.result === 'error') + throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', ')); + const features = data.features.filter(feature => compiled.value.evaluate({ zoom: 0 }, feature)); + data = { type: 'FeatureCollection', features }; + } + return data; + }); + } + /** + * Fetch and parse GeoJSON according to the given params. + * + * GeoJSON is loaded and parsed from `params.url` if it exists, or else + * expected as a literal (string or object) `params.data`. + * + * @param params - the parameters + * @param abortController - the abort controller that allows aborting this operation + * @returns a promise that resolves when the data is loaded + */ + loadGeoJSON(params, abortController) { + return __awaiter(this, void 0, void 0, function* () { + const { promoteId } = params; + if (params.request) { + const response = yield getJSON(params.request, abortController); + this._dataUpdateable = isUpdateableGeoJSON(response.data, promoteId) ? toUpdateable(response.data, promoteId) : undefined; + return response.data; + } + if (typeof params.data === 'string') { + try { + const parsed = JSON.parse(params.data); + this._dataUpdateable = isUpdateableGeoJSON(parsed, promoteId) ? toUpdateable(parsed, promoteId) : undefined; + return parsed; + } + catch (e) { + throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`); + } + } + if (!params.dataDiff) { + throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`); + } + if (!this._dataUpdateable) { + throw new Error(`Cannot update existing geojson data in ${params.source}`); + } + applySourceDiff(this._dataUpdateable, params.dataDiff, promoteId); + return { type: 'FeatureCollection', features: Array.from(this._dataUpdateable.values()) }; + }); + } + removeSource(_params) { + return __awaiter(this, void 0, void 0, function* () { + if (this._pendingRequest) { + this._pendingRequest.abort(); + } + }); + } + getClusterExpansionZoom(params) { + return this._geoJSONIndex.getClusterExpansionZoom(params.clusterId); + } + getClusterChildren(params) { + return this._geoJSONIndex.getChildren(params.clusterId); + } + getClusterLeaves(params) { + return this._geoJSONIndex.getLeaves(params.clusterId, params.limit, params.offset); + } +} +function getSuperclusterOptions({ superclusterOptions, clusterProperties }) { + if (!clusterProperties || !superclusterOptions) + return superclusterOptions; + const mapExpressions = {}; + const reduceExpressions = {}; + const globals = { accumulated: null, zoom: 0 }; + const feature = { properties: null }; + const propertyNames = Object.keys(clusterProperties); + for (const key of propertyNames) { + const [operator, mapExpression] = clusterProperties[key]; + const mapExpressionParsed = createExpression(mapExpression); + const reduceExpressionParsed = createExpression(typeof operator === 'string' ? [operator, ['accumulated'], ['get', key]] : operator); + mapExpressions[key] = mapExpressionParsed.value; + reduceExpressions[key] = reduceExpressionParsed.value; + } + superclusterOptions.map = (pointProperties) => { + feature.properties = pointProperties; + const properties = {}; + for (const key of propertyNames) { + properties[key] = mapExpressions[key].evaluate(globals, feature); + } + return properties; + }; + superclusterOptions.reduce = (accumulated, clusterProperties) => { + feature.properties = clusterProperties; + for (const key of propertyNames) { + globals.accumulated = accumulated[key]; + accumulated[key] = reduceExpressions[key].evaluate(globals, feature); + } + }; + return superclusterOptions; +} + +/** + * The Worker class responsible for background thread related execution + */ +class Worker { + constructor(self) { + this.self = self; + this.actor = new Actor(self); + this.layerIndexes = {}; + this.availableImages = {}; + this.workerSources = {}; + this.demWorkerSources = {}; + this.externalWorkerSourceTypes = {}; + this.self.registerWorkerSource = (name, WorkerSource) => { + if (this.externalWorkerSourceTypes[name]) { + throw new Error(`Worker source with name "${name}" already registered.`); + } + this.externalWorkerSourceTypes[name] = WorkerSource; + }; + this.self.addProtocol = addProtocol; + this.self.removeProtocol = removeProtocol; + // This is invoked by the RTL text plugin when the download via the `importScripts` call has finished, and the code has been parsed. + this.self.registerRTLTextPlugin = (rtlTextPlugin) => { + if (rtlWorkerPlugin.isParsed()) { + throw new Error('RTL text plugin already registered.'); + } + rtlWorkerPlugin.setMethods(rtlTextPlugin); + }; + this.actor.registerMessageHandler("LDT" /* MessageType.loadDEMTile */, (mapId, params) => { + return this._getDEMWorkerSource(mapId, params.source).loadTile(params); + }); + this.actor.registerMessageHandler("RDT" /* MessageType.removeDEMTile */, (mapId, params) => __awaiter(this, void 0, void 0, function* () { + this._getDEMWorkerSource(mapId, params.source).removeTile(params); + })); + this.actor.registerMessageHandler("GCEZ" /* MessageType.getClusterExpansionZoom */, (mapId, params) => __awaiter(this, void 0, void 0, function* () { + return this._getWorkerSource(mapId, params.type, params.source).getClusterExpansionZoom(params); + })); + this.actor.registerMessageHandler("GCC" /* MessageType.getClusterChildren */, (mapId, params) => __awaiter(this, void 0, void 0, function* () { + return this._getWorkerSource(mapId, params.type, params.source).getClusterChildren(params); + })); + this.actor.registerMessageHandler("GCL" /* MessageType.getClusterLeaves */, (mapId, params) => __awaiter(this, void 0, void 0, function* () { + return this._getWorkerSource(mapId, params.type, params.source).getClusterLeaves(params); + })); + this.actor.registerMessageHandler("LD" /* MessageType.loadData */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).loadData(params); + }); + this.actor.registerMessageHandler("GD" /* MessageType.getData */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).getData(); + }); + this.actor.registerMessageHandler("LT" /* MessageType.loadTile */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).loadTile(params); + }); + this.actor.registerMessageHandler("RT" /* MessageType.reloadTile */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).reloadTile(params); + }); + this.actor.registerMessageHandler("AT" /* MessageType.abortTile */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).abortTile(params); + }); + this.actor.registerMessageHandler("RMT" /* MessageType.removeTile */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).removeTile(params); + }); + this.actor.registerMessageHandler("RS" /* MessageType.removeSource */, (mapId, params) => __awaiter(this, void 0, void 0, function* () { + if (!this.workerSources[mapId] || + !this.workerSources[mapId][params.type] || + !this.workerSources[mapId][params.type][params.source]) { + return; + } + const worker = this.workerSources[mapId][params.type][params.source]; + delete this.workerSources[mapId][params.type][params.source]; + if (worker.removeSource !== undefined) { + worker.removeSource(params); + } + })); + this.actor.registerMessageHandler("RM" /* MessageType.removeMap */, (mapId) => __awaiter(this, void 0, void 0, function* () { + delete this.layerIndexes[mapId]; + delete this.availableImages[mapId]; + delete this.workerSources[mapId]; + delete this.demWorkerSources[mapId]; + })); + this.actor.registerMessageHandler("SR" /* MessageType.setReferrer */, (_mapId, params) => __awaiter(this, void 0, void 0, function* () { + this.referrer = params; + })); + this.actor.registerMessageHandler("SRPS" /* MessageType.syncRTLPluginState */, (mapId, params) => { + return this._syncRTLPluginState(mapId, params); + }); + this.actor.registerMessageHandler("IS" /* MessageType.importScript */, (_mapId, params) => __awaiter(this, void 0, void 0, function* () { + this.self.importScripts(params); + })); + this.actor.registerMessageHandler("SI" /* MessageType.setImages */, (mapId, params) => { + return this._setImages(mapId, params); + }); + this.actor.registerMessageHandler("UL" /* MessageType.updateLayers */, (mapId, params) => __awaiter(this, void 0, void 0, function* () { + this._getLayerIndex(mapId).update(params.layers, params.removedIds); + })); + this.actor.registerMessageHandler("SL" /* MessageType.setLayers */, (mapId, params) => __awaiter(this, void 0, void 0, function* () { + this._getLayerIndex(mapId).replace(params); + })); + } + _setImages(mapId, images) { + return __awaiter(this, void 0, void 0, function* () { + this.availableImages[mapId] = images; + for (const workerSource in this.workerSources[mapId]) { + const ws = this.workerSources[mapId][workerSource]; + for (const source in ws) { + ws[source].availableImages = images; + } + } + }); + } + _syncRTLPluginState(mapId, incomingState) { + return __awaiter(this, void 0, void 0, function* () { + // Parsed plugin cannot be changed, so just return its current state. + if (rtlWorkerPlugin.isParsed()) { + return rtlWorkerPlugin.getState(); + } + if (incomingState.pluginStatus !== 'loading') { + // simply sync and done + rtlWorkerPlugin.setState(incomingState); + return incomingState; + } + const urlToLoad = incomingState.pluginURL; + this.self.importScripts(urlToLoad); + const complete = rtlWorkerPlugin.isParsed(); + if (complete) { + const loadedState = { + pluginStatus: 'loaded', + pluginURL: urlToLoad + }; + rtlWorkerPlugin.setState(loadedState); + return loadedState; + } + // error case + rtlWorkerPlugin.setState({ + pluginStatus: 'error', + pluginURL: '' + }); + throw new Error(`RTL Text Plugin failed to import scripts from ${urlToLoad}`); + }); + } + _getAvailableImages(mapId) { + let availableImages = this.availableImages[mapId]; + if (!availableImages) { + availableImages = []; + } + return availableImages; + } + _getLayerIndex(mapId) { + let layerIndexes = this.layerIndexes[mapId]; + if (!layerIndexes) { + layerIndexes = this.layerIndexes[mapId] = new StyleLayerIndex(); + } + return layerIndexes; + } + /** + * This is basically a lazy initialization of a worker per mapId and sourceType and sourceName + * @param mapId - the mapId + * @param sourceType - the source type - 'vector' for example + * @param sourceName - the source name - 'osm' for example + * @returns a new instance or a cached one + */ + _getWorkerSource(mapId, sourceType, sourceName) { + if (!this.workerSources[mapId]) + this.workerSources[mapId] = {}; + if (!this.workerSources[mapId][sourceType]) + this.workerSources[mapId][sourceType] = {}; + if (!this.workerSources[mapId][sourceType][sourceName]) { + // use a wrapped actor so that we can attach a target mapId param + // to any messages invoked by the WorkerSource, this is very important when there are multiple maps + const actor = { + sendAsync: (message, abortController) => { + message.targetMapId = mapId; + return this.actor.sendAsync(message, abortController); + } + }; + switch (sourceType) { + case 'vector': + this.workerSources[mapId][sourceType][sourceName] = new VectorTileWorkerSource(actor, this._getLayerIndex(mapId), this._getAvailableImages(mapId)); + break; + case 'geojson': + this.workerSources[mapId][sourceType][sourceName] = new GeoJSONWorkerSource(actor, this._getLayerIndex(mapId), this._getAvailableImages(mapId)); + break; + default: + this.workerSources[mapId][sourceType][sourceName] = new (this.externalWorkerSourceTypes[sourceType])(actor, this._getLayerIndex(mapId), this._getAvailableImages(mapId)); + break; + } + } + return this.workerSources[mapId][sourceType][sourceName]; + } + /** + * This is basically a lazy initialization of a worker per mapId and source + * @param mapId - the mapId + * @param sourceType - the source type - 'raster-dem' for example + * @returns a new instance or a cached one + */ + _getDEMWorkerSource(mapId, sourceType) { + if (!this.demWorkerSources[mapId]) + this.demWorkerSources[mapId] = {}; + if (!this.demWorkerSources[mapId][sourceType]) { + this.demWorkerSources[mapId][sourceType] = new RasterDEMTileWorkerSource(); + } + return this.demWorkerSources[mapId][sourceType]; + } +} +if (isWorker(self)) { + self.worker = new Worker(self); +} + +return Worker; + +})(); +//# sourceMappingURL=maplibre-gl-csp-worker-dev.js.map diff --git a/dist/maplibre-gl-csp-worker.js b/dist/maplibre-gl-csp-worker.js new file mode 100644 index 0000000000..78e2ae5e61 --- /dev/null +++ b/dist/maplibre-gl-csp-worker.js @@ -0,0 +1,6 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v4.7.0/LICENSE.txt + */ +var maplibregl=function(){"use strict";function t(t,e,r,n){return new(r||(r=Promise))((function(i,s){function o(t){try{l(n.next(t))}catch(t){s(t)}}function a(t){try{l(n.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(o,a)}l((n=n.apply(t,e||[])).next())}))}function e(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}"function"==typeof SuppressedError&&SuppressedError;var r=n;function n(t,e){this.x=t,this.y=e}n.prototype={clone:function(){return new n(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},n.convert=function(t){return t instanceof n?t:Array.isArray(t)?new n(t[0],t[1]):t};var i=e(r),s=o;function o(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n}let a,l;function u(t,e,r){return Math.min(r,Math.max(e,t))}function c(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}function h(t,e,r){const n={};for(const r in t)n[r]=e.call(this,t[r],r,t);return n}function p(t){return Array.isArray(t)?t.map(p):"object"==typeof t&&t?h(t,p):t}o.prototype={sampleCurveX:function(t){return((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return(3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?o=r:a=r,r=.5*(a-o)+o;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},new(e(s))(.25,.1,.25,1);const f={};function d(t){f[t]||("undefined"!=typeof console&&console.warn(t),f[t]=!0)}function y(t,e,r){return(r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function m(t){return"undefined"!=typeof WorkerGlobalScope&&void 0!==t&&t instanceof WorkerGlobalScope}function g(t){return"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}let x,v;class b{constructor(t,e,r){const n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(let t=0;t=u[l+0]&&n>=u[l+1])?(o[h]=!0,s.push(i[h])):o[h]=!1}}}}_forEachCell(t,e,r,n,i,s,o,a){const l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(r),h=this._convertToCellCoord(n);for(let p=l;p<=c;p++)for(let l=u;l<=h;l++){const u=this.d*l+p;if((!a||a(this._convertFromCellCoord(p),this._convertFromCellCoord(l),this._convertFromCellCoord(p+1),this._convertFromCellCoord(l+1)))&&i.call(this,t,e,r,n,u,s,o,a))return}}_convertFromCellCoord(t){return(t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let r=0;for(let t=0;t":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"enum",default:"mercator",values:{mercator:{},globe:{}}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const _=["type","source","source-layer","minzoom","maxzoom","filter","layout"];class S{constructor(t,e,r,n){this.message=(t?`${t}: `:"")+r,n&&(this.identifier=n),null!=e&&e.__line__&&(this.line=e.__line__)}}function k(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}class A extends Error{constructor(t,e){super(e),this.message=e,this.key=t}}class I{constructor(t,e=[]){this.parent=t,this.bindings={};for(const[t,r]of e)this.bindings[t]=r}concat(t){return new I(this,t)}get(t){if(this.bindings[t])return this.bindings[t];if(this.parent)return this.parent.get(t);throw new Error(`${t} not found in scope.`)}has(t){return!!this.bindings[t]||!!this.parent&&this.parent.has(t)}}const M={kind:"null"},z={kind:"number"},P={kind:"string"},C={kind:"boolean"},B={kind:"color"},V={kind:"object"},T={kind:"value"},E={kind:"collator"},F={kind:"formatted"},D={kind:"padding"},$={kind:"resolvedImage"},L={kind:"variableAnchorOffsetCollection"};function O(t,e){return{kind:"array",itemType:t,N:e}}function R(t){if("array"===t.kind){const e=R(t.itemType);return"number"==typeof t.N?`array<${e}, ${t.N}>`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const j=[M,z,P,C,B,F,V,O(T),D,$,L];function q(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!q(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else{if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of j)if(!q(t,e))return null}return`Expected ${R(t)} but found ${R(e)} instead.`}function U(t,e){return e.some((e=>e.kind===t.kind))}function N(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function Z(t,e){return"array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const G=.96422,X=.82521,H=4/29,Y=6/29,J=3*Y*Y,K=Y*Y*Y,W=Math.PI/180,Q=180/Math.PI;function tt(t){return(t%=360)<0&&(t+=360),t}function et([t,e,r,n]){let i,s;const o=nt((.2225045*(t=rt(t))+.7168786*(e=rt(e))+.0606169*(r=rt(r)))/1);t===e&&e===r?i=s=o:(i=nt((.4360747*t+.3850649*e+.1430804*r)/G),s=nt((.0139322*t+.0971045*e+.7141733*r)/X));const a=116*o-16;return[a<0?0:a,500*(i-o),200*(o-s),n]}function rt(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function nt(t){return t>K?Math.pow(t,1/3):t/J+H}function it([t,e,r,n]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,o=isNaN(r)?i:i-r/200;return i=1*ot(i),s=G*ot(s),o=X*ot(o),[st(3.1338561*s-1.6168667*i-.4906146*o),st(-.9787684*s+1.9161415*i+.033454*o),st(.0719453*s-.2289914*i+1.4052427*o),n]}function st(t){return(t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function ot(t){return t>Y?t*t*t:J*(t-H)}function at(t){return parseInt(t.padEnd(2,t),16)/255}function lt(t,e){return ut(e?t/100:t,0,1)}function ut(t,e,r){return Math.min(Math.max(e,t),r)}function ct(t){return!t.some(Number.isNaN)}const ht={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};class pt{constructor(t,e,r,n=1,i=!0){this.r=t,this.g=e,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[t,e,r,n]))}static parse(t){if(t instanceof pt)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return[0,0,0,0];const e=ht[t];if(e){const[t,r,n]=e;return[t/255,r/255,n/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let r=1;return[at(t.slice(r,r+=e)),at(t.slice(r,r+=e)),at(t.slice(r,r+=e)),at(t.slice(r,r+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,r,n,i,s,o,a,l,u,c,h,p]=e,f=[i||" ",a||" ",c].join("");if(" "===f||" /"===f||",,"===f||",,,"===f){const t=[n,o,u].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[ut(+r/e,0,1),ut(+s/e,0,1),ut(+l/e,0,1),h?lt(+h,p):1];if(ct(t))return t}}return}}const r=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[t,e,n,i,s,o,a,l,u]=r,c=[n||" ",s||" ",a].join("");if(" "===c||" /"===c||",,"===c||",,,"===c){const t=[+e,ut(+i,0,100),ut(+o,0,100),l?lt(+l,u):1];if(ct(t))return function([t,e,r,n]){function i(n){const i=(n+t/30)%12,s=e*Math.min(r,1-r);return r-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=tt(t),e/=100,r/=100,[i(0),i(8),i(4),n]}(t)}}}(t);return e?new pt(...e,!1):void 0}get rgb(){const{r:t,g:e,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[t/i,e/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,r,n,i]=et(t),s=Math.sqrt(r*r+n*n);return[Math.round(1e4*s)?tt(Math.atan2(n,r)*Q):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",et(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,r,n]=this.rgb;return`rgba(${[t,e,r].map((t=>Math.round(255*t))).join(",")},${n})`}}pt.black=new pt(0,0,0,1),pt.white=new pt(1,1,1,1),pt.transparent=new pt(0,0,0,0),pt.red=new pt(1,0,0,1);class ft{constructor(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class dt{constructor(t,e,r,n,i){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i}}class yt{constructor(t){this.sections=t}static fromString(t){return new yt([new dt(t,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof yt?t:yt.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class mt{constructor(t){this.values=t.slice()}static parse(t){if(t instanceof mt)return t;if("number"==typeof t)return new mt([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]]}return new mt(t)}}toString(){return JSON.stringify(this.values)}}const gt=new Set(["center","left","right","top","bottom","top-left","top-right","bottom-left","bottom-right"]);class xt{constructor(t){this.values=t.slice()}static parse(t){if(t instanceof xt)return t;if(Array.isArray(t)&&!(t.length<1)&&t.length%2==0){for(let e=0;e=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[t,e,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function wt(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof pt||t instanceof ft||t instanceof yt||t instanceof mt||t instanceof xt||t instanceof vt)return!0;if(Array.isArray(t)){for(const e of t)if(!wt(e))return!1;return!0}if("object"==typeof t){for(const e in t)if(!wt(t[e]))return!1;return!0}return!1}function _t(t){if(null===t)return M;if("string"==typeof t)return P;if("boolean"==typeof t)return C;if("number"==typeof t)return z;if(t instanceof pt)return B;if(t instanceof ft)return E;if(t instanceof yt)return F;if(t instanceof mt)return D;if(t instanceof xt)return L;if(t instanceof vt)return $;if(Array.isArray(t)){const e=t.length;let r;for(const e of t){const t=_t(e);if(r){if(r===t)continue;r=T;break}r=t}return O(r||T,e)}return V}function St(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof pt||t instanceof yt||t instanceof mt||t instanceof xt||t instanceof vt?t.toString():JSON.stringify(t)}class kt{constructor(t,e){this.type=t,this.value=e}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!wt(t[1]))return e.error("invalid value");const r=t[1];let n=_t(r);const i=e.expectedType;return"array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new kt(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}}class At{constructor(t){this.name="ExpressionEvaluationError",this.message=t}toJSON(){return this.message}}const It={string:P,number:z,boolean:C,object:V};class Mt{constructor(t,e){this.type=t,this.args=e}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r,n=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const r=t[1];if("string"!=typeof r||!(r in It)||"object"===r)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=It[r],n++}else i=T;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],n++}r=O(i,s)}else{if(!It[i])throw new Error(`Types doesn't contain name = ${i}`);r=It[i]}const s=[];for(;nt.outputDefined()))}}const zt={"to-boolean":C,"to-color":B,"to-number":z,"to-string":P};class Pt{constructor(t,e){this.type=t,this.args=e}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[0];if(!zt[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");const n=zt[r],i=[];for(let r=1;r4?`Invalid rbga value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:bt(e[0],e[1],e[2],e[3]),!r))return new pt(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new At(r||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"padding":{let e;for(const r of this.args){e=r.evaluate(t);const n=mt.parse(e);if(n)return n}throw new At(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"variableAnchorOffsetCollection":{let e;for(const r of this.args){e=r.evaluate(t);const n=xt.parse(e);if(n)return n}throw new At(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"number":{let e=null;for(const r of this.args){if(e=r.evaluate(t),null===e)return 0;const n=Number(e);if(!isNaN(n))return n}throw new At(`Could not convert ${JSON.stringify(e)} to number.`)}case"formatted":return yt.fromString(St(this.args[0].evaluate(t)));case"resolvedImage":return vt.fromString(St(this.args[0].evaluate(t)));default:return St(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t)}outputDefined(){return this.args.every((t=>t.outputDefined()))}}const Ct=["Unknown","Point","LineString","Polygon"];class Bt{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?Ct[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache[t];return e||(e=this._parseColorCache[t]=pt.parse(t)),e}}class Vt{constructor(t,e,r=[],n,i=new I,s=[]){this.registry=t,this.path=r,this.key=r.map((t=>`[${t}]`)).join(""),this.scope=i,this.errors=s,this.expectedType=n,this._isConstant=e}parse(t,e,r,n,i={}){return e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)}_parse(t,e){function r(t,e,r){return"assert"===r?new Mt(e,[t]):"coerce"===r?new Pt(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const n=t[0];if("string"!=typeof n)return this.error(`Expression name must be a string, but found ${typeof n} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[n];if(i){let n=i.parse(t,this);if(!n)return null;if(this.expectedType){const t=this.expectedType,i=n.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind)if("color"!==t.kind&&"formatted"!==t.kind&&"resolvedImage"!==t.kind||"value"!==i.kind&&"string"!==i.kind)if("padding"!==t.kind||"value"!==i.kind&&"number"!==i.kind&&"array"!==i.kind)if("variableAnchorOffsetCollection"!==t.kind||"value"!==i.kind&&"array"!==i.kind){if(this.checkSubtype(t,i))return null}else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"assert")}if(!(n instanceof kt)&&"resolvedImage"!==n.type.kind&&this._isConstant(n)){const t=new Bt;try{n=new kt(n.type,n.evaluate(t))}catch(t){return this.error(t.message),null}}return n}return this.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,r){const n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Vt(this.registry,this._isConstant,n,e||null,i,this.errors)}error(t,...e){const r=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new A(r,t))}checkSubtype(t,e){const r=q(t,e);return r&&this.error(r),r}}class Tt{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result)}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const r=[];for(let n=1;n=r.length)throw new At(`Array index out of bounds: ${e} > ${r.length-1}.`);if(e!==Math.floor(e))throw new At(`Array index must be an integer, but found ${e} instead.`);return r[e]}eachChild(t){t(this.index),t(this.input)}outputDefined(){return!1}}class Dt{constructor(t,e){this.type=C,this.needle=t,this.haystack=e}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,T),n=e.parse(t[2],2,T);return r&&n?U(r.type,[C,P,z,M,T])?new Dt(r,n):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${R(r.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return!1;if(!N(e,["boolean","string","number","null"]))throw new At(`Expected first argument to be of type boolean, string, number or null, but found ${R(_t(e))} instead.`);if(!N(r,["string","array"]))throw new At(`Expected second argument to be of type array or string, but found ${R(_t(r))} instead.`);return r.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack)}outputDefined(){return!0}}class $t{constructor(t,e,r){this.type=z,this.needle=t,this.haystack=e,this.fromIndex=r}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,T),n=e.parse(t[2],2,T);if(!r||!n)return null;if(!U(r.type,[C,P,z,M,T]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${R(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,z);return i?new $t(r,n,i):null}return new $t(r,n)}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!N(e,["boolean","string","number","null"]))throw new At(`Expected first argument to be of type boolean, string, number or null, but found ${R(_t(e))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(t)),N(r,["string"])){const t=r.indexOf(e,n);return-1===t?-1:[...r.slice(0,t)].length}if(N(r,["array"]))return r.indexOf(e,n);throw new At(`Expected second argument to be of type array or string, but found ${R(_t(r))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex)}outputDefined(){return!1}}class Lt{constructor(t,e,r,n,i,s){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=s}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const i={},s=[];for(let o=2;oNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return u.error("Numeric branch labels must be integer values.");if(r){if(u.checkSubtype(r,_t(t)))return null}else r=_t(t);if(void 0!==i[String(t)])return u.error("Branch labels must be unique.");i[String(t)]=s.length}const c=e.parse(l,o,n);if(!c)return null;n=n||c.type,s.push(c)}const o=e.parse(t[1],1,T);if(!o)return null;const a=e.parse(t[t.length-1],t.length-1,n);return a?"value"!==o.type.kind&&e.concat(1).checkSubtype(r,o.type)?null:new Lt(r,n,o,i,s,a):null}evaluate(t){const e=this.input.evaluate(t);return(_t(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise)}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class Ot{constructor(t,e,r){this.type=t,this.branches=e,this.otherwise=r}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const n=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}}class Rt{constructor(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,T),n=e.parse(t[2],2,z);if(!r||!n)return null;if(!U(r.type,[O(T),P,T]))return e.error(`Expected first argument to be of type array or string, but found ${R(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,z);return i?new Rt(r.type,r,n,i):null}return new Rt(r.type,r,n)}evaluate(t){const e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);let n;if(this.endIndex&&(n=this.endIndex.evaluate(t)),N(e,["string"]))return[...e].slice(r,n).join("");if(N(e,["array"]))return e.slice(r,n);throw new At(`Expected first argument to be of type array or string, but found ${R(_t(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex)}outputDefined(){return!1}}function jt(t,e){const r=t.length-1;let n,i,s=0,o=r,a=0;for(;s<=o;)if(a=Math.floor((s+o)/2),n=t[a],i=t[a+1],n<=e){if(a===r||ee))throw new At("Input is not a number.");o=a-1}return 0}class qt{constructor(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of r)this.labels.push(t),this.outputs.push(e)}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const r=e.parse(t[1],1,z);if(!r)return null;const n=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let r=1;r=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',a);const u=e.parse(o,l,i);if(!u)return null;i=i||u.type,n.push([s,u])}return new qt(i,r,n)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[jt(e,n)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e)}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function Ut(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Nt=Zt;function Zt(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n}Zt.prototype={sampleCurveX:function(t){return((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return(3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?o=r:a=r,r=.5*(a-o)+o;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}};var Gt=Ut(Nt);function Xt(t,e,r){return t+r*(e-t)}function Ht(t,e,r){return t.map(((t,n)=>Xt(t,e[n],r)))}const Yt={number:Xt,color:function(t,e,r,n="rgb"){switch(n){case"rgb":{const[n,i,s,o]=Ht(t.rgb,e.rgb,r);return new pt(n,i,s,o,!1)}case"hcl":{const[n,i,s,o]=t.hcl,[a,l,u,c]=e.hcl;let h,p;if(isNaN(n)||isNaN(a))isNaN(n)?isNaN(a)?h=NaN:(h=a,1!==s&&0!==s||(p=l)):(h=n,1!==u&&0!==u||(p=i));else{let t=a-n;a>n&&t>180?t-=360:a180&&(t+=360),h=n+r*t}const[f,d,y,m]=function([t,e,r,n]){return t=isNaN(t)?0:t*W,it([r,Math.cos(t)*e,Math.sin(t)*e,n])}([h,null!=p?p:Xt(i,l,r),Xt(s,u,r),Xt(o,c,r)]);return new pt(f,d,y,m,!1)}case"lab":{const[n,i,s,o]=it(Ht(t.lab,e.lab,r));return new pt(n,i,s,o,!1)}}},array:Ht,padding:function(t,e,r){return new mt(Ht(t.values,e.values,r))},variableAnchorOffsetCollection:function(t,e,r){const n=t.values,i=e.values;if(n.length!==i.length)throw new At(`Cannot interpolate values of different length. from: ${t.toString()}, to: ${e.toString()}`);const s=[];for(let t=0;t"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:t}}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,z),!i)return null;const o=[];let a=null;"interpolate-hcl"===r||"interpolate-lab"===r?a=B:e.expectedType&&"value"!==e.expectedType.kind&&(a=e.expectedType);for(let t=0;t=r)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(n,l,a);if(!u)return null;a=a||u.type,o.push([r,u])}return Z(a,z)||Z(a,B)||Z(a,D)||Z(a,L)||Z(a,O(z))?new Jt(a,r,n,i,o):e.error(`Type ${R(a)} is not interpolatable.`)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);const s=jt(e,n),o=Jt.interpolationFactor(this.interpolation,n,e[s],e[s+1]),a=r[s].evaluate(t),l=r[s+1].evaluate(t);switch(this.operator){case"interpolate":return Yt[this.type.kind](a,l,o);case"interpolate-hcl":return Yt.color(a,l,o,"hcl");case"interpolate-lab":return Yt.color(a,l,o,"lab")}}eachChild(t){t(this.input);for(const e of this.outputs)t(e)}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function Kt(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}class Wt{constructor(t,e){this.type=t,this.args=e}static parse(t,e){if(t.length<2)return e.error("Expectected at least one argument.");let r=null;const n=e.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const n of t.slice(1)){const t=e.parse(n,1+i.length,r,void 0,{typeAnnotation:"omit"});if(!t)return null;r=r||t.type,i.push(t)}if(!r)throw new Error("No output type");const s=n&&i.some((t=>q(n,t.type)));return new Wt(s?T:r,i)}evaluate(t){let e,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(t),r&&r instanceof vt&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null!==r)break;return r}eachChild(t){this.args.forEach(t)}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function Qt(t,e){return"=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function te(t,e,r,n){return 0===n.compare(e,r)}function ee(t,e,r){const n="=="!==t&&"!="!==t;return class i{constructor(t,e,r){this.type=C,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const r=t[0];let s=e.parse(t[1],1,T);if(!s)return null;if(!Qt(r,s.type))return e.concat(1).error(`"${r}" comparisons are not supported for type '${R(s.type)}'.`);let o=e.parse(t[2],2,T);if(!o)return null;if(!Qt(r,o.type))return e.concat(2).error(`"${r}" comparisons are not supported for type '${R(o.type)}'.`);if(s.type.kind!==o.type.kind&&"value"!==s.type.kind&&"value"!==o.type.kind)return e.error(`Cannot compare types '${R(s.type)}' and '${R(o.type)}'.`);n&&("value"===s.type.kind&&"value"!==o.type.kind?s=new Mt(o.type,[s]):"value"!==s.type.kind&&"value"===o.type.kind&&(o=new Mt(s.type,[o])));let a=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==o.type.kind&&"value"!==s.type.kind&&"value"!==o.type.kind)return e.error("Cannot use collator to compare non-string types.");if(a=e.parse(t[3],3,E),!a)return null}return new i(s,o,a)}evaluate(i){const s=this.lhs.evaluate(i),o=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const e=_t(s),r=_t(o);if(e.kind!==r.kind||"string"!==e.kind&&"number"!==e.kind)throw new At(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const t=_t(s),r=_t(o);if("string"!==t.kind||"string"!==r.kind)return e(i,s,o)}return this.collator?r(i,s,o,this.collator.evaluate(i)):e(i,s,o)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator)}outputDefined(){return!0}}}const re=ee("==",(function(t,e,r){return e===r}),te),ne=ee("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return!te(0,e,r,n)})),ie=ee("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),oe=ee("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),ae=ee(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0}));class le{constructor(t,e,r){this.type=E,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");const n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,C);if(!n)return null;const i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,C);if(!i)return null;let s=null;return r.locale&&(s=e.parse(r.locale,1,P),!s)?null:new le(n,i,s)}evaluate(t){return new ft(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale)}outputDefined(){return!1}}class ue{constructor(t,e,r,n,i){this.type=P,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,z);if(!r)return null;const n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=e.parse(n.locale,1,P),!i))return null;let s=null;if(n.currency&&(s=e.parse(n.currency,1,P),!s))return null;let o=null;if(n["min-fraction-digits"]&&(o=e.parse(n["min-fraction-digits"],1,z),!o))return null;let a=null;return n["max-fraction-digits"]&&(a=e.parse(n["max-fraction-digits"],1,z),!a)?null:new ue(r,i,s,o,a)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits)}outputDefined(){return!1}}class ce{constructor(t){this.type=F,this.sections=t}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");const n=[];let i=!1;for(let r=1;r<=t.length-1;++r){const s=t[r];if(i&&"object"==typeof s&&!Array.isArray(s)){i=!1;let t=null;if(s["font-scale"]&&(t=e.parse(s["font-scale"],1,z),!t))return null;let r=null;if(s["text-font"]&&(r=e.parse(s["text-font"],1,O(P)),!r))return null;let o=null;if(s["text-color"]&&(o=e.parse(s["text-color"],1,B),!o))return null;const a=n[n.length-1];a.scale=t,a.font=r,a.textColor=o}else{const s=e.parse(t[r],1,T);if(!s)return null;const o=s.type.kind;if("string"!==o&&"value"!==o&&"null"!==o&&"resolvedImage"!==o)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:s,scale:null,font:null,textColor:null})}}return new ce(n)}evaluate(t){return new yt(this.sections.map((e=>{const r=e.content.evaluate(t);return _t(r)===$?new dt("",r,null,null,null):new dt(St(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor)}outputDefined(){return!1}}class he{constructor(t){this.type=$,this.input=t}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,P);return r?new he(r):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),r=vt.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r}eachChild(t){t(this.input)}outputDefined(){return!1}}class pe{constructor(t){this.type=z,this.input=t}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error(`Expected argument of type string or array, but found ${R(r.type)} instead.`):new pe(r):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return[...e].length;if(Array.isArray(e))return e.length;throw new At(`Expected value to be of type string or array, but found ${R(_t(e))} instead.`)}eachChild(t){t(this.input)}outputDefined(){return!1}}const fe=8192;function de(t,e){const r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return[Math.round(r*i*fe),Math.round(n*i*fe)]}function ye(t,e){const r=Math.pow(2,e.z);return[(i=(t[0]/fe+e.x)/r,360*i-180),(n=(t[1]/fe+e.y)/r,360/Math.PI*Math.atan(Math.exp((180-360*n)*Math.PI/180))-90)];var n,i}function me(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1])}function ge(t,e){return!(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function xe(t,e,r){const n=t[0]-e[0],i=t[1]-e[1],s=t[0]-r[0],o=t[1]-r[1];return n*o-s*i==0&&n*s<=0&&i*o<=0}function ve(t,e,r,n){return 0!=(i=[n[0]-r[0],n[1]-r[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!Ae(t,e,r,n)||!Ae(r,n,t,e));var i,s}function be(t,e,r){for(const n of r)for(let r=0;r(i=t)[1]!=(o=a[e+1])[1]>i[1]&&i[0]<(o[0]-s[0])*(i[1]-s[1])/(o[1]-s[1])+s[0]&&(n=!n)}var i,s,o;return n}function _e(t,e){for(const r of e)if(we(t,r))return!0;return!1}function Se(t,e){for(const r of t)if(!we(r,e))return!1;for(let r=0;r0&&a<0||o<0&&a>0}function Ie(t,e,r){const n=[];for(let i=0;ir[2]){const e=.5*n;let i=t[0]-r[0]>e?-n:r[0]-t[0]>e?n:0;0===i&&(i=t[0]-r[2]>e?-n:r[2]-t[0]>e?n:0),t[0]+=i}me(e,t)}function Pe(t,e,r,n){const i=Math.pow(2,n.z)*fe,s=[n.x*fe,n.y*fe],o=[];for(const n of t)for(const t of n){const n=[t.x+s[0],t.y+s[1]];ze(n,e,r,i),o.push(n)}return o}function Ce(t,e,r,n){const i=Math.pow(2,n.z)*fe,s=[n.x*fe,n.y*fe],o=[];for(const r of t){const t=[];for(const n of r){const r=[n.x+s[0],n.y+s[1]];me(e,r),t.push(r)}o.push(t)}if(e[2]-e[0]<=i/2){(a=e)[0]=a[1]=1/0,a[2]=a[3]=-1/0;for(const t of o)for(const n of t)ze(n,e,r,i)}var a;return o}class Be{constructor(t,e){this.type=C,this.geojson=t,this.geometries=e}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(wt(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const r of e.features){const{type:e,coordinates:n}=r.geometry;"Polygon"===e&&t.push(n),"MultiPolygon"===e&&t.push(...n)}if(t.length)return new Be(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new Be(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new Be(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Ie(e.coordinates,n,i),o=Pe(t.geometry(),r,n,i);if(!ge(r,n))return!1;for(const t of o)if(!we(t,s))return!1}if("MultiPolygon"===e.type){const s=Me(e.coordinates,n,i),o=Pe(t.geometry(),r,n,i);if(!ge(r,n))return!1;for(const t of o)if(!_e(t,s))return!1}return!0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=Ie(e.coordinates,n,i),o=Ce(t.geometry(),r,n,i);if(!ge(r,n))return!1;for(const t of o)if(!Se(t,s))return!1}if("MultiPolygon"===e.type){const s=Me(e.coordinates,n,i),o=Ce(t.geometry(),r,n,i);if(!ge(r,n))return!1;for(const t of o)if(!ke(t,s))return!1}return!0}(t,this.geometries)}return!1}eachChild(){}outputDefined(){return!0}}let Ve=class{constructor(t=[],e=((t,e)=>te?1:0)){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t)}push(t){this.data.push(t),this._up(this.length++)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return--this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i}e[t]=n}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n}e[t]=i}};function Te(t,e,r,n,i){Ee(t,e,r,n||t.length-1,i||De)}function Ee(t,e,r,n,i){for(;n>r;){if(n-r>600){var s=n-r+1,o=e-r+1,a=Math.log(s),l=.5*Math.exp(2*a/3),u=.5*Math.sqrt(a*l*(s-l)/s)*(o-s/2<0?-1:1);Ee(t,e,Math.max(r,Math.floor(e-o*l/s+u)),Math.min(n,Math.floor(e+(s-o)*l/s+u)),i)}var c=t[e],h=r,p=n;for(Fe(t,r,e),i(t[n],c)>0&&Fe(t,r,n);h0;)p--}0===i(t[r],c)?Fe(t,r,p):Fe(t,++p,n),p<=e&&(r=p+1),e<=p&&(n=p-1)}}function Fe(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function De(t,e){return te?1:0}function $e(t,e){if(t.length<=1)return[t];const r=[];let n,i;for(const e of t){const t=Oe(e);0!==t&&(e.area=Math.abs(t),void 0===i&&(i=t<0),i===t<0?(n&&r.push(n),n=[e]):n.push(e))}if(n&&r.push(n),e>1)for(let t=0;t1?(l=t[a+1][0],u=t[a+1][1]):p>0&&(l+=c/this.kx*p,u+=h/this.ky*p)),c=this.wrap(e[0]-l)*this.kx,h=(e[1]-u)*this.ky;const f=c*c+h*h;f180;)t-=360;return t}}function Ne(t,e){return e[0]-t[0]}function Ze(t){return t[1]-t[0]+1}function Ge(t,e){return t[1]>=t[0]&&t[1]t[1])return[null,null];const r=Ze(t);if(e){if(2===r)return[t,null];const e=Math.floor(r/2);return[[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===r)return[t,null];const n=Math.floor(r/2)-1;return[[t[0],t[0]+n],[t[0]+n+1,t[1]]]}function He(t,e){if(!Ge(e,t.length))return[1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=e[0];n<=e[1];++n)me(r,t[n]);return r}function Ye(t){const e=[1/0,1/0,-1/0,-1/0];for(const r of t)for(const t of r)me(e,t);return e}function Je(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function Ke(t,e,r){if(!Je(t)||!Je(e))return NaN;let n=0,i=0;return t[2]e[2]&&(n=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=n)return n;if(ge(i,s)){if(ir(t,e))return 0}else if(ir(e,t))return 0;let o=1/0;for(const n of t)for(let t=0,i=n.length,s=i-1;t0;){const i=o.pop();if(i[0]>=s)continue;const l=i[1],u=e?50:100;if(Ze(l)<=u){if(!Ge(l,t.length))return NaN;if(e){const e=nr(t,l,r,n);if(isNaN(e)||0===e)return e;s=Math.min(s,e)}else for(let e=l[0];e<=l[1];++e){const i=rr(t[e],r,n);if(s=Math.min(s,i),0===s)return 0}}else{const r=Xe(l,e);or(o,s,n,t,a,r[0]),or(o,s,n,t,a,r[1])}}return s}function ur(t,e,r,n,i,s=1/0){let o=Math.min(s,i.distance(t[0],r[0]));if(0===o)return o;const a=new Ve([[0,[0,t.length-1],[0,r.length-1]]],Ne);for(;a.length>0;){const s=a.pop();if(s[0]>=o)continue;const l=s[1],u=s[2],c=e?50:100,h=n?50:100;if(Ze(l)<=c&&Ze(u)<=h){if(!Ge(l,t.length)&&Ge(u,r.length))return NaN;let s;if(e&&n)s=tr(t,l,r,u,i),o=Math.min(o,s);else if(e&&!n){const e=t.slice(l[0],l[1]+1);for(let t=u[0];t<=u[1];++t)if(s=We(r[t],e,i),o=Math.min(o,s),0===o)return o}else if(!e&&n){const e=r.slice(u[0],u[1]+1);for(let r=l[0];r<=l[1];++r)if(s=We(t[r],e,i),o=Math.min(o,s),0===o)return o}else s=er(t,l,r,u,i),o=Math.min(o,s)}else{const s=Xe(l,e),c=Xe(u,n);ar(a,o,i,t,r,s[0],c[0]),ar(a,o,i,t,r,s[0],c[1]),ar(a,o,i,t,r,s[1],c[0]),ar(a,o,i,t,r,s[1],c[1])}}return o}function cr(t){return"MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class hr{constructor(t,e){this.type=z,this.geojson=t,this.geometries=e}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(wt(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new hr(e,e.features.map((t=>cr(t.geometry))).flat());if("Feature"===e.type)return new hr(e,cr(e.geometry));if("type"in e&&"coordinates"in e)return new hr(e,cr(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>ye([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new Ue(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case"Point":s=Math.min(s,ur(n,!1,[t.coordinates],!1,i,s));break;case"LineString":s=Math.min(s,ur(n,!1,t.coordinates,!0,i,s));break;case"Polygon":s=Math.min(s,lr(n,!1,t.coordinates,i,s))}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>ye([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new Ue(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case"Point":s=Math.min(s,ur(n,!0,[t.coordinates],!1,i,s));break;case"LineString":s=Math.min(s,ur(n,!0,t.coordinates,!0,i,s));break;case"Polygon":s=Math.min(s,lr(n,!0,t.coordinates,i,s))}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const r=t.geometry();if(0===r.length||0===r[0].length)return NaN;const n=$e(r,0).map((e=>e.map((e=>e.map((e=>ye([e.x,e.y],t.canonical))))))),i=new Ue(n[0][0][0][1]);let s=1/0;for(const t of e)for(const e of n){switch(t.type){case"Point":s=Math.min(s,lr([t.coordinates],!1,e,i,s));break;case"LineString":s=Math.min(s,lr(t.coordinates,!0,e,i,s));break;case"Polygon":s=Math.min(s,sr(e,t.coordinates,i,s))}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return!0}}const pr={"==":re,"!=":ne,">":se,"<":ie,">=":ae,"<=":oe,array:Mt,at:Ft,boolean:Mt,case:Ot,coalesce:Wt,collator:le,format:ce,image:he,in:Dt,"index-of":$t,interpolate:Jt,"interpolate-hcl":Jt,"interpolate-lab":Jt,length:pe,let:Tt,literal:kt,match:Lt,number:Mt,"number-format":ue,object:Mt,slice:Rt,step:qt,string:Mt,"to-boolean":Pt,"to-color":Pt,"to-number":Pt,"to-string":Pt,var:Et,within:Be,distance:hr};class fr{constructor(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t)}outputDefined(){return!1}static parse(t,e){const r=t[0],n=fr.definitions[r];if(!n)return e.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,s=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,o=s.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let a=null;for(const[n,s]of o){a=new Vt(e.registry,xr,e.path,null,e.scope);const o=[];let l=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(R).join(", ")})`:`(${R(e.type)}...)`;var e})).join(" | "),n=[];for(let r=1;r{r=e?r&&xr(t):r&&t instanceof kt})),!!r&&vr(t)&&wr(t,["zoom","heatmap-density","line-progress","accumulated","is-supported-script"])}function vr(t){if(t instanceof fr){if("get"===t.name&&1===t.args.length)return!1;if("feature-state"===t.name)return!1;if("has"===t.name&&1===t.args.length)return!1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return!1;if(/^filter-/.test(t.name))return!1}if(t instanceof Be)return!1;if(t instanceof hr)return!1;let e=!0;return t.eachChild((t=>{e&&!vr(t)&&(e=!1)})),e}function br(t){if(t instanceof fr&&"feature-state"===t.name)return!1;let e=!0;return t.eachChild((t=>{e&&!br(t)&&(e=!1)})),e}function wr(t,e){if(t instanceof fr&&e.indexOf(t.name)>=0)return!1;let r=!0;return t.eachChild((t=>{r&&!wr(t,e)&&(r=!1)})),r}function _r(t){return{result:"success",value:t}}function Sr(t){return{result:"error",value:t}}function kr(t){return"data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Ar(t){return!!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function Ir(t){return!!t.expression&&t.expression.interpolated}function Mr(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function zr(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function Pr(t){return t}function Cr(t,e){const r="color"===e.type,n=t.stops&&"object"==typeof t.stops[0][0],i=n||!(n||void 0!==t.property),s=t.type||(Ir(e)?"exponential":"interval");if(r||"padding"===e.type){const n=r?pt.parse:mt.parse;(t=k({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],n(t[1])]))),t.default=n(t.default?t.default:e.default)}if(t.colorSpace&&"rgb"!==(o=t.colorSpace)&&"hcl"!==o&&"lab"!==o)throw new Error(`Unknown color space: "${t.colorSpace}"`);var o;let a,l,u;if("exponential"===s)a=Er;else if("interval"===s)a=Tr;else if("categorical"===s){a=Vr,l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];u=typeof t.stops[0][0]}else{if("identity"!==s)throw new Error(`Unknown function type "${s}"`);a=Fr}if(n){const r={},n=[];for(let e=0;et[0])),evaluate:({zoom:r},n)=>Er({stops:i,base:t.base},e,r).evaluate(r,n)}}if(i){const r="exponential"===s?{name:"exponential",base:void 0!==t.base?t.base:1}:null;return{kind:"camera",interpolationType:r,interpolationFactor:Jt.interpolationFactor.bind(void 0,r),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:r})=>a(t,e,r,l,u)}}return{kind:"source",evaluate(r,n){const i=n&&n.properties?n.properties[t.property]:void 0;return void 0===i?Br(t.default,e.default):a(t,e,i,l,u)}}}function Br(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Vr(t,e,r,n,i){return Br(typeof r===i?n[r]:void 0,t.default,e.default)}function Tr(t,e,r){if("number"!==Mr(r))return Br(t.default,e.default);const n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];const i=jt(t.stops.map((t=>t[0])),r);return t.stops[i][1]}function Er(t,e,r){const n=void 0!==t.base?t.base:1;if("number"!==Mr(r))return Br(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];const s=jt(t.stops.map((t=>t[0])),r),o=function(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[s][0],t.stops[s+1][0]),a=t.stops[s][1],l=t.stops[s+1][1],u=Yt[e.type]||Pr;return"function"==typeof a.evaluate?{evaluate(...e){const r=a.evaluate.apply(void 0,e),n=l.evaluate.apply(void 0,e);if(void 0!==r&&void 0!==n)return u(r,n,o,t.colorSpace)}}:u(a,l,o,t.colorSpace)}function Fr(t,e,r){switch(e.type){case"color":r=pt.parse(r);break;case"formatted":r=yt.fromString(r.toString());break;case"resolvedImage":r=vt.fromString(r.toString());break;case"padding":r=mt.parse(r);break;default:Mr(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0)}return Br(r,t.default,e.default)}fr.register(pr,{error:[{kind:"error"},[P],(t,[e])=>{throw new At(e.evaluate(t))}],typeof:[P,[T],(t,[e])=>R(_t(e.evaluate(t)))],"to-rgba":[O(z,4),[B],(t,[e])=>{const[r,n,i,s]=e.evaluate(t).rgb;return[255*r,255*n,255*i,s]}],rgb:[B,[z,z,z],dr],rgba:[B,[z,z,z,z],dr],has:{type:C,overloads:[[[P],(t,[e])=>yr(e.evaluate(t),t.properties())],[[P,V],(t,[e,r])=>yr(e.evaluate(t),r.evaluate(t))]]},get:{type:T,overloads:[[[P],(t,[e])=>mr(e.evaluate(t),t.properties())],[[P,V],(t,[e,r])=>mr(e.evaluate(t),r.evaluate(t))]]},"feature-state":[T,[P],(t,[e])=>mr(e.evaluate(t),t.featureState||{})],properties:[V,[],t=>t.properties()],"geometry-type":[P,[],t=>t.geometryType()],id:[T,[],t=>t.id()],zoom:[z,[],t=>t.globals.zoom],"heatmap-density":[z,[],t=>t.globals.heatmapDensity||0],"line-progress":[z,[],t=>t.globals.lineProgress||0],accumulated:[T,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[z,gr(z),(t,e)=>{let r=0;for(const n of e)r+=n.evaluate(t);return r}],"*":[z,gr(z),(t,e)=>{let r=1;for(const n of e)r*=n.evaluate(t);return r}],"-":{type:z,overloads:[[[z,z],(t,[e,r])=>e.evaluate(t)-r.evaluate(t)],[[z],(t,[e])=>-e.evaluate(t)]]},"/":[z,[z,z],(t,[e,r])=>e.evaluate(t)/r.evaluate(t)],"%":[z,[z,z],(t,[e,r])=>e.evaluate(t)%r.evaluate(t)],ln2:[z,[],()=>Math.LN2],pi:[z,[],()=>Math.PI],e:[z,[],()=>Math.E],"^":[z,[z,z],(t,[e,r])=>Math.pow(e.evaluate(t),r.evaluate(t))],sqrt:[z,[z],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[z,[z],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[z,[z],(t,[e])=>Math.log(e.evaluate(t))],log2:[z,[z],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[z,[z],(t,[e])=>Math.sin(e.evaluate(t))],cos:[z,[z],(t,[e])=>Math.cos(e.evaluate(t))],tan:[z,[z],(t,[e])=>Math.tan(e.evaluate(t))],asin:[z,[z],(t,[e])=>Math.asin(e.evaluate(t))],acos:[z,[z],(t,[e])=>Math.acos(e.evaluate(t))],atan:[z,[z],(t,[e])=>Math.atan(e.evaluate(t))],min:[z,gr(z),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[z,gr(z),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[z,[z],(t,[e])=>Math.abs(e.evaluate(t))],round:[z,[z],(t,[e])=>{const r=e.evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[z,[z],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[z,[z],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[C,[P,T],(t,[e,r])=>t.properties()[e.value]===r.value],"filter-id-==":[C,[T],(t,[e])=>t.id()===e.value],"filter-type-==":[C,[P],(t,[e])=>t.geometryType()===e.value],"filter-<":[C,[P,T],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n{const r=t.id(),n=e.value;return typeof r==typeof n&&r":[C,[P,T],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[C,[T],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>n}],"filter-<=":[C,[P,T],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[C,[T],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r<=n}],"filter->=":[C,[P,T],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[C,[T],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>=n}],"filter-has":[C,[T],(t,[e])=>e.value in t.properties()],"filter-has-id":[C,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[C,[O(P)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[C,[O(T)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[C,[P,O(T)],(t,[e,r])=>r.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[C,[P,O(T)],(t,[e,r])=>function(t,e,r,n){for(;r<=n;){const i=r+n>>1;if(e[i]===t)return!0;e[i]>t?n=i-1:r=i+1}return!1}(t.properties()[e.value],r.value,0,r.value.length-1)],all:{type:C,overloads:[[[C,C],(t,[e,r])=>e.evaluate(t)&&r.evaluate(t)],[gr(C),(t,e)=>{for(const r of e)if(!r.evaluate(t))return!1;return!0}]]},any:{type:C,overloads:[[[C,C],(t,[e,r])=>e.evaluate(t)||r.evaluate(t)],[gr(C),(t,e)=>{for(const r of e)if(r.evaluate(t))return!0;return!1}]]},"!":[C,[C],(t,[e])=>!e.evaluate(t)],"is-supported-script":[C,[P],(t,[e])=>{const r=t.globals&&t.globals.isSupportedScript;return!r||r(e.evaluate(t))}],upcase:[P,[P],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[P,[P],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[P,gr(T),(t,e)=>e.map((e=>St(e.evaluate(t)))).join("")],"resolved-locale":[P,[E],(t,[e])=>e.evaluate(t).resolvedLocale()]});class Dr{constructor(t,e){var r;this.expression=t,this._warningHistory={},this._evaluator=new Bt,this._defaultValue=e?"color"===(r=e).type&&zr(r.default)?new pt(0,0,0,0):"color"===r.type?pt.parse(r.default)||null:"padding"===r.type?mt.parse(r.default)||null:"variableAnchorOffsetCollection"===r.type?xt.parse(r.default)||null:void 0===r.default?null:r.default:null,this._enumValues=e&&"enum"===e.type?e.values:null}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,r,n,i,s){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new At(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function $r(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in pr}function Lr(t,e){const r=new Vt(pr,xr,[],e?function(t){const e={color:B,string:P,number:z,enum:P,boolean:C,formatted:F,padding:D,resolvedImage:$,variableAnchorOffsetCollection:L};return"array"===t.type?O(e[t.value]||T,t.length):e[t.type]}(e):void 0),n=r.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return n?_r(new Dr(n,e)):Sr(r.errors)}class Or{constructor(t,e){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!br(e.expression)}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._styleExpression.evaluate(t,e,r,n,i,s)}}class Rr{constructor(t,e,r,n){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!br(e.expression),this.interpolationType=n}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._styleExpression.evaluate(t,e,r,n,i,s)}interpolationFactor(t,e,r){return this.interpolationType?Jt.interpolationFactor(this.interpolationType,t,e,r):0}}function jr(t,e){const r=Lr(t,e);if("error"===r.result)return r;const n=r.value.expression,i=vr(n);if(!i&&!kr(e))return Sr([new A("","data expressions not supported")]);const s=wr(n,["zoom"]);if(!s&&!Ar(e))return Sr([new A("","zoom expressions not supported")]);const o=Ur(n);return o||s?o instanceof A?Sr([o]):o instanceof Jt&&!Ir(e)?Sr([new A("",'"interpolate" expressions cannot be used with this property')]):_r(o?new Rr(i?"camera":"composite",r.value,o.labels,o instanceof Jt?o.interpolation:void 0):new Or(i?"constant":"source",r.value)):Sr([new A("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class qr{constructor(t,e){this._parameters=t,this._specification=e,k(this,Cr(this._parameters,this._specification))}static deserialize(t){return new qr(t._parameters,t._specification)}static serialize(t){return{_parameters:t._parameters,_specification:t._specification}}}function Ur(t){let e=null;if(t instanceof Tt)e=Ur(t.result);else if(t instanceof Wt){for(const r of t.args)if(e=Ur(r),e)break}else(t instanceof qt||t instanceof Jt)&&t.input instanceof fr&&"zoom"===t.input.name&&(e=t);return e instanceof A||t.eachChild((t=>{const r=Ur(t);r instanceof A?e=r:!e&&r?e=new A("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&r&&e!==r&&(e=new A("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))})),e}function Nr(t){if(!0===t||!1===t)return!0;if(!Array.isArray(t)||0===t.length)return!1;switch(t[0]){case"has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case"any":case"all":for(const e of t.slice(1))if(!Nr(e)&&"boolean"!=typeof e)return!1;return!0;default:return!0}}const Zr={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function Gr(t){if(null==t)return{filter:()=>!0,needGeometry:!1};Nr(t)||(t=Yr(t));const e=Lr(t,Zr);if("error"===e.result)throw new Error(e.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return{filter:(t,r,n)=>e.value.evaluate(t,r,{},n),needGeometry:Hr(t)}}function Xr(t,e){return te?1:0}function Hr(t){if(!Array.isArray(t))return!1;if("within"===t[0]||"distance"===t[0])return!0;for(let e=1;e"===e||"<="===e||">="===e?Jr(t[1],t[2],e):"any"===e?(r=t.slice(1),["any"].concat(r.map(Yr))):"all"===e?["all"].concat(t.slice(1).map(Yr)):"none"===e?["all"].concat(t.slice(1).map(Yr).map(Qr)):"in"===e?Kr(t[1],t.slice(2)):"!in"===e?Qr(Kr(t[1],t.slice(2))):"has"===e?Wr(t[1]):"!has"!==e||Qr(Wr(t[1]));var r}function Jr(t,e,r){switch(t){case"$type":return[`filter-type-${r}`,e];case"$id":return[`filter-id-${r}`,e];default:return[`filter-${r}`,t,e]}}function Kr(t,e){if(0===e.length)return!1;switch(t){case"$type":return["filter-type-in",["literal",e]];case"$id":return["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort(Xr)]]:["filter-in-small",t,["literal",e]]}}function Wr(t){switch(t){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",t]}}function Qr(t){return["!",t]}function tn(t){const e=typeof t;if("number"===e||"boolean"===e||"string"===e||null==t)return JSON.stringify(t);if(Array.isArray(t)){let e="[";for(const r of t)e+=`${tn(r)},`;return`${e}]`}const r=Object.keys(t).sort();let n="{";for(let e=0;en.maximum?[new S(e,r,`${r} is greater than the maximum value ${n.maximum}`)]:[]}function un(t){const e=t.valueSpec,r=nn(t.value.type);let n,i,s,o={};const a="categorical"!==r&&void 0===t.value.property,l=!a,u="array"===Mr(t.value.stops)&&"array"===Mr(t.value.stops[0])&&"object"===Mr(t.value.stops[0][0]),c=on({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===r)return[new S(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const n=t.value;return e=e.concat(an({key:t.key,value:n,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===Mr(n)&&0===n.length&&e.push(new S(t.key,n,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return"identity"===r&&a&&c.push(new S(t.key,t.value,'missing required property "property"')),"identity"===r||t.value.stops||c.push(new S(t.key,t.value,'missing required property "stops"')),"exponential"===r&&t.valueSpec.expression&&!Ir(t.valueSpec)&&c.push(new S(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!kr(t.valueSpec)?c.push(new S(t.key,t.value,"property functions not supported")):a&&!Ar(t.valueSpec)&&c.push(new S(t.key,t.value,"zoom functions not supported"))),"categorical"!==r&&!u||void 0!==t.value.property||c.push(new S(t.key,t.value,'"property" property is required')),c;function h(t){let r=[];const n=t.value,a=t.key;if("array"!==Mr(n))return[new S(a,n,`array expected, ${Mr(n)} found`)];if(2!==n.length)return[new S(a,n,`array length 2 expected, length ${n.length} found`)];if(u){if("object"!==Mr(n[0]))return[new S(a,n,`object expected, ${Mr(n[0])} found`)];if(void 0===n[0].zoom)return[new S(a,n,"object stop key must have zoom")];if(void 0===n[0].value)return[new S(a,n,"object stop key must have value")];if(s&&s>nn(n[0].zoom))return[new S(a,n[0].zoom,"stop zoom values must appear in ascending order")];nn(n[0].zoom)!==s&&(s=nn(n[0].zoom),i=void 0,o={}),r=r.concat(on({key:`${a}[0]`,value:n[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:ln,value:p}}))}else r=r.concat(p({key:`${a}[0]`,value:n[0],valueSpec:{},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},n));return $r(sn(n[1]))?r.concat([new S(`${a}[1]`,n[1],"expressions are not allowed in function stops.")]):r.concat(t.validateSpec({key:`${a}[1]`,value:n[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const a=Mr(t.value),l=nn(t.value),u=null!==t.value?t.value:s;if(n){if(a!==n)return[new S(t.key,u,`${a} stop domain type must match previous stop domain type ${n}`)]}else n=a;if("number"!==a&&"string"!==a&&"boolean"!==a)return[new S(t.key,u,"stop domain value must be a number, string, or boolean")];if("number"!==a&&"categorical"!==r){let n=`number expected, ${a} found`;return kr(e)&&void 0===r&&(n+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new S(t.key,u,n)]}return"categorical"!==r||"number"!==a||isFinite(l)&&Math.floor(l)===l?"categorical"!==r&&"number"===a&&void 0!==i&&lnew S(`${t.key}${e.key}`,t.value,e.message)));const r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return[new S(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!br(r))return[new S(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!br(r))return[new S(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!wr(r,["zoom","feature-state"]))return[new S(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!vr(r))return[new S(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function hn(t){const e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(nn(r))&&i.push(new S(e,r,`expected one of [${n.values.join(", ")}], ${JSON.stringify(r)} found`)):-1===Object.keys(n.values).indexOf(nn(r))&&i.push(new S(e,r,`expected one of [${Object.keys(n.values).join(", ")}], ${JSON.stringify(r)} found`)),i}function pn(t){return Nr(sn(t.value))?cn(k({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):fn(t)}function fn(t){const e=t.value,r=t.key;if("array"!==Mr(e))return[new S(r,e,`array expected, ${Mr(e)} found`)];const n=t.styleSpec;let i,s=[];if(e.length<1)return[new S(r,e,"filter array must have at least 1 element")];switch(s=s.concat(hn({key:`${r}[0]`,value:e[0],valueSpec:n.filter_operator,style:t.style,styleSpec:t.styleSpec})),nn(e[0])){case"<":case"<=":case">":case">=":e.length>=2&&"$type"===nn(e[1])&&s.push(new S(r,e,`"$type" cannot be use with operator "${e[0]}"`));case"==":case"!=":3!==e.length&&s.push(new S(r,e,`filter array for operator "${e[0]}" must have 3 elements`));case"in":case"!in":e.length>=2&&(i=Mr(e[1]),"string"!==i&&s.push(new S(`${r}[1]`,e[1],`string expected, ${i} found`)));for(let o=2;o{t in r&&e.push(new S(n,r[t],`"${t}" is prohibited for ref layers`))})),i.layers.forEach((e=>{nn(e.id)===a&&(t=e)})),t?t.ref?e.push(new S(n,r.ref,"ref cannot reference another ref layer")):o=nn(t.type):e.push(new S(n,r.ref,`ref layer "${a}" not found`))}else if("background"!==o)if(r.source){const t=i.sources&&i.sources[r.source],s=t&&nn(t.type);t?"vector"===s&&"raster"===o?e.push(new S(n,r.source,`layer "${r.id}" requires a raster source`)):"raster-dem"!==s&&"hillshade"===o?e.push(new S(n,r.source,`layer "${r.id}" requires a raster-dem source`)):"raster"===s&&"raster"!==o?e.push(new S(n,r.source,`layer "${r.id}" requires a vector source`)):"vector"!==s||r["source-layer"]?"raster-dem"===s&&"hillshade"!==o?e.push(new S(n,r.source,"raster-dem source can only be used with layer type 'hillshade'.")):"line"!==o||!r.paint||!r.paint["line-gradient"]||"geojson"===s&&t.lineMetrics||e.push(new S(n,r,`layer "${r.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):e.push(new S(n,r,`layer "${r.id}" must specify a "source-layer"`)):e.push(new S(n,r.source,`source "${r.source}" not found`))}else e.push(new S(n,r,'missing required property "source"'));return e=e.concat(on({key:n,value:r,valueSpec:s.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${n}.type`,value:r.type,valueSpec:s.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:r,objectKey:"type"}),filter:pn,layout:t=>on({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>mn(k({layerType:o},t))}}),paint:t=>on({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>yn(k({layerType:o},t))}})}})),e}function xn(t){const e=t.value,r=t.key,n=Mr(e);return"string"!==n?[new S(r,e,`string expected, ${n} found`)]:[]}const vn={promoteId:function({key:t,value:e}){if("string"===Mr(e))return xn({key:t,value:e});{const r=[];for(const n in e)r.push(...xn({key:`${t}.${n}`,value:e[n]}));return r}}};function bn(t){const e=t.value,r=t.key,n=t.styleSpec,i=t.style,s=t.validateSpec;if(!e.type)return[new S(r,e,'"type" is required')];const o=nn(e.type);let a;switch(o){case"vector":case"raster":return a=on({key:r,value:e,valueSpec:n[`source_${o.replace("-","_")}`],style:t.style,styleSpec:n,objectElementValidators:vn,validateSpec:s}),a;case"raster-dem":return a=function(t){var e;const r=null!==(e=t.sourceName)&&void 0!==e?e:"",n=t.value,i=t.styleSpec,s=i.source_raster_dem,o=t.style;let a=[];const l=Mr(n);if(void 0===n)return a;if("object"!==l)return a.push(new S("source_raster_dem",n,`object expected, ${l} found`)),a;const u="custom"===nn(n.encoding),c=["redFactor","greenFactor","blueFactor","baseShift"],h=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in n)!u&&c.includes(e)?a.push(new S(e,n[e],`In "${r}": "${e}" is only valid when "encoding" is set to "custom". ${h} encoding found`)):s[e]?a=a.concat(t.validateSpec({key:e,value:n[e],valueSpec:s[e],validateSpec:t.validateSpec,style:o,styleSpec:i})):a.push(new S(e,n[e],`unknown property "${e}"`));return a}({sourceName:r,value:e,style:t.style,styleSpec:n,validateSpec:s}),a;case"geojson":if(a=on({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,validateSpec:s,objectElementValidators:vn}),e.cluster)for(const t in e.clusterProperties){const[n,i]=e.clusterProperties[t],o="string"==typeof n?[n,["accumulated"],["get",t]]:n;a.push(...cn({key:`${r}.${t}.map`,value:i,validateSpec:s,expressionContext:"cluster-map"})),a.push(...cn({key:`${r}.${t}.reduce`,value:o,validateSpec:s,expressionContext:"cluster-reduce"}))}return a;case"video":return on({key:r,value:e,valueSpec:n.source_video,style:i,validateSpec:s,styleSpec:n});case"image":return on({key:r,value:e,valueSpec:n.source_image,style:i,validateSpec:s,styleSpec:n});case"canvas":return[new S(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return hn({key:`${r}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:i,validateSpec:s,styleSpec:n})}}function wn(t){const e=t.value,r=t.styleSpec,n=r.light,i=t.style;let s=[];const o=Mr(e);if(void 0===e)return s;if("object"!==o)return s=s.concat([new S("light",e,`object expected, ${o} found`)]),s;for(const o in e){const a=o.match(/^(.*)-transition$/);s=s.concat(a&&n[a[1]]&&n[a[1]].transition?t.validateSpec({key:o,value:e[o],valueSpec:r.transition,validateSpec:t.validateSpec,style:i,styleSpec:r}):n[o]?t.validateSpec({key:o,value:e[o],valueSpec:n[o],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new S(o,e[o],`unknown property "${o}"`)])}return s}function _n(t){const e=t.value,r=t.styleSpec,n=r.sky,i=t.style,s=Mr(e);if(void 0===e)return[];if("object"!==s)return[new S("sky",e,`object expected, ${s} found`)];let o=[];for(const s in e)o=o.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new S(s,e[s],`unknown property "${s}"`)]);return o}function Sn(t){const e=t.value,r=t.styleSpec,n=r.terrain,i=t.style;let s=[];const o=Mr(e);if(void 0===e)return s;if("object"!==o)return s=s.concat([new S("terrain",e,`object expected, ${o} found`)]),s;for(const o in e)s=s.concat(n[o]?t.validateSpec({key:o,value:e[o],valueSpec:n[o],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new S(o,e[o],`unknown property "${o}"`)]);return s}function kn(t){let e=[];const r=t.value,n=t.key;if(Array.isArray(r)){const i=[],s=[];for(const o in r)r[o].id&&i.includes(r[o].id)&&e.push(new S(n,r,`all the sprites' ids must be unique, but ${r[o].id} is duplicated`)),i.push(r[o].id),r[o].url&&s.includes(r[o].url)&&e.push(new S(n,r,`all the sprites' URLs must be unique, but ${r[o].url} is duplicated`)),s.push(r[o].url),e=e.concat(on({key:`${n}[${o}]`,value:r[o],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:t.validateSpec}));return e}return xn({key:n,value:r})}const An={"*":()=>[],array:an,boolean:function(t){const e=t.value,r=t.key,n=Mr(e);return"boolean"!==n?[new S(r,e,`boolean expected, ${n} found`)]:[]},number:ln,color:function(t){const e=t.key,r=t.value,n=Mr(r);return"string"!==n?[new S(e,r,`color expected, ${n} found`)]:pt.parse(String(r))?[]:[new S(e,r,`color expected, "${r}" found`)]},constants:rn,enum:hn,filter:pn,function:un,layer:gn,object:on,source:bn,light:wn,sky:_n,terrain:Sn,projection:function(t){const e=t.value,r=t.styleSpec,n=r.projection,i=t.style,s=Mr(e);if(void 0===e)return[];if("object"!==s)return[new S("projection",e,`object expected, ${s} found`)];let o=[];for(const s in e)o=o.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new S(s,e[s],`unknown property "${s}"`)]);return o},string:xn,formatted:function(t){return 0===xn(t).length?[]:cn(t)},resolvedImage:function(t){return 0===xn(t).length?[]:cn(t)},padding:function(t){const e=t.key,r=t.value;if("array"===Mr(r)){if(r.length<1||r.length>4)return[new S(e,r,`padding requires 1 to 4 values; ${r.length} values found`)];const n={type:"number"};let i=[];for(let s=0;s[]}})),t.constants&&(r=r.concat(rn({key:"constants",value:t.constants,style:t,styleSpec:e,validateSpec:In}))),Cn(r)}function Pn(t){return function(e){return t({...e,validateSpec:In})}}function Cn(t){return[].concat(t).sort(((t,e)=>t.line-e.line))}function Bn(t){return function(...e){return Cn(t.apply(this,e))}}zn.source=Bn(Pn(bn)),zn.sprite=Bn(Pn(kn)),zn.glyphs=Bn(Pn(Mn)),zn.light=Bn(Pn(wn)),zn.sky=Bn(Pn(_n)),zn.terrain=Bn(Pn(Sn)),zn.layer=Bn(Pn(gn)),zn.filter=Bn(Pn(pn)),zn.paintProperty=Bn(Pn(yn)),zn.layoutProperty=Bn(Pn(mn));const Vn="AbortError";function Tn(){return new Error(Vn)}const En={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:""};function Fn(t,e){En.REGISTERED_PROTOCOLS[t]=e}function Dn(t){delete En.REGISTERED_PROTOCOLS[t]}const $n="global-dispatcher";class Ln extends Error{constructor(t,e,r,n){super(`AJAXError: ${e} (${t}): ${r}`),this.status=t,this.statusText=e,this.url=r,this.body=n}}const On=()=>m(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,Rn=function(e,r){if(/:\/\//.test(e.url)&&!/^https?:|^file:/.test(e.url)){const t=En.REGISTERED_PROTOCOLS[(n=e.url).substring(0,n.indexOf("://"))];if(t)return t(e,r);if(m(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:e,targetMapId:$n},r)}var n;if(!(t=>/^file:/.test(t)||/^file:/.test(On())&&!/^\w+:/.test(t))(e.url)){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(e,r){return t(this,void 0,void 0,(function*(){const t=new Request(e.url,{method:e.method||"GET",body:e.body,credentials:e.credentials,headers:e.headers,cache:e.cache,referrer:On(),signal:r.signal});"json"!==e.type||t.headers.has("Accept")||t.headers.set("Accept","application/json");const n=yield fetch(t);if(!n.ok){const t=yield n.blob();throw new Ln(n.status,n.statusText,e.url,t)}let i;i="arrayBuffer"===e.type||"image"===e.type?n.arrayBuffer():"json"===e.type?n.json():n.text();const s=yield i;if(r.signal.aborted)throw Tn();return{data:s,cacheControl:n.headers.get("Cache-Control"),expires:n.headers.get("Expires")}}))}(e,r);if(m(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:e,mustQueue:!0,targetMapId:$n},r)}return function(t,e){return new Promise(((r,n)=>{var i;const s=new XMLHttpRequest;s.open(t.method||"GET",t.url,!0),"arrayBuffer"!==t.type&&"image"!==t.type||(s.responseType="arraybuffer");for(const e in t.headers)s.setRequestHeader(e,t.headers[e]);"json"===t.type&&(s.responseType="text",(null===(i=t.headers)||void 0===i?void 0:i.Accept)||s.setRequestHeader("Accept","application/json")),s.withCredentials="include"===t.credentials,s.onerror=()=>{n(new Error(s.statusText))},s.onload=()=>{if(!e.signal.aborted)if((s.status>=200&&s.status<300||0===s.status)&&null!==s.response){let e=s.response;if("json"===t.type)try{e=JSON.parse(s.response)}catch(t){return void n(t)}r({data:e,cacheControl:s.getResponseHeader("Cache-Control"),expires:s.getResponseHeader("Expires")})}else{const e=new Blob([s.response],{type:s.getResponseHeader("Content-Type")});n(new Ln(s.status,s.statusText,t.url,e))}},e.signal.addEventListener("abort",(()=>{s.abort(),n(Tn())})),s.send(t.body)}))}(e,r)},jn={};function qn(t,e,r={}){if(jn[t])throw new Error(`${t} is already registered.`);Object.defineProperty(e,"_classRegistryKey",{value:t,writeable:!1}),jn[t]={klass:e,omit:r.omit||[],shallow:r.shallow||[]}}qn("Object",Object),qn("TransferableGridIndex",b),qn("Color",pt),qn("Error",Error),qn("AJAXError",Ln),qn("ResolvedImage",vt),qn("StylePropertyFunction",qr),qn("StyleExpression",Dr,{omit:["_evaluator"]}),qn("ZoomDependentExpression",Rr),qn("ZoomConstantExpression",Or),qn("CompoundExpression",fr,{omit:["_evaluate"]});for(const t in pr)pr[t]._classRegistryKey||qn(`Expression_${t}`,pr[t]);function Un(t){return t&&"undefined"!=typeof ArrayBuffer&&(t instanceof ArrayBuffer||t.constructor&&"ArrayBuffer"===t.constructor.name)}function Nn(t){return t.$name||t.constructor._classRegistryKey}function Zn(t){return!function(t){if(null===t||"object"!=typeof t)return!1;const e=Nn(t);return!(!e||"Object"===e)}(t)&&(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp||t instanceof Blob||t instanceof Error||Un(t)||g(t)||ArrayBuffer.isView(t)||t instanceof ImageData)}function Gn(t,e){if(Zn(t))return(Un(t)||g(t))&&e&&e.push(t),ArrayBuffer.isView(t)&&e&&e.push(t.buffer),t instanceof ImageData&&e&&e.push(t.data.buffer),t;if(Array.isArray(t)){const r=[];for(const n of t)r.push(Gn(n,e));return r}if("object"!=typeof t)throw new Error("can't serialize object of type "+typeof t);const r=Nn(t);if(!r)throw new Error(`can't serialize object of unregistered class ${t.constructor.name}`);if(!jn[r])throw new Error(`${r} is not registered.`);const{klass:n}=jn[r],i=n.serialize?n.serialize(t,e):{};if(n.serialize){if(e&&i===e[e.length-1])throw new Error("statically serialized object won't survive transfer of $name property")}else{for(const n in t){if(!t.hasOwnProperty(n))continue;if(jn[r].omit.indexOf(n)>=0)continue;const s=t[n];i[n]=jn[r].shallow.indexOf(n)>=0?s:Gn(s,e)}t instanceof Error&&(i.message=t.message)}if(i.$name)throw new Error("$name property is reserved for worker serialization logic.");return"Object"!==r&&(i.$name=r),i}function Xn(t){if(Zn(t))return t;if(Array.isArray(t))return t.map(Xn);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=Nn(t)||"Object";if(!jn[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:r}=jn[e];if(!r)throw new Error(`can't deserialize unregistered class ${e}`);if(r.deserialize)return r.deserialize(t);const n=Object.create(r.prototype);for(const r of Object.keys(t)){if("$name"===r)continue;const i=t[r];n[r]=jn[e].shallow.indexOf(r)>=0?i:Xn(i)}return n}class Hn{constructor(t){this._methodToThrottle=t,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle()})}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._methodToThrottle()}),0))}remove(){delete this._channel,this._methodToThrottle=()=>{}}}class Yn{constructor(t,e){this.target=t,this.mapId=e,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new Hn((()=>this.process())),this.subscription=function(t,e,r,n){return t.addEventListener(e,r,!1),{unsubscribe:()=>{t.removeEventListener(e,r,!1)}}}(this.target,"message",(t=>this.receive(t))),this.globalScope=m(self)?t:window}registerMessageHandler(t,e){this.messageHandlers[t]=e}sendAsync(t,e){return new Promise(((r,n)=>{const i=Math.round(1e18*Math.random()).toString(36).substring(0,10);this.resolveRejects[i]={resolve:r,reject:n},e&&e.signal.addEventListener("abort",(()=>{delete this.resolveRejects[i];const e={id:i,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e)}),{once:!0});const s=[],o=Object.assign(Object.assign({},t),{id:i,sourceMapId:this.mapId,origin:location.origin,data:Gn(t.data,s)});this.target.postMessage(o,{transfer:s})}))}receive(t){const e=t.data,r=e.id;if(!("file://"!==e.origin&&"file://"!==location.origin&&"resource://android"!==e.origin&&"resource://android"!==location.origin&&e.origin!==location.origin||e.targetMapId&&this.mapId!==e.targetMapId)){if(""===e.type){delete this.tasks[r];const t=this.abortControllers[r];return delete this.abortControllers[r],void(t&&t.abort())}if(m(self)||e.mustQueue)return this.tasks[r]=e,this.taskQueue.push(r),void this.invoker.trigger();this.processTask(r,e)}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e)}processTask(e,r){return t(this,void 0,void 0,(function*(){if(""===r.type){const t=this.resolveRejects[e];if(delete this.resolveRejects[e],!t)return;return void(r.error?t.reject(Xn(r.error)):t.resolve(Xn(r.data)))}if(!this.messageHandlers[r.type])return void this.completeTask(e,new Error(`Could not find a registered handler for ${r.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const t=Xn(r.data),n=new AbortController;this.abortControllers[e]=n;try{const i=yield this.messageHandlers[r.type](r.sourceMapId,t,n);this.completeTask(e,null,i)}catch(t){this.completeTask(e,t)}}))}completeTask(t,e,r){const n=[];delete this.abortControllers[t];const i={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?Gn(e):null,data:Gn(r,n)};this.target.postMessage(i,{transfer:n})}remove(){this.invoker.remove(),this.subscription.unsubscribe()}}function Jn(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e))}function Kn(t,e,r){if(r&&r[t]){const n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1)}}class Wn{constructor(t,e={}){c(this,e),this.type=t}}class Qn extends Wn{constructor(t,e={}){super("error",c({error:t},e))}}class ti{on(t,e){return this._listeners=this._listeners||{},Jn(t,e,this._listeners),this}off(t,e){return Kn(t,e,this._listeners),Kn(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},Jn(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new Wn(t,e||{}));const r=t.type;if(this.listens(r)){t.target=this;const e=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];for(const r of e)r.call(this,t);const n=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];for(const e of n)Kn(r,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(c(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t))}else t instanceof Qn&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}const ei=zn,ri=ei.paintProperty,ni=ei.layoutProperty;class ii{constructor(){this.first=!0}update(t,e){const r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoomt>=128&&t<=255,"Hangul Jamo":t=>t>=4352&&t<=4607,Khmer:t=>t>=6016&&t<=6143,"General Punctuation":t=>t>=8192&&t<=8303,"Letterlike Symbols":t=>t>=8448&&t<=8527,"Number Forms":t=>t>=8528&&t<=8591,"Miscellaneous Technical":t=>t>=8960&&t<=9215,"Control Pictures":t=>t>=9216&&t<=9279,"Optical Character Recognition":t=>t>=9280&&t<=9311,"Enclosed Alphanumerics":t=>t>=9312&&t<=9471,"Geometric Shapes":t=>t>=9632&&t<=9727,"Miscellaneous Symbols":t=>t>=9728&&t<=9983,"Miscellaneous Symbols and Arrows":t=>t>=11008&&t<=11263,"Ideographic Description Characters":t=>t>=12272&&t<=12287,"CJK Symbols and Punctuation":t=>t>=12288&&t<=12351,Katakana:t=>t>=12448&&t<=12543,Kanbun:t=>t>=12688&&t<=12703,"CJK Strokes":t=>t>=12736&&t<=12783,"Enclosed CJK Letters and Months":t=>t>=12800&&t<=13055,"CJK Compatibility":t=>t>=13056&&t<=13311,"Yijing Hexagram Symbols":t=>t>=19904&&t<=19967,"Private Use Area":t=>t>=57344&&t<=63743,"Vertical Forms":t=>t>=65040&&t<=65055,"CJK Compatibility Forms":t=>t>=65072&&t<=65103,"Small Form Variants":t=>t>=65104&&t<=65135,"Halfwidth and Fullwidth Forms":t=>t>=65280&&t<=65519};function oi(t){for(const e of t)if(pi(e.charCodeAt(0)))return!0;return!1}function ai(t){for(const e of t)if(!ci(e.charCodeAt(0)))return!1;return!0}function li(t){const e=t.map((t=>{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}const ui=li(["Arab","Dupl","Mong","Ougr","Syrc"]);function ci(t){return!ui.test(String.fromCodePoint(t))}const hi=li(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function pi(t){return!(746!==t&&747!==t&&(t<4352||!(si["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||si["CJK Compatibility"](t)||si["CJK Strokes"](t)||!(!si["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||si["Enclosed CJK Letters and Months"](t)||si["Ideographic Description Characters"](t)||si.Kanbun(t)||si.Katakana(t)&&12540!==t||!(!si["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!si["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||si["Vertical Forms"](t)||si["Yijing Hexagram Symbols"](t)||/\p{sc=Cans}/u.test(String.fromCodePoint(t))||/\p{sc=Hang}/u.test(String.fromCodePoint(t))||hi.test(String.fromCodePoint(t)))))}function fi(t){return!(pi(t)||function(t){return!!(si["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||si["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||si["Letterlike Symbols"](t)||si["Number Forms"](t)||si["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||si["Control Pictures"](t)&&9251!==t||si["Optical Character Recognition"](t)||si["Enclosed Alphanumerics"](t)||si["Geometric Shapes"](t)||si["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||si["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||si["CJK Symbols and Punctuation"](t)||si.Katakana(t)||si["Private Use Area"](t)||si["CJK Compatibility Forms"](t)||si["Small Form Variants"](t)||si["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}const di=li(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function yi(t){return di.test(String.fromCodePoint(t))}function mi(t,e){return!(!e&&yi(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||si.Khmer(t))}function gi(t){for(const e of t)if(yi(e.charCodeAt(0)))return!0;return!1}const xi=new class{constructor(){this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL}getState(){return{pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getPluginURL(){return this.pluginURL}getRTLTextPluginStatus(){return this.pluginStatus}};class vi{constructor(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new ii,this.transition={})}isSupportedScript(t){return function(t,e){for(const r of t)if(!mi(r.charCodeAt(0),e))return!1;return!0}(t,"loaded"===xi.getRTLTextPluginStatus())}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}}}class bi{constructor(t,e){this.property=t,this.value=e,this.expression=function(t,e){if(zr(t))return new qr(t,e);if($r(t)){const r=jr(t,e);if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return r.value}{let r=t;return"color"===e.type&&"string"==typeof t?r=pt.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)&&(r=xt.parse(t)):r=mt.parse(t),{kind:"constant",evaluate:()=>r}}}(void 0===e?t.specification.default:e,t.specification)}isDataDriven(){return"source"===this.expression.kind||"composite"===this.expression.kind}possiblyEvaluate(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)}}class wi{constructor(t){this.property=t,this.value=new bi(t,void 0)}transitioned(t,e){return new Si(this.property,this.value,e,c({},t.transition,this.transition),t.now)}untransitioned(){return new Si(this.property,this.value,null,{},0)}}class _i{constructor(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues)}getValue(t){return p(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new wi(this._values[t].property)),this._values[t].value=new bi(this._values[t].property,null===e?void 0:p(e))}getTransition(t){return p(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new wi(this._values[t].property)),this._values[t].transition=p(e)||void 0}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);void 0!==r&&(t[e]=r);const n=this.getTransition(e);void 0!==n&&(t[`${e}-transition`]=n)}return t}transitioned(t,e){const r=new ki(this._properties);for(const n of Object.keys(this._values))r._values[n]=this._values[n].transitioned(t,e._values[n]);return r}untransitioned(){const t=new ki(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class Si{constructor(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r)}possiblyEvaluate(t,e,r){const n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),s=this.prior;if(s){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(n=1)return 1;const e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}(o))}}return i}}class ki{constructor(t){this._properties=t,this._values=Object.create(t.defaultTransitioningPropertyValues)}possiblyEvaluate(t,e,r){const n=new Mi(this._properties);for(const i of Object.keys(this._values))n._values[i]=this._values[i].possiblyEvaluate(t,e,r);return n}hasTransition(){for(const t of Object.keys(this._values))if(this._values[t].prior)return!0;return!1}}class Ai{constructor(t){this._properties=t,this._values=Object.create(t.defaultPropertyValues)}hasValue(t){return void 0!==this._values[t].value}getValue(t){return p(this._values[t].value)}setValue(t,e){this._values[t]=new bi(this._values[t].property,null===e?void 0:p(e))}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);void 0!==r&&(t[e]=r)}return t}possiblyEvaluate(t,e,r){const n=new Mi(this._properties);for(const i of Object.keys(this._values))n._values[i]=this._values[i].possiblyEvaluate(t,e,r);return n}}class Ii{constructor(t,e,r){this.property=t,this.value=e,this.parameters=r}isConstant(){return"constant"===this.value.kind}constantOr(t){return"constant"===this.value.kind?this.value.value:t}evaluate(t,e,r,n){return this.property.evaluate(this.value,this.parameters,t,e,r,n)}}class Mi{constructor(t){this._properties=t,this._values=Object.create(t.defaultPossiblyEvaluatedValues)}get(t){return this._values[t]}}class zi{constructor(t){this.specification=t}possiblyEvaluate(t,e){if(t.isDataDriven())throw new Error("Value should not be data driven");return t.expression.evaluate(e)}interpolate(t,e,r){const n=Yt[this.specification.type];return n?n(t,e,r):t}}class Pi{constructor(t,e){this.specification=t,this.overrides=e}possiblyEvaluate(t,e,r,n){return new Ii(this,"constant"===t.expression.kind||"camera"===t.expression.kind?{kind:"constant",value:t.expression.evaluate(e,null,{},r,n)}:t.expression,e)}interpolate(t,e,r){if("constant"!==t.value.kind||"constant"!==e.value.kind)return t;if(void 0===t.value.value||void 0===e.value.value)return new Ii(this,{kind:"constant",value:void 0},t.parameters);const n=Yt[this.specification.type];if(n){const i=n(t.value.value,e.value.value,r);return new Ii(this,{kind:"constant",value:i},t.parameters)}return t}evaluate(t,e,r,n,i,s){return"constant"===t.kind?t.value:t.evaluate(e,r,n,i,s)}}class Ci extends Pi{possiblyEvaluate(t,e,r,n){if(void 0===t.value)return new Ii(this,{kind:"constant",value:void 0},e);if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n),s="resolvedImage"===t.property.specification.type&&"string"!=typeof i?i.name:i,o=this._calculate(s,s,s,e);return new Ii(this,{kind:"constant",value:o},e)}if("camera"===t.expression.kind){const r=this._calculate(t.expression.evaluate({zoom:e.zoom-1}),t.expression.evaluate({zoom:e.zoom}),t.expression.evaluate({zoom:e.zoom+1}),e);return new Ii(this,{kind:"constant",value:r},e)}return new Ii(this,t.expression,e)}evaluate(t,e,r,n,i,s){if("source"===t.kind){const o=t.evaluate(e,r,n,i,s);return this._calculate(o,o,o,e)}return"composite"===t.kind?this._calculate(t.evaluate({zoom:Math.floor(e.zoom)-1},r,n),t.evaluate({zoom:Math.floor(e.zoom)},r,n),t.evaluate({zoom:Math.floor(e.zoom)+1},r,n),e):t.value}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Bi{constructor(t){this.specification=t}possiblyEvaluate(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new vi(Math.floor(e.zoom-1),e)),t.expression.evaluate(new vi(Math.floor(e.zoom),e)),t.expression.evaluate(new vi(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Vi{constructor(t){this.specification=t}possiblyEvaluate(t,e,r,n){return!!t.expression.evaluate(e,null,{},r,n)}interpolate(){return!1}}class Ti{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const r=t[e];r.specification.overridable&&this.overridableProperties.push(e);const n=this.defaultPropertyValues[e]=new bi(r,void 0),i=this.defaultTransitionablePropertyValues[e]=new wi(r);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({})}}}qn("DataDrivenProperty",Pi),qn("DataConstantProperty",zi),qn("CrossFadedDataDrivenProperty",Ci),qn("CrossFadedProperty",Bi),qn("ColorRampProperty",Vi);const Ei="-transition";class Fi extends ti{constructor(t,e){if(super(),this.id=t.id,this.type=t.type,this._featureFilter={filter:()=>!0,needGeometry:!1},"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter),e.layout&&(this._unevaluatedLayout=new Ai(e.layout)),e.paint)){this._transitionablePaint=new _i(e.paint);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:!1});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new Mi(e.paint)}}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){return"visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)}setLayoutProperty(t,e,r={}){null!=e&&this._validate(ni,`layers.${this.id}.layout.${t}`,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e)}getPaintProperty(t){return t.endsWith(Ei)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,r={}){if(null!=e&&this._validate(ri,`layers.${this.id}.paint.${t}`,t,e,r))return!1;if(t.endsWith(Ei))return this._transitionablePaint.setTransition(t.slice(0,-11),e||void 0),!1;{const r=this._transitionablePaint._values[t],n="cross-faded-data-driven"===r.property.specification["property-type"],i=r.value.isDataDriven(),s=r.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const o=this._transitionablePaint._values[t].value;return o.isDataDriven()||i||n||this._handleOverridablePaintPropertyUpdate(t,s,o)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,r){return!1}isHidden(t){return!!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e)}serialize(){const t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),function(t,e,r){const n={};for(const r in t)e.call(this,t[r],r,t)&&(n[r]=t[r]);return n}(t,((t,e)=>!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,r,n,i={}){return(!i||!1!==i.validate)&&function(t,e){let r=!1;if(e&&e.length)for(const n of e)t.fire(new Qn(new Error(n.message))),r=!0;return r}(this,t.call(ei,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:w,style:{glyphs:!0,sprite:!0}}))}is3D(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof Ii&&kr(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return!0}return!1}}const Di={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class $i{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}class Li{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0)}static serialize(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(t){this.reserve(t),this.length=t}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e)}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function Oi(t,e=1){let r=0,n=0;return{members:t.map((t=>{const i=Di[t.type].BYTES_PER_ELEMENT,s=r=Ri(r,Math.max(e,i)),o=t.components||1;return n=Math.max(n,i),r+=i*o,{name:t.name,type:t.type,components:o,offset:s}})),size:Ri(r,Math.max(n,e)),alignment:e}}function Ri(t,e){return Math.ceil(t/e)*e}class ji extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t}}ji.prototype.bytesPerElement=4,qn("StructArrayLayout2i4",ji);class qi extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t}}qi.prototype.bytesPerElement=6,qn("StructArrayLayout3i6",qi);class Ui extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,t}}Ui.prototype.bytesPerElement=8,qn("StructArrayLayout4i8",Ui);class Ni extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,r,n,i,s){const o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,o){const a=6*t;return this.int16[a+0]=e,this.int16[a+1]=r,this.int16[a+2]=n,this.int16[a+3]=i,this.int16[a+4]=s,this.int16[a+5]=o,t}}Ni.prototype.bytesPerElement=12,qn("StructArrayLayout2i4i12",Ni);class Zi extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,r,n,i,s){const o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,o){const a=4*t,l=8*t;return this.int16[a+0]=e,this.int16[a+1]=r,this.uint8[l+4]=n,this.uint8[l+5]=i,this.uint8[l+6]=s,this.uint8[l+7]=o,t}}Zi.prototype.bytesPerElement=8,qn("StructArrayLayout2i4ub8",Zi);class Gi extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t}}Gi.prototype.bytesPerElement=8,qn("StructArrayLayout2f8",Gi);class Xi extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t,e,r,n,i,s,o,a,l,u){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,r,n,i,s,o,a,l,u)}emplace(t,e,r,n,i,s,o,a,l,u,c){const h=10*t;return this.uint16[h+0]=e,this.uint16[h+1]=r,this.uint16[h+2]=n,this.uint16[h+3]=i,this.uint16[h+4]=s,this.uint16[h+5]=o,this.uint16[h+6]=a,this.uint16[h+7]=l,this.uint16[h+8]=u,this.uint16[h+9]=c,t}}Xi.prototype.bytesPerElement=20,qn("StructArrayLayout10ui20",Xi);class Hi extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t,e,r,n,i,s,o,a,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,s,o,a,l,u,c,h)}emplace(t,e,r,n,i,s,o,a,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=o,this.uint16[f+6]=a,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}Hi.prototype.bytesPerElement=24,qn("StructArrayLayout4i4ui4i24",Hi);class Yi extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}Yi.prototype.bytesPerElement=12,qn("StructArrayLayout3f12",Yi);class Ji extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}Ji.prototype.bytesPerElement=4,qn("StructArrayLayout1ul4",Ji);class Ki extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t,e,r,n,i,s,o,a,l){const u=this.length;return this.resize(u+1),this.emplace(u,t,e,r,n,i,s,o,a,l)}emplace(t,e,r,n,i,s,o,a,l,u){const c=10*t,h=5*t;return this.int16[c+0]=e,this.int16[c+1]=r,this.int16[c+2]=n,this.int16[c+3]=i,this.int16[c+4]=s,this.int16[c+5]=o,this.uint32[h+3]=a,this.uint16[c+8]=l,this.uint16[c+9]=u,t}}Ki.prototype.bytesPerElement=20,qn("StructArrayLayout6i1ul2ui20",Ki);class Wi extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,r,n,i,s){const o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,o){const a=6*t;return this.int16[a+0]=e,this.int16[a+1]=r,this.int16[a+2]=n,this.int16[a+3]=i,this.int16[a+4]=s,this.int16[a+5]=o,t}}Wi.prototype.bytesPerElement=12,qn("StructArrayLayout2i2i2i12",Wi);class Qi extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const o=4*t,a=8*t;return this.float32[o+0]=e,this.float32[o+1]=r,this.float32[o+2]=n,this.int16[a+6]=i,this.int16[a+7]=s,t}}Qi.prototype.bytesPerElement=16,qn("StructArrayLayout2f1f2i16",Qi);class ts extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,r,n,i,s){const o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,o){const a=16*t,l=4*t,u=8*t;return this.uint8[a+0]=e,this.uint8[a+1]=r,this.float32[l+1]=n,this.float32[l+2]=i,this.int16[u+6]=s,this.int16[u+7]=o,t}}ts.prototype.bytesPerElement=16,qn("StructArrayLayout2ub2f2i16",ts);class es extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t}}es.prototype.bytesPerElement=6,qn("StructArrayLayout3ui6",es);class rs extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t,e,r,n,i,s,o,a,l,u,c,h,p,f,d,y,m){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,r,n,i,s,o,a,l,u,c,h,p,f,d,y,m)}emplace(t,e,r,n,i,s,o,a,l,u,c,h,p,f,d,y,m,g){const x=24*t,v=12*t,b=48*t;return this.int16[x+0]=e,this.int16[x+1]=r,this.uint16[x+2]=n,this.uint16[x+3]=i,this.uint32[v+2]=s,this.uint32[v+3]=o,this.uint32[v+4]=a,this.uint16[x+10]=l,this.uint16[x+11]=u,this.uint16[x+12]=c,this.float32[v+7]=h,this.float32[v+8]=p,this.uint8[b+36]=f,this.uint8[b+37]=d,this.uint8[b+38]=y,this.uint32[v+10]=m,this.int16[x+22]=g,t}}rs.prototype.bytesPerElement=48,qn("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",rs);class ns extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t,e,r,n,i,s,o,a,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,k,A,I,M){const z=this.length;return this.resize(z+1),this.emplace(z,t,e,r,n,i,s,o,a,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,k,A,I,M)}emplace(t,e,r,n,i,s,o,a,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,k,A,I,M,z){const P=32*t,C=16*t;return this.int16[P+0]=e,this.int16[P+1]=r,this.int16[P+2]=n,this.int16[P+3]=i,this.int16[P+4]=s,this.int16[P+5]=o,this.int16[P+6]=a,this.int16[P+7]=l,this.uint16[P+8]=u,this.uint16[P+9]=c,this.uint16[P+10]=h,this.uint16[P+11]=p,this.uint16[P+12]=f,this.uint16[P+13]=d,this.uint16[P+14]=y,this.uint16[P+15]=m,this.uint16[P+16]=g,this.uint16[P+17]=x,this.uint16[P+18]=v,this.uint16[P+19]=b,this.uint16[P+20]=w,this.uint16[P+21]=_,this.uint16[P+22]=S,this.uint32[C+12]=k,this.float32[C+13]=A,this.float32[C+14]=I,this.uint16[P+30]=M,this.uint16[P+31]=z,t}}ns.prototype.bytesPerElement=64,qn("StructArrayLayout8i15ui1ul2f2ui64",ns);class is extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}is.prototype.bytesPerElement=4,qn("StructArrayLayout1f4",is);class ss extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[6*t+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}ss.prototype.bytesPerElement=12,qn("StructArrayLayout1ui2f12",ss);class os extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t}}os.prototype.bytesPerElement=8,qn("StructArrayLayout1ul2ui8",os);class as extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t}}as.prototype.bytesPerElement=4,qn("StructArrayLayout2ui4",as);class ls extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}ls.prototype.bytesPerElement=2,qn("StructArrayLayout1ui2",ls);class us extends Li{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=r,this.float32[s+2]=n,this.float32[s+3]=i,t}}us.prototype.bytesPerElement=16,qn("StructArrayLayout4f16",us);class cs extends $i{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new i(this.anchorPointX,this.anchorPointY)}}cs.prototype.size=20;class hs extends Ki{get(t){return new cs(this,t)}}qn("CollisionBoxArray",hs);class ps extends $i{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}ps.prototype.size=48;class fs extends rs{get(t){return new ps(this,t)}}qn("PlacedSymbolArray",fs);class ds extends $i{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}ds.prototype.size=64;class ys extends ns{get(t){return new ds(this,t)}}qn("SymbolInstanceArray",ys);class ms extends is{getoffsetX(t){return this.float32[1*t+0]}}qn("GlyphOffsetArray",ms);class gs extends qi{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}qn("SymbolLineVertexArray",gs);class xs extends $i{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}xs.prototype.size=12;class vs extends ss{get(t){return new xs(this,t)}}qn("TextAnchorOffsetArray",vs);class bs extends $i{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}bs.prototype.size=8;class ws extends os{get(t){return new bs(this,t)}}qn("FeatureIndexArray",ws);class _s extends ji{}class Ss extends ji{}class ks extends ji{}class As extends Ni{}class Is extends Zi{}class Ms extends Gi{}class zs extends Xi{}class Ps extends Hi{}class Cs extends Yi{}class Bs extends Ji{}class Vs extends Wi{}class Ts extends ts{}class Es extends es{}class Fs extends as{}const Ds=Oi([{name:"a_pos",components:2,type:"Int16"}],4),{members:$s}=Ds;class Ls{constructor(t=[]){this.segments=t}prepareSegment(t,e,r,n){let i=this.segments[this.segments.length-1];return t>Ls.MAX_VERTEX_ARRAY_LENGTH&&d(`Max vertices per segment is ${Ls.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}`),(!i||i.vertexLength+t>Ls.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n)&&(i={vertexOffset:e.length,primitiveOffset:r.length,vertexLength:0,primitiveLength:0},void 0!==n&&(i.sortKey=n),this.segments.push(i)),i}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy()}static simpleSegment(t,e,r,n){return new Ls([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])}}function Os(t,e){return 256*(t=u(Math.floor(t),0,255))+u(Math.floor(e),0,255)}Ls.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,qn("SegmentVector",Ls);const Rs=Oi([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var js={exports:{}},qs={exports:{}};qs.exports=function(t,e){var r,n,i,s,o,a,l,u;for(n=t.length-(r=3&t.length),i=e,o=3432918353,a=461845907,u=0;u>>16)*o&65535)<<16)&4294967295)<<15|l>>>17))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,r){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<15|l>>>17))*a+(((l>>>16)*a&65535)<<16)&4294967295}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0};var Us=qs.exports,Ns={exports:{}};Ns.exports=function(t,e){for(var r,n=t.length,i=e^n,s=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++s;switch(n){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16)}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0};var Zs=Us,Gs=Ns.exports;js.exports=Zs,js.exports.murmur3=Zs,js.exports.murmur2=Gs;var Xs=e(js.exports);class Hs{constructor(){this.ids=[],this.positions=[],this.indexed=!1}add(t,e,r,n){this.ids.push(Ys(t)),this.positions.push(e,r,n)}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=Ys(t);let r=0,n=this.ids.length-1;for(;r>1;this.ids[t]>=e?n=t:r=t+1}const i=[];for(;this.ids[r]===e;)i.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return i}static serialize(t,e){const r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return Js(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}}static deserialize(t){const e=new Hs;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e}}function Ys(t){const e=+t;return!isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:Xs(String(t))}function Js(t,e,r,n){for(;r>1];let s=r-1,o=n+1;for(;;){do{s++}while(t[s]i);if(s>=o)break;Ks(t,s,o),Ks(e,3*s,3*o),Ks(e,3*s+1,3*o+1),Ks(e,3*s+2,3*o+2)}o-r`u_${t}`)),this.type=r}setUniform(t,e,r){t.set(r.constantOr(this.value))}getBinding(t,e,r){return"color"===this.type?new eo(t,e):new Qs(t,e)}}class io{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr}setUniform(t,e,r,n){const i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i)}getBinding(t,e,r){return"u_pattern"===r.substr(0,9)?new to(t,e):new Qs(t,e)}}class so{constructor(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?2:1,offset:0}))),this.paintVertexArray=new n}populatePaintArray(t,e,r,n,i){const s=this.paintVertexArray.length,o=this.expression.evaluate(new vi(0),e,{},n,[],i);this.paintVertexArray.resize(t),this._setPaintValue(s,t,o)}updatePaintArray(t,e,r,n){const i=this.expression.evaluate({zoom:0},r,n);this._setPaintValue(t,e,i)}_setPaintValue(t,e,r){if("color"===this.type){const n=ro(r);for(let r=t;r`u_${t}_t`)),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?4:2,offset:0}))),this.paintVertexArray=new s}populatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new vi(this.zoom),e,{},n,[],i),o=this.expression.evaluate(new vi(this.zoom+1),e,{},n,[],i),a=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(a,t,s,o)}updatePaintArray(t,e,r,n){const i=this.expression.evaluate({zoom:this.zoom},r,n),s=this.expression.evaluate({zoom:this.zoom+1},r,n);this._setPaintValue(t,e,i,s)}_setPaintValue(t,e,r,n){if("color"===this.type){const i=ro(r),s=ro(n);for(let r=t;r`#define HAS_UNIFORM_${t}`)))}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const r=this.binders[e];if(r instanceof so||r instanceof oo)for(let e=0;e!0)){this.programConfigurations={};for(const n of t)this.programConfigurations[n.id]=new lo(n,e,r);this.needsUpload=!1,this._featureMap=new Hs,this._bufferOffset=0}populatePaintArrays(t,e,r,n,i,s){for(const r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e,n,i,s);void 0!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0}updatePaintArrays(t,e,r,n){for(const i of r)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(t,this._featureMap,e,i,n)||this.needsUpload}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy()}}function co(t,e){return{"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function ho(t,e,r){const n={color:{source:Gi,composite:us},number:{source:is,composite:Gi}},i=function(t){return{"line-pattern":{source:zs,composite:zs},"fill-pattern":{source:zs,composite:zs},"fill-extrusion-pattern":{source:zs,composite:zs}}[t]}(t);return i&&i[r]||n[e][r]}qn("ConstantBinder",no),qn("CrossFadedConstantBinder",io),qn("SourceExpressionBinder",so),qn("CrossFadedCompositeBinder",ao),qn("CompositeExpressionBinder",oo),qn("ProgramConfiguration",lo,{omit:["_buffers"]}),qn("ProgramConfigurationSet",uo);const po=8192,fo=Math.pow(2,14)-1,yo=-fo-1;function mo(t){const e=po/t.extent,r=t.loadGeometry();for(let t=0;tr.x+1||sr.y+1)&&d("Geometry exceeds allowed extent, reduce your vector tile buffer size")}}return r}function go(t,e){return{type:t.type,id:t.id,properties:t.properties,geometry:e?mo(t):[]}}function xo(t,e,r,n,i){t.emplaceBack(2*e+(n+1)/2,2*r+(i+1)/2)}class vo{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Ss,this.indexArray=new Es,this.segments=new Ls,this.programConfigurations=new uo(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id))}populate(t,e,r){const n=this.layers[0],i=[];let s=null,o=!1;"circle"===n.type&&(s=n.layout.get("circle-sort-key"),o=!s.isConstant());for(const{feature:e,id:n,index:a,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=go(e,t);if(!this.layers[0]._featureFilter.filter(new vi(this.zoom),u,r))continue;const c=o?s.evaluate(u,{},r):void 0,h={id:n,properties:e.properties,type:e.type,sourceLayerIndex:l,index:a,geometry:t?u.geometry:mo(e),patterns:{},sortKey:c};i.push(h)}o&&i.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of i){const{geometry:i,index:s,sourceLayerIndex:o}=n,a=t[s].feature;this.addFeature(n,i,s,r),e.featureIndex.insert(a,i,s,o,this.index)}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r)}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,$s),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(t,e,r,n){for(const r of e)for(const e of r){const r=e.x,n=e.y;if(r<0||r>=po||n<0||n>=po)continue;const i=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,t.sortKey),s=i.vertexLength;xo(this.layoutVertexArray,r,n,-1,-1),xo(this.layoutVertexArray,r,n,1,-1),xo(this.layoutVertexArray,r,n,1,1),xo(this.layoutVertexArray,r,n,-1,1),this.indexArray.emplaceBack(s,s+1,s+2),this.indexArray.emplaceBack(s,s+3,s+2),i.vertexLength+=4,i.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{},n)}}function bo(t,e){for(let r=0;r1){if(ko(t,e))return!0;for(let n=0;n1?r:r.sub(e)._mult(i)._add(e))}function zo(t,e){let r,n,i,s=!1;for(let o=0;oe.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(s=!s)}return s}function Po(t,e){let r=!1;for(let n=0,i=t.length-1;ne.y!=o.y>e.y&&e.x<(o.x-s.x)*(e.y-s.y)/(o.y-s.y)+s.x&&(r=!r)}return r}function Co(t,e,r){const n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return!1;const s=y(t,e,r[0]);return s!==y(t,e,r[1])||s!==y(t,e,r[2])||s!==y(t,e,r[3])}function Bo(t,e,r){const n=e.paint.get(t).value;return"constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function Vo(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function To(t,e,r,n,s){if(!e[0]&&!e[1])return t;const o=i.convert(e)._mult(s);"viewport"===r&&o._rotate(-n);const a=[];for(let e=0;eqo(t,e)))}(l,a),p=c?u*o:u;for(const t of n)for(const e of t){const t=c?e:qo(e,a);let r=p;const n=Ro([],[e.x,e.y,0,1],a);if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?r*=n[3]/s.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(r*=s.cameraToCenterDistance/n[3]),wo(h,t,r))return!0}return!1}}function qo(t,e){const r=Ro([],[t.x,t.y,0,1],e);return new i(r[0]/r[3],r[1]/r[3])}class Uo extends vo{}let No;qn("HeatmapBucket",Uo,{omit:["layers"]});var Zo={get paint(){return No=No||new Ti({"heatmap-radius":new Pi(w.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Pi(w.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new zi(w.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Vi(w.paint_heatmap["heatmap-color"]),"heatmap-opacity":new zi(w.paint_heatmap["heatmap-opacity"])})}};function Go(t,{width:e,height:r},n,i){if(i){if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==e*r*n)throw new RangeError(`mismatched image size. expected: ${i.length} but got: ${e*r*n}`)}else i=new Uint8Array(e*r*n);return t.width=e,t.height=r,t.data=i,t}function Xo(t,{width:e,height:r},n){if(e===t.width&&r===t.height)return;const i=Go({},{width:e,height:r},n);Ho(t,i,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,r)},n),t.width=e,t.height=r,t.data=i.data}function Ho(t,e,r,n,i,s){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");const o=t.data,a=e.data;if(o===a)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=s;const o=t.expression.evaluate(e);i.data[r+n+0]=Math.floor(255*o.r/o.a),i.data[r+n+1]=Math.floor(255*o.g/o.a),i.data[r+n+2]=Math.floor(255*o.b/o.a),i.data[r+n+3]=Math.floor(255*o.a)};if(t.clips)for(let e=0,i=0;e80*r){a=1/0,l=1/0;let e=-1/0,n=-1/0;for(let s=r;se&&(e=r),i>n&&(n=i)}u=Math.max(e-a,n-l),u=0!==u?32767/u:0}return aa(s,o,r,a,l,u,0),o}function sa(t,e,r,n,i){let s;if(i===function(t,e,r,n){let i=0;for(let s=e,o=r-n;s0)for(let i=e;i=e;i-=n)s=Ia(i/n|0,t[i],t[i+1],s);return s&&ba(s,s.next)&&(Ma(s),s=s.next),s}function oa(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!ba(n,n.next)&&0!==va(n.prev,n,n.next))n=n.next;else{if(Ma(n),n=e=n.prev,n===n.next)break;r=!0}}while(r||n!==e);return e}function aa(t,e,r,n,i,s,o){if(!t)return;!o&&s&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=ya(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let s=null;for(e=0;i;){e++;let o=i,a=0;for(let t=0;t0||l>0&&o;)0!==a&&(0===l||!o||i.z<=o.z)?(n=i,i=i.nextZ,a--):(n=o,o=o.nextZ,l--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;i=o}s.nextZ=null,r*=2}while(e>1)}(i)}(t,n,i,s);let a=t;for(;t.prev!==t.next;){const l=t.prev,u=t.next;if(s?ua(t,n,i,s):la(t))e.push(l.i,t.i,u.i),Ma(t),t=u.next,a=u.next;else if((t=u)===a){o?1===o?aa(t=ca(oa(t),e),e,r,n,i,s,2):2===o&&ha(t,e,r,n,i,s):aa(oa(t),e,r,n,i,s,1);break}}}function la(t){const e=t.prev,r=t,n=t.next;if(va(e,r,n)>=0)return!1;const i=e.x,s=r.x,o=n.x,a=e.y,l=r.y,u=n.y,c=is?i>o?i:o:s>o?s:o,f=a>l?a>u?a:u:l>u?l:u;let d=n.next;for(;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&ga(i,a,s,l,o,u,d.x,d.y)&&va(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function ua(t,e,r,n){const i=t.prev,s=t,o=t.next;if(va(i,s,o)>=0)return!1;const a=i.x,l=s.x,u=o.x,c=i.y,h=s.y,p=o.y,f=al?a>u?a:u:l>u?l:u,m=c>h?c>p?c:p:h>p?h:p,g=ya(f,d,e,r,n),x=ya(y,m,e,r,n);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==o&&ga(a,c,l,h,u,p,v.x,v.y)&&va(v.prev,v,v.next)>=0)return!1;if(v=v.prevZ,b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==o&&ga(a,c,l,h,u,p,b.x,b.y)&&va(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==o&&ga(a,c,l,h,u,p,v.x,v.y)&&va(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==o&&ga(a,c,l,h,u,p,b.x,b.y)&&va(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function ca(t,e){let r=t;do{const n=r.prev,i=r.next.next;!ba(n,i)&&wa(n,r,r.next,i)&&ka(n,i)&&ka(i,n)&&(e.push(n.i,r.i,i.i),Ma(r),Ma(r.next),r=t=i),r=r.next}while(r!==t);return oa(r)}function ha(t,e,r,n,i,s){let o=t;do{let t=o.next.next;for(;t!==o.prev;){if(o.i!==t.i&&xa(o,t)){let a=Aa(o,t);return o=oa(o,o.next),a=oa(a,a.next),aa(o,e,r,n,i,s,0),void aa(a,e,r,n,i,s,0)}t=t.next}o=o.next}while(o!==t)}function pa(t,e){return t.x-e.x}function fa(t,e){const r=function(t,e){let r=e;const n=t.x,i=t.y;let s,o=-1/0;do{if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){const t=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(t<=n&&t>o&&(o=t,s=r.x=r.x&&r.x>=l&&n!==r.x&&ga(is.x||r.x===s.x&&da(s,r)))&&(s=r,c=e)}r=r.next}while(r!==a);return s}(t,e);if(!r)return e;const n=Aa(r,t);return oa(n,n.next),oa(r,r.next)}function da(t,e){return va(t.prev,t,e.prev)<0&&va(e.next,t,t.next)<0}function ya(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function ma(t){let e=t,r=t;do{(e.x=(t-o)*(s-a)&&(t-o)*(n-a)>=(r-o)*(e-a)&&(r-o)*(s-a)>=(i-o)*(n-a)}function xa(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&wa(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&(ka(t,e)&&ka(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{r.y>s!=r.next.y>s&&r.next.y!==r.y&&i<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)&&(va(t.prev,t,e.prev)||va(t,e.prev,e))||ba(t,e)&&va(t.prev,t,t.next)>0&&va(e.prev,e,e.next)>0)}function va(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function ba(t,e){return t.x===e.x&&t.y===e.y}function wa(t,e,r,n){const i=Sa(va(t,e,r)),s=Sa(va(t,e,n)),o=Sa(va(r,n,t)),a=Sa(va(r,n,e));return i!==s&&o!==a||!(0!==i||!_a(t,r,e))||!(0!==s||!_a(t,n,e))||!(0!==o||!_a(r,t,n))||!(0!==a||!_a(r,e,n))}function _a(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function Sa(t){return t>0?1:t<0?-1:0}function ka(t,e){return va(t.prev,t,t.next)<0?va(t,e,t.next)>=0&&va(t,t.prev,e)>=0:va(t,e,t.prev)<0||va(t,t.next,e)<0}function Aa(t,e){const r=za(t.i,t.x,t.y),n=za(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,s.next=n,n.prev=s,n}function Ia(t,e,r,n){const i=za(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Ma(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function za(t,e,r){return{i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function Pa(t,e,r){const n=r.patternDependencies;let i=!1;for(const r of e){const e=r.paint.get(`${t}-pattern`);e.isConstant()||(i=!0);const s=e.constantOr(null);s&&(i=!0,n[s.to]=!0,n[s.from]=!0)}return i}function Ca(t,e,r,n,i){const s=i.patternDependencies;for(const o of e){const e=o.paint.get(`${t}-pattern`).value;if("constant"!==e.kind){let t=e.evaluate({zoom:n-1},r,{},i.availableImages),a=e.evaluate({zoom:n},r,{},i.availableImages),l=e.evaluate({zoom:n+1},r,{},i.availableImages);t=t&&t.name?t.name:t,a=a&&a.name?a.name:a,l=l&&l.name?l.name:l,s[t]=!0,s[a]=!0,s[l]=!0,r.patterns[o.id]={min:t,mid:a,max:l}}}return r}class Ba{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new ks,this.indexArray=new Es,this.indexArray2=new Fs,this.programConfigurations=new uo(t.layers,t.zoom),this.segments=new Ls,this.segments2=new Ls,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id))}populate(t,e,r){this.hasPattern=Pa("fill",this.layers,e);const n=this.layers[0].layout.get("fill-sort-key"),i=!n.isConstant(),s=[];for(const{feature:o,id:a,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=go(o,t);if(!this.layers[0]._featureFilter.filter(new vi(this.zoom),c,r))continue;const h=i?n.evaluate(c,{},r,e.availableImages):void 0,p={id:a,properties:o.properties,type:o.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:mo(o),patterns:{},sortKey:h};s.push(p)}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:o}=n;if(this.hasPattern){const t=Ca("fill",this.layers,n,this.zoom,e);this.patternFeatures.push(t)}else this.addFeature(n,i,s,r,{});e.featureIndex.insert(t[s].feature,i,s,o,this.index)}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r)}addFeatures(t,e,r){for(const t of this.patternFeatures)this.addFeature(t,t.geometry,t.index,e,r)}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,na),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy())}addFeature(t,e,r,n,i){for(const t of $e(e,500)){let e=0;for(const r of t)e+=r.length;const r=this.segments.prepareSegment(e,this.layoutVertexArray,this.indexArray),n=r.vertexLength,i=[],s=[];for(const e of t){if(0===e.length)continue;e!==t[0]&&s.push(i.length/2);const r=this.segments2.prepareSegment(e.length,this.layoutVertexArray,this.indexArray2),n=r.vertexLength;this.layoutVertexArray.emplaceBack(e[0].x,e[0].y),this.indexArray2.emplaceBack(n+e.length-1,n),i.push(e[0].x),i.push(e[0].y);for(let t=1;t>3}if(i--,1===n||2===n)s+=t.readSVarint(),o+=t.readSVarint(),1===n&&(e&&a.push(e),e=[]),e.push(new Ra(s,o));else{if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone())}}return e&&a.push(e),a},qa.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,s=0,o=1/0,a=-1/0,l=1/0,u=-1/0;t.pos>3}if(n--,1===r||2===r)(i+=t.readSVarint())a&&(a=i),(s+=t.readSVarint())u&&(u=s);else if(7!==r)throw new Error("unknown command "+r)}return[o,l,a,u]},qa.prototype.toGeoJSON=function(t,e,r){var n,i,s=this.extent*Math.pow(2,r),o=this.extent*t,a=this.extent*e,l=this.loadGeometry(),u=qa.types[this.type];function c(t){for(var e=0;e>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null}return e}(r))}Xa.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new Za(this._pbf,e,this.extent,this._keys,this._values)};var Ya=Ga;function Ja(t,e,r){if(3===t){var n=new Ya(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n)}}Oa.VectorTile=function(t,e){this.layers=t.readFields(Ja,{},e)},Oa.VectorTileFeature=ja,Oa.VectorTileLayer=Ga;const Ka=Oa.VectorTileFeature.types,Wa=Math.pow(2,13);function Qa(t,e,r,n,i,s,o,a){t.emplaceBack(e,r,2*Math.floor(n*Wa)+o,i*Wa*2,s*Wa*2,Math.round(a))}class tl{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new As,this.centroidVertexArray=new _s,this.indexArray=new Es,this.programConfigurations=new uo(t.layers,t.zoom),this.segments=new Ls,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id))}populate(t,e,r){this.features=[],this.hasPattern=Pa("fill-extrusion",this.layers,e);for(const{feature:n,id:i,index:s,sourceLayerIndex:o}of t){const t=this.layers[0]._featureFilter.needGeometry,a=go(n,t);if(!this.layers[0]._featureFilter.filter(new vi(this.zoom),a,r))continue;const l={id:i,sourceLayerIndex:o,index:s,geometry:t?a.geometry:mo(n),properties:n.properties,type:n.type,patterns:{}};this.hasPattern?this.features.push(Ca("fill-extrusion",this.layers,l,this.zoom,e)):this.addFeature(l,l.geometry,s,r,{}),e.featureIndex.insert(n,l.geometry,s,o,this.index,!0)}}addFeatures(t,e,r){for(const t of this.features){const{geometry:n}=t;this.addFeature(t,n,t.index,e,r)}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r)}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,La),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,$a.members,!0),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy())}addFeature(t,e,r,n,i){for(const r of $e(e,500)){const e={x:0,y:0,vertexCount:0};let n=0;for(const t of r)n+=t.length;let i=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray);for(const t of r){if(0===t.length)continue;if(rl(t))continue;let r=0;for(let n=0;n=1){const o=t[n-1];if(!el(s,o)){i.vertexLength+4>Ls.MAX_VERTEX_ARRAY_LENGTH&&(i=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const t=s.sub(o)._perp()._unit(),n=o.dist(s);r+n>32768&&(r=0),Qa(this.layoutVertexArray,s.x,s.y,t.x,t.y,0,0,r),Qa(this.layoutVertexArray,s.x,s.y,t.x,t.y,0,1,r),e.x+=2*s.x,e.y+=2*s.y,e.vertexCount+=2,r+=n,Qa(this.layoutVertexArray,o.x,o.y,t.x,t.y,0,0,r),Qa(this.layoutVertexArray,o.x,o.y,t.x,t.y,0,1,r),e.x+=2*o.x,e.y+=2*o.y,e.vertexCount+=2;const a=i.vertexLength;this.indexArray.emplaceBack(a,a+2,a+1),this.indexArray.emplaceBack(a+1,a+2,a+3),i.vertexLength+=4,i.primitiveLength+=2}}}}if(i.vertexLength+n>Ls.MAX_VERTEX_ARRAY_LENGTH&&(i=this.segments.prepareSegment(n,this.layoutVertexArray,this.indexArray)),"Polygon"!==Ka[t.type])continue;const s=[],o=[],a=i.vertexLength;for(const t of r)if(0!==t.length){t!==r[0]&&o.push(s.length/2);for(let r=0;rpo)||t.y===e.y&&(t.y<0||t.y>po)}function rl(t){return t.every((t=>t.x<0))||t.every((t=>t.x>po))||t.every((t=>t.y<0))||t.every((t=>t.y>po))}let nl;qn("FillExtrusionBucket",tl,{omit:["layers","features"]});var il={get paint(){return nl=nl||new Ti({"fill-extrusion-opacity":new zi(w["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Pi(w["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new zi(w["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new zi(w["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Ci(w["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new Pi(w["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Pi(w["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new zi(w["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class sl extends Fi{constructor(t){super(t,il)}createBucket(t){return new tl(t)}queryRadius(){return Vo(this.paint.get("fill-extrusion-translate"))}is3D(){return!0}queryIntersectsFeature(t,e,r,n,s,o,a,l){const u=To(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),o.angle,a),c=this.paint.get("fill-extrusion-height").evaluate(e,r),h=this.paint.get("fill-extrusion-base").evaluate(e,r),p=function(t,e,r,n){const s=[];for(const r of t){const t=[r.x,r.y,0,1];Ro(t,t,e),s.push(new i(t[0]/t[3],t[1]/t[3]))}return s}(u,l),f=function(t,e,r,n){const s=[],o=[],a=n[8]*e,l=n[9]*e,u=n[10]*e,c=n[11]*e,h=n[8]*r,p=n[9]*r,f=n[10]*r,d=n[11]*r;for(const e of t){const t=[],r=[];for(const s of e){const e=s.x,o=s.y,y=n[0]*e+n[4]*o+n[12],m=n[1]*e+n[5]*o+n[13],g=n[2]*e+n[6]*o+n[14],x=n[3]*e+n[7]*o+n[15],v=g+u,b=x+c,w=y+h,_=m+p,S=g+f,k=x+d,A=new i((y+a)/b,(m+l)/b);A.z=v/b,t.push(A);const I=new i(w/k,_/k);I.z=S/k,r.push(I)}s.push(t),o.push(r)}return[s,o]}(n,h,c,l);return function(t,e,r){let n=1/0;_o(r,e)&&(n=al(r,e[0]));for(let i=0;it.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={}})),this.layoutVertexArray=new Is,this.layoutVertexArray2=new Ms,this.indexArray=new Es,this.programConfigurations=new uo(t.layers,t.zoom),this.segments=new Ls,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id))}populate(t,e,r){this.hasPattern=Pa("line",this.layers,e);const n=this.layers[0].layout.get("line-sort-key"),i=!n.isConstant(),s=[];for(const{feature:e,id:o,index:a,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=go(e,t);if(!this.layers[0]._featureFilter.filter(new vi(this.zoom),u,r))continue;const c=i?n.evaluate(u,{},r):void 0,h={id:o,properties:e.properties,type:e.type,sourceLayerIndex:l,index:a,geometry:t?u.geometry:mo(e),patterns:{},sortKey:c};s.push(h)}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:o}=n;if(this.hasPattern){const t=Ca("line",this.layers,n,this.zoom,e);this.patternFeatures.push(t)}else this.addFeature(n,i,s,r,{});e.featureIndex.insert(t[s].feature,i,s,o,this.index)}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r)}addFeatures(t,e,r){for(const t of this.patternFeatures)this.addFeature(t,t.geometry,t.index,e,r)}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,hl)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,ul),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_end"))return{start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,r,n,i){const s=this.layers[0].layout,o=s.get("line-join").evaluate(t,{}),a=s.get("line-cap"),l=s.get("line-miter-limit"),u=s.get("line-round-limit");this.lineClips=this.lineFeatureClips(t);for(const r of e)this.addLine(r,t,o,a,l,u);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n)}addLine(t,e,r,n,i,s){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[a-1].equals(t[a-2]);)a--;let l=0;for(;l0;if(w&&e>l){const t=h.dist(p);if(t>2*u){const e=h.sub(h.sub(p)._mult(u/t)._round());this.updateDistance(p,e),this.addCurrentVertex(e,d,0,0,c),p=e}}const S=p&&f;let k=S?r:o?"butt":n;if(S&&"round"===k&&(vi&&(k="bevel"),"bevel"===k&&(v>2&&(k="flipbevel"),v100)m=y.mult(-1);else{const t=v*d.add(y).mag()/d.sub(y).mag();m._perp()._mult(t*(_?-1:1))}this.addCurrentVertex(h,m,0,0,c),this.addCurrentVertex(h,m.mult(-1),0,0,c)}else if("bevel"===k||"fakeround"===k){const t=-Math.sqrt(v*v-1),e=_?t:0,r=_?0:t;if(p&&this.addCurrentVertex(h,d,e,r,c),"fakeround"===k){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*u){const e=h.add(f.sub(h)._mult(u/t)._round());this.updateDistance(h,e),this.addCurrentVertex(e,y,0,0,c),h=e}}}}addCurrentVertex(t,e,r,n,i,s=!1){const o=e.y*n-e.x,a=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,s,!1,r,i),this.addHalfVertex(t,o,a,s,!0,-n,i),this.distance>dl/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,r,n,i,s))}addHalfVertex({x:t,y:e},r,n,i,s,o,a){const l=.5*(this.lineClips?this.scaledDistance*(dl-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*r)+128,Math.round(63*n)+128,1+(0===o?0:o<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const u=a.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,u),a.primitiveLength++),s?this.e2=u:this.e1=u}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance()}}let ml,gl;qn("LineBucket",yl,{omit:["layers","patternFeatures"]});var xl={get paint(){return gl=gl||new Ti({"line-opacity":new Pi(w.paint_line["line-opacity"]),"line-color":new Pi(w.paint_line["line-color"]),"line-translate":new zi(w.paint_line["line-translate"]),"line-translate-anchor":new zi(w.paint_line["line-translate-anchor"]),"line-width":new Pi(w.paint_line["line-width"]),"line-gap-width":new Pi(w.paint_line["line-gap-width"]),"line-offset":new Pi(w.paint_line["line-offset"]),"line-blur":new Pi(w.paint_line["line-blur"]),"line-dasharray":new Bi(w.paint_line["line-dasharray"]),"line-pattern":new Ci(w.paint_line["line-pattern"]),"line-gradient":new Vi(w.paint_line["line-gradient"])})},get layout(){return ml=ml||new Ti({"line-cap":new zi(w.layout_line["line-cap"]),"line-join":new Pi(w.layout_line["line-join"]),"line-miter-limit":new zi(w.layout_line["line-miter-limit"]),"line-round-limit":new zi(w.layout_line["line-round-limit"]),"line-sort-key":new Pi(w.layout_line["line-sort-key"])})}};class vl extends Pi{possiblyEvaluate(t,e){return e=new vi(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,r,n){return e=c({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,r,n)}}let bl;class wl extends Fi{constructor(t){super(t,xl),this.gradientVersion=0,bl||(bl=new vl(xl.paint.properties["line-width"].specification),bl.useIntegerZoom=!0)}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return void 0!==t._styleExpression}(t)&&t._styleExpression.expression instanceof qt,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=bl.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t)}createBucket(t){return new yl(t)}queryRadius(t){const e=t,r=_l(Bo("line-width",this,e),Bo("line-gap-width",this,e)),n=Bo("line-offset",this,e);return r/2+Math.abs(n)+Vo(this.paint.get("line-translate"))}queryIntersectsFeature(t,e,r,n,s,o,a){const l=To(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),o.angle,a),u=a/2*_l(this.paint.get("line-width").evaluate(e,r),this.paint.get("line-gap-width").evaluate(e,r)),c=this.paint.get("line-offset").evaluate(e,r);return c&&(n=function(t,e){const r=[];for(let n=0;n=3)for(let e=0;e0?e+2*t:t}const Sl=Oi([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),kl=Oi([{name:"a_projected_pos",components:3,type:"Float32"}],4);Oi([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Al=Oi([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);Oi([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const Il=Oi([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4);function Ml(t,e,r){return t.sections.forEach((t=>{t.text=function(t,e,r){const n=e.layout.get("text-transform").evaluate(r,{});return"uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),xi.applyArabicShaping&&(t=xi.applyArabicShaping(t)),t}(t.text,e,r)})),t}Oi([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4),Oi([{name:"triangle",components:3,type:"Uint16"}]),Oi([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Oi([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),Oi([{type:"Float32",name:"offsetX"}]),Oi([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),Oi([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const zl={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var Pl=24,Cl=Tl,Bl=function(t,e,r,n,i){var s,o,a=8*i-n-1,l=(1<>1,c=-7,h=r?i-1:0,p=r?-1:1,f=t[e+h];for(h+=p,s=f&(1<<-c)-1,f>>=-c,c+=a;c>0;s=256*s+t[e+h],h+=p,c-=8);for(o=s&(1<<-c)-1,s>>=-c,c+=n;c>0;o=256*o+t[e+h],h+=p,c-=8);if(0===s)s=1-u;else{if(s===l)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,n),s-=u}return(f?-1:1)*o*Math.pow(2,s-n)},Vl=function(t,e,r,n,i,s){var o,a,l,u=8*s-i-1,c=(1<>1,p=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:s-1,d=n?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),(e+=o+h>=1?p/l:p*Math.pow(2,1-h))*l>=2&&(o++,l/=2),o+h>=c?(a=0,o=c):o+h>=1?(a=(e*l-1)*Math.pow(2,i),o+=h):(a=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+f]=255&a,f+=d,a/=256,i-=8);for(o=o<0;t[r+f]=255&o,f+=d,o/=256,u-=8);t[r+f-d]|=128*y};function Tl(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length}Tl.Varint=0,Tl.Fixed64=1,Tl.Bytes=2,Tl.Fixed32=5;var El=4294967296,Fl=1/El,Dl="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");function $l(t){return t.type===Tl.Bytes?t.readVarint()+t.pos:t.pos+1}function Ll(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function Ol(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i]}function Rl(t,e){for(var r=0;r>>8,t[r+2]=e>>>16,t[r+3]=e>>>24}function Kl(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}Tl.prototype={destroy:function(){this.buf=null},readFields:function(t,e,r){for(r=r||this.length;this.pos>3,s=this.pos;this.type=7&n,t(i,e,this),this.pos===s&&this.skip(n)}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=Yl(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=Kl(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=Yl(this.buf,this.pos)+Yl(this.buf,this.pos+4)*El;return this.pos+=8,t},readSFixed64:function(){var t=Yl(this.buf,this.pos)+Kl(this.buf,this.pos+4)*El;return this.pos+=8,t},readFloat:function(){var t=Bl(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=Bl(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,s=r.buf;if(n=(112&(i=s[r.pos++]))>>4,i<128)return Ll(t,n,e);if(n|=(127&(i=s[r.pos++]))<<3,i<128)return Ll(t,n,e);if(n|=(127&(i=s[r.pos++]))<<10,i<128)return Ll(t,n,e);if(n|=(127&(i=s[r.pos++]))<<17,i<128)return Ll(t,n,e);if(n|=(127&(i=s[r.pos++]))<<24,i<128)return Ll(t,n,e);if(n|=(1&(i=s[r.pos++]))<<31,i<128)return Ll(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&Dl?function(t,e,r){return Dl.decode(t.subarray(e,r))}(this.buf,e,t):function(t,e,r){for(var n="",i=e;i239?4:l>223?3:l>191?2:1;if(i+c>r)break;1===c?l<128&&(u=l):2===c?128==(192&(s=t[i+1]))&&(u=(31&l)<<6|63&s)<=127&&(u=null):3===c?(o=t[i+2],128==(192&(s=t[i+1]))&&128==(192&o)&&((u=(15&l)<<12|(63&s)<<6|63&o)<=2047||u>=55296&&u<=57343)&&(u=null)):4===c&&(o=t[i+2],a=t[i+3],128==(192&(s=t[i+1]))&&128==(192&o)&&128==(192&a)&&((u=(15&l)<<18|(63&s)<<12|(63&o)<<6|63&a)<=65535||u>=1114112)&&(u=null)),null===u?(u=65533,c=1):u>65535&&(u-=65536,n+=String.fromCharCode(u>>>10&1023|55296),u=56320|1023&u),n+=String.fromCharCode(u),i+=c}return n}(this.buf,e,t)},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){if(this.type!==Tl.Bytes)return t.push(this.readVarint(e));var r=$l(this);for(t=t||[];this.pos127;);else if(e===Tl.Bytes)this.pos=this.readVarint()+this.pos;else if(e===Tl.Fixed32)this.pos+=4;else{if(e!==Tl.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(t,e){this.writeVarint(t<<3|e)},realloc:function(t){for(var e=this.length||16;e268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7)}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))))}(n,e)}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))))},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t)},writeBoolean:function(t){this.writeVarint(Boolean(t))},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,s=0;s55295&&n<57344){if(!i){n>56319||s+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128)}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&Ol(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r},writeFloat:function(t){this.realloc(4),Vl(this.buf,t,this.pos,!0,23,4),this.pos+=4},writeDouble:function(t){this.realloc(8),Vl(this.buf,t,this.pos,!0,52,8),this.pos+=8},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&Ol(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n},writeMessage:function(t,e,r){this.writeTag(t,Tl.Bytes),this.writeRawMessage(e,r)},writePackedVarint:function(t,e){e.length&&this.writeMessage(t,Rl,e)},writePackedSVarint:function(t,e){e.length&&this.writeMessage(t,jl,e)},writePackedBoolean:function(t,e){e.length&&this.writeMessage(t,Nl,e)},writePackedFloat:function(t,e){e.length&&this.writeMessage(t,ql,e)},writePackedDouble:function(t,e){e.length&&this.writeMessage(t,Ul,e)},writePackedFixed32:function(t,e){e.length&&this.writeMessage(t,Zl,e)},writePackedSFixed32:function(t,e){e.length&&this.writeMessage(t,Gl,e)},writePackedFixed64:function(t,e){e.length&&this.writeMessage(t,Xl,e)},writePackedSFixed64:function(t,e){e.length&&this.writeMessage(t,Hl,e)},writeBytesField:function(t,e){this.writeTag(t,Tl.Bytes),this.writeBytes(e)},writeFixed32Field:function(t,e){this.writeTag(t,Tl.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(t,e){this.writeTag(t,Tl.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(t,e){this.writeTag(t,Tl.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(t,e){this.writeTag(t,Tl.Fixed64),this.writeSFixed64(e)},writeVarintField:function(t,e){this.writeTag(t,Tl.Varint),this.writeVarint(e)},writeSVarintField:function(t,e){this.writeTag(t,Tl.Varint),this.writeSVarint(e)},writeStringField:function(t,e){this.writeTag(t,Tl.Bytes),this.writeString(e)},writeFloatField:function(t,e){this.writeTag(t,Tl.Fixed32),this.writeFloat(e)},writeDoubleField:function(t,e){this.writeTag(t,Tl.Fixed64),this.writeDouble(e)},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e))}};var Wl=e(Cl);const Ql=3;function tu(t){let e=0,r=0;for(const n of t)e+=n.w*n.h,r=Math.max(r,n.w);t.sort(((t,e)=>e.h-t.h));const n=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}];let i=0,s=0;for(const e of t)for(let t=n.length-1;t>=0;t--){const r=n[t];if(!(e.w>r.w||e.h>r.h)){if(e.x=r.x,e.y=r.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===r.w&&e.h===r.h){const e=n.pop();t=0&&r>=t&&uu[this.text.charCodeAt(r)];r--)e--;this.text=this.text.substring(t,e),this.sectionIndex=this.sectionIndex.slice(t,e)}substring(t,e){const r=new au;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((t,e)=>Math.max(t,this.sections[e].scale)),0)}addTextSection(t,e){this.text+=t.text,this.sections.push(ou.forText(t.scale,t.fontStack||e));const r=this.sections.length-1;for(let e=0;e=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function lu(t,e,r,n,i,s,o,a,l,u,c,h,p,f,d){const y=au.fromFeature(t,i);let m;h===iu.vertical&&y.verticalizePunctuation();const{processBidirectionalText:g,processStyledBidirectionalText:x}=xi;if(g&&1===y.sections.length){m=[];const t=g(y.toString(),gu(y,u,s,e,n,f));for(const e of t){const t=new au;t.text=e,t.sections=y.sections;for(let r=0;r0&&s>w&&(w=s)}else{const t=r[d.fontStack],n=t&&t[m];if(n&&n.rect)_=n.rect,v=n.metrics;else{const t=e[d.fontStack],r=t&&t[m];if(!r)continue;v=r.metrics}g=(i-d.scale)*Pl}A?(t.verticalizable=!0,b.push({glyph:m,imageName:S,x:p,y:f+g,vertical:A,scale:d.scale,fontStack:d.fontStack,sectionIndex:y,metrics:v,rect:_}),p+=k*d.scale+u):(b.push({glyph:m,imageName:S,x:p,y:f+g,vertical:A,scale:d.scale,fontStack:d.fontStack,sectionIndex:y,metrics:v,rect:_}),p+=v.advance*d.scale+u)}0!==b.length&&(d=Math.max(p-u,d),vu(b,0,b.length-1,m,w)),p=0;const _=s*i+w;v.lineOffset=Math.max(w,a),f+=_,y=Math.max(_,y),++g}var x;const v=f-su,{horizontalAlign:b,verticalAlign:w}=xu(o);(function(t,e,r,n,i,s,o,a,l){const u=(e-r)*i;let c=0;c=s!==o?-a*n-su:(-n*l+.5)*o;for(const e of t)for(const t of e.positionedGlyphs)t.x+=u,t.y+=c})(t.positionedLines,m,b,w,d,y,s,v,i.length),t.top+=-w*v,t.bottom=t.top+v,t.left+=-b*d,t.right=t.left+d}(b,e,r,n,m,o,a,l,h,u,p,d),!function(t){for(const e of t)if(0!==e.positionedGlyphs.length)return!1;return!0}(v)&&b}const uu={9:!0,10:!0,11:!0,12:!0,13:!0,32:!0},cu={10:!0,32:!0,38:!0,41:!0,43:!0,45:!0,47:!0,173:!0,183:!0,8203:!0,8208:!0,8211:!0,8231:!0},hu={40:!0};function pu(t,e,r,n,i,s){if(e.imageName){const t=n[e.imageName];return t?t.displaySize[0]*e.scale*Pl/s+i:0}{const n=r[e.fontStack],s=n&&n[t];return s?s.metrics.advance*e.scale+i:0}}function fu(t,e,r,n){const i=Math.pow(t-e,2);return n?t=0;let u=0;for(let r=0;ru){const t=Math.ceil(s/u);i*=t/o,o=t}return{x1:n,y1:i,x2:n+s,y2:i+o}}function _u(t,e,r,n,i,s){const o=t.image;let a;if(o.content){const t=o.content,e=o.pixelRatio||1;a=[t[0]/e,t[1]/e,o.displaySize[0]-t[2]/e,o.displaySize[1]-t[3]/e]}const l=e.left*s,u=e.right*s;let c,h,p,f;"width"===r||"both"===r?(f=i[0]+l-n[3],h=i[0]+u+n[1]):(f=i[0]+(l+u-o.displaySize[0])/2,h=f+o.displaySize[0]);const d=e.top*s,y=e.bottom*s;return"height"===r||"both"===r?(c=i[1]+d-n[0],p=i[1]+y+n[2]):(c=i[1]+(d+y-o.displaySize[1])/2,p=c+o.displaySize[1]),{image:o,top:c,right:h,bottom:p,left:f,collisionPadding:a}}const Su=255,ku=128,Au=Su*ku;function Iu(t,e){const{expression:r}=e;if("constant"===r.kind)return{kind:"constant",layoutSize:r.evaluate(new vi(t+1))};if("source"===r.kind)return{kind:"source"};{const{zoomStops:e,interpolationType:n}=r;let i=0;for(;it.id)),this.index=t.index,this.pixelRatio=t.pixelRatio,this.sourceLayerIndex=t.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=Oo([]),this.placementViewportMatrix=Oo([]);const e=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Iu(this.zoom,e["text-size"]),this.iconSizeData=Iu(this.zoom,e["icon-size"]);const r=this.layers[0].layout,n=r.get("symbol-sort-key"),i=r.get("symbol-z-order");this.canOverlap="never"!==Mu(r,"text-overlap","text-allow-overlap")||"never"!==Mu(r,"icon-overlap","icon-allow-overlap")||r.get("text-ignore-placement")||r.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==i&&!n.isConstant(),this.sortFeaturesByY=("viewport-y"===i||"auto"===i&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===r.get("symbol-placement")&&(this.writingModes=r.get("text-writing-mode").map((t=>iu[t]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=t.sourceID}createArrays(){this.text=new Tu(new uo(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new Tu(new uo(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new ms,this.lineVertexArray=new gs,this.symbolInstances=new ys,this.textAnchorOffsets=new vs}calculateGlyphDependencies(t,e,r,n,i){for(let s=0;s0)&&("constant"!==s.value.kind||s.value.value.length>0),u="constant"!==a.value.kind||!!a.value.value||Object.keys(a.parameters).length>0,c=i.get("symbol-sort-key");if(this.features=[],!l&&!u)return;const h=e.iconDependencies,p=e.glyphDependencies,f=e.availableImages,d=new vi(this.zoom);for(const{feature:e,id:o,index:a,sourceLayerIndex:y}of t){const t=n._featureFilter.needGeometry,m=go(e,t);if(!n._featureFilter.filter(d,m,r))continue;let g,x;if(t||(m.geometry=mo(e)),l){const t=n.getValueAndResolveTokens("text-field",m,r,f),e=yt.factory(t),i=this.hasRTLText=this.hasRTLText||Vu(e);(!i||"unavailable"===xi.getRTLTextPluginStatus()||i&&xi.isParsed())&&(g=Ml(e,n,m))}if(u){const t=n.getValueAndResolveTokens("icon-image",m,r,f);x=t instanceof vt?t:vt.fromString(t)}if(!g&&!x)continue;const v=this.sortFeaturesByKey?c.evaluate(m,{},r):void 0;if(this.features.push({id:o,text:g,icon:x,index:a,sourceLayerIndex:y,geometry:m.geometry,properties:e.properties,type:zu[e.type],sortKey:v}),x&&(h[x.name]=!0),g){const t=s.evaluate(m,{},r).join(","),e="viewport"!==i.get("text-rotation-alignment")&&"point"!==i.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(iu.vertical)>=0;for(const r of g.sections)if(r.image)h[r.image.name]=!0;else{const n=oi(g.toString()),i=r.fontStack||t,s=p[i]=p[i]||{};this.calculateGlyphDependencies(r.text,s,e,this.allowVerticalPlacement,n)}}}"line"===i.get("symbol-placement")&&(this.features=function(t){const e={},r={},n=[];let i=0;function s(e){n.push(t[e]),i++}function o(t,e,i){const s=r[t];return delete r[t],r[e]=s,n[s].geometry[0].pop(),n[s].geometry[0]=n[s].geometry[0].concat(i[0]),s}function a(t,r,i){const s=e[r];return delete e[r],e[t]=s,n[s].geometry[0].shift(),n[s].geometry[0]=i[0].concat(n[s].geometry[0]),s}function l(t,e,r){const n=r?e[0][e[0].length-1]:e[0][0];return`${t}:${n.x}:${n.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey))}update(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,r),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,r))}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(t,e){const r=this.lineVertexArray.length;if(void 0!==t.segment){let r=t.dist(e[t.segment+1]),n=t.dist(e[t.segment]);const i={};for(let n=t.segment+1;n=0;r--)i[r]={x:e[r].x,y:e[r].y,tileUnitDistanceFromAnchor:n},r>0&&(n+=e[r-1].dist(e[r]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs;for(let e=r.vertexStartIndex;en[t]-n[e]||i[e]-i[t])),s}addToSortKeyRanges(t,e){const r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1})}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,r)=>{t>=0&&r.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t)})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}}let Du,$u;qn("SymbolBucket",Fu,{omit:["layers","collisionBoxArray","features","compareText"]}),Fu.MAX_GLYPHS=65535,Fu.addDynamicAttributes=Bu;var Lu={get paint(){return $u=$u||new Ti({"icon-opacity":new Pi(w.paint_symbol["icon-opacity"]),"icon-color":new Pi(w.paint_symbol["icon-color"]),"icon-halo-color":new Pi(w.paint_symbol["icon-halo-color"]),"icon-halo-width":new Pi(w.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Pi(w.paint_symbol["icon-halo-blur"]),"icon-translate":new zi(w.paint_symbol["icon-translate"]),"icon-translate-anchor":new zi(w.paint_symbol["icon-translate-anchor"]),"text-opacity":new Pi(w.paint_symbol["text-opacity"]),"text-color":new Pi(w.paint_symbol["text-color"],{runtimeType:B,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new Pi(w.paint_symbol["text-halo-color"]),"text-halo-width":new Pi(w.paint_symbol["text-halo-width"]),"text-halo-blur":new Pi(w.paint_symbol["text-halo-blur"]),"text-translate":new zi(w.paint_symbol["text-translate"]),"text-translate-anchor":new zi(w.paint_symbol["text-translate-anchor"])})},get layout(){return Du=Du||new Ti({"symbol-placement":new zi(w.layout_symbol["symbol-placement"]),"symbol-spacing":new zi(w.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new zi(w.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Pi(w.layout_symbol["symbol-sort-key"]),"symbol-z-order":new zi(w.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new zi(w.layout_symbol["icon-allow-overlap"]),"icon-overlap":new zi(w.layout_symbol["icon-overlap"]),"icon-ignore-placement":new zi(w.layout_symbol["icon-ignore-placement"]),"icon-optional":new zi(w.layout_symbol["icon-optional"]),"icon-rotation-alignment":new zi(w.layout_symbol["icon-rotation-alignment"]),"icon-size":new Pi(w.layout_symbol["icon-size"]),"icon-text-fit":new zi(w.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new zi(w.layout_symbol["icon-text-fit-padding"]),"icon-image":new Pi(w.layout_symbol["icon-image"]),"icon-rotate":new Pi(w.layout_symbol["icon-rotate"]),"icon-padding":new Pi(w.layout_symbol["icon-padding"]),"icon-keep-upright":new zi(w.layout_symbol["icon-keep-upright"]),"icon-offset":new Pi(w.layout_symbol["icon-offset"]),"icon-anchor":new Pi(w.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new zi(w.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new zi(w.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new zi(w.layout_symbol["text-rotation-alignment"]),"text-field":new Pi(w.layout_symbol["text-field"]),"text-font":new Pi(w.layout_symbol["text-font"]),"text-size":new Pi(w.layout_symbol["text-size"]),"text-max-width":new Pi(w.layout_symbol["text-max-width"]),"text-line-height":new zi(w.layout_symbol["text-line-height"]),"text-letter-spacing":new Pi(w.layout_symbol["text-letter-spacing"]),"text-justify":new Pi(w.layout_symbol["text-justify"]),"text-radial-offset":new Pi(w.layout_symbol["text-radial-offset"]),"text-variable-anchor":new zi(w.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new Pi(w.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new Pi(w.layout_symbol["text-anchor"]),"text-max-angle":new zi(w.layout_symbol["text-max-angle"]),"text-writing-mode":new zi(w.layout_symbol["text-writing-mode"]),"text-rotate":new Pi(w.layout_symbol["text-rotate"]),"text-padding":new zi(w.layout_symbol["text-padding"]),"text-keep-upright":new zi(w.layout_symbol["text-keep-upright"]),"text-transform":new Pi(w.layout_symbol["text-transform"]),"text-offset":new Pi(w.layout_symbol["text-offset"]),"text-allow-overlap":new zi(w.layout_symbol["text-allow-overlap"]),"text-overlap":new zi(w.layout_symbol["text-overlap"]),"text-ignore-placement":new zi(w.layout_symbol["text-ignore-placement"]),"text-optional":new zi(w.layout_symbol["text-optional"])})}};class Ou{constructor(t){if(void 0===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:M,this.defaultValue=t}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}qn("FormatSectionOverride",Ou,{omit:["defaultValue"]});class Ru extends Fi{constructor(t){super(t,Lu)}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const r of t)e.indexOf(r)<0&&e.push(r);this.layout._values["text-writing-mode"]=e}else this.layout._values["text-writing-mode"]=["horizontal"]}this._setPaintOverrides()}getValueAndResolveTokens(t,e,r,n){const i=this.layout.get(t).evaluate(e,{},r,n),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||$r(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,r)=>t&&r in t?String(t[r]):""))}(e.properties,i)}createBucket(t){return new Fu(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of Lu.paint.overridableProperties){if(!Ru.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),r=new Ou(e),n=new Dr(r,e.property.specification);let i=null;i="constant"===e.value.kind||"source"===e.value.kind?new Or("source",n):new Rr("composite",n,e.value.zoomStops),this.paint._values[t]=new Ii(e.property,i,e.parameters)}}_handleOverridablePaintPropertyUpdate(t,e,r){return!(!this.layout||e.isDataDriven()||r.isDataDriven())&&Ru.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const r=t.get("text-field"),n=Lu.paint.properties[e];let i=!1;const s=t=>{for(const e of t)if(n.overrides&&n.overrides.hasOverride(e))return void(i=!0)};if("constant"===r.value.kind&&r.value.value instanceof yt)s(r.value.value.sections);else if("source"===r.value.kind){const t=e=>{i||(e instanceof kt&&_t(e.value)===F?s(e.value.sections):e instanceof ce?s(e.sections):e.eachChild(t))},e=r.value;e._styleExpression&&t(e._styleExpression.expression)}return i}}let ju;var qu={get paint(){return ju=ju||new Ti({"background-color":new zi(w.paint_background["background-color"]),"background-pattern":new Bi(w.paint_background["background-pattern"]),"background-opacity":new zi(w.paint_background["background-opacity"])})}};class Uu extends Fi{constructor(t){super(t,qu)}}let Nu;var Zu={get paint(){return Nu=Nu||new Ti({"raster-opacity":new zi(w.paint_raster["raster-opacity"]),"raster-hue-rotate":new zi(w.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new zi(w.paint_raster["raster-brightness-min"]),"raster-brightness-max":new zi(w.paint_raster["raster-brightness-max"]),"raster-saturation":new zi(w.paint_raster["raster-saturation"]),"raster-contrast":new zi(w.paint_raster["raster-contrast"]),"raster-resampling":new zi(w.paint_raster["raster-resampling"]),"raster-fade-duration":new zi(w.paint_raster["raster-fade-duration"])})}};class Gu extends Fi{constructor(t){super(t,Zu)}}class Xu extends Fi{constructor(t){super(t,{}),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl)},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl)},this.implementation=t}is3D(){return"3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){throw new Error("Custom layers cannot be serialized")}}function Hu(t){if("custom"===t.type)return new Xu(t);switch(t.type){case"background":return new Uu(t);case"circle":return new jo(t);case"fill":return new Fa(t);case"fill-extrusion":return new sl(t);case"heatmap":return new Wo(t);case"hillshade":return new ea(t);case"line":return new wl(t);case"raster":return new Gu(t);case"symbol":return new Ru(t)}}class Yu{constructor(t){this.keyCache={},t&&this.replace(t)}replace(t){this._layerConfigs={},this._layers={},this.update(t,[])}update(t,e){for(const e of t){this._layerConfigs[e.id]=e;const t=this._layers[e.id]=Hu(e);t._featureFilter=Gr(t.filter),this.keyCache[e.id]&&delete this.keyCache[e.id]}for(const t of e)delete this.keyCache[t],delete this._layerConfigs[t],delete this._layers[t];this.familiesBySource={};const r=function(t,e){const r={};for(let n=0;nthis._layers[t.id])),r=e[0];if("none"===r.visibility)continue;const n=r.source||"";let i=this.familiesBySource[n];i||(i=this.familiesBySource[n]={});const s=r.sourceLayer||"_geojsonTileLayer";let o=i[s];o||(o=i[s]=[]),o.push(e)}}}class Ju{constructor(t){this._stringToNumber={},this._numberToString=[];for(let e=0;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class Ku{constructor(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(t){this._geometry=t}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t}}class Wu{constructor(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new b(po,16,0),this.grid3D=new b(po,16,0),this.featureIndexArray=new ws,this.promoteId=e}insert(t,e,r,n,i,s){const o=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);const a=s?this.grid3D:this.grid;for(let t=0;t=0&&n[3]>=0&&a.insert(o,n[0],n[1],n[2],n[3])}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new Oa.VectorTile(new Wl(this.rawTileData)).layers,this.sourceLayerCoder=new Ju(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(t,e,r,n){this.loadVTLayers();const s=t.params||{},o=po/t.tileSize/t.scale,a=Gr(s.filter),l=t.queryGeometry,u=t.queryPadding*o,c=tc(l),h=this.grid.query(c.minX-u,c.minY-u,c.maxX+u,c.maxY+u),p=tc(t.cameraQueryGeometry),f=this.grid3D.query(p.minX-u,p.minY-u,p.maxX+u,p.maxY+u,((e,r,n,s)=>function(t,e,r,n,s){for(const i of t)if(e<=i.x&&r<=i.y&&n>=i.x&&s>=i.y)return!0;const o=[new i(e,r),new i(e,s),new i(n,s),new i(n,r)];if(t.length>2)for(const e of o)if(Po(t,e))return!0;for(let e=0;e(p||(p=mo(e)),r.queryIntersectsFeature(l,e,n,p,this.z,t.transform,o,t.pixelPosMatrix))))}return d}loadMatchingFeature(t,e,r,n,i,s,o,a,l,u,h){const p=this.bucketLayerIDs[e];if(s&&!function(t,e){for(let r=0;r=0)return!0;return!1}(s,p))return;const f=this.sourceLayerCoder.decode(r),d=this.vtLayers[f].feature(n);if(i.needGeometry){const t=go(d,!0);if(!i.filter(new vi(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!i.filter(new vi(this.tileID.overscaledZ),d))return;const y=this.getId(d,f);for(let e=0;e{const o=e instanceof Mi?e.get(s):null;return o&&o.evaluate?o.evaluate(r,n,i):o}))}function tc(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return{minX:e,minY:r,maxX:n,maxY:i}}function ec(t,e){return e-t}qn("FeatureIndex",Wu,{omit:["rawTileData","sourceLayerCoder"]});class rc extends i{constructor(t,e,r,n){super(t,e),this.angle=r,void 0!==n&&(this.segment=n)}clone(){return new rc(this.x,this.y,this.angle,this.segment)}}function nc(t,e,r,n,i){if(void 0===e.segment||0===r)return!0;let s=e,o=e.segment+1,a=0;for(;a>-r/2;){if(o--,o<0)return!1;a-=t[o].dist(s),s=t[o]}a+=t[o].dist(t[o+1]),o++;const l=[];let u=0;for(;an;)u-=l.shift().angleDelta;if(u>i)return!1;o++,a+=e.dist(r)}return!0}function ic(t){let e=0;for(let r=0;ru){const c=(u-l)/s,h=Yt.number(n.x,i.x,c),p=Yt.number(n.y,i.y,c),f=new rc(h,p,i.angleTo(n),r);return f._round(),!o||nc(t,f,a,o,e)?f:void 0}l+=s}}function lc(t,e,r,n,i,s,o,a,l){const u=sc(n,s,o),c=oc(n,i),h=c*o,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const r=new rc(g,x,y,e);r._round(),n&&!nc(t,r,s,n,i)||f.push(r)}}h+=d}return a||f.length||o||(f=uc(t,h/2,r,n,i,s,o,!0,l)),f}qn("Anchor",rc);const cc=eu;function hc(t,e,r,n){const s=[],o=t.image,a=o.pixelRatio,l=o.paddedRect.w-2*cc,u=o.paddedRect.h-2*cc;let c={x1:t.left,y1:t.top,x2:t.right,y2:t.bottom};const h=o.stretchX||[[0,l]],p=o.stretchY||[[0,u]],f=(t,e)=>t+e[1]-e[0],d=h.reduce(f,0),y=p.reduce(f,0),m=l-d,g=u-y;let x=0,v=d,b=0,w=y,_=0,S=m,k=0,A=g;if(o.content&&n){const e=o.content,r=e[2]-e[0],n=e[3]-e[1];(o.textFitWidth||o.textFitHeight)&&(c=wu(t)),x=pc(h,0,e[0]),b=pc(p,0,e[1]),v=pc(h,e[0],e[2]),w=pc(p,e[1],e[3]),_=e[0]-x,k=e[1]-b,S=r-v,A=n-w}const I=c.x1,M=c.y1,z=c.x2-I,P=c.y2-M,C=(t,n,s,l)=>{const u=dc(t.stretch-x,v,z,I),c=yc(t.fixed-_,S,t.stretch,d),h=dc(n.stretch-b,w,P,M),p=yc(n.fixed-k,A,n.stretch,y),f=dc(s.stretch-x,v,z,I),m=yc(s.fixed-_,S,s.stretch,d),g=dc(l.stretch-b,w,P,M),C=yc(l.fixed-k,A,l.stretch,y),B=new i(u,h),V=new i(f,h),T=new i(f,g),E=new i(u,g),F=new i(c/a,p/a),D=new i(m/a,C/a),$=e*Math.PI/180;if($){const t=Math.sin($),e=Math.cos($),r=[e,-t,t,e];B._matMult(r),V._matMult(r),E._matMult(r),T._matMult(r)}const L=t.stretch+t.fixed,O=n.stretch+n.fixed;return{tl:B,tr:V,bl:E,br:T,tex:{x:o.paddedRect.x+cc+L,y:o.paddedRect.y+cc+O,w:s.stretch+s.fixed-L,h:l.stretch+l.fixed-O},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:F,pixelOffsetBR:D,minFontScaleX:S/a/z,minFontScaleY:A/a/P,isSDF:r}};if(n&&(o.stretchX||o.stretchY)){const t=fc(h,m,d),e=fc(p,g,y);for(let r=0;r0&&(n=Math.max(10,n),this.circleDiameter=n)}else{const u=(null===(h=o.image)||void 0===h?void 0:h.content)&&(o.image.textFitWidth||o.image.textFitHeight)?wu(o):{x1:o.left,y1:o.top,x2:o.right,y2:o.bottom};u.y1=u.y1*a-l[0],u.y2=u.y2*a+l[2],u.x1=u.x1*a-l[3],u.x2=u.x2*a+l[1];const p=o.collisionPadding;if(p&&(u.x1-=p[0]*a,u.y1-=p[1]*a,u.x2+=p[2]*a,u.y2+=p[3]*a),c){const t=new i(u.x1,u.y1),e=new i(u.x2,u.y1),r=new i(u.x1,u.y2),n=new i(u.x2,u.y2),s=c*Math.PI/180;t._rotate(s),e._rotate(s),r._rotate(s),n._rotate(s),u.x1=Math.min(t.x,e.x,r.x,n.x),u.x2=Math.max(t.x,e.x,r.x,n.x),u.y1=Math.min(t.y,e.y,r.y,n.y),u.y2=Math.max(t.y,e.y,r.y,n.y)}t.emplaceBack(e.x,e.y,u.x1,u.y1,u.x2,u.y2,r,n,s)}this.boxEndIndex=t.length}}class gc{constructor(t=[],e=((t,e)=>te?1:0)){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t)}push(t){this.data.push(t),this._up(this.length++)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return--this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i}e[t]=n}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n}e[t]=i}}function xc(t,e=1,r=!1){let n=1/0,s=1/0,o=-1/0,a=-1/0;const l=t[0];for(let t=0;to)&&(o=e.x),(!t||e.y>a)&&(a=e.y)}const u=Math.min(o-n,a-s);let c=u/2;const h=new gc([],vc);if(0===u)return new i(n,s);for(let e=n;ep.d||!p.d)&&(p=n,r&&console.log("found best %d after %d probes",Math.round(1e4*n.d)/1e4,f)),n.max-p.d<=e||(c=n.h/2,h.push(new bc(n.p.x-c,n.p.y-c,c,t)),h.push(new bc(n.p.x+c,n.p.y-c,c,t)),h.push(new bc(n.p.x-c,n.p.y+c,c,t)),h.push(new bc(n.p.x+c,n.p.y+c,c,t)),f+=4)}return r&&(console.log(`num probes: ${f}`),console.log(`best distance: ${p.d}`)),p.p}function vc(t,e){return e.max-t.max}function bc(t,e,r,n){this.p=new i(t,e),this.h=r,this.d=function(t,e){let r=!1,n=1/0;for(let i=0;it.y!=a.y>t.y&&t.x<(a.x-i.x)*(t.y-i.y)/(a.y-i.y)+i.x&&(r=!r),n=Math.min(n,Mo(t,i,a))}}return(r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2}var wc;!function(t){t[t.center=1]="center",t[t.left=2]="left",t[t.right=3]="right",t[t.top=4]="top",t[t.bottom=5]="bottom",t[t["top-left"]=6]="top-left",t[t["top-right"]=7]="top-right",t[t["bottom-left"]=8]="bottom-left",t[t["bottom-right"]=9]="bottom-right"}(wc||(wc={}));const _c=7,Sc=Number.POSITIVE_INFINITY;function kc(t,e){return e[1]!==Sc?function(t,e,r){let n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case"top-right":case"top-left":case"top":i=r-_c;break;case"bottom-right":case"bottom-left":case"bottom":i=-r+_c}switch(t){case"top-right":case"bottom-right":case"right":n=-e;break;case"top-left":case"bottom-left":case"left":n=e}return[n,i]}(t,e[0],e[1]):function(t,e){let r=0,n=0;e<0&&(e=0);const i=e/Math.SQRT2;switch(t){case"top-right":case"top-left":n=i-_c;break;case"bottom-right":case"bottom-left":n=-i+_c;break;case"bottom":n=-e+_c;break;case"top":n=e-_c}switch(t){case"top-right":case"bottom-right":r=-i;break;case"top-left":case"bottom-left":r=i;break;case"left":r=e;break;case"right":r=-e}return[r,n]}(t,e[0])}function Ac(t,e,r){var n;const i=t.layout,s=null===(n=i.get("text-variable-anchor-offset"))||void 0===n?void 0:n.evaluate(e,{},r);if(s){const t=s.values,e=[];for(let r=0;rt*Pl));n.startsWith("top")?i[1]-=_c:n.startsWith("bottom")&&(i[1]+=_c),e[r+1]=i}return new xt(e)}const o=i.get("text-variable-anchor");if(o){let n;n=void 0!==t._unevaluatedLayout.getValue("text-radial-offset")?[i.get("text-radial-offset").evaluate(e,{},r)*Pl,Sc]:i.get("text-offset").evaluate(e,{},r).map((t=>t*Pl));const s=[];for(const t of o)s.push(t,kc(t,n));return new xt(s)}return null}function Ic(t){t.bucket.createArrays(),t.bucket.tilePixelRatio=po/(512*t.bucket.overscaling),t.bucket.compareText={},t.bucket.iconsNeedLinear=!1;const e=t.bucket.layers[0],r=e.layout,n=e._unevaluatedLayout._values,i={layoutIconSize:n["icon-size"].possiblyEvaluate(new vi(t.bucket.zoom+1),t.canonical),layoutTextSize:n["text-size"].possiblyEvaluate(new vi(t.bucket.zoom+1),t.canonical),textMaxSize:n["text-size"].possiblyEvaluate(new vi(18))};if("composite"===t.bucket.textSizeData.kind){const{minZoom:e,maxZoom:r}=t.bucket.textSizeData;i.compositeTextSizes=[n["text-size"].possiblyEvaluate(new vi(e),t.canonical),n["text-size"].possiblyEvaluate(new vi(r),t.canonical)]}if("composite"===t.bucket.iconSizeData.kind){const{minZoom:e,maxZoom:r}=t.bucket.iconSizeData;i.compositeIconSizes=[n["icon-size"].possiblyEvaluate(new vi(e),t.canonical),n["icon-size"].possiblyEvaluate(new vi(r),t.canonical)]}const s=r.get("text-line-height")*Pl,o="viewport"!==r.get("text-rotation-alignment")&&"point"!==r.get("symbol-placement"),a=r.get("text-keep-upright"),l=r.get("text-size");for(const n of t.bucket.features){const u=r.get("text-font").evaluate(n,{},t.canonical).join(","),c=l.evaluate(n,{},t.canonical),h=i.layoutTextSize.evaluate(n,{},t.canonical),p=i.layoutIconSize.evaluate(n,{},t.canonical),f={horizontal:{},vertical:void 0},y=n.text;let m,g=[0,0];if(y){const i=y.toString(),l=r.get("text-letter-spacing").evaluate(n,{},t.canonical)*Pl,p=ai(i)?l:0,d=r.get("text-anchor").evaluate(n,{},t.canonical),m=Ac(e,n,t.canonical);if(!m){const e=r.get("text-radial-offset").evaluate(n,{},t.canonical);g=e?kc(d,[e*Pl,Sc]):r.get("text-offset").evaluate(n,{},t.canonical).map((t=>t*Pl))}let x=o?"center":r.get("text-justify").evaluate(n,{},t.canonical);const v="point"===r.get("symbol-placement")?r.get("text-max-width").evaluate(n,{},t.canonical)*Pl:1/0,b=()=>{t.bucket.allowVerticalPlacement&&oi(i)&&(f.vertical=lu(y,t.glyphMap,t.glyphPositions,t.imagePositions,u,v,s,d,"left",p,g,iu.vertical,!0,h,c))};if(!o&&m){const e=new Set;if("auto"===x)for(let t=0;t{l.x<0||l.x>=po||l.y<0||l.y>=po||function(t,e,r,n,i,s,o,a,l,u,c,h,p,f,y,m,g,x,v,b,w,_,S,k,A){const I=t.addToLineVertexArray(e,r);let M,z,P,C,B=0,V=0,T=0,E=0,F=-1,D=-1;const $={};let L=Xs("");if(t.allowVerticalPlacement&&n.vertical){const t=a.layout.get("text-rotate").evaluate(w,{},k)+90;P=new mc(l,e,u,c,h,n.vertical,p,f,y,t),o&&(C=new mc(l,e,u,c,h,o,g,x,y,t))}if(i){const r=a.layout.get("icon-rotate").evaluate(w,{}),n="none"!==a.layout.get("icon-text-fit"),s=hc(i,r,S,n),p=o?hc(o,r,S,n):void 0;z=new mc(l,e,u,c,h,i,g,x,!1,r),B=4*s.length;const f=t.iconSizeData;let y=null;"source"===f.kind?(y=[ku*a.layout.get("icon-size").evaluate(w,{})],y[0]>Au&&d(`${t.layerIds[0]}: Value for "icon-size" is >= ${Su}. Reduce your "icon-size".`)):"composite"===f.kind&&(y=[ku*_.compositeIconSizes[0].evaluate(w,{},k),ku*_.compositeIconSizes[1].evaluate(w,{},k)],(y[0]>Au||y[1]>Au)&&d(`${t.layerIds[0]}: Value for "icon-size" is >= ${Su}. Reduce your "icon-size".`)),t.addSymbols(t.icon,s,y,b,v,w,iu.none,e,I.lineStartIndex,I.lineLength,-1,k),F=t.icon.placedSymbolArray.length-1,p&&(V=4*p.length,t.addSymbols(t.icon,p,y,b,v,w,iu.vertical,e,I.lineStartIndex,I.lineLength,-1,k),D=t.icon.placedSymbolArray.length-1)}const O=Object.keys(n.horizontal);for(const r of O){const i=n.horizontal[r];if(!M){L=Xs(i.text);const t=a.layout.get("text-rotate").evaluate(w,{},k);M=new mc(l,e,u,c,h,i,p,f,y,t)}const o=1===i.positionedLines.length;if(T+=Pc(t,e,i,s,a,y,w,m,I,n.vertical?iu.horizontal:iu.horizontalOnly,o?O:[r],$,F,_,k),o)break}n.vertical&&(E+=Pc(t,e,n.vertical,s,a,y,w,m,I,iu.vertical,["vertical"],$,D,_,k));const R=M?M.boxStartIndex:t.collisionBoxArray.length,j=M?M.boxEndIndex:t.collisionBoxArray.length,q=P?P.boxStartIndex:t.collisionBoxArray.length,U=P?P.boxEndIndex:t.collisionBoxArray.length,N=z?z.boxStartIndex:t.collisionBoxArray.length,Z=z?z.boxEndIndex:t.collisionBoxArray.length,G=C?C.boxStartIndex:t.collisionBoxArray.length,X=C?C.boxEndIndex:t.collisionBoxArray.length;let H=-1;const Y=(t,e)=>t&&t.circleDiameter?Math.max(t.circleDiameter,e):e;H=Y(M,H),H=Y(P,H),H=Y(z,H),H=Y(C,H);const J=H>-1?1:0;J&&(H*=A/Pl),t.glyphOffsetArray.length>=Fu.MAX_GLYPHS&&d("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==w.sortKey&&t.addToSortKeyRanges(t.symbolInstances.length,w.sortKey);const K=Ac(a,w,k),[W,Q]=function(t,e){const r=t.length,n=null==e?void 0:e.values;if((null==n?void 0:n.length)>0)for(let e=0;e=0?$.right:-1,$.center>=0?$.center:-1,$.left>=0?$.left:-1,$.vertical||-1,F,D,L,R,j,q,U,N,Z,G,X,u,T,E,B,V,J,0,p,H,W,Q)}(t,l,i,r,n,s,C,t.layers[0],t.collisionBoxArray,e.index,e.sourceLayerIndex,t.index,x,[_,_,_,_],A,u,b,S,I,y,e,o,c,h,a)};if("line"===M)for(const s of function(t,e,r,n,s){const o=[];for(let e=0;e=n&&l.x>=n||(e.x>=n?e=new i(n,e.y+(n-e.x)/(l.x-e.x)*(l.y-e.y))._round():l.x>=n&&(l=new i(n,e.y+(n-e.x)/(l.x-e.x)*(l.y-e.y))._round()),e.y>=s&&l.y>=s||(e.y>=s?e=new i(e.x+(s-e.y)/(l.y-e.y)*(l.x-e.x),s)._round():l.y>=s&&(l=new i(e.x+(s-e.y)/(l.y-e.y)*(l.x-e.x),s)._round()),a&&e.equals(a[a.length-1])||(a=[e],o.push(a)),a.push(l)))))}}return o}(e.geometry,0,0,po,po)){const e=lc(s,w,k,r.vertical||m,n,24,v,t.overscaling,po);for(const r of e)m&&Bc(t,m.text,z,r)||B(s,r)}else if("line-center"===M){for(const t of e.geometry)if(t.length>1){const e=ac(t,k,r.vertical||m,n,24,v);e&&B(t,e)}}else if("Polygon"===e.type)for(const t of $e(e.geometry,0)){const e=xc(t,16);B(t[0],new rc(e.x,e.y,0))}else if("LineString"===e.type)for(const t of e.geometry)B(t,new rc(t[0].x,t[0].y,0));else if("Point"===e.type)for(const t of e.geometry)for(const e of t)B([e],new rc(e.x,e.y,0))}function Pc(t,e,r,n,s,o,a,l,u,c,h,p,f,y,m){const g=function(t,e,r,n,s,o,a,l){const u=n.layout.get("text-rotate").evaluate(o,{})*Math.PI/180,c=[];for(const t of e.positionedLines)for(const n of t.positionedGlyphs){if(!n.rect)continue;const o=n.rect||{};let h=Ql+1,p=!0,f=1,d=0;const y=(s||l)&&n.vertical,m=n.metrics.advance*n.scale/2;if(l&&e.verticalizable&&(d=t.lineOffset/2-(n.imageName?-(Pl-n.metrics.width*n.scale)/2:(n.scale-1)*Pl)),n.imageName){const t=a[n.imageName];p=t.sdf,f=t.pixelRatio,h=eu/f}const g=s?[n.x+m,n.y]:[0,0];let x=s?[0,0]:[n.x+m+r[0],n.y+r[1]-d],v=[0,0];y&&(v=x,x=[0,0]);const b=n.metrics.isDoubleResolution?2:1,w=(n.metrics.left-h)*n.scale-m+x[0],_=(-n.metrics.top-h)*n.scale+x[1],S=w+o.w/b*n.scale/f,k=_+o.h/b*n.scale/f,A=new i(w,_),I=new i(S,_),M=new i(w,k),z=new i(S,k);if(y){const t=new i(-m,m-su),e=-Math.PI/2,r=Pl/2-m,s=new i(5-su-r,-(n.imageName?r:0)),o=new i(...v);A._rotateAround(e,t)._add(s)._add(o),I._rotateAround(e,t)._add(s)._add(o),M._rotateAround(e,t)._add(s)._add(o),z._rotateAround(e,t)._add(s)._add(o)}if(u){const t=Math.sin(u),e=Math.cos(u),r=[e,-t,t,e];A._matMult(r),I._matMult(r),M._matMult(r),z._matMult(r)}const P=new i(0,0),C=new i(0,0);c.push({tl:A,tr:I,bl:M,br:z,tex:o,writingMode:e.writingMode,glyphOffset:g,sectionIndex:n.sectionIndex,isSDF:p,pixelOffsetTL:P,pixelOffsetBR:C,minFontScaleX:0,minFontScaleY:0})}return c}(0,r,l,s,o,a,n,t.allowVerticalPlacement),x=t.textSizeData;let v=null;"source"===x.kind?(v=[ku*s.layout.get("text-size").evaluate(a,{})],v[0]>Au&&d(`${t.layerIds[0]}: Value for "text-size" is >= ${Su}. Reduce your "text-size".`)):"composite"===x.kind&&(v=[ku*y.compositeTextSizes[0].evaluate(a,{},m),ku*y.compositeTextSizes[1].evaluate(a,{},m)],(v[0]>Au||v[1]>Au)&&d(`${t.layerIds[0]}: Value for "text-size" is >= ${Su}. Reduce your "text-size".`)),t.addSymbols(t.text,g,v,l,o,a,c,e,u.lineStartIndex,u.lineLength,f,m);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*g.length}function Cc(t){for(const e in t)return t[e];return null}function Bc(t,e,r,n){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(n.dist(t[e])90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Fc(function(t,e,r){const n=((t-e)%360+360)%360+e;return n===e?180:n}(this.lng,-180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return Ec*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof Fc)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new Fc(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new Fc(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const Dc=2*Math.PI*Ec;function $c(t){return Dc*Math.cos(t*Math.PI/180)}function Lc(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}class Oc{constructor(t,e,r=0){this.x=+t,this.y=+e,this.z=+r}static fromLngLat(t,e=0){const r=Fc.convert(t);return new Oc((180+r.lng)/360,(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+r.lat*Math.PI/360)))/360,function(t,e){return t/$c(e)}(e,r.lat))}toLngLat(){return new Fc(360*this.x-180,Lc(this.y))}toAltitude(){return this.z*$c(Lc(this.y))}meterInMercatorCoordinateUnits(){return 1/Dc*(t=Lc(this.y),1/Math.cos(t*Math.PI/180));var t}}class Rc{constructor(t,e,r){if(!function(t,e,r){return!(t<0||t>25||r<0||r>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,r))throw new Error(`x=${e}, y=${r}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=r,this.key=Uc(0,t,t,e,r)}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,r){const n=(s=this.y,o=this.z,a=Tc(256*(i=this.x),256*(s=Math.pow(2,o)-s-1),o),l=Tc(256*(i+1),256*(s+1),o),a[0]+","+a[1]+","+l[0]+","+l[1]);var i,s,o,a,l;const u=function(t,e,r){let n,i="";for(let s=t;s>0;s--)n=1<1?"@2x":"").replace(/{quadkey}/g,u).replace(/{bbox-epsg-3857}/g,n)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new i((t.x*e-this.x)*po,(t.y*e-this.y)*po)}toString(){return`${this.z}/${this.x}/${this.y}`}}class jc{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Uc(t,e.z,e.z,e.x,e.y)}}class qc{constructor(t,e,r,n,i){if(t= z; overscaledZ = ${t}; z = ${r}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Rc(r,+n,+i),this.key=Uc(e,t,r,n,i)}clone(){return new qc(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new qc(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new qc(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const r=this.canonical.z-t;return t>this.canonical.z?Uc(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Uc(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)}isChildOf(t){if(t.wrap!==this.wrap)return!1;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return[new qc(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return[new qc(e,this.wrap,e,r,n),new qc(e,this.wrap,e,r+1,n),new qc(e,this.wrap,e,r,n+1),new qc(e,this.wrap,e,r+1,n+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.y=e.maxzoom||"none"!==e.visibility&&(Zc(t,this.zoom,n),(o[e.id]=e.createBucket({index:s.bucketLayerIDs.length,layers:t,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:u,sourceID:this.source})).populate(c,a,this.tileID.canonical),s.bucketLayerIDs.push(t.map((t=>t.id))))}}const u=h(a.glyphDependencies,(t=>Object.keys(t).map(Number)));this.inFlightDependencies.forEach((t=>null==t?void 0:t.abort())),this.inFlightDependencies=[];let c=Promise.resolve({});if(Object.keys(u).length){const t=new AbortController;this.inFlightDependencies.push(t),c=i.sendAsync({type:"GG",data:{stacks:u,source:this.source,tileID:this.tileID,type:"glyphs"}},t)}const p=Object.keys(a.iconDependencies);let f=Promise.resolve({}),y=Promise.resolve({});if(p.length){const t=new AbortController;this.inFlightDependencies.push(t),f=i.sendAsync({type:"GI",data:{icons:p,source:this.source,tileID:this.tileID,type:"icons"}},t);const e=p.filter((t=>t.includes("msdf"))).map((t=>t.replace("msdf","msdf-backgrounds")));e.length&&(y=i.sendAsync({type:"GI",data:{icons:e,source:this.source,tileID:this.tileID,type:"icons"}},t))}const m=Object.keys(a.patternDependencies);let g=Promise.resolve({});if(m.length){const t=new AbortController;this.inFlightDependencies.push(t),g=i.sendAsync({type:"GI",data:{icons:m,source:this.source,tileID:this.tileID,type:"patterns"}},t)}const[x,v,b,w]=yield Promise.all([c,f,y,g]),_=new Vc(x),S=new nu(v,w),k=new nu(b,{});for(const t in o){const e=o[t];e instanceof Fu?(Zc(e.layers,this.zoom,n),Ic({bucket:e,glyphMap:x,glyphPositions:_.positions,imageMap:v,imagePositions:S.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical})):e.hasPattern&&(e instanceof yl||e instanceof Ba||e instanceof tl)&&(Zc(e.layers,this.zoom,n),e.addFeatures(a,this.tileID.canonical,S.patternPositions))}return this.status="done",{buckets:Object.values(o).filter((t=>!t.isEmpty())),featureIndex:s,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:_.image,imageAtlas:S,imageBackgroundsAtlas:k,glyphMap:this.returnDependencies?x:null,iconMap:this.returnDependencies?v:null,glyphPositions:this.returnDependencies?_.positions:null}}))}}function Zc(t,e,r){const n=new vi(e);for(const e of t)e.recalculate(n,r)}var Gc;!function(t){t.create="create",t.load="load",t.fullLoad="fullLoad"}(Gc||(Gc={}));class Xc{constructor(t){this._marks={start:[t.url,"start"].join("#"),end:[t.url,"end"].join("#"),measure:t.url.toString()},performance.mark(this._marks.start)}finish(){performance.mark(this._marks.end);let t=performance.getEntriesByName(this._marks.measure);return 0===t.length&&(performance.measure(this._marks.measure,this._marks.start,this._marks.end),t=performance.getEntriesByName(this._marks.measure),performance.clearMarks(this._marks.start),performance.clearMarks(this._marks.end),performance.clearMeasures(this._marks.measure)),t}}class Hc{constructor(t,e,r){this.actor=t,this.layerIndex=e,this.availableImages=r,this.fetching={},this.loading={},this.loaded={}}loadVectorTile(e,r){return t(this,void 0,void 0,(function*(){const t=yield((t,e)=>Rn(c(t,{type:"arrayBuffer"}),e))(e.request,r);try{return{vectorTile:new Oa.VectorTile(new Wl(t.data)),rawData:t.data,cacheControl:t.cacheControl,expires:t.expires}}catch(r){const n=new Uint8Array(t.data);let i=`Unable to parse the tile at ${e.request.url}, `;throw i+=31===n[0]&&139===n[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${r.message}`,new Error(i)}}))}loadTile(e){return t(this,void 0,void 0,(function*(){const t=e.uid,r=!!(e&&e.request&&e.request.collectResourceTiming)&&new Xc(e.request),n=new Nc(e);this.loading[t]=n;const i=new AbortController;n.abort=i;try{const s=yield this.loadVectorTile(e,i);if(delete this.loading[t],!s)return null;const o=s.rawData,a={};s.expires&&(a.expires=s.expires),s.cacheControl&&(a.cacheControl=s.cacheControl);const l={};if(r){const t=r.finish();t&&(l.resourceTiming=JSON.parse(JSON.stringify(t)))}n.vectorTile=s.vectorTile;const u=n.parse(s.vectorTile,this.layerIndex,this.availableImages,this.actor);this.loaded[t]=n,this.fetching[t]={rawTileData:o,cacheControl:a,resourceTiming:l};try{const t=yield u;return c({rawTileData:o.slice(0)},t,a,l)}finally{delete this.fetching[t]}}catch(e){throw delete this.loading[t],n.status="done",this.loaded[t]=n,e}}))}reloadTile(e){return t(this,void 0,void 0,(function*(){const t=e.uid;if(!this.loaded||!this.loaded[t])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const r=this.loaded[t];if(r.showCollisionBoxes=e.showCollisionBoxes,"parsing"===r.status){const e=yield r.parse(r.vectorTile,this.layerIndex,this.availableImages,this.actor);let n;if(this.fetching[t]){const{rawTileData:r,cacheControl:i,resourceTiming:s}=this.fetching[t];delete this.fetching[t],n=c({rawTileData:r.slice(0)},e,i,s)}else n=e;return n}if("done"===r.status&&r.vectorTile)return r.parse(r.vectorTile,this.layerIndex,this.availableImages,this.actor)}))}abortTile(e){return t(this,void 0,void 0,(function*(){const t=this.loading,r=e.uid;t&&t[r]&&t[r].abort&&(t[r].abort.abort(),delete t[r])}))}removeTile(e){return t(this,void 0,void 0,(function*(){this.loaded&&this.loaded[e.uid]&&delete this.loaded[e.uid]}))}}class Yc{constructor(t,e,r,n=1,i=1,s=1,o=0){if(this.uid=t,e.height!==e.width)throw new RangeError("DEM tiles must be square");if(r&&!["mapbox","terrarium","custom"].includes(r))return void d(`"${r}" is not a valid encoding type. Valid types include "mapbox", "terrarium" and "custom".`);this.stride=e.height;const a=this.dim=e.height-2;switch(this.data=new Uint32Array(e.data.buffer),r){case"terrarium":this.redFactor=256,this.greenFactor=1,this.blueFactor=1/256,this.baseShift=32768;break;case"custom":this.redFactor=n,this.greenFactor=i,this.blueFactor=s,this.baseShift=o;break;default:this.redFactor=6553.6,this.greenFactor=25.6,this.blueFactor=.1,this.baseShift=1e4}for(let t=0;tthis.max&&(this.max=r),r=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(e+1)*this.stride+(t+1)}unpack(t,e,r){return t*this.redFactor+e*this.greenFactor+r*this.blueFactor-this.baseShift}getPixels(){return new Jo({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let n=e*this.dim,i=e*this.dim+this.dim,s=r*this.dim,o=r*this.dim+this.dim;switch(e){case-1:n=i-1;break;case 1:i=n+1}switch(r){case-1:s=o-1;break;case 1:o=s+1}const a=-e*this.dim,l=-r*this.dim;for(let e=s;e=Math.abs(a)?r-l+a:a-l+r,r=l}r+n>=0!=!!e&&t.reverse()}var Qc=e((function t(e,r){var n,i=e&&e.type;if("FeatureCollection"===i)for(n=0;n>31}function yh(t,e){for(var r=t.loadGeometry(),n=t.type,i=0,s=0,o=r.length,a=0;a>4;if(1!==n)throw new Error(`Got v${n} data when expected v1.`);const i=xh[15&r];if(!i)throw new Error("Unrecognized array type.");const[s]=new Uint16Array(t,2,1),[o]=new Uint32Array(t,4,1);return new vh(o,s,i,t)}constructor(t,e=64,r=Float64Array,n){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=xh.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,o=t*this.IndexArrayType.BYTES_PER_ELEMENT,a=(8-o%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);n&&n instanceof ArrayBuffer?(this.data=n,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+o+a,2*t),this._pos=2*t,this._finished=!0):(this.data=new ArrayBuffer(8+s+o+a),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+o+a,2*t),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t)}add(t,e){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=e,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return bh(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,e,r,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:s,nodeSize:o}=this,a=[0,i.length-1,0],l=[];for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=o){for(let o=h;o<=c;o++){const a=s[2*o],u=s[2*o+1];a>=t&&a<=r&&u>=e&&u<=n&&l.push(i[o])}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=r&&d>=e&&d<=n&&l.push(i[p]),(0===u?t<=f:e<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?r>=f:n>=d)&&(a.push(p+1),a.push(c),a.push(1-u))}return l}within(t,e,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:n,coords:i,nodeSize:s}=this,o=[0,n.length-1,0],a=[],l=r*r;for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=s){for(let r=h;r<=c;r++)kh(i[2*r],i[2*r+1],t,e)<=l&&a.push(n[r]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];kh(f,d,t,e)<=l&&a.push(n[p]),(0===u?t-r<=f:e-r<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?t+r>=f:e+r>=d)&&(o.push(p+1),o.push(c),o.push(1-u))}return a}}function bh(t,e,r,n,i,s){if(i-n<=r)return;const o=n+i>>1;wh(t,e,o,n,i,s),bh(t,e,r,n,o-1,1-s),bh(t,e,r,o+1,i,1-s)}function wh(t,e,r,n,i,s){for(;i>n;){if(i-n>600){const o=i-n+1,a=r-n+1,l=Math.log(o),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(o-u)/o)*(a-o/2<0?-1:1);wh(t,e,r,Math.max(n,Math.floor(r-a*u/o+c)),Math.min(i,Math.floor(r+(o-a)*u/o+c)),s)}const o=e[2*r+s];let a=n,l=i;for(_h(t,e,n,r),e[2*i+s]>o&&_h(t,e,n,i);ao;)l--}e[2*n+s]===o?_h(t,e,n,l):(l++,_h(t,e,l,i)),l<=r&&(n=l+1),r<=l&&(i=l-1)}}function _h(t,e,r,n){Sh(t,r,n),Sh(e,2*r,2*n),Sh(e,2*r+1,2*n+1)}function Sh(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function kh(t,e,r,n){const i=t-r,s=e-n;return i*i+s*s}const Ah={minZoom:0,maxZoom:16,minPoints:2,radius:40,extent:512,nodeSize:64,log:!1,generateId:!1,reduce:null,map:t=>t},Ih=Math.fround||(Mh=new Float32Array(1),t=>(Mh[0]=+t,Mh[0]));var Mh;const zh=3,Ph=5,Ch=6;class Bh{constructor(t){this.options=Object.assign(Object.create(Ah),t),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(t){const{log:e,minZoom:r,maxZoom:n}=this.options;e&&console.time("total time");const i=`prepare ${t.length} points`;e&&console.time(i),this.points=t;const s=[];for(let e=0;e=r;t--){const r=+Date.now();o=this.trees[t]=this._createTree(this._cluster(o,t)),e&&console.log("z%d: %d clusters in %dms",t,o.numItems,+Date.now()-r)}return e&&console.timeEnd("total time"),this}getClusters(t,e){let r=((t[0]+180)%360+360)%360-180;const n=Math.max(-90,Math.min(90,t[1]));let i=180===t[2]?180:((t[2]+180)%360+360)%360-180;const s=Math.max(-90,Math.min(90,t[3]));if(t[2]-t[0]>=360)r=-180,i=180;else if(r>i){const t=this.getClusters([r,n,180,s],e),o=this.getClusters([-180,n,i,s],e);return t.concat(o)}const o=this.trees[this._limitZoom(e)],a=o.range(Eh(r),Fh(s),Eh(i),Fh(n)),l=o.data,u=[];for(const t of a){const e=this.stride*t;u.push(l[e+Ph]>1?Vh(l,e,this.clusterProps):this.points[l[e+zh]])}return u}getChildren(t){const e=this._getOriginId(t),r=this._getOriginZoom(t),n="No cluster with the specified id.",i=this.trees[r];if(!i)throw new Error(n);const s=i.data;if(e*this.stride>=s.length)throw new Error(n);const o=this.options.radius/(this.options.extent*Math.pow(2,r-1)),a=i.within(s[e*this.stride],s[e*this.stride+1],o),l=[];for(const e of a){const r=e*this.stride;s[r+4]===t&&l.push(s[r+Ph]>1?Vh(s,r,this.clusterProps):this.points[s[r+zh]])}if(0===l.length)throw new Error(n);return l}getLeaves(t,e,r){const n=[];return this._appendLeaves(n,t,e=e||10,r=r||0,0),n}getTile(t,e,r){const n=this.trees[this._limitZoom(t)],i=Math.pow(2,t),{extent:s,radius:o}=this.options,a=o/s,l=(r-a)/i,u=(r+1+a)/i,c={features:[]};return this._addTileFeatures(n.range((e-a)/i,l,(e+1+a)/i,u),n.data,e,r,i,c),0===e&&this._addTileFeatures(n.range(1-a/i,l,1,u),n.data,i,r,i,c),e===i-1&&this._addTileFeatures(n.range(0,l,a/i,u),n.data,-1,r,i,c),c.features.length?c:null}getClusterExpansionZoom(t){let e=this._getOriginZoom(t)-1;for(;e<=this.options.maxZoom;){const r=this.getChildren(t);if(e++,1!==r.length)break;t=r[0].properties.cluster_id}return e}_appendLeaves(t,e,r,n,i){const s=this.getChildren(e);for(const e of s){const s=e.properties;if(s&&s.cluster?i+s.point_count<=n?i+=s.point_count:i=this._appendLeaves(t,s.cluster_id,r,n,i):i1;let l,u,c;if(a)l=Th(e,t,this.clusterProps),u=e[t],c=e[t+1];else{const r=this.points[e[t+zh]];l=r.properties;const[n,i]=r.geometry.coordinates;u=Eh(n),c=Fh(i)}const h={type:1,geometry:[[Math.round(this.options.extent*(u*i-r)),Math.round(this.options.extent*(c*i-n))]],tags:l};let p;p=a||this.options.generateId?e[t+zh]:this.points[e[t+zh]].id,void 0!==p&&(h.id=p),s.features.push(h)}}_limitZoom(t){return Math.max(this.options.minZoom,Math.min(Math.floor(+t),this.options.maxZoom+1))}_cluster(t,e){const{radius:r,extent:n,reduce:i,minPoints:s}=this.options,o=r/(n*Math.pow(2,e)),a=t.data,l=[],u=this.stride;for(let r=0;re&&(f+=a[r+Ph])}if(f>p&&f>=s){let t,s=n*p,o=c*p,d=-1;const y=((r/u|0)<<5)+(e+1)+this.points.length;for(const n of h){const l=n*u;if(a[l+2]<=e)continue;a[l+2]=e;const c=a[l+Ph];s+=a[l]*c,o+=a[l+1]*c,a[l+4]=y,i&&(t||(t=this._map(a,r,!0),d=this.clusterProps.length,this.clusterProps.push(t)),i(t,this._map(a,l)))}a[r+4]=y,l.push(s/f,o/f,1/0,y,-1,f),i&&l.push(d)}else{for(let t=0;t1)for(const t of h){const r=t*u;if(!(a[r+2]<=e)){a[r+2]=e;for(let t=0;t>5}_getOriginZoom(t){return(t-this.points.length)%32}_map(t,e,r){if(t[e+Ph]>1){const n=this.clusterProps[t[e+Ch]];return r?Object.assign({},n):n}const n=this.points[t[e+zh]].properties,i=this.options.map(n);return r&&i===n?Object.assign({},i):i}}function Vh(t,e,r){return{type:"Feature",id:t[e+zh],properties:Th(t,e,r),geometry:{type:"Point",coordinates:[(n=t[e],360*(n-.5)),Dh(t[e+1])]}};var n}function Th(t,e,r){const n=t[e+Ph],i=n>=1e4?`${Math.round(n/1e3)}k`:n>=1e3?Math.round(n/100)/10+"k":n,s=t[e+Ch],o=-1===s?{}:Object.assign({},r[s]);return Object.assign(o,{cluster:!0,cluster_id:t[e+zh],point_count:n,point_count_abbreviated:i})}function Eh(t){return t/360+.5}function Fh(t){const e=Math.sin(t*Math.PI/180),r=.5-.25*Math.log((1+e)/(1-e))/Math.PI;return r<0?0:r>1?1:r}function Dh(t){const e=(180-360*t)*Math.PI/180;return 360*Math.atan(Math.exp(e))/Math.PI-90}function $h(t,e,r,n){let i=n;const s=e+(r-e>>1);let o,a=r-e;const l=t[e],u=t[e+1],c=t[r],h=t[r+1];for(let n=e+3;ni)o=n,i=e;else if(e===i){const t=Math.abs(n-s);tn&&(o-e>3&&$h(t,e,o,n),t[o+2]=i,r-o>3&&$h(t,o,r,n))}function Lh(t,e,r,n,i,s){let o=i-r,a=s-n;if(0!==o||0!==a){const l=((t-r)*o+(e-n)*a)/(o*o+a*a);l>1?(r=i,n=s):l>0&&(r+=o*l,n+=a*l)}return o=t-r,a=e-n,o*o+a*a}function Oh(t,e,r,n){const i={id:null==t?null:t,type:e,geometry:r,tags:n,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===e||"MultiPoint"===e||"LineString"===e)Rh(i,r);else if("Polygon"===e)Rh(i,r[0]);else if("MultiLineString"===e)for(const t of r)Rh(i,t);else if("MultiPolygon"===e)for(const t of r)Rh(i,t[0]);return i}function Rh(t,e){for(let r=0;r0&&(o+=n?(i*l-a*s)/2:Math.sqrt(Math.pow(a-i,2)+Math.pow(l-s,2))),i=a,s=l}const a=e.length-3;e[2]=1,$h(e,0,a,r),e[a+2]=1,e.size=Math.abs(o),e.start=0,e.end=e.size}function Nh(t,e,r,n){for(let i=0;i1?1:r}function Xh(t,e,r,n,i,s,o,a){if(n/=e,s>=(r/=e)&&o=n)return null;const l=[];for(const e of t){const t=e.geometry;let s=e.type;const o=0===i?e.minX:e.minY,u=0===i?e.maxX:e.maxY;if(o>=r&&u=n)continue;let c=[];if("Point"===s||"MultiPoint"===s)Hh(t,c,r,n,i);else if("LineString"===s)Yh(t,c,r,n,i,!1,a.lineMetrics);else if("MultiLineString"===s)Kh(t,c,r,n,i,!1);else if("Polygon"===s)Kh(t,c,r,n,i,!0);else if("MultiPolygon"===s)for(const e of t){const t=[];Kh(e,t,r,n,i,!0),t.length&&c.push(t)}if(c.length){if(a.lineMetrics&&"LineString"===s){for(const t of c)l.push(Oh(e.id,s,t,e.tags));continue}"LineString"!==s&&"MultiLineString"!==s||(1===c.length?(s="LineString",c=c[0]):s="MultiLineString"),"Point"!==s&&"MultiPoint"!==s||(s=3===c.length?"Point":"MultiPoint"),l.push(Oh(e.id,s,c,e.tags))}}return l.length?l:null}function Hh(t,e,r,n,i){for(let s=0;s=r&&o<=n&&Wh(e,t[s],t[s+1],t[s+2])}}function Yh(t,e,r,n,i,s,o){let a=Jh(t);const l=0===i?Qh:tp;let u,c,h=t.start;for(let p=0;pr&&(c=l(a,f,d,m,g,r),o&&(a.start=h+u*c)):x>n?v=r&&(c=l(a,f,d,m,g,r),b=!0),v>n&&x<=n&&(c=l(a,f,d,m,g,n),b=!0),!s&&b&&(o&&(a.end=h+u*c),e.push(a),a=Jh(t)),o&&(h+=u)}let p=t.length-3;const f=t[p],d=t[p+1],y=0===i?f:d;y>=r&&y<=n&&Wh(a,f,d,t[p+2]),p=a.length-3,s&&p>=3&&(a[p]!==a[0]||a[p+1]!==a[1])&&Wh(a,a[0],a[1],a[2]),a.length&&e.push(a)}function Jh(t){const e=[];return e.size=t.size,e.start=t.start,e.end=t.end,e}function Kh(t,e,r,n,i,s){for(const o of t)Yh(o,e,r,n,i,s,!1)}function Wh(t,e,r,n){t.push(e,r,n)}function Qh(t,e,r,n,i,s){const o=(s-e)/(n-e);return Wh(t,s,r+(i-r)*o,1),o}function tp(t,e,r,n,i,s){const o=(s-r)/(i-r);return Wh(t,e+(n-e)*o,s,1),o}function ep(t,e){const r=[];for(let n=0;n0&&e.size<(i?o:n))return void(r.numPoints+=e.length/3);const a=[];for(let t=0;to)&&(r.numSimplified++,a.push(e[t],e[t+1])),r.numPoints++;i&&function(t,e){let r=0;for(let e=0,n=t.length,i=n-2;e0===e)for(let e=0,r=t.length;e24)throw new Error("maxZoom should be in the 0-24 range");if(e.promoteId&&e.generateId)throw new Error("promoteId and generateId cannot be used together.");let n=function(t,e){const r=[];if("FeatureCollection"===t.type)for(let n=0;n1&&console.time("creation"),p=this.tiles[h]=sp(t,e,r,n,l),this.tileCoords.push({z:e,x:r,y:n}),u)){u>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",e,r,n,p.numFeatures,p.numPoints,p.numSimplified),console.timeEnd("creation"));const t=`z${e}`;this.stats[t]=(this.stats[t]||0)+1,this.total++}if(p.source=t,null==i){if(e===l.indexMaxZoom||p.numPoints<=l.indexMaxPoints)continue}else{if(e===l.maxZoom||e===i)continue;if(null!=i){const t=i-e;if(r!==s>>t||n!==o>>t)continue}}if(p.source=null,0===t.length)continue;u>1&&console.time("clipping");const f=.5*l.buffer/l.extent,d=.5-f,y=.5+f,m=1+f;let g=null,x=null,v=null,b=null,w=Xh(t,c,r-f,r+y,0,p.minX,p.maxX,l),_=Xh(t,c,r+d,r+m,0,p.minX,p.maxX,l);t=null,w&&(g=Xh(w,c,n-f,n+y,1,p.minY,p.maxY,l),x=Xh(w,c,n+d,n+m,1,p.minY,p.maxY,l),w=null),_&&(v=Xh(_,c,n-f,n+y,1,p.minY,p.maxY,l),b=Xh(_,c,n+d,n+m,1,p.minY,p.maxY,l),_=null),u>1&&console.timeEnd("clipping"),a.push(g||[],e+1,2*r,2*n),a.push(x||[],e+1,2*r,2*n+1),a.push(v||[],e+1,2*r+1,2*n),a.push(b||[],e+1,2*r+1,2*n+1)}}getTile(t,e,r){t=+t,e=+e,r=+r;const n=this.options,{extent:i,debug:s}=n;if(t<0||t>24)return null;const o=1<1&&console.log("drilling down to z%d-%d-%d",t,e,r);let l,u=t,c=e,h=r;for(;!l&&u>0;)u--,c>>=1,h>>=1,l=this.tiles[cp(u,c,h)];return l&&l.source?(s>1&&(console.log("found parent tile z%d-%d-%d",u,c,h),console.time("drilling down")),this.splitTile(l.source,u,c,h,t,e,r),s>1&&console.timeEnd("drilling down"),this.tiles[a]?np(this.tiles[a],i):null):null}}function cp(t,e,r){return 32*((1<{s.properties=t;const e={};for(const t of o)e[t]=r[t].evaluate(i,s);return e},t.reduce=(t,e)=>{s.properties=e;for(const e of o)i.accumulated=t[e],t[e]=n[e].evaluate(i,s)},t}(e)).load((yield this._pendingData).features):(n=yield this._pendingData,new up(n,e.geojsonVtOptions)),this.loaded={};const t={};if(r){const n=r.finish();n&&(t.resourceTiming={},t.resourceTiming[e.source]=JSON.parse(JSON.stringify(n)))}return t}catch(t){if(delete this._pendingRequest,function(t){return t.message===Vn}(t))return{abandoned:!0};throw t}var n}))}getData(){return t(this,void 0,void 0,(function*(){return this._pendingData}))}reloadTile(t){const e=this.loaded;return e&&e[t.uid]?super.reloadTile(t):this.loadTile(t)}loadAndProcessGeoJSON(e,r){return t(this,void 0,void 0,(function*(){let t=yield this.loadGeoJSON(e,r);if(delete this._pendingRequest,"object"!=typeof t)throw new Error(`Input data given to '${e.source}' is not a valid GeoJSON object.`);if(Qc(t,!0),e.filter){const r=Lr(e.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));const n=t.features.filter((t=>r.value.evaluate({zoom:0},t)));t={type:"FeatureCollection",features:n}}return t}))}loadGeoJSON(e,r){return t(this,void 0,void 0,(function*(){const{promoteId:t}=e;if(e.request){const n=yield((t,e)=>Rn(c(t,{type:"json"}),e))(e.request,r);return this._dataUpdateable=pp(n.data,t)?fp(n.data,t):void 0,n.data}if("string"==typeof e.data)try{const r=JSON.parse(e.data);return this._dataUpdateable=pp(r,t)?fp(r,t):void 0,r}catch(t){throw new Error(`Input data given to '${e.source}' is not a valid GeoJSON object.`)}if(!e.dataDiff)throw new Error(`Input data given to '${e.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${e.source}`);return function(t,e,r){var n,i,s,o;if(e.removeAll&&t.clear(),e.remove)for(const r of e.remove)t.delete(r);if(e.add)for(const n of e.add){const e=hp(n,r);null!=e&&t.set(e,n)}if(e.update)for(const r of e.update){let e=t.get(r.id);if(null==e)continue;const a=!r.removeAllProperties&&((null===(n=r.removeProperties)||void 0===n?void 0:n.length)>0||(null===(i=r.addOrUpdateProperties)||void 0===i?void 0:i.length)>0);if((r.newGeometry||r.removeAllProperties||a)&&(e=Object.assign({},e),t.set(r.id,e),a&&(e.properties=Object.assign({},e.properties))),r.newGeometry&&(e.geometry=r.newGeometry),r.removeAllProperties)e.properties={};else if((null===(s=r.removeProperties)||void 0===s?void 0:s.length)>0)for(const t of r.removeProperties)Object.prototype.hasOwnProperty.call(e.properties,t)&&delete e.properties[t];if((null===(o=r.addOrUpdateProperties)||void 0===o?void 0:o.length)>0)for(const{key:t,value:n}of r.addOrUpdateProperties)e.properties[t]=n}}(this._dataUpdateable,e.dataDiff,t),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(e){return t(this,void 0,void 0,(function*(){this._pendingRequest&&this._pendingRequest.abort()}))}getClusterExpansionZoom(t){return this._geoJSONIndex.getClusterExpansionZoom(t.clusterId)}getClusterChildren(t){return this._geoJSONIndex.getChildren(t.clusterId)}getClusterLeaves(t){return this._geoJSONIndex.getLeaves(t.clusterId,t.limit,t.offset)}}class yp{constructor(e){this.self=e,this.actor=new Yn(e),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.self.registerWorkerSource=(t,e)=>{if(this.externalWorkerSourceTypes[t])throw new Error(`Worker source with name "${t}" already registered.`);this.externalWorkerSourceTypes[t]=e},this.self.addProtocol=Fn,this.self.removeProtocol=Dn,this.self.registerRTLTextPlugin=t=>{if(xi.isParsed())throw new Error("RTL text plugin already registered.");xi.setMethods(t)},this.actor.registerMessageHandler("LDT",((t,e)=>this._getDEMWorkerSource(t,e.source).loadTile(e))),this.actor.registerMessageHandler("RDT",((e,r)=>t(this,void 0,void 0,(function*(){this._getDEMWorkerSource(e,r.source).removeTile(r)})))),this.actor.registerMessageHandler("GCEZ",((e,r)=>t(this,void 0,void 0,(function*(){return this._getWorkerSource(e,r.type,r.source).getClusterExpansionZoom(r)})))),this.actor.registerMessageHandler("GCC",((e,r)=>t(this,void 0,void 0,(function*(){return this._getWorkerSource(e,r.type,r.source).getClusterChildren(r)})))),this.actor.registerMessageHandler("GCL",((e,r)=>t(this,void 0,void 0,(function*(){return this._getWorkerSource(e,r.type,r.source).getClusterLeaves(r)})))),this.actor.registerMessageHandler("LD",((t,e)=>this._getWorkerSource(t,e.type,e.source).loadData(e))),this.actor.registerMessageHandler("GD",((t,e)=>this._getWorkerSource(t,e.type,e.source).getData())),this.actor.registerMessageHandler("LT",((t,e)=>this._getWorkerSource(t,e.type,e.source).loadTile(e))),this.actor.registerMessageHandler("RT",((t,e)=>this._getWorkerSource(t,e.type,e.source).reloadTile(e))),this.actor.registerMessageHandler("AT",((t,e)=>this._getWorkerSource(t,e.type,e.source).abortTile(e))),this.actor.registerMessageHandler("RMT",((t,e)=>this._getWorkerSource(t,e.type,e.source).removeTile(e))),this.actor.registerMessageHandler("RS",((e,r)=>t(this,void 0,void 0,(function*(){if(!this.workerSources[e]||!this.workerSources[e][r.type]||!this.workerSources[e][r.type][r.source])return;const t=this.workerSources[e][r.type][r.source];delete this.workerSources[e][r.type][r.source],void 0!==t.removeSource&&t.removeSource(r)})))),this.actor.registerMessageHandler("RM",(e=>t(this,void 0,void 0,(function*(){delete this.layerIndexes[e],delete this.availableImages[e],delete this.workerSources[e],delete this.demWorkerSources[e]})))),this.actor.registerMessageHandler("SR",((e,r)=>t(this,void 0,void 0,(function*(){this.referrer=r})))),this.actor.registerMessageHandler("SRPS",((t,e)=>this._syncRTLPluginState(t,e))),this.actor.registerMessageHandler("IS",((e,r)=>t(this,void 0,void 0,(function*(){this.self.importScripts(r)})))),this.actor.registerMessageHandler("SI",((t,e)=>this._setImages(t,e))),this.actor.registerMessageHandler("UL",((e,r)=>t(this,void 0,void 0,(function*(){this._getLayerIndex(e).update(r.layers,r.removedIds)})))),this.actor.registerMessageHandler("SL",((e,r)=>t(this,void 0,void 0,(function*(){this._getLayerIndex(e).replace(r)}))))}_setImages(e,r){return t(this,void 0,void 0,(function*(){this.availableImages[e]=r;for(const t in this.workerSources[e]){const n=this.workerSources[e][t];for(const t in n)n[t].availableImages=r}}))}_syncRTLPluginState(e,r){return t(this,void 0,void 0,(function*(){if(xi.isParsed())return xi.getState();if("loading"!==r.pluginStatus)return xi.setState(r),r;const t=r.pluginURL;if(this.self.importScripts(t),xi.isParsed()){const e={pluginStatus:"loaded",pluginURL:t};return xi.setState(e),e}throw xi.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${t}`)}))}_getAvailableImages(t){let e=this.availableImages[t];return e||(e=[]),e}_getLayerIndex(t){let e=this.layerIndexes[t];return e||(e=this.layerIndexes[t]=new Yu),e}_getWorkerSource(t,e,r){if(this.workerSources[t]||(this.workerSources[t]={}),this.workerSources[t][e]||(this.workerSources[t][e]={}),!this.workerSources[t][e][r]){const n={sendAsync:(e,r)=>(e.targetMapId=t,this.actor.sendAsync(e,r))};switch(e){case"vector":this.workerSources[t][e][r]=new Hc(n,this._getLayerIndex(t),this._getAvailableImages(t));break;case"geojson":this.workerSources[t][e][r]=new dp(n,this._getLayerIndex(t),this._getAvailableImages(t));break;default:this.workerSources[t][e][r]=new this.externalWorkerSourceTypes[e](n,this._getLayerIndex(t),this._getAvailableImages(t))}}return this.workerSources[t][e][r]}_getDEMWorkerSource(t,e){return this.demWorkerSources[t]||(this.demWorkerSources[t]={}),this.demWorkerSources[t][e]||(this.demWorkerSources[t][e]=new Jc),this.demWorkerSources[t][e]}}return m(self)&&(self.worker=new yp(self)),yp}(); +//# sourceMappingURL=maplibre-gl-csp-worker.js.map diff --git a/dist/maplibre-gl-csp.js b/dist/maplibre-gl-csp.js new file mode 100644 index 0000000000..7e7da505e7 --- /dev/null +++ b/dist/maplibre-gl-csp.js @@ -0,0 +1,6 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v4.7.0/LICENSE.txt + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).maplibregl={})}(this,(function(t){"use strict";var e="4.7.0";function i(t,e,i,r){return new(i||(i=Promise))((function(s,n){function a(t){try{l(r.next(t))}catch(t){n(t)}}function o(t){try{l(r.throw(t))}catch(t){n(t)}}function l(t){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(a,o)}l((r=r.apply(t,e||[])).next())}))}function r(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}"function"==typeof SuppressedError&&SuppressedError;var s=n;function n(t,e){this.x=t,this.y=e}n.prototype={clone:function(){return new n(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,i=t.y-this.y;return e*e+i*i},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),i=Math.sin(t),r=i*this.x+e*this.y;return this.x=e*this.x-i*this.y,this.y=r,this},_rotateAround:function(t,e){var i=Math.cos(t),r=Math.sin(t),s=e.y+r*(this.x-e.x)+i*(this.y-e.y);return this.x=e.x+i*(this.x-e.x)-r*(this.y-e.y),this.y=s,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},n.convert=function(t){return t instanceof n?t:Array.isArray(t)?new n(t[0],t[1]):t};var a=r(s),o=l;function l(t,e,i,r){this.cx=3*t,this.bx=3*(i-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(r-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=i,this.p2y=r}l.prototype={sampleCurveX:function(t){return((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return(3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var i=t,r=0;r<8;r++){var s=this.sampleCurveX(i)-t;if(Math.abs(s)s?a=i:o=i,i=.5*(o-a)+a;return i},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}};var c=r(o);let h,u;function d(){return null==h&&(h="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),h}function p(t){let e=1/0,i=1/0,r=-1/0,s=-1/0;for(const n of t)e=Math.min(e,n.x),i=Math.min(i,n.y),r=Math.max(r,n.x),s=Math.max(s,n.y);return[e,i,r,s]}function f(t,e,i,r){const s=new c(t,e,i,r);return t=>s.solve(t)}const m=f(.25,.1,.25,1);function _(t,e,i){return Math.min(i,Math.max(e,t))}function g(t,e,i){const r=i-e,s=((t-e)%r+r)%r+e;return s===e?i:s}function y(t,...e){for(const i of e)for(const e in i)t[e]=i[e];return t}function x(t,e){const i={};for(let r=0;r(e.y-t.y)*(i.x-t.x)}function z(t){return"undefined"!=typeof WorkerGlobalScope&&void 0!==t&&t instanceof WorkerGlobalScope}let P=null;function M(t){return"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const k="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function D(t){return t*Math.PI/180}function L(){return new Error("AbortError")}let R,B;const F={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frameAsync:t=>new Promise(((e,i)=>{const r=requestAnimationFrame(e);t.signal.addEventListener("abort",(()=>{cancelAnimationFrame(r),i(L())}))})),getImageData(t,e=0){return this.getImageCanvasContext(t).getImageData(-e,-e,t.width+2*e,t.height+2*e)},getImageCanvasContext(t){const e=window.document.createElement("canvas"),i=e.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return e.width=t.width,e.height=t.height,i.drawImage(t,0,0,t.width,t.height),i},resolveURL:t=>(R||(R=document.createElement("a")),R.href=t,R.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return!!matchMedia&&(null==B&&(B=matchMedia("(prefers-reduced-motion: reduce)")),B.matches)}};class O{static testProp(t){if(!O.docStyle)return t[0];for(let e=0;e{window.removeEventListener("click",O.suppressClickInternal,!0)}),0)}static getScale(t){const e=t.getBoundingClientRect();return{x:e.width/t.offsetWidth||1,y:e.height/t.offsetHeight||1,boundingClientRect:e}}static getPoint(t,e,i){const r=e.boundingClientRect;return new a((i.clientX-r.left)/e.x-t.clientLeft,(i.clientY-r.top)/e.y-t.clientTop)}static mousePos(t,e){const i=O.getScale(t);return O.getPoint(t,i,e)}static touchPos(t,e){const i=[],r=O.getScale(t);for(let s=0;sz(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,q=function(t,e){if(/:\/\//.test(t.url)&&!/^https?:|^file:/.test(t.url)){const i=U(t.url);if(i)return i(t,e);if(z(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,targetMapId:N},e)}if(!(/^file:/.test(r=t.url)||/^file:/.test($())&&!/^\w+:/.test(r))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(t,e){return i(this,void 0,void 0,(function*(){const i=new Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,cache:t.cache,referrer:$(),signal:e.signal});"json"!==t.type||i.headers.has("Accept")||i.headers.set("Accept","application/json");const r=yield fetch(i);if(!r.ok){const e=yield r.blob();throw new j(r.status,r.statusText,t.url,e)}let s;s="arrayBuffer"===t.type||"image"===t.type?r.arrayBuffer():"json"===t.type?r.json():r.text();const n=yield s;if(e.signal.aborted)throw L();return{data:n,cacheControl:r.headers.get("Cache-Control"),expires:r.headers.get("Expires")}}))}(t,e);if(z(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,mustQueue:!0,targetMapId:N},e)}var r;return function(t,e){return new Promise(((i,r)=>{var s;const n=new XMLHttpRequest;n.open(t.method||"GET",t.url,!0),"arrayBuffer"!==t.type&&"image"!==t.type||(n.responseType="arraybuffer");for(const e in t.headers)n.setRequestHeader(e,t.headers[e]);"json"===t.type&&(n.responseType="text",(null===(s=t.headers)||void 0===s?void 0:s.Accept)||n.setRequestHeader("Accept","application/json")),n.withCredentials="include"===t.credentials,n.onerror=()=>{r(new Error(n.statusText))},n.onload=()=>{if(!e.signal.aborted)if((n.status>=200&&n.status<300||0===n.status)&&null!==n.response){let e=n.response;if("json"===t.type)try{e=JSON.parse(n.response)}catch(t){return void r(t)}i({data:e,cacheControl:n.getResponseHeader("Cache-Control"),expires:n.getResponseHeader("Expires")})}else{const e=new Blob([n.response],{type:n.getResponseHeader("Content-Type")});r(new j(n.status,n.statusText,t.url,e))}},e.signal.addEventListener("abort",(()=>{n.abort(),r(L())})),n.send(t.body)}))}(t,e)},Z=(t,e)=>q(y(t,{type:"json"}),e);function G(t){if(!t||t.indexOf("://")<=0||0===t.indexOf("data:image/")||0===t.indexOf("blob:"))return!0;const e=new URL(t),i=window.location;return e.protocol===i.protocol&&e.host===i.host}const W={supported:!1,testSupport:function(t){!K&&X&&(Y?J(t):H=t)}};let H,X,K=!1,Y=!1;function J(t){const e=t.createTexture();t.bindTexture(t.TEXTURE_2D,e);try{if(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,X),t.isContextLost())return;W.supported=!0}catch(t){}t.deleteTexture(e),K=!0}var Q;"undefined"!=typeof document&&(X=document.createElement("img"),X.onload=()=>{H&&J(H),H=null,Y=!0},X.onerror=()=>{K=!0,H=null},X.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(t){let e,r,s,n;t.resetRequestQueue=()=>{e=[],r=0,s=0,n={}},t.addThrottleControl=t=>{const e=s++;return n[e]=t,e},t.removeThrottleControl=t=>{delete n[t],o()},t.getImage=(t,i,r=!0)=>new Promise(((s,n)=>{W.supported&&(t.headers||(t.headers={}),t.headers.accept="image/webp,*/*"),y(t,{type:"image"});const a={abortController:i,requestParameters:t,supportImageRefresh:r,state:"queued",onError:t=>{n(t)},onSuccess:t=>{s(t)}};e.push(a),o()}));const a=t=>i(this,void 0,void 0,(function*(){t.state="running";const{requestParameters:e,supportImageRefresh:s,onError:n,onSuccess:a,abortController:c}=t,h=!1===s&&!z(self)&&!U(e.url)&&(!e.headers||Object.keys(e.headers).reduce(((t,e)=>t&&"accept"===e),!0));r++;const u=h?l(e,c):q(e,c);try{const e=yield u;delete t.abortController,t.state="completed",e.data instanceof HTMLImageElement||M(e.data)?a(e):e.data&&a({data:yield(d=e.data,"function"==typeof createImageBitmap?(t=>i(void 0,void 0,void 0,(function*(){if(0===t.byteLength)return createImageBitmap(new ImageData(1,1));const e=new Blob([new Uint8Array(t)],{type:"image/png"});try{return createImageBitmap(e)}catch(t){throw new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})))(d):(t=>new Promise(((e,i)=>{const r=new Image;r.onload=()=>{e(r),URL.revokeObjectURL(r.src),r.onload=null,window.requestAnimationFrame((()=>{r.src=k}))},r.onerror=()=>i(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."));const s=new Blob([new Uint8Array(t)],{type:"image/png"});r.src=t.byteLength?URL.createObjectURL(s):k})))(d)),cacheControl:e.cacheControl,expires:e.expires})}catch(e){delete t.abortController,n(e)}finally{r--,o()}var d})),o=()=>{const t=(()=>{for(const t of Object.keys(n))if(n[t]())return!0;return!1})()?V.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:V.MAX_PARALLEL_IMAGE_REQUESTS;for(let i=r;i0;i++){const t=e.shift();t.abortController.signal.aborted?i--:a(t)}},l=(t,e)=>new Promise(((i,r)=>{const s=new Image,n=t.url,a=t.credentials;a&&"include"===a?s.crossOrigin="use-credentials":(a&&"same-origin"===a||!G(n))&&(s.crossOrigin="anonymous"),e.signal.addEventListener("abort",(()=>{s.src="",r(L())})),s.fetchPriority="high",s.onload=()=>{s.onerror=s.onload=null,i({data:s})},s.onerror=()=>{s.onerror=s.onload=null,e.signal.aborted||r(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."))},s.src=n}))}(Q||(Q={})),Q.resetRequestQueue();class tt{constructor(t){this._transformRequestFn=t}transformRequest(t,e){return this._transformRequestFn&&this._transformRequestFn(t,e)||{url:t}}setTransformRequest(t){this._transformRequestFn=t}}function et(t,e,i){i[t]&&-1!==i[t].indexOf(e)||(i[t]=i[t]||[],i[t].push(e))}function it(t,e,i){if(i&&i[t]){const r=i[t].indexOf(e);-1!==r&&i[t].splice(r,1)}}class rt{constructor(t,e={}){y(this,e),this.type=t}}class st extends rt{constructor(t,e={}){super("error",y({error:t},e))}}class nt{on(t,e){return this._listeners=this._listeners||{},et(t,e,this._listeners),this}off(t,e){return it(t,e,this._listeners),it(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},et(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new rt(t,e||{}));const i=t.type;if(this.listens(i)){t.target=this;const e=this._listeners&&this._listeners[i]?this._listeners[i].slice():[];for(const i of e)i.call(this,t);const r=this._oneTimeListeners&&this._oneTimeListeners[i]?this._oneTimeListeners[i].slice():[];for(const e of r)it(i,e,this._oneTimeListeners),e.call(this,t);const s=this._eventedParent;s&&(y(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),s.fire(t))}else t instanceof st&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var at={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"enum",default:"mercator",values:{mercator:{},globe:{}}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const ot=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function lt(t,e){const i={};for(const e in t)"ref"!==e&&(i[e]=t[e]);return ot.forEach((t=>{t in e&&(i[t]=e[t])})),i}function ct(t){t=t.slice();const e=Object.create(null);for(let i=0;i`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const Ft=[Tt,St,It,At,Et,Mt,Ct,Rt(zt),kt,Dt,Lt];function Ot(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Ot(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else{if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of Ft)if(!Ot(t,e))return null}return`Expected ${Bt(t)} but found ${Bt(e)} instead.`}function Vt(t,e){return e.some((e=>e.kind===t.kind))}function Ut(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function Nt(t,e){return"array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const jt=.96422,$t=.82521,qt=4/29,Zt=6/29,Gt=3*Zt*Zt,Wt=Zt*Zt*Zt,Ht=Math.PI/180,Xt=180/Math.PI;function Kt(t){return(t%=360)<0&&(t+=360),t}function Yt([t,e,i,r]){let s,n;const a=Qt((.2225045*(t=Jt(t))+.7168786*(e=Jt(e))+.0606169*(i=Jt(i)))/1);t===e&&e===i?s=n=a:(s=Qt((.4360747*t+.3850649*e+.1430804*i)/jt),n=Qt((.0139322*t+.0971045*e+.7141733*i)/$t));const o=116*a-16;return[o<0?0:o,500*(s-a),200*(a-n),r]}function Jt(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Qt(t){return t>Wt?Math.pow(t,1/3):t/Gt+qt}function te([t,e,i,r]){let s=(t+16)/116,n=isNaN(e)?s:s+e/500,a=isNaN(i)?s:s-i/200;return s=1*ie(s),n=jt*ie(n),a=$t*ie(a),[ee(3.1338561*n-1.6168667*s-.4906146*a),ee(-.9787684*n+1.9161415*s+.033454*a),ee(.0719453*n-.2289914*s+1.4052427*a),r]}function ee(t){return(t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function ie(t){return t>Zt?t*t*t:Gt*(t-qt)}function re(t){return parseInt(t.padEnd(2,t),16)/255}function se(t,e){return ne(e?t/100:t,0,1)}function ne(t,e,i){return Math.min(Math.max(e,t),i)}function ae(t){return!t.some(Number.isNaN)}const oe={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};class le{constructor(t,e,i,r=1,s=!0){this.r=t,this.g=e,this.b=i,this.a=r,s||(this.r*=r,this.g*=r,this.b*=r,r||this.overwriteGetter("rgb",[t,e,i,r]))}static parse(t){if(t instanceof le)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return[0,0,0,0];const e=oe[t];if(e){const[t,i,r]=e;return[t/255,i/255,r/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let i=1;return[re(t.slice(i,i+=e)),re(t.slice(i,i+=e)),re(t.slice(i,i+=e)),re(t.slice(i,i+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,i,r,s,n,a,o,l,c,h,u,d]=e,p=[s||" ",o||" ",h].join("");if(" "===p||" /"===p||",,"===p||",,,"===p){const t=[r,a,c].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[ne(+i/e,0,1),ne(+n/e,0,1),ne(+l/e,0,1),u?se(+u,d):1];if(ae(t))return t}}return}}const i=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(i){const[t,e,r,s,n,a,o,l,c]=i,h=[r||" ",n||" ",o].join("");if(" "===h||" /"===h||",,"===h||",,,"===h){const t=[+e,ne(+s,0,100),ne(+a,0,100),l?se(+l,c):1];if(ae(t))return function([t,e,i,r]){function s(r){const s=(r+t/30)%12,n=e*Math.min(i,1-i);return i-n*Math.max(-1,Math.min(s-3,9-s,1))}return t=Kt(t),e/=100,i/=100,[s(0),s(8),s(4),r]}(t)}}}(t);return e?new le(...e,!1):void 0}get rgb(){const{r:t,g:e,b:i,a:r}=this,s=r||1/0;return this.overwriteGetter("rgb",[t/s,e/s,i/s,r])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,i,r,s]=Yt(t),n=Math.sqrt(i*i+r*r);return[Math.round(1e4*n)?Kt(Math.atan2(r,i)*Xt):NaN,n,e,s]}(this.rgb))}get lab(){return this.overwriteGetter("lab",Yt(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,i,r]=this.rgb;return`rgba(${[t,e,i].map((t=>Math.round(255*t))).join(",")},${r})`}}le.black=new le(0,0,0,1),le.white=new le(1,1,1,1),le.transparent=new le(0,0,0,0),le.red=new le(1,0,0,1);class ce{constructor(t,e,i){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=i,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class he{constructor(t,e,i,r,s){this.text=t,this.image=e,this.scale=i,this.fontStack=r,this.textColor=s}}class ue{constructor(t){this.sections=t}static fromString(t){return new ue([new he(t,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof ue?t:ue.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class de{constructor(t){this.values=t.slice()}static parse(t){if(t instanceof de)return t;if("number"==typeof t)return new de([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]]}return new de(t)}}toString(){return JSON.stringify(this.values)}}const pe=new Set(["center","left","right","top","bottom","top-left","top-right","bottom-left","bottom-right"]);class fe{constructor(t){this.values=t.slice()}static parse(t){if(t instanceof fe)return t;if(Array.isArray(t)&&!(t.length<1)&&t.length%2==0){for(let e=0;e=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof i&&i>=0&&i<=255?void 0===r||"number"==typeof r&&r>=0&&r<=1?null:`Invalid rgba value [${[t,e,i,r].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof r?[t,e,i,r]:[t,e,i]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function ge(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof le||t instanceof ce||t instanceof ue||t instanceof de||t instanceof fe||t instanceof me)return!0;if(Array.isArray(t)){for(const e of t)if(!ge(e))return!1;return!0}if("object"==typeof t){for(const e in t)if(!ge(t[e]))return!1;return!0}return!1}function ye(t){if(null===t)return Tt;if("string"==typeof t)return It;if("boolean"==typeof t)return At;if("number"==typeof t)return St;if(t instanceof le)return Et;if(t instanceof ce)return Pt;if(t instanceof ue)return Mt;if(t instanceof de)return kt;if(t instanceof fe)return Lt;if(t instanceof me)return Dt;if(Array.isArray(t)){const e=t.length;let i;for(const e of t){const t=ye(e);if(i){if(i===t)continue;i=zt;break}i=t}return Rt(i||zt,e)}return Ct}function xe(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof le||t instanceof ue||t instanceof de||t instanceof fe||t instanceof me?t.toString():JSON.stringify(t)}class ve{constructor(t,e){this.type=t,this.value=e}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!ge(t[1]))return e.error("invalid value");const i=t[1];let r=ye(i);const s=e.expectedType;return"array"!==r.kind||0!==r.N||!s||"array"!==s.kind||"number"==typeof s.N&&0!==s.N||(r=s),new ve(r,i)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}}class be{constructor(t){this.name="ExpressionEvaluationError",this.message=t}toJSON(){return this.message}}const we={string:It,number:St,boolean:At,object:Ct};class Te{constructor(t,e){this.type=t,this.args=e}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let i,r=1;const s=t[0];if("array"===s){let s,n;if(t.length>2){const i=t[1];if("string"!=typeof i||!(i in we)||"object"===i)return e.error('The item type argument of "array" must be one of string, number, boolean',1);s=we[i],r++}else s=zt;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);n=t[2],r++}i=Rt(s,n)}else{if(!we[s])throw new Error(`Types doesn't contain name = ${s}`);i=we[s]}const n=[];for(;rt.outputDefined()))}}const Se={"to-boolean":At,"to-color":Et,"to-number":St,"to-string":It};class Ie{constructor(t,e){this.type=t,this.args=e}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const i=t[0];if(!Se[i])throw new Error(`Can't parse ${i} as it is not part of the known types`);if(("to-boolean"===i||"to-string"===i)&&2!==t.length)return e.error("Expected one argument.");const r=Se[i],s=[];for(let i=1;i4?`Invalid rbga value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:_e(e[0],e[1],e[2],e[3]),!i))return new le(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new be(i||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"padding":{let e;for(const i of this.args){e=i.evaluate(t);const r=de.parse(e);if(r)return r}throw new be(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"variableAnchorOffsetCollection":{let e;for(const i of this.args){e=i.evaluate(t);const r=fe.parse(e);if(r)return r}throw new be(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"number":{let e=null;for(const i of this.args){if(e=i.evaluate(t),null===e)return 0;const r=Number(e);if(!isNaN(r))return r}throw new be(`Could not convert ${JSON.stringify(e)} to number.`)}case"formatted":return ue.fromString(xe(this.args[0].evaluate(t)));case"resolvedImage":return me.fromString(xe(this.args[0].evaluate(t)));default:return xe(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t)}outputDefined(){return this.args.every((t=>t.outputDefined()))}}const Ae=["Unknown","Point","LineString","Polygon"];class Ee{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?Ae[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache[t];return e||(e=this._parseColorCache[t]=le.parse(t)),e}}class Ce{constructor(t,e,i=[],r,s=new wt,n=[]){this.registry=t,this.path=i,this.key=i.map((t=>`[${t}]`)).join(""),this.scope=s,this.errors=n,this.expectedType=r,this._isConstant=e}parse(t,e,i,r,s={}){return e?this.concat(e,i,r)._parse(t,s):this._parse(t,s)}_parse(t,e){function i(t,e,i){return"assert"===i?new Te(e,[t]):"coerce"===i?new Ie(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const r=t[0];if("string"!=typeof r)return this.error(`Expression name must be a string, but found ${typeof r} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const s=this.registry[r];if(s){let r=s.parse(t,this);if(!r)return null;if(this.expectedType){const t=this.expectedType,s=r.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==s.kind)if("color"!==t.kind&&"formatted"!==t.kind&&"resolvedImage"!==t.kind||"value"!==s.kind&&"string"!==s.kind)if("padding"!==t.kind||"value"!==s.kind&&"number"!==s.kind&&"array"!==s.kind)if("variableAnchorOffsetCollection"!==t.kind||"value"!==s.kind&&"array"!==s.kind){if(this.checkSubtype(t,s))return null}else r=i(r,t,e.typeAnnotation||"coerce");else r=i(r,t,e.typeAnnotation||"coerce");else r=i(r,t,e.typeAnnotation||"coerce");else r=i(r,t,e.typeAnnotation||"assert")}if(!(r instanceof ve)&&"resolvedImage"!==r.type.kind&&this._isConstant(r)){const t=new Ee;try{r=new ve(r.type,r.evaluate(t))}catch(t){return this.error(t.message),null}}return r}return this.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,i){const r="number"==typeof t?this.path.concat(t):this.path,s=i?this.scope.concat(i):this.scope;return new Ce(this.registry,this._isConstant,r,e||null,s,this.errors)}error(t,...e){const i=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new bt(i,t))}checkSubtype(t,e){const i=Ot(t,e);return i&&this.error(i),i}}class ze{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result)}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const i=[];for(let r=1;r=i.length)throw new be(`Array index out of bounds: ${e} > ${i.length-1}.`);if(e!==Math.floor(e))throw new be(`Array index must be an integer, but found ${e} instead.`);return i[e]}eachChild(t){t(this.index),t(this.input)}outputDefined(){return!1}}class ke{constructor(t,e){this.type=At,this.needle=t,this.haystack=e}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const i=e.parse(t[1],1,zt),r=e.parse(t[2],2,zt);return i&&r?Vt(i.type,[At,It,St,Tt,zt])?new ke(i,r):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Bt(i.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),i=this.haystack.evaluate(t);if(!i)return!1;if(!Ut(e,["boolean","string","number","null"]))throw new be(`Expected first argument to be of type boolean, string, number or null, but found ${Bt(ye(e))} instead.`);if(!Ut(i,["string","array"]))throw new be(`Expected second argument to be of type array or string, but found ${Bt(ye(i))} instead.`);return i.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack)}outputDefined(){return!0}}class De{constructor(t,e,i){this.type=St,this.needle=t,this.haystack=e,this.fromIndex=i}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const i=e.parse(t[1],1,zt),r=e.parse(t[2],2,zt);if(!i||!r)return null;if(!Vt(i.type,[At,It,St,Tt,zt]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${Bt(i.type)} instead`);if(4===t.length){const s=e.parse(t[3],3,St);return s?new De(i,r,s):null}return new De(i,r)}evaluate(t){const e=this.needle.evaluate(t),i=this.haystack.evaluate(t);if(!Ut(e,["boolean","string","number","null"]))throw new be(`Expected first argument to be of type boolean, string, number or null, but found ${Bt(ye(e))} instead.`);let r;if(this.fromIndex&&(r=this.fromIndex.evaluate(t)),Ut(i,["string"])){const t=i.indexOf(e,r);return-1===t?-1:[...i.slice(0,t)].length}if(Ut(i,["array"]))return i.indexOf(e,r);throw new be(`Expected second argument to be of type array or string, but found ${Bt(ye(i))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex)}outputDefined(){return!1}}class Le{constructor(t,e,i,r,s,n){this.inputType=t,this.type=e,this.input=i,this.cases=r,this.outputs=s,this.otherwise=n}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let i,r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const s={},n=[];for(let a=2;aNumber.MAX_SAFE_INTEGER)return c.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return c.error("Numeric branch labels must be integer values.");if(i){if(c.checkSubtype(i,ye(t)))return null}else i=ye(t);if(void 0!==s[String(t)])return c.error("Branch labels must be unique.");s[String(t)]=n.length}const h=e.parse(l,a,r);if(!h)return null;r=r||h.type,n.push(h)}const a=e.parse(t[1],1,zt);if(!a)return null;const o=e.parse(t[t.length-1],t.length-1,r);return o?"value"!==a.type.kind&&e.concat(1).checkSubtype(i,a.type)?null:new Le(i,r,a,s,n,o):null}evaluate(t){const e=this.input.evaluate(t);return(ye(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise)}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class Re{constructor(t,e,i){this.type=t,this.branches=e,this.otherwise=i}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let i;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);const r=[];for(let s=1;se.outputDefined()))&&this.otherwise.outputDefined()}}class Be{constructor(t,e,i,r){this.type=t,this.input=e,this.beginIndex=i,this.endIndex=r}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const i=e.parse(t[1],1,zt),r=e.parse(t[2],2,St);if(!i||!r)return null;if(!Vt(i.type,[Rt(zt),It,zt]))return e.error(`Expected first argument to be of type array or string, but found ${Bt(i.type)} instead`);if(4===t.length){const s=e.parse(t[3],3,St);return s?new Be(i.type,i,r,s):null}return new Be(i.type,i,r)}evaluate(t){const e=this.input.evaluate(t),i=this.beginIndex.evaluate(t);let r;if(this.endIndex&&(r=this.endIndex.evaluate(t)),Ut(e,["string"]))return[...e].slice(i,r).join("");if(Ut(e,["array"]))return e.slice(i,r);throw new be(`Expected first argument to be of type array or string, but found ${Bt(ye(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex)}outputDefined(){return!1}}function Fe(t,e){const i=t.length-1;let r,s,n=0,a=i,o=0;for(;n<=a;)if(o=Math.floor((n+a)/2),r=t[o],s=t[o+1],r<=e){if(o===i||ee))throw new be("Input is not a number.");a=o-1}return 0}class Oe{constructor(t,e,i){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of i)this.labels.push(t),this.outputs.push(e)}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const i=e.parse(t[1],1,St);if(!i)return null;const r=[];let s=null;e.expectedType&&"value"!==e.expectedType.kind&&(s=e.expectedType);for(let i=1;i=n)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',o);const c=e.parse(a,l,s);if(!c)return null;s=s||c.type,r.push([n,c])}return new Oe(s,i,r)}evaluate(t){const e=this.labels,i=this.outputs;if(1===e.length)return i[0].evaluate(t);const r=this.input.evaluate(t);if(r<=e[0])return i[0].evaluate(t);const s=e.length;return r>=e[s-1]?i[s-1].evaluate(t):i[Fe(e,r)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e)}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function Ve(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ue=Ne;function Ne(t,e,i,r){this.cx=3*t,this.bx=3*(i-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(r-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=i,this.p2y=r}Ne.prototype={sampleCurveX:function(t){return((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return(3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var i=t,r=0;r<8;r++){var s=this.sampleCurveX(i)-t;if(Math.abs(s)s?a=i:o=i,i=.5*(o-a)+a;return i},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}};var je=Ve(Ue);function $e(t,e,i){return t+i*(e-t)}function qe(t,e,i){return t.map(((t,r)=>$e(t,e[r],i)))}const Ze={number:$e,color:function(t,e,i,r="rgb"){switch(r){case"rgb":{const[r,s,n,a]=qe(t.rgb,e.rgb,i);return new le(r,s,n,a,!1)}case"hcl":{const[r,s,n,a]=t.hcl,[o,l,c,h]=e.hcl;let u,d;if(isNaN(r)||isNaN(o))isNaN(r)?isNaN(o)?u=NaN:(u=o,1!==n&&0!==n||(d=l)):(u=r,1!==c&&0!==c||(d=s));else{let t=o-r;o>r&&t>180?t-=360:o180&&(t+=360),u=r+i*t}const[p,f,m,_]=function([t,e,i,r]){return t=isNaN(t)?0:t*Ht,te([i,Math.cos(t)*e,Math.sin(t)*e,r])}([u,null!=d?d:$e(s,l,i),$e(n,c,i),$e(a,h,i)]);return new le(p,f,m,_,!1)}case"lab":{const[r,s,n,a]=te(qe(t.lab,e.lab,i));return new le(r,s,n,a,!1)}}},array:qe,padding:function(t,e,i){return new de(qe(t.values,e.values,i))},variableAnchorOffsetCollection:function(t,e,i){const r=t.values,s=e.values;if(r.length!==s.length)throw new be(`Cannot interpolate values of different length. from: ${t.toString()}, to: ${e.toString()}`);const n=[];for(let t=0;t"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);r={name:"cubic-bezier",controlPoints:t}}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(s=e.parse(s,2,St),!s)return null;const a=[];let o=null;"interpolate-hcl"===i||"interpolate-lab"===i?o=Et:e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType);for(let t=0;t=i)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',s);const c=e.parse(r,l,o);if(!c)return null;o=o||c.type,a.push([i,c])}return Nt(o,St)||Nt(o,Et)||Nt(o,kt)||Nt(o,Lt)||Nt(o,Rt(St))?new Ge(o,i,r,s,a):e.error(`Type ${Bt(o)} is not interpolatable.`)}evaluate(t){const e=this.labels,i=this.outputs;if(1===e.length)return i[0].evaluate(t);const r=this.input.evaluate(t);if(r<=e[0])return i[0].evaluate(t);const s=e.length;if(r>=e[s-1])return i[s-1].evaluate(t);const n=Fe(e,r),a=Ge.interpolationFactor(this.interpolation,r,e[n],e[n+1]),o=i[n].evaluate(t),l=i[n+1].evaluate(t);switch(this.operator){case"interpolate":return Ze[this.type.kind](o,l,a);case"interpolate-hcl":return Ze.color(o,l,a,"hcl");case"interpolate-lab":return Ze.color(o,l,a,"lab")}}eachChild(t){t(this.input);for(const e of this.outputs)t(e)}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function We(t,e,i,r){const s=r-i,n=t-i;return 0===s?0:1===e?n/s:(Math.pow(e,n)-1)/(Math.pow(e,s)-1)}class He{constructor(t,e){this.type=t,this.args=e}static parse(t,e){if(t.length<2)return e.error("Expectected at least one argument.");let i=null;const r=e.expectedType;r&&"value"!==r.kind&&(i=r);const s=[];for(const r of t.slice(1)){const t=e.parse(r,1+s.length,i,void 0,{typeAnnotation:"omit"});if(!t)return null;i=i||t.type,s.push(t)}if(!i)throw new Error("No output type");const n=r&&s.some((t=>Ot(r,t.type)));return new He(n?zt:i,s)}evaluate(t){let e,i=null,r=0;for(const s of this.args)if(r++,i=s.evaluate(t),i&&i instanceof me&&!i.available&&(e||(e=i.name),i=null,r===this.args.length&&(i=e)),null!==i)break;return i}eachChild(t){this.args.forEach(t)}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function Xe(t,e){return"=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function Ke(t,e,i,r){return 0===r.compare(e,i)}function Ye(t,e,i){const r="=="!==t&&"!="!==t;return class s{constructor(t,e,i){this.type=At,this.lhs=t,this.rhs=e,this.collator=i,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const i=t[0];let n=e.parse(t[1],1,zt);if(!n)return null;if(!Xe(i,n.type))return e.concat(1).error(`"${i}" comparisons are not supported for type '${Bt(n.type)}'.`);let a=e.parse(t[2],2,zt);if(!a)return null;if(!Xe(i,a.type))return e.concat(2).error(`"${i}" comparisons are not supported for type '${Bt(a.type)}'.`);if(n.type.kind!==a.type.kind&&"value"!==n.type.kind&&"value"!==a.type.kind)return e.error(`Cannot compare types '${Bt(n.type)}' and '${Bt(a.type)}'.`);r&&("value"===n.type.kind&&"value"!==a.type.kind?n=new Te(a.type,[n]):"value"!==n.type.kind&&"value"===a.type.kind&&(a=new Te(n.type,[a])));let o=null;if(4===t.length){if("string"!==n.type.kind&&"string"!==a.type.kind&&"value"!==n.type.kind&&"value"!==a.type.kind)return e.error("Cannot use collator to compare non-string types.");if(o=e.parse(t[3],3,Pt),!o)return null}return new s(n,a,o)}evaluate(s){const n=this.lhs.evaluate(s),a=this.rhs.evaluate(s);if(r&&this.hasUntypedArgument){const e=ye(n),i=ye(a);if(e.kind!==i.kind||"string"!==e.kind&&"number"!==e.kind)throw new be(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${i.kind}) instead.`)}if(this.collator&&!r&&this.hasUntypedArgument){const t=ye(n),i=ye(a);if("string"!==t.kind||"string"!==i.kind)return e(s,n,a)}return this.collator?i(s,n,a,this.collator.evaluate(s)):e(s,n,a)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator)}outputDefined(){return!0}}}const Je=Ye("==",(function(t,e,i){return e===i}),Ke),Qe=Ye("!=",(function(t,e,i){return e!==i}),(function(t,e,i,r){return!Ke(0,e,i,r)})),ti=Ye("<",(function(t,e,i){return e",(function(t,e,i){return e>i}),(function(t,e,i,r){return r.compare(e,i)>0})),ii=Ye("<=",(function(t,e,i){return e<=i}),(function(t,e,i,r){return r.compare(e,i)<=0})),ri=Ye(">=",(function(t,e,i){return e>=i}),(function(t,e,i,r){return r.compare(e,i)>=0}));class si{constructor(t,e,i){this.type=Pt,this.locale=i,this.caseSensitive=t,this.diacriticSensitive=e}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const i=t[1];if("object"!=typeof i||Array.isArray(i))return e.error("Collator options argument must be an object.");const r=e.parse(void 0!==i["case-sensitive"]&&i["case-sensitive"],1,At);if(!r)return null;const s=e.parse(void 0!==i["diacritic-sensitive"]&&i["diacritic-sensitive"],1,At);if(!s)return null;let n=null;return i.locale&&(n=e.parse(i.locale,1,It),!n)?null:new si(r,s,n)}evaluate(t){return new ce(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale)}outputDefined(){return!1}}class ni{constructor(t,e,i,r,s){this.type=It,this.number=t,this.locale=e,this.currency=i,this.minFractionDigits=r,this.maxFractionDigits=s}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const i=e.parse(t[1],1,St);if(!i)return null;const r=t[2];if("object"!=typeof r||Array.isArray(r))return e.error("NumberFormat options argument must be an object.");let s=null;if(r.locale&&(s=e.parse(r.locale,1,It),!s))return null;let n=null;if(r.currency&&(n=e.parse(r.currency,1,It),!n))return null;let a=null;if(r["min-fraction-digits"]&&(a=e.parse(r["min-fraction-digits"],1,St),!a))return null;let o=null;return r["max-fraction-digits"]&&(o=e.parse(r["max-fraction-digits"],1,St),!o)?null:new ni(i,s,n,a,o)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits)}outputDefined(){return!1}}class ai{constructor(t){this.type=Mt,this.sections=t}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const i=t[1];if(!Array.isArray(i)&&"object"==typeof i)return e.error("First argument must be an image or text section.");const r=[];let s=!1;for(let i=1;i<=t.length-1;++i){const n=t[i];if(s&&"object"==typeof n&&!Array.isArray(n)){s=!1;let t=null;if(n["font-scale"]&&(t=e.parse(n["font-scale"],1,St),!t))return null;let i=null;if(n["text-font"]&&(i=e.parse(n["text-font"],1,Rt(It)),!i))return null;let a=null;if(n["text-color"]&&(a=e.parse(n["text-color"],1,Et),!a))return null;const o=r[r.length-1];o.scale=t,o.font=i,o.textColor=a}else{const n=e.parse(t[i],1,zt);if(!n)return null;const a=n.type.kind;if("string"!==a&&"value"!==a&&"null"!==a&&"resolvedImage"!==a)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");s=!0,r.push({content:n,scale:null,font:null,textColor:null})}}return new ai(r)}evaluate(t){return new ue(this.sections.map((e=>{const i=e.content.evaluate(t);return ye(i)===Dt?new he("",i,null,null,null):new he(xe(i),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor)}outputDefined(){return!1}}class oi{constructor(t){this.type=Dt,this.input=t}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const i=e.parse(t[1],1,It);return i?new oi(i):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),i=me.fromString(e);return i&&t.availableImages&&(i.available=t.availableImages.indexOf(e)>-1),i}eachChild(t){t(this.input)}outputDefined(){return!1}}class li{constructor(t){this.type=St,this.input=t}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const i=e.parse(t[1],1);return i?"array"!==i.type.kind&&"string"!==i.type.kind&&"value"!==i.type.kind?e.error(`Expected argument of type string or array, but found ${Bt(i.type)} instead.`):new li(i):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return[...e].length;if(Array.isArray(e))return e.length;throw new be(`Expected value to be of type string or array, but found ${Bt(ye(e))} instead.`)}eachChild(t){t(this.input)}outputDefined(){return!1}}const ci=8192;function hi(t,e){const i=(180+t[0])/360,r=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,s=Math.pow(2,e.z);return[Math.round(i*s*ci),Math.round(r*s*ci)]}function ui(t,e){const i=Math.pow(2,e.z);return[(s=(t[0]/ci+e.x)/i,360*s-180),(r=(t[1]/ci+e.y)/i,360/Math.PI*Math.atan(Math.exp((180-360*r)*Math.PI/180))-90)];var r,s}function di(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1])}function pi(t,e){return!(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function fi(t,e,i){const r=t[0]-e[0],s=t[1]-e[1],n=t[0]-i[0],a=t[1]-i[1];return r*a-n*s==0&&r*n<=0&&s*a<=0}function mi(t,e,i,r){return 0!=(s=[r[0]-i[0],r[1]-i[1]])[0]*(n=[e[0]-t[0],e[1]-t[1]])[1]-s[1]*n[0]&&!(!bi(t,e,i,r)||!bi(i,r,t,e));var s,n}function _i(t,e,i){for(const r of i)for(let i=0;i(s=t)[1]!=(a=o[e+1])[1]>s[1]&&s[0]<(a[0]-n[0])*(s[1]-n[1])/(a[1]-n[1])+n[0]&&(r=!r)}var s,n,a;return r}function yi(t,e){for(const i of e)if(gi(t,i))return!0;return!1}function xi(t,e){for(const i of t)if(!gi(i,e))return!1;for(let i=0;i0&&o<0||a<0&&o>0}function wi(t,e,i){const r=[];for(let s=0;si[2]){const e=.5*r;let s=t[0]-i[0]>e?-r:i[0]-t[0]>e?r:0;0===s&&(s=t[0]-i[2]>e?-r:i[2]-t[0]>e?r:0),t[0]+=s}di(e,t)}function Ii(t,e,i,r){const s=Math.pow(2,r.z)*ci,n=[r.x*ci,r.y*ci],a=[];for(const r of t)for(const t of r){const r=[t.x+n[0],t.y+n[1]];Si(r,e,i,s),a.push(r)}return a}function Ai(t,e,i,r){const s=Math.pow(2,r.z)*ci,n=[r.x*ci,r.y*ci],a=[];for(const i of t){const t=[];for(const r of i){const i=[r.x+n[0],r.y+n[1]];di(e,i),t.push(i)}a.push(t)}if(e[2]-e[0]<=s/2){(o=e)[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(const t of a)for(const r of t)Si(r,e,i,s)}var o;return a}class Ei{constructor(t,e){this.type=At,this.geojson=t,this.geometries=e}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(ge(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const i of e.features){const{type:e,coordinates:r}=i.geometry;"Polygon"===e&&t.push(r),"MultiPolygon"===e&&t.push(...r)}if(t.length)return new Ei(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new Ei(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new Ei(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const i=[1/0,1/0,-1/0,-1/0],r=[1/0,1/0,-1/0,-1/0],s=t.canonicalID();if("Polygon"===e.type){const n=wi(e.coordinates,r,s),a=Ii(t.geometry(),i,r,s);if(!pi(i,r))return!1;for(const t of a)if(!gi(t,n))return!1}if("MultiPolygon"===e.type){const n=Ti(e.coordinates,r,s),a=Ii(t.geometry(),i,r,s);if(!pi(i,r))return!1;for(const t of a)if(!yi(t,n))return!1}return!0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const i=[1/0,1/0,-1/0,-1/0],r=[1/0,1/0,-1/0,-1/0],s=t.canonicalID();if("Polygon"===e.type){const n=wi(e.coordinates,r,s),a=Ai(t.geometry(),i,r,s);if(!pi(i,r))return!1;for(const t of a)if(!xi(t,n))return!1}if("MultiPolygon"===e.type){const n=Ti(e.coordinates,r,s),a=Ai(t.geometry(),i,r,s);if(!pi(i,r))return!1;for(const t of a)if(!vi(t,n))return!1}return!0}(t,this.geometries)}return!1}eachChild(){}outputDefined(){return!0}}class Ci{constructor(t=[],e=((t,e)=>te?1:0)){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t)}push(t){this.data.push(t),this._up(this.length++)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return--this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:i}=this,r=e[t];for(;t>0;){const s=t-1>>1,n=e[s];if(i(r,n)>=0)break;e[t]=n,t=s}e[t]=r}_down(t){const{data:e,compare:i}=this,r=this.length>>1,s=e[t];for(;t=0)break;e[t]=e[r],t=r}e[t]=s}}function zi(t,e,i,r,s){Pi(t,e,i,r||t.length-1,s||ki)}function Pi(t,e,i,r,s){for(;r>i;){if(r-i>600){var n=r-i+1,a=e-i+1,o=Math.log(n),l=.5*Math.exp(2*o/3),c=.5*Math.sqrt(o*l*(n-l)/n)*(a-n/2<0?-1:1);Pi(t,e,Math.max(i,Math.floor(e-a*l/n+c)),Math.min(r,Math.floor(e+(n-a)*l/n+c)),s)}var h=t[e],u=i,d=r;for(Mi(t,i,e),s(t[r],h)>0&&Mi(t,i,r);u0;)d--}0===s(t[i],h)?Mi(t,i,d):Mi(t,++d,r),d<=e&&(i=d+1),e<=d&&(r=d-1)}}function Mi(t,e,i){var r=t[e];t[e]=t[i],t[i]=r}function ki(t,e){return te?1:0}function Di(t,e){if(t.length<=1)return[t];const i=[];let r,s;for(const e of t){const t=Ri(e);0!==t&&(e.area=Math.abs(t),void 0===s&&(s=t<0),s===t<0?(r&&i.push(r),r=[e]):r.push(e))}if(r&&i.push(r),e>1)for(let t=0;t1?(l=t[o+1][0],c=t[o+1][1]):d>0&&(l+=h/this.kx*d,c+=u/this.ky*d)),h=this.wrap(e[0]-l)*this.kx,u=(e[1]-c)*this.ky;const p=h*h+u*u;p180;)t-=360;return t}}function Ui(t,e){return e[0]-t[0]}function Ni(t){return t[1]-t[0]+1}function ji(t,e){return t[1]>=t[0]&&t[1]t[1])return[null,null];const i=Ni(t);if(e){if(2===i)return[t,null];const e=Math.floor(i/2);return[[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===i)return[t,null];const r=Math.floor(i/2)-1;return[[t[0],t[0]+r],[t[0]+r+1,t[1]]]}function qi(t,e){if(!ji(e,t.length))return[1/0,1/0,-1/0,-1/0];const i=[1/0,1/0,-1/0,-1/0];for(let r=e[0];r<=e[1];++r)di(i,t[r]);return i}function Zi(t){const e=[1/0,1/0,-1/0,-1/0];for(const i of t)for(const t of i)di(e,t);return e}function Gi(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function Wi(t,e,i){if(!Gi(t)||!Gi(e))return NaN;let r=0,s=0;return t[2]e[2]&&(r=t[0]-e[2]),t[1]>e[3]&&(s=t[1]-e[3]),t[3]=r)return r;if(pi(s,n)){if(tr(t,e))return 0}else if(tr(e,t))return 0;let a=1/0;for(const r of t)for(let t=0,s=r.length,n=s-1;t0;){const s=a.pop();if(s[0]>=n)continue;const l=s[1],c=e?50:100;if(Ni(l)<=c){if(!ji(l,t.length))return NaN;if(e){const e=Qi(t,l,i,r);if(isNaN(e)||0===e)return e;n=Math.min(n,e)}else for(let e=l[0];e<=l[1];++e){const s=Ji(t[e],i,r);if(n=Math.min(n,s),0===n)return 0}}else{const i=$i(l,e);ir(a,n,r,t,o,i[0]),ir(a,n,r,t,o,i[1])}}return n}function nr(t,e,i,r,s,n=1/0){let a=Math.min(n,s.distance(t[0],i[0]));if(0===a)return a;const o=new Ci([[0,[0,t.length-1],[0,i.length-1]]],Ui);for(;o.length>0;){const n=o.pop();if(n[0]>=a)continue;const l=n[1],c=n[2],h=e?50:100,u=r?50:100;if(Ni(l)<=h&&Ni(c)<=u){if(!ji(l,t.length)&&ji(c,i.length))return NaN;let n;if(e&&r)n=Ki(t,l,i,c,s),a=Math.min(a,n);else if(e&&!r){const e=t.slice(l[0],l[1]+1);for(let t=c[0];t<=c[1];++t)if(n=Hi(i[t],e,s),a=Math.min(a,n),0===a)return a}else if(!e&&r){const e=i.slice(c[0],c[1]+1);for(let i=l[0];i<=l[1];++i)if(n=Hi(t[i],e,s),a=Math.min(a,n),0===a)return a}else n=Yi(t,l,i,c,s),a=Math.min(a,n)}else{const n=$i(l,e),h=$i(c,r);rr(o,a,s,t,i,n[0],h[0]),rr(o,a,s,t,i,n[0],h[1]),rr(o,a,s,t,i,n[1],h[0]),rr(o,a,s,t,i,n[1],h[1])}}return a}function ar(t){return"MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class or{constructor(t,e){this.type=St,this.geojson=t,this.geometries=e}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(ge(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new or(e,e.features.map((t=>ar(t.geometry))).flat());if("Feature"===e.type)return new or(e,ar(e.geometry));if("type"in e&&"coordinates"in e)return new or(e,ar(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const i=t.geometry(),r=i.flat().map((e=>ui([e.x,e.y],t.canonical)));if(0===i.length)return NaN;const s=new Vi(r[0][1]);let n=1/0;for(const t of e){switch(t.type){case"Point":n=Math.min(n,nr(r,!1,[t.coordinates],!1,s,n));break;case"LineString":n=Math.min(n,nr(r,!1,t.coordinates,!0,s,n));break;case"Polygon":n=Math.min(n,sr(r,!1,t.coordinates,s,n))}if(0===n)return n}return n}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const i=t.geometry(),r=i.flat().map((e=>ui([e.x,e.y],t.canonical)));if(0===i.length)return NaN;const s=new Vi(r[0][1]);let n=1/0;for(const t of e){switch(t.type){case"Point":n=Math.min(n,nr(r,!0,[t.coordinates],!1,s,n));break;case"LineString":n=Math.min(n,nr(r,!0,t.coordinates,!0,s,n));break;case"Polygon":n=Math.min(n,sr(r,!0,t.coordinates,s,n))}if(0===n)return n}return n}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const i=t.geometry();if(0===i.length||0===i[0].length)return NaN;const r=Di(i,0).map((e=>e.map((e=>e.map((e=>ui([e.x,e.y],t.canonical))))))),s=new Vi(r[0][0][0][1]);let n=1/0;for(const t of e)for(const e of r){switch(t.type){case"Point":n=Math.min(n,sr([t.coordinates],!1,e,s,n));break;case"LineString":n=Math.min(n,sr(t.coordinates,!0,e,s,n));break;case"Polygon":n=Math.min(n,er(e,t.coordinates,s,n))}if(0===n)return n}return n}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return!0}}const lr={"==":Je,"!=":Qe,">":ei,"<":ti,">=":ri,"<=":ii,array:Te,at:Me,boolean:Te,case:Re,coalesce:He,collator:si,format:ai,image:oi,in:ke,"index-of":De,interpolate:Ge,"interpolate-hcl":Ge,"interpolate-lab":Ge,length:li,let:ze,literal:ve,match:Le,number:Te,"number-format":ni,object:Te,slice:Be,step:Oe,string:Te,"to-boolean":Ie,"to-color":Ie,"to-number":Ie,"to-string":Ie,var:Pe,within:Ei,distance:or};class cr{constructor(t,e,i,r){this.name=t,this.type=e,this._evaluate=i,this.args=r}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t)}outputDefined(){return!1}static parse(t,e){const i=t[0],r=cr.definitions[i];if(!r)return e.error(`Unknown expression "${i}". If you wanted a literal array, use ["literal", [...]].`,0);const s=Array.isArray(r)?r[0]:r.type,n=Array.isArray(r)?[[r[1],r[2]]]:r.overloads,a=n.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let o=null;for(const[r,n]of a){o=new Ce(e.registry,fr,e.path,null,e.scope);const a=[];let l=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(Bt).join(", ")})`:`(${Bt(e.type)}...)`;var e})).join(" | "),r=[];for(let i=1;i{i=e?i&&fr(t):i&&t instanceof ve})),!!i&&mr(t)&&gr(t,["zoom","heatmap-density","line-progress","accumulated","is-supported-script"])}function mr(t){if(t instanceof cr){if("get"===t.name&&1===t.args.length)return!1;if("feature-state"===t.name)return!1;if("has"===t.name&&1===t.args.length)return!1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return!1;if(/^filter-/.test(t.name))return!1}if(t instanceof Ei)return!1;if(t instanceof or)return!1;let e=!0;return t.eachChild((t=>{e&&!mr(t)&&(e=!1)})),e}function _r(t){if(t instanceof cr&&"feature-state"===t.name)return!1;let e=!0;return t.eachChild((t=>{e&&!_r(t)&&(e=!1)})),e}function gr(t,e){if(t instanceof cr&&e.indexOf(t.name)>=0)return!1;let i=!0;return t.eachChild((t=>{i&&!gr(t,e)&&(i=!1)})),i}function yr(t){return{result:"success",value:t}}function xr(t){return{result:"error",value:t}}function vr(t){return"data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function br(t){return!!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function wr(t){return!!t.expression&&t.expression.interpolated}function Tr(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Sr(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function Ir(t){return t}function Ar(t,e){const i="color"===e.type,r=t.stops&&"object"==typeof t.stops[0][0],s=r||!(r||void 0!==t.property),n=t.type||(wr(e)?"exponential":"interval");if(i||"padding"===e.type){const r=i?le.parse:de.parse;(t=vt({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],r(t[1])]))),t.default=r(t.default?t.default:e.default)}if(t.colorSpace&&"rgb"!==(a=t.colorSpace)&&"hcl"!==a&&"lab"!==a)throw new Error(`Unknown color space: "${t.colorSpace}"`);var a;let o,l,c;if("exponential"===n)o=Pr;else if("interval"===n)o=zr;else if("categorical"===n){o=Cr,l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];c=typeof t.stops[0][0]}else{if("identity"!==n)throw new Error(`Unknown function type "${n}"`);o=Mr}if(r){const i={},r=[];for(let e=0;et[0])),evaluate:({zoom:i},r)=>Pr({stops:s,base:t.base},e,i).evaluate(i,r)}}if(s){const i="exponential"===n?{name:"exponential",base:void 0!==t.base?t.base:1}:null;return{kind:"camera",interpolationType:i,interpolationFactor:Ge.interpolationFactor.bind(void 0,i),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:i})=>o(t,e,i,l,c)}}return{kind:"source",evaluate(i,r){const s=r&&r.properties?r.properties[t.property]:void 0;return void 0===s?Er(t.default,e.default):o(t,e,s,l,c)}}}function Er(t,e,i){return void 0!==t?t:void 0!==e?e:void 0!==i?i:void 0}function Cr(t,e,i,r,s){return Er(typeof i===s?r[i]:void 0,t.default,e.default)}function zr(t,e,i){if("number"!==Tr(i))return Er(t.default,e.default);const r=t.stops.length;if(1===r)return t.stops[0][1];if(i<=t.stops[0][0])return t.stops[0][1];if(i>=t.stops[r-1][0])return t.stops[r-1][1];const s=Fe(t.stops.map((t=>t[0])),i);return t.stops[s][1]}function Pr(t,e,i){const r=void 0!==t.base?t.base:1;if("number"!==Tr(i))return Er(t.default,e.default);const s=t.stops.length;if(1===s)return t.stops[0][1];if(i<=t.stops[0][0])return t.stops[0][1];if(i>=t.stops[s-1][0])return t.stops[s-1][1];const n=Fe(t.stops.map((t=>t[0])),i),a=function(t,e,i,r){const s=r-i,n=t-i;return 0===s?0:1===e?n/s:(Math.pow(e,n)-1)/(Math.pow(e,s)-1)}(i,r,t.stops[n][0],t.stops[n+1][0]),o=t.stops[n][1],l=t.stops[n+1][1],c=Ze[e.type]||Ir;return"function"==typeof o.evaluate?{evaluate(...e){const i=o.evaluate.apply(void 0,e),r=l.evaluate.apply(void 0,e);if(void 0!==i&&void 0!==r)return c(i,r,a,t.colorSpace)}}:c(o,l,a,t.colorSpace)}function Mr(t,e,i){switch(e.type){case"color":i=le.parse(i);break;case"formatted":i=ue.fromString(i.toString());break;case"resolvedImage":i=me.fromString(i.toString());break;case"padding":i=de.parse(i);break;default:Tr(i)===e.type||"enum"===e.type&&e.values[i]||(i=void 0)}return Er(i,t.default,e.default)}cr.register(lr,{error:[{kind:"error"},[It],(t,[e])=>{throw new be(e.evaluate(t))}],typeof:[It,[zt],(t,[e])=>Bt(ye(e.evaluate(t)))],"to-rgba":[Rt(St,4),[Et],(t,[e])=>{const[i,r,s,n]=e.evaluate(t).rgb;return[255*i,255*r,255*s,n]}],rgb:[Et,[St,St,St],hr],rgba:[Et,[St,St,St,St],hr],has:{type:At,overloads:[[[It],(t,[e])=>ur(e.evaluate(t),t.properties())],[[It,Ct],(t,[e,i])=>ur(e.evaluate(t),i.evaluate(t))]]},get:{type:zt,overloads:[[[It],(t,[e])=>dr(e.evaluate(t),t.properties())],[[It,Ct],(t,[e,i])=>dr(e.evaluate(t),i.evaluate(t))]]},"feature-state":[zt,[It],(t,[e])=>dr(e.evaluate(t),t.featureState||{})],properties:[Ct,[],t=>t.properties()],"geometry-type":[It,[],t=>t.geometryType()],id:[zt,[],t=>t.id()],zoom:[St,[],t=>t.globals.zoom],"heatmap-density":[St,[],t=>t.globals.heatmapDensity||0],"line-progress":[St,[],t=>t.globals.lineProgress||0],accumulated:[zt,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[St,pr(St),(t,e)=>{let i=0;for(const r of e)i+=r.evaluate(t);return i}],"*":[St,pr(St),(t,e)=>{let i=1;for(const r of e)i*=r.evaluate(t);return i}],"-":{type:St,overloads:[[[St,St],(t,[e,i])=>e.evaluate(t)-i.evaluate(t)],[[St],(t,[e])=>-e.evaluate(t)]]},"/":[St,[St,St],(t,[e,i])=>e.evaluate(t)/i.evaluate(t)],"%":[St,[St,St],(t,[e,i])=>e.evaluate(t)%i.evaluate(t)],ln2:[St,[],()=>Math.LN2],pi:[St,[],()=>Math.PI],e:[St,[],()=>Math.E],"^":[St,[St,St],(t,[e,i])=>Math.pow(e.evaluate(t),i.evaluate(t))],sqrt:[St,[St],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[St,[St],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[St,[St],(t,[e])=>Math.log(e.evaluate(t))],log2:[St,[St],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[St,[St],(t,[e])=>Math.sin(e.evaluate(t))],cos:[St,[St],(t,[e])=>Math.cos(e.evaluate(t))],tan:[St,[St],(t,[e])=>Math.tan(e.evaluate(t))],asin:[St,[St],(t,[e])=>Math.asin(e.evaluate(t))],acos:[St,[St],(t,[e])=>Math.acos(e.evaluate(t))],atan:[St,[St],(t,[e])=>Math.atan(e.evaluate(t))],min:[St,pr(St),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[St,pr(St),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[St,[St],(t,[e])=>Math.abs(e.evaluate(t))],round:[St,[St],(t,[e])=>{const i=e.evaluate(t);return i<0?-Math.round(-i):Math.round(i)}],floor:[St,[St],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[St,[St],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[At,[It,zt],(t,[e,i])=>t.properties()[e.value]===i.value],"filter-id-==":[At,[zt],(t,[e])=>t.id()===e.value],"filter-type-==":[At,[It],(t,[e])=>t.geometryType()===e.value],"filter-<":[At,[It,zt],(t,[e,i])=>{const r=t.properties()[e.value],s=i.value;return typeof r==typeof s&&r{const i=t.id(),r=e.value;return typeof i==typeof r&&i":[At,[It,zt],(t,[e,i])=>{const r=t.properties()[e.value],s=i.value;return typeof r==typeof s&&r>s}],"filter-id->":[At,[zt],(t,[e])=>{const i=t.id(),r=e.value;return typeof i==typeof r&&i>r}],"filter-<=":[At,[It,zt],(t,[e,i])=>{const r=t.properties()[e.value],s=i.value;return typeof r==typeof s&&r<=s}],"filter-id-<=":[At,[zt],(t,[e])=>{const i=t.id(),r=e.value;return typeof i==typeof r&&i<=r}],"filter->=":[At,[It,zt],(t,[e,i])=>{const r=t.properties()[e.value],s=i.value;return typeof r==typeof s&&r>=s}],"filter-id->=":[At,[zt],(t,[e])=>{const i=t.id(),r=e.value;return typeof i==typeof r&&i>=r}],"filter-has":[At,[zt],(t,[e])=>e.value in t.properties()],"filter-has-id":[At,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[At,[Rt(It)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[At,[Rt(zt)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[At,[It,Rt(zt)],(t,[e,i])=>i.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[At,[It,Rt(zt)],(t,[e,i])=>function(t,e,i,r){for(;i<=r;){const s=i+r>>1;if(e[s]===t)return!0;e[s]>t?r=s-1:i=s+1}return!1}(t.properties()[e.value],i.value,0,i.value.length-1)],all:{type:At,overloads:[[[At,At],(t,[e,i])=>e.evaluate(t)&&i.evaluate(t)],[pr(At),(t,e)=>{for(const i of e)if(!i.evaluate(t))return!1;return!0}]]},any:{type:At,overloads:[[[At,At],(t,[e,i])=>e.evaluate(t)||i.evaluate(t)],[pr(At),(t,e)=>{for(const i of e)if(i.evaluate(t))return!0;return!1}]]},"!":[At,[At],(t,[e])=>!e.evaluate(t)],"is-supported-script":[At,[It],(t,[e])=>{const i=t.globals&&t.globals.isSupportedScript;return!i||i(e.evaluate(t))}],upcase:[It,[It],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[It,[It],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[It,pr(zt),(t,e)=>e.map((e=>xe(e.evaluate(t)))).join("")],"resolved-locale":[It,[Pt],(t,[e])=>e.evaluate(t).resolvedLocale()]});class kr{constructor(t,e){var i;this.expression=t,this._warningHistory={},this._evaluator=new Ee,this._defaultValue=e?"color"===(i=e).type&&Sr(i.default)?new le(0,0,0,0):"color"===i.type?le.parse(i.default)||null:"padding"===i.type?de.parse(i.default)||null:"variableAnchorOffsetCollection"===i.type?fe.parse(i.default)||null:void 0===i.default?null:i.default:null,this._enumValues=e&&"enum"===e.type?e.values:null}evaluateWithoutErrorHandling(t,e,i,r,s,n){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=i,this._evaluator.canonical=r,this._evaluator.availableImages=s||null,this._evaluator.formattedSection=n,this.expression.evaluate(this._evaluator)}evaluate(t,e,i,r,s,n){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=i||null,this._evaluator.canonical=r,this._evaluator.availableImages=s||null,this._evaluator.formattedSection=n||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new be(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function Dr(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in lr}function Lr(t,e){const i=new Ce(lr,fr,[],e?function(t){const e={color:Et,string:It,number:St,enum:It,boolean:At,formatted:Mt,padding:kt,resolvedImage:Dt,variableAnchorOffsetCollection:Lt};return"array"===t.type?Rt(e[t.value]||zt,t.length):e[t.type]}(e):void 0),r=i.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return r?yr(new kr(r,e)):xr(i.errors)}class Rr{constructor(t,e){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!_r(e.expression)}evaluateWithoutErrorHandling(t,e,i,r,s,n){return this._styleExpression.evaluateWithoutErrorHandling(t,e,i,r,s,n)}evaluate(t,e,i,r,s,n){return this._styleExpression.evaluate(t,e,i,r,s,n)}}class Br{constructor(t,e,i,r){this.kind=t,this.zoomStops=i,this._styleExpression=e,this.isStateDependent="camera"!==t&&!_r(e.expression),this.interpolationType=r}evaluateWithoutErrorHandling(t,e,i,r,s,n){return this._styleExpression.evaluateWithoutErrorHandling(t,e,i,r,s,n)}evaluate(t,e,i,r,s,n){return this._styleExpression.evaluate(t,e,i,r,s,n)}interpolationFactor(t,e,i){return this.interpolationType?Ge.interpolationFactor(this.interpolationType,t,e,i):0}}function Fr(t,e){const i=Lr(t,e);if("error"===i.result)return i;const r=i.value.expression,s=mr(r);if(!s&&!vr(e))return xr([new bt("","data expressions not supported")]);const n=gr(r,["zoom"]);if(!n&&!br(e))return xr([new bt("","zoom expressions not supported")]);const a=Vr(r);return a||n?a instanceof bt?xr([a]):a instanceof Ge&&!wr(e)?xr([new bt("",'"interpolate" expressions cannot be used with this property')]):yr(a?new Br(s?"camera":"composite",i.value,a.labels,a instanceof Ge?a.interpolation:void 0):new Rr(s?"constant":"source",i.value)):xr([new bt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class Or{constructor(t,e){this._parameters=t,this._specification=e,vt(this,Ar(this._parameters,this._specification))}static deserialize(t){return new Or(t._parameters,t._specification)}static serialize(t){return{_parameters:t._parameters,_specification:t._specification}}}function Vr(t){let e=null;if(t instanceof ze)e=Vr(t.result);else if(t instanceof He){for(const i of t.args)if(e=Vr(i),e)break}else(t instanceof Oe||t instanceof Ge)&&t.input instanceof cr&&"zoom"===t.input.name&&(e=t);return e instanceof bt||t.eachChild((t=>{const i=Vr(t);i instanceof bt?e=i:!e&&i?e=new bt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&i&&e!==i&&(e=new bt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))})),e}function Ur(t){if(!0===t||!1===t)return!0;if(!Array.isArray(t)||0===t.length)return!1;switch(t[0]){case"has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case"any":case"all":for(const e of t.slice(1))if(!Ur(e)&&"boolean"!=typeof e)return!1;return!0;default:return!0}}const Nr={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function jr(t){if(null==t)return{filter:()=>!0,needGeometry:!1};Ur(t)||(t=Zr(t));const e=Lr(t,Nr);if("error"===e.result)throw new Error(e.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return{filter:(t,i,r)=>e.value.evaluate(t,i,{},r),needGeometry:qr(t)}}function $r(t,e){return te?1:0}function qr(t){if(!Array.isArray(t))return!1;if("within"===t[0]||"distance"===t[0])return!0;for(let e=1;e"===e||"<="===e||">="===e?Gr(t[1],t[2],e):"any"===e?(i=t.slice(1),["any"].concat(i.map(Zr))):"all"===e?["all"].concat(t.slice(1).map(Zr)):"none"===e?["all"].concat(t.slice(1).map(Zr).map(Xr)):"in"===e?Wr(t[1],t.slice(2)):"!in"===e?Xr(Wr(t[1],t.slice(2))):"has"===e?Hr(t[1]):"!has"!==e||Xr(Hr(t[1]));var i}function Gr(t,e,i){switch(t){case"$type":return[`filter-type-${i}`,e];case"$id":return[`filter-id-${i}`,e];default:return[`filter-${i}`,t,e]}}function Wr(t,e){if(0===e.length)return!1;switch(t){case"$type":return["filter-type-in",["literal",e]];case"$id":return["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort($r)]]:["filter-in-small",t,["literal",e]]}}function Hr(t){switch(t){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",t]}}function Xr(t){return["!",t]}function Kr(t){const e=t.value;return e?[new xt(t.key,e,"constants have been deprecated as of v8")]:[]}function Yr(t){return t instanceof Number||t instanceof String||t instanceof Boolean?t.valueOf():t}function Jr(t){if(Array.isArray(t))return t.map(Jr);if(t instanceof Object&&!(t instanceof Number||t instanceof String||t instanceof Boolean)){const e={};for(const i in t)e[i]=Jr(t[i]);return e}return Yr(t)}function Qr(t){const e=t.key,i=t.value,r=t.valueSpec||{},s=t.objectElementValidators||{},n=t.style,a=t.styleSpec,o=t.validateSpec;let l=[];const c=Tr(i);if("object"!==c)return[new xt(e,i,`object expected, ${c} found`)];for(const t in i){const c=t.split(".")[0],h=r[c]||r["*"];let u;if(s[c])u=s[c];else if(r[c])u=o;else if(s["*"])u=s["*"];else{if(!r["*"]){l.push(new xt(e,i[t],`unknown property "${t}"`));continue}u=o}l=l.concat(u({key:(e?`${e}.`:e)+t,value:i[t],valueSpec:h,style:n,styleSpec:a,object:i,objectKey:t,validateSpec:o},i))}for(const t in r)s[t]||r[t].required&&void 0===r[t].default&&void 0===i[t]&&l.push(new xt(e,i,`missing required property "${t}"`));return l}function ts(t){const e=t.value,i=t.valueSpec,r=t.style,s=t.styleSpec,n=t.key,a=t.arrayElementValidator||t.validateSpec;if("array"!==Tr(e))return[new xt(n,e,`array expected, ${Tr(e)} found`)];if(i.length&&e.length!==i.length)return[new xt(n,e,`array length ${i.length} expected, length ${e.length} found`)];if(i["min-length"]&&e.lengthr.maximum?[new xt(e,i,`${i} is greater than the maximum value ${r.maximum}`)]:[]}function is(t){const e=t.valueSpec,i=Yr(t.value.type);let r,s,n,a={};const o="categorical"!==i&&void 0===t.value.property,l=!o,c="array"===Tr(t.value.stops)&&"array"===Tr(t.value.stops[0])&&"object"===Tr(t.value.stops[0][0]),h=Qr({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===i)return[new xt(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const r=t.value;return e=e.concat(ts({key:t.key,value:r,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:u})),"array"===Tr(r)&&0===r.length&&e.push(new xt(t.key,r,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return"identity"===i&&o&&h.push(new xt(t.key,t.value,'missing required property "property"')),"identity"===i||t.value.stops||h.push(new xt(t.key,t.value,'missing required property "stops"')),"exponential"===i&&t.valueSpec.expression&&!wr(t.valueSpec)&&h.push(new xt(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!vr(t.valueSpec)?h.push(new xt(t.key,t.value,"property functions not supported")):o&&!br(t.valueSpec)&&h.push(new xt(t.key,t.value,"zoom functions not supported"))),"categorical"!==i&&!c||void 0!==t.value.property||h.push(new xt(t.key,t.value,'"property" property is required')),h;function u(t){let i=[];const r=t.value,o=t.key;if("array"!==Tr(r))return[new xt(o,r,`array expected, ${Tr(r)} found`)];if(2!==r.length)return[new xt(o,r,`array length 2 expected, length ${r.length} found`)];if(c){if("object"!==Tr(r[0]))return[new xt(o,r,`object expected, ${Tr(r[0])} found`)];if(void 0===r[0].zoom)return[new xt(o,r,"object stop key must have zoom")];if(void 0===r[0].value)return[new xt(o,r,"object stop key must have value")];if(n&&n>Yr(r[0].zoom))return[new xt(o,r[0].zoom,"stop zoom values must appear in ascending order")];Yr(r[0].zoom)!==n&&(n=Yr(r[0].zoom),s=void 0,a={}),i=i.concat(Qr({key:`${o}[0]`,value:r[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:es,value:d}}))}else i=i.concat(d({key:`${o}[0]`,value:r[0],valueSpec:{},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},r));return Dr(Jr(r[1]))?i.concat([new xt(`${o}[1]`,r[1],"expressions are not allowed in function stops.")]):i.concat(t.validateSpec({key:`${o}[1]`,value:r[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function d(t,n){const o=Tr(t.value),l=Yr(t.value),c=null!==t.value?t.value:n;if(r){if(o!==r)return[new xt(t.key,c,`${o} stop domain type must match previous stop domain type ${r}`)]}else r=o;if("number"!==o&&"string"!==o&&"boolean"!==o)return[new xt(t.key,c,"stop domain value must be a number, string, or boolean")];if("number"!==o&&"categorical"!==i){let r=`number expected, ${o} found`;return vr(e)&&void 0===i&&(r+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new xt(t.key,c,r)]}return"categorical"!==i||"number"!==o||isFinite(l)&&Math.floor(l)===l?"categorical"!==i&&"number"===o&&void 0!==s&&lnew xt(`${t.key}${e.key}`,t.value,e.message)));const i=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!i.outputDefined())return[new xt(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!_r(i))return[new xt(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!_r(i))return[new xt(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!gr(i,["zoom","feature-state"]))return[new xt(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!mr(i))return[new xt(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function ss(t){const e=t.key,i=t.value,r=t.valueSpec,s=[];return Array.isArray(r.values)?-1===r.values.indexOf(Yr(i))&&s.push(new xt(e,i,`expected one of [${r.values.join(", ")}], ${JSON.stringify(i)} found`)):-1===Object.keys(r.values).indexOf(Yr(i))&&s.push(new xt(e,i,`expected one of [${Object.keys(r.values).join(", ")}], ${JSON.stringify(i)} found`)),s}function ns(t){return Ur(Jr(t.value))?rs(vt({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):as(t)}function as(t){const e=t.value,i=t.key;if("array"!==Tr(e))return[new xt(i,e,`array expected, ${Tr(e)} found`)];const r=t.styleSpec;let s,n=[];if(e.length<1)return[new xt(i,e,"filter array must have at least 1 element")];switch(n=n.concat(ss({key:`${i}[0]`,value:e[0],valueSpec:r.filter_operator,style:t.style,styleSpec:t.styleSpec})),Yr(e[0])){case"<":case"<=":case">":case">=":e.length>=2&&"$type"===Yr(e[1])&&n.push(new xt(i,e,`"$type" cannot be use with operator "${e[0]}"`));case"==":case"!=":3!==e.length&&n.push(new xt(i,e,`filter array for operator "${e[0]}" must have 3 elements`));case"in":case"!in":e.length>=2&&(s=Tr(e[1]),"string"!==s&&n.push(new xt(`${i}[1]`,e[1],`string expected, ${s} found`)));for(let a=2;a{t in i&&e.push(new xt(r,i[t],`"${t}" is prohibited for ref layers`))})),s.layers.forEach((e=>{Yr(e.id)===o&&(t=e)})),t?t.ref?e.push(new xt(r,i.ref,"ref cannot reference another ref layer")):a=Yr(t.type):e.push(new xt(r,i.ref,`ref layer "${o}" not found`))}else if("background"!==a)if(i.source){const t=s.sources&&s.sources[i.source],n=t&&Yr(t.type);t?"vector"===n&&"raster"===a?e.push(new xt(r,i.source,`layer "${i.id}" requires a raster source`)):"raster-dem"!==n&&"hillshade"===a?e.push(new xt(r,i.source,`layer "${i.id}" requires a raster-dem source`)):"raster"===n&&"raster"!==a?e.push(new xt(r,i.source,`layer "${i.id}" requires a vector source`)):"vector"!==n||i["source-layer"]?"raster-dem"===n&&"hillshade"!==a?e.push(new xt(r,i.source,"raster-dem source can only be used with layer type 'hillshade'.")):"line"!==a||!i.paint||!i.paint["line-gradient"]||"geojson"===n&&t.lineMetrics||e.push(new xt(r,i,`layer "${i.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):e.push(new xt(r,i,`layer "${i.id}" must specify a "source-layer"`)):e.push(new xt(r,i.source,`source "${i.source}" not found`))}else e.push(new xt(r,i,'missing required property "source"'));return e=e.concat(Qr({key:r,value:i,valueSpec:n.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${r}.type`,value:i.type,valueSpec:n.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:i,objectKey:"type"}),filter:ns,layout:t=>Qr({layer:i,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>cs(vt({layerType:a},t))}}),paint:t=>Qr({layer:i,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>ls(vt({layerType:a},t))}})}})),e}function us(t){const e=t.value,i=t.key,r=Tr(e);return"string"!==r?[new xt(i,e,`string expected, ${r} found`)]:[]}const ds={promoteId:function({key:t,value:e}){if("string"===Tr(e))return us({key:t,value:e});{const i=[];for(const r in e)i.push(...us({key:`${t}.${r}`,value:e[r]}));return i}}};function ps(t){const e=t.value,i=t.key,r=t.styleSpec,s=t.style,n=t.validateSpec;if(!e.type)return[new xt(i,e,'"type" is required')];const a=Yr(e.type);let o;switch(a){case"vector":case"raster":return o=Qr({key:i,value:e,valueSpec:r[`source_${a.replace("-","_")}`],style:t.style,styleSpec:r,objectElementValidators:ds,validateSpec:n}),o;case"raster-dem":return o=function(t){var e;const i=null!==(e=t.sourceName)&&void 0!==e?e:"",r=t.value,s=t.styleSpec,n=s.source_raster_dem,a=t.style;let o=[];const l=Tr(r);if(void 0===r)return o;if("object"!==l)return o.push(new xt("source_raster_dem",r,`object expected, ${l} found`)),o;const c="custom"===Yr(r.encoding),h=["redFactor","greenFactor","blueFactor","baseShift"],u=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in r)!c&&h.includes(e)?o.push(new xt(e,r[e],`In "${i}": "${e}" is only valid when "encoding" is set to "custom". ${u} encoding found`)):n[e]?o=o.concat(t.validateSpec({key:e,value:r[e],valueSpec:n[e],validateSpec:t.validateSpec,style:a,styleSpec:s})):o.push(new xt(e,r[e],`unknown property "${e}"`));return o}({sourceName:i,value:e,style:t.style,styleSpec:r,validateSpec:n}),o;case"geojson":if(o=Qr({key:i,value:e,valueSpec:r.source_geojson,style:s,styleSpec:r,validateSpec:n,objectElementValidators:ds}),e.cluster)for(const t in e.clusterProperties){const[r,s]=e.clusterProperties[t],a="string"==typeof r?[r,["accumulated"],["get",t]]:r;o.push(...rs({key:`${i}.${t}.map`,value:s,validateSpec:n,expressionContext:"cluster-map"})),o.push(...rs({key:`${i}.${t}.reduce`,value:a,validateSpec:n,expressionContext:"cluster-reduce"}))}return o;case"video":return Qr({key:i,value:e,valueSpec:r.source_video,style:s,validateSpec:n,styleSpec:r});case"image":return Qr({key:i,value:e,valueSpec:r.source_image,style:s,validateSpec:n,styleSpec:r});case"canvas":return[new xt(i,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return ss({key:`${i}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:s,validateSpec:n,styleSpec:r})}}function fs(t){const e=t.value,i=t.styleSpec,r=i.light,s=t.style;let n=[];const a=Tr(e);if(void 0===e)return n;if("object"!==a)return n=n.concat([new xt("light",e,`object expected, ${a} found`)]),n;for(const a in e){const o=a.match(/^(.*)-transition$/);n=n.concat(o&&r[o[1]]&&r[o[1]].transition?t.validateSpec({key:a,value:e[a],valueSpec:i.transition,validateSpec:t.validateSpec,style:s,styleSpec:i}):r[a]?t.validateSpec({key:a,value:e[a],valueSpec:r[a],validateSpec:t.validateSpec,style:s,styleSpec:i}):[new xt(a,e[a],`unknown property "${a}"`)])}return n}function ms(t){const e=t.value,i=t.styleSpec,r=i.sky,s=t.style,n=Tr(e);if(void 0===e)return[];if("object"!==n)return[new xt("sky",e,`object expected, ${n} found`)];let a=[];for(const n in e)a=a.concat(r[n]?t.validateSpec({key:n,value:e[n],valueSpec:r[n],style:s,styleSpec:i}):[new xt(n,e[n],`unknown property "${n}"`)]);return a}function _s(t){const e=t.value,i=t.styleSpec,r=i.terrain,s=t.style;let n=[];const a=Tr(e);if(void 0===e)return n;if("object"!==a)return n=n.concat([new xt("terrain",e,`object expected, ${a} found`)]),n;for(const a in e)n=n.concat(r[a]?t.validateSpec({key:a,value:e[a],valueSpec:r[a],validateSpec:t.validateSpec,style:s,styleSpec:i}):[new xt(a,e[a],`unknown property "${a}"`)]);return n}function gs(t){let e=[];const i=t.value,r=t.key;if(Array.isArray(i)){const s=[],n=[];for(const a in i)i[a].id&&s.includes(i[a].id)&&e.push(new xt(r,i,`all the sprites' ids must be unique, but ${i[a].id} is duplicated`)),s.push(i[a].id),i[a].url&&n.includes(i[a].url)&&e.push(new xt(r,i,`all the sprites' URLs must be unique, but ${i[a].url} is duplicated`)),n.push(i[a].url),e=e.concat(Qr({key:`${r}[${a}]`,value:i[a],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:t.validateSpec}));return e}return us({key:r,value:i})}const ys={"*":()=>[],array:ts,boolean:function(t){const e=t.value,i=t.key,r=Tr(e);return"boolean"!==r?[new xt(i,e,`boolean expected, ${r} found`)]:[]},number:es,color:function(t){const e=t.key,i=t.value,r=Tr(i);return"string"!==r?[new xt(e,i,`color expected, ${r} found`)]:le.parse(String(i))?[]:[new xt(e,i,`color expected, "${i}" found`)]},constants:Kr,enum:ss,filter:ns,function:is,layer:hs,object:Qr,source:ps,light:fs,sky:ms,terrain:_s,projection:function(t){const e=t.value,i=t.styleSpec,r=i.projection,s=t.style,n=Tr(e);if(void 0===e)return[];if("object"!==n)return[new xt("projection",e,`object expected, ${n} found`)];let a=[];for(const n in e)a=a.concat(r[n]?t.validateSpec({key:n,value:e[n],valueSpec:r[n],style:s,styleSpec:i}):[new xt(n,e[n],`unknown property "${n}"`)]);return a},string:us,formatted:function(t){return 0===us(t).length?[]:rs(t)},resolvedImage:function(t){return 0===us(t).length?[]:rs(t)},padding:function(t){const e=t.key,i=t.value;if("array"===Tr(i)){if(i.length<1||i.length>4)return[new xt(e,i,`padding requires 1 to 4 values; ${i.length} values found`)];const r={type:"number"};let s=[];for(let n=0;n[]}})),t.constants&&(i=i.concat(Kr({key:"constants",value:t.constants,style:t,styleSpec:e,validateSpec:xs}))),Ts(i)}function ws(t){return function(e){return t({...e,validateSpec:xs})}}function Ts(t){return[].concat(t).sort(((t,e)=>t.line-e.line))}function Ss(t){return function(...e){return Ts(t.apply(this,e))}}bs.source=Ss(ws(ps)),bs.sprite=Ss(ws(gs)),bs.glyphs=Ss(ws(vs)),bs.light=Ss(ws(fs)),bs.sky=Ss(ws(ms)),bs.terrain=Ss(ws(_s)),bs.layer=Ss(ws(hs)),bs.filter=Ss(ws(ns)),bs.paintProperty=Ss(ws(ls)),bs.layoutProperty=Ss(ws(cs));const Is=bs,As=Is.light,Es=Is.sky,Cs=Is.paintProperty,zs=Is.layoutProperty;function Ps(t,e){let i=!1;if(e&&e.length)for(const r of e)t.fire(new st(new Error(r.message))),i=!0;return i}class Ms{constructor(t,e,i){const r=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const s=new Int32Array(this.arrayBuffer);t=s[0],this.d=(e=s[1])+2*(i=s[2]);for(let t=0;t=c[l+0]&&r>=c[l+1])?(a[u]=!0,n.push(s[u])):a[u]=!1}}}}_forEachCell(t,e,i,r,s,n,a,o){const l=this._convertToCellCoord(t),c=this._convertToCellCoord(e),h=this._convertToCellCoord(i),u=this._convertToCellCoord(r);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++){const c=this.d*l+d;if((!o||o(this._convertFromCellCoord(d),this._convertFromCellCoord(l),this._convertFromCellCoord(d+1),this._convertFromCellCoord(l+1)))&&s.call(this,t,e,i,r,c,n,a,o))return}}_convertFromCellCoord(t){return(t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let i=0;for(let t=0;t=0)continue;const n=t[r];s[r]=ks[i].shallow.indexOf(r)>=0?n:Fs(n,e)}t instanceof Error&&(s.message=t.message)}if(s.$name)throw new Error("$name property is reserved for worker serialization logic.");return"Object"!==i&&(s.$name=i),s}function Os(t){if(Bs(t))return t;if(Array.isArray(t))return t.map(Os);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=Rs(t)||"Object";if(!ks[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:i}=ks[e];if(!i)throw new Error(`can't deserialize unregistered class ${e}`);if(i.deserialize)return i.deserialize(t);const r=Object.create(i.prototype);for(const i of Object.keys(t)){if("$name"===i)continue;const s=t[i];r[i]=ks[e].shallow.indexOf(i)>=0?s:Os(s)}return r}class Vs{constructor(){this.first=!0}update(t,e){const i=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=i,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=i,!0):(this.lastFloorZoom>i?(this.lastIntegerZoom=i+1,this.lastIntegerZoomTime=e):this.lastFloorZoomt>=128&&t<=255,"Hangul Jamo":t=>t>=4352&&t<=4607,Khmer:t=>t>=6016&&t<=6143,"General Punctuation":t=>t>=8192&&t<=8303,"Letterlike Symbols":t=>t>=8448&&t<=8527,"Number Forms":t=>t>=8528&&t<=8591,"Miscellaneous Technical":t=>t>=8960&&t<=9215,"Control Pictures":t=>t>=9216&&t<=9279,"Optical Character Recognition":t=>t>=9280&&t<=9311,"Enclosed Alphanumerics":t=>t>=9312&&t<=9471,"Geometric Shapes":t=>t>=9632&&t<=9727,"Miscellaneous Symbols":t=>t>=9728&&t<=9983,"Miscellaneous Symbols and Arrows":t=>t>=11008&&t<=11263,"Ideographic Description Characters":t=>t>=12272&&t<=12287,"CJK Symbols and Punctuation":t=>t>=12288&&t<=12351,Katakana:t=>t>=12448&&t<=12543,Kanbun:t=>t>=12688&&t<=12703,"CJK Strokes":t=>t>=12736&&t<=12783,"Enclosed CJK Letters and Months":t=>t>=12800&&t<=13055,"CJK Compatibility":t=>t>=13056&&t<=13311,"Yijing Hexagram Symbols":t=>t>=19904&&t<=19967,"Private Use Area":t=>t>=57344&&t<=63743,"Vertical Forms":t=>t>=65040&&t<=65055,"CJK Compatibility Forms":t=>t>=65072&&t<=65103,"Small Form Variants":t=>t>=65104&&t<=65135,"Halfwidth and Fullwidth Forms":t=>t>=65280&&t<=65519};function Ns(t){for(const e of t)if(qs(e.charCodeAt(0)))return!0;return!1}function js(t){const e=t.map((t=>{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}js(["Arab","Dupl","Mong","Ougr","Syrc"]);const $s=js(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function qs(t){return!(746!==t&&747!==t&&(t<4352||!(Us["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||Us["CJK Compatibility"](t)||Us["CJK Strokes"](t)||!(!Us["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||Us["Enclosed CJK Letters and Months"](t)||Us["Ideographic Description Characters"](t)||Us.Kanbun(t)||Us.Katakana(t)&&12540!==t||!(!Us["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!Us["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||Us["Vertical Forms"](t)||Us["Yijing Hexagram Symbols"](t)||/\p{sc=Cans}/u.test(String.fromCodePoint(t))||/\p{sc=Hang}/u.test(String.fromCodePoint(t))||$s.test(String.fromCodePoint(t)))))}const Zs=js(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function Gs(t){return Zs.test(String.fromCodePoint(t))}function Ws(t,e){return!(!e&&Gs(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||Us.Khmer(t))}function Hs(t){for(const e of t)if(Gs(e.charCodeAt(0)))return!0;return!1}const Xs=new class{constructor(){this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL}getState(){return{pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getPluginURL(){return this.pluginURL}getRTLTextPluginStatus(){return this.pluginStatus}};class Ks{constructor(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new Vs,this.transition={})}isSupportedScript(t){return function(t,e){for(const i of t)if(!Ws(i.charCodeAt(0),e))return!1;return!0}(t,"loaded"===Xs.getRTLTextPluginStatus())}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),i=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*i}:{fromScale:.5,toScale:1,t:1-(1-i)*e}}}class Ys{constructor(t,e){this.property=t,this.value=e,this.expression=function(t,e){if(Sr(t))return new Or(t,e);if(Dr(t)){const i=Fr(t,e);if("error"===i.result)throw new Error(i.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return i.value}{let i=t;return"color"===e.type&&"string"==typeof t?i=le.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)&&(i=fe.parse(t)):i=de.parse(t),{kind:"constant",evaluate:()=>i}}}(void 0===e?t.specification.default:e,t.specification)}isDataDriven(){return"source"===this.expression.kind||"composite"===this.expression.kind}possiblyEvaluate(t,e,i){return this.property.possiblyEvaluate(this,t,e,i)}}class Js{constructor(t){this.property=t,this.value=new Ys(t,void 0)}transitioned(t,e){return new tn(this.property,this.value,e,y({},t.transition,this.transition),t.now)}untransitioned(){return new tn(this.property,this.value,null,{},0)}}class Qs{constructor(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues)}getValue(t){return I(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Js(this._values[t].property)),this._values[t].value=new Ys(this._values[t].property,null===e?void 0:I(e))}getTransition(t){return I(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Js(this._values[t].property)),this._values[t].transition=I(e)||void 0}serialize(){const t={};for(const e of Object.keys(this._values)){const i=this.getValue(e);void 0!==i&&(t[e]=i);const r=this.getTransition(e);void 0!==r&&(t[`${e}-transition`]=r)}return t}transitioned(t,e){const i=new en(this._properties);for(const r of Object.keys(this._values))i._values[r]=this._values[r].transitioned(t,e._values[r]);return i}untransitioned(){const t=new en(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class tn{constructor(t,e,i,r,s){this.property=t,this.value=e,this.begin=s+r.delay||0,this.end=this.begin+r.duration||0,t.specification.transition&&(r.delay||r.duration)&&(this.prior=i)}possiblyEvaluate(t,e,i){const r=t.now||0,s=this.value.possiblyEvaluate(t,e,i),n=this.prior;if(n){if(r>this.end)return this.prior=null,s;if(this.value.isDataDriven())return this.prior=null,s;if(r=1)return 1;const e=t*t,i=e*t;return 4*(t<.5?i:3*(t-e)+i-.75)}(a))}}return s}}class en{constructor(t){this._properties=t,this._values=Object.create(t.defaultTransitioningPropertyValues)}possiblyEvaluate(t,e,i){const r=new nn(this._properties);for(const s of Object.keys(this._values))r._values[s]=this._values[s].possiblyEvaluate(t,e,i);return r}hasTransition(){for(const t of Object.keys(this._values))if(this._values[t].prior)return!0;return!1}}class rn{constructor(t){this._properties=t,this._values=Object.create(t.defaultPropertyValues)}hasValue(t){return void 0!==this._values[t].value}getValue(t){return I(this._values[t].value)}setValue(t,e){this._values[t]=new Ys(this._values[t].property,null===e?void 0:I(e))}serialize(){const t={};for(const e of Object.keys(this._values)){const i=this.getValue(e);void 0!==i&&(t[e]=i)}return t}possiblyEvaluate(t,e,i){const r=new nn(this._properties);for(const s of Object.keys(this._values))r._values[s]=this._values[s].possiblyEvaluate(t,e,i);return r}}class sn{constructor(t,e,i){this.property=t,this.value=e,this.parameters=i}isConstant(){return"constant"===this.value.kind}constantOr(t){return"constant"===this.value.kind?this.value.value:t}evaluate(t,e,i,r){return this.property.evaluate(this.value,this.parameters,t,e,i,r)}}class nn{constructor(t){this._properties=t,this._values=Object.create(t.defaultPossiblyEvaluatedValues)}get(t){return this._values[t]}}class an{constructor(t){this.specification=t}possiblyEvaluate(t,e){if(t.isDataDriven())throw new Error("Value should not be data driven");return t.expression.evaluate(e)}interpolate(t,e,i){const r=Ze[this.specification.type];return r?r(t,e,i):t}}class on{constructor(t,e){this.specification=t,this.overrides=e}possiblyEvaluate(t,e,i,r){return new sn(this,"constant"===t.expression.kind||"camera"===t.expression.kind?{kind:"constant",value:t.expression.evaluate(e,null,{},i,r)}:t.expression,e)}interpolate(t,e,i){if("constant"!==t.value.kind||"constant"!==e.value.kind)return t;if(void 0===t.value.value||void 0===e.value.value)return new sn(this,{kind:"constant",value:void 0},t.parameters);const r=Ze[this.specification.type];if(r){const s=r(t.value.value,e.value.value,i);return new sn(this,{kind:"constant",value:s},t.parameters)}return t}evaluate(t,e,i,r,s,n){return"constant"===t.kind?t.value:t.evaluate(e,i,r,s,n)}}class ln extends on{possiblyEvaluate(t,e,i,r){if(void 0===t.value)return new sn(this,{kind:"constant",value:void 0},e);if("constant"===t.expression.kind){const s=t.expression.evaluate(e,null,{},i,r),n="resolvedImage"===t.property.specification.type&&"string"!=typeof s?s.name:s,a=this._calculate(n,n,n,e);return new sn(this,{kind:"constant",value:a},e)}if("camera"===t.expression.kind){const i=this._calculate(t.expression.evaluate({zoom:e.zoom-1}),t.expression.evaluate({zoom:e.zoom}),t.expression.evaluate({zoom:e.zoom+1}),e);return new sn(this,{kind:"constant",value:i},e)}return new sn(this,t.expression,e)}evaluate(t,e,i,r,s,n){if("source"===t.kind){const a=t.evaluate(e,i,r,s,n);return this._calculate(a,a,a,e)}return"composite"===t.kind?this._calculate(t.evaluate({zoom:Math.floor(e.zoom)-1},i,r),t.evaluate({zoom:Math.floor(e.zoom)},i,r),t.evaluate({zoom:Math.floor(e.zoom)+1},i,r),e):t.value}_calculate(t,e,i,r){return r.zoom>r.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:i,to:e}}interpolate(t){return t}}class cn{constructor(t){this.specification=t}possiblyEvaluate(t,e,i,r){if(void 0!==t.value){if("constant"===t.expression.kind){const s=t.expression.evaluate(e,null,{},i,r);return this._calculate(s,s,s,e)}return this._calculate(t.expression.evaluate(new Ks(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Ks(Math.floor(e.zoom),e)),t.expression.evaluate(new Ks(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,i,r){return r.zoom>r.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:i,to:e}}interpolate(t){return t}}class hn{constructor(t){this.specification=t}possiblyEvaluate(t,e,i,r){return!!t.expression.evaluate(e,null,{},i,r)}interpolate(){return!1}}class un{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const i=t[e];i.specification.overridable&&this.overridableProperties.push(e);const r=this.defaultPropertyValues[e]=new Ys(i,void 0),s=this.defaultTransitionablePropertyValues[e]=new Js(i);this.defaultTransitioningPropertyValues[e]=s.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=r.possiblyEvaluate({})}}}Ds("DataDrivenProperty",on),Ds("DataConstantProperty",an),Ds("CrossFadedDataDrivenProperty",ln),Ds("CrossFadedProperty",cn),Ds("ColorRampProperty",hn);const dn="-transition";class pn extends nt{constructor(t,e){if(super(),this.id=t.id,this.type=t.type,this._featureFilter={filter:()=>!0,needGeometry:!1},"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter),e.layout&&(this._unevaluatedLayout=new rn(e.layout)),e.paint)){this._transitionablePaint=new Qs(e.paint);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:!1});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new nn(e.paint)}}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){return"visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)}setLayoutProperty(t,e,i={}){null!=e&&this._validate(zs,`layers.${this.id}.layout.${t}`,t,e,i)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e)}getPaintProperty(t){return t.endsWith(dn)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,i={}){if(null!=e&&this._validate(Cs,`layers.${this.id}.paint.${t}`,t,e,i))return!1;if(t.endsWith(dn))return this._transitionablePaint.setTransition(t.slice(0,-11),e||void 0),!1;{const i=this._transitionablePaint._values[t],r="cross-faded-data-driven"===i.property.specification["property-type"],s=i.value.isDataDriven(),n=i.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const a=this._transitionablePaint._values[t].value;return a.isDataDriven()||s||r||this._handleOverridablePaintPropertyUpdate(t,n,a)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,i){return!1}isHidden(t){return!!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e)}serialize(){const t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),T(t,((t,e)=>!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,i,r,s={}){return(!s||!1!==s.validate)&&Ps(this,t.call(Is,{key:e,layerType:this.type,objectKey:i,value:r,styleSpec:at,style:{glyphs:!0,sprite:!0}}))}is3D(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof sn&&vr(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return!0}return!1}}const fn={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class mn{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}class _n{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0)}static serialize(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(t){this.reserve(t),this.length=t}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e)}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function gn(t,e=1){let i=0,r=0;return{members:t.map((t=>{const s=fn[t.type].BYTES_PER_ELEMENT,n=i=yn(i,Math.max(e,s)),a=t.components||1;return r=Math.max(r,s),i+=s*a,{name:t.name,type:t.type,components:a,offset:n}})),size:yn(i,Math.max(r,e)),alignment:e}}function yn(t,e){return Math.ceil(t/e)*e}class xn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e){const i=this.length;return this.resize(i+1),this.emplace(i,t,e)}emplace(t,e,i){const r=2*t;return this.int16[r+0]=e,this.int16[r+1]=i,t}}xn.prototype.bytesPerElement=4,Ds("StructArrayLayout2i4",xn);class vn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,i){const r=this.length;return this.resize(r+1),this.emplace(r,t,e,i)}emplace(t,e,i,r){const s=3*t;return this.int16[s+0]=e,this.int16[s+1]=i,this.int16[s+2]=r,t}}vn.prototype.bytesPerElement=6,Ds("StructArrayLayout3i6",vn);class bn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,i,r){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,i,r)}emplace(t,e,i,r,s){const n=4*t;return this.int16[n+0]=e,this.int16[n+1]=i,this.int16[n+2]=r,this.int16[n+3]=s,t}}bn.prototype.bytesPerElement=8,Ds("StructArrayLayout4i8",bn);class wn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,i,r,s,n){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,i,r,s,n)}emplace(t,e,i,r,s,n,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=i,this.int16[o+2]=r,this.int16[o+3]=s,this.int16[o+4]=n,this.int16[o+5]=a,t}}wn.prototype.bytesPerElement=12,Ds("StructArrayLayout2i4i12",wn);class Tn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,i,r,s,n){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,i,r,s,n)}emplace(t,e,i,r,s,n,a){const o=4*t,l=8*t;return this.int16[o+0]=e,this.int16[o+1]=i,this.uint8[l+4]=r,this.uint8[l+5]=s,this.uint8[l+6]=n,this.uint8[l+7]=a,t}}Tn.prototype.bytesPerElement=8,Ds("StructArrayLayout2i4ub8",Tn);class Sn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t,e){const i=this.length;return this.resize(i+1),this.emplace(i,t,e)}emplace(t,e,i){const r=2*t;return this.float32[r+0]=e,this.float32[r+1]=i,t}}Sn.prototype.bytesPerElement=8,Ds("StructArrayLayout2f8",Sn);class In extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t,e,i,r,s,n,a,o,l,c){const h=this.length;return this.resize(h+1),this.emplace(h,t,e,i,r,s,n,a,o,l,c)}emplace(t,e,i,r,s,n,a,o,l,c,h){const u=10*t;return this.uint16[u+0]=e,this.uint16[u+1]=i,this.uint16[u+2]=r,this.uint16[u+3]=s,this.uint16[u+4]=n,this.uint16[u+5]=a,this.uint16[u+6]=o,this.uint16[u+7]=l,this.uint16[u+8]=c,this.uint16[u+9]=h,t}}In.prototype.bytesPerElement=20,Ds("StructArrayLayout10ui20",In);class An extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t,e,i,r,s,n,a,o,l,c,h,u){const d=this.length;return this.resize(d+1),this.emplace(d,t,e,i,r,s,n,a,o,l,c,h,u)}emplace(t,e,i,r,s,n,a,o,l,c,h,u,d){const p=12*t;return this.int16[p+0]=e,this.int16[p+1]=i,this.int16[p+2]=r,this.int16[p+3]=s,this.uint16[p+4]=n,this.uint16[p+5]=a,this.uint16[p+6]=o,this.uint16[p+7]=l,this.int16[p+8]=c,this.int16[p+9]=h,this.int16[p+10]=u,this.int16[p+11]=d,t}}An.prototype.bytesPerElement=24,Ds("StructArrayLayout4i4ui4i24",An);class En extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t,e,i){const r=this.length;return this.resize(r+1),this.emplace(r,t,e,i)}emplace(t,e,i,r){const s=3*t;return this.float32[s+0]=e,this.float32[s+1]=i,this.float32[s+2]=r,t}}En.prototype.bytesPerElement=12,Ds("StructArrayLayout3f12",En);class Cn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}Cn.prototype.bytesPerElement=4,Ds("StructArrayLayout1ul4",Cn);class zn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t,e,i,r,s,n,a,o,l){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,i,r,s,n,a,o,l)}emplace(t,e,i,r,s,n,a,o,l,c){const h=10*t,u=5*t;return this.int16[h+0]=e,this.int16[h+1]=i,this.int16[h+2]=r,this.int16[h+3]=s,this.int16[h+4]=n,this.int16[h+5]=a,this.uint32[u+3]=o,this.uint16[h+8]=l,this.uint16[h+9]=c,t}}zn.prototype.bytesPerElement=20,Ds("StructArrayLayout6i1ul2ui20",zn);class Pn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,i,r,s,n){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,i,r,s,n)}emplace(t,e,i,r,s,n,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=i,this.int16[o+2]=r,this.int16[o+3]=s,this.int16[o+4]=n,this.int16[o+5]=a,t}}Pn.prototype.bytesPerElement=12,Ds("StructArrayLayout2i2i2i12",Pn);class Mn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,i,r,s){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,i,r,s)}emplace(t,e,i,r,s,n){const a=4*t,o=8*t;return this.float32[a+0]=e,this.float32[a+1]=i,this.float32[a+2]=r,this.int16[o+6]=s,this.int16[o+7]=n,t}}Mn.prototype.bytesPerElement=16,Ds("StructArrayLayout2f1f2i16",Mn);class kn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(t,e,i,r,s,n){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,i,r,s,n)}emplace(t,e,i,r,s,n,a){const o=16*t,l=4*t,c=8*t;return this.uint8[o+0]=e,this.uint8[o+1]=i,this.float32[l+1]=r,this.float32[l+2]=s,this.int16[c+6]=n,this.int16[c+7]=a,t}}kn.prototype.bytesPerElement=16,Ds("StructArrayLayout2ub2f2i16",kn);class Dn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t,e,i){const r=this.length;return this.resize(r+1),this.emplace(r,t,e,i)}emplace(t,e,i,r){const s=3*t;return this.uint16[s+0]=e,this.uint16[s+1]=i,this.uint16[s+2]=r,t}}Dn.prototype.bytesPerElement=6,Ds("StructArrayLayout3ui6",Dn);class Ln extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t,e,i,r,s,n,a,o,l,c,h,u,d,p,f,m,_){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,i,r,s,n,a,o,l,c,h,u,d,p,f,m,_)}emplace(t,e,i,r,s,n,a,o,l,c,h,u,d,p,f,m,_,g){const y=24*t,x=12*t,v=48*t;return this.int16[y+0]=e,this.int16[y+1]=i,this.uint16[y+2]=r,this.uint16[y+3]=s,this.uint32[x+2]=n,this.uint32[x+3]=a,this.uint32[x+4]=o,this.uint16[y+10]=l,this.uint16[y+11]=c,this.uint16[y+12]=h,this.float32[x+7]=u,this.float32[x+8]=d,this.uint8[v+36]=p,this.uint8[v+37]=f,this.uint8[v+38]=m,this.uint32[x+10]=_,this.int16[y+22]=g,t}}Ln.prototype.bytesPerElement=48,Ds("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",Ln);class Rn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t,e,i,r,s,n,a,o,l,c,h,u,d,p,f,m,_,g,y,x,v,b,w,T,S,I,A,E){const C=this.length;return this.resize(C+1),this.emplace(C,t,e,i,r,s,n,a,o,l,c,h,u,d,p,f,m,_,g,y,x,v,b,w,T,S,I,A,E)}emplace(t,e,i,r,s,n,a,o,l,c,h,u,d,p,f,m,_,g,y,x,v,b,w,T,S,I,A,E,C){const z=32*t,P=16*t;return this.int16[z+0]=e,this.int16[z+1]=i,this.int16[z+2]=r,this.int16[z+3]=s,this.int16[z+4]=n,this.int16[z+5]=a,this.int16[z+6]=o,this.int16[z+7]=l,this.uint16[z+8]=c,this.uint16[z+9]=h,this.uint16[z+10]=u,this.uint16[z+11]=d,this.uint16[z+12]=p,this.uint16[z+13]=f,this.uint16[z+14]=m,this.uint16[z+15]=_,this.uint16[z+16]=g,this.uint16[z+17]=y,this.uint16[z+18]=x,this.uint16[z+19]=v,this.uint16[z+20]=b,this.uint16[z+21]=w,this.uint16[z+22]=T,this.uint32[P+12]=S,this.float32[P+13]=I,this.float32[P+14]=A,this.uint16[z+30]=E,this.uint16[z+31]=C,t}}Rn.prototype.bytesPerElement=64,Ds("StructArrayLayout8i15ui1ul2f2ui64",Rn);class Bn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}Bn.prototype.bytesPerElement=4,Ds("StructArrayLayout1f4",Bn);class Fn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t,e,i){const r=this.length;return this.resize(r+1),this.emplace(r,t,e,i)}emplace(t,e,i,r){const s=3*t;return this.uint16[6*t+0]=e,this.float32[s+1]=i,this.float32[s+2]=r,t}}Fn.prototype.bytesPerElement=12,Ds("StructArrayLayout1ui2f12",Fn);class On extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t,e,i){const r=this.length;return this.resize(r+1),this.emplace(r,t,e,i)}emplace(t,e,i,r){const s=4*t;return this.uint32[2*t+0]=e,this.uint16[s+2]=i,this.uint16[s+3]=r,t}}On.prototype.bytesPerElement=8,Ds("StructArrayLayout1ul2ui8",On);class Vn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t,e){const i=this.length;return this.resize(i+1),this.emplace(i,t,e)}emplace(t,e,i){const r=2*t;return this.uint16[r+0]=e,this.uint16[r+1]=i,t}}Vn.prototype.bytesPerElement=4,Ds("StructArrayLayout2ui4",Vn);class Un extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}Un.prototype.bytesPerElement=2,Ds("StructArrayLayout1ui2",Un);class Nn extends _n{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(t,e,i,r){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,i,r)}emplace(t,e,i,r,s){const n=4*t;return this.float32[n+0]=e,this.float32[n+1]=i,this.float32[n+2]=r,this.float32[n+3]=s,t}}Nn.prototype.bytesPerElement=16,Ds("StructArrayLayout4f16",Nn);class jn extends mn{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new a(this.anchorPointX,this.anchorPointY)}}jn.prototype.size=20;class $n extends zn{get(t){return new jn(this,t)}}Ds("CollisionBoxArray",$n);class qn extends mn{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}qn.prototype.size=48;class Zn extends Ln{get(t){return new qn(this,t)}}Ds("PlacedSymbolArray",Zn);class Gn extends mn{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}Gn.prototype.size=64;class Wn extends Rn{get(t){return new Gn(this,t)}}Ds("SymbolInstanceArray",Wn);class Hn extends Bn{getoffsetX(t){return this.float32[1*t+0]}}Ds("GlyphOffsetArray",Hn);class Xn extends vn{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}Ds("SymbolLineVertexArray",Xn);class Kn extends mn{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}Kn.prototype.size=12;class Yn extends Fn{get(t){return new Kn(this,t)}}Ds("TextAnchorOffsetArray",Yn);class Jn extends mn{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}Jn.prototype.size=8;class Qn extends On{get(t){return new Jn(this,t)}}Ds("FeatureIndexArray",Qn);class ta extends xn{}class ea extends vn{}class ia extends bn{}class ra extends xn{}class sa extends xn{}class na extends wn{}class aa extends Tn{}class oa extends Sn{}class la extends In{}class ca extends An{}class ha extends En{}class ua extends Cn{}class da extends Pn{}class pa extends Mn{}class fa extends kn{}class ma extends Dn{}class _a extends Dn{}class ga extends Vn{}class ya extends Un{}const xa=gn([{name:"a_pos",components:2,type:"Int16"}],4),{members:va}=xa;class ba{constructor(t=[]){this.segments=t}prepareSegment(t,e,i,r){let s=this.segments[this.segments.length-1];return t>ba.MAX_VERTEX_ARRAY_LENGTH&&E(`Max vertices per segment is ${ba.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}`),(!s||s.vertexLength+t>ba.MAX_VERTEX_ARRAY_LENGTH||s.sortKey!==r)&&(s={vertexOffset:e.length,primitiveOffset:i.length,vertexLength:0,primitiveLength:0},void 0!==r&&(s.sortKey=r),this.segments.push(s)),s}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy()}static simpleSegment(t,e,i,r){return new ba([{vertexOffset:t,primitiveOffset:e,vertexLength:i,primitiveLength:r,vaos:{},sortKey:0}])}}function wa(t,e){return 256*(t=_(Math.floor(t),0,255))+_(Math.floor(e),0,255)}ba.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Ds("SegmentVector",ba);const Ta=gn([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var Sa={exports:{}},Ia={exports:{}};!function(t){t.exports=function(t,e){var i,r,s,n,a,o,l,c;for(r=t.length-(i=3&t.length),s=e,a=3432918353,o=461845907,c=0;c>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<13|s>>>19))+((5*(s>>>16)&65535)<<16)&4294967295))+((58964+(n>>>16)&65535)<<16);switch(l=0,i){case 3:l^=(255&t.charCodeAt(c+2))<<16;case 2:l^=(255&t.charCodeAt(c+1))<<8;case 1:s^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(c)))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295}return s^=t.length,s=2246822507*(65535&(s^=s>>>16))+((2246822507*(s>>>16)&65535)<<16)&4294967295,s=3266489909*(65535&(s^=s>>>13))+((3266489909*(s>>>16)&65535)<<16)&4294967295,(s^=s>>>16)>>>0}}(Ia);var Aa=Ia.exports,Ea={exports:{}};!function(t){t.exports=function(t,e){for(var i,r=t.length,s=e^r,n=0;r>=4;)i=1540483477*(65535&(i=255&t.charCodeAt(n)|(255&t.charCodeAt(++n))<<8|(255&t.charCodeAt(++n))<<16|(255&t.charCodeAt(++n))<<24))+((1540483477*(i>>>16)&65535)<<16),s=1540483477*(65535&s)+((1540483477*(s>>>16)&65535)<<16)^(i=1540483477*(65535&(i^=i>>>24))+((1540483477*(i>>>16)&65535)<<16)),r-=4,++n;switch(r){case 3:s^=(255&t.charCodeAt(n+2))<<16;case 2:s^=(255&t.charCodeAt(n+1))<<8;case 1:s=1540483477*(65535&(s^=255&t.charCodeAt(n)))+((1540483477*(s>>>16)&65535)<<16)}return s=1540483477*(65535&(s^=s>>>13))+((1540483477*(s>>>16)&65535)<<16),(s^=s>>>15)>>>0}}(Ea);var Ca=Aa,za=Ea.exports;Sa.exports=Ca,Sa.exports.murmur3=Ca,Sa.exports.murmur2=za;var Pa=r(Sa.exports);class Ma{constructor(){this.ids=[],this.positions=[],this.indexed=!1}add(t,e,i,r){this.ids.push(ka(t)),this.positions.push(e,i,r)}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=ka(t);let i=0,r=this.ids.length-1;for(;i>1;this.ids[t]>=e?r=t:i=t+1}const s=[];for(;this.ids[i]===e;)s.push({index:this.positions[3*i],start:this.positions[3*i+1],end:this.positions[3*i+2]}),i++;return s}static serialize(t,e){const i=new Float64Array(t.ids),r=new Uint32Array(t.positions);return Da(i,r,0,i.length-1),e&&e.push(i.buffer,r.buffer),{ids:i,positions:r}}static deserialize(t){const e=new Ma;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e}}function ka(t){const e=+t;return!isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:Pa(String(t))}function Da(t,e,i,r){for(;i>1];let n=i-1,a=r+1;for(;;){do{n++}while(t[n]s);if(n>=a)break;La(t,n,a),La(e,3*n,3*a),La(e,3*n+1,3*a+1),La(e,3*n+2,3*a+2)}a-i`u_${t}`)),this.type=i}setUniform(t,e,i){t.set(i.constantOr(this.value))}getBinding(t,e,i){return"color"===this.type?new Na(t,e):new Fa(t,e)}}class Ga{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr}setUniform(t,e,i,r){const s="u_pattern_to"===r?this.patternTo:"u_pattern_from"===r?this.patternFrom:"u_pixel_ratio_to"===r?this.pixelRatioTo:"u_pixel_ratio_from"===r?this.pixelRatioFrom:null;s&&t.set(s)}getBinding(t,e,i){return"u_pattern"===i.substr(0,9)?new Ua(t,e):new Fa(t,e)}}class Wa{constructor(t,e,i,r){this.expression=t,this.type=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===i?2:1,offset:0}))),this.paintVertexArray=new r}populatePaintArray(t,e,i,r,s){const n=this.paintVertexArray.length,a=this.expression.evaluate(new Ks(0),e,{},r,[],s);this.paintVertexArray.resize(t),this._setPaintValue(n,t,a)}updatePaintArray(t,e,i,r){const s=this.expression.evaluate({zoom:0},i,r);this._setPaintValue(t,e,s)}_setPaintValue(t,e,i){if("color"===this.type){const r=qa(i);for(let i=t;i`u_${t}_t`)),this.type=i,this.useIntegerZoom=r,this.zoom=s,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===i?4:2,offset:0}))),this.paintVertexArray=new n}populatePaintArray(t,e,i,r,s){const n=this.expression.evaluate(new Ks(this.zoom),e,{},r,[],s),a=this.expression.evaluate(new Ks(this.zoom+1),e,{},r,[],s),o=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(o,t,n,a)}updatePaintArray(t,e,i,r){const s=this.expression.evaluate({zoom:this.zoom},i,r),n=this.expression.evaluate({zoom:this.zoom+1},i,r);this._setPaintValue(t,e,s,n)}_setPaintValue(t,e,i,r){if("color"===this.type){const s=qa(i),n=qa(r);for(let i=t;i`#define HAS_UNIFORM_${t}`)))}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const i=this.binders[e];if(i instanceof Wa||i instanceof Ha)for(let e=0;e!0)){this.programConfigurations={};for(const r of t)this.programConfigurations[r.id]=new Ka(r,e,i);this.needsUpload=!1,this._featureMap=new Ma,this._bufferOffset=0}populatePaintArrays(t,e,i,r,s,n){for(const i in this.programConfigurations)this.programConfigurations[i].populatePaintArrays(t,e,r,s,n);void 0!==e.id&&this._featureMap.add(e.id,i,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0}updatePaintArrays(t,e,i,r){for(const s of i)this.needsUpload=this.programConfigurations[s.id].updatePaintArrays(t,this._featureMap,e,s,r)||this.needsUpload}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy()}}function Ja(t,e){return{"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function Qa(t,e,i){const r={color:{source:Sn,composite:Nn},number:{source:Bn,composite:Sn}},s=function(t){return{"line-pattern":{source:la,composite:la},"fill-pattern":{source:la,composite:la},"fill-extrusion-pattern":{source:la,composite:la}}[t]}(t);return s&&s[i]||r[e][i]}Ds("ConstantBinder",Za),Ds("CrossFadedConstantBinder",Ga),Ds("SourceExpressionBinder",Wa),Ds("CrossFadedCompositeBinder",Xa),Ds("CompositeExpressionBinder",Ha),Ds("ProgramConfiguration",Ka,{omit:["_buffers"]}),Ds("ProgramConfigurationSet",Ya);const to=8192,eo=Math.pow(2,14)-1,io=-eo-1;function ro(t){const e=to/t.extent,i=t.loadGeometry();for(let t=0;ti.x+1||ni.y+1)&&E("Geometry exceeds allowed extent, reduce your vector tile buffer size")}}return i}function so(t,e){return{type:t.type,id:t.id,properties:t.properties,geometry:e?ro(t):[]}}function no(t,e,i,r,s){t.emplaceBack(2*e+(r+1)/2,2*i+(s+1)/2)}class ao{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new ra,this.indexArray=new _a,this.segments=new ba,this.programConfigurations=new Ya(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id))}populate(t,e,i){const r=this.layers[0],s=[];let n=null,a=!1;"circle"===r.type&&(n=r.layout.get("circle-sort-key"),a=!n.isConstant());for(const{feature:e,id:r,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,c=so(e,t);if(!this.layers[0]._featureFilter.filter(new Ks(this.zoom),c,i))continue;const h=a?n.evaluate(c,{},i):void 0,u={id:r,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?c.geometry:ro(e),patterns:{},sortKey:h};s.push(u)}a&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const r of s){const{geometry:s,index:n,sourceLayerIndex:a}=r,o=t[n].feature;this.addFeature(r,s,n,i),e.featureIndex.insert(o,s,n,a,this.index)}}update(t,e,i){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,i)}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,va),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(t,e,i,r){for(const i of e)for(const e of i){const i=e.x,r=e.y;if(i<0||i>=to||r<0||r>=to)continue;const s=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,t.sortKey),n=s.vertexLength;no(this.layoutVertexArray,i,r,-1,-1),no(this.layoutVertexArray,i,r,1,-1),no(this.layoutVertexArray,i,r,1,1),no(this.layoutVertexArray,i,r,-1,1),this.indexArray.emplaceBack(n,n+1,n+2),this.indexArray.emplaceBack(n,n+3,n+2),s.vertexLength+=4,s.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,i,{},r)}}function oo(t,e){for(let i=0;i1){if(uo(t,e))return!0;for(let r=0;r1?i:i.sub(e)._mult(s)._add(e))}function _o(t,e){let i,r,s,n=!1;for(let a=0;ae.y!=s.y>e.y&&e.x<(s.x-r.x)*(e.y-r.y)/(s.y-r.y)+r.x&&(n=!n)}return n}function go(t,e){let i=!1;for(let r=0,s=t.length-1;re.y!=a.y>e.y&&e.x<(a.x-n.x)*(e.y-n.y)/(a.y-n.y)+n.x&&(i=!i)}return i}function yo(t,e,i){const r=i[0],s=i[2];if(t.xs.x&&e.x>s.x||t.ys.y&&e.y>s.y)return!1;const n=C(t,e,i[0]);return n!==C(t,e,i[1])||n!==C(t,e,i[2])||n!==C(t,e,i[3])}function xo(t,e,i){const r=e.paint.get(t).value;return"constant"===r.kind?r.value:i.programConfigurations.get(e.id).getMaxValue(t)}function vo(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function bo(t,e,i,r,s){if(!e[0]&&!e[1])return t;const n=a.convert(e)._mult(s);"viewport"===i&&n._rotate(-r);const o=[];for(let e=0;eZo(t,e)))}(l,o),d=h?c*a:c;for(const t of r)for(const e of t){const t=h?e:Zo(e,o);let i=d;const r=jo([],[e.x,e.y,0,1],o);if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?i*=r[3]/n.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(i*=n.cameraToCenterDistance/r[3]),lo(u,t,i))return!0}return!1}}function Zo(t,e){const i=jo([],[t.x,t.y,0,1],e);return new a(i[0]/i[3],i[1]/i[3])}class Go extends ao{}let Wo;Ds("HeatmapBucket",Go,{omit:["layers"]});var Ho={get paint(){return Wo=Wo||new un({"heatmap-radius":new on(at.paint_heatmap["heatmap-radius"]),"heatmap-weight":new on(at.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new an(at.paint_heatmap["heatmap-intensity"]),"heatmap-color":new hn(at.paint_heatmap["heatmap-color"]),"heatmap-opacity":new an(at.paint_heatmap["heatmap-opacity"])})}};function Xo(t,{width:e,height:i},r,s){if(s){if(s instanceof Uint8ClampedArray)s=new Uint8Array(s.buffer);else if(s.length!==e*i*r)throw new RangeError(`mismatched image size. expected: ${s.length} but got: ${e*i*r}`)}else s=new Uint8Array(e*i*r);return t.width=e,t.height=i,t.data=s,t}function Ko(t,{width:e,height:i},r){if(e===t.width&&i===t.height)return;const s=Xo({},{width:e,height:i},r);Yo(t,s,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,i)},r),t.width=e,t.height=i,t.data=s.data}function Yo(t,e,i,r,s,n){if(0===s.width||0===s.height)return e;if(s.width>t.width||s.height>t.height||i.x>t.width-s.width||i.y>t.height-s.height)throw new RangeError("out of range source coordinates for image copy");if(s.width>e.width||s.height>e.height||r.x>e.width-s.width||r.y>e.height-s.height)throw new RangeError("out of range destination coordinates for image copy");const a=t.data,o=e.data;if(a===o)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=n;const a=t.expression.evaluate(e);s.data[i+r+0]=Math.floor(255*a.r/a.a),s.data[i+r+1]=Math.floor(255*a.g/a.a),s.data[i+r+2]=Math.floor(255*a.b/a.a),s.data[i+r+3]=Math.floor(255*a.a)};if(t.clips)for(let e=0,s=0;e80*i){o=1/0,l=1/0;let e=-1/0,r=-1/0;for(let n=i;ne&&(e=i),s>r&&(r=s)}c=Math.max(e-o,r-l),c=0!==c?32767/c:0}return ul(n,a,i,o,l,c,0),a}function cl(t,e,i,r,s){let n;if(s===function(t,e,i,r){let s=0;for(let n=e,a=i-r;n0)for(let s=e;s=e;s-=r)n=Pl(s/r|0,t[s],t[s+1],n);return n&&Sl(n,n.next)&&(Ml(n),n=n.next),n}function hl(t,e){if(!t)return t;e||(e=t);let i,r=t;do{if(i=!1,r.steiner||!Sl(r,r.next)&&0!==Tl(r.prev,r,r.next))r=r.next;else{if(Ml(r),r=e=r.prev,r===r.next)break;i=!0}}while(i||r!==e);return e}function ul(t,e,i,r,s,n,a){if(!t)return;!a&&n&&function(t,e,i,r){let s=t;do{0===s.z&&(s.z=xl(s.x,s.y,e,i,r)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==t);s.prevZ.nextZ=null,s.prevZ=null,function(t){let e,i=1;do{let r,s=t;t=null;let n=null;for(e=0;s;){e++;let a=s,o=0;for(let t=0;t0||l>0&&a;)0!==o&&(0===l||!a||s.z<=a.z)?(r=s,s=s.nextZ,o--):(r=a,a=a.nextZ,l--),n?n.nextZ=r:t=r,r.prevZ=n,n=r;s=a}n.nextZ=null,i*=2}while(e>1)}(s)}(t,r,s,n);let o=t;for(;t.prev!==t.next;){const l=t.prev,c=t.next;if(n?pl(t,r,s,n):dl(t))e.push(l.i,t.i,c.i),Ml(t),t=c.next,o=c.next;else if((t=c)===o){a?1===a?ul(t=fl(hl(t),e),e,i,r,s,n,2):2===a&&ml(t,e,i,r,s,n):ul(hl(t),e,i,r,s,n,1);break}}}function dl(t){const e=t.prev,i=t,r=t.next;if(Tl(e,i,r)>=0)return!1;const s=e.x,n=i.x,a=r.x,o=e.y,l=i.y,c=r.y,h=sn?s>a?s:a:n>a?n:a,p=o>l?o>c?o:c:l>c?l:c;let f=r.next;for(;f!==e;){if(f.x>=h&&f.x<=d&&f.y>=u&&f.y<=p&&bl(s,o,n,l,a,c,f.x,f.y)&&Tl(f.prev,f,f.next)>=0)return!1;f=f.next}return!0}function pl(t,e,i,r){const s=t.prev,n=t,a=t.next;if(Tl(s,n,a)>=0)return!1;const o=s.x,l=n.x,c=a.x,h=s.y,u=n.y,d=a.y,p=ol?o>c?o:c:l>c?l:c,_=h>u?h>d?h:d:u>d?u:d,g=xl(p,f,e,i,r),y=xl(m,_,e,i,r);let x=t.prevZ,v=t.nextZ;for(;x&&x.z>=g&&v&&v.z<=y;){if(x.x>=p&&x.x<=m&&x.y>=f&&x.y<=_&&x!==s&&x!==a&&bl(o,h,l,u,c,d,x.x,x.y)&&Tl(x.prev,x,x.next)>=0)return!1;if(x=x.prevZ,v.x>=p&&v.x<=m&&v.y>=f&&v.y<=_&&v!==s&&v!==a&&bl(o,h,l,u,c,d,v.x,v.y)&&Tl(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;x&&x.z>=g;){if(x.x>=p&&x.x<=m&&x.y>=f&&x.y<=_&&x!==s&&x!==a&&bl(o,h,l,u,c,d,x.x,x.y)&&Tl(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;v&&v.z<=y;){if(v.x>=p&&v.x<=m&&v.y>=f&&v.y<=_&&v!==s&&v!==a&&bl(o,h,l,u,c,d,v.x,v.y)&&Tl(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function fl(t,e){let i=t;do{const r=i.prev,s=i.next.next;!Sl(r,s)&&Il(r,i,i.next,s)&&Cl(r,s)&&Cl(s,r)&&(e.push(r.i,i.i,s.i),Ml(i),Ml(i.next),i=t=s),i=i.next}while(i!==t);return hl(i)}function ml(t,e,i,r,s,n){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&wl(a,t)){let o=zl(a,t);return a=hl(a,a.next),o=hl(o,o.next),ul(a,e,i,r,s,n,0),void ul(o,e,i,r,s,n,0)}t=t.next}a=a.next}while(a!==t)}function _l(t,e){return t.x-e.x}function gl(t,e){const i=function(t,e){let i=e;const r=t.x,s=t.y;let n,a=-1/0;do{if(s<=i.y&&s>=i.next.y&&i.next.y!==i.y){const t=i.x+(s-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(t<=r&&t>a&&(a=t,n=i.x=i.x&&i.x>=l&&r!==i.x&&bl(sn.x||i.x===n.x&&yl(n,i)))&&(n=i,h=e)}i=i.next}while(i!==o);return n}(t,e);if(!i)return e;const r=zl(i,t);return hl(r,r.next),hl(i,i.next)}function yl(t,e){return Tl(t.prev,t,e.prev)<0&&Tl(e.next,t,t.next)<0}function xl(t,e,i,r,s){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*s|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*s|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function vl(t){let e=t,i=t;do{(e.x=(t-a)*(n-o)&&(t-a)*(r-o)>=(i-a)*(e-o)&&(i-a)*(n-o)>=(s-a)*(r-o)}function wl(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&Il(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(Cl(t,e)&&Cl(e,t)&&function(t,e){let i=t,r=!1;const s=(t.x+e.x)/2,n=(t.y+e.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&s<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(r=!r),i=i.next}while(i!==t);return r}(t,e)&&(Tl(t.prev,t,e.prev)||Tl(t,e.prev,e))||Sl(t,e)&&Tl(t.prev,t,t.next)>0&&Tl(e.prev,e,e.next)>0)}function Tl(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function Sl(t,e){return t.x===e.x&&t.y===e.y}function Il(t,e,i,r){const s=El(Tl(t,e,i)),n=El(Tl(t,e,r)),a=El(Tl(i,r,t)),o=El(Tl(i,r,e));return s!==n&&a!==o||!(0!==s||!Al(t,i,e))||!(0!==n||!Al(t,r,e))||!(0!==a||!Al(i,t,r))||!(0!==o||!Al(i,e,r))}function Al(t,e,i){return e.x<=Math.max(t.x,i.x)&&e.x>=Math.min(t.x,i.x)&&e.y<=Math.max(t.y,i.y)&&e.y>=Math.min(t.y,i.y)}function El(t){return t>0?1:t<0?-1:0}function Cl(t,e){return Tl(t.prev,t,t.next)<0?Tl(t,e,t.next)>=0&&Tl(t,t.prev,e)>=0:Tl(t,e,t.prev)<0||Tl(t,t.next,e)<0}function zl(t,e){const i=kl(t.i,t.x,t.y),r=kl(e.i,e.x,e.y),s=t.next,n=e.prev;return t.next=e,e.prev=t,i.next=s,s.prev=i,r.next=i,i.prev=r,n.next=r,r.prev=n,r}function Pl(t,e,i,r){const s=kl(t,e,i);return r?(s.next=r.next,s.prev=r,r.next.prev=s,r.next=s):(s.prev=s,s.next=s),s}function Ml(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function kl(t,e,i){return{i:t,x:e,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function Dl(t,e,i){const r=i.patternDependencies;let s=!1;for(const i of e){const e=i.paint.get(`${t}-pattern`);e.isConstant()||(s=!0);const n=e.constantOr(null);n&&(s=!0,r[n.to]=!0,r[n.from]=!0)}return s}function Ll(t,e,i,r,s){const n=s.patternDependencies;for(const a of e){const e=a.paint.get(`${t}-pattern`).value;if("constant"!==e.kind){let t=e.evaluate({zoom:r-1},i,{},s.availableImages),o=e.evaluate({zoom:r},i,{},s.availableImages),l=e.evaluate({zoom:r+1},i,{},s.availableImages);t=t&&t.name?t.name:t,o=o&&o.name?o.name:o,l=l&&l.name?l.name:l,n[t]=!0,n[o]=!0,n[l]=!0,i.patterns[a.id]={min:t,mid:o,max:l}}}return i}class Rl{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new sa,this.indexArray=new _a,this.indexArray2=new ga,this.programConfigurations=new Ya(t.layers,t.zoom),this.segments=new ba,this.segments2=new ba,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id))}populate(t,e,i){this.hasPattern=Dl("fill",this.layers,e);const r=this.layers[0].layout.get("fill-sort-key"),s=!r.isConstant(),n=[];for(const{feature:a,id:o,index:l,sourceLayerIndex:c}of t){const t=this.layers[0]._featureFilter.needGeometry,h=so(a,t);if(!this.layers[0]._featureFilter.filter(new Ks(this.zoom),h,i))continue;const u=s?r.evaluate(h,{},i,e.availableImages):void 0,d={id:o,properties:a.properties,type:a.type,sourceLayerIndex:c,index:l,geometry:t?h.geometry:ro(a),patterns:{},sortKey:u};n.push(d)}s&&n.sort(((t,e)=>t.sortKey-e.sortKey));for(const r of n){const{geometry:s,index:n,sourceLayerIndex:a}=r;if(this.hasPattern){const t=Ll("fill",this.layers,r,this.zoom,e);this.patternFeatures.push(t)}else this.addFeature(r,s,n,i,{});e.featureIndex.insert(t[n].feature,s,n,a,this.index)}}update(t,e,i){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,i)}addFeatures(t,e,i){for(const t of this.patternFeatures)this.addFeature(t,t.geometry,t.index,e,i)}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,ol),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy())}addFeature(t,e,i,r,s){for(const t of Di(e,500)){let e=0;for(const i of t)e+=i.length;const i=this.segments.prepareSegment(e,this.layoutVertexArray,this.indexArray),r=i.vertexLength,s=[],n=[];for(const e of t){if(0===e.length)continue;e!==t[0]&&n.push(s.length/2);const i=this.segments2.prepareSegment(e.length,this.layoutVertexArray,this.indexArray2),r=i.vertexLength;this.layoutVertexArray.emplaceBack(e[0].x,e[0].y),this.indexArray2.emplaceBack(r+e.length-1,r),s.push(e[0].x),s.push(e[0].y);for(let t=1;t>3}if(s--,1===r||2===r)n+=t.readSVarint(),a+=t.readSVarint(),1===r&&(e&&o.push(e),e=[]),e.push(new ql(n,a));else{if(7!==r)throw new Error("unknown command "+r);e&&e.push(e[0].clone())}}return e&&o.push(e),o},Gl.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,i=1,r=0,s=0,n=0,a=1/0,o=-1/0,l=1/0,c=-1/0;t.pos>3}if(r--,1===i||2===i)(s+=t.readSVarint())o&&(o=s),(n+=t.readSVarint())c&&(c=n);else if(7!==i)throw new Error("unknown command "+i)}return[a,l,o,c]},Gl.prototype.toGeoJSON=function(t,e,i){var r,s,n=this.extent*Math.pow(2,i),a=this.extent*t,o=this.extent*e,l=this.loadGeometry(),c=Gl.types[this.type];function h(t){for(var e=0;e>3;e=1===r?t.readString():2===r?t.readFloat():3===r?t.readDouble():4===r?t.readVarint64():5===r?t.readVarint():6===r?t.readSVarint():7===r?t.readBoolean():null}return e}(i))}Yl.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new Xl(this._pbf,e,this.extent,this._keys,this._values)};var Ql=Kl;function tc(t,e,i){if(3===t){var r=new Ql(i,i.readVarint()+i.pos);r.length&&(e[r.name]=r)}}$l.VectorTile=function(t,e){this.layers=t.readFields(tc,{},e)},$l.VectorTileFeature=Zl,$l.VectorTileLayer=Kl;const ec=$l.VectorTileFeature.types,ic=Math.pow(2,13);function rc(t,e,i,r,s,n,a,o){t.emplaceBack(e,i,2*Math.floor(r*ic)+a,s*ic*2,n*ic*2,Math.round(o))}class sc{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new na,this.centroidVertexArray=new ta,this.indexArray=new _a,this.programConfigurations=new Ya(t.layers,t.zoom),this.segments=new ba,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id))}populate(t,e,i){this.features=[],this.hasPattern=Dl("fill-extrusion",this.layers,e);for(const{feature:r,id:s,index:n,sourceLayerIndex:a}of t){const t=this.layers[0]._featureFilter.needGeometry,o=so(r,t);if(!this.layers[0]._featureFilter.filter(new Ks(this.zoom),o,i))continue;const l={id:s,sourceLayerIndex:a,index:n,geometry:t?o.geometry:ro(r),properties:r.properties,type:r.type,patterns:{}};this.hasPattern?this.features.push(Ll("fill-extrusion",this.layers,l,this.zoom,e)):this.addFeature(l,l.geometry,n,i,{}),e.featureIndex.insert(r,l.geometry,n,a,this.index,!0)}}addFeatures(t,e,i){for(const t of this.features){const{geometry:r}=t;this.addFeature(t,r,t.index,e,i)}}update(t,e,i){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,i)}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,jl),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,Nl.members,!0),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy())}addFeature(t,e,i,r,s){for(const i of Di(e,500)){const e={x:0,y:0,vertexCount:0};let r=0;for(const t of i)r+=t.length;let s=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray);for(const t of i){if(0===t.length)continue;if(ac(t))continue;let i=0;for(let r=0;r=1){const a=t[r-1];if(!nc(n,a)){s.vertexLength+4>ba.MAX_VERTEX_ARRAY_LENGTH&&(s=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const t=n.sub(a)._perp()._unit(),r=a.dist(n);i+r>32768&&(i=0),rc(this.layoutVertexArray,n.x,n.y,t.x,t.y,0,0,i),rc(this.layoutVertexArray,n.x,n.y,t.x,t.y,0,1,i),e.x+=2*n.x,e.y+=2*n.y,e.vertexCount+=2,i+=r,rc(this.layoutVertexArray,a.x,a.y,t.x,t.y,0,0,i),rc(this.layoutVertexArray,a.x,a.y,t.x,t.y,0,1,i),e.x+=2*a.x,e.y+=2*a.y,e.vertexCount+=2;const o=s.vertexLength;this.indexArray.emplaceBack(o,o+2,o+1),this.indexArray.emplaceBack(o+1,o+2,o+3),s.vertexLength+=4,s.primitiveLength+=2}}}}if(s.vertexLength+r>ba.MAX_VERTEX_ARRAY_LENGTH&&(s=this.segments.prepareSegment(r,this.layoutVertexArray,this.indexArray)),"Polygon"!==ec[t.type])continue;const n=[],a=[],o=s.vertexLength;for(const t of i)if(0!==t.length){t!==i[0]&&a.push(n.length/2);for(let i=0;ito)||t.y===e.y&&(t.y<0||t.y>to)}function ac(t){return t.every((t=>t.x<0))||t.every((t=>t.x>to))||t.every((t=>t.y<0))||t.every((t=>t.y>to))}let oc;Ds("FillExtrusionBucket",sc,{omit:["layers","features"]});var lc={get paint(){return oc=oc||new un({"fill-extrusion-opacity":new an(at["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new on(at["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new an(at["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new an(at["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new ln(at["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new on(at["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new on(at["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new an(at["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class cc extends pn{constructor(t){super(t,lc)}createBucket(t){return new sc(t)}queryRadius(){return vo(this.paint.get("fill-extrusion-translate"))}is3D(){return!0}queryIntersectsFeature(t,e,i,r,s,n,o,l){const c=bo(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),n.angle,o),h=this.paint.get("fill-extrusion-height").evaluate(e,i),u=this.paint.get("fill-extrusion-base").evaluate(e,i),d=function(t,e,i,r){const s=[];for(const i of t){const t=[i.x,i.y,0,1];jo(t,t,e),s.push(new a(t[0]/t[3],t[1]/t[3]))}return s}(c,l),p=function(t,e,i,r){const s=[],n=[],o=r[8]*e,l=r[9]*e,c=r[10]*e,h=r[11]*e,u=r[8]*i,d=r[9]*i,p=r[10]*i,f=r[11]*i;for(const e of t){const t=[],i=[];for(const s of e){const e=s.x,n=s.y,m=r[0]*e+r[4]*n+r[12],_=r[1]*e+r[5]*n+r[13],g=r[2]*e+r[6]*n+r[14],y=r[3]*e+r[7]*n+r[15],x=g+c,v=y+h,b=m+u,w=_+d,T=g+p,S=y+f,I=new a((m+o)/v,(_+l)/v);I.z=x/v,t.push(I);const A=new a(b/S,w/S);A.z=T/S,i.push(A)}s.push(t),n.push(i)}return[s,n]}(r,u,h,l);return function(t,e,i){let r=1/0;co(i,e)&&(r=uc(i,e[0]));for(let s=0;st.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={}})),this.layoutVertexArray=new aa,this.layoutVertexArray2=new oa,this.indexArray=new _a,this.programConfigurations=new Ya(t.layers,t.zoom),this.segments=new ba,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id))}populate(t,e,i){this.hasPattern=Dl("line",this.layers,e);const r=this.layers[0].layout.get("line-sort-key"),s=!r.isConstant(),n=[];for(const{feature:e,id:a,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,c=so(e,t);if(!this.layers[0]._featureFilter.filter(new Ks(this.zoom),c,i))continue;const h=s?r.evaluate(c,{},i):void 0,u={id:a,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?c.geometry:ro(e),patterns:{},sortKey:h};n.push(u)}s&&n.sort(((t,e)=>t.sortKey-e.sortKey));for(const r of n){const{geometry:s,index:n,sourceLayerIndex:a}=r;if(this.hasPattern){const t=Ll("line",this.layers,r,this.zoom,e);this.patternFeatures.push(t)}else this.addFeature(r,s,n,i,{});e.featureIndex.insert(t[n].feature,s,n,a,this.index)}}update(t,e,i){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,i)}addFeatures(t,e,i){for(const t of this.patternFeatures)this.addFeature(t,t.geometry,t.index,e,i)}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,mc)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,pc),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_end"))return{start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,i,r,s){const n=this.layers[0].layout,a=n.get("line-join").evaluate(t,{}),o=n.get("line-cap"),l=n.get("line-miter-limit"),c=n.get("line-round-limit");this.lineClips=this.lineFeatureClips(t);for(const i of e)this.addLine(i,t,a,o,l,c);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,i,s,r)}addLine(t,e,i,r,s,n){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[o-1].equals(t[o-2]);)o--;let l=0;for(;l0;if(b&&e>l){const t=u.dist(d);if(t>2*c){const e=u.sub(u.sub(d)._mult(c/t)._round());this.updateDistance(d,e),this.addCurrentVertex(e,f,0,0,h),d=e}}const T=d&&p;let S=T?i:a?"butt":r;if(T&&"round"===S&&(xs&&(S="bevel"),"bevel"===S&&(x>2&&(S="flipbevel"),x100)_=m.mult(-1);else{const t=x*f.add(m).mag()/f.sub(m).mag();_._perp()._mult(t*(w?-1:1))}this.addCurrentVertex(u,_,0,0,h),this.addCurrentVertex(u,_.mult(-1),0,0,h)}else if("bevel"===S||"fakeround"===S){const t=-Math.sqrt(x*x-1),e=w?t:0,i=w?0:t;if(d&&this.addCurrentVertex(u,f,e,i,h),"fakeround"===S){const t=Math.round(180*v/Math.PI/20);for(let e=1;e2*c){const e=u.add(p.sub(u)._mult(c/t)._round());this.updateDistance(u,e),this.addCurrentVertex(e,m,0,0,h),u=e}}}}addCurrentVertex(t,e,i,r,s,n=!1){const a=e.y*r-e.x,o=-e.y-e.x*r;this.addHalfVertex(t,e.x+e.y*i,e.y-e.x*i,n,!1,i,s),this.addHalfVertex(t,a,o,n,!0,-r,s),this.distance>yc/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,i,r,s,n))}addHalfVertex({x:t,y:e},i,r,s,n,a,o){const l=.5*(this.lineClips?this.scaledDistance*(yc-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(s?1:0),(e<<1)+(n?1:0),Math.round(63*i)+128,Math.round(63*r)+128,1+(0===a?0:a<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const c=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,c),o.primitiveLength++),n?this.e2=c:this.e1=c}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance()}}let vc,bc;Ds("LineBucket",xc,{omit:["layers","patternFeatures"]});var wc={get paint(){return bc=bc||new un({"line-opacity":new on(at.paint_line["line-opacity"]),"line-color":new on(at.paint_line["line-color"]),"line-translate":new an(at.paint_line["line-translate"]),"line-translate-anchor":new an(at.paint_line["line-translate-anchor"]),"line-width":new on(at.paint_line["line-width"]),"line-gap-width":new on(at.paint_line["line-gap-width"]),"line-offset":new on(at.paint_line["line-offset"]),"line-blur":new on(at.paint_line["line-blur"]),"line-dasharray":new cn(at.paint_line["line-dasharray"]),"line-pattern":new ln(at.paint_line["line-pattern"]),"line-gradient":new hn(at.paint_line["line-gradient"])})},get layout(){return vc=vc||new un({"line-cap":new an(at.layout_line["line-cap"]),"line-join":new on(at.layout_line["line-join"]),"line-miter-limit":new an(at.layout_line["line-miter-limit"]),"line-round-limit":new an(at.layout_line["line-round-limit"]),"line-sort-key":new on(at.layout_line["line-sort-key"])})}};class Tc extends on{possiblyEvaluate(t,e){return e=new Ks(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,i,r){return e=y({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,i,r)}}let Sc;class Ic extends pn{constructor(t){super(t,wc),this.gradientVersion=0,Sc||(Sc=new Tc(wc.paint.properties["line-width"].specification),Sc.useIntegerZoom=!0)}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return void 0!==t._styleExpression}(t)&&t._styleExpression.expression instanceof Oe,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=Sc.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t)}createBucket(t){return new xc(t)}queryRadius(t){const e=t,i=Ac(xo("line-width",this,e),xo("line-gap-width",this,e)),r=xo("line-offset",this,e);return i/2+Math.abs(r)+vo(this.paint.get("line-translate"))}queryIntersectsFeature(t,e,i,r,s,n,o){const l=bo(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),n.angle,o),c=o/2*Ac(this.paint.get("line-width").evaluate(e,i),this.paint.get("line-gap-width").evaluate(e,i)),h=this.paint.get("line-offset").evaluate(e,i);return h&&(r=function(t,e){const i=[];for(let r=0;r=3)for(let e=0;e0?e+2*t:t}const Ec=gn([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Cc=gn([{name:"a_projected_pos",components:3,type:"Float32"}],4);gn([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const zc=gn([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);gn([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const Pc=gn([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Mc=gn([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function kc(t,e,i){return t.sections.forEach((t=>{t.text=function(t,e,i){const r=e.layout.get("text-transform").evaluate(i,{});return"uppercase"===r?t=t.toLocaleUpperCase():"lowercase"===r&&(t=t.toLocaleLowerCase()),Xs.applyArabicShaping&&(t=Xs.applyArabicShaping(t)),t}(t.text,e,i)})),t}gn([{name:"triangle",components:3,type:"Uint16"}]),gn([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),gn([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),gn([{type:"Float32",name:"offsetX"}]),gn([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),gn([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const Dc={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var Lc=Fc,Rc=function(t,e,i,r,s){var n,a,o=8*s-r-1,l=(1<>1,h=-7,u=i?s-1:0,d=i?-1:1,p=t[e+u];for(u+=d,n=p&(1<<-h)-1,p>>=-h,h+=o;h>0;n=256*n+t[e+u],u+=d,h-=8);for(a=n&(1<<-h)-1,n>>=-h,h+=r;h>0;a=256*a+t[e+u],u+=d,h-=8);if(0===n)n=1-c;else{if(n===l)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,r),n-=c}return(p?-1:1)*a*Math.pow(2,n-r)},Bc=function(t,e,i,r,s,n){var a,o,l,c=8*n-s-1,h=(1<>1,d=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:n-1,f=r?1:-1,m=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=h):(a=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-a))<1&&(a--,l*=2),(e+=a+u>=1?d/l:d*Math.pow(2,1-u))*l>=2&&(a++,l/=2),a+u>=h?(o=0,a=h):a+u>=1?(o=(e*l-1)*Math.pow(2,s),a+=u):(o=e*Math.pow(2,u-1)*Math.pow(2,s),a=0));s>=8;t[i+p]=255&o,p+=f,o/=256,s-=8);for(a=a<0;t[i+p]=255&a,p+=f,a/=256,c-=8);t[i+p-f]|=128*m};function Fc(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length}Fc.Varint=0,Fc.Fixed64=1,Fc.Bytes=2,Fc.Fixed32=5;var Oc=4294967296,Vc=1/Oc,Uc="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");function Nc(t){return t.type===Fc.Bytes?t.readVarint()+t.pos:t.pos+1}function jc(t,e,i){return i?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function $c(t,e,i){var r=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));i.realloc(r);for(var s=i.pos-1;s>=t;s--)i.buf[s+r]=i.buf[s]}function qc(t,e){for(var i=0;i>>8,t[i+2]=e>>>16,t[i+3]=e>>>24}function eh(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}Fc.prototype={destroy:function(){this.buf=null},readFields:function(t,e,i){for(i=i||this.length;this.pos>3,n=this.pos;this.type=7&r,t(s,e,this),this.pos===n&&this.skip(r)}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=Qc(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=eh(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=Qc(this.buf,this.pos)+Qc(this.buf,this.pos+4)*Oc;return this.pos+=8,t},readSFixed64:function(){var t=Qc(this.buf,this.pos)+eh(this.buf,this.pos+4)*Oc;return this.pos+=8,t},readFloat:function(){var t=Rc(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=Rc(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,i,r=this.buf;return e=127&(i=r[this.pos++]),i<128?e:(e|=(127&(i=r[this.pos++]))<<7,i<128?e:(e|=(127&(i=r[this.pos++]))<<14,i<128?e:(e|=(127&(i=r[this.pos++]))<<21,i<128?e:function(t,e,i){var r,s,n=i.buf;if(r=(112&(s=n[i.pos++]))>>4,s<128)return jc(t,r,e);if(r|=(127&(s=n[i.pos++]))<<3,s<128)return jc(t,r,e);if(r|=(127&(s=n[i.pos++]))<<10,s<128)return jc(t,r,e);if(r|=(127&(s=n[i.pos++]))<<17,s<128)return jc(t,r,e);if(r|=(127&(s=n[i.pos++]))<<24,s<128)return jc(t,r,e);if(r|=(1&(s=n[i.pos++]))<<31,s<128)return jc(t,r,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(i=r[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&Uc?function(t,e,i){return Uc.decode(t.subarray(e,i))}(this.buf,e,t):function(t,e,i){for(var r="",s=e;s239?4:l>223?3:l>191?2:1;if(s+h>i)break;1===h?l<128&&(c=l):2===h?128==(192&(n=t[s+1]))&&(c=(31&l)<<6|63&n)<=127&&(c=null):3===h?(a=t[s+2],128==(192&(n=t[s+1]))&&128==(192&a)&&((c=(15&l)<<12|(63&n)<<6|63&a)<=2047||c>=55296&&c<=57343)&&(c=null)):4===h&&(a=t[s+2],o=t[s+3],128==(192&(n=t[s+1]))&&128==(192&a)&&128==(192&o)&&((c=(15&l)<<18|(63&n)<<12|(63&a)<<6|63&o)<=65535||c>=1114112)&&(c=null)),null===c?(c=65533,h=1):c>65535&&(c-=65536,r+=String.fromCharCode(c>>>10&1023|55296),c=56320|1023&c),r+=String.fromCharCode(c),s+=h}return r}(this.buf,e,t)},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){if(this.type!==Fc.Bytes)return t.push(this.readVarint(e));var i=Nc(this);for(t=t||[];this.pos127;);else if(e===Fc.Bytes)this.pos=this.readVarint()+this.pos;else if(e===Fc.Fixed32)this.pos+=4;else{if(e!==Fc.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(t,e){this.writeVarint(t<<3|e)},realloc:function(t){for(var e=this.length||16;e268435455||t<0?function(t,e){var i,r;if(t>=0?(i=t%4294967296|0,r=t/4294967296|0):(r=~(-t/4294967296),4294967295^(i=~(-t%4294967296))?i=i+1|0:(i=0,r=r+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,i){i.buf[i.pos++]=127&t|128,t>>>=7,i.buf[i.pos++]=127&t|128,t>>>=7,i.buf[i.pos++]=127&t|128,t>>>=7,i.buf[i.pos++]=127&t|128,i.buf[i.pos]=127&(t>>>=7)}(i,0,e),function(t,e){var i=(7&t)<<4;e.buf[e.pos++]|=i|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))))}(r,e)}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))))},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t)},writeBoolean:function(t){this.writeVarint(Boolean(t))},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,i){for(var r,s,n=0;n55295&&r<57344){if(!s){r>56319||n+1===e.length?(t[i++]=239,t[i++]=191,t[i++]=189):s=r;continue}if(r<56320){t[i++]=239,t[i++]=191,t[i++]=189,s=r;continue}r=s-55296<<10|r-56320|65536,s=null}else s&&(t[i++]=239,t[i++]=191,t[i++]=189,s=null);r<128?t[i++]=r:(r<2048?t[i++]=r>>6|192:(r<65536?t[i++]=r>>12|224:(t[i++]=r>>18|240,t[i++]=r>>12&63|128),t[i++]=r>>6&63|128),t[i++]=63&r|128)}return i}(this.buf,t,this.pos);var i=this.pos-e;i>=128&&$c(e,i,this),this.pos=e-1,this.writeVarint(i),this.pos+=i},writeFloat:function(t){this.realloc(4),Bc(this.buf,t,this.pos,!0,23,4),this.pos+=4},writeDouble:function(t){this.realloc(8),Bc(this.buf,t,this.pos,!0,52,8),this.pos+=8},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var i=0;i=128&&$c(i,r,this),this.pos=i-1,this.writeVarint(r),this.pos+=r},writeMessage:function(t,e,i){this.writeTag(t,Fc.Bytes),this.writeRawMessage(e,i)},writePackedVarint:function(t,e){e.length&&this.writeMessage(t,qc,e)},writePackedSVarint:function(t,e){e.length&&this.writeMessage(t,Zc,e)},writePackedBoolean:function(t,e){e.length&&this.writeMessage(t,Hc,e)},writePackedFloat:function(t,e){e.length&&this.writeMessage(t,Gc,e)},writePackedDouble:function(t,e){e.length&&this.writeMessage(t,Wc,e)},writePackedFixed32:function(t,e){e.length&&this.writeMessage(t,Xc,e)},writePackedSFixed32:function(t,e){e.length&&this.writeMessage(t,Kc,e)},writePackedFixed64:function(t,e){e.length&&this.writeMessage(t,Yc,e)},writePackedSFixed64:function(t,e){e.length&&this.writeMessage(t,Jc,e)},writeBytesField:function(t,e){this.writeTag(t,Fc.Bytes),this.writeBytes(e)},writeFixed32Field:function(t,e){this.writeTag(t,Fc.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(t,e){this.writeTag(t,Fc.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(t,e){this.writeTag(t,Fc.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(t,e){this.writeTag(t,Fc.Fixed64),this.writeSFixed64(e)},writeVarintField:function(t,e){this.writeTag(t,Fc.Varint),this.writeVarint(e)},writeSVarintField:function(t,e){this.writeTag(t,Fc.Varint),this.writeSVarint(e)},writeStringField:function(t,e){this.writeTag(t,Fc.Bytes),this.writeString(e)},writeFloatField:function(t,e){this.writeTag(t,Fc.Fixed32),this.writeFloat(e)},writeDoubleField:function(t,e){this.writeTag(t,Fc.Fixed64),this.writeDouble(e)},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e))}};var ih=r(Lc);const rh=3;function sh(t,e,i){1===t&&i.readMessage(nh,e)}function nh(t,e,i){if(3===t){const{id:t,bitmap:r,width:s,height:n,left:a,top:o,advance:l}=i.readMessage(ah,{});e.push({id:t,bitmap:new Jo({width:s+2*rh,height:n+2*rh},r),metrics:{width:s,height:n,left:a,top:o,advance:l}})}}function ah(t,e,i){1===t?e.id=i.readVarint():2===t?e.bitmap=i.readBytes():3===t?e.width=i.readVarint():4===t?e.height=i.readVarint():5===t?e.left=i.readSVarint():6===t?e.top=i.readSVarint():7===t&&(e.advance=i.readVarint())}function oh(t){let e=0,i=0;for(const r of t)e+=r.w*r.h,i=Math.max(i,r.w);t.sort(((t,e)=>e.h-t.h));const r=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),i),h:1/0}];let s=0,n=0;for(const e of t)for(let t=r.length-1;t>=0;t--){const i=r[t];if(!(e.w>i.w||e.h>i.h)){if(e.x=i.x,e.y=i.y,n=Math.max(n,e.y+e.h),s=Math.max(s,e.x+e.w),e.w===i.w&&e.h===i.h){const e=r.pop();tt.id)),this.index=t.index,this.pixelRatio=t.pixelRatio,this.sourceLayerIndex=t.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=zo([]),this.placementViewportMatrix=zo([]);const e=this.layers[0]._unevaluatedLayout._values;this.textSizeData=ph(this.zoom,e["text-size"]),this.iconSizeData=ph(this.zoom,e["icon-size"]);const i=this.layers[0].layout,r=i.get("symbol-sort-key"),s=i.get("symbol-z-order");this.canOverlap="never"!==_h(i,"text-overlap","text-allow-overlap")||"never"!==_h(i,"icon-overlap","icon-allow-overlap")||i.get("text-ignore-placement")||i.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==s&&!r.isConstant(),this.sortFeaturesByY=("viewport-y"===s||"auto"===s&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===i.get("symbol-placement")&&(this.writingModes=i.get("text-writing-mode").map((t=>ch[t]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=t.sourceID}createArrays(){this.text=new wh(new Ya(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new wh(new Ya(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new Hn,this.lineVertexArray=new Xn,this.symbolInstances=new Wn,this.textAnchorOffsets=new Yn}calculateGlyphDependencies(t,e,i,r,s){for(let n=0;n0)&&("constant"!==n.value.kind||n.value.value.length>0),c="constant"!==o.value.kind||!!o.value.value||Object.keys(o.parameters).length>0,h=s.get("symbol-sort-key");if(this.features=[],!l&&!c)return;const u=e.iconDependencies,d=e.glyphDependencies,p=e.availableImages,f=new Ks(this.zoom);for(const{feature:e,id:a,index:o,sourceLayerIndex:m}of t){const t=r._featureFilter.needGeometry,_=so(e,t);if(!r._featureFilter.filter(f,_,i))continue;let g,y;if(t||(_.geometry=ro(e)),l){const t=r.getValueAndResolveTokens("text-field",_,i,p),e=ue.factory(t),s=this.hasRTLText=this.hasRTLText||bh(e);(!s||"unavailable"===Xs.getRTLTextPluginStatus()||s&&Xs.isParsed())&&(g=kc(e,r,_))}if(c){const t=r.getValueAndResolveTokens("icon-image",_,i,p);y=t instanceof me?t:me.fromString(t)}if(!g&&!y)continue;const x=this.sortFeaturesByKey?h.evaluate(_,{},i):void 0;if(this.features.push({id:a,text:g,icon:y,index:o,sourceLayerIndex:m,geometry:_.geometry,properties:e.properties,type:gh[e.type],sortKey:x}),y&&(u[y.name]=!0),g){const t=n.evaluate(_,{},i).join(","),e="viewport"!==s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(ch.vertical)>=0;for(const i of g.sections)if(i.image)u[i.image.name]=!0;else{const r=Ns(g.toString()),s=i.fontStack||t,n=d[s]=d[s]||{};this.calculateGlyphDependencies(i.text,n,e,this.allowVerticalPlacement,r)}}}"line"===s.get("symbol-placement")&&(this.features=function(t){const e={},i={},r=[];let s=0;function n(e){r.push(t[e]),s++}function a(t,e,s){const n=i[t];return delete i[t],i[e]=n,r[n].geometry[0].pop(),r[n].geometry[0]=r[n].geometry[0].concat(s[0]),n}function o(t,i,s){const n=e[i];return delete e[i],e[t]=n,r[n].geometry[0].shift(),r[n].geometry[0]=s[0].concat(r[n].geometry[0]),n}function l(t,e,i){const r=i?e[0][e[0].length-1]:e[0][0];return`${t}:${r.x}:${r.y}`}for(let c=0;ct.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey))}update(t,e,i){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,i),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,i))}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(t,e){const i=this.lineVertexArray.length;if(void 0!==t.segment){let i=t.dist(e[t.segment+1]),r=t.dist(e[t.segment]);const s={};for(let r=t.segment+1;r=0;i--)s[i]={x:e[i].x,y:e[i].y,tileUnitDistanceFromAnchor:r},i>0&&(r+=e[i-1].dist(e[i]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const i=t.placedSymbolArray.get(e),r=i.vertexStartIndex+4*i.numGlyphs;for(let e=i.vertexStartIndex;er[t]-r[e]||s[e]-s[t])),n}addToSortKeyRanges(t,e){const i=this.sortKeyRanges[this.sortKeyRanges.length-1];i&&i.sortKey===e?i.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1})}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,i)=>{t>=0&&i.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t)})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}}let Ih,Ah;Ds("SymbolBucket",Sh,{omit:["layers","collisionBoxArray","features","compareText"]}),Sh.MAX_GLYPHS=65535,Sh.addDynamicAttributes=vh;var Eh={get paint(){return Ah=Ah||new un({"icon-opacity":new on(at.paint_symbol["icon-opacity"]),"icon-color":new on(at.paint_symbol["icon-color"]),"icon-halo-color":new on(at.paint_symbol["icon-halo-color"]),"icon-halo-width":new on(at.paint_symbol["icon-halo-width"]),"icon-halo-blur":new on(at.paint_symbol["icon-halo-blur"]),"icon-translate":new an(at.paint_symbol["icon-translate"]),"icon-translate-anchor":new an(at.paint_symbol["icon-translate-anchor"]),"text-opacity":new on(at.paint_symbol["text-opacity"]),"text-color":new on(at.paint_symbol["text-color"],{runtimeType:Et,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new on(at.paint_symbol["text-halo-color"]),"text-halo-width":new on(at.paint_symbol["text-halo-width"]),"text-halo-blur":new on(at.paint_symbol["text-halo-blur"]),"text-translate":new an(at.paint_symbol["text-translate"]),"text-translate-anchor":new an(at.paint_symbol["text-translate-anchor"])})},get layout(){return Ih=Ih||new un({"symbol-placement":new an(at.layout_symbol["symbol-placement"]),"symbol-spacing":new an(at.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new an(at.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new on(at.layout_symbol["symbol-sort-key"]),"symbol-z-order":new an(at.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new an(at.layout_symbol["icon-allow-overlap"]),"icon-overlap":new an(at.layout_symbol["icon-overlap"]),"icon-ignore-placement":new an(at.layout_symbol["icon-ignore-placement"]),"icon-optional":new an(at.layout_symbol["icon-optional"]),"icon-rotation-alignment":new an(at.layout_symbol["icon-rotation-alignment"]),"icon-size":new on(at.layout_symbol["icon-size"]),"icon-text-fit":new an(at.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new an(at.layout_symbol["icon-text-fit-padding"]),"icon-image":new on(at.layout_symbol["icon-image"]),"icon-rotate":new on(at.layout_symbol["icon-rotate"]),"icon-padding":new on(at.layout_symbol["icon-padding"]),"icon-keep-upright":new an(at.layout_symbol["icon-keep-upright"]),"icon-offset":new on(at.layout_symbol["icon-offset"]),"icon-anchor":new on(at.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new an(at.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new an(at.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new an(at.layout_symbol["text-rotation-alignment"]),"text-field":new on(at.layout_symbol["text-field"]),"text-font":new on(at.layout_symbol["text-font"]),"text-size":new on(at.layout_symbol["text-size"]),"text-max-width":new on(at.layout_symbol["text-max-width"]),"text-line-height":new an(at.layout_symbol["text-line-height"]),"text-letter-spacing":new on(at.layout_symbol["text-letter-spacing"]),"text-justify":new on(at.layout_symbol["text-justify"]),"text-radial-offset":new on(at.layout_symbol["text-radial-offset"]),"text-variable-anchor":new an(at.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new on(at.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new on(at.layout_symbol["text-anchor"]),"text-max-angle":new an(at.layout_symbol["text-max-angle"]),"text-writing-mode":new an(at.layout_symbol["text-writing-mode"]),"text-rotate":new on(at.layout_symbol["text-rotate"]),"text-padding":new an(at.layout_symbol["text-padding"]),"text-keep-upright":new an(at.layout_symbol["text-keep-upright"]),"text-transform":new on(at.layout_symbol["text-transform"]),"text-offset":new on(at.layout_symbol["text-offset"]),"text-allow-overlap":new an(at.layout_symbol["text-allow-overlap"]),"text-overlap":new an(at.layout_symbol["text-overlap"]),"text-ignore-placement":new an(at.layout_symbol["text-ignore-placement"]),"text-optional":new an(at.layout_symbol["text-optional"])})}};class Ch{constructor(t){if(void 0===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:Tt,this.defaultValue=t}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Ds("FormatSectionOverride",Ch,{omit:["defaultValue"]});class zh extends pn{constructor(t){super(t,Eh)}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const i of t)e.indexOf(i)<0&&e.push(i);this.layout._values["text-writing-mode"]=e}else this.layout._values["text-writing-mode"]=["horizontal"]}this._setPaintOverrides()}getValueAndResolveTokens(t,e,i,r){const s=this.layout.get(t).evaluate(e,{},i,r),n=this._unevaluatedLayout._values[t];return n.isDataDriven()||Dr(n.value)||!s?s:function(t,e){return e.replace(/{([^{}]+)}/g,((e,i)=>t&&i in t?String(t[i]):""))}(e.properties,s)}createBucket(t){return new Sh(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of Eh.paint.overridableProperties){if(!zh.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),i=new Ch(e),r=new kr(i,e.property.specification);let s=null;s="constant"===e.value.kind||"source"===e.value.kind?new Rr("source",r):new Br("composite",r,e.value.zoomStops),this.paint._values[t]=new sn(e.property,s,e.parameters)}}_handleOverridablePaintPropertyUpdate(t,e,i){return!(!this.layout||e.isDataDriven()||i.isDataDriven())&&zh.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const i=t.get("text-field"),r=Eh.paint.properties[e];let s=!1;const n=t=>{for(const e of t)if(r.overrides&&r.overrides.hasOverride(e))return void(s=!0)};if("constant"===i.value.kind&&i.value.value instanceof ue)n(i.value.value.sections);else if("source"===i.value.kind){const t=e=>{s||(e instanceof ve&&ye(e.value)===Mt?n(e.value.sections):e instanceof ai?n(e.sections):e.eachChild(t))},e=i.value;e._styleExpression&&t(e._styleExpression.expression)}return s}}let Ph;var Mh={get paint(){return Ph=Ph||new un({"background-color":new an(at.paint_background["background-color"]),"background-pattern":new cn(at.paint_background["background-pattern"]),"background-opacity":new an(at.paint_background["background-opacity"])})}};class kh extends pn{constructor(t){super(t,Mh)}}let Dh;var Lh={get paint(){return Dh=Dh||new un({"raster-opacity":new an(at.paint_raster["raster-opacity"]),"raster-hue-rotate":new an(at.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new an(at.paint_raster["raster-brightness-min"]),"raster-brightness-max":new an(at.paint_raster["raster-brightness-max"]),"raster-saturation":new an(at.paint_raster["raster-saturation"]),"raster-contrast":new an(at.paint_raster["raster-contrast"]),"raster-resampling":new an(at.paint_raster["raster-resampling"]),"raster-fade-duration":new an(at.paint_raster["raster-fade-duration"])})}};class Rh extends pn{constructor(t){super(t,Lh)}}class Bh extends pn{constructor(t){super(t,{}),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl)},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl)},this.implementation=t}is3D(){return"3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){throw new Error("Custom layers cannot be serialized")}}function Fh(t){if("custom"===t.type)return new Bh(t);switch(t.type){case"background":return new kh(t);case"circle":return new qo(t);case"fill":return new Vl(t);case"fill-extrusion":return new cc(t);case"heatmap":return new il(t);case"hillshade":return new nl(t);case"line":return new Ic(t);case"raster":return new Rh(t);case"symbol":return new zh(t)}}function Oh(t){const e=[];if("string"==typeof t)e.push({id:"default",url:t});else if(t&&t.length>0){const i=[];for(const{id:r,url:s}of t){const t=`${r}${s}`;-1===i.indexOf(t)&&(i.push(t),e.push({id:r,url:s}))}}return e}function Vh(t,e,i){const r=t.split("?");return r[0]+=`${e}${i}`,r.join("?")}class Uh{constructor(t,e,i,r){this.context=t,this.format=i,this.texture=t.gl.createTexture(),this.update(e,r)}update(t,e,i){const{width:r,height:s}=t,n=!(this.size&&this.size[0]===r&&this.size[1]===s||i),{context:a}=this,{gl:o}=a;if(this.useMipmap=Boolean(e&&e.useMipmap),o.bindTexture(o.TEXTURE_2D,this.texture),a.pixelStoreUnpackFlipY.set(!1),a.pixelStoreUnpack.set(1),a.pixelStoreUnpackPremultiplyAlpha.set(this.format===o.RGBA&&(!e||!1!==e.premultiply)),n)this.size=[r,s],t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement||t instanceof ImageData||M(t)?o.texImage2D(o.TEXTURE_2D,0,this.format,this.format,o.UNSIGNED_BYTE,t):o.texImage2D(o.TEXTURE_2D,0,this.format,r,s,0,this.format,o.UNSIGNED_BYTE,t.data);else{const{x:e,y:n}=i||{x:0,y:0};t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement||t instanceof ImageData||M(t)?o.texSubImage2D(o.TEXTURE_2D,0,e,n,o.RGBA,o.UNSIGNED_BYTE,t):o.texSubImage2D(o.TEXTURE_2D,0,e,n,r,s,o.RGBA,o.UNSIGNED_BYTE,t.data)}this.useMipmap&&this.isSizePowerOfTwo()&&o.generateMipmap(o.TEXTURE_2D)}bind(t,e,i){const{context:r}=this,{gl:s}=r;s.bindTexture(s.TEXTURE_2D,this.texture),i!==s.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(i=s.LINEAR),t!==this.filter&&(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,t),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,i||t),this.filter=t),e!==this.wrap&&(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,e),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,e),this.wrap=e)}isSizePowerOfTwo(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0}destroy(){const{gl:t}=this.context;t.deleteTexture(this.texture),this.texture=null}}function Nh(t){const{userImage:e}=t;return!!(e&&e.render&&e.render())&&(t.data.replace(new Uint8Array(e.data.buffer)),!0)}class jh extends nt{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new Qo({width:1,height:1}),this.dirty=!0}isLoaded(){return this.loaded}setLoaded(t){if(this.loaded!==t&&(this.loaded=t,t)){for(const{ids:t,promiseResolve:e}of this.requestors)e(this._getImagesForIds(t));this.requestors=[]}}getImage(t){const e=this.images[t];if(e&&!e.data&&e.spriteData){const t=e.spriteData;e.data=new Qo({width:t.width,height:t.height},t.context.getImageData(t.x,t.y,t.width,t.height).data),e.spriteData=null}return e}addImage(t,e){if(this.images[t])throw new Error(`Image id ${t} already exist, use updateImage instead`);this._validate(t,e)&&(this.images[t]=e)}_validate(t,e){let i=!0;const r=e.data||e.spriteData;return this._validateStretch(e.stretchX,r&&r.width)||(this.fire(new st(new Error(`Image "${t}" has invalid "stretchX" value`))),i=!1),this._validateStretch(e.stretchY,r&&r.height)||(this.fire(new st(new Error(`Image "${t}" has invalid "stretchY" value`))),i=!1),this._validateContent(e.content,e)||(this.fire(new st(new Error(`Image "${t}" has invalid "content" value`))),i=!1),i}_validateStretch(t,e){if(!t)return!0;let i=0;for(const r of t){if(r[0]{let r=!0;if(!this.isLoaded())for(const e of t)this.images[e]||(r=!1);this.isLoaded()||r?e(this._getImagesForIds(t)):this.requestors.push({ids:t,promiseResolve:e})}))}_getImagesForIds(t){const e={};for(const i of t){let t=this.getImage(i);t||(this.fire(new rt("styleimagemissing",{id:i})),t=this.getImage(i)),t?e[i]={data:t.data.clone(),pixelRatio:t.pixelRatio,sdf:t.sdf,version:t.version,stretchX:t.stretchX,stretchY:t.stretchY,content:t.content,textFitWidth:t.textFitWidth,textFitHeight:t.textFitHeight,hasRenderCallback:Boolean(t.userImage&&t.userImage.render)}:E(`Image "${i}" 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.`)}return e}getPixelSize(){const{width:t,height:e}=this.atlasImage;return{width:t,height:e}}getPattern(t){const e=this.patterns[t],i=this.getImage(t);if(!i)return null;if(e&&e.position.version===i.version)return e.position;if(e)e.position.version=i.version;else{const e={w:i.data.width+2,h:i.data.height+2,x:0,y:0},r=new lh(e,i);this.patterns[t]={bin:e,position:r}}return this._updatePatternAtlas(),this.patterns[t].position}bind(t){const e=t.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new Uh(t,this.atlasImage,e.RGBA),this.atlasTexture.bind(e.LINEAR,e.CLAMP_TO_EDGE)}_updatePatternAtlas(){const t=[];for(const e in this.patterns)t.push(this.patterns[e].bin);const{w:e,h:i}=oh(t),r=this.atlasImage;r.resize({width:e||1,height:i||1});for(const t in this.patterns){const{bin:e}=this.patterns[t],i=e.x+1,s=e.y+1,n=this.getImage(t).data,a=n.width,o=n.height;Qo.copy(n,r,{x:0,y:0},{x:i,y:s},{width:a,height:o}),Qo.copy(n,r,{x:0,y:o-1},{x:i,y:s-1},{width:a,height:1}),Qo.copy(n,r,{x:0,y:0},{x:i,y:s+o},{width:a,height:1}),Qo.copy(n,r,{x:a-1,y:0},{x:i-1,y:s},{width:1,height:o}),Qo.copy(n,r,{x:0,y:0},{x:i+a,y:s},{width:1,height:o})}this.dirty=!0}beginFrame(){this.callbackDispatchedThisFrame={}}dispatchRenderCallbacks(t){for(const e of t){if(this.callbackDispatchedThisFrame[e])continue;this.callbackDispatchedThisFrame[e]=!0;const t=this.getImage(e);t||E(`Image with ID: "${e}" was not found`),Nh(t)&&this.updateImage(e,t)}}}const $h=1e20;function qh(t,e,i,r,s,n,a,o,l){for(let c=e;c-1);l++,n[l]=o,a[l]=c,a[l+1]=$h}for(let o=0,l=0;o65535)throw new Error("glyphs > 65535 not supported");if(i.ranges[s])return{stack:t,id:e,glyph:r};if(!this.url)throw new Error("glyphsUrl is not set");if(!i.requests[s]){const e=Gh.loadGlyphRange(t,s,this.url,this.requestManager);i.requests[s]=e}const n=yield i.requests[s];for(const t in n)this._doesCharSupportLocalGlyph(+t)||(i.glyphs[+t]=n[+t]);return i.ranges[s]=!0,{stack:t,id:e,glyph:n[e]||null}}))}_doesCharSupportLocalGlyph(t){return!!this.localIdeographFontFamily&&/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(t))}_tinySDF(t,e,i){const r=this.localIdeographFontFamily;if(!r)return;if(!this._doesCharSupportLocalGlyph(i))return;let s=t.tinySDF;if(!s){let i="400";/bold/i.test(e)?i="900":/medium/i.test(e)?i="500":/light/i.test(e)&&(i="200"),s=t.tinySDF=new Gh.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,fontFamily:r,fontWeight:i})}const n=s.draw(String.fromCharCode(i));return{id:i,bitmap:new Jo({width:n.width||60,height:n.height||60},n.data),metrics:{width:n.glyphWidth/2||24,height:n.glyphHeight/2||24,left:n.glyphLeft/2+.5||0,top:n.glyphTop/2-27.5||-8,advance:n.glyphAdvance/2||24,isDoubleResolution:!0}}}}Gh.loadGlyphRange=function(t,e,r,s){return i(this,void 0,void 0,(function*(){const i=256*e,n=i+255,a=s.transformRequest(r.replace("{fontstack}",t).replace("{range}",`${i}-${n}`),"Glyphs"),o=yield(l=a,c=new AbortController,q(y(l,{type:"arrayBuffer"}),c));var l,c;if(!o||!o.data)throw new Error(`Could not load glyph range. range: ${e}, ${i}-${n}`);const h={};for(const t of new ih(o.data).readFields(sh,[]))h[t.id]=t;return h}))},Gh.TinySDF=class{constructor({fontSize:t=24,buffer:e=3,radius:i=8,cutoff:r=.25,fontFamily:s="sans-serif",fontWeight:n="normal",fontStyle:a="normal"}={}){this.buffer=e,this.cutoff=r,this.radius=i;const o=this.size=t+4*e,l=this._createCanvas(o),c=this.ctx=l.getContext("2d",{willReadFrequently:!0});c.font=`${a} ${n} ${t}px ${s}`,c.textBaseline="alphabetic",c.textAlign="left",c.fillStyle="black",this.gridOuter=new Float64Array(o*o),this.gridInner=new Float64Array(o*o),this.f=new Float64Array(o),this.z=new Float64Array(o+1),this.v=new Uint16Array(o)}_createCanvas(t){const e=document.createElement("canvas");return e.width=e.height=t,e}draw(t){const{width:e,actualBoundingBoxAscent:i,actualBoundingBoxDescent:r,actualBoundingBoxLeft:s,actualBoundingBoxRight:n}=this.ctx.measureText(t),a=Math.ceil(i),o=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(n-s))),l=Math.min(this.size-this.buffer,a+Math.ceil(r)),c=o+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),p={data:d,width:c,height:h,glyphWidth:o,glyphHeight:l,glyphTop:a,glyphLeft:0,glyphAdvance:e};if(0===o||0===l)return p;const{ctx:f,buffer:m,gridInner:_,gridOuter:g}=this;f.clearRect(m,m,o,l),f.fillText(t,m,m+a);const y=f.getImageData(m,m,o,l);g.fill($h,0,u),_.fill(0,0,u);for(let t=0;t0?t*t:0,_[r]=t<0?t*t:0}}qh(g,0,0,c,h,c,this.f,this.v,this.z),qh(_,m,m,o,l,c,this.f,this.v,this.z);for(let t=0;t1&&(a=t[++n]);const l=Math.abs(o-a.left),c=Math.abs(o-a.right),h=Math.min(l,c);let u;const d=e/i*(r+1);if(a.isDash){const t=r-Math.abs(d);u=Math.sqrt(h*h+t*t)}else u=r-Math.sqrt(h*h+d*d);this.data[s+o]=Math.max(0,Math.min(255,u+128))}}}addRegularDash(t){for(let e=t.length-1;e>=0;--e){const i=t[e],r=t[e+1];i.zeroLength?t.splice(e,1):r&&r.isDash===i.isDash&&(r.left=i.left,t.splice(e,1))}const e=t[0],i=t[t.length-1];e.isDash===i.isDash&&(e.left=i.left-this.width,i.right=e.right+this.width);const r=this.width*this.nextRow;let s=0,n=t[s];for(let e=0;e1&&(n=t[++s]);const i=Math.abs(e-n.left),a=Math.abs(e-n.right),o=Math.min(i,a);this.data[r+e]=Math.max(0,Math.min(255,(n.isDash?o:-o)+128))}}addDash(t,e){const i=e?7:0,r=2*i+1;if(this.nextRow+r>this.height)return E("LineAtlas out of space"),null;let s=0;for(let e=0;e{this._triggered=!1,this._methodToThrottle()})}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._methodToThrottle()}),0))}remove(){delete this._channel,this._methodToThrottle=()=>{}}}class tu{constructor(t,e){this.target=t,this.mapId=e,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new Qh((()=>this.process())),this.subscription=function(t,e,i,r){return t.addEventListener(e,i,!1),{unsubscribe:()=>{t.removeEventListener(e,i,!1)}}}(this.target,"message",(t=>this.receive(t))),this.globalScope=z(self)?t:window}registerMessageHandler(t,e){this.messageHandlers[t]=e}sendAsync(t,e){return new Promise(((i,r)=>{const s=Math.round(1e18*Math.random()).toString(36).substring(0,10);this.resolveRejects[s]={resolve:i,reject:r},e&&e.signal.addEventListener("abort",(()=>{delete this.resolveRejects[s];const e={id:s,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e)}),{once:!0});const n=[],a=Object.assign(Object.assign({},t),{id:s,sourceMapId:this.mapId,origin:location.origin,data:Fs(t.data,n)});this.target.postMessage(a,{transfer:n})}))}receive(t){const e=t.data,i=e.id;if(!("file://"!==e.origin&&"file://"!==location.origin&&"resource://android"!==e.origin&&"resource://android"!==location.origin&&e.origin!==location.origin||e.targetMapId&&this.mapId!==e.targetMapId)){if(""===e.type){delete this.tasks[i];const t=this.abortControllers[i];return delete this.abortControllers[i],void(t&&t.abort())}if(z(self)||e.mustQueue)return this.tasks[i]=e,this.taskQueue.push(i),void this.invoker.trigger();this.processTask(i,e)}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e)}processTask(t,e){return i(this,void 0,void 0,(function*(){if(""===e.type){const i=this.resolveRejects[t];if(delete this.resolveRejects[t],!i)return;return void(e.error?i.reject(Os(e.error)):i.resolve(Os(e.data)))}if(!this.messageHandlers[e.type])return void this.completeTask(t,new Error(`Could not find a registered handler for ${e.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const i=Os(e.data),r=new AbortController;this.abortControllers[t]=r;try{const s=yield this.messageHandlers[e.type](e.sourceMapId,i,r);this.completeTask(t,null,s)}catch(e){this.completeTask(t,e)}}))}completeTask(t,e,i){const r=[];delete this.abortControllers[t];const s={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?Fs(e):null,data:Fs(i,r)};this.target.postMessage(s,{transfer:r})}remove(){this.invoker.remove(),this.subscription.unsubscribe()}}const eu="maplibre_preloaded_worker_pool";class iu{constructor(){this.active={}}acquire(t){if(!this.workers)for(this.workers=[];this.workers.length{t.terminate()})),this.workers=null)}isPreloaded(){return!!this.active[eu]}numActive(){return Object.keys(this.active).length}}const ru=Math.floor(F.hardwareConcurrency/2);let su,nu;function au(){return su||(su=new iu),su}iu.workerCount=function(t){if(null==P){const e=t.navigator?t.navigator.userAgent:null;P=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")))}return P}(globalThis)?Math.max(Math.min(ru,3),1):1;class ou{constructor(t,e){this.workerPool=t,this.actors=[],this.currentActor=0,this.id=e;const i=this.workerPool.acquire(e);for(let t=0;t{t.remove()})),this.actors=[],t&&this.workerPool.release(this.id)}registerMessageHandler(t,e){for(const i of this.actors)i.registerMessageHandler(t,e)}}function lu(){return nu||(nu=new ou(au(),N),nu.registerMessageHandler("GR",((t,e,i)=>q(e,i)))),nu}function cu(t,e){const i=Eo();return ko(i,i,[1,1,0]),Do(i,i,[.5*t.width,.5*t.height,1]),Mo(i,i,t.calculatePosMatrix(e.toUnwrapped()))}function hu(t,e,i,r,s,n){const a=function(t,e,i){if(t)for(const r of t){const t=e[r];if(t&&t.source===i&&"fill-extrusion"===t.type)return!0}else for(const t in e){const r=e[t];if(r.source===i&&"fill-extrusion"===r.type)return!0}return!1}(s&&s.layers,e,t.id),o=n.maxPitchScaleFactor(),l=t.tilesIn(r,o,a);l.sort(uu);const c=[];for(const r of l)c.push({wrappedTileID:r.tileID.wrapped().key,queryResults:r.tile.queryRenderedFeatures(e,i,t._state,r.queryGeometry,r.cameraQueryGeometry,r.scale,s,n,o,cu(t.transform,r.tileID))});const h=function(t){const e={},i={};for(const r of t){const t=r.queryResults,s=r.wrappedTileID,n=i[s]=i[s]||{};for(const i in t){const r=t[i],s=n[i]=n[i]||{},a=e[i]=e[i]||[];for(const t of r)s[t.featureIndex]||(s[t.featureIndex]=!0,a.push(t))}}return e}(c);for(const e in h)h[e].forEach((e=>{const i=e.feature,r=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=r}));return h}function uu(t,e){const i=t.tileID,r=e.tileID;return i.overscaledZ-r.overscaledZ||i.canonical.y-r.canonical.y||i.wrap-r.wrap||i.canonical.x-r.canonical.x}function du(t,e,r){return i(this,void 0,void 0,(function*(){let i=t;if(t.url?i=(yield Z(e.transformRequest(t.url,"Source"),r)).data:yield F.frameAsync(r),!i)return null;const s=x(y(i,t),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return"vector_layers"in i&&i.vector_layers&&(s.vectorLayerIds=i.vector_layers.map((t=>t.id))),s}))}const pu=6371008.8;class fu{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new fu(g(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,i=this.lat*e,r=t.lat*e,s=Math.sin(i)*Math.sin(r)+Math.cos(i)*Math.cos(r)*Math.cos((t.lng-this.lng)*e);return pu*Math.acos(Math.min(s,1))}static convert(t){if(t instanceof fu)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new fu(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new fu(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}class mu{constructor(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):Array.isArray(t)&&(4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1])))}setNorthEast(t){return this._ne=t instanceof fu?new fu(t.lng,t.lat):fu.convert(t),this}setSouthWest(t){return this._sw=t instanceof fu?new fu(t.lng,t.lat):fu.convert(t),this}extend(t){const e=this._sw,i=this._ne;let r,s;if(t instanceof fu)r=t,s=t;else{if(!(t instanceof mu))return Array.isArray(t)?4===t.length||t.every(Array.isArray)?this.extend(mu.convert(t)):this.extend(fu.convert(t)):t&&("lng"in t||"lon"in t)&&"lat"in t?this.extend(fu.convert(t)):this;if(r=t._sw,s=t._ne,!r||!s)return this}return e||i?(e.lng=Math.min(r.lng,e.lng),e.lat=Math.min(r.lat,e.lat),i.lng=Math.max(s.lng,i.lng),i.lat=Math.max(s.lat,i.lat)):(this._sw=new fu(r.lng,r.lat),this._ne=new fu(s.lng,s.lat)),this}getCenter(){return new fu((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new fu(this.getWest(),this.getNorth())}getSouthEast(){return new fu(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(t){const{lng:e,lat:i}=fu.convert(t);let r=this._sw.lng<=e&&e<=this._ne.lng;return this._sw.lng>this._ne.lng&&(r=this._sw.lng>=e&&e>=this._ne.lng),this._sw.lat<=i&&i<=this._ne.lat&&r}static convert(t){return t instanceof mu?t:t?new mu(t):t}static fromLngLat(t,e=0){const i=360*e/40075017,r=i/Math.cos(Math.PI/180*t.lat);return new mu(new fu(t.lng-r,t.lat-i),new fu(t.lng+r,t.lat+i))}adjustAntiMeridian(){const t=new fu(this._sw.lng,this._sw.lat),e=new fu(this._ne.lng,this._ne.lat);return new mu(t,t.lng>e.lng?new fu(e.lng+360,e.lat):e)}}const _u=2*Math.PI*pu;function gu(t){return _u*Math.cos(t*Math.PI/180)}function yu(t){return(180+t)/360}function xu(t){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function vu(t,e){return t/gu(e)}function bu(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}class wu{constructor(t,e,i=0){this.x=+t,this.y=+e,this.z=+i}static fromLngLat(t,e=0){const i=fu.convert(t);return new wu(yu(i.lng),xu(i.lat),vu(e,i.lat))}toLngLat(){return new fu(360*this.x-180,bu(this.y))}toAltitude(){return this.z*gu(bu(this.y))}meterInMercatorCoordinateUnits(){return 1/_u*(t=bu(this.y),1/Math.cos(t*Math.PI/180));var t}}class Tu{constructor(t,e,i){this.bounds=mu.convert(this.validateBounds(t)),this.minzoom=e||0,this.maxzoom=i||24}validateBounds(t){return Array.isArray(t)&&4===t.length?[Math.max(-180,t[0]),Math.max(-90,t[1]),Math.min(180,t[2]),Math.min(90,t[3])]:[-180,-90,180,90]}contains(t){const e=Math.pow(2,t.z),i=Math.floor(yu(this.bounds.getWest())*e),r=Math.floor(xu(this.bounds.getNorth())*e),s=Math.ceil(yu(this.bounds.getEast())*e),n=Math.ceil(xu(this.bounds.getSouth())*e);return t.x>=i&&t.x=r&&t.y{this._options.tiles=t})),this}setUrl(t){return this.setSourceProperty((()=>{this.url=t,this._options.url=t})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null)}serialize(){return y({},this._options)}loadTile(t){return i(this,void 0,void 0,(function*(){const e=t.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(e,"Tile"),uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,tileSize:this.tileSize*t.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId};i.request.collectResourceTiming=this._collectResourceTiming;let r="RT";if(t.actor&&"expired"!==t.state){if("loading"===t.state)return new Promise(((e,i)=>{t.reloadPromise={resolve:e,reject:i}}))}else t.actor=this.dispatcher.getActor(),r="LT";t.abortController=new AbortController;try{const e=yield t.actor.sendAsync({type:r,data:i},t.abortController);if(delete t.abortController,t.aborted)return;this._afterTileLoadWorkerResponse(t,e)}catch(e){if(delete t.abortController,t.aborted)return;if(e&&404!==e.status)throw e;this._afterTileLoadWorkerResponse(t,null)}}))}_afterTileLoadWorkerResponse(t,e){if(e&&e.resourceTiming&&(t.resourceTiming=e.resourceTiming),e&&this.map._refreshExpiredTiles&&t.setExpiryData(e),t.loadVectorData(e,this.map.painter),t.reloadPromise){const e=t.reloadPromise;t.reloadPromise=null,this.loadTile(t).then(e.resolve).catch(e.reject)}}abortTile(t){return i(this,void 0,void 0,(function*(){t.abortController&&(t.abortController.abort(),delete t.abortController),t.actor&&(yield t.actor.sendAsync({type:"AT",data:{uid:t.uid,type:this.type,source:this.id}}))}))}unloadTile(t){return i(this,void 0,void 0,(function*(){t.unloadVectorData(),t.actor&&(yield t.actor.sendAsync({type:"RMT",data:{uid:t.uid,type:this.type,source:this.id}}))}))}hasTransition(){return!1}}class Iu extends nt{constructor(t,e,i,r){super(),this.id=t,this.dispatcher=i,this.setEventedParent(r),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=y({type:"raster"},e),y(this,x(e,["url","scheme","tileSize"]))}load(){return i(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new rt("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const t=yield du(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,t&&(y(this,t),t.bounds&&(this.tileBounds=new Tu(t.bounds,this.minzoom,this.maxzoom)),this.fire(new rt("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new rt("data",{dataType:"source",sourceDataType:"content"})))}catch(t){this._tileJSONRequest=null,this.fire(new st(t))}}))}loaded(){return this._loaded}onAdd(t){this.map=t,this.load()}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null)}setSourceProperty(t){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),t(),this.load()}setTiles(t){return this.setSourceProperty((()=>{this._options.tiles=t})),this}setUrl(t){return this.setSourceProperty((()=>{this.url=t,this._options.url=t})),this}serialize(){return y({},this._options)}hasTile(t){return!this.tileBounds||this.tileBounds.contains(t.canonical)}loadTile(t){return i(this,void 0,void 0,(function*(){const e=t.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);t.abortController=new AbortController;try{const i=yield Q.getImage(this.map._requestManager.transformRequest(e,"Tile"),t.abortController,this.map._refreshExpiredTiles);if(delete t.abortController,t.aborted)return void(t.state="unloaded");if(i&&i.data){this.map._refreshExpiredTiles&&i.cacheControl&&i.expires&&t.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const e=this.map.painter.context,r=e.gl,s=i.data;t.texture=this.map.painter.getTileTexture(s.width),t.texture?t.texture.update(s,{useMipmap:!0}):(t.texture=new Uh(e,s,r.RGBA,{useMipmap:!0}),t.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE,r.LINEAR_MIPMAP_NEAREST)),t.state="loaded"}}catch(e){if(delete t.abortController,t.aborted)t.state="unloaded";else if(e)throw t.state="errored",e}}))}abortTile(t){return i(this,void 0,void 0,(function*(){t.abortController&&(t.abortController.abort(),delete t.abortController)}))}unloadTile(t){return i(this,void 0,void 0,(function*(){t.texture&&this.map.painter.saveTileTexture(t.texture)}))}hasTransition(){return!1}}function Au(t,e,i){var r=2*Math.PI*6378137/256/Math.pow(2,i);return[t*r-2*Math.PI*6378137/2,e*r-2*Math.PI*6378137/2]}class Eu{constructor(t,e,i){if(!function(t,e,i){return!(t<0||t>25||i<0||i>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,i))throw new Error(`x=${e}, y=${i}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=i,this.key=Pu(0,t,t,e,i)}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,i){const r=(n=this.y,a=this.z,o=Au(256*(s=this.x),256*(n=Math.pow(2,a)-n-1),a),l=Au(256*(s+1),256*(n+1),a),o[0]+","+o[1]+","+l[0]+","+l[1]);var s,n,a,o,l;const c=function(t,e,i){let r,s="";for(let n=t;n>0;n--)r=1<1?"@2x":"").replace(/{quadkey}/g,c).replace(/{bbox-epsg-3857}/g,r)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new a((t.x*e-this.x)*to,(t.y*e-this.y)*to)}toString(){return`${this.z}/${this.x}/${this.y}`}}class Cu{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Pu(t,e.z,e.z,e.x,e.y)}}class zu{constructor(t,e,i,r,s){if(t= z; overscaledZ = ${t}; z = ${i}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Eu(i,+r,+s),this.key=Pu(e,t,i,r,s)}clone(){return new zu(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new zu(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new zu(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const i=this.canonical.z-t;return t>this.canonical.z?Pu(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Pu(this.wrap*+e,t,t,this.canonical.x>>i,this.canonical.y>>i)}isChildOf(t){if(t.wrap!==this.wrap)return!1;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return[new zu(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,i=2*this.canonical.x,r=2*this.canonical.y;return[new zu(e,this.wrap,e,i,r),new zu(e,this.wrap,e,i+1,r),new zu(e,this.wrap,e,i,r+1),new zu(e,this.wrap,e,i+1,r+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.ythis.max&&(this.max=i),i=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(e+1)*this.stride+(t+1)}unpack(t,e,i){return t*this.redFactor+e*this.greenFactor+i*this.blueFactor-this.baseShift}getPixels(){return new Qo({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,i){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let r=e*this.dim,s=e*this.dim+this.dim,n=i*this.dim,a=i*this.dim+this.dim;switch(e){case-1:r=s-1;break;case 1:s=r+1}switch(i){case-1:n=a-1;break;case 1:a=n+1}const o=-e*this.dim,l=-i*this.dim;for(let e=n;e0&&(o[new zu(t.overscaledZ,s,e.z,r,e.y-1).key]={backfilled:!1},o[new zu(t.overscaledZ,t.wrap,e.z,e.x,e.y-1).key]={backfilled:!1},o[new zu(t.overscaledZ,a,e.z,n,e.y-1).key]={backfilled:!1}),e.y+10&&y(r,{resourceTiming:i}),this.fire(new rt("data",Object.assign(Object.assign({},r),{sourceDataType:"metadata"}))),this.fire(new rt("data",Object.assign(Object.assign({},r),{sourceDataType:"content"})))}catch(t){if(this._pendingLoads--,this._removed)return void this.fire(new rt("dataabort",{dataType:"source"}));this.fire(new st(t))}}))}loaded(){return 0===this._pendingLoads}loadTile(t){return i(this,void 0,void 0,(function*(){const e=t.actor?"RT":"LT";t.actor=this.actor;const i={type:this.type,uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId};t.abortController=new AbortController;const r=yield this.actor.sendAsync({type:e,data:i},t.abortController);delete t.abortController,t.unloadVectorData(),t.aborted||t.loadVectorData(r,this.map.painter,"RT"===e)}))}abortTile(t){return i(this,void 0,void 0,(function*(){t.abortController&&(t.abortController.abort(),delete t.abortController),t.aborted=!0}))}unloadTile(t){return i(this,void 0,void 0,(function*(){t.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:t.uid,type:this.type,source:this.id}})}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}})}serialize(){return y({},this._options,{type:this.type,data:this._data})}hasTransition(){return!1}}var Du=gn([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class Lu extends nt{constructor(t,e,i,r){super(),this.id=t,this.dispatcher=i,this.coordinates=e.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(r),this.options=e}load(t){return i(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new rt("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const e=yield Q.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,e&&e.data&&(this.image=e.data,t&&(this.coordinates=t),this._finishLoading())}catch(t){this._request=null,this._loaded=!0,this.fire(new st(t))}}))}loaded(){return this._loaded}updateImage(t){return t.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=t.url,this.load(t.coordinates).finally((()=>{this.texture=null})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new rt("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(t){this.map=t,this.load()}onRemove(){this._request&&(this._request.abort(),this._request=null)}setCoordinates(t){this.coordinates=t;const e=t.map(wu.fromLngLat);this.tileID=function(t){let e=1/0,i=1/0,r=-1/0,s=-1/0;for(const n of t)e=Math.min(e,n.x),i=Math.min(i,n.y),r=Math.max(r,n.x),s=Math.max(s,n.y);const n=Math.max(r-e,s-i),a=Math.max(0,Math.floor(-Math.log(n)/Math.LN2)),o=Math.pow(2,a);return new Eu(a,Math.floor((e+r)/2*o),Math.floor((i+s)/2*o))}(e),this.minzoom=this.maxzoom=this.tileID.z;const i=e.map((t=>this.tileID.getTilePoint(t)._round()));return this._boundsArray=new ia,this._boundsArray.emplaceBack(i[0].x,i[0].y,0,0),this._boundsArray.emplaceBack(i[1].x,i[1].y,to,0),this._boundsArray.emplaceBack(i[3].x,i[3].y,0,to),this._boundsArray.emplaceBack(i[2].x,i[2].y,to,to),this.boundsBuffer&&(this.boundsBuffer.destroy(),delete this.boundsBuffer),this.fire(new rt("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const t=this.map.painter.context,e=t.gl;this.boundsBuffer||(this.boundsBuffer=t.createVertexBuffer(this._boundsArray,Du.members)),this.boundsSegments||(this.boundsSegments=ba.simpleSegment(0,0,4,2)),this.texture||(this.texture=new Uh(t,this.image,e.RGBA),this.texture.bind(e.LINEAR,e.CLAMP_TO_EDGE));let i=!1;for(const t in this.tiles){const e=this.tiles[t];"loaded"!==e.state&&(e.state="loaded",e.texture=this.texture,i=!0)}i&&this.fire(new rt("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}loadTile(t){return i(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(t.tileID.canonical)?(this.tiles[String(t.tileID.wrap)]=t,t.buckets={}):t.state="errored"}))}serialize(){return{type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return!1}}class Ru extends Lu{constructor(t,e,i,r){super(t,e,i,r),this.roundZoom=!0,this.type="video",this.options=e}load(){return i(this,void 0,void 0,(function*(){this._loaded=!1;const t=this.options;this.urls=[];for(const e of t.urls)this.urls.push(this.map._requestManager.transformRequest(e,"Source").url);try{const t=yield(t=>{const e=window.document.createElement("video");return e.muted=!0,new Promise((i=>{e.onloadstart=()=>{i(e)};for(const i of t){const t=window.document.createElement("source");G(i)||(e.crossOrigin="Anonymous"),t.src=i,e.appendChild(t)}}))})(this.urls);if(this._loaded=!0,!t)return;this.video=t,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint()})),this.map&&this.video.play(),this._finishLoading()}catch(t){this.fire(new st(t))}}))}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(t){if(this.video){const e=this.video.seekable;te.end(0)?this.fire(new st(new xt(`sources.${this.id}`,null,`Playback for this video can be set only between the ${e.start(0)} and ${e.end(0)}-second mark.`))):this.video.currentTime=t}}getVideo(){return this.video}onAdd(t){this.map||(this.map=t,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)))}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const t=this.map.painter.context,e=t.gl;this.boundsBuffer||(this.boundsBuffer=t.createVertexBuffer(this._boundsArray,Du.members)),this.boundsSegments||(this.boundsSegments=ba.simpleSegment(0,0,4,2)),this.texture?this.video.paused||(this.texture.bind(e.LINEAR,e.CLAMP_TO_EDGE),e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,this.video)):(this.texture=new Uh(t,this.video,e.RGBA),this.texture.bind(e.LINEAR,e.CLAMP_TO_EDGE));let i=!1;for(const t in this.tiles){const e=this.tiles[t];"loaded"!==e.state&&(e.state="loaded",e.texture=this.texture,i=!0)}i&&this.fire(new rt("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class Bu extends Lu{constructor(t,e,i,r){super(t,e,i,r),e.coordinates?Array.isArray(e.coordinates)&&4===e.coordinates.length&&!e.coordinates.some((t=>!Array.isArray(t)||2!==t.length||t.some((t=>"number"!=typeof t))))||this.fire(new st(new xt(`sources.${t}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new st(new xt(`sources.${t}`,null,'missing required property "coordinates"'))),e.animate&&"boolean"!=typeof e.animate&&this.fire(new st(new xt(`sources.${t}`,null,'optional "animate" property must be a boolean value'))),e.canvas?"string"==typeof e.canvas||e.canvas instanceof HTMLCanvasElement||this.fire(new st(new xt(`sources.${t}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new st(new xt(`sources.${t}`,null,'missing required property "canvas"'))),this.options=e,this.animate=void 0===e.animate||e.animate}load(){return i(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new st(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint()},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1)},this._finishLoading())}))}getCanvas(){return this.canvas}onAdd(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play()}onRemove(){this.pause()}prepare(){let t=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,t=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,t=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const e=this.map.painter.context,i=e.gl;this.boundsBuffer||(this.boundsBuffer=e.createVertexBuffer(this._boundsArray,Du.members)),this.boundsSegments||(this.boundsSegments=ba.simpleSegment(0,0,4,2)),this.texture?(t||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new Uh(e,this.canvas,i.RGBA,{premultiply:!0});let r=!1;for(const t in this.tiles){const e=this.tiles[t];"loaded"!==e.state&&(e.state="loaded",e.texture=this.texture,r=!0)}r&&this.fire(new rt("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const t of[this.canvas.width,this.canvas.height])if(isNaN(t)||t<=0)return!0;return!1}}const Fu={},Ou=t=>{switch(t){case"geojson":return ku;case"image":return Lu;case"raster":return Iu;case"raster-dem":return Mu;case"vector":return Su;case"video":return Ru;case"canvas":return Bu}return Fu[t]};class Vu{constructor(t){this._stringToNumber={},this._numberToString=[];for(let e=0;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class Uu{constructor(t,e,i,r,s){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=i,t._y=r,this.properties=t.properties,this.id=s}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(t){this._geometry=t}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t}}function Nu(t,e,i,r,s){return w(t,((t,n)=>{const a=e instanceof nn?e.get(n):null;return a&&a.evaluate?a.evaluate(i,r,s):a}))}function ju(t){let e=1/0,i=1/0,r=-1/0,s=-1/0;for(const n of t)e=Math.min(e,n.x),i=Math.min(i,n.y),r=Math.max(r,n.x),s=Math.max(s,n.y);return{minX:e,minY:i,maxX:r,maxY:s}}function $u(t,e){return e-t}Ds("FeatureIndex",class{constructor(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new Ms(to,16,0),this.grid3D=new Ms(to,16,0),this.featureIndexArray=new Qn,this.promoteId=e}insert(t,e,i,r,s,n){const a=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(i,r,s);const o=n?this.grid3D:this.grid;for(let t=0;t=0&&r[3]>=0&&o.insert(a,r[0],r[1],r[2],r[3])}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new $l.VectorTile(new ih(this.rawTileData)).layers,this.sourceLayerCoder=new Vu(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(t,e,i,r){this.loadVTLayers();const s=t.params||{},n=to/t.tileSize/t.scale,o=jr(s.filter),l=t.queryGeometry,c=t.queryPadding*n,h=ju(l),u=this.grid.query(h.minX-c,h.minY-c,h.maxX+c,h.maxY+c),d=ju(t.cameraQueryGeometry),p=this.grid3D.query(d.minX-c,d.minY-c,d.maxX+c,d.maxY+c,((e,i,r,s)=>function(t,e,i,r,s){for(const n of t)if(e<=n.x&&i<=n.y&&r>=n.x&&s>=n.y)return!0;const n=[new a(e,i),new a(e,s),new a(r,s),new a(r,i)];if(t.length>2)for(const e of n)if(go(t,e))return!0;for(let e=0;e(d||(d=ro(e)),i.queryIntersectsFeature(l,e,r,d,this.z,t.transform,n,t.pixelPosMatrix))))}return f}loadMatchingFeature(t,e,i,r,s,n,a,o,l,c,h){const u=this.bucketLayerIDs[e];if(n&&!function(t,e){for(let i=0;i=0)return!0;return!1}(n,u))return;const d=this.sourceLayerCoder.decode(i),p=this.vtLayers[d].feature(r);if(s.needGeometry){const t=so(p,!0);if(!s.filter(new Ks(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!s.filter(new Ks(this.tileID.overscaledZ),p))return;const f=this.getId(p,d);for(let e=0;e{throw this.status="error",t}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null}setRTLTextPlugin(t){return i(this,arguments,void 0,(function*(t,e=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=F.resolveURL(t),!this.url)throw new Error(`requested url ${t} is invalid`);if("unavailable"===this.status){if(!e)return this._requestImport();this.status="deferred",this._syncState(this.status)}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return i(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new rt(qu))}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport()}}let Gu=null;function Wu(){return Gu||(Gu=new Zu),Gu}class Hu{constructor(t,e){this.timeAdded=0,this.fadeEndTime=0,this.tileID=t,this.uid=b(),this.uses=0,this.tileSize=e,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading"}registerFadeDuration(t){const e=t+this.timeAdded;ee.getLayer(t))).filter(Boolean);if(0!==t.length){r.layers=t,r.stateDependentLayerIds&&(r.stateDependentLayers=r.stateDependentLayerIds.map((e=>t.filter((t=>t.id===e))[0])));for(const e of t)i[e.id]=r}}return i}(t.buckets,e.style),this.hasSymbolBuckets=!1;for(const t in this.buckets){const e=this.buckets[t];if(e instanceof Sh){if(this.hasSymbolBuckets=!0,!i)break;e.justReloaded=!0}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const t in this.buckets){const e=this.buckets[t];if(e instanceof Sh&&e.hasRTLText){this.hasRTLText=!0,Wu().lazyLoad();break}}this.queryPadding=0;for(const t in this.buckets){const i=this.buckets[t];this.queryPadding=Math.max(this.queryPadding,e.style.getLayer(t).queryRadius(i))}t.imageAtlas&&(this.imageAtlas=t.imageAtlas),t.imageBackgroundsAtlas&&(this.imageBackgroundsAtlas=t.imageBackgroundsAtlas),t.glyphAtlasImage&&(this.glyphAtlasImage=t.glyphAtlasImage)}else this.collisionBoxArray=new $n}unloadVectorData(){for(const t in this.buckets)this.buckets[t].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageBackgroundsAtlasTexture&&this.imageBackgroundsAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.imageBackgroundsAtlas&&(this.imageBackgroundsAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded"}getBucket(t){return this.buckets[t.id]}upload(t){for(const e in this.buckets){const i=this.buckets[e];i.uploadPending()&&i.upload(t)}const e=t.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new Uh(t,this.imageAtlas.image,e.RGBA),this.imageAtlas.uploaded=!0),this.imageBackgroundsAtlas&&!this.imageBackgroundsAtlas.uploaded&&(this.imageBackgroundsAtlasTexture=new Uh(t,this.imageBackgroundsAtlas.image,e.RGBA),this.imageBackgroundsAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new Uh(t,this.glyphAtlasImage,e.ALPHA),this.glyphAtlasImage=null)}prepare(t){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(t,this.imageAtlasTexture),this.imageBackgroundsAtlas&&this.imageBackgroundsAtlas.patchUpdatedImages(t,this.imageBackgroundsAtlasTexture)}queryRenderedFeatures(t,e,i,r,s,n,a,o,l,c){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:r,cameraQueryGeometry:s,scale:n,tileSize:this.tileSize,pixelPosMatrix:c,transform:o,params:a,queryPadding:this.queryPadding*l},t,e,i):{}}querySourceFeatures(t,e){const i=this.latestFeatureIndex;if(!i||!i.rawTileData)return;const r=i.loadVTLayers(),s=e&&e.sourceLayer?e.sourceLayer:"",n=r._geojsonTileLayer||r[s];if(!n)return;const a=jr(e&&e.filter),{z:o,x:l,y:c}=this.tileID.canonical,h={z:o,x:l,y:c};for(let e=0;e@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((t,i,r,s)=>{const n=r||s;return e[i]=!n||n.toLowerCase(),""})),e["max-age"]){const t=parseInt(e["max-age"],10);isNaN(t)?delete e["max-age"]:e["max-age"]=t}return e}(t.cacheControl);e["max-age"]&&(this.expirationTime=Date.now()+1e3*e["max-age"])}else t.expires&&(this.expirationTime=new Date(t.expires).getTime());if(this.expirationTime){const t=Date.now();let i=!1;if(this.expirationTime>t)i=!1;else if(e)if(this.expirationTime{this.remove(t,s)}),i)),this.data[r].push(s),this.order.push(r),this.order.length>this.max){const t=this._getAndRemoveByKey(this.order[0]);t&&this.onRemove(t)}return this}has(t){return t.wrapped().key in this.data}getAndRemove(t){return this.has(t)?this._getAndRemoveByKey(t.wrapped().key):null}_getAndRemoveByKey(t){const e=this.data[t].shift();return e.timeout&&clearTimeout(e.timeout),0===this.data[t].length&&delete this.data[t],this.order.splice(this.order.indexOf(t),1),e.value}getByKey(t){const e=this.data[t];return e?e[0].value:null}get(t){return this.has(t)?this.data[t.wrapped().key][0].value:null}remove(t,e){if(!this.has(t))return this;const i=t.wrapped().key,r=void 0===e?0:this.data[i].indexOf(e),s=this.data[i][r];return this.data[i].splice(r,1),s.timeout&&clearTimeout(s.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(s.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(t){for(this.max=t;this.order.length>this.max;){const t=this._getAndRemoveByKey(this.order[0]);t&&this.onRemove(t)}return this}filter(t){const e=[];for(const i in this.data)for(const r of this.data[i])t(r.value)||e.push(r);for(const t of e)this.remove(t.value.tileID,t)}}class Ku{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(t,e,i){const r=String(e);if(this.stateChanges[t]=this.stateChanges[t]||{},this.stateChanges[t][r]=this.stateChanges[t][r]||{},y(this.stateChanges[t][r],i),null===this.deletedStates[t]){this.deletedStates[t]={};for(const e in this.state[t])e!==r&&(this.deletedStates[t][e]=null)}else if(this.deletedStates[t]&&null===this.deletedStates[t][r]){this.deletedStates[t][r]={};for(const e in this.state[t][r])i[e]||(this.deletedStates[t][r][e]=null)}else for(const e in i)this.deletedStates[t]&&this.deletedStates[t][r]&&null===this.deletedStates[t][r][e]&&delete this.deletedStates[t][r][e]}removeFeatureState(t,e,i){if(null===this.deletedStates[t])return;const r=String(e);if(this.deletedStates[t]=this.deletedStates[t]||{},i&&void 0!==e)null!==this.deletedStates[t][r]&&(this.deletedStates[t][r]=this.deletedStates[t][r]||{},this.deletedStates[t][r][i]=null);else if(void 0!==e)if(this.stateChanges[t]&&this.stateChanges[t][r])for(i in this.deletedStates[t][r]={},this.stateChanges[t][r])this.deletedStates[t][r][i]=null;else this.deletedStates[t][r]=null;else this.deletedStates[t]=null}getState(t,e){const i=String(e),r=y({},(this.state[t]||{})[i],(this.stateChanges[t]||{})[i]);if(null===this.deletedStates[t])return{};if(this.deletedStates[t]){const i=this.deletedStates[t][e];if(null===i)return{};for(const t in i)delete r[t]}return r}initializeTileState(t,e){t.setFeatureState(this.state,e)}coalesceChanges(t,e){const i={};for(const t in this.stateChanges){this.state[t]=this.state[t]||{};const e={};for(const i in this.stateChanges[t])this.state[t][i]||(this.state[t][i]={}),y(this.state[t][i],this.stateChanges[t][i]),e[i]=this.state[t][i];i[t]=e}for(const t in this.deletedStates){this.state[t]=this.state[t]||{};const e={};if(null===this.deletedStates[t])for(const i in this.state[t])e[i]={},this.state[t][i]={};else for(const i in this.deletedStates[t]){if(null===this.deletedStates[t][i])this.state[t][i]={};else for(const e of Object.keys(this.deletedStates[t][i]))delete this.state[t][i][e];e[i]=this.state[t][i]}i[t]=i[t]||{},y(i[t],e)}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(i).length)for(const r in t)t[r].setFeatureState(i,e)}}class Yu extends nt{constructor(t,e,i){super(),this.id=t,this.dispatcher=i,this.on("data",(t=>this._dataHandler(t))),this.on("dataloading",(()=>{this._sourceErrored=!1})),this.on("error",(()=>{this._sourceErrored=this._source.loaded()})),this._source=((t,e,i,r)=>{const s=new(Ou(e.type))(t,e,i,r);if(s.id!==t)throw new Error(`Expected Source id to be ${t} instead of ${s.id}`);return s})(t,e,i,this),this._tiles={},this._cache=new Xu(0,(t=>this._unloadTile(t))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new Ku,this._didEmitContent=!1,this._updated=!1}onAdd(t){this.map=t,this._maxTileCacheSize=t?t._maxTileCacheSize:null,this._maxTileCacheZoomLevels=t?t._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(t)}onRemove(t){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(t)}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded)return!1;if(!this._source.loaded())return!1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return!0;if(!this._updated)return!1;for(const t in this._tiles){const e=this._tiles[t];if("loaded"!==e.state&&"errored"!==e.state)return!1}return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const t=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,t&&this.reload(),this.transform&&this.update(this.transform,this.terrain)}_loadTile(t,e,r){return i(this,void 0,void 0,(function*(){try{yield this._source.loadTile(t),this._tileLoaded(t,e,r)}catch(e){t.state="errored",404!==e.status?this._source.fire(new st(e,{tile:t})):this.update(this.transform,this.terrain)}}))}_unloadTile(t){this._source.unloadTile&&this._source.unloadTile(t)}_abortTile(t){this._source.abortTile&&this._source.abortTile(t),this._source.fire(new rt("dataabort",{tile:t,coord:t.tileID,dataType:"source"}))}serialize(){return this._source.serialize()}prepare(t){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const e in this._tiles){const i=this._tiles[e];i.upload(t),i.prepare(this.map.style.imageManager)}}getIds(){return Object.values(this._tiles).map((t=>t.tileID)).sort(Ju).map((t=>t.key))}getRenderableIds(t){const e=[];for(const i in this._tiles)this._isIdRenderable(i,t)&&e.push(this._tiles[i]);return t?e.sort(((t,e)=>{const i=t.tileID,r=e.tileID,s=new a(i.canonical.x,i.canonical.y)._rotate(this.transform.angle),n=new a(r.canonical.x,r.canonical.y)._rotate(this.transform.angle);return i.overscaledZ-r.overscaledZ||n.y-s.y||n.x-s.x})).map((t=>t.tileID.key)):e.map((t=>t.tileID)).sort(Ju).map((t=>t.key))}hasRenderableParent(t){const e=this.findLoadedParent(t,0);return!!e&&this._isIdRenderable(e.tileID.key)}_isIdRenderable(t,e){return this._tiles[t]&&this._tiles[t].hasData()&&!this._coveredTiles[t]&&(e||!this._tiles[t].holdingForFade())}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const t in this._tiles)"errored"!==this._tiles[t].state&&this._reloadTile(t,"reloading")}}_reloadTile(t,e){return i(this,void 0,void 0,(function*(){const i=this._tiles[t];i&&("loading"!==i.state&&(i.state=e),yield this._loadTile(i,t,e))}))}_tileLoaded(t,e,i){t.timeAdded=F.now(),"expired"===i&&(t.refreshedUponExpiration=!0),this._setTileReloadTimer(e,t),"raster-dem"===this.getSource().type&&t.dem&&this._backfillDEM(t),this._state.initializeTileState(t,this.map?this.map.painter:null),t.aborted||this._source.fire(new rt("data",{dataType:"source",tile:t,coord:t.tileID}))}_backfillDEM(t){const e=this.getRenderableIds();for(let r=0;r1||(Math.abs(i)>1&&(1===Math.abs(i+s)?i+=s:1===Math.abs(i-s)&&(i-=s)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,i,r),t.neighboringTiles&&t.neighboringTiles[n]&&(t.neighboringTiles[n].backfilled=!0)))}}getTile(t){return this.getTileByID(t.key)}getTileByID(t){return this._tiles[t]}_retainLoadedChildren(t,e,i,r){for(const s in this._tiles){let n=this._tiles[s];if(r[s]||!n.hasData()||n.tileID.overscaledZ<=e||n.tileID.overscaledZ>i)continue;let a=n.tileID;for(;n&&n.tileID.overscaledZ>e+1;){const t=n.tileID.scaledTo(n.tileID.overscaledZ-1);n=this._tiles[t.key],n&&n.hasData()&&(a=t)}let o=a;for(;o.overscaledZ>e;)if(o=o.scaledTo(o.overscaledZ-1),t[o.key]){r[a.key]=a;break}}}findLoadedParent(t,e){if(t.key in this._loadedParentTiles){const i=this._loadedParentTiles[t.key];return i&&i.tileID.overscaledZ>=e?i:null}for(let i=t.overscaledZ-1;i>=e;i--){const e=t.scaledTo(i),r=this._getLoadedTile(e);if(r)return r}}findLoadedSibling(t){return this._getLoadedTile(t)}_getLoadedTile(t){const e=this._tiles[t.key];return e&&e.hasData()?e:this._cache.getByKey(t.wrapped().key)}updateCacheSize(t){const e=Math.ceil(t.width/this._source.tileSize)+1,i=Math.ceil(t.height/this._source.tileSize)+1,r=Math.floor(e*i*(null===this._maxTileCacheZoomLevels?V.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),s="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(s)}handleWrapJump(t){const e=Math.round((t-(void 0===this._prevLng?t:this._prevLng))/360);if(this._prevLng=t,e){const t={};for(const i in this._tiles){const r=this._tiles[i];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+e),t[r.tileID.key]=r}this._tiles=t;for(const t in this._timers)clearTimeout(this._timers[t]),delete this._timers[t];for(const t in this._tiles)this._setTileReloadTimer(t,this._tiles[t])}}_updateCoveredAndRetainedTiles(t,e,i,r,s,n){const a={},o={},l=Object.keys(t),c=F.now();for(const i of l){const r=t[i],s=this._tiles[i];if(!s||0!==s.fadeEndTime&&s.fadeEndTime<=c)continue;const n=this.findLoadedParent(r,e),l=this.findLoadedSibling(r),h=n||l||null;h&&(this._addTile(h.tileID),a[h.tileID.key]=h.tileID),o[i]=r}this._retainLoadedChildren(o,r,i,t);for(const e in a)t[e]||(this._coveredTiles[e]=!0,t[e]=a[e]);if(n){const e={},i={};for(const t of s)this._tiles[t.key].hasData()?e[t.key]=t:i[t.key]=t;for(const r in i){const s=i[r].children(this._source.maxzoom);this._tiles[s[0].key]&&this._tiles[s[1].key]&&this._tiles[s[2].key]&&this._tiles[s[3].key]&&(e[s[0].key]=t[s[0].key]=s[0],e[s[1].key]=t[s[1].key]=s[1],e[s[2].key]=t[s[2].key]=s[2],e[s[3].key]=t[s[3].key]=s[3],delete i[r])}for(const r in i){const s=i[r],n=this.findLoadedParent(s,this._source.minzoom),a=this.findLoadedSibling(s),o=n||a||null;if(o){e[o.tileID.key]=t[o.tileID.key]=o.tileID;for(const t in e)e[t].isChildOf(o.tileID)&&delete e[t]}}for(const t in this._tiles)e[t]||(this._coveredTiles[t]=!0)}}update(t,e){if(!this._sourceLoaded||this._paused)return;let i;this.transform=t,this.terrain=e,this.updateCacheSize(t),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?i=t.getVisibleUnwrappedCoordinates(this._source.tileID).map((t=>new zu(t.canonical.z,t.wrap,t.canonical.z,t.canonical.x,t.canonical.y))):(i=t.coveringTiles({tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:e}),this._source.hasTile&&(i=i.filter((t=>this._source.hasTile(t))))):i=[];const r=t.coveringZoomLevel(this._source),s=Math.max(r-Yu.maxOverzooming,this._source.minzoom),n=Math.max(r+Yu.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const t={};for(const e of i)if(e.canonical.z>this._source.minzoom){const i=e.scaledTo(e.canonical.z-1);t[i.key]=i;const r=e.scaledTo(Math.max(this._source.minzoom,Math.min(e.canonical.z,5)));t[r.key]=r}i=i.concat(Object.values(t))}const a=0===i.length&&!this._updated&&this._didEmitContent;this._updated=!0,a&&this.fire(new rt("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const o=this._updateRetainedTiles(i,r);Qu(this._source.type)&&this._updateCoveredAndRetainedTiles(o,s,n,r,i,e);for(const t in o)this._tiles[t].clearFadeHold();const l=function(t,e){const i=[];for(const r in t)r in e||i.push(r);return i}(this._tiles,o);for(const t of l){const e=this._tiles[t];e.hasSymbolBuckets&&!e.holdingForFade()?e.setHoldDuration(this.map._fadeDuration):e.hasSymbolBuckets&&!e.symbolFadeFinished()||this._removeTile(t)}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache()}releaseSymbolFadeTiles(){for(const t in this._tiles)this._tiles[t].holdingForFade()&&this._removeTile(t)}_updateRetainedTiles(t,e){var i;const r={},s={},n=Math.max(e-Yu.maxOverzooming,this._source.minzoom),a=Math.max(e+Yu.maxUnderzooming,this._source.minzoom),o={};for(const i of t){const t=this._addTile(i);r[i.key]=i,t.hasData()||ethis._source.maxzoom){const t=a.children(this._source.maxzoom)[0],e=this.getTile(t);if(e&&e.hasData()){r[t.key]=t;continue}}else{const t=a.children(this._source.maxzoom);if(r[t[0].key]&&r[t[1].key]&&r[t[2].key]&&r[t[3].key])continue}let o=t.wasRequested();for(let e=a.overscaledZ-1;e>=n;--e){const n=a.scaledTo(e);if(s[n.key])break;if(s[n.key]=!0,t=this.getTile(n),!t&&o&&(t=this._addTile(n)),t){const e=t.hasData();if((e||!(null===(i=this.map)||void 0===i?void 0:i.cancelPendingTileRequestsWhileZooming)||o)&&(r[n.key]=n),o=t.wasRequested(),e)break}}}return r}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const t in this._tiles){const e=[];let i,r=this._tiles[t].tileID;for(;r.overscaledZ>0;){if(r.key in this._loadedParentTiles){i=this._loadedParentTiles[r.key];break}e.push(r.key);const t=r.scaledTo(r.overscaledZ-1);if(i=this._getLoadedTile(t),i)break;r=t}for(const t of e)this._loadedParentTiles[t]=i}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const t in this._tiles){const e=this._tiles[t].tileID,i=this._getLoadedTile(e);this._loadedSiblingTiles[e.key]=i}}_addTile(t){let e=this._tiles[t.key];if(e)return e;e=this._cache.getAndRemove(t),e&&(this._setTileReloadTimer(t.key,e),e.tileID=t,this._state.initializeTileState(e,this.map?this.map.painter:null),this._cacheTimers[t.key]&&(clearTimeout(this._cacheTimers[t.key]),delete this._cacheTimers[t.key],this._setTileReloadTimer(t.key,e)));const i=e;return e||(e=new Hu(t,this._source.tileSize*t.overscaleFactor()),this._loadTile(e,t.key,e.state)),e.uses++,this._tiles[t.key]=e,i||this._source.fire(new rt("dataloading",{tile:e,coord:e.tileID,dataType:"source"})),e}_setTileReloadTimer(t,e){t in this._timers&&(clearTimeout(this._timers[t]),delete this._timers[t]);const i=e.getExpiryTimeout();i&&(this._timers[t]=setTimeout((()=>{this._reloadTile(t,"expired"),delete this._timers[t]}),i))}_removeTile(t){const e=this._tiles[t];e&&(e.uses--,delete this._tiles[t],this._timers[t]&&(clearTimeout(this._timers[t]),delete this._timers[t]),e.uses>0||(e.hasData()&&"reloading"!==e.state?this._cache.add(e.tileID,e,e.getExpiryTimeout()):(e.aborted=!0,this._abortTile(e),this._unloadTile(e))))}_dataHandler(t){const e=t.sourceDataType;"source"===t.dataType&&"metadata"===e&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===t.dataType&&"content"===e&&(this.reload(),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0)}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const t in this._tiles)this._removeTile(t);this._cache.reset()}tilesIn(t,e,i){const r=[],s=this.transform;if(!s)return r;const n=i?s.getCameraQueryGeometry(t):t,a=t.map((t=>s.pointCoordinate(t,this.terrain))),o=n.map((t=>s.pointCoordinate(t,this.terrain))),l=this.getIds();let c=1/0,h=1/0,u=-1/0,d=-1/0;for(const t of o)c=Math.min(c,t.x),h=Math.min(h,t.y),u=Math.max(u,t.x),d=Math.max(d,t.y);for(let t=0;t=0&&m[1].y+f>=0){const t=a.map((t=>n.getTilePoint(t))),e=o.map((t=>n.getTilePoint(t)));r.push({tile:i,tileID:n,queryGeometry:t,cameraQueryGeometry:e,scale:p})}}return r}getVisibleCoordinates(t){const e=this.getRenderableIds(t).map((t=>this._tiles[t].tileID));for(const t of e)t.posMatrix=this.transform.calculatePosMatrix(t.toUnwrapped());return e}hasTransition(){if(this._source.hasTransition())return!0;if(Qu(this._source.type)){const t=F.now();for(const e in this._tiles)if(this._tiles[e].fadeEndTime>=t)return!0}return!1}setFeatureState(t,e,i){this._state.updateState(t=t||"_geojsonTileLayer",e,i)}removeFeatureState(t,e,i){this._state.removeFeatureState(t=t||"_geojsonTileLayer",e,i)}getFeatureState(t,e){return this._state.getState(t=t||"_geojsonTileLayer",e)}setDependencies(t,e,i){const r=this._tiles[t];r&&r.setDependencies(e,i)}reloadTilesForDependencies(t,e){for(const i in this._tiles)this._tiles[i].hasDependency(t,e)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(t,e)))}}function Ju(t,e){const i=Math.abs(2*t.wrap)-+(t.wrap<0),r=Math.abs(2*e.wrap)-+(e.wrap<0);return t.overscaledZ-e.overscaledZ||r-i||e.canonical.y-t.canonical.y||e.canonical.x-t.canonical.x}function Qu(t){return"raster"===t||"image"===t||"video"===t}Yu.maxOverzooming=10,Yu.maxUnderzooming=3;class td{constructor(t,e){this.reset(t,e)}reset(t,e){this.points=t||[],this._distances=[0];for(let t=1;t0?(r-n)/a:0;return this.points[s].mult(1-o).add(this.points[e].mult(o))}}function ed(t,e){let i=!0;return"always"===t||"never"!==t&&"never"!==e||(i=!1),i}class id{constructor(t,e,i){const r=this.boxCells=[],s=this.circleCells=[];this.xCellCount=Math.ceil(t/i),this.yCellCount=Math.ceil(e/i);for(let t=0;tthis.width||r<0||e>this.height)return[];const o=[];if(t<=0&&e<=0&&this.width<=i&&this.height<=r){if(s)return[{key:null,x1:t,y1:e,x2:i,y2:r}];for(let t=0;t0}hitTestCircle(t,e,i,r,s){const n=t-i,a=t+i,o=e-i,l=e+i;if(a<0||n>this.width||l<0||o>this.height)return!1;const c=[];return this._forEachCell(n,o,a,l,this._queryCellCircle,c,{hitTest:!0,overlapMode:r,circle:{x:t,y:e,radius:i},seenUids:{box:{},circle:{}}},s),c.length>0}_queryCell(t,e,i,r,s,n,a,o){const{seenUids:l,hitTest:c,overlapMode:h}=a,u=this.boxCells[s];if(null!==u){const s=this.bboxes;for(const a of u)if(!l.box[a]){l.box[a]=!0;const u=4*a,d=this.boxKeys[a];if(t<=s[u+2]&&e<=s[u+3]&&i>=s[u+0]&&r>=s[u+1]&&(!o||o(d))&&(!c||!ed(h,d.overlapMode))&&(n.push({key:d,x1:s[u],y1:s[u+1],x2:s[u+2],y2:s[u+3]}),c))return!0}}const d=this.circleCells[s];if(null!==d){const s=this.circles;for(const a of d)if(!l.circle[a]){l.circle[a]=!0;const u=3*a,d=this.circleKeys[a];if(this._circleAndRectCollide(s[u],s[u+1],s[u+2],t,e,i,r)&&(!o||o(d))&&(!c||!ed(h,d.overlapMode))){const t=s[u],e=s[u+1],i=s[u+2];if(n.push({key:d,x1:t-i,y1:e-i,x2:t+i,y2:e+i}),c)return!0}}}return!1}_queryCellCircle(t,e,i,r,s,n,a,o){const{circle:l,seenUids:c,overlapMode:h}=a,u=this.boxCells[s];if(null!==u){const t=this.bboxes;for(const e of u)if(!c.box[e]){c.box[e]=!0;const i=4*e,r=this.boxKeys[e];if(this._circleAndRectCollide(l.x,l.y,l.radius,t[i+0],t[i+1],t[i+2],t[i+3])&&(!o||o(r))&&!ed(h,r.overlapMode))return n.push(!0),!0}}const d=this.circleCells[s];if(null!==d){const t=this.circles;for(const e of d)if(!c.circle[e]){c.circle[e]=!0;const i=3*e,r=this.circleKeys[e];if(this._circlesCollide(t[i],t[i+1],t[i+2],l.x,l.y,l.radius)&&(!o||o(r))&&!ed(h,r.overlapMode))return n.push(!0),!0}}}_forEachCell(t,e,i,r,s,n,a,o){const l=this._convertToXCellCoord(t),c=this._convertToYCellCoord(e),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(r);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(s.call(this,t,e,i,r,this.xCellCount*l+d,n,a,o))return}_convertToXCellCoord(t){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(t*this.xScale)))}_convertToYCellCoord(t){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(t*this.yScale)))}_circlesCollide(t,e,i,r,s,n){const a=r-t,o=s-e,l=i+n;return l*l>a*a+o*o}_circleAndRectCollide(t,e,i,r,s,n,a){const o=(n-r)/2,l=Math.abs(t-(r+o));if(l>o+i)return!1;const c=(a-s)/2,h=Math.abs(e-(s+c));if(h>c+i)return!1;if(l<=o||h<=c)return!0;const u=l-o,d=h-c;return u*u+d*d<=i*i}}function rd(t,e,i,r,s){const n=Eo();return e?(Do(n,n,[1/s,1/s,1]),i||Ro(n,n,r.angle)):Mo(n,r.labelPlaneMatrix,t),n}function sd(t,e,i,r,s){if(e){const e=Co(t);return Do(e,e,[s,s,1]),i||Ro(e,e,-r.angle),e}return r.glCoordMatrix}function nd(t,e,i,r){let s;r?(s=[t,e,r(t,e),1],jo(s,s,i)):(s=[t,e,0,1],vd(s,s,i));const n=s[3];return{point:new a(s[0]/n,s[1]/n),signedDistanceFromCamera:n,isOccluded:!1}}function ad(t,e){return.5+t/e*.5}function od(t,e){return t.x>=-e[0]&&t.x<=e[0]&&t.y>=-e[1]&&t.y<=e[1]}function ld(t,e,i,r,s,n,o,l,c,h,u,d,p,f,m){const _=r?t.textSizeData:t.iconSizeData,g=mh(_,i.transform.zoom),y=[256/i.width*2+1,256/i.height*2+1],x=r?t.text.dynamicLayoutVertexArray:t.icon.dynamicLayoutVertexArray;x.clear();const v=t.lineVertexArray,b=r?t.text.placedSymbolArray:t.icon.placedSymbolArray,w=i.transform.width/i.transform.height;let T=!1;for(let r=0;rMath.abs(i.x-e.x)*r?{useVertical:!0}:(t===ch.vertical?e.yi.x)?{needsFlipping:!0}:null}function ud(t,e,i,r,s,n,o,l,c,h,u){const d=i/24,p=e.lineOffsetX*d,f=e.lineOffsetY*d;let m;if(e.numGlyphs>1){const i=e.glyphStartIndex+e.numGlyphs,n=e.lineStartIndex,a=e.lineStartIndex+e.lineLength,c=cd(d,l,p,f,r,e,u,t);if(!c)return{notEnoughRoom:!0};const _=nd(c.first.point.x,c.first.point.y,o,t.getElevation).point,g=nd(c.last.point.x,c.last.point.y,o,t.getElevation).point;if(s&&!r){const t=hd(e.writingMode,_,g,h);if(t)return t}m=[c.first];for(let s=e.glyphStartIndex+1;s0?o.point:function(t,e,i,r,s,n){return dd(t,e,i,1,s,n)}(t.tileAnchorPoint,s,i,0,n,t),c=hd(e.writingMode,i,l,h);if(c)return c}const i=gd(d*l.getoffsetX(e.glyphStartIndex),p,f,r,e.segment,e.lineStartIndex,e.lineStartIndex+e.lineLength,t,u);if(!i||t.projectionCache.anyProjectionOccluded)return{notEnoughRoom:!0};m=[i]}for(const t of m)vh(c,t.point,t.angle);return{}}function dd(t,e,i,r,s,n){const a=t.add(t.sub(e)._unit()),o=void 0!==s?nd(a.x,a.y,s,n.getElevation).point:fd(a.x,a.y,n).point,l=i.sub(o);return i.add(l._mult(r/l.mag()))}function pd(t,e,i){const r=e.projectionCache;if(r.projections[t])return r.projections[t];const s=new a(e.lineVertexArray.getx(t),e.lineVertexArray.gety(t)),n=fd(s.x,s.y,e);if(n.signedDistanceFromCamera>0)return r.projections[t]=n.point,r.anyProjectionOccluded=r.anyProjectionOccluded||n.isOccluded,n.point;const o=t-i.direction;return function(t,e,i,r,s){return dd(t,e,i,r,void 0,s)}(0===i.distanceFromAnchor?e.tileAnchorPoint:new a(e.lineVertexArray.getx(o),e.lineVertexArray.gety(o)),s,i.previousVertex,i.absOffsetX-i.distanceFromAnchor+1,e)}function fd(t,e,i){const r=t+i.translation[0],s=e+i.translation[1];let n;return!i.pitchWithMap&&i.projection.useSpecialProjectionForSymbols?(n=i.projection.projectTileCoordinates(r,s,i.unwrappedTileID,i.getElevation),n.point.x=(.5*n.point.x+.5)*i.width,n.point.y=(.5*-n.point.y+.5)*i.height):(n=nd(r,s,i.labelPlaneMatrix,i.getElevation),n.isOccluded=!1),n}function md(t,e,i){return t._unit()._perp()._mult(e*i)}function _d(t,e,i,r,s,n,o,l,c){if(l.projectionCache.offsets[t])return l.projectionCache.offsets[t];const h=i.add(e);if(t+c.direction=s)return l.projectionCache.offsets[t]=h,h;const u=pd(t+c.direction,l,c),d=md(u.sub(i),o,c.direction),p=i.add(d),f=u.add(d);return l.projectionCache.offsets[t]=function(t,e,i,r){const s=e.y-t.y,n=e.x-t.x,o=r.y-i.y,l=r.x-i.x,c=o*n-l*s;if(0===c)return null;const h=(l*(t.y-i.y)-o*(t.x-i.x))/c;return new a(t.x+h*n,t.y+h*s)}(n,h,p,f)||h,l.projectionCache.offsets[t]}function gd(t,e,i,r,s,n,a,o,l){const c=r?t-e:t+e;let h=c>0?1:-1,u=0;r&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,p=h>0?n+s:n+s+1;o.projectionCache.cachedAnchorPoint?d=o.projectionCache.cachedAnchorPoint:(d=fd(o.tileAnchorPoint.x,o.tileAnchorPoint.y,o).point,o.projectionCache.cachedAnchorPoint=d);let f,m,_=d,g=d,y=0,x=0;const v=Math.abs(c),b=[];let w;for(;y+x<=v;){if(p+=h,p=a)return null;y+=x,g=_,m=f;const t={absOffsetX:v,direction:h,distanceFromAnchor:y,previousVertex:g};if(_=pd(p,o,t),0===i)b.push(g),w=_.sub(g);else{let e;const r=_.sub(g);e=0===r.mag()?md(pd(p+h,o,t).sub(_),i,h):md(r,i,h),m||(m=g.add(e)),f=_d(p,e,_,n,a,m,i,o,t),b.push(m),w=f.sub(m)}x=w.mag()}const T=w._mult((v-y)/x)._add(m||g),S=u+Math.atan2(_.y-g.y,_.x-g.x);return b.push(T),{point:T,angle:l?S:0,path:b}}const yd=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function xd(t,e){for(let i=0;i=1;t--)l.push(n.path[t]);for(let t=1;tt.signedDistanceFromCamera<=0))?[]:t.map((t=>t.point))}let m=[];if(l.length>0){const t=l[0].clone(),e=l[0].clone();for(let i=1;i=i.x&&e.x<=r.x&&t.y>=i.y&&e.y<=r.y?[l]:e.xr.x||e.yr.y?[]:function(t,e,i,r,s){const n=[];for(let o=0;o=r&&h.x>=r||(o.x>=r?o=new a(r,o.y+(r-o.x)/(h.x-o.x)*(h.y-o.y))._round():h.x>=r&&(h=new a(r,o.y+(r-o.x)/(h.x-o.x)*(h.y-o.y))._round()),o.y>=s&&h.y>=s||(o.y>=s?o=new a(o.x+(s-o.y)/(h.y-o.y)*(h.x-o.x),s)._round():h.y>=s&&(h=new a(o.x+(s-o.y)/(h.y-o.y)*(h.x-o.x),s)._round()),c&&o.equals(c[c.length-1])||(c=[o],n.push(c)),c.push(h)))))}}return n}([l],i.x,i.y,r.x,r.y)}for(const i of m){s.reset(i,.25*e);let r=0;r=s.length<=.5*e?1:Math.ceil(s.paddedLength/u)+1;for(let i=0;ind(t.x,t.y,i,e.getElevation)))}queryRenderedSymbols(t){if(0===t.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return{};const e=[];let i=1/0,r=1/0,s=-1/0,n=-1/0;for(const o of t){const t=new a(o.x+bd,o.y+bd);i=Math.min(i,t.x),r=Math.min(r,t.y),s=Math.max(s,t.x),n=Math.max(n,t.y),e.push(t)}const o=this.grid.query(i,r,s,n).concat(this.ignoredGrid.query(i,r,s,n)),l={},c={};for(const t of o){const i=t.key;void 0===l[i.bucketInstanceId]&&(l[i.bucketInstanceId]={}),l[i.bucketInstanceId][i.featureIndex]||oo(e,[new a(t.x1,t.y1),new a(t.x2,t.y1),new a(t.x2,t.y2),new a(t.x1,t.y2)])&&(l[i.bucketInstanceId][i.featureIndex]=!0,void 0===c[i.bucketInstanceId]&&(c[i.bucketInstanceId]=[]),c[i.bucketInstanceId].push(i.featureIndex))}return c}insertCollisionBox(t,e,i,r,s,n){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:r,featureIndex:s,collisionGroupID:n,overlapMode:e},t[0],t[1],t[2],t[3])}insertCollisionCircles(t,e,i,r,s,n){const a=i?this.ignoredGrid:this.grid,o={bucketInstanceId:r,featureIndex:s,collisionGroupID:n,overlapMode:e};for(let e=0;e=this.screenRightBoundary||rthis.screenBottomBoundary}isInsideGrid(t,e,i,r){return i>=0&&t=0&&ethis.projectAndGetPerspectiveRatio(i,t.x,t.y,r,c)));A=t.some((t=>!t.isOccluded)),I=t.map((t=>t.point))}else A=!0;return{box:p(I),allPointsOccluded:!A}}}class Td extends a{constructor(t,e,i,r){super(t,e),this.angle=i,void 0!==r&&(this.segment=r)}clone(){return new Td(this.x,this.y,this.angle,this.segment)}}var Sd;function Id(t,e,i){return e*(to/(t.tileSize*Math.pow(2,i-t.tileID.overscaledZ)))}Ds("Anchor",Td),function(t){t[t.center=1]="center",t[t.left=2]="left",t[t.right=3]="right",t[t.top=4]="top",t[t.bottom=5]="bottom",t[t["top-left"]=6]="top-left",t[t["top-right"]=7]="top-right",t[t["bottom-left"]=8]="bottom-left",t[t["bottom-right"]=9]="bottom-right"}(Sd||(Sd={}));class Ad{constructor(t,e,i,r){this.opacity=t?Math.max(0,Math.min(1,t.opacity+(t.placed?e:-e))):r&&i?1:0,this.placed=i}isHidden(){return 0===this.opacity&&!this.placed}}class Ed{constructor(t,e,i,r,s){this.text=new Ad(t?t.text:null,e,i,s),this.icon=new Ad(t?t.icon:null,e,r,s)}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Cd{constructor(t,e,i){this.text=t,this.icon=e,this.skipFade=i}}class zd{constructor(){this.invProjMatrix=Eo(),this.viewportMatrix=Eo(),this.circles=[]}}class Pd{constructor(t,e,i,r,s){this.bucketInstanceId=t,this.featureIndex=e,this.sourceLayerIndex=i,this.bucketIndex=r,this.tileID=s}}class Md{constructor(t){this.crossSourceCollisions=t,this.maxGroupID=0,this.collisionGroups={}}get(t){if(this.crossSourceCollisions)return{ID:0,predicate:null};if(!this.collisionGroups[t]){const e=++this.maxGroupID;this.collisionGroups[t]={ID:e,predicate:t=>t.collisionGroupID===e}}return this.collisionGroups[t]}}function kd(t,e,i,r,s){const{horizontalAlign:n,verticalAlign:o}=hh(t);return new a(-(n-.5)*e+r[0]*s,-(o-.5)*i+r[1]*s)}class Dd{constructor(t,e,i,r,s,n){this.transform=t.clone(),this.terrain=i,this.collisionIndex=new wd(this.transform,e),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=r,this.retainedQueryData={},this.collisionGroups=new Md(s),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=n,n&&(n.prevPlacement=void 0),this.placedOrientations={}}_getTerrainElevationFunc(t){const e=this.terrain;return e?(i,r)=>e.getElevation(t,i,r):null}getBucketParts(t,e,i,r){const s=i.getBucket(e),n=i.latestFeatureIndex;if(!s||!n||e.id!==s.layerIds[0])return;const a=i.collisionBoxArray,o=s.layers[0].layout,l=s.layers[0].paint,c=Math.pow(2,this.transform.zoom-i.tileID.overscaledZ),h=i.tileSize/to,u=i.tileID.toUnwrapped(),d=this.transform.calculatePosMatrix(u),p="map"===o.get("text-pitch-alignment"),f="map"===o.get("text-rotation-alignment"),m=Id(i,1,this.transform.zoom),_=this.collisionIndex.mapProjection.translatePosition(this.transform,i,l.get("text-translate"),l.get("text-translate-anchor")),g=this.collisionIndex.mapProjection.translatePosition(this.transform,i,l.get("icon-translate"),l.get("icon-translate-anchor")),y=rd(d,p,f,this.transform,m);let x=null;if(p){const t=sd(d,p,f,this.transform,m);x=Mo([],this.transform.labelPlaneMatrix,t)}this.retainedQueryData[s.bucketInstanceId]=new Pd(s.bucketInstanceId,n,s.sourceLayerIndex,s.index,i.tileID);const v={bucket:s,layout:o,translationText:_,translationIcon:g,posMatrix:d,unwrappedTileID:u,textLabelPlaneMatrix:y,labelToScreenMatrix:x,scale:c,textPixelRatio:h,holdingForFade:i.holdingForFade(),collisionBoxArray:a,partiallyEvaluatedTextSize:mh(s.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(s.sourceID)};if(r)for(const e of s.sortKeyRanges){const{sortKey:i,symbolInstanceStart:r,symbolInstanceEnd:s}=e;t.push({sortKey:i,symbolInstanceStart:r,symbolInstanceEnd:s,parameters:v})}else t.push({symbolInstanceStart:0,symbolInstanceEnd:s.symbolInstances.length,parameters:v})}attemptAnchorPlacement(t,e,i,r,s,n,a,o,l,c,h,u,d,p,f,m,_,g,y){const x=Sd[t.textAnchor],v=[t.textOffset0,t.textOffset1],b=kd(x,i,r,v,s),w=this.collisionIndex.placeCollisionBox(e,u,o,l,c,a,n,m,h.predicate,y,b);if((!g||this.collisionIndex.placeCollisionBox(g,u,o,l,c,a,n,_,h.predicate,y,b).placeable)&&w.placeable){let t;if(this.prevPlacement&&this.prevPlacement.variableOffsets[d.crossTileID]&&this.prevPlacement.placements[d.crossTileID]&&this.prevPlacement.placements[d.crossTileID].text&&(t=this.prevPlacement.variableOffsets[d.crossTileID].anchor),0===d.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[d.crossTileID]={textOffset:v,width:i,height:r,anchor:x,textBoxScale:s,prevAnchor:t},this.markUsedJustification(p,x,d,f),p.allowVerticalPlacement&&(this.markUsedOrientation(p,f,d),this.placedOrientations[d.crossTileID]=f),{shift:b,placedGlyphBoxes:w}}}placeLayerBucketPart(t,e,i){const{bucket:r,layout:s,translationText:n,translationIcon:o,posMatrix:l,unwrappedTileID:c,textLabelPlaneMatrix:h,labelToScreenMatrix:u,textPixelRatio:d,holdingForFade:p,collisionBoxArray:f,partiallyEvaluatedTextSize:m,collisionGroup:_}=t.parameters,g=s.get("text-optional"),y=s.get("icon-optional"),x=_h(s,"text-overlap","text-allow-overlap"),v="always"===x,b=_h(s,"icon-overlap","icon-allow-overlap"),w="always"===b,T="map"===s.get("text-rotation-alignment"),S="map"===s.get("text-pitch-alignment"),I="none"!==s.get("icon-text-fit"),A="viewport-y"===s.get("symbol-z-order"),C=v&&(w||!r.hasIconData()||y),z=w&&(v||!r.hasTextData()||g);!r.collisionArrays&&f&&r.deserializeCollisionBoxes(f);const P=this._getTerrainElevationFunc(this.retainedQueryData[r.bucketInstanceId].tileID),M=(t,f,w)=>{var A,M;if(e[t.crossTileID])return;if(p)return void(this.placements[t.crossTileID]=new Cd(!1,!1,!1));let k=!1,D=!1,L=!0,R=null,B={box:null,placeable:!1,offscreen:null},F={box:null,placeable:!1,offscreen:null},O=null,V=null,U=null,N=0,j=0,$=0;f.textFeatureIndex?N=f.textFeatureIndex:t.useRuntimeCollisionCircles&&(N=t.featureIndex),f.verticalTextFeatureIndex&&(j=f.verticalTextFeatureIndex);const q=f.textBox;if(q){const e=e=>{let i=ch.horizontal;if(r.allowVerticalPlacement&&!e&&this.prevPlacement){const e=this.prevPlacement.placedOrientations[t.crossTileID];e&&(this.placedOrientations[t.crossTileID]=e,i=e,this.markUsedOrientation(r,i,t))}return i},s=(e,i)=>{if(r.allowVerticalPlacement&&t.numVerticalGlyphVertices>0&&f.verticalTextBox){for(const t of r.writingModes)if(t===ch.vertical?(B=i(),F=B):B=e(),B&&B.placeable)break}else B=e()},h=t.textAnchorOffsetStartIndex,u=t.textAnchorOffsetEndIndex;if(u===h){const i=(e,i)=>{const s=this.collisionIndex.placeCollisionBox(e,x,d,l,c,S,T,n,_.predicate,P);return s&&s.placeable&&(this.markUsedOrientation(r,i,t),this.placedOrientations[t.crossTileID]=i),s};s((()=>i(q,ch.horizontal)),(()=>{const e=f.verticalTextBox;return r.allowVerticalPlacement&&t.numVerticalGlyphVertices>0&&e?i(e,ch.vertical):{box:null,offscreen:null}})),e(B&&B.placeable)}else{let p=Sd[null===(M=null===(A=this.prevPlacement)||void 0===A?void 0:A.variableOffsets[t.crossTileID])||void 0===M?void 0:M.anchor];const m=(e,s,f)=>{const m=e.x2-e.x1,g=e.y2-e.y1,y=t.textBoxScale,v=I&&"never"===b?s:null;let w=null,A="never"===x?1:2,E="never";p&&A++;for(let i=0;im(q,f.iconBox,ch.horizontal)),(()=>{const e=f.verticalTextBox;return r.allowVerticalPlacement&&(!B||!B.placeable)&&t.numVerticalGlyphVertices>0&&e?m(e,f.verticalIconBox,ch.vertical):{box:null,occluded:!0,offscreen:null}})),B&&(k=B.placeable,L=B.offscreen);const g=e(B&&B.placeable);if(!k&&this.prevPlacement){const e=this.prevPlacement.variableOffsets[t.crossTileID];e&&(this.variableOffsets[t.crossTileID]=e,this.markUsedJustification(r,e.anchor,t,g))}}}if(O=B,k=O&&O.placeable,L=O&&O.offscreen,t.useRuntimeCollisionCircles){const e=r.text.placedSymbolArray.get(t.centerJustifiedTextSymbolIndex),a=fh(r.textSizeData,m,e),o=s.get("text-padding");V=this.collisionIndex.placeCollisionCircles(x,e,r.lineVertexArray,r.glyphOffsetArray,a,l,c,h,u,i,S,_.predicate,t.collisionCircleDiameter,o,n,P),V.circles.length&&V.collisionDetected&&!i&&E("Collisions detected, but collision boxes are not shown"),k=v||V.circles.length>0&&!V.collisionDetected,L=L&&V.offscreen}if(f.iconFeatureIndex&&($=f.iconFeatureIndex),f.iconBox){const t=t=>this.collisionIndex.placeCollisionBox(t,b,d,l,c,S,T,o,_.predicate,P,I&&R?R:void 0);F&&F.placeable&&f.verticalIconBox?(U=t(f.verticalIconBox),D=U.placeable):(U=t(f.iconBox),D=U.placeable),L=L&&U.offscreen}const Z=g||0===t.numHorizontalGlyphVertices&&0===t.numVerticalGlyphVertices,G=y||0===t.numIconVertices;Z||G?G?Z||(D=D&&k):k=D&&k:D=k=D&&k;const W=D&&U.placeable;if(k&&O.placeable&&this.collisionIndex.insertCollisionBox(O.box,x,s.get("text-ignore-placement"),r.bucketInstanceId,F&&F.placeable&&j?j:N,_.ID),W&&this.collisionIndex.insertCollisionBox(U.box,b,s.get("icon-ignore-placement"),r.bucketInstanceId,$,_.ID),V&&k&&this.collisionIndex.insertCollisionCircles(V.circles,x,s.get("text-ignore-placement"),r.bucketInstanceId,N,_.ID),i&&this.storeCollisionData(r.bucketInstanceId,w,f,O,U,V),0===t.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===r.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[t.crossTileID]=new Cd(k||C,D||z,L||r.justReloaded),e[t.crossTileID]=!0};if(A){if(0!==t.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const e=r.getSortedSymbolIndexes(this.transform.angle);for(let t=e.length-1;t>=0;--t){const i=e[t];M(r.symbolInstances.get(i),r.collisionArrays[i],i)}}else for(let e=t.symbolInstanceStart;e=0&&(t.text.placedSymbolArray.get(e).crossTileID=s>=0&&e!==s?0:i.crossTileID)}markUsedOrientation(t,e,i){const r=e===ch.horizontal||e===ch.horizontalOnly?e:0,s=e===ch.vertical?e:0,n=[i.leftJustifiedTextSymbolIndex,i.centerJustifiedTextSymbolIndex,i.rightJustifiedTextSymbolIndex];for(const e of n)t.text.placedSymbolArray.get(e).placedOrientation=r;i.verticalPlacedTextSymbolIndex&&(t.text.placedSymbolArray.get(i.verticalPlacedTextSymbolIndex).placedOrientation=s)}commit(t){this.commitTime=t,this.zoomAtLastRecencyCheck=this.transform.zoom;const e=this.prevPlacement;let i=!1;this.prevZoomAdjustment=e?e.zoomAdjustment(this.transform.zoom):0;const r=e?e.symbolFadeChange(t):1,s=e?e.opacities:{},n=e?e.variableOffsets:{},a=e?e.placedOrientations:{};for(const t in this.placements){const e=this.placements[t],n=s[t];n?(this.opacities[t]=new Ed(n,r,e.text,e.icon),i=i||e.text!==n.text.placed||e.icon!==n.icon.placed):(this.opacities[t]=new Ed(null,r,e.text,e.icon,e.skipFade),i=i||e.text||e.icon)}for(const t in s){const e=s[t];if(!this.opacities[t]){const s=new Ed(e,r,!1,!1);s.isHidden()||(this.opacities[t]=s,i=i||e.text.placed||e.icon.placed)}}for(const t in n)this.variableOffsets[t]||!this.opacities[t]||this.opacities[t].isHidden()||(this.variableOffsets[t]=n[t]);for(const t in a)this.placedOrientations[t]||!this.opacities[t]||this.opacities[t].isHidden()||(this.placedOrientations[t]=a[t]);if(e&&void 0===e.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=t:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=e?e.lastPlacementChangeTime:t)}updateLayerOpacities(t,e){const i={};for(const r of e){const e=r.getBucket(t);e&&r.latestFeatureIndex&&t.id===e.layerIds[0]&&this.updateBucketOpacities(e,r.tileID,i,r.collisionBoxArray)}}updateBucketOpacities(t,e,i,r){t.hasTextData()&&(t.text.opacityVertexArray.clear(),t.text.hasVisibleVertices=!1),t.hasIconData()&&(t.icon.opacityVertexArray.clear(),t.icon.hasVisibleVertices=!1),t.hasIconCollisionBoxData()&&t.iconCollisionBox.collisionVertexArray.clear(),t.hasTextCollisionBoxData()&&t.textCollisionBox.collisionVertexArray.clear();const s=t.layers[0],n=s.layout,o=new Ed(null,0,!1,!1,!0),l=n.get("text-allow-overlap"),c=n.get("icon-allow-overlap"),h=s._unevaluatedLayout.hasValue("text-variable-anchor")||s._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===n.get("text-rotation-alignment"),d="map"===n.get("text-pitch-alignment"),p="none"!==n.get("icon-text-fit"),f=new Ed(null,0,l&&(c||!t.hasIconData()||n.get("icon-optional")),c&&(l||!t.hasTextData()||n.get("text-optional")),!0);!t.collisionArrays&&r&&(t.hasIconCollisionBoxData()||t.hasTextCollisionBoxData())&&t.deserializeCollisionBoxes(r);const m=(t,e,i)=>{for(let r=0;r0,y=this.placedOrientations[r.crossTileID],x=y===ch.vertical,v=y===ch.horizontal||y===ch.horizontalOnly;if(s>0||n>0){const e=jd(c.text);m(t.text,s,x?$d:e),m(t.text,n,v?$d:e);const i=c.text.isHidden();[r.rightJustifiedTextSymbolIndex,r.centerJustifiedTextSymbolIndex,r.leftJustifiedTextSymbolIndex].forEach((e=>{e>=0&&(t.text.placedSymbolArray.get(e).hidden=i||x?1:0)})),r.verticalPlacedTextSymbolIndex>=0&&(t.text.placedSymbolArray.get(r.verticalPlacedTextSymbolIndex).hidden=i||v?1:0);const a=this.variableOffsets[r.crossTileID];a&&this.markUsedJustification(t,a.anchor,r,y);const o=this.placedOrientations[r.crossTileID];o&&(this.markUsedJustification(t,"left",r,o),this.markUsedOrientation(t,o,r))}if(g){const e=jd(c.icon),i=!(p&&r.verticalPlacedIconSymbolIndex&&x);r.placedIconSymbolIndex>=0&&(m(t.icon,r.numIconVertices,i?e:$d),t.icon.placedSymbolArray.get(r.placedIconSymbolIndex).hidden=c.icon.isHidden()),r.verticalPlacedIconSymbolIndex>=0&&(m(t.icon,r.numVerticalIconVertices,i?$d:e),t.icon.placedSymbolArray.get(r.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden())}const b=_&&_.has(e)?_.get(e):{text:null,icon:null};if(t.hasIconCollisionBoxData()||t.hasTextCollisionBoxData()){const i=t.collisionArrays[e];if(i){let e=new a(0,0);if(i.textBox||i.verticalTextBox){let r=!0;if(h){const t=this.variableOffsets[l];t?(e=kd(t.anchor,t.width,t.height,t.textOffset,t.textBoxScale),u&&e._rotate(d?this.transform.angle:-this.transform.angle)):r=!1}if(i.textBox||i.verticalTextBox){let s;i.textBox&&(s=x),i.verticalTextBox&&(s=v),Ld(t.textCollisionBox.collisionVertexArray,c.text.placed,!r||s,b.text,e.x,e.y)}}if(i.iconBox||i.verticalIconBox){const r=Boolean(!v&&i.verticalIconBox);let s;i.iconBox&&(s=r),i.verticalIconBox&&(s=!r),Ld(t.iconCollisionBox.collisionVertexArray,c.icon.placed,s,b.icon,p?e.x:0,p?e.y:0)}}}}if(t.sortFeatures(this.transform.angle),this.retainedQueryData[t.bucketInstanceId]&&(this.retainedQueryData[t.bucketInstanceId].featureSortOrder=t.featureSortOrder),t.hasTextData()&&t.text.opacityVertexBuffer&&t.text.opacityVertexBuffer.updateData(t.text.opacityVertexArray),t.hasIconData()&&t.icon.opacityVertexBuffer&&t.icon.opacityVertexBuffer.updateData(t.icon.opacityVertexArray),t.hasIconCollisionBoxData()&&t.iconCollisionBox.collisionVertexBuffer&&t.iconCollisionBox.collisionVertexBuffer.updateData(t.iconCollisionBox.collisionVertexArray),t.hasTextCollisionBoxData()&&t.textCollisionBox.collisionVertexBuffer&&t.textCollisionBox.collisionVertexBuffer.updateData(t.textCollisionBox.collisionVertexArray),t.text.opacityVertexArray.length!==t.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${t.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${t.text.layoutVertexArray.length}) / 4`);if(t.icon.opacityVertexArray.length!==t.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${t.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${t.icon.layoutVertexArray.length}) / 4`);if(t.bucketInstanceId in this.collisionCircleArrays){const e=this.collisionCircleArrays[t.bucketInstanceId];t.placementInvProjMatrix=e.invProjMatrix,t.placementViewportMatrix=e.viewportMatrix,t.collisionCircleArray=e.circles,delete this.collisionCircleArrays[t.bucketInstanceId]}}symbolFadeChange(t){return 0===this.fadeDuration?1:(t-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(t){return Math.max(0,(this.transform.zoom-t)/1.5)}hasTransitions(t){return this.stale||t-this.lastPlacementChangeTimet}setStale(){this.stale=!0}}function Ld(t,e,i,r,s,n){r&&0!==r.length||(r=[0,0,0,0]);const a=r[0]-bd,o=r[1]-bd,l=r[2]-bd,c=r[3]-bd;t.emplaceBack(e?1:0,i?1:0,s||0,n||0,a,o),t.emplaceBack(e?1:0,i?1:0,s||0,n||0,l,o),t.emplaceBack(e?1:0,i?1:0,s||0,n||0,l,c),t.emplaceBack(e?1:0,i?1:0,s||0,n||0,a,c)}const Rd=Math.pow(2,25),Bd=Math.pow(2,24),Fd=Math.pow(2,17),Od=Math.pow(2,16),Vd=Math.pow(2,9),Ud=Math.pow(2,8),Nd=Math.pow(2,1);function jd(t){if(0===t.opacity&&!t.placed)return 0;if(1===t.opacity&&t.placed)return 4294967295;const e=t.placed?1:0,i=Math.floor(127*t.opacity);return i*Rd+e*Bd+i*Fd+e*Od+i*Vd+e*Ud+i*Nd+e}const $d=0;function qd(){return{isOccluded:(t,e,i)=>!1,getPitchedTextCorrection:(t,e,i)=>1,get useSpecialProjectionForSymbols(){return!1},projectTileCoordinates(t,e,i,r){throw new Error("Not implemented.")},translatePosition:(t,e,i,r)=>function(t,e,i,r,s=!1){if(!i[0]&&!i[1])return[0,0];const n=s?"map"===r?t.angle:0:"viewport"===r?-t.angle:0;if(n){const t=Math.sin(n),e=Math.cos(n);i=[i[0]*e-i[1]*t,i[0]*t+i[1]*e]}return[s?i[0]:Id(e,i[0],t.zoom),s?i[1]:Id(e,i[1],t.zoom)]}(t,e,i,r),getCircleRadiusCorrection:t=>1}}class Zd{constructor(t){this._sortAcrossTiles="viewport-y"!==t.layout.get("symbol-z-order")&&!t.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[]}continuePlacement(t,e,i,r,s){const n=this._bucketParts;for(;this._currentTileIndext.sortKey-e.sortKey)));this._currentPartIndex!this._forceFullPlacement&&F.now()-r>2;for(;this._currentPlacementIndex>=0;){const r=e[t[this._currentPlacementIndex]],n=this.placement.collisionIndex.transform.zoom;if("symbol"===r.type&&(!r.minzoom||r.minzoom<=n)&&(!r.maxzoom||r.maxzoom>n)){if(this._inProgressLayer||(this._inProgressLayer=new Zd(r)),this._inProgressLayer.continuePlacement(i[r.source],this.placement,this._showCollisionBoxes,r,s))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._done=!0}commit(t){return this.placement.commit(t),this.placement}}const Wd=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class Hd{static from(t){if(!(t instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[e,i]=new Uint8Array(t,0,2);if(219!==e)throw new Error("Data does not appear to be in a KDBush format.");const r=i>>4;if(1!==r)throw new Error(`Got v${r} data when expected v1.`);const s=Wd[15&i];if(!s)throw new Error("Unrecognized array type.");const[n]=new Uint16Array(t,2,1),[a]=new Uint32Array(t,4,1);return new Hd(a,n,s,t)}constructor(t,e=64,i=Float64Array,r){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=i,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const s=Wd.indexOf(this.ArrayType),n=2*t*this.ArrayType.BYTES_PER_ELEMENT,a=t*this.IndexArrayType.BYTES_PER_ELEMENT,o=(8-a%8)%8;if(s<0)throw new Error(`Unexpected typed array class: ${i}.`);r&&r instanceof ArrayBuffer?(this.data=r,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=2*t,this._finished=!0):(this.data=new ArrayBuffer(8+n+a+o),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+s]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t)}add(t,e){const i=this._pos>>1;return this.ids[i]=i,this.coords[this._pos++]=t,this.coords[this._pos++]=e,i}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return Xd(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,e,i,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:s,coords:n,nodeSize:a}=this,o=[0,s.length-1,0],l=[];for(;o.length;){const c=o.pop()||0,h=o.pop()||0,u=o.pop()||0;if(h-u<=a){for(let a=u;a<=h;a++){const o=n[2*a],c=n[2*a+1];o>=t&&o<=i&&c>=e&&c<=r&&l.push(s[a])}continue}const d=u+h>>1,p=n[2*d],f=n[2*d+1];p>=t&&p<=i&&f>=e&&f<=r&&l.push(s[d]),(0===c?t<=p:e<=f)&&(o.push(u),o.push(d-1),o.push(1-c)),(0===c?i>=p:r>=f)&&(o.push(d+1),o.push(h),o.push(1-c))}return l}within(t,e,i){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:r,coords:s,nodeSize:n}=this,a=[0,r.length-1,0],o=[],l=i*i;for(;a.length;){const c=a.pop()||0,h=a.pop()||0,u=a.pop()||0;if(h-u<=n){for(let i=u;i<=h;i++)Qd(s[2*i],s[2*i+1],t,e)<=l&&o.push(r[i]);continue}const d=u+h>>1,p=s[2*d],f=s[2*d+1];Qd(p,f,t,e)<=l&&o.push(r[d]),(0===c?t-i<=p:e-i<=f)&&(a.push(u),a.push(d-1),a.push(1-c)),(0===c?t+i>=p:e+i>=f)&&(a.push(d+1),a.push(h),a.push(1-c))}return o}}function Xd(t,e,i,r,s,n){if(s-r<=i)return;const a=r+s>>1;Kd(t,e,a,r,s,n),Xd(t,e,i,r,a-1,1-n),Xd(t,e,i,a+1,s,1-n)}function Kd(t,e,i,r,s,n){for(;s>r;){if(s-r>600){const a=s-r+1,o=i-r+1,l=Math.log(a),c=.5*Math.exp(2*l/3),h=.5*Math.sqrt(l*c*(a-c)/a)*(o-a/2<0?-1:1);Kd(t,e,i,Math.max(r,Math.floor(i-o*c/a+h)),Math.min(s,Math.floor(i+(a-o)*c/a+h)),n)}const a=e[2*i+n];let o=r,l=s;for(Yd(t,e,r,i),e[2*s+n]>a&&Yd(t,e,r,s);oa;)l--}e[2*r+n]===a?Yd(t,e,r,l):(l++,Yd(t,e,l,s)),l<=i&&(r=l+1),i<=l&&(s=l-1)}}function Yd(t,e,i,r){Jd(t,i,r),Jd(e,2*i,2*r),Jd(e,2*i+1,2*r+1)}function Jd(t,e,i){const r=t[e];t[e]=t[i],t[i]=r}function Qd(t,e,i,r){const s=t-i,n=e-r;return s*s+n*n}const tp=512/to/2;class ep{constructor(t,e,i){this.tileID=t,this.bucketInstanceId=i,this._symbolsByKey={};const r=new Map;for(let t=0;t({x:Math.floor(t.anchorX*tp),y:Math.floor(t.anchorY*tp)}))),crossTileIDs:e.map((t=>t.crossTileID))};if(i.positions.length>128){const t=new Hd(i.positions.length,16,Uint16Array);for(const{x:e,y:r}of i.positions)t.add(e,r);t.finish(),delete i.positions,i.index=t}this._symbolsByKey[t]=i}}getScaledCoordinates(t,e){const{x:i,y:r,z:s}=this.tileID.canonical,{x:n,y:a,z:o}=e.canonical,l=tp/Math.pow(2,o-s),c=(a*to+t.anchorY)*l,h=r*to*tp;return{x:Math.floor((n*to+t.anchorX)*l-i*to*tp),y:Math.floor(c-h)}}findMatches(t,e,i){const r=this.tileID.canonical.zt))}}class ip{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class rp{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(t){const e=Math.round((t-this.lng)/360);if(0!==e)for(const t in this.indexes){const i=this.indexes[t],r={};for(const t in i){const s=i[t];s.tileID=s.tileID.unwrapTo(s.tileID.wrap+e),r[s.tileID.key]=s}this.indexes[t]=r}this.lng=t}addBucket(t,e,i){if(this.indexes[t.overscaledZ]&&this.indexes[t.overscaledZ][t.key]){if(this.indexes[t.overscaledZ][t.key].bucketInstanceId===e.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(t.overscaledZ,this.indexes[t.overscaledZ][t.key])}for(let t=0;tt.overscaledZ)for(const i in s){const n=s[i];n.tileID.isChildOf(t)&&n.findMatches(e.symbolInstances,t,r)}else{const n=s[t.scaledTo(Number(i)).key];n&&n.findMatches(e.symbolInstances,t,r)}}for(let t=0;t{e[t]=!0}));for(const t in this.layerIndexes)e[t]||delete this.layerIndexes[t]}}const np=(t,e)=>Ps(t,e&&e.filter((t=>"source.canvas"!==t.identifier))),ap=function(){const t={},e=at.$version;for(const i in at.$root){const r=at.$root[i];if(r.required){let s=null;s="version"===i?e:"array"===r.type?[]:{},null!=s&&(t[i]=s)}}return t}();class op extends nt{constructor(t,e={}){super(),this._rtlPluginLoaded=()=>{for(const t in this.sourceCaches){const e=this.sourceCaches[t].getSource().type;"vector"!==e&&"geojson"!==e||this.sourceCaches[t].reload()}},this.map=t,this.dispatcher=new ou(au(),t._getMapId()),this.dispatcher.registerMessageHandler("GG",((t,e)=>this.getGlyphs(t,e))),this.dispatcher.registerMessageHandler("GI",((t,e)=>this.getImages(t,e))),this.imageManager=new jh,this.imageManager.setEventedParent(this),this.glyphManager=new Gh(t._requestManager,e.localIdeographFontFamily),this.lineAtlas=new Jh(256,512),this.crossTileSymbolIndex=new sp,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new Vs,this._loaded=!1,this._availableImages=[],this._resetUpdates(),this.dispatcher.broadcast("SR",$()),Wu().on(qu,this._rtlPluginLoaded),this.on("data",(t=>{if("source"!==t.dataType||"metadata"!==t.sourceDataType)return;const e=this.sourceCaches[t.sourceId];if(!e)return;const i=e.getSource();if(i&&i.vectorLayerIds)for(const t in this._layers){const e=this._layers[t];e.source===i.id&&this._validateLayer(e)}}))}loadURL(t,e={},i){this.fire(new rt("dataloading",{dataType:"style"})),e.validate="boolean"!=typeof e.validate||e.validate;const r=this.map._requestManager.transformRequest(t,"Style");this._loadStyleRequest=new AbortController;const s=this._loadStyleRequest;Z(r,this._loadStyleRequest).then((t=>{this._loadStyleRequest=null,this._load(t.data,e,i)})).catch((t=>{this._loadStyleRequest=null,t&&!s.signal.aborted&&this.fire(new st(t))}))}loadJSON(t,e={},i){this.fire(new rt("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,F.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,e.validate=!1!==e.validate,this._load(t,e,i)})).catch((()=>{}))}loadEmpty(){this.fire(new rt("dataloading",{dataType:"style"})),this._load(ap,{validate:!1})}_load(t,e,i){var r;const s=e.transformStyle?e.transformStyle(i,t):t;if(!e.validate||!np(this,Is(s))){this._loaded=!0,this.stylesheet=s;for(const t in s.sources)this.addSource(t,s.sources[t],{validate:!1});s.sprite?this._loadSprite(s.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(s.glyphs),this._createLayers(),this.light=new Xh(this.stylesheet.light),this.sky=new Yh(this.stylesheet.sky),this.map.setTerrain(null!==(r=this.stylesheet.terrain)&&void 0!==r?r:null),this.fire(new rt("data",{dataType:"style"})),this.fire(new rt("style.load"))}}_createLayers(){const t=ct(this.stylesheet.layers);this.dispatcher.broadcast("SL",t),this._order=t.map((t=>t.id)),this._layers={},this._serializedLayers=null;for(const e of t){const t=Fh(e);t.setEventedParent(this,{layer:{id:e.id}}),this._layers[e.id]=t}}_loadSprite(t,e=!1,r=void 0){let s;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(t,e,r,s){return i(this,void 0,void 0,(function*(){const n=Oh(t),a=r>1?"@2x":"",o={},l={};for(const{id:t,url:i}of n){const r=e.transformRequest(Vh(i,a,".json"),"SpriteJSON");o[t]=Z(r,s);const n=e.transformRequest(Vh(i,a,".png"),"SpriteImage");l[t]=Q.getImage(n,s)}return yield Promise.all([...Object.values(o),...Object.values(l)]),function(t,e){return i(this,void 0,void 0,(function*(){const i={};for(const r in t){i[r]={};const s=F.getImageCanvasContext((yield e[r]).data),n=(yield t[r]).data;for(const t in n){const{width:e,height:a,x:o,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:p,textFitWidth:f,textFitHeight:m}=n[t];i[r][t]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:p,textFitWidth:f,textFitHeight:m,spriteData:{width:e,height:a,x:o,y:l,context:s}}}}return i}))}(o,l)}))}(t,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((t=>{if(this._spriteRequest=null,t)for(const i in t){this._spritesImagesIds[i]=[];const r=this._spritesImagesIds[i]?this._spritesImagesIds[i].filter((e=>!(e in t))):[];for(const t of r)this.imageManager.removeImage(t),this._changedImages[t]=!0;for(const r in t[i]){const s="default"===i?r:`${i}:${r}`;this._spritesImagesIds[i].push(s),s in this.imageManager.images?this.imageManager.updateImage(s,t[i][r],!1):this.imageManager.addImage(s,t[i][r]),e&&(this._changedImages[s]=!0)}}})).catch((t=>{this._spriteRequest=null,s=t,this.fire(new st(s))})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),e&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new rt("data",{dataType:"style"})),r&&r(s)}))}_unloadSprite(){for(const t of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(t),this._changedImages[t]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new rt("data",{dataType:"style"}))}_validateLayer(t){const e=this.sourceCaches[t.source];if(!e)return;const i=t.sourceLayer;if(!i)return;const r=e.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(i))&&this.fire(new st(new Error(`Source layer "${i}" does not exist on source "${r.id}" as specified by style layer "${t.id}".`)))}loaded(){if(!this._loaded)return!1;if(Object.keys(this._updatedSources).length)return!1;for(const t in this.sourceCaches)if(!this.sourceCaches[t].loaded())return!1;return!!this.imageManager.isLoaded()}_serializeByIds(t,e=!1){const i=this._serializedAllLayers();if(!t||0===t.length)return Object.values(e?I(i):i);const r=[];for(const s of t)if(i[s]){const t=e?I(i[s]):i[s];r.push(t)}return r}_serializedAllLayers(){let t=this._serializedLayers;if(t)return t;t=this._serializedLayers={};const e=Object.keys(this._layers);for(const i of e){const e=this._layers[i];"custom"!==e.type&&(t[i]=e.serialize())}return t}hasTransitions(){if(this.light&&this.light.hasTransition())return!0;if(this.sky&&this.sky.hasTransition())return!0;for(const t in this.sourceCaches)if(this.sourceCaches[t].hasTransition())return!0;for(const t in this._layers)if(this._layers[t].hasTransition())return!0;return!1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(t){if(!this._loaded)return;const e=this._changed;if(e){const e=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(e.length||i.length)&&this._updateWorkerLayers(e,i);for(const t in this._updatedSources){const e=this._updatedSources[t];if("reload"===e)this._reloadSource(t);else{if("clear"!==e)throw new Error(`Invalid action ${e}`);this._clearSource(t)}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const e in this._updatedPaintProps)this._layers[e].updateTransitions(t);this.light.updateTransitions(t),this.sky.updateTransitions(t),this._resetUpdates()}const i={};for(const t in this.sourceCaches){const e=this.sourceCaches[t];i[t]=e.used,e.used=!1}for(const e of this._order){const i=this._layers[e];i.recalculate(t,this._availableImages),!i.isHidden(t.zoom)&&i.source&&(this.sourceCaches[i.source].used=!0)}for(const t in i){const e=this.sourceCaches[t];!!i[t]!=!!e.used&&e.fire(new rt("data",{sourceDataType:"visibility",dataType:"source",sourceId:t}))}this.light.recalculate(t),this.sky.recalculate(t),this.z=t.zoom,e&&this.fire(new rt("data",{dataType:"style"}))}_updateTilesForChangedImages(){const t=Object.keys(this._changedImages);if(t.length){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["icons","patterns"],t);this._changedImages={}}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1}}_updateWorkerLayers(t,e){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(t,!1),removedIds:e})}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1}setState(t,e={}){var i;this._checkLoaded();const r=this.serialize();if(t=e.transformStyle?e.transformStyle(r,t):t,(null===(i=e.validate)||void 0===i||i)&&np(this,Is(t)))return!1;(t=I(t)).layers=ct(t.layers);const s=function(t,e){if(!t)return[{command:"setStyle",args:[e]}];let i=[];try{if(!ht(t.version,e.version))return[{command:"setStyle",args:[e]}];ht(t.center,e.center)||i.push({command:"setCenter",args:[e.center]}),ht(t.zoom,e.zoom)||i.push({command:"setZoom",args:[e.zoom]}),ht(t.bearing,e.bearing)||i.push({command:"setBearing",args:[e.bearing]}),ht(t.pitch,e.pitch)||i.push({command:"setPitch",args:[e.pitch]}),ht(t.sprite,e.sprite)||i.push({command:"setSprite",args:[e.sprite]}),ht(t.glyphs,e.glyphs)||i.push({command:"setGlyphs",args:[e.glyphs]}),ht(t.transition,e.transition)||i.push({command:"setTransition",args:[e.transition]}),ht(t.light,e.light)||i.push({command:"setLight",args:[e.light]}),ht(t.terrain,e.terrain)||i.push({command:"setTerrain",args:[e.terrain]}),ht(t.sky,e.sky)||i.push({command:"setSky",args:[e.sky]}),ht(t.projection,e.projection)||i.push({command:"setProjection",args:[e.projection]});const r={},s=[];!function(t,e,i,r){let s;for(s in e=e||{},t=t||{})Object.prototype.hasOwnProperty.call(t,s)&&(Object.prototype.hasOwnProperty.call(e,s)||pt(s,i,r));for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&(Object.prototype.hasOwnProperty.call(t,s)?ht(t[s],e[s])||("geojson"===t[s].type&&"geojson"===e[s].type&&mt(t,e,s)?ut(i,{command:"setGeoJSONSourceData",args:[s,e[s].data]}):ft(s,e,i,r)):dt(s,e,i))}(t.sources,e.sources,s,r);const n=[];t.layers&&t.layers.forEach((t=>{"source"in t&&r[t.source]?i.push({command:"removeLayer",args:[t.id]}):n.push(t)})),i=i.concat(s),function(t,e,i){e=e||[];const r=(t=t||[]).map(gt),s=e.map(gt),n=t.reduce(yt,{}),a=e.reduce(yt,{}),o=r.slice(),l=Object.create(null);let c,h,u,d,p;for(let t=0,e=0;t0)throw new Error(`Unimplemented: ${n.unimplemented.join(", ")}.`);if(0===n.operations.length)return!1;for(const t of n.operations)t();return this.stylesheet=t,this._serializedLayers=null,!0}_getOperationsToPerform(t){const e=[],i=[];for(const r of t)switch(r.command){case"setCenter":case"setZoom":case"setBearing":case"setPitch":continue;case"addLayer":e.push((()=>this.addLayer.apply(this,r.args)));break;case"removeLayer":e.push((()=>this.removeLayer.apply(this,r.args)));break;case"setPaintProperty":e.push((()=>this.setPaintProperty.apply(this,r.args)));break;case"setLayoutProperty":e.push((()=>this.setLayoutProperty.apply(this,r.args)));break;case"setFilter":e.push((()=>this.setFilter.apply(this,r.args)));break;case"addSource":e.push((()=>this.addSource.apply(this,r.args)));break;case"removeSource":e.push((()=>this.removeSource.apply(this,r.args)));break;case"setLayerZoomRange":e.push((()=>this.setLayerZoomRange.apply(this,r.args)));break;case"setLight":e.push((()=>this.setLight.apply(this,r.args)));break;case"setGeoJSONSourceData":e.push((()=>this.setGeoJSONSourceData.apply(this,r.args)));break;case"setGlyphs":e.push((()=>this.setGlyphs.apply(this,r.args)));break;case"setSprite":e.push((()=>this.setSprite.apply(this,r.args)));break;case"setSky":e.push((()=>this.setSky.apply(this,r.args)));break;case"setTerrain":e.push((()=>this.map.setTerrain.apply(this,r.args)));break;case"setTransition":e.push((()=>{}));break;default:i.push(r.command)}return{operations:e,unimplemented:i}}addImage(t,e){if(this.getImage(t))return this.fire(new st(new Error(`An image named "${t}" already exists.`)));this.imageManager.addImage(t,e),this._afterImageUpdated(t)}updateImage(t,e){this.imageManager.updateImage(t,e)}getImage(t){return this.imageManager.getImage(t)}removeImage(t){if(!this.getImage(t))return this.fire(new st(new Error(`An image named "${t}" does not exist.`)));this.imageManager.removeImage(t),this._afterImageUpdated(t)}_afterImageUpdated(t){this._availableImages=this.imageManager.listImages(),this._changedImages[t]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new rt("data",{dataType:"style"}))}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(t,e,i={}){if(this._checkLoaded(),void 0!==this.sourceCaches[t])throw new Error(`Source "${t}" already exists.`);if(!e.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(e).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(e.type)>=0&&this._validate(Is.source,`sources.${t}`,e,null,i))return;this.map&&this.map._collectResourceTiming&&(e.collectResourceTiming=!0);const r=this.sourceCaches[t]=new Yu(t,e,this.dispatcher);r.style=this,r.setEventedParent(this,(()=>({isSourceLoaded:r.loaded(),source:r.serialize(),sourceId:t}))),r.onAdd(this.map),this._changed=!0}removeSource(t){if(this._checkLoaded(),void 0===this.sourceCaches[t])throw new Error("There is no source with this ID");for(const e in this._layers)if(this._layers[e].source===t)return this.fire(new st(new Error(`Source "${t}" cannot be removed while layer "${e}" is using it.`)));const e=this.sourceCaches[t];delete this.sourceCaches[t],delete this._updatedSources[t],e.fire(new rt("data",{sourceDataType:"metadata",dataType:"source",sourceId:t})),e.setEventedParent(null),e.onRemove(this.map),this._changed=!0}setGeoJSONSourceData(t,e){if(this._checkLoaded(),void 0===this.sourceCaches[t])throw new Error(`There is no source with this ID=${t}`);const i=this.sourceCaches[t].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(e),this._changed=!0}getSource(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()}addLayer(t,e,i={}){this._checkLoaded();const r=t.id;if(this.getLayer(r))return void this.fire(new st(new Error(`Layer "${r}" already exists on this map.`)));let s;if("custom"===t.type){if(np(this,function(t){const e=[],i=t.id;return void 0===i&&e.push({message:`layers.${i}: missing required property "id"`}),void 0===t.render&&e.push({message:`layers.${i}: missing required method "render"`}),t.renderingMode&&"2d"!==t.renderingMode&&"3d"!==t.renderingMode&&e.push({message:`layers.${i}: property "renderingMode" must be either "2d" or "3d"`}),e}(t)))return;s=Fh(t)}else{if("source"in t&&"object"==typeof t.source&&(this.addSource(r,t.source),t=y(t=I(t),{source:r})),this._validate(Is.layer,`layers.${r}`,t,{arrayIndex:-1},i))return;s=Fh(t),this._validateLayer(s),s.setEventedParent(this,{layer:{id:r}})}const n=e?this._order.indexOf(e):this._order.length;if(e&&-1===n)this.fire(new st(new Error(`Cannot add layer "${r}" before non-existing layer "${e}".`)));else{if(this._order.splice(n,0,r),this._layerOrderChanged=!0,this._layers[r]=s,this._removedLayers[r]&&s.source&&"custom"!==s.type){const t=this._removedLayers[r];delete this._removedLayers[r],t.type!==s.type?this._updatedSources[s.source]="clear":(this._updatedSources[s.source]="reload",this.sourceCaches[s.source].pause())}this._updateLayer(s),s.onAdd&&s.onAdd(this.map)}}moveLayer(t,e){if(this._checkLoaded(),this._changed=!0,!this._layers[t])return void this.fire(new st(new Error(`The layer '${t}' does not exist in the map's style and cannot be moved.`)));if(t===e)return;const i=this._order.indexOf(t);this._order.splice(i,1);const r=e?this._order.indexOf(e):this._order.length;e&&-1===r?this.fire(new st(new Error(`Cannot move layer "${t}" before non-existing layer "${e}".`))):(this._order.splice(r,0,t),this._layerOrderChanged=!0)}removeLayer(t){this._checkLoaded();const e=this._layers[t];if(!e)return void this.fire(new st(new Error(`Cannot remove non-existing layer "${t}".`)));e.setEventedParent(null);const i=this._order.indexOf(t);this._order.splice(i,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[t]=e,delete this._layers[t],this._serializedLayers&&delete this._serializedLayers[t],delete this._updatedLayers[t],delete this._updatedPaintProps[t],e.onRemove&&e.onRemove(this.map)}getLayer(t){return this._layers[t]}getLayersOrder(){return[...this._order]}hasLayer(t){return t in this._layers}setLayerZoomRange(t,e,i){this._checkLoaded();const r=this.getLayer(t);r?r.minzoom===e&&r.maxzoom===i||(null!=e&&(r.minzoom=e),null!=i&&(r.maxzoom=i),this._updateLayer(r)):this.fire(new st(new Error(`Cannot set the zoom range of non-existing layer "${t}".`)))}setFilter(t,e,i={}){this._checkLoaded();const r=this.getLayer(t);if(r){if(!S(r.filter,e))return null==e?(r.filter=void 0,void this._updateLayer(r)):void(this._validate(Is.filter,`layers.${r.id}.filter`,e,null,i)||(r.filter=I(e),this._updateLayer(r)))}else this.fire(new st(new Error(`Cannot filter non-existing layer "${t}".`)))}getFilter(t){return I(this.getLayer(t).filter)}setLayoutProperty(t,e,i,r={}){this._checkLoaded();const s=this.getLayer(t);s?S(s.getLayoutProperty(e),i)||(s.setLayoutProperty(e,i,r),this._updateLayer(s)):this.fire(new st(new Error(`Cannot style non-existing layer "${t}".`)))}getLayoutProperty(t,e){const i=this.getLayer(t);if(i)return i.getLayoutProperty(e);this.fire(new st(new Error(`Cannot get style of non-existing layer "${t}".`)))}setPaintProperty(t,e,i,r={}){this._checkLoaded();const s=this.getLayer(t);s?S(s.getPaintProperty(e),i)||(s.setPaintProperty(e,i,r)&&this._updateLayer(s),this._changed=!0,this._updatedPaintProps[t]=!0,this._serializedLayers=null):this.fire(new st(new Error(`Cannot style non-existing layer "${t}".`)))}getPaintProperty(t,e){return this.getLayer(t).getPaintProperty(e)}setFeatureState(t,e){this._checkLoaded();const i=t.source,r=t.sourceLayer,s=this.sourceCaches[i];if(void 0===s)return void this.fire(new st(new Error(`The source '${i}' does not exist in the map's style.`)));const n=s.getSource().type;"geojson"===n&&r?this.fire(new st(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==n||r?(void 0===t.id&&this.fire(new st(new Error("The feature id parameter must be provided."))),s.setFeatureState(r,t.id,e)):this.fire(new st(new Error("The sourceLayer parameter must be provided for vector source types.")))}removeFeatureState(t,e){this._checkLoaded();const i=t.source,r=this.sourceCaches[i];if(void 0===r)return void this.fire(new st(new Error(`The source '${i}' does not exist in the map's style.`)));const s=r.getSource().type,n="vector"===s?t.sourceLayer:void 0;"vector"!==s||n?e&&"string"!=typeof t.id&&"number"!=typeof t.id?this.fire(new st(new Error("A feature id is required to remove its specific state property."))):r.removeFeatureState(n,t.id,e):this.fire(new st(new Error("The sourceLayer parameter must be provided for vector source types.")))}getFeatureState(t){this._checkLoaded();const e=t.source,i=t.sourceLayer,r=this.sourceCaches[e];if(void 0!==r)return"vector"!==r.getSource().type||i?(void 0===t.id&&this.fire(new st(new Error("The feature id parameter must be provided."))),r.getFeatureState(i,t.id)):void this.fire(new st(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new st(new Error(`The source '${e}' does not exist in the map's style.`)))}getTransition(){return y({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const t=w(this.sourceCaches,(t=>t.serialize())),e=this._serializeByIds(this._order,!0),i=this.map.getTerrain()||void 0,r=this.stylesheet;return T({version:r.version,name:r.name,metadata:r.metadata,light:r.light,sky:r.sky,center:r.center,zoom:r.zoom,bearing:r.bearing,pitch:r.pitch,sprite:r.sprite,glyphs:r.glyphs,transition:r.transition,sources:t,layers:e,terrain:i},(t=>void 0!==t))}_updateLayer(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&"raster"!==this.sourceCaches[t.source].getSource().type&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._serializedLayers=null,this._changed=!0}_flattenAndSortRenderedFeatures(t){const e=t=>"fill-extrusion"===this._layers[t].type,i={},r=[];for(let s=this._order.length-1;s>=0;s--){const n=this._order[s];if(e(n)){i[n]=s;for(const e of t){const t=e[n];if(t)for(const e of t)r.push(e)}}}r.sort(((t,e)=>e.intersectionZ-t.intersectionZ));const s=[];for(let n=this._order.length-1;n>=0;n--){const a=this._order[n];if(e(a))for(let t=r.length-1;t>=0;t--){const e=r[t].feature;if(i[e.layer.id]{const r=i.featureSortOrder;if(r){const i=r.indexOf(t.featureIndex);return r.indexOf(e.featureIndex)-i}return e.featureIndex-t.featureIndex}));for(const t of s)e.push(t)}}for(const e in o)o[e].forEach((r=>{const s=r.feature,n=i[t[e].source].getFeatureState(s.layer["source-layer"],s.id);s.source=s.layer.source,s.layer["source-layer"]&&(s.sourceLayer=s.layer["source-layer"]),s.state=n}));return o}(this._layers,n,this.sourceCaches,t,e,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(s)}querySourceFeatures(t,e){e&&e.filter&&this._validate(Is.filter,"querySourceFeatures.filter",e.filter,null,e);const i=this.sourceCaches[t];return i?function(t,e){const i=t.getRenderableIds().map((e=>t.getTileByID(e))),r=[],s={};for(let t=0;tt.getTileByID(e))).sort(((t,e)=>e.tileID.overscaledZ-t.tileID.overscaledZ||(t.tileID.isLessThan(e.tileID)?-1:1)))}const r=this.crossTileSymbolIndex.addLayer(i,o[i.source],t.center.lng);n=n||r}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((s=s||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(F.now(),t.zoom))&&(this.pauseablePlacement=new Gd(t,this.map.terrain,this._order,s,e,i,r,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,o),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(F.now()),a=!0),n&&this.pauseablePlacement.placement.setStale()),a||n)for(const t of this._order){const e=this._layers[t];"symbol"===e.type&&this.placement.updateLayerOpacities(e,o[e.source])}return!this.pauseablePlacement.isDone()||this.placement.hasTransitions(F.now())}_releaseSymbolFadeTiles(){for(const t in this.sourceCaches)this.sourceCaches[t].releaseSymbolFadeTiles()}getImages(t,e){return i(this,void 0,void 0,(function*(){const t=yield this.imageManager.getImages(e.icons);this._updateTilesForChangedImages();const i=this.sourceCaches[e.source];return i&&i.setDependencies(e.tileID.key,e.type,e.icons),t}))}getGlyphs(t,e){return i(this,void 0,void 0,(function*(){const t=yield this.glyphManager.getGlyphs(e.stacks),i=this.sourceCaches[e.source];return i&&i.setDependencies(e.tileID.key,e.type,[""]),t}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(t,e={}){this._checkLoaded(),t&&this._validate(Is.glyphs,"glyphs",t,null,e)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=t,this.glyphManager.entries={},this.glyphManager.setURL(t))}addSprite(t,e,i={},r){this._checkLoaded();const s=[{id:t,url:e}],n=[...Oh(this.stylesheet.sprite),...s];this._validate(Is.sprite,"sprite",n,null,i)||(this.stylesheet.sprite=n,this._loadSprite(s,!0,r))}removeSprite(t){this._checkLoaded();const e=Oh(this.stylesheet.sprite);if(e.find((e=>e.id===t))){if(this._spritesImagesIds[t])for(const e of this._spritesImagesIds[t])this.imageManager.removeImage(e),this._changedImages[e]=!0;e.splice(e.findIndex((e=>e.id===t)),1),this.stylesheet.sprite=e.length>0?e:void 0,delete this._spritesImagesIds[t],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new rt("data",{dataType:"style"}))}else this.fire(new st(new Error(`Sprite "${t}" doesn't exists on this map.`)))}getSprite(){return Oh(this.stylesheet.sprite)}setSprite(t,e={},i){this._checkLoaded(),t&&this._validate(Is.sprite,"sprite",t,null,e)||(this.stylesheet.sprite=t,t?this._loadSprite(t,!0,i):(this._unloadSprite(),i&&i(null)))}}var lp=gn([{name:"a_pos",type:"Int16",components:2}]);const cp={prelude:hp("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\n","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture2D(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture2D(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}"),background:hp("uniform vec4 u_color;uniform float u_opacity;void main() {gl_FragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),backgroundPattern:hp("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:hp("varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);lowp float antialiasblur=v_data.z;float antialiased_blur=-max(blur,antialiasblur);float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));gl_FragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);float ele=get_elevation(circle_center);v_visibility=calculate_visibility(u_matrix*vec4(circle_center,ele,1.0));if (u_pitch_with_map) {vec2 corner_position=circle_center;if (u_scale_with_map) {corner_position+=extrude*(radius+stroke_width)*u_extrude_scale;} else {vec4 projected_center=u_matrix*vec4(circle_center,0,1);corner_position+=extrude*(radius+stroke_width)*u_extrude_scale*(projected_center.w/u_camera_to_center_distance);}gl_Position=u_matrix*vec4(corner_position,ele,1);} else {gl_Position=u_matrix*vec4(circle_center,ele,1);if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:hp("void main() {gl_FragColor=vec4(1.0);}","attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),heatmap:hp("uniform highp float u_intensity;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);gl_FragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec4 pos=vec4(floor(a_pos*0.5)+extrude,get_elevation(floor(a_pos*0.5)),1);gl_Position=u_matrix*pos;}"),heatmapTexture:hp("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:hp("varying float v_placed;varying float v_notUsed;void main() {float alpha=0.5;gl_FragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}","attribute vec2 a_anchor_pos;attribute vec2 a_placed;attribute vec2 a_box_real;uniform mat4 u_matrix;uniform vec2 u_pixel_extrude_scale;varying float v_placed;varying float v_notUsed;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:hp("varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}","attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),debug:hp("uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}","attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,get_elevation(a_pos),1);}"),fill:hp("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}"),fillOutline:hp("varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),fillOutlinePattern:hp("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),fillPattern:hp("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:hp("varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:hp("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:hp("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:hp("uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}"),line:hp("uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:hp("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,v_uv);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;attribute float a_uv_x;attribute float a_split_index;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:hp("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:hp("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:hp("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:hp("uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_tex;varying float v_fade_opacity;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:hp("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_2;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nfloat median(vec3 values) {return max(min(values.r,values.g),min(max(values.r,values.g),values.b));}float screenPxRange(float fontScale) {return fontScale*SDF_PX;}vec4 renderText(vec4 fill_color,vec4 halo_color,float opacity,float halo_width,float halo_blur,float EDGE_GAMMA,vec2 tex,float gamma_scale,float size,float fade_opacity) {float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}return color*(alpha*opacity*fade_opacity);}vec4 renderMSDFIcon(vec4 fill_color,vec4 halo_color,float opacity,float EDGE_GAMMA,vec2 tex,float gamma_scale,float size,float fade_opacity) {float fontScale=size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;vec3 s=texture2D(u_texture,tex).rgb;float sd=median(s);float dist=sd-0.5;if (u_is_halo) {color=halo_color;s=texture2D(u_texture_2,tex).rgb;sd=median(s);dist=sd-0.5;}float clampedDistance=clamp(dist*screenPxRange(fontScale)+0.5,0.0,1.0);highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,clampedDistance);return color*(alpha*opacity*fade_opacity);}void main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];gl_FragColor=u_is_text ? renderText(fill_color,halo_color,opacity,halo_width,halo_blur,EDGE_GAMMA,tex,gamma_scale,size,fade_opacity) : renderMSDFIcon(fill_color,halo_color,opacity,EDGE_GAMMA,tex,gamma_scale,size,fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_data0;varying vec3 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:hp("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec4 v_data0;varying vec4 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:hp("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;varying vec2 v_texture_pos;varying float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture2D(u_texture,v_texture_pos);if (v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);gl_FragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {gl_FragColor=surface_color;}}","attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform mat4 u_fog_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;varying float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:hp("varying float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {gl_FragColor=pack(v_depth);}","attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:hp("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;varying vec2 v_texture_pos;void main() {vec4 rgba=texture2D(u_texture,v_texture_pos);gl_FragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);}"),sky:hp("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform float u_horizon;uniform float u_sky_horizon_blend;void main() {float y=gl_FragCoord.y;if (y > u_horizon) {float blend=y-u_horizon;if (blend < u_sky_horizon_blend) {gl_FragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {gl_FragColor=u_sky_color;}}}","attribute vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function hp(t,e){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,r=e.match(/attribute ([\w]+) ([\w]+)/g),s=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),n=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=n?n.concat(s):s,o={};return{fragmentSource:t=t.replace(i,((t,e,i,r,s)=>(o[s]=!0,"define"===e?`\n#ifndef HAS_UNIFORM_u_${s}\nvarying ${i} ${r} ${s};\n#else\nuniform ${i} ${r} u_${s};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${s}\n ${i} ${r} ${s} = u_${s};\n#endif\n`))),vertexSource:e=e.replace(i,((t,e,i,r,s)=>{const n="float"===r?"vec2":"vec4",a=s.match(/color/)?"color":n;return o[s]?"define"===e?`\n#ifndef HAS_UNIFORM_u_${s}\nuniform lowp float u_${s}_t;\nattribute ${i} ${n} a_${s};\nvarying ${i} ${r} ${s};\n#else\nuniform ${i} ${r} u_${s};\n#endif\n`:"vec4"===a?`\n#ifndef HAS_UNIFORM_u_${s}\n ${s} = a_${s};\n#else\n ${i} ${r} ${s} = u_${s};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${s}\n ${s} = unpack_mix_${a}(a_${s}, u_${s}_t);\n#else\n ${i} ${r} ${s} = u_${s};\n#endif\n`:"define"===e?`\n#ifndef HAS_UNIFORM_u_${s}\nuniform lowp float u_${s}_t;\nattribute ${i} ${n} a_${s};\n#else\nuniform ${i} ${r} u_${s};\n#endif\n`:"vec4"===a?`\n#ifndef HAS_UNIFORM_u_${s}\n ${i} ${r} ${s} = a_${s};\n#else\n ${i} ${r} ${s} = u_${s};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${s}\n ${i} ${r} ${s} = unpack_mix_${a}(a_${s}, u_${s}_t);\n#else\n ${i} ${r} ${s} = u_${s};\n#endif\n`})),staticAttributes:r,staticUniforms:a}}class up{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null}bind(t,e,i,r,s,n,a,o,l){this.context=t;let c=this.boundPaintVertexBuffers.length!==r.length;for(let t=0;!c&&t({u_matrix:t,u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:r?r.properties.get("fog-color"):le.white,u_fog_ground_blend:r?r.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:r?r.calculateFogBlendOpacity(s):0,u_horizon_color:r?r.properties.get("horizon-color"):le.white,u_horizon_fog_blend:r?r.properties.get("horizon-fog-blend"):1});function pp(t){const e=[];for(let i=0;i({u_depth:new Ba(t,e.u_depth),u_terrain:new Ba(t,e.u_terrain),u_terrain_dim:new Fa(t,e.u_terrain_dim),u_terrain_matrix:new $a(t,e.u_terrain_matrix),u_terrain_unpack:new Ua(t,e.u_terrain_unpack),u_terrain_exaggeration:new Fa(t,e.u_terrain_exaggeration)}))(t,v),this.binderUniforms=i?i.getUniforms(t,v):[]}draw(t,e,i,r,s,n,a,o,l,c,h,u,d,p,f,m,_,g){const y=t.gl;if(this.failedToCreate)return;if(t.program.set(this.program),t.setDepthMode(i),t.setStencilMode(r),t.setColorMode(s),t.setCullFace(n),o){t.activeTexture.set(y.TEXTURE2),y.bindTexture(y.TEXTURE_2D,o.depthTexture),t.activeTexture.set(y.TEXTURE3),y.bindTexture(y.TEXTURE_2D,o.texture);for(const t in this.terrainUniforms)this.terrainUniforms[t].set(o[t])}for(const t in this.fixedUniforms)this.fixedUniforms[t].set(a[t]);f&&f.setUniforms(t,this.binderUniforms,d,{zoom:p});let x=0;switch(e){case y.LINES:x=2;break;case y.TRIANGLES:x=3;break;case y.LINE_STRIP:x=1}for(const i of u.get()){const r=i.vaos||(i.vaos={});(r[l]||(r[l]=new up)).bind(t,this,c,f?f.getPaintVertexBuffers():[],h,i.vertexOffset,m,_,g),y.drawElements(e,i.primitiveLength*x,y.UNSIGNED_SHORT,i.primitiveOffset*x*2)}}}function mp(t,e,i){const r=1/Id(i,1,e.transform.tileZoom),s=Math.pow(2,i.tileID.overscaledZ),n=i.tileSize*Math.pow(2,e.transform.tileZoom)/s,a=n*(i.tileID.canonical.x+i.tileID.wrap*s),o=n*i.tileID.canonical.y;return{u_image:0,u_texsize:i.imageAtlasTexture.size,u_scale:[r,t.fromScale,t.toScale],u_fade:t.t,u_pixel_coord_upper:[a>>16,o>>16],u_pixel_coord_lower:[65535&a,65535&o]}}const _p=(t,e,i,r)=>{const s=e.style.light,n=s.properties.get("position"),a=[n.x,n.y,n.z],o=function(){var t=new Ao(9);return Ao!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t}();"viewport"===s.properties.get("anchor")&&function(t,e){var i=Math.sin(e),r=Math.cos(e);t[0]=r,t[1]=i,t[2]=0,t[3]=-i,t[4]=r,t[5]=0,t[6]=0,t[7]=0,t[8]=1}(o,-e.transform.angle),function(t,e,i){var r=e[0],s=e[1],n=e[2];t[0]=r*i[0]+s*i[3]+n*i[6],t[1]=r*i[1]+s*i[4]+n*i[7],t[2]=r*i[2]+s*i[5]+n*i[8]}(a,a,o);const l=s.properties.get("color");return{u_matrix:t,u_lightpos:a,u_lightintensity:s.properties.get("intensity"),u_lightcolor:[l.r,l.g,l.b],u_vertical_gradient:+i,u_opacity:r}},gp=(t,e,i,r,s,n,a)=>y(_p(t,e,i,r),mp(n,e,a),{u_height_factor:-Math.pow(2,s.overscaledZ)/a.tileSize/8}),yp=t=>({u_matrix:t}),xp=(t,e,i,r)=>y(yp(t),mp(i,e,r)),vp=(t,e)=>({u_matrix:t,u_world:e}),bp=(t,e,i,r,s)=>y(xp(t,e,i,r),{u_world:s}),wp=(t,e,i,r)=>{const s=t.transform;let n,a;if("map"===r.paint.get("circle-pitch-alignment")){const t=Id(i,1,s.zoom);n=!0,a=[t,t]}else n=!1,a=s.pixelsToGLUnits;return{u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===r.paint.get("circle-pitch-scale")),u_matrix:t.translatePosMatrix(e.posMatrix,i,r.paint.get("circle-translate"),r.paint.get("circle-translate-anchor")),u_pitch_with_map:+n,u_device_pixel_ratio:t.pixelRatio,u_extrude_scale:a}},Tp=(t,e,i)=>({u_matrix:t,u_inv_matrix:e,u_camera_to_center_distance:i.cameraToCenterDistance,u_viewport_size:[i.width,i.height]}),Sp=(t,e,i=1)=>({u_matrix:t,u_color:e,u_overlay:0,u_overlay_scale:i}),Ip=t=>({u_matrix:t}),Ap=(t,e,i,r)=>({u_matrix:t,u_extrude_scale:Id(e,1,i),u_intensity:r}),Ep=(t,e,i,r)=>{const s=Eo();Fo(s,0,t.width,t.height,0,0,1);const n=t.context.gl;return{u_matrix:s,u_world:[n.drawingBufferWidth,n.drawingBufferHeight],u_image:i,u_color_ramp:r,u_opacity:e.paint.get("heatmap-opacity")}};function Cp(t,e){const i=Math.pow(2,e.canonical.z),r=e.canonical.y;return[new wu(0,r/i).toLngLat().lat,new wu(0,(r+1)/i).toLngLat().lat]}const zp=(t,e,i,r)=>{const s=t.transform;return{u_matrix:Lp(t,e,i,r),u_ratio:1/Id(e,1,s.zoom),u_device_pixel_ratio:t.pixelRatio,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},Pp=(t,e,i,r,s)=>y(zp(t,e,i,s),{u_image:0,u_image_height:r}),Mp=(t,e,i,r,s)=>{const n=t.transform,a=Dp(e,n);return{u_matrix:Lp(t,e,i,s),u_texsize:e.imageAtlasTexture.size,u_ratio:1/Id(e,1,n.zoom),u_device_pixel_ratio:t.pixelRatio,u_image:0,u_scale:[a,r.fromScale,r.toScale],u_fade:r.t,u_units_to_pixels:[1/n.pixelsToGLUnits[0],1/n.pixelsToGLUnits[1]]}},kp=(t,e,i,r,s,n)=>{const a=t.lineAtlas,o=Dp(e,t.transform),l="round"===i.layout.get("line-cap"),c=a.getDash(r.from,l),h=a.getDash(r.to,l),u=c.width*s.fromScale,d=h.width*s.toScale;return y(zp(t,e,i,n),{u_patternscale_a:[o/u,-c.height/2],u_patternscale_b:[o/d,-h.height/2],u_sdfgamma:a.width/(256*Math.min(u,d)*t.pixelRatio)/2,u_image:0,u_tex_y_a:c.y,u_tex_y_b:h.y,u_mix:s.t})};function Dp(t,e){return 1/Id(t,1,e.tileZoom)}function Lp(t,e,i,r){return t.translatePosMatrix(r?r.posMatrix:e.tileID.posMatrix,e,i.paint.get("line-translate"),i.paint.get("line-translate-anchor"))}const Rp=(t,e,i,r,s)=>{return{u_matrix:t,u_tl_parent:e,u_scale_parent:i,u_buffer_scale:1,u_fade_t:r.mix,u_opacity:r.opacity*s.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:s.paint.get("raster-brightness-min"),u_brightness_high:s.paint.get("raster-brightness-max"),u_saturation_factor:(a=s.paint.get("raster-saturation"),a>0?1-1/(1.001-a):-a),u_contrast_factor:(n=s.paint.get("raster-contrast"),n>0?1/(1-n):1+n),u_spin_weights:Bp(s.paint.get("raster-hue-rotate"))};var n,a};function Bp(t){t*=Math.PI/180;const e=Math.sin(t),i=Math.cos(t);return[(2*i+1)/3,(-Math.sqrt(3)*e-i+1)/3,(Math.sqrt(3)*e-i+1)/3]}const Fp=(t,e,i,r,s,n,a,o,l,c,h,u,d,p)=>{const f=a.transform;return{u_is_size_zoom_constant:+("constant"===t||"source"===t),u_is_size_feature_constant:+("constant"===t||"camera"===t),u_size_t:e?e.uSizeT:0,u_size:e?e.uSize:0,u_camera_to_center_distance:f.cameraToCenterDistance,u_pitch:f.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:f.width/f.height,u_fade_change:a.options.fadeDuration?a.symbolFadeChange:1,u_matrix:o,u_label_plane_matrix:l,u_coord_matrix:c,u_is_text:+u,u_pitch_with_map:+r,u_is_along_line:s,u_is_variable_anchor:n,u_texsize:d,u_texture:0,u_translation:h,u_pitched_scale:p}},Op=(t,e,i,r,s,n,a,o,l,c,h,u,d,p,f)=>{const m=a.transform;return y(Fp(t,e,i,r,s,n,a,o,l,c,h,u,d,f),{u_gamma_scale:r?Math.cos(m._pitch)*m.cameraToCenterDistance:1,u_device_pixel_ratio:a.pixelRatio,u_is_halo:+p,u_texture_2:1})},Vp=(t,e,i,r,s,n,a,o,l,c,h,u,d,p)=>y(Op(t,e,i,r,s,n,a,o,l,c,h,!0,u,!0,p),{u_texsize_icon:d,u_texture_icon:1}),Up=(t,e,i)=>({u_matrix:t,u_opacity:e,u_color:i}),Np=(t,e,i,r,s,n)=>y(function(t,e,i,r){const s=i.imageManager.getPattern(t.from.toString()),n=i.imageManager.getPattern(t.to.toString()),{width:a,height:o}=i.imageManager.getPixelSize(),l=Math.pow(2,r.tileID.overscaledZ),c=r.tileSize*Math.pow(2,i.transform.tileZoom)/l,h=c*(r.tileID.canonical.x+r.tileID.wrap*l),u=c*r.tileID.canonical.y;return{u_image:0,u_pattern_tl_a:s.tl,u_pattern_br_a:s.br,u_pattern_tl_b:n.tl,u_pattern_br_b:n.br,u_texsize:[a,o],u_mix:e.t,u_pattern_size_a:s.displaySize,u_pattern_size_b:n.displaySize,u_scale_a:e.fromScale,u_scale_b:e.toScale,u_tile_units_to_pixels:1/Id(r,1,i.transform.tileZoom),u_pixel_coord_upper:[h>>16,u>>16],u_pixel_coord_lower:[65535&h,65535&u]}}(r,n,i,s),{u_matrix:t,u_opacity:e}),jp={fillExtrusion:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_lightpos:new Va(t,e.u_lightpos),u_lightintensity:new Fa(t,e.u_lightintensity),u_lightcolor:new Va(t,e.u_lightcolor),u_vertical_gradient:new Fa(t,e.u_vertical_gradient),u_opacity:new Fa(t,e.u_opacity)}),fillExtrusionPattern:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_lightpos:new Va(t,e.u_lightpos),u_lightintensity:new Fa(t,e.u_lightintensity),u_lightcolor:new Va(t,e.u_lightcolor),u_vertical_gradient:new Fa(t,e.u_vertical_gradient),u_height_factor:new Fa(t,e.u_height_factor),u_image:new Ba(t,e.u_image),u_texsize:new Oa(t,e.u_texsize),u_pixel_coord_upper:new Oa(t,e.u_pixel_coord_upper),u_pixel_coord_lower:new Oa(t,e.u_pixel_coord_lower),u_scale:new Va(t,e.u_scale),u_fade:new Fa(t,e.u_fade),u_opacity:new Fa(t,e.u_opacity)}),fill:(t,e)=>({u_matrix:new $a(t,e.u_matrix)}),fillPattern:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_image:new Ba(t,e.u_image),u_texsize:new Oa(t,e.u_texsize),u_pixel_coord_upper:new Oa(t,e.u_pixel_coord_upper),u_pixel_coord_lower:new Oa(t,e.u_pixel_coord_lower),u_scale:new Va(t,e.u_scale),u_fade:new Fa(t,e.u_fade)}),fillOutline:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_world:new Oa(t,e.u_world)}),fillOutlinePattern:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_world:new Oa(t,e.u_world),u_image:new Ba(t,e.u_image),u_texsize:new Oa(t,e.u_texsize),u_pixel_coord_upper:new Oa(t,e.u_pixel_coord_upper),u_pixel_coord_lower:new Oa(t,e.u_pixel_coord_lower),u_scale:new Va(t,e.u_scale),u_fade:new Fa(t,e.u_fade)}),circle:(t,e)=>({u_camera_to_center_distance:new Fa(t,e.u_camera_to_center_distance),u_scale_with_map:new Ba(t,e.u_scale_with_map),u_pitch_with_map:new Ba(t,e.u_pitch_with_map),u_extrude_scale:new Oa(t,e.u_extrude_scale),u_device_pixel_ratio:new Fa(t,e.u_device_pixel_ratio),u_matrix:new $a(t,e.u_matrix)}),collisionBox:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_pixel_extrude_scale:new Oa(t,e.u_pixel_extrude_scale)}),collisionCircle:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_inv_matrix:new $a(t,e.u_inv_matrix),u_camera_to_center_distance:new Fa(t,e.u_camera_to_center_distance),u_viewport_size:new Oa(t,e.u_viewport_size)}),debug:(t,e)=>({u_color:new Na(t,e.u_color),u_matrix:new $a(t,e.u_matrix),u_overlay:new Ba(t,e.u_overlay),u_overlay_scale:new Fa(t,e.u_overlay_scale)}),clippingMask:(t,e)=>({u_matrix:new $a(t,e.u_matrix)}),heatmap:(t,e)=>({u_extrude_scale:new Fa(t,e.u_extrude_scale),u_intensity:new Fa(t,e.u_intensity),u_matrix:new $a(t,e.u_matrix)}),heatmapTexture:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_world:new Oa(t,e.u_world),u_image:new Ba(t,e.u_image),u_color_ramp:new Ba(t,e.u_color_ramp),u_opacity:new Fa(t,e.u_opacity)}),hillshade:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_image:new Ba(t,e.u_image),u_latrange:new Oa(t,e.u_latrange),u_light:new Oa(t,e.u_light),u_shadow:new Na(t,e.u_shadow),u_highlight:new Na(t,e.u_highlight),u_accent:new Na(t,e.u_accent)}),hillshadePrepare:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_image:new Ba(t,e.u_image),u_dimension:new Oa(t,e.u_dimension),u_zoom:new Fa(t,e.u_zoom),u_unpack:new Ua(t,e.u_unpack)}),line:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_ratio:new Fa(t,e.u_ratio),u_device_pixel_ratio:new Fa(t,e.u_device_pixel_ratio),u_units_to_pixels:new Oa(t,e.u_units_to_pixels)}),lineGradient:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_ratio:new Fa(t,e.u_ratio),u_device_pixel_ratio:new Fa(t,e.u_device_pixel_ratio),u_units_to_pixels:new Oa(t,e.u_units_to_pixels),u_image:new Ba(t,e.u_image),u_image_height:new Fa(t,e.u_image_height)}),linePattern:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_texsize:new Oa(t,e.u_texsize),u_ratio:new Fa(t,e.u_ratio),u_device_pixel_ratio:new Fa(t,e.u_device_pixel_ratio),u_image:new Ba(t,e.u_image),u_units_to_pixels:new Oa(t,e.u_units_to_pixels),u_scale:new Va(t,e.u_scale),u_fade:new Fa(t,e.u_fade)}),lineSDF:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_ratio:new Fa(t,e.u_ratio),u_device_pixel_ratio:new Fa(t,e.u_device_pixel_ratio),u_units_to_pixels:new Oa(t,e.u_units_to_pixels),u_patternscale_a:new Oa(t,e.u_patternscale_a),u_patternscale_b:new Oa(t,e.u_patternscale_b),u_sdfgamma:new Fa(t,e.u_sdfgamma),u_image:new Ba(t,e.u_image),u_tex_y_a:new Fa(t,e.u_tex_y_a),u_tex_y_b:new Fa(t,e.u_tex_y_b),u_mix:new Fa(t,e.u_mix)}),raster:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_tl_parent:new Oa(t,e.u_tl_parent),u_scale_parent:new Fa(t,e.u_scale_parent),u_buffer_scale:new Fa(t,e.u_buffer_scale),u_fade_t:new Fa(t,e.u_fade_t),u_opacity:new Fa(t,e.u_opacity),u_image0:new Ba(t,e.u_image0),u_image1:new Ba(t,e.u_image1),u_brightness_low:new Fa(t,e.u_brightness_low),u_brightness_high:new Fa(t,e.u_brightness_high),u_saturation_factor:new Fa(t,e.u_saturation_factor),u_contrast_factor:new Fa(t,e.u_contrast_factor),u_spin_weights:new Va(t,e.u_spin_weights)}),symbolIcon:(t,e)=>({u_is_size_zoom_constant:new Ba(t,e.u_is_size_zoom_constant),u_is_size_feature_constant:new Ba(t,e.u_is_size_feature_constant),u_size_t:new Fa(t,e.u_size_t),u_size:new Fa(t,e.u_size),u_camera_to_center_distance:new Fa(t,e.u_camera_to_center_distance),u_pitch:new Fa(t,e.u_pitch),u_rotate_symbol:new Ba(t,e.u_rotate_symbol),u_aspect_ratio:new Fa(t,e.u_aspect_ratio),u_fade_change:new Fa(t,e.u_fade_change),u_matrix:new $a(t,e.u_matrix),u_label_plane_matrix:new $a(t,e.u_label_plane_matrix),u_coord_matrix:new $a(t,e.u_coord_matrix),u_is_text:new Ba(t,e.u_is_text),u_pitch_with_map:new Ba(t,e.u_pitch_with_map),u_is_along_line:new Ba(t,e.u_is_along_line),u_is_variable_anchor:new Ba(t,e.u_is_variable_anchor),u_texsize:new Oa(t,e.u_texsize),u_texture:new Ba(t,e.u_texture),u_translation:new Oa(t,e.u_translation),u_pitched_scale:new Fa(t,e.u_pitched_scale)}),symbolSDF:(t,e)=>({u_is_size_zoom_constant:new Ba(t,e.u_is_size_zoom_constant),u_is_size_feature_constant:new Ba(t,e.u_is_size_feature_constant),u_size_t:new Fa(t,e.u_size_t),u_size:new Fa(t,e.u_size),u_camera_to_center_distance:new Fa(t,e.u_camera_to_center_distance),u_pitch:new Fa(t,e.u_pitch),u_rotate_symbol:new Ba(t,e.u_rotate_symbol),u_aspect_ratio:new Fa(t,e.u_aspect_ratio),u_fade_change:new Fa(t,e.u_fade_change),u_matrix:new $a(t,e.u_matrix),u_label_plane_matrix:new $a(t,e.u_label_plane_matrix),u_coord_matrix:new $a(t,e.u_coord_matrix),u_is_text:new Ba(t,e.u_is_text),u_pitch_with_map:new Ba(t,e.u_pitch_with_map),u_is_along_line:new Ba(t,e.u_is_along_line),u_is_variable_anchor:new Ba(t,e.u_is_variable_anchor),u_texsize:new Oa(t,e.u_texsize),u_texture:new Ba(t,e.u_texture),u_texture_2:new Ba(t,e.u_texture_2),u_gamma_scale:new Fa(t,e.u_gamma_scale),u_device_pixel_ratio:new Fa(t,e.u_device_pixel_ratio),u_is_halo:new Ba(t,e.u_is_halo),u_translation:new Oa(t,e.u_translation),u_pitched_scale:new Fa(t,e.u_pitched_scale)}),symbolTextAndIcon:(t,e)=>({u_is_size_zoom_constant:new Ba(t,e.u_is_size_zoom_constant),u_is_size_feature_constant:new Ba(t,e.u_is_size_feature_constant),u_size_t:new Fa(t,e.u_size_t),u_size:new Fa(t,e.u_size),u_camera_to_center_distance:new Fa(t,e.u_camera_to_center_distance),u_pitch:new Fa(t,e.u_pitch),u_rotate_symbol:new Ba(t,e.u_rotate_symbol),u_aspect_ratio:new Fa(t,e.u_aspect_ratio),u_fade_change:new Fa(t,e.u_fade_change),u_matrix:new $a(t,e.u_matrix),u_label_plane_matrix:new $a(t,e.u_label_plane_matrix),u_coord_matrix:new $a(t,e.u_coord_matrix),u_is_text:new Ba(t,e.u_is_text),u_pitch_with_map:new Ba(t,e.u_pitch_with_map),u_is_along_line:new Ba(t,e.u_is_along_line),u_is_variable_anchor:new Ba(t,e.u_is_variable_anchor),u_texsize:new Oa(t,e.u_texsize),u_texsize_icon:new Oa(t,e.u_texsize_icon),u_texture:new Ba(t,e.u_texture),u_texture_icon:new Ba(t,e.u_texture_icon),u_gamma_scale:new Fa(t,e.u_gamma_scale),u_device_pixel_ratio:new Fa(t,e.u_device_pixel_ratio),u_is_halo:new Ba(t,e.u_is_halo),u_translation:new Oa(t,e.u_translation),u_pitched_scale:new Fa(t,e.u_pitched_scale)}),background:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_opacity:new Fa(t,e.u_opacity),u_color:new Na(t,e.u_color)}),backgroundPattern:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_opacity:new Fa(t,e.u_opacity),u_image:new Ba(t,e.u_image),u_pattern_tl_a:new Oa(t,e.u_pattern_tl_a),u_pattern_br_a:new Oa(t,e.u_pattern_br_a),u_pattern_tl_b:new Oa(t,e.u_pattern_tl_b),u_pattern_br_b:new Oa(t,e.u_pattern_br_b),u_texsize:new Oa(t,e.u_texsize),u_mix:new Fa(t,e.u_mix),u_pattern_size_a:new Oa(t,e.u_pattern_size_a),u_pattern_size_b:new Oa(t,e.u_pattern_size_b),u_scale_a:new Fa(t,e.u_scale_a),u_scale_b:new Fa(t,e.u_scale_b),u_pixel_coord_upper:new Oa(t,e.u_pixel_coord_upper),u_pixel_coord_lower:new Oa(t,e.u_pixel_coord_lower),u_tile_units_to_pixels:new Fa(t,e.u_tile_units_to_pixels)}),terrain:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_texture:new Ba(t,e.u_texture),u_ele_delta:new Fa(t,e.u_ele_delta),u_fog_matrix:new $a(t,e.u_fog_matrix),u_fog_color:new Na(t,e.u_fog_color),u_fog_ground_blend:new Fa(t,e.u_fog_ground_blend),u_fog_ground_blend_opacity:new Fa(t,e.u_fog_ground_blend_opacity),u_horizon_color:new Na(t,e.u_horizon_color),u_horizon_fog_blend:new Fa(t,e.u_horizon_fog_blend)}),terrainDepth:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_ele_delta:new Fa(t,e.u_ele_delta)}),terrainCoords:(t,e)=>({u_matrix:new $a(t,e.u_matrix),u_texture:new Ba(t,e.u_texture),u_terrain_coords_id:new Fa(t,e.u_terrain_coords_id),u_ele_delta:new Fa(t,e.u_ele_delta)}),sky:(t,e)=>({u_sky_color:new Na(t,e.u_sky_color),u_horizon_color:new Na(t,e.u_horizon_color),u_horizon:new Fa(t,e.u_horizon),u_sky_horizon_blend:new Fa(t,e.u_sky_horizon_blend)})};class $p{constructor(t,e,i){this.context=t;const r=t.gl;this.buffer=r.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),t.bindElementBuffer.set(this.buffer),r.bufferData(r.ELEMENT_ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(t){const e=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),e.bufferSubData(e.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}const qp={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class Zp{constructor(t,e,i,r){this.length=e.length,this.attributes=i,this.itemSize=e.bytesPerElement,this.dynamicDraw=r,this.context=t;const s=t.gl;this.buffer=s.createBuffer(),t.bindVertexBuffer.set(this.buffer),s.bufferData(s.ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?s.DYNAMIC_DRAW:s.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(t){if(t.length!==this.length)throw new Error(`Length of new data is ${t.length}, which doesn't match current length of ${this.length}`);const e=this.context.gl;this.bind(),e.bufferSubData(e.ARRAY_BUFFER,0,t.arrayBuffer)}enableAttributes(t,e){for(let i=0;i0){const e=Eo();Oo(e,f.placementInvProjMatrix,t.transform.glCoordMatrix),Oo(e,e,f.placementViewportMatrix),l.push({circleArray:_,circleOffset:h,transform:p.posMatrix,invTransform:e,coord:p}),c+=_.length/4,h=c}m&&o.draw(n,a.LINES,Lf.disabled,Bf.disabled,t.colorModeForRenderPass(),Ff.disabled,{u_matrix:p.posMatrix,u_pixel_extrude_scale:[1/(u=t.transform).width,1/u.height]},t.style.map.terrain&&t.style.map.terrain.getTerrainData(p),i.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,t.transform.zoom,null,null,m.collisionVertexBuffer)}var u;if(!s||!l.length)return;const d=t.useProgram("collisionCircle"),p=new pa;p.resize(4*c),p._trim();let f=0;for(const t of l)for(let e=0;e=0&&(y[x.associatedIconIndex]={shiftedAnchor:P,angle:M})}else xd(x.numGlyphs,_)}if(h){g.clear();const e=t.icon.placedSymbolArray;for(let t=0;tt.style.map.terrain.getElevation(o,e,i):null,r="map"===i.layout.get("text-rotation-alignment");ld(l,o.posMatrix,t,s,U,j,g,c,r,m,o.toUnwrapped(),f.width,f.height,$,e)}const G=o.posMatrix,W=s&&S||Z,H=y||W?Uf:U,X=N,K=d&&0!==i.paint.get(s?"text-halo-width":"icon-halo-width").constantOr(1);let Y;Y=d?l.iconsInText?Vp(T.kind,z,x,g,y,W,t,G,H,X,$,M,B,A):Op(T.kind,z,x,g,y,W,t,G,H,X,$,s,M,!0,A):Fp(T.kind,z,x,g,y,W,t,G,H,X,$,s,M,A);const J={program:C,buffers:h,uniformValues:Y,atlasTexture:k,atlasBackgroundTexture:R,atlasTextureIcon:F,atlasInterpolation:D,atlasInterpolationIcon:L,isSDF:d,hasHalo:K};if(b&&l.canOverlap){w=!0;const t=h.segments.get();for(const e of t)I.push({segments:new ba([e]),sortKey:e.sortKey,state:J,terrainData:P})}else I.push({segments:h.segments,sortKey:0,state:J,terrainData:P})}w&&I.sort(((t,e)=>t.sortKey-e.sortKey));for(const e of I){const r=e.state;if(d.activeTexture.set(p.TEXTURE0),r.atlasTexture.bind(r.atlasInterpolation,p.CLAMP_TO_EDGE),(r.atlasTextureIcon||r.atlasBackgroundTexture)&&(d.activeTexture.set(p.TEXTURE1),r.atlasTextureIcon&&r.atlasTextureIcon.bind(r.atlasInterpolationIcon,p.CLAMP_TO_EDGE),r.atlasBackgroundTexture&&r.atlasBackgroundTexture.bind(r.atlasInterpolation,p.CLAMP_TO_EDGE)),r.isSDF){const s=r.uniformValues;r.hasHalo&&(s.u_is_halo=1,Gf(r.buffers,e.segments,i,t,r.program,T,h,u,s,e.terrainData)),s.u_is_halo=0}Gf(r.buffers,e.segments,i,t,r.program,T,h,u,r.uniformValues,e.terrainData)}}function Gf(t,e,i,r,s,n,a,o,l,c){const h=r.context;s.draw(h,h.gl.TRIANGLES,n,a,o,Ff.disabled,l,c,i.id,t.layoutVertexBuffer,t.indexBuffer,e,i.paint,r.transform.zoom,t.programConfigurations.get(i.id),t.dynamicLayoutVertexBuffer,t.opacityVertexBuffer)}function Wf(t,e,i,r){const s=t.context,n=s.gl,a=Bf.disabled,o=new kf([n.ONE,n.ONE],le.transparent,[!0,!0,!0,!0]),l=e.getBucket(i);if(!l)return;const c=r.key;let h=i.heatmapFbos.get(c);h||(h=Xf(s,e.tileSize,e.tileSize),i.heatmapFbos.set(c,h)),s.bindFramebuffer.set(h.framebuffer),s.viewport.set([0,0,e.tileSize,e.tileSize]),s.clear({color:le.transparent});const u=l.programConfigurations.get(i.id),d=t.useProgram("heatmap",u),p=t.style.map.terrain.getTerrainData(r);d.draw(s,n.TRIANGLES,Lf.disabled,a,o,Ff.disabled,Ap(r.posMatrix,e,t.transform.zoom,i.paint.get("heatmap-intensity")),p,i.id,l.layoutVertexBuffer,l.indexBuffer,l.segments,i.paint,t.transform.zoom,u)}function Hf(t,e,i){const r=t.context,s=r.gl;r.setColorMode(t.colorModeForRenderPass());const n=Kf(r,e),a=i.key,o=e.heatmapFbos.get(a);o&&(r.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,o.colorAttachment.get()),r.activeTexture.set(s.TEXTURE1),n.bind(s.LINEAR,s.CLAMP_TO_EDGE),t.useProgram("heatmapTexture").draw(r,s.TRIANGLES,Lf.disabled,Bf.disabled,t.colorModeForRenderPass(),Ff.disabled,Ep(t,e,0,1),null,e.id,t.rasterBoundsBuffer,t.quadTriangleIndexBuffer,t.rasterBoundsSegments,e.paint,t.transform.zoom),o.destroy(),e.heatmapFbos.delete(a))}function Xf(t,e,i){var r,s;const n=t.gl,a=n.createTexture();n.bindTexture(n.TEXTURE_2D,a),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR);const o=null!==(r=t.HALF_FLOAT)&&void 0!==r?r:n.UNSIGNED_BYTE,l=null!==(s=t.RGBA16F)&&void 0!==s?s:n.RGBA;n.texImage2D(n.TEXTURE_2D,0,l,e,i,0,n.RGBA,o,null);const c=t.createFramebuffer(e,i,!1,!1);return c.colorAttachment.set(a),c}function Kf(t,e){return e.colorRampTexture||(e.colorRampTexture=new Uh(t,e.colorRamp,t.gl.RGBA)),e.colorRampTexture}function Yf(t,e,i,r,s){if(!i||!r||!r.imageAtlas)return;const n=r.imageAtlas.patternPositions;let a=n[i.to.toString()],o=n[i.from.toString()];if(!a&&o&&(a=o),!o&&a&&(o=a),!a||!o){const t=s.getPaintProperty(e);a=n[t],o=n[t]}a&&o&&t.setConstantPatternPositions(a,o)}function Jf(t,e,i,r,s,n,a){const o=t.context.gl,l="fill-pattern",c=i.paint.get(l),h=c&&c.constantOr(1),u=i.getCrossfadeParameters();let d,p,f,m,_;a?(p=h&&!i.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",d=o.LINES):(p=h?"fillPattern":"fill",d=o.TRIANGLES);const g=c.constantOr(null);for(const c of r){const r=e.getTile(c);if(h&&!r.patternsLoaded())continue;const y=r.getBucket(i);if(!y)continue;const x=y.programConfigurations.get(i.id),v=t.useProgram(p,x),b=t.style.map.terrain&&t.style.map.terrain.getTerrainData(c);h&&(t.context.activeTexture.set(o.TEXTURE0),r.imageAtlasTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE),x.updatePaintBuffers(u)),Yf(x,l,g,r,i);const w=b?c:null,T=t.translatePosMatrix(w?w.posMatrix:c.posMatrix,r,i.paint.get("fill-translate"),i.paint.get("fill-translate-anchor"));if(a){m=y.indexBuffer2,_=y.segments2;const e=[o.drawingBufferWidth,o.drawingBufferHeight];f="fillOutlinePattern"===p&&h?bp(T,t,u,r,e):vp(T,e)}else m=y.indexBuffer,_=y.segments,f=h?xp(T,t,u,r):yp(T);v.draw(t.context,d,s,t.stencilModeForClipping(c),n,Ff.disabled,f,b,i.id,y.layoutVertexBuffer,m,_,i.paint,t.transform.zoom,x)}}function Qf(t,e,i,r,s,n,a){const o=t.context,l=o.gl,c="fill-extrusion-pattern",h=i.paint.get(c),u=h.constantOr(1),d=i.getCrossfadeParameters(),p=i.paint.get("fill-extrusion-opacity"),f=h.constantOr(null);for(const h of r){const r=e.getTile(h),m=r.getBucket(i);if(!m)continue;const _=t.style.map.terrain&&t.style.map.terrain.getTerrainData(h),g=m.programConfigurations.get(i.id),y=t.useProgram(u?"fillExtrusionPattern":"fillExtrusion",g);u&&(t.context.activeTexture.set(l.TEXTURE0),r.imageAtlasTexture.bind(l.LINEAR,l.CLAMP_TO_EDGE),g.updatePaintBuffers(d)),Yf(g,c,f,r,i);const x=t.translatePosMatrix(h.posMatrix,r,i.paint.get("fill-extrusion-translate"),i.paint.get("fill-extrusion-translate-anchor")),v=i.paint.get("fill-extrusion-vertical-gradient"),b=u?gp(x,t,v,p,h,d,r):_p(x,t,v,p);y.draw(o,o.gl.TRIANGLES,s,n,a,Ff.backCCW,b,_,i.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,i.paint,t.transform.zoom,g,t.style.map.terrain&&m.centroidVertexBuffer)}}function tm(t,e,i,r,s,n,a){const o=t.context,l=o.gl,c=i.fbo;if(!c)return;const h=t.useProgram("hillshade"),u=t.style.map.terrain&&t.style.map.terrain.getTerrainData(e);o.activeTexture.set(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,c.colorAttachment.get()),h.draw(o,l.TRIANGLES,s,n,a,Ff.disabled,((t,e,i,r)=>{const s=i.paint.get("hillshade-shadow-color"),n=i.paint.get("hillshade-highlight-color"),a=i.paint.get("hillshade-accent-color");let o=i.paint.get("hillshade-illumination-direction")*(Math.PI/180);"viewport"===i.paint.get("hillshade-illumination-anchor")&&(o-=t.transform.angle);const l=!t.options.moving;return{u_matrix:r?r.posMatrix:t.transform.calculatePosMatrix(e.tileID.toUnwrapped(),l),u_image:0,u_latrange:Cp(0,e.tileID),u_light:[i.paint.get("hillshade-exaggeration"),o],u_shadow:s,u_highlight:n,u_accent:a}})(t,i,r,u?e:null),u,r.id,t.rasterBoundsBuffer,t.quadTriangleIndexBuffer,t.rasterBoundsSegments)}function em(t,e,i,r,s,n){const a=t.context,o=a.gl,l=e.dem;if(l&&l.data){const c=l.dim,h=l.stride,u=l.getPixels();if(a.activeTexture.set(o.TEXTURE1),a.pixelStoreUnpackPremultiplyAlpha.set(!1),e.demTexture=e.demTexture||t.getTileTexture(h),e.demTexture){const t=e.demTexture;t.update(u,{premultiply:!1}),t.bind(o.NEAREST,o.CLAMP_TO_EDGE)}else e.demTexture=new Uh(a,u,o.RGBA,{premultiply:!1}),e.demTexture.bind(o.NEAREST,o.CLAMP_TO_EDGE);a.activeTexture.set(o.TEXTURE0);let d=e.fbo;if(!d){const t=new Uh(a,{width:c,height:c,data:null},o.RGBA);t.bind(o.LINEAR,o.CLAMP_TO_EDGE),d=e.fbo=a.createFramebuffer(c,c,!0,!1),d.colorAttachment.set(t.texture)}a.bindFramebuffer.set(d.framebuffer),a.viewport.set([0,0,c,c]),t.useProgram("hillshadePrepare").draw(a,o.TRIANGLES,r,s,n,Ff.disabled,((t,e)=>{const i=e.stride,r=Eo();return Fo(r,0,to,-to,0,0,1),ko(r,r,[0,-to,0]),{u_matrix:r,u_image:1,u_dimension:[i,i],u_zoom:t.overscaledZ,u_unpack:e.getUnpackVector()}})(e.tileID,l),null,i.id,t.rasterBoundsBuffer,t.quadTriangleIndexBuffer,t.rasterBoundsSegments),e.needsHillshadePrepare=!1}}function im(t,e,i,r,s,n){const a=r.paint.get("raster-fade-duration");if(!n&&a>0){const r=F.now(),n=(r-t.timeAdded)/a,o=e?(r-e.timeAdded)/a:-1,l=i.getSource(),c=s.coveringZoomLevel({tileSize:l.tileSize,roundZoom:l.roundZoom}),h=!e||Math.abs(e.tileID.overscaledZ-c)>Math.abs(t.tileID.overscaledZ-c),u=h&&t.refreshedUponExpiration?1:_(h?n:1-o,0,1);return t.refreshedUponExpiration&&n>=1&&(t.refreshedUponExpiration=!1),e?{opacity:1,mix:1-u}:{opacity:u,mix:0}}return{opacity:1,mix:0}}const rm=new le(1,0,0,1),sm=new le(0,1,0,1),nm=new le(0,0,1,1),am=new le(1,0,1,1),om=new le(0,1,1,1);function lm(t,e,i,r){hm(t,0,e+i/2,t.transform.width,i,r)}function cm(t,e,i,r){hm(t,e-i/2,0,i,t.transform.height,r)}function hm(t,e,i,r,s,n){const a=t.context,o=a.gl;o.enable(o.SCISSOR_TEST),o.scissor(e*t.pixelRatio,i*t.pixelRatio,r*t.pixelRatio,s*t.pixelRatio),a.clear({color:n}),o.disable(o.SCISSOR_TEST)}function um(t,e,i){const r=t.context,s=r.gl,n=i.posMatrix,a=t.useProgram("debug"),o=Lf.disabled,l=Bf.disabled,c=t.colorModeForRenderPass(),h="$debug",u=t.style.map.terrain&&t.style.map.terrain.getTerrainData(i);r.activeTexture.set(s.TEXTURE0);const d=e.getTileByID(i.key).latestRawTileData,p=Math.floor((d&&d.byteLength||0)/1024),f=e.getTile(i).tileSize,m=512/Math.min(f,512)*(i.overscaledZ/t.transform.zoom)*.5;let _=i.canonical.toString();i.overscaledZ!==i.canonical.z&&(_+=` => ${i.overscaledZ}`),function(t,e){t.initDebugOverlayCanvas();const i=t.debugOverlayCanvas,r=t.context.gl,s=t.debugOverlayCanvas.getContext("2d");s.clearRect(0,0,i.width,i.height),s.shadowColor="white",s.shadowBlur=2,s.lineWidth=1.5,s.strokeStyle="white",s.textBaseline="top",s.font="bold 36px Open Sans, sans-serif",s.fillText(e,5,5),s.strokeText(e,5,5),t.debugOverlayTexture.update(i),t.debugOverlayTexture.bind(r.LINEAR,r.CLAMP_TO_EDGE)}(t,`${_} ${p}kB`),a.draw(r,s.TRIANGLES,o,l,kf.alphaBlended,Ff.disabled,Sp(n,le.transparent,m),null,h,t.debugBuffer,t.quadTriangleIndexBuffer,t.debugSegments),a.draw(r,s.LINE_STRIP,o,l,c,Ff.disabled,Sp(n,le.red),u,h,t.debugBuffer,t.tileBorderIndexBuffer,t.debugSegments)}function dm(t,e,i){const r=t.context,s=r.gl,n=t.colorModeForRenderPass(),a=new Lf(s.LEQUAL,Lf.ReadWrite,t.depthRangeFor3D),o=t.useProgram("terrain"),l=e.getTerrainMesh();r.bindFramebuffer.set(null),r.viewport.set([0,0,t.width,t.height]);for(const c of i){const i=t.renderToTexture.getTexture(c),h=e.getTerrainData(c.tileID);r.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,i.texture);const u=t.transform.calculatePosMatrix(c.tileID.toUnwrapped()),d=e.getMeshFrameDelta(t.transform.zoom),p=t.transform.calculateFogMatrix(c.tileID.toUnwrapped()),f=dp(u,d,p,t.style.sky,t.transform.pitch);o.draw(r,s.TRIANGLES,a,Bf.disabled,n,Ff.backCCW,f,h,"terrain",l.vertexBuffer,l.indexBuffer,l.segments)}}class pm{constructor(t,e,i){this.vertexBuffer=t,this.indexBuffer=e,this.segments=i}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null}}class fm{constructor(t,e){this.context=new Df(t),this.transform=e,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:zo(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=Yu.maxUnderzooming+Yu.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new sp}resize(t,e,i){if(this.width=Math.floor(t*i),this.height=Math.floor(e*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const t of this.style._order)this.style._layers[t].resize()}setup(){const t=this.context,e=new ta;e.emplaceBack(0,0),e.emplaceBack(to,0),e.emplaceBack(0,to),e.emplaceBack(to,to),this.tileExtentBuffer=t.createVertexBuffer(e,lp.members),this.tileExtentSegments=ba.simpleSegment(0,0,4,2);const i=new ta;i.emplaceBack(0,0),i.emplaceBack(to,0),i.emplaceBack(0,to),i.emplaceBack(to,to),this.debugBuffer=t.createVertexBuffer(i,lp.members),this.debugSegments=ba.simpleSegment(0,0,4,5);const r=new ia;r.emplaceBack(0,0,0,0),r.emplaceBack(to,0,to,0),r.emplaceBack(0,to,0,to),r.emplaceBack(to,to,to,to),this.rasterBoundsBuffer=t.createVertexBuffer(r,Du.members),this.rasterBoundsSegments=ba.simpleSegment(0,0,4,2);const s=new ta;s.emplaceBack(0,0),s.emplaceBack(1,0),s.emplaceBack(0,1),s.emplaceBack(1,1),this.viewportBuffer=t.createVertexBuffer(s,lp.members),this.viewportSegments=ba.simpleSegment(0,0,4,2);const n=new ya;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=t.createIndexBuffer(n);const a=new _a;a.emplaceBack(0,1,2),a.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=t.createIndexBuffer(a);const o=this.context.gl;this.stencilClearMode=new Bf({func:o.ALWAYS,mask:0},0,255,o.ZERO,o.ZERO,o.ZERO)}clearStencil(){const t=this.context,e=t.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const i=Eo();Fo(i,0,this.width,this.height,0,0,1),Do(i,i,[e.drawingBufferWidth,e.drawingBufferHeight,0]),this.useProgram("clippingMask").draw(t,e.TRIANGLES,Lf.disabled,this.stencilClearMode,kf.disabled,Ff.disabled,Ip(i),null,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}_renderTileClippingMasks(t,e){if(this.currentStencilSource===t.source||!t.isTileClipped()||!e||!e.length)return;this.currentStencilSource=t.source;const i=this.context,r=i.gl;this.nextStencilID+e.length>256&&this.clearStencil(),i.setColorMode(kf.disabled),i.setDepthMode(Lf.disabled);const s=this.useProgram("clippingMask");this._tileClippingMaskIDs={};for(const t of e){const e=this._tileClippingMaskIDs[t.key]=this.nextStencilID++,n=this.style.map.terrain&&this.style.map.terrain.getTerrainData(t);s.draw(i,r.TRIANGLES,Lf.disabled,new Bf({func:r.ALWAYS,mask:0},e,255,r.KEEP,r.KEEP,r.REPLACE),kf.disabled,Ff.disabled,Ip(t.posMatrix),n,"$clipping",this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const t=this.nextStencilID++,e=this.context.gl;return new Bf({func:e.NOTEQUAL,mask:255},t,255,e.KEEP,e.KEEP,e.REPLACE)}stencilModeForClipping(t){const e=this.context.gl;return new Bf({func:e.EQUAL,mask:255},this._tileClippingMaskIDs[t.key],0,e.KEEP,e.KEEP,e.REPLACE)}stencilConfigForOverlap(t){const e=this.context.gl,i=t.sort(((t,e)=>e.overscaledZ-t.overscaledZ)),r=i[i.length-1].overscaledZ,s=i[0].overscaledZ-r+1;if(s>1){this.currentStencilSource=void 0,this.nextStencilID+s>256&&this.clearStencil();const t={};for(let i=0;i({u_sky_color:t.properties.get("sky-color"),u_horizon_color:t.properties.get("horizon-color"),u_horizon:(e.height/2+e.getHorizon())*i,u_sky_horizon_blend:t.properties.get("sky-horizon-blend")*e.height/2*i}))(e,t.style.map.transform,t.pixelRatio),n=new Lf(r.LEQUAL,Lf.ReadWrite,[0,1]),a=Bf.disabled,o=t.colorModeForRenderPass(),l=t.useProgram("sky");if(!e.mesh){const t=new ta;t.emplaceBack(-1,-1),t.emplaceBack(1,-1),t.emplaceBack(1,1),t.emplaceBack(-1,1);const r=new _a;r.emplaceBack(0,1,2),r.emplaceBack(0,2,3),e.mesh=new pm(i.createVertexBuffer(t,lp.members),i.createIndexBuffer(r),ba.simpleSegment(0,0,t.length,r.length))}l.draw(i,r.TRIANGLES,n,a,o,Ff.disabled,s,void 0,"sky",e.mesh.vertexBuffer,e.mesh.indexBuffer,e.mesh.segments)}(this,this.style.sky),this._showOverdrawInspector=e.showOverdrawInspector,this.depthRangeFor3D=[0,1-(t._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=i.length-1;this.currentLayer>=0;this.currentLayer--){const t=this.style._layers[i[this.currentLayer]],e=r[t.source],n=s[t.source];this._renderTileClippingMasks(t,n),this.renderLayer(this,e,t,n)}for(this.renderPass="translucent",this.currentLayer=0;this.currentLayeri.source&&!i.isHidden(e)?[t.sourceCaches[i.source]]:[])),s=r.filter((t=>"vector"===t.getSource().type)),n=r.filter((t=>"vector"!==t.getSource().type)),a=t=>{(!i||i.getSource().maxzooma(t))),i||n.forEach((t=>a(t))),i}(this.style,this.transform.zoom);t&&function(t,e,i){for(let r=0;r0),r&&(function(t,e){t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]}(e,i),this.terrainFacilitator.renderTime=Date.now(),this.terrainFacilitator.dirty=!1,function(t,e){const i=t.context,r=i.gl,s=kf.unblended,n=new Lf(r.LEQUAL,Lf.ReadWrite,[0,1]),a=e.getTerrainMesh(),o=e.sourceCache.getRenderableTiles(),l=t.useProgram("terrainDepth");i.bindFramebuffer.set(e.getFramebuffer("depth").framebuffer),i.viewport.set([0,0,t.width/devicePixelRatio,t.height/devicePixelRatio]),i.clear({color:le.transparent,depth:1});for(const c of o){const o=e.getTerrainData(c.tileID),h={u_matrix:t.transform.calculatePosMatrix(c.tileID.toUnwrapped()),u_ele_delta:e.getMeshFrameDelta(t.transform.zoom)};l.draw(i,r.TRIANGLES,n,Bf.disabled,s,Ff.backCCW,h,o,"terrain",a.vertexBuffer,a.indexBuffer,a.segments)}i.bindFramebuffer.set(null),i.viewport.set([0,0,t.width,t.height])}(this,this.style.map.terrain),function(t,e){const i=t.context,r=i.gl,s=kf.unblended,n=new Lf(r.LEQUAL,Lf.ReadWrite,[0,1]),a=e.getTerrainMesh(),o=e.getCoordsTexture(),l=e.sourceCache.getRenderableTiles(),c=t.useProgram("terrainCoords");i.bindFramebuffer.set(e.getFramebuffer("coords").framebuffer),i.viewport.set([0,0,t.width/devicePixelRatio,t.height/devicePixelRatio]),i.clear({color:le.transparent,depth:1}),e.coordsIndex=[];for(const h of l){const l=e.getTerrainData(h.tileID);i.activeTexture.set(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,o.texture);const u={u_matrix:t.transform.calculatePosMatrix(h.tileID.toUnwrapped()),u_terrain_coords_id:(255-e.coordsIndex.length)/255,u_texture:0,u_ele_delta:e.getMeshFrameDelta(t.transform.zoom)};c.draw(i,r.TRIANGLES,n,Bf.disabled,s,Ff.backCCW,u,l,"terrain",a.vertexBuffer,a.indexBuffer,a.segments),e.coordsIndex.push(h.tileID.key)}i.bindFramebuffer.set(null),i.viewport.set([0,0,t.width,t.height])}(this,this.style.map.terrain))}renderLayer(t,e,i,r){if(!i.isHidden(this.transform.zoom)&&("background"===i.type||"custom"===i.type||(r||[]).length))switch(this.id=i.id,i.type){case"symbol":!function(t,e,i,r,s){if("translucent"!==t.renderPass)return;const n=Bf.disabled,a=t.colorModeForRenderPass();(i._unevaluatedLayout.hasValue("text-variable-anchor")||i._unevaluatedLayout.hasValue("text-variable-anchor-offset"))&&function(t,e,i,r,s,n,a,o,l){const c=e.transform,h=qd(),u="map"===s,d="map"===n;for(const s of t){const t=r.getTile(s),n=t.getBucket(i);if(!n||!n.text||!n.text.segments.get().length)continue;const p=mh(n.textSizeData,c.zoom),f=Id(t,1,e.transform.zoom),m=rd(s.posMatrix,d,u,e.transform,f),_="none"!==i.layout.get("icon-text-fit")&&n.hasIconData();if(p){const i=Math.pow(2,c.zoom-t.tileID.overscaledZ),r=e.style.map.terrain?(t,i)=>e.style.map.terrain.getElevation(s,t,i):null,f=h.translatePosition(c,t,a,o);$f(n,u,d,l,c,m,s.posMatrix,i,p,_,h,f,s.toUnwrapped(),r)}}}(r,t,i,e,i.layout.get("text-rotation-alignment"),i.layout.get("text-pitch-alignment"),i.paint.get("text-translate"),i.paint.get("text-translate-anchor"),s),0!==i.paint.get("icon-opacity").constantOr(1)&&Zf(t,e,i,r,!1,i.paint.get("icon-translate"),i.paint.get("icon-translate-anchor"),i.layout.get("icon-rotation-alignment"),i.layout.get("icon-pitch-alignment"),i.layout.get("icon-keep-upright"),n,a),0!==i.paint.get("text-opacity").constantOr(1)&&Zf(t,e,i,r,!0,i.paint.get("text-translate"),i.paint.get("text-translate-anchor"),i.layout.get("text-rotation-alignment"),i.layout.get("text-pitch-alignment"),i.layout.get("text-keep-upright"),n,a),e.map.showCollisionBoxes&&(Vf(t,e,i,r,!0),Vf(t,e,i,r,!1))}(t,e,i,r,this.style.placement.variableOffsets);break;case"circle":!function(t,e,i,r){if("translucent"!==t.renderPass)return;const s=i.paint.get("circle-opacity"),n=i.paint.get("circle-stroke-width"),a=i.paint.get("circle-stroke-opacity"),o=!i.layout.get("circle-sort-key").isConstant();if(0===s.constantOr(1)&&(0===n.constantOr(1)||0===a.constantOr(1)))return;const l=t.context,c=l.gl,h=t.depthModeForSublayer(0,Lf.ReadOnly),u=Bf.disabled,d=t.colorModeForRenderPass(),p=[];for(let s=0;st.sortKey-e.sortKey));for(const e of p){const{programConfiguration:r,program:s,layoutVertexBuffer:n,indexBuffer:a,uniformValues:o,terrainData:p}=e.state;s.draw(l,c.TRIANGLES,h,u,d,Ff.disabled,o,p,i.id,n,a,e.segments,i.paint,t.transform.zoom,r)}}(t,e,i,r);break;case"heatmap":!function(t,e,i,r){if(0===i.paint.get("heatmap-opacity"))return;const s=t.context;if(t.style.map.terrain){for(const s of r){const r=e.getTile(s);e.hasRenderableParent(s)||("offscreen"===t.renderPass?Wf(t,r,i,s):"translucent"===t.renderPass&&Hf(t,i,s))}s.viewport.set([0,0,t.width,t.height])}else"offscreen"===t.renderPass?function(t,e,i,r){const s=t.context,n=s.gl,a=Bf.disabled,o=new kf([n.ONE,n.ONE],le.transparent,[!0,!0,!0,!0]);(function(t,e,i){const r=t.gl;t.activeTexture.set(r.TEXTURE1),t.viewport.set([0,0,e.width/4,e.height/4]);let s=i.heatmapFbos.get(el);s?(r.bindTexture(r.TEXTURE_2D,s.colorAttachment.get()),t.bindFramebuffer.set(s.framebuffer)):(s=Xf(t,e.width/4,e.height/4),i.heatmapFbos.set(el,s))})(s,t,i),s.clear({color:le.transparent});for(let l=0;l20&&n.texParameterf(n.TEXTURE_2D,s.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,s.extTextureFilterAnisotropicMax);const v=t.style.map.terrain&&t.style.map.terrain.getTerrainData(r),b=v?r:null,w=b?b.posMatrix:t.transform.calculatePosMatrix(r.toUnwrapped(),d),T=Rp(w,y||[0,0],g||1,_,i);a instanceof Lu?o.draw(s,n.TRIANGLES,h,Bf.disabled,l,Ff.disabled,T,v,i.id,a.boundsBuffer,t.quadTriangleIndexBuffer,a.boundsSegments):o.draw(s,n.TRIANGLES,h,c[r.overscaledZ],l,Ff.disabled,T,v,i.id,t.rasterBoundsBuffer,t.quadTriangleIndexBuffer,t.rasterBoundsSegments)}}(t,e,i,r);break;case"background":!function(t,e,i,r){const s=i.paint.get("background-color"),n=i.paint.get("background-opacity");if(0===n)return;const a=t.context,o=a.gl,l=t.transform,c=l.tileSize,h=i.paint.get("background-pattern");if(t.isPatternMissing(h))return;const u=!h&&1===s.a&&1===n&&t.opaquePassEnabledForLayer()?"opaque":"translucent";if(t.renderPass!==u)return;const d=Bf.disabled,p=t.depthModeForSublayer(0,"opaque"===u?Lf.ReadWrite:Lf.ReadOnly),f=t.colorModeForRenderPass(),m=t.useProgram(h?"backgroundPattern":"background"),_=r||l.coveringTiles({tileSize:c,terrain:t.style.map.terrain});h&&(a.activeTexture.set(o.TEXTURE0),t.imageManager.bind(t.context));const g=i.getCrossfadeParameters();for(const e of _){const l=r?e.posMatrix:t.transform.calculatePosMatrix(e.toUnwrapped()),u=h?Np(l,n,t,h,{tileID:e,tileSize:c},g):Up(l,n,s),_=t.style.map.terrain&&t.style.map.terrain.getTerrainData(e);m.draw(a,o.TRIANGLES,p,d,f,Ff.disabled,u,_,i.id,t.tileExtentBuffer,t.quadTriangleIndexBuffer,t.tileExtentSegments)}}(t,0,i,r);break;case"custom":!function(t,e,i){const r=t.context,s=i.implementation;if("offscreen"===t.renderPass){const e=s.prerender;e&&(t.setCustomLayerDefaults(),r.setColorMode(t.colorModeForRenderPass()),e.call(s,r.gl,t.transform.customLayerMatrix()),r.setDirty(),t.setBaseState())}else if("translucent"===t.renderPass){t.setCustomLayerDefaults(),r.setColorMode(t.colorModeForRenderPass()),r.setStencilMode(Bf.disabled);const e="3d"===s.renderingMode?new Lf(t.context.gl.LEQUAL,Lf.ReadWrite,t.depthRangeFor3D):t.depthModeForSublayer(0,Lf.ReadOnly);r.setDepthMode(e),s.render(r.gl,t.transform.customLayerMatrix(),{farZ:t.transform.farZ,nearZ:t.transform.nearZ,fov:t.transform._fov,modelViewProjectionMatrix:t.transform.modelViewProjectionMatrix,projectionMatrix:t.transform.projectionMatrix}),r.setDirty(),t.setBaseState(),r.bindFramebuffer.set(null)}}(t,0,i)}}translatePosMatrix(t,e,i,r,s){if(!i[0]&&!i[1])return t;const n=s?"map"===r?this.transform.angle:0:"viewport"===r?-this.transform.angle:0;if(n){const t=Math.sin(n),e=Math.cos(n);i=[i[0]*e-i[1]*t,i[0]*t+i[1]*e]}const a=[s?i[0]:Id(e,i[0],this.transform.zoom),s?i[1]:Id(e,i[1],this.transform.zoom),0],o=new Float32Array(16);return ko(o,t,a),o}saveTileTexture(t){const e=this._tileTextures[t.size[0]];e?e.push(t):this._tileTextures[t.size[0]]=[t]}getTileTexture(t){const e=this._tileTextures[t];return e&&e.length>0?e.pop():null}isPatternMissing(t){if(!t)return!1;if(!t.from||!t.to)return!0;const e=this.imageManager.getPattern(t.from.toString()),i=this.imageManager.getPattern(t.to.toString());return!e||!i}useProgram(t,e){this.cache=this.cache||{};const i=t+(e?e.cacheKey:"")+(this._showOverdrawInspector?"/overdraw":"")+(this.style.map.terrain?"/terrain":"");return this.cache[i]||(this.cache[i]=new fp(this.context,cp[t],e,jp[t],this._showOverdrawInspector,this.style.map.terrain)),this.cache[i]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){const t=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(t.FUNC_ADD)}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new Uh(this.context,this.debugOverlayCanvas,this.context.gl.RGBA))}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy()}overLimit(){const{drawingBufferWidth:t,drawingBufferHeight:e}=this.context.gl;return this.width!==t||this.height!==e}}class mm{constructor(t,e){this.points=t,this.planes=e}static fromInvProjectionMatrix(t,e,i){const r=Math.pow(2,i),s=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((i=>{const s=1/(i=jo([],i,t))[3]/e*r;return function(t,e,i){return t[0]=e[0]*i[0],t[1]=e[1]*i[1],t[2]=e[2]*i[2],t[3]=e[3]*i[3],t}(i,i,[s,s,1/i[3],s])})),n=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((t=>{const e=function(t,e){var i=e[0],r=e[1],s=e[2],n=i*i+r*r+s*s;return n>0&&(n=1/Math.sqrt(n)),t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t}([],function(t,e,i){var r=e[0],s=e[1],n=e[2],a=i[0],o=i[1],l=i[2];return t[0]=s*l-n*o,t[1]=n*a-r*l,t[2]=r*o-s*a,t}([],No([],s[t[0]],s[t[1]]),No([],s[t[2]],s[t[1]]))),i=-((r=e)[0]*(n=s[t[1]])[0]+r[1]*n[1]+r[2]*n[2]);var r,n;return e.concat(i)}));return new mm(s,n)}}class _m{constructor(t,e){this.min=t,this.max=e,this.center=function(t,e,i){return t[0]=.5*e[0],t[1]=.5*e[1],t[2]=.5*e[2],t}([],function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t[2]=e[2]+i[2],t}([],this.min,this.max))}quadrant(t){const e=[t%2==0,t<2],i=Vo(this.min),r=Vo(this.max);for(let t=0;t=0&&o++;if(0===o)return 0;o!==e.length&&(i=!1)}var r,s;if(i)return 2;for(let e=0;e<3;e++){let i=Number.MAX_VALUE,r=-Number.MAX_VALUE;for(let s=0;sthis.max[e]-this.min[e])return 0}return 1}}class gm{constructor(t=0,e=0,i=0,r=0){if(isNaN(t)||t<0||isNaN(e)||e<0||isNaN(i)||i<0||isNaN(r)||r<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=t,this.bottom=e,this.left=i,this.right=r}interpolate(t,e,i){return null!=e.top&&null!=t.top&&(this.top=Ze.number(t.top,e.top,i)),null!=e.bottom&&null!=t.bottom&&(this.bottom=Ze.number(t.bottom,e.bottom,i)),null!=e.left&&null!=t.left&&(this.left=Ze.number(t.left,e.left,i)),null!=e.right&&null!=t.right&&(this.right=Ze.number(t.right,e.right,i)),this}getCenter(t,e){const i=_((this.left+t-this.right)/2,0,t),r=_((this.top+e-this.bottom)/2,0,e);return new a(i,r)}equals(t){return this.top===t.top&&this.bottom===t.bottom&&this.left===t.left&&this.right===t.right}clone(){return new gm(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const ym=85.051129;class xm{constructor(t,e,i,r,s){this.tileSize=512,this._renderWorldCopies=void 0===s||!!s,this._minZoom=t||0,this._maxZoom=e||22,this._minPitch=null==i?0:i,this._maxPitch=null==r?60:r,this.setMaxBounds(),this.width=0,this.height=0,this._center=new fu(0,0),this._elevation=0,this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._edgeInsets=new gm,this._posMatrixCache={},this._alignedPosMatrixCache={},this._fogMatrixCache={},this.minElevationForCurrentTile=0}clone(){const t=new xm(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies);return t.apply(this),t}apply(t){this.tileSize=t.tileSize,this.latRange=t.latRange,this.lngRange=t.lngRange,this.width=t.width,this.height=t.height,this._center=t._center,this._elevation=t._elevation,this.minElevationForCurrentTile=t.minElevationForCurrentTile,this.zoom=t.zoom,this.angle=t.angle,this._fov=t._fov,this._pitch=t._pitch,this._unmodified=t._unmodified,this._edgeInsets=t._edgeInsets.clone(),this._calcMatrices()}get minZoom(){return this._minZoom}set minZoom(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t))}get maxZoom(){return this._maxZoom}set maxZoom(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t))}get minPitch(){return this._minPitch}set minPitch(t){this._minPitch!==t&&(this._minPitch=t,this.pitch=Math.max(this.pitch,t))}get maxPitch(){return this._maxPitch}set maxPitch(t){this._maxPitch!==t&&(this._maxPitch=t,this.pitch=Math.min(this.pitch,t))}get renderWorldCopies(){return this._renderWorldCopies}set renderWorldCopies(t){void 0===t?t=!0:null===t&&(t=!1),this._renderWorldCopies=t}get worldSize(){return this.tileSize*this.scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new a(this.width,this.height)}get bearing(){return-this.angle/Math.PI*180}set bearing(t){const e=-g(t,-180,180)*Math.PI/180;this.angle!==e&&(this._unmodified=!1,this.angle=e,this._calcMatrices(),this.rotationMatrix=function(){var t=new Ao(4);return Ao!=Float32Array&&(t[1]=0,t[2]=0),t[0]=1,t[3]=1,t}(),function(t,e,i){var r=e[0],s=e[1],n=e[2],a=e[3],o=Math.sin(i),l=Math.cos(i);t[0]=r*l+n*o,t[1]=s*l+a*o,t[2]=r*-o+n*l,t[3]=s*-o+a*l}(this.rotationMatrix,this.rotationMatrix,this.angle))}get pitch(){return this._pitch/Math.PI*180}set pitch(t){const e=_(t,this.minPitch,this.maxPitch)/180*Math.PI;this._pitch!==e&&(this._unmodified=!1,this._pitch=e,this._calcMatrices())}get fov(){return this._fov/Math.PI*180}set fov(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices())}get zoom(){return this._zoom}set zoom(t){const e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.tileZoom=Math.max(0,Math.floor(e)),this.scale=this.zoomScale(e),this._constrain(),this._calcMatrices())}get center(){return this._center}set center(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices())}get elevation(){return this._elevation}set elevation(t){t!==this._elevation&&(this._elevation=t,this._constrain(),this._calcMatrices())}get padding(){return this._edgeInsets.toJSON()}set padding(t){this._edgeInsets.equals(t)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,t,1),this._calcMatrices())}get centerPoint(){return this._edgeInsets.getCenter(this.width,this.height)}isPaddingEqual(t){return this._edgeInsets.equals(t)}interpolatePadding(t,e,i){this._unmodified=!1,this._edgeInsets.interpolate(t,e,i),this._constrain(),this._calcMatrices()}coveringZoomLevel(t){const e=(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize));return Math.max(0,e)}getVisibleUnwrappedCoordinates(t){const e=[new Cu(0,t)];if(this._renderWorldCopies){const i=this.pointCoordinate(new a(0,0)),r=this.pointCoordinate(new a(this.width,0)),s=this.pointCoordinate(new a(this.width,this.height)),n=this.pointCoordinate(new a(0,this.height)),o=Math.floor(Math.min(i.x,r.x,s.x,n.x)),l=Math.floor(Math.max(i.x,r.x,s.x,n.x)),c=1;for(let i=o-c;i<=l+c;i++)0!==i&&e.push(new Cu(i,t))}return e}coveringTiles(t){var e,i;let r=this.coveringZoomLevel(t);const s=r;if(void 0!==t.minzoom&&rt.maxzoom&&(r=t.maxzoom);const n=this.pointCoordinate(this.getCameraPoint()),a=wu.fromLngLat(this.center),o=Math.pow(2,r),l=[o*n.x,o*n.y,0],c=[o*a.x,o*a.y,0],h=mm.fromInvProjectionMatrix(this.invModelViewProjectionMatrix,this.worldSize,r);let u=t.minzoom||0;!t.terrain&&this.pitch<=60&&this._edgeInsets.top<.1&&(u=r);const d=t.terrain?2/Math.min(this.tileSize,t.tileSize)*this.tileSize:3,p=t=>({aabb:new _m([t*o,0,0],[(t+1)*o,o,0]),zoom:0,x:0,y:0,wrap:t,fullyVisible:!1}),f=[],m=[],_=r,g=t.reparseOverscaled?s:r;if(this._renderWorldCopies)for(let t=1;t<=3;t++)f.push(p(-t)),f.push(p(t));for(f.push(p(0));f.length>0;){const r=f.pop(),s=r.x,n=r.y;let a=r.fullyVisible;if(!a){const t=r.aabb.intersects(h);if(0===t)continue;a=2===t}const o=t.terrain?l:c,p=r.aabb.distanceX(o),y=r.aabb.distanceY(o),x=Math.max(Math.abs(p),Math.abs(y));if(r.zoom===_||x>d+(1<<_-r.zoom)-2&&r.zoom>=u){const t=_-r.zoom,e=l[0]-.5-(s<>1),h=r.zoom+1;let u=r.aabb.quadrant(o);if(t.terrain){const s=new zu(h,r.wrap,h,l,c),n=t.terrain.getMinMaxElevation(s),a=null!==(e=n.minElevation)&&void 0!==e?e:this.elevation,o=null!==(i=n.maxElevation)&&void 0!==i?i:this.elevation;u=new _m([u.min[0],u.min[1],a],[u.max[0],u.max[1],o])}f.push({aabb:u,zoom:h,x:l,y:c,wrap:r.wrap,fullyVisible:a})}}return m.sort(((t,e)=>t.distanceSq-e.distanceSq)).map((t=>t.tileID))}resize(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(t){return Math.pow(2,t)}scaleZoom(t){return Math.log(t)/Math.LN2}project(t){const e=_(t.lat,-85.051129,ym);return new a(yu(t.lng)*this.worldSize,xu(e)*this.worldSize)}unproject(t){return new wu(t.x/this.worldSize,t.y/this.worldSize).toLngLat()}get point(){return this.project(this.center)}getCameraPosition(){return{lngLat:this.pointLocation(this.getCameraPoint()),altitude:Math.cos(this._pitch)*this.cameraToCenterDistance/this._pixelPerMeter+this.elevation}}recalculateZoom(t){const e=this.elevation,i=Math.cos(this._pitch)*this.cameraToCenterDistance/this._pixelPerMeter,r=this.pointLocation(this.centerPoint,t),s=t.getElevationForLngLatZoom(r,this.tileZoom);if(!(this.elevation-s))return;const n=i+e-s,a=Math.cos(this._pitch)*this.cameraToCenterDistance/n/vu(1,r.lat),o=this.scaleZoom(a/this.tileSize);this._elevation=s,this._center=r,this.zoom=o}setLocationAtPoint(t,e){const i=this.pointCoordinate(e),r=this.pointCoordinate(this.centerPoint),s=this.locationCoordinate(t),n=new wu(s.x-(i.x-r.x),s.y-(i.y-r.y));this.center=this.coordinateLocation(n),this._renderWorldCopies&&(this.center=this.center.wrap())}locationPoint(t,e){return e?this.coordinatePoint(this.locationCoordinate(t),e.getElevationForLngLatZoom(t,this.tileZoom),this.pixelMatrix3D):this.coordinatePoint(this.locationCoordinate(t))}pointLocation(t,e){return this.coordinateLocation(this.pointCoordinate(t,e))}locationCoordinate(t){return wu.fromLngLat(t)}coordinateLocation(t){return t&&t.toLngLat()}pointCoordinate(t,e){if(e){const i=e.pointCoordinate(t);if(null!=i)return i}const i=[t.x,t.y,0,1],r=[t.x,t.y,1,1];jo(i,i,this.pixelMatrixInverse),jo(r,r,this.pixelMatrixInverse);const s=i[3],n=r[3],a=i[1]/s,o=r[1]/n,l=i[2]/s,c=r[2]/n,h=l===c?0:(0-l)/(c-l);return new wu(Ze.number(i[0]/s,r[0]/n,h)/this.worldSize,Ze.number(a,o,h)/this.worldSize)}coordinatePoint(t,e=0,i=this.pixelMatrix){const r=[t.x*this.worldSize,t.y*this.worldSize,e,1];return jo(r,r,i),new a(r[0]/r[3],r[1]/r[3])}getBounds(){const t=Math.max(0,this.height/2-this.getHorizon());return(new mu).extend(this.pointLocation(new a(0,t))).extend(this.pointLocation(new a(this.width,t))).extend(this.pointLocation(new a(this.width,this.height))).extend(this.pointLocation(new a(0,this.height)))}getMaxBounds(){return this.latRange&&2===this.latRange.length&&this.lngRange&&2===this.lngRange.length?new mu([this.lngRange[0],this.latRange[0]],[this.lngRange[1],this.latRange[1]]):null}getHorizon(){return Math.tan(Math.PI/2-this._pitch)*this.cameraToCenterDistance*.85}setMaxBounds(t){t?(this.lngRange=[t.getWest(),t.getEast()],this.latRange=[t.getSouth(),t.getNorth()],this._constrain()):(this.lngRange=null,this.latRange=[-85.051129,ym])}calculateTileMatrix(t){const e=t.canonical,i=this.worldSize/this.zoomScale(e.z),r=e.x+Math.pow(2,e.z)*t.wrap,s=zo(new Float64Array(16));return ko(s,s,[r*i,e.y*i,0]),Do(s,s,[i/to,i/to,1]),s}calculatePosMatrix(t,e=!1){const i=t.key,r=e?this._alignedPosMatrixCache:this._posMatrixCache;if(r[i])return r[i];const s=this.calculateTileMatrix(t);return Mo(s,e?this.alignedModelViewProjectionMatrix:this.modelViewProjectionMatrix,s),r[i]=new Float32Array(s),r[i]}calculateFogMatrix(t){const e=t.key,i=this._fogMatrixCache;if(i[e])return i[e];const r=this.calculateTileMatrix(t);return Mo(r,this.fogMatrix,r),i[e]=new Float32Array(r),i[e]}customLayerMatrix(){return this.mercatorMatrix.slice()}getConstrained(t,e){e=_(+e,this.minZoom,this.maxZoom);const i={center:new fu(t.lng,t.lat),zoom:e};let r=this.lngRange;if(!this._renderWorldCopies&&null===r){const t=180-1e-10;r=[-t,t]}const s=this.tileSize*this.zoomScale(i.zoom);let n=0,o=s,l=0,c=s,h=0,u=0;const{x:d,y:p}=this.size;if(this.latRange){const t=this.latRange;n=xu(t[1])*s,o=xu(t[0])*s,o-no&&(x=o-t)}if(r){const t=(l+c)/2;let e=f;this._renderWorldCopies&&(e=g(f,t-s/2,t+s/2));const i=d/2;e-ic&&(y=c-i)}if(void 0!==y||void 0!==x){const t=new a(null!=y?y:f,null!=x?x:m);i.center=this.unproject.call({worldSize:s},t).wrap()}return i}_constrain(){if(!this.center||!this.width||!this.height||this._constraining)return;this._constraining=!0;const t=this._unmodified,{center:e,zoom:i}=this.getConstrained(this.center,this.zoom);this.center=e,this.zoom=i,this._unmodified=t,this._constraining=!1}_calcMatrices(){if(!this.height)return;const t=this.centerOffset,e=this.point.x,i=this.point.y;this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height,this._pixelPerMeter=vu(1,this.center.lat)*this.worldSize;let r=zo(new Float64Array(16));Do(r,r,[this.width/2,-this.height/2,1]),ko(r,r,[1,-1,0]),this.labelPlaneMatrix=r,r=zo(new Float64Array(16)),Do(r,r,[1,-1,1]),ko(r,r,[-1,-1,0]),Do(r,r,[2/this.width,2/this.height,1]),this.glCoordMatrix=r;const s=this.cameraToCenterDistance+this._elevation*this._pixelPerMeter/Math.cos(this._pitch),n=Math.min(this.elevation,this.minElevationForCurrentTile),a=s-n*this._pixelPerMeter/Math.cos(this._pitch),o=n<0?a:s,l=Math.PI/2+this._pitch,c=this._fov*(.5+t.y/this.height),h=Math.sin(c)*o/Math.sin(_(Math.PI-l-c,.01,Math.PI-.01)),u=this.getHorizon(),d=2*Math.atan(u/this.cameraToCenterDistance)*(.5+t.y/(2*u)),p=Math.sin(d)*o/Math.sin(_(Math.PI-l-d,.01,Math.PI-.01)),f=Math.min(h,p);this.farZ=1.01*(Math.cos(Math.PI/2-this._pitch)*f+o),this.nearZ=this.height/50,r=new Float64Array(16),Bo(r,this._fov,this.width/this.height,this.nearZ,this.farZ),r[8]=2*-t.x/this.width,r[9]=2*t.y/this.height,this.projectionMatrix=Co(r),Do(r,r,[1,-1,1]),ko(r,r,[0,0,-this.cameraToCenterDistance]),Lo(r,r,this._pitch),Ro(r,r,this.angle),ko(r,r,[-e,-i,0]),this.mercatorMatrix=Do([],r,[this.worldSize,this.worldSize,this.worldSize]),Do(r,r,[1,1,this._pixelPerMeter]),this.pixelMatrix=Mo(new Float64Array(16),this.labelPlaneMatrix,r),ko(r,r,[0,0,-this.elevation]),this.modelViewProjectionMatrix=r,this.invModelViewProjectionMatrix=Po([],r),this.fogMatrix=new Float64Array(16),Bo(this.fogMatrix,this._fov,this.width/this.height,s,this.farZ),this.fogMatrix[8]=2*-t.x/this.width,this.fogMatrix[9]=2*t.y/this.height,Do(this.fogMatrix,this.fogMatrix,[1,-1,1]),ko(this.fogMatrix,this.fogMatrix,[0,0,-this.cameraToCenterDistance]),Lo(this.fogMatrix,this.fogMatrix,this._pitch),Ro(this.fogMatrix,this.fogMatrix,this.angle),ko(this.fogMatrix,this.fogMatrix,[-e,-i,0]),Do(this.fogMatrix,this.fogMatrix,[1,1,this._pixelPerMeter]),ko(this.fogMatrix,this.fogMatrix,[0,0,-this.elevation]),this.pixelMatrix3D=Mo(new Float64Array(16),this.labelPlaneMatrix,r);const m=this.width%2/2,g=this.height%2/2,y=Math.cos(this.angle),x=Math.sin(this.angle),v=e-Math.round(e)+y*m+x*g,b=i-Math.round(i)+y*g+x*m,w=new Float64Array(r);if(ko(w,w,[v>.5?v-1:v,b>.5?b-1:b,0]),this.alignedModelViewProjectionMatrix=w,r=Po(new Float64Array(16),this.pixelMatrix),!r)throw new Error("failed to invert matrix");this.pixelMatrixInverse=r,this._posMatrixCache={},this._alignedPosMatrixCache={},this._fogMatrixCache={}}maxPitchScaleFactor(){if(!this.pixelMatrixInverse)return 1;const t=this.pointCoordinate(new a(0,0)),e=[t.x*this.worldSize,t.y*this.worldSize,0,1];return jo(e,e,this.pixelMatrix)[3]/this.cameraToCenterDistance}getCameraPoint(){const t=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new a(0,t))}getCameraQueryGeometry(t){const e=this.getCameraPoint();if(1===t.length)return[t[0],e];{let i=e.x,r=e.y,s=e.x,n=e.y;for(const e of t)i=Math.min(i,e.x),r=Math.min(r,e.y),s=Math.max(s,e.x),n=Math.max(n,e.y);return[new a(i,r),new a(s,r),new a(s,n),new a(i,n),new a(i,r)]}}lngLatToCameraDepth(t,e){const i=this.locationCoordinate(t),r=[i.x*this.worldSize,i.y*this.worldSize,e,1];return jo(r,r,this.modelViewProjectionMatrix),r[2]/r[3]}}function vm(t,e){let i,r=!1,s=null,n=null;const a=()=>{s=null,r&&(t.apply(n,i),s=setTimeout(a,e),r=!1)};return(...t)=>(r=!0,n=this,i=t,s||a(),s)}class bm{constructor(t){this._getCurrentHash=()=>{const t=window.location.hash.replace("#","");if(this._hashName){let e;return t.split("&").map((t=>t.split("="))).forEach((t=>{t[0]===this._hashName&&(e=t)})),(e&&e[1]||"").split("/")}return t.split("/")},this._onHashChange=()=>{const t=this._getCurrentHash();if(t.length>=3&&!t.some((t=>isNaN(t)))){const e=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(t[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:e,pitch:+(t[4]||0)}),!0}return!1},this._updateHashUnthrottled=()=>{const t=window.location.href.replace(/(#.+)?$/,this.getHashString());window.history.replaceState(window.history.state,null,t)},this._removeHash=()=>{const t=this._getCurrentHash();if(0===t.length)return;const e=t.join("/");let i=e;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${e}`);let r=window.location.hash.replace(i,"");r.startsWith("#&")?r=r.slice(0,1)+r.slice(2):"#"===r&&(r="");let s=window.location.href.replace(/(#.+)?$/,r);s=s.replace("&&","&"),window.history.replaceState(window.history.state,null,s)},this._updateHash=vm(this._updateHashUnthrottled,300),this._hashName=t&&encodeURIComponent(t)}addTo(t){return this._map=t,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(t){const e=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,r=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),s=Math.pow(10,r),n=Math.round(e.lng*s)/s,a=Math.round(e.lat*s)/s,o=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=t?`/${n}/${a}/${i}`:`${i}/${a}/${n}`,(o||l)&&(c+="/"+Math.round(10*o)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const t=this._hashName;let e=!1;const i=window.location.hash.slice(1).split("&").map((i=>{const r=i.split("=")[0];return r===t?(e=!0,`${r}=${c}`):i})).filter((t=>t));return e||i.push(`${t}=${c}`),`#${i.join("&")}`}return`#${c}`}}const wm={linearity:.3,easing:f(0,0,.3,1)},Tm=y({deceleration:2500,maxSpeed:1400},wm),Sm=y({deceleration:20,maxSpeed:1400},wm),Im=y({deceleration:1e3,maxSpeed:360},wm),Am=y({deceleration:1e3,maxSpeed:90},wm);class Em{constructor(t){this._map=t,this.clear()}clear(){this._inertiaBuffer=[]}record(t){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:F.now(),settings:t})}_drainInertiaBuffer(){const t=this._inertiaBuffer,e=F.now();for(;t.length>0&&e-t[0].time>160;)t.shift()}_onMoveEnd(t){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const e={zoom:0,bearing:0,pitch:0,pan:new a(0,0),pinchAround:void 0,around:void 0};for(const{settings:t}of this._inertiaBuffer)e.zoom+=t.zoomDelta||0,e.bearing+=t.bearingDelta||0,e.pitch+=t.pitchDelta||0,t.panDelta&&e.pan._add(t.panDelta),t.around&&(e.around=t.around),t.pinchAround&&(e.pinchAround=t.pinchAround);const i=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,r={};if(e.pan.mag()){const s=zm(e.pan.mag(),i,y({},Tm,t||{}));r.offset=e.pan.mult(s.amount/e.pan.mag()),r.center=this._map.transform.center,Cm(r,s)}if(e.zoom){const t=zm(e.zoom,i,Sm);r.zoom=this._map.transform.zoom+t.amount,Cm(r,t)}if(e.bearing){const t=zm(e.bearing,i,Im);r.bearing=this._map.transform.bearing+_(t.amount,-179,179),Cm(r,t)}if(e.pitch){const t=zm(e.pitch,i,Am);r.pitch=this._map.transform.pitch+t.amount,Cm(r,t)}if(r.zoom||r.bearing){const t=void 0===e.pinchAround?e.around:e.pinchAround;r.around=t?this._map.unproject(t):this._map.getCenter()}return this.clear(),y(r,{noMoveStart:!0})}}function Cm(t,e){(!t.duration||t.duratione.unproject(t))),o=s.reduce(((t,e,i,r)=>t.add(e.div(r.length))),new a(0,0));super(t,{points:s,point:o,lngLats:n,lngLat:e.unproject(o),originalEvent:i}),this._defaultPrevented=!1}}class km extends rt{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(t,e,i){super(t,{originalEvent:i}),this._defaultPrevented=!1}}class Dm{constructor(t,e){this._map=t,this._clickTolerance=e.clickTolerance}reset(){delete this._mousedownPos}wheel(t){return this._firePreventable(new km(t.type,this._map,t))}mousedown(t,e){return this._mousedownPos=e,this._firePreventable(new Pm(t.type,this._map,t))}mouseup(t){this._map.fire(new Pm(t.type,this._map,t))}click(t,e){this._mousedownPos&&this._mousedownPos.dist(e)>=this._clickTolerance||this._map.fire(new Pm(t.type,this._map,t))}dblclick(t){return this._firePreventable(new Pm(t.type,this._map,t))}mouseover(t){this._map.fire(new Pm(t.type,this._map,t))}mouseout(t){this._map.fire(new Pm(t.type,this._map,t))}touchstart(t){return this._firePreventable(new Mm(t.type,this._map,t))}touchmove(t){this._map.fire(new Mm(t.type,this._map,t))}touchend(t){this._map.fire(new Mm(t.type,this._map,t))}touchcancel(t){this._map.fire(new Mm(t.type,this._map,t))}_firePreventable(t){if(this._map.fire(t),t.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Lm{constructor(t){this._map=t}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent}mousemove(t){this._map.fire(new Pm(t.type,this._map,t))}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Pm("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(t){this._delayContextMenu?this._contextMenuEvent=t:this._ignoreContextMenu||this._map.fire(new Pm(t.type,this._map,t)),this._map.listens("contextmenu")&&t.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Rm{constructor(t){this._map=t}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return{lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(t){return this.transform.pointLocation(a.convert(t),this._map.terrain)}}class Bm{constructor(t,e){this._map=t,this._tr=new Rm(t),this._el=t.getCanvasContainer(),this._container=t.getContainer(),this._clickTolerance=e.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(t,e){this.isEnabled()&&t.shiftKey&&0===t.button&&(O.disableDrag(),this._startPos=this._lastPos=e,this._active=!0)}mousemoveWindow(t,e){if(!this._active)return;const i=e;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)t.fitScreenCoordinates(i,r,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",t)}keydown(t){this._active&&27===t.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",t))}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(O.remove(this._box),this._box=null),O.enableDrag(),delete this._startPos,delete this._lastPos}_fireEvent(t,e){return this._map.fire(new rt(t,{originalEvent:e}))}}function Fm(t,e){if(t.length!==e.length)throw new Error(`The number of touches and points are not equal - touches ${t.length}, points ${e.length}`);const i={};for(let r=0;rthis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=t.timeStamp),i.length===this.numTouches&&(this.centroid=function(t){const e=new a(0,0);for(const i of t)e._add(i);return e.div(t.length)}(e),this.touches=Fm(i,e)))}touchmove(t,e,i){if(this.aborted||!this.centroid)return;const r=Fm(i,e);for(const t in this.touches){const e=r[t];(!e||e.dist(this.touches[t])>30)&&(this.aborted=!0)}}touchend(t,e,i){if((!this.centroid||t.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const t=!this.aborted&&this.centroid;if(this.reset(),t)return t}}}class Vm{constructor(t){this.singleTap=new Om(t),this.numTaps=t.numTaps,this.reset()}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset()}touchstart(t,e,i){this.singleTap.touchstart(t,e,i)}touchmove(t,e,i){this.singleTap.touchmove(t,e,i)}touchend(t,e,i){const r=this.singleTap.touchend(t,e,i);if(r){const e=t.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(r)<30;if(e&&i||this.reset(),this.count++,this.lastTime=t.timeStamp,this.lastTap=r,this.count===this.numTaps)return this.reset(),r}}}class Um{constructor(t){this._tr=new Rm(t),this._zoomIn=new Vm({numTouches:1,numTaps:2}),this._zoomOut=new Vm({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(t,e,i){this._zoomIn.touchstart(t,e,i),this._zoomOut.touchstart(t,e,i)}touchmove(t,e,i){this._zoomIn.touchmove(t,e,i),this._zoomOut.touchmove(t,e,i)}touchend(t,e,i){const r=this._zoomIn.touchend(t,e,i),s=this._zoomOut.touchend(t,e,i),n=this._tr;return r?(this._active=!0,t.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:e=>e.easeTo({duration:300,zoom:n.zoom+1,around:n.unproject(r)},{originalEvent:t})}):s?(this._active=!0,t.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:e=>e.easeTo({duration:300,zoom:n.zoom-1,around:n.unproject(s)},{originalEvent:t})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Nm{constructor(t){this._enabled=!!t.enable,this._moveStateManager=t.moveStateManager,this._clickTolerance=t.clickTolerance||1,this._moveFunction=t.move,this._activateOnStart=!!t.activateOnStart,t.assignEvents(this),this.reset()}reset(t){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(t)}_move(...t){const e=this._moveFunction(...t);if(e.bearingDelta||e.pitchDelta||e.around||e.panDelta)return this._active=!0,e}dragStart(t,e){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(t)&&(this._moveStateManager.startMove(t),this._lastPoint=e.length?e[0]:e,this._activateOnStart&&this._lastPoint&&(this._active=!0))}dragMove(t,e){if(!this.isEnabled())return;const i=this._lastPoint;if(!i)return;if(t.preventDefault(),!this._moveStateManager.isValidMoveEvent(t))return void this.reset(t);const r=e.length?e[0]:e;return!this._moved&&r.dist(i){t.mousedown=t.dragStart,t.mousemoveWindow=t.dragMove,t.mouseup=t.dragEnd,t.contextmenu=t=>{t.preventDefault()}},Gm=({enable:t,clickTolerance:e,bearingDegreesPerPixelMoved:i=.8})=>{const r=new $m({checkCorrectEvent:t=>0===O.mouseButton(t)&&t.ctrlKey||2===O.mouseButton(t)});return new Nm({clickTolerance:e,move:(t,e)=>({bearingDelta:(e.x-t.x)*i}),moveStateManager:r,enable:t,assignEvents:Zm})},Wm=({enable:t,clickTolerance:e,pitchDegreesPerPixelMoved:i=-.5})=>{const r=new $m({checkCorrectEvent:t=>0===O.mouseButton(t)&&t.ctrlKey||2===O.mouseButton(t)});return new Nm({clickTolerance:e,move:(t,e)=>({pitchDelta:(e.y-t.y)*i}),moveStateManager:r,enable:t,assignEvents:Zm})};class Hm{constructor(t,e){this._clickTolerance=t.clickTolerance||1,this._map=e,this.reset()}reset(){this._active=!1,this._touches={},this._sum=new a(0,0)}_shouldBePrevented(t){return t<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(t,e,i){return this._calculateTransform(t,e,i)}touchmove(t,e,i){if(this._active){if(!this._shouldBePrevented(i.length))return t.preventDefault(),this._calculateTransform(t,e,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",t)}}touchend(t,e,i){this._calculateTransform(t,e,i),this._active&&this._shouldBePrevented(i.length)&&this.reset()}touchcancel(){this.reset()}_calculateTransform(t,e,i){i.length>0&&(this._active=!0);const r=Fm(i,e),s=new a(0,0),n=new a(0,0);let o=0;for(const t in r){const e=r[t],i=this._touches[t];i&&(s._add(e),n._add(e.sub(i)),o++,r[t]=e)}if(this._touches=r,this._shouldBePrevented(o)||!n.mag())return;const l=n.div(o);return this._sum._add(l),this._sum.mag()Math.abs(t.x)}class i_ extends Xm{constructor(t){super(),this._currentTouchCount=0,this._map=t}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints}touchstart(t,e,i){super.touchstart(t,e,i),this._currentTouchCount=i.length}_start(t){this._lastPoints=t,e_(t[0].sub(t[1]))&&(this._valid=!1)}_move(t,e,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const r=t[0].sub(this._lastPoints[0]),s=t[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(r,s,i.timeStamp),this._valid?(this._lastPoints=t,this._active=!0,{pitchDelta:(r.y+s.y)/2*-.5}):void 0}gestureBeginsVertically(t,e,i){if(void 0!==this._valid)return this._valid;const r=t.mag()>=2,s=e.mag()>=2;if(!r&&!s)return;if(!r||!s)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const n=t.y>0==e.y>0;return e_(t)&&e_(e)&&n}}const r_={panStep:100,bearingStep:15,pitchStep:10};class s_{constructor(t){this._tr=new Rm(t);const e=r_;this._panStep=e.panStep,this._bearingStep=e.bearingStep,this._pitchStep=e.pitchStep,this._rotationDisabled=!1}reset(){this._active=!1}keydown(t){if(t.altKey||t.ctrlKey||t.metaKey)return;let e=0,i=0,r=0,s=0,n=0;switch(t.keyCode){case 61:case 107:case 171:case 187:e=1;break;case 189:case 109:case 173:e=-1;break;case 37:t.shiftKey?i=-1:(t.preventDefault(),s=-1);break;case 39:t.shiftKey?i=1:(t.preventDefault(),s=1);break;case 38:t.shiftKey?r=1:(t.preventDefault(),n=-1);break;case 40:t.shiftKey?r=-1:(t.preventDefault(),n=1);break;default:return}return this._rotationDisabled&&(i=0,r=0),{cameraAnimation:a=>{const o=this._tr;a.easeTo({duration:300,easeId:"keyboardHandler",easing:n_,zoom:e?Math.round(o.zoom)+e*(t.shiftKey?2:1):o.zoom,bearing:o.bearing+i*this._bearingStep,pitch:o.pitch+r*this._pitchStep,offset:[-s*this._panStep,-n*this._panStep],center:o.center},{originalEvent:t})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function n_(t){return t*(2-t)}const a_=4.000244140625;class o_{constructor(t,e){this._onTimeout=t=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(t)},this._map=t,this._tr=new Rm(t),this._triggerRenderFrame=e,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=.0022222222222222222}setZoomRate(t){this._defaultZoomRate=t}setWheelZoomRate(t){this._wheelZoomRate=t}isEnabled(){return!!this._enabled}isActive(){return!!this._active||void 0!==this._finishTimeout}isZooming(){return!!this._zooming}enable(t){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!t&&"center"===t.around)}disable(){this.isEnabled()&&(this._enabled=!1)}_shouldBePrevented(t){return!!this._map.cooperativeGestures.isEnabled()&&!(t.ctrlKey||this._map.cooperativeGestures.isBypassed(t))}wheel(t){if(!this.isEnabled())return;if(this._shouldBePrevented(t))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",t);let e=t.deltaMode===WheelEvent.DOM_DELTA_LINE?40*t.deltaY:t.deltaY;const i=F.now(),r=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==e&&e%a_==0?this._type="wheel":0!==e&&Math.abs(e)<4?this._type="trackpad":r>400?(this._type=null,this._lastValue=e,this._timeout=setTimeout(this._onTimeout,40,t)):this._type||(this._type=Math.abs(r*e)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,e+=this._lastValue)),t.shiftKey&&e&&(e/=4),this._type&&(this._lastWheelEvent=t,this._delta-=e,this._active||this._start(t)),t.preventDefault()}_start(t){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const e=O.mousePos(this._map.getCanvas(),t),i=this._tr;this._around=e.y>i.transform.height/2-i.transform.getHorizon()?fu.convert(this._aroundCenter?i.center:i.unproject(e)):fu.convert(i.center),this._aroundPoint=i.transform.locationPoint(this._around),this._frameId||(this._frameId=!0,this._triggerRenderFrame())}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const t=this._tr.transform;if(0!==this._delta){const e="wheel"===this._type&&Math.abs(this._delta)>a_?this._wheelZoomRate:this._defaultZoomRate;let i=2/(1+Math.exp(-Math.abs(this._delta*e)));this._delta<0&&0!==i&&(i=1/i);const r="number"==typeof this._targetZoom?t.zoomScale(this._targetZoom):t.scale;this._targetZoom=Math.min(t.maxZoom,Math.max(t.minZoom,t.scaleZoom(r*i))),"wheel"===this._type&&(this._startZoom=t.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0}const e="number"==typeof this._targetZoom?this._targetZoom:t.zoom,i=this._startZoom,r=this._easing;let s,n=!1;const a=F.now()-this._lastWheelEventTime;if("wheel"===this._type&&i&&r&&a){const t=Math.min(a/200,1),o=r(t);s=Ze.number(i,e,o),t<1?this._frameId||(this._frameId=!0):n=!0}else s=e,n=!0;return this._active=!0,n&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout}),200)),{noInertia:!0,needsRenderFrame:!n,zoomDelta:s-t.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(t){let e=m;if(this._prevEase){const t=this._prevEase,i=(F.now()-t.start)/t.duration,r=t.easing(i+.01)-t.easing(i),s=.27/Math.sqrt(r*r+1e-4)*.01;e=f(s,Math.sqrt(.0729-s*s),.25,1)}return this._prevEase={start:F.now(),duration:t,easing:e},e}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout)}}class l_{constructor(t,e){this._clickZoom=t,this._tapZoom=e}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class c_{constructor(t){this._tr=new Rm(t),this.reset()}reset(){this._active=!1}dblclick(t,e){return t.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(t.shiftKey?-1:1),around:this._tr.unproject(e)},{originalEvent:t})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class h_{constructor(){this._tap=new Vm({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset()}touchstart(t,e,i){if(!this._swipePoint)if(this._tapTime){const r=e[0],s=t.timeStamp-this._tapTime<500,n=this._tapPoint.dist(r)<30;s&&n?i.length>0&&(this._swipePoint=r,this._swipeTouch=i[0].identifier):this.reset()}else this._tap.touchstart(t,e,i)}touchmove(t,e,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const r=e[0],s=r.y-this._swipePoint.y;return this._swipePoint=r,t.preventDefault(),this._active=!0,{zoomDelta:s/128}}}else this._tap.touchmove(t,e,i)}touchend(t,e,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else{const r=this._tap.touchend(t,e,i);r&&(this._tapTime=t.timeStamp,this._tapPoint=r)}}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class u_{constructor(t,e,i){this._el=t,this._mousePan=e,this._touchPan=i}enable(t){this._inertiaOptions=t||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan")}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class d_{constructor(t,e,i){this._pitchWithRotate=t.pitchWithRotate,this._mouseRotate=e,this._mousePitch=i}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}}class p_{constructor(t,e,i,r){this._el=t,this._touchZoom=e,this._touchRotate=i,this._tapDragZoom=r,this._rotationDisabled=!1,this._enabled=!0}enable(t){this._touchZoom.enable(t),this._rotationDisabled||this._touchRotate.enable(t),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate")}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable()}}class f_{constructor(t,e){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=t,this._options=e,this._enabled=!1}isActive(){return!1}reset(){}_setupUI(){if(this._container)return;const t=this._map.getCanvasContainer();t.classList.add("maplibregl-cooperative-gestures"),this._container=O.create("div","maplibregl-cooperative-gesture-screen",t);let e=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(e=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),r=document.createElement("div");r.className="maplibregl-desktop-message",r.textContent=e,this._container.appendChild(r);const s=document.createElement("div");s.className="maplibregl-mobile-message",s.textContent=i,this._container.appendChild(s),this._container.setAttribute("aria-hidden","true")}_destroyUI(){this._container&&(O.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container}enable(){this._setupUI(),this._enabled=!0}disable(){this._enabled=!1,this._destroyUI()}isEnabled(){return this._enabled}isBypassed(t){return t[this._bypassKey]}notifyGestureBlocked(t,e){this._enabled&&(this._map.fire(new rt("cooperativegestureprevented",{gestureType:t,originalEvent:e})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show")}),100))}}const m_=t=>t.zoom||t.drag||t.pitch||t.rotate;class __ extends rt{}function g_(t){return t.panDelta&&t.panDelta.mag()||t.zoomDelta||t.bearingDelta||t.pitchDelta}class y_{constructor(t,e){this.handleWindowEvent=t=>{this.handleEvent(t,`${t.type}Window`)},this.handleEvent=(t,e)=>{if("blur"===t.type)return void this.stop(!0);this._updatingCamera=!0;const i="renderFrame"===t.type?void 0:t,r={needsRenderFrame:!1},s={},n={},a=t.touches,o=a?this._getMapTouches(a):void 0,l=o?O.touchPos(this._map.getCanvas(),o):O.mousePos(this._map.getCanvas(),t);for(const{handlerName:a,handler:c,allowed:h}of this._handlers){if(!c.isEnabled())continue;let u;this._blockedByActive(n,h,a)?c.reset():c[e||t.type]&&(u=c[e||t.type](t,l,o),this.mergeHandlerResult(r,s,u,a,i),u&&u.needsRenderFrame&&this._triggerRenderFrame()),(u||c.isActive())&&(n[a]=c)}const c={};for(const t in this._previousActiveHandlers)n[t]||(c[t]=i);this._previousActiveHandlers=n,(Object.keys(c).length||g_(r))&&(this._changes.push([r,s,c]),this._triggerRenderFrame()),(Object.keys(n).length||g_(r))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:h}=r;h&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],h(this._map))},this._map=t,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Em(t),this._bearingSnap=e.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(e);const i=this._el;this._listeners=[[i,"touchstart",{passive:!0}],[i,"touchmove",{passive:!1}],[i,"touchend",void 0],[i,"touchcancel",void 0],[i,"mousedown",void 0],[i,"mousemove",void 0],[i,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[i,"mouseover",void 0],[i,"mouseout",void 0],[i,"dblclick",void 0],[i,"click",void 0],[i,"keydown",{capture:!1}],[i,"keyup",void 0],[i,"wheel",{passive:!1}],[i,"contextmenu",void 0],[window,"blur",void 0]];for(const[t,e,i]of this._listeners)O.addEventListener(t,e,t===document?this.handleWindowEvent:this.handleEvent,i)}destroy(){for(const[t,e,i]of this._listeners)O.removeEventListener(t,e,t===document?this.handleWindowEvent:this.handleEvent,i)}_addDefaultHandlers(t){const e=this._map,i=e.getCanvasContainer();this._add("mapEvent",new Dm(e,t));const r=e.boxZoom=new Bm(e,t);this._add("boxZoom",r),t.interactive&&t.boxZoom&&r.enable();const s=e.cooperativeGestures=new f_(e,t.cooperativeGestures);this._add("cooperativeGestures",s),t.cooperativeGestures&&s.enable();const n=new Um(e),a=new c_(e);e.doubleClickZoom=new l_(a,n),this._add("tapZoom",n),this._add("clickZoom",a),t.interactive&&t.doubleClickZoom&&e.doubleClickZoom.enable();const o=new h_;this._add("tapDragZoom",o);const l=e.touchPitch=new i_(e);this._add("touchPitch",l),t.interactive&&t.touchPitch&&e.touchPitch.enable(t.touchPitch);const c=Gm(t),h=Wm(t);e.dragRotate=new d_(t,c,h),this._add("mouseRotate",c,["mousePitch"]),this._add("mousePitch",h,["mouseRotate"]),t.interactive&&t.dragRotate&&e.dragRotate.enable();const u=(({enable:t,clickTolerance:e})=>{const i=new $m({checkCorrectEvent:t=>0===O.mouseButton(t)&&!t.ctrlKey});return new Nm({clickTolerance:e,move:(t,e)=>({around:e,panDelta:e.sub(t)}),activateOnStart:!0,moveStateManager:i,enable:t,assignEvents:Zm})})(t),d=new Hm(t,e);e.dragPan=new u_(i,u,d),this._add("mousePan",u),this._add("touchPan",d,["touchZoom","touchRotate"]),t.interactive&&t.dragPan&&e.dragPan.enable(t.dragPan);const p=new t_,f=new Jm;e.touchZoomRotate=new p_(i,f,p,o),this._add("touchRotate",p,["touchPan","touchZoom"]),this._add("touchZoom",f,["touchPan","touchRotate"]),t.interactive&&t.touchZoomRotate&&e.touchZoomRotate.enable(t.touchZoomRotate);const m=e.scrollZoom=new o_(e,(()=>this._triggerRenderFrame()));this._add("scrollZoom",m,["mousePan"]),t.interactive&&t.scrollZoom&&e.scrollZoom.enable(t.scrollZoom);const _=e.keyboard=new s_(e);this._add("keyboard",_),t.interactive&&t.keyboard&&e.keyboard.enable(),this._add("blockableMapEvent",new Lm(e))}_add(t,e,i){this._handlers.push({handlerName:t,handler:e,allowed:i}),this._handlersById[t]=e}stop(t){if(!this._updatingCamera){for(const{handler:t}of this._handlers)t.reset();this._inertia.clear(),this._fireEvents({},{},t),this._changes=[]}}isActive(){for(const{handler:t}of this._handlers)if(t.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return Boolean(m_(this._eventsInProgress))||this.isZooming()}_blockedByActive(t,e,i){for(const r in t)if(r!==i&&(!e||e.indexOf(r)<0))return!0;return!1}_getMapTouches(t){const e=[];for(const i of t)this._el.contains(i.target)&&e.push(i);return e}mergeHandlerResult(t,e,i,r,s){if(!i)return;y(t,i);const n={handlerName:r,originalEvent:i.originalEvent||s};void 0!==i.zoomDelta&&(e.zoom=n),void 0!==i.panDelta&&(e.drag=n),void 0!==i.pitchDelta&&(e.pitch=n),void 0!==i.bearingDelta&&(e.rotate=n)}_applyChanges(){const t={},e={},i={};for(const[r,s,n]of this._changes)r.panDelta&&(t.panDelta=(t.panDelta||new a(0,0))._add(r.panDelta)),r.zoomDelta&&(t.zoomDelta=(t.zoomDelta||0)+r.zoomDelta),r.bearingDelta&&(t.bearingDelta=(t.bearingDelta||0)+r.bearingDelta),r.pitchDelta&&(t.pitchDelta=(t.pitchDelta||0)+r.pitchDelta),void 0!==r.around&&(t.around=r.around),void 0!==r.pinchAround&&(t.pinchAround=r.pinchAround),r.noInertia&&(t.noInertia=r.noInertia),y(e,s),y(i,n);this._updateMapTransform(t,e,i),this._changes=[]}_updateMapTransform(t,e,i){const r=this._map,s=r._getTransformForUpdate(),n=r.terrain;if(!(g_(t)||n&&this._terrainMovement))return this._fireEvents(e,i,!0);let{panDelta:a,zoomDelta:o,bearingDelta:l,pitchDelta:c,around:h,pinchAround:u}=t;void 0!==u&&(h=u),r._stop(!0),h=h||r.transform.centerPoint;const d=s.pointLocation(a?h.sub(a):h);l&&(s.bearing+=l),c&&(s.pitch+=c),o&&(s.zoom+=o),n?this._terrainMovement||!e.drag&&!e.zoom?e.drag&&this._terrainMovement?s.center=s.pointLocation(s.centerPoint.sub(a)):s.setLocationAtPoint(d,h):(this._terrainMovement=!0,this._map._elevationFreeze=!0,s.setLocationAtPoint(d,h)):s.setLocationAtPoint(d,h),r._applyUpdatedTransform(s),this._map._update(),t.noInertia||this._inertia.record(t),this._fireEvents(e,i,!0)}_fireEvents(t,e,i){const r=m_(this._eventsInProgress),s=m_(t),n={};for(const e in t){const{originalEvent:i}=t[e];this._eventsInProgress[e]||(n[`${e}start`]=i),this._eventsInProgress[e]=t[e]}!r&&s&&this._fireEvent("movestart",s.originalEvent);for(const t in n)this._fireEvent(t,n[t]);s&&this._fireEvent("move",s.originalEvent);for(const e in t){const{originalEvent:i}=t[e];this._fireEvent(e,i)}const a={};let o;for(const t in this._eventsInProgress){const{handlerName:i,originalEvent:r}=this._eventsInProgress[t];this._handlersById[i].isActive()||(delete this._eventsInProgress[t],o=e[i]||r,a[`${t}end`]=o)}for(const t in a)this._fireEvent(t,a[t]);const l=m_(this._eventsInProgress),c=(r||s)&&!l;if(c&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const t=this._map._getTransformForUpdate();t.recalculateZoom(this._map.terrain),this._map._applyUpdatedTransform(t)}if(i&&c){this._updatingCamera=!0;const t=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),e=t=>0!==t&&-this._bearingSnap{delete this._frameId,this.handleEvent(new __("renderFrame",{timeStamp:t})),this._applyChanges()}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame())}}class x_ extends nt{constructor(t,e){super(),this._renderFrameCallback=()=>{const t=Math.min((F.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(t)),t<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()},this._moving=!1,this._zooming=!1,this.transform=t,this._bearingSnap=e.bearingSnap,this.on("moveend",(()=>{delete this._requestedCameraState}))}getCenter(){return new fu(this.transform.center.lng,this.transform.center.lat)}setCenter(t,e){return this.jumpTo({center:t},e)}panBy(t,e,i){return t=a.convert(t).mult(-1),this.panTo(this.transform.center,y({offset:t},e),i)}panTo(t,e,i){return this.easeTo(y({center:t},e),i)}getZoom(){return this.transform.zoom}setZoom(t,e){return this.jumpTo({zoom:t},e),this}zoomTo(t,e,i){return this.easeTo(y({zoom:t},e),i)}zoomIn(t,e){return this.zoomTo(this.getZoom()+1,t,e),this}zoomOut(t,e){return this.zoomTo(this.getZoom()-1,t,e),this}getBearing(){return this.transform.bearing}setBearing(t,e){return this.jumpTo({bearing:t},e),this}getPadding(){return this.transform.padding}setPadding(t,e){return this.jumpTo({padding:t},e),this}rotateTo(t,e,i){return this.easeTo(y({bearing:t},e),i)}resetNorth(t,e){return this.rotateTo(0,y({duration:1e3},t),e),this}resetNorthPitch(t,e){return this.easeTo(y({bearing:0,pitch:0,duration:1e3},t),e),this}snapToNorth(t,e){return Math.abs(this.getBearing()){if(this._zooming&&(r.zoom=Ze.number(s,g,i)),this._rotating&&(r.bearing=Ze.number(n,c,i)),this._pitching&&(r.pitch=Ze.number(o,h,i)),this._padding&&(r.interpolatePadding(l,u,i),p=r.centerPoint.add(d)),this.terrain&&!t.freezeElevation&&this._updateElevation(i),w)r.setLocationAtPoint(w,T);else{const t=r.zoomScale(r.zoom-s),e=g>s?Math.min(2,b):Math.max(.5,b),n=Math.pow(e,1-i),a=r.unproject(x.add(v.mult(i*n)).mult(t));r.setLocationAtPoint(r.renderWorldCopies?a.wrap():a,p)}this._applyUpdatedTransform(r),this._fireMoveEvents(e)}),(i=>{this.terrain&&t.freezeElevation&&this._finalizeElevation(),this._afterEase(e,i)}),t),this}_prepareEase(t,e,i={}){this._moving=!0,e||i.moving||this.fire(new rt("movestart",t)),this._zooming&&!i.zooming&&this.fire(new rt("zoomstart",t)),this._rotating&&!i.rotating&&this.fire(new rt("rotatestart",t)),this._pitching&&!i.pitching&&this.fire(new rt("pitchstart",t))}_prepareElevation(t){this._elevationCenter=t,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(t,this.transform.tileZoom),this._elevationFreeze=!0}_updateElevation(t){this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);const e=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(t<1&&e!==this._elevationTarget){const i=this._elevationTarget-this._elevationStart;this._elevationStart+=t*(i-(e-(i*t+this._elevationStart))/(1-t)),this._elevationTarget=e}this.transform.elevation=Ze.number(this._elevationStart,this._elevationTarget,t)}_finalizeElevation(){this._elevationFreeze=!1,this.transform.recalculateZoom(this.terrain)}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(t){const e=t.getCameraPosition(),i=this.terrain.getElevationForLngLatZoom(e.lngLat,t.zoom);if(e.altitudethis._elevateCameraIfInsideTerrain(t))),this.transformCameraUpdate&&e.push((t=>this.transformCameraUpdate(t))),!e.length)return;const i=t.clone();for(const t of e){const e=i.clone(),{center:r,zoom:s,pitch:n,bearing:a,elevation:o}=t(e);r&&(e.center=r),void 0!==s&&(e.zoom=s),void 0!==n&&(e.pitch=n),void 0!==a&&(e.bearing=a),void 0!==o&&(e.elevation=o),i.apply(e)}this.transform.apply(i)}_fireMoveEvents(t){this.fire(new rt("move",t)),this._zooming&&this.fire(new rt("zoom",t)),this._rotating&&this.fire(new rt("rotate",t)),this._pitching&&this.fire(new rt("pitch",t))}_afterEase(t,e){if(this._easeId&&e&&this._easeId===e)return;delete this._easeId;const i=this._zooming,r=this._rotating,s=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,i&&this.fire(new rt("zoomend",t)),r&&this.fire(new rt("rotateend",t)),s&&this.fire(new rt("pitchend",t)),this.fire(new rt("moveend",t))}flyTo(t,e){var i;if(!t.essential&&F.prefersReducedMotion){const i=x(t,["center","zoom","bearing","pitch","around"]);return this.jumpTo(i,e)}this.stop(),t=y({offset:[0,0],speed:1.2,curve:1.42,easing:m},t);const r=this._getTransformForUpdate(),s=r.zoom,n=r.bearing,o=r.pitch,l=r.padding,c="bearing"in t?this._normalizeBearing(t.bearing,n):n,h="pitch"in t?+t.pitch:o,u="padding"in t?t.padding:r.padding,d=a.convert(t.offset);let p=r.centerPoint.add(d);const f=r.pointLocation(p),{center:g,zoom:v}=r.getConstrained(fu.convert(t.center||f),null!==(i=t.zoom)&&void 0!==i?i:s);this._normalizeCenter(g,r);const b=r.zoomScale(v-s),w=r.project(f),T=r.project(g).sub(w);let S=t.curve;const I=Math.max(r.width,r.height),A=I/b,E=T.mag();if("minZoom"in t){const e=_(Math.min(t.minZoom,s,v),r.minZoom,r.maxZoom),i=I/r.zoomScale(e-s);S=Math.sqrt(i/E*2)}const C=S*S;function z(t){const e=(A*A-I*I+(t?-1:1)*C*C*E*E)/(2*(t?A:I)*C*E);return Math.log(Math.sqrt(e*e+1)-e)}function P(t){return(Math.exp(t)-Math.exp(-t))/2}function M(t){return(Math.exp(t)+Math.exp(-t))/2}const k=z(!1);let D=function(t){return M(k)/M(k+S*t)},L=function(t){return I*((M(k)*(P(e=k+S*t)/M(e))-P(k))/C)/E;var e},R=(z(!0)-k)/S;if(Math.abs(E)<1e-6||!isFinite(R)){if(Math.abs(I-A)<1e-6)return this.easeTo(t,e);const i=A0,D=t=>Math.exp(i*S*t)}return t.duration="duration"in t?+t.duration:1e3*R/("screenSpeed"in t?+t.screenSpeed/S:+t.speed),t.maxDuration&&t.duration>t.maxDuration&&(t.duration=0),this._zooming=!0,this._rotating=n!==c,this._pitching=h!==o,this._padding=!r.isPaddingEqual(u),this._prepareEase(e,!1),this.terrain&&this._prepareElevation(g),this._ease((i=>{const a=i*R,f=1/D(a);r.zoom=1===i?v:s+r.scaleZoom(f),this._rotating&&(r.bearing=Ze.number(n,c,i)),this._pitching&&(r.pitch=Ze.number(o,h,i)),this._padding&&(r.interpolatePadding(l,u,i),p=r.centerPoint.add(d)),this.terrain&&!t.freezeElevation&&this._updateElevation(i);const m=1===i?g:r.unproject(w.add(T.mult(L(a))).mult(f));r.setLocationAtPoint(r.renderWorldCopies?m.wrap():m,p),this._applyUpdatedTransform(r),this._fireMoveEvents(e)}),(()=>{this.terrain&&t.freezeElevation&&this._finalizeElevation(),this._afterEase(e)}),t),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_stop(t,e){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const t=this._onEaseEnd;delete this._onEaseEnd,t.call(this,e)}return t||null===(i=this.handlers)||void 0===i||i.stop(!1),this}_ease(t,e,i){!1===i.animate||0===i.duration?(t(1),e()):(this._easeStart=F.now(),this._easeOptions=i,this._onEaseFrame=t,this._onEaseEnd=e,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_normalizeBearing(t,e){t=g(t,-180,180);const i=Math.abs(t-e);return Math.abs(t-360-e)180?-360:i<-180?360:0}queryTerrainElevation(t){return this.terrain?this.terrain.getElevationForLngLatZoom(fu.convert(t),this.transform.tileZoom)-this.transform.elevation:null}}const v_={compact:!0,customAttribution:'MapLibre'};class b_{constructor(t=v_){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")))},this._updateData=t=>{!t||"metadata"!==t.sourceDataType&&"visibility"!==t.sourceDataType&&"style"!==t.dataType&&"terrain"!==t.type||this._updateAttributions()},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"))},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show")},this.options=t}getDefaultPosition(){return"bottom-right"}onAdd(t){return this._map=t,this._compact=this.options.compact,this._container=O.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=O.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=O.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){O.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0}_setElementTitle(t,e){const i=this._map._getUIString(`AttributionControl.${e}`);t.title=i,t.setAttribute("aria-label",i)}_updateAttributions(){if(!this._map.style)return;let t=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?t=t.concat(this.options.customAttribution.map((t=>"string"!=typeof t?"":t))):"string"==typeof this.options.customAttribution&&t.push(this.options.customAttribution)),this._map.style.stylesheet){const t=this._map.style.stylesheet;this.styleOwner=t.owner,this.styleId=t.id}const e=this._map.style.sourceCaches;for(const i in e){const r=e[i];if(r.used||r.usedForTerrain){const e=r.getSource();e.attribution&&t.indexOf(e.attribution)<0&&t.push(e.attribution)}}t=t.filter((t=>String(t).trim())),t.sort(((t,e)=>t.length-e.length)),t=t.filter(((e,i)=>{for(let r=i+1;r=0)return!1;return!0}));const i=t.join(" | ");i!==this._attribHTML&&(this._attribHTML=i,t.length?(this._innerContainer.innerHTML=i,this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null)}}class w_{constructor(t={}){this._updateCompact=()=>{const t=this._container.children;if(t.length){const e=t[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&e.classList.add("maplibregl-compact"):e.classList.remove("maplibregl-compact")}},this.options=t}getDefaultPosition(){return"bottom-left"}onAdd(t){this._map=t,this._compact=this.options&&this.options.compact,this._container=O.create("div","maplibregl-ctrl");const e=O.create("a","maplibregl-ctrl-logo");return e.target="_blank",e.rel="noopener nofollow",e.href="https://maplibre.org/",e.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),e.setAttribute("rel","noopener nofollow"),this._container.appendChild(e),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){O.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0}}class T_{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(t){const e=++this._id;return this._queue.push({callback:t,id:e,cancelled:!1}),e}remove(t){const e=this._currentlyRunning,i=e?this._queue.concat(e):this._queue;for(const e of i)if(e.id===t)return void(e.cancelled=!0)}run(t=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const e=this._currentlyRunning=this._queue;this._queue=[];for(const i of e)if(!i.cancelled&&(i.callback(t),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}var S_;!function(t){t.create="create",t.load="load",t.fullLoad="fullLoad"}(S_||(S_={}));let I_=null,A_=[];const E_=1e3/60,C_="loadTime",z_="fullLoadTime",P_={mark(t){performance.mark(t)},frame(t){const e=t;null!=I_&&A_.push(e-I_),I_=e},clearMetrics(){I_=null,A_=[],performance.clearMeasures(C_),performance.clearMeasures(z_);for(const t in S_)performance.clearMarks(S_[t])},getPerformanceMetrics(){performance.measure(C_,S_.create,S_.load),performance.measure(z_,S_.create,S_.fullLoad);const t=performance.getEntriesByName(C_)[0].duration,e=performance.getEntriesByName(z_)[0].duration,i=A_.length,r=1/(A_.reduce(((t,e)=>t+e),0)/i/1e3),s=A_.filter((t=>t>E_)).reduce(((t,e)=>t+(e-E_)/E_),0);return{loadTime:t,fullLoadTime:e,fps:r,percentDroppedFrames:s/(i+s)*100,totalFrames:i}}};var M_=gn([{name:"a_pos3d",type:"Int16",components:3}]);class k_ extends nt{constructor(t){super(),this.sourceCache=t,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.deltaZoom=1,t.usedForTerrain=!0,t.tileSize=this.tileSize*2**this.deltaZoom}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null}update(t,e){this.sourceCache.update(t,e),this._renderableTilesKeys=[];const i={};for(const r of t.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:e}))i[r.key]=!0,this._renderableTilesKeys.push(r.key),this._tiles[r.key]||(r.posMatrix=new Float64Array(16),Fo(r.posMatrix,0,to,0,to,0,1),this._tiles[r.key]=new Hu(r,this.tileSize));for(const t in this._tiles)i[t]||delete this._tiles[t]}freeRtt(t){for(const e in this._tiles){const i=this._tiles[e];(!t||i.tileID.equals(t)||i.tileID.isChildOf(t)||t.isChildOf(i.tileID))&&(i.rtt=[])}}getRenderableTiles(){return this._renderableTilesKeys.map((t=>this.getTileByID(t)))}getTileByID(t){return this._tiles[t]}getTerrainCoords(t){const e={};for(const i of this._renderableTilesKeys){const r=this._tiles[i].tileID;if(r.canonical.equals(t.canonical)){const r=t.clone();r.posMatrix=new Float64Array(16),Fo(r.posMatrix,0,to,0,to,0,1),e[i]=r}else if(r.canonical.isChildOf(t.canonical)){const s=t.clone();s.posMatrix=new Float64Array(16);const n=r.canonical.z-t.canonical.z,a=r.canonical.x-(r.canonical.x>>n<>n<>n;Fo(s.posMatrix,0,l,0,l,0,1),ko(s.posMatrix,s.posMatrix,[-a*l,-o*l,0]),e[i]=s}else if(t.canonical.isChildOf(r.canonical)){const s=t.clone();s.posMatrix=new Float64Array(16);const n=t.canonical.z-r.canonical.z,a=t.canonical.x-(t.canonical.x>>n<>n<>n;Fo(s.posMatrix,0,to,0,to,0,1),ko(s.posMatrix,s.posMatrix,[a*l,o*l,0]),Do(s.posMatrix,s.posMatrix,[1/2**n,1/2**n,0]),e[i]=s}}return e}getSourceTile(t,e){const i=this.sourceCache._source;let r=t.overscaledZ-this.deltaZoom;if(r>i.maxzoom&&(r=i.maxzoom),r=i.minzoom&&(!s||!s.dem);)s=this.sourceCache.getTileByID(t.scaledTo(r--).key);return s}tilesAfterTime(t=Date.now()){return Object.values(this._tiles).filter((e=>e.timeAdded>=t))}}class D_{constructor(t,e,i){this.painter=t,this.sourceCache=new k_(e),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024}getDEMElevation(t,e,i,r=to){var s;if(!(e>=0&&e=0&&i25||r<0||r>=1||i<0||i>=1)}(e,t.wrap()))return 0;const{tileID:i,mercatorX:r,mercatorY:s}=this._getOverscaledTileIDFromLngLatZoom(t,e);return this.getElevation(i,r%to,s%to,to)}getElevation(t,e,i,r=to){return this.getDEMElevation(t,e,i,r)*this.exaggeration}getTerrainData(t){if(!this._emptyDemTexture){const t=this.painter.context,e=new Qo({width:1,height:1},new Uint8Array(4));this._emptyDepthTexture=new Uh(t,e,t.gl.RGBA,{premultiply:!1}),this._emptyDemUnpack=[0,0,0,0],this._emptyDemTexture=new Uh(t,new Qo({width:1,height:1}),t.gl.RGBA,{premultiply:!1}),this._emptyDemTexture.bind(t.gl.NEAREST,t.gl.CLAMP_TO_EDGE),this._emptyDemMatrix=zo([])}const e=this.sourceCache.getSourceTile(t,!0);if(e&&e.dem&&(!e.demTexture||e.needsTerrainPrepare)){const t=this.painter.context;e.demTexture=this.painter.getTileTexture(e.dem.stride),e.demTexture?e.demTexture.update(e.dem.getPixels(),{premultiply:!1}):e.demTexture=new Uh(t,e.dem.getPixels(),t.gl.RGBA,{premultiply:!1}),e.demTexture.bind(t.gl.NEAREST,t.gl.CLAMP_TO_EDGE),e.needsTerrainPrepare=!1}const i=e&&e+e.tileID.key+t.key;if(i&&!this._demMatrixCache[i]){const i=this.sourceCache.sourceCache._source.maxzoom;let r=t.canonical.z-e.tileID.canonical.z;t.overscaledZ>t.canonical.z&&(t.canonical.z>=i?r=t.canonical.z-i:E("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const s=t.canonical.x-(t.canonical.x>>r<>r<>8<<4|t>>8,e[i+3]=0;const i=new Qo({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(e.buffer)),r=new Uh(t,i,t.gl.RGBA,{premultiply:!1});return r.bind(t.gl.NEAREST,t.gl.CLAMP_TO_EDGE),this._coordsTexture=r,r}pointCoordinate(t){this.painter.maybeDrawDepthAndCoords(!0);const e=new Uint8Array(4),i=this.painter.context,r=i.gl,s=Math.round(t.x*this.painter.pixelRatio/devicePixelRatio),n=Math.round(t.y*this.painter.pixelRatio/devicePixelRatio),a=Math.round(this.painter.height/devicePixelRatio);i.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),r.readPixels(s,a-n-1,1,1,r.RGBA,r.UNSIGNED_BYTE,e),i.bindFramebuffer.set(null);const o=e[0]+(e[2]>>4<<8),l=e[1]+((15&e[2])<<8),c=this.coordsIndex[255-e[3]],h=c&&this.sourceCache.getTileByID(c);if(!h)return null;const u=this._coordsTextureSize,d=(1<t.id!==e)),this._recentlyUsed.push(t.id)}stampObject(t){t.stamp=++this._stamp}getOrCreateFreeObject(){for(const t of this._recentlyUsed)if(!this._objects[t].inUse)return this._objects[t];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const t=this._createObject(this._objects.length);return this._objects.push(t),t}freeObject(t){t.inUse=!1}freeAllObjects(){for(const t of this._objects)this.freeObject(t)}isFull(){return!(this._objects.length!t.inUse))}}const R_={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0};class B_{constructor(t,e){this.painter=t,this.terrain=e,this.pool=new L_(t.context,30,e.sourceCache.tileSize*e.qualityFactor)}destruct(){this.pool.destruct()}getTexture(t){return this.pool.getObjectForId(t.rtt[this._stacks.length-1].id).texture}prepareForRender(t,e){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=t._order.filter((i=>!t._layers[i].isHidden(e))),this._coordsDescendingInv={};for(const e in t.sourceCaches){this._coordsDescendingInv[e]={};const i=t.sourceCaches[e].getVisibleCoordinates();for(const t of i){const i=this.terrain.sourceCache.getTerrainCoords(t);for(const t in i)this._coordsDescendingInv[e][t]||(this._coordsDescendingInv[e][t]=[]),this._coordsDescendingInv[e][t].push(i[t])}}this._coordsDescendingInvStr={};for(const e of t._order){const i=t._layers[e],r=i.source;if(R_[i.type]&&!this._coordsDescendingInvStr[r]){this._coordsDescendingInvStr[r]={};for(const t in this._coordsDescendingInv[r])this._coordsDescendingInvStr[r][t]=this._coordsDescendingInv[r][t].map((t=>t.key)).sort().join()}}for(const t of this._renderableTiles)for(const e in this._coordsDescendingInvStr){const i=this._coordsDescendingInvStr[e][t.tileID.key];i&&i!==t.rttCoords[e]&&(t.rtt=[])}}renderLayer(t){if(t.isHidden(this.painter.transform.zoom))return!1;const e=t.type,i=this.painter,r=this._renderableLayerIds[this._renderableLayerIds.length-1]===t.id;if(R_[e]&&(this._prevType&&R_[this._prevType]||this._stacks.push([]),this._prevType=e,this._stacks[this._stacks.length-1].push(t.id),!r))return!0;if(R_[this._prevType]||R_[e]&&r){this._prevType=e;const t=this._stacks.length-1,r=this._stacks[t]||[];for(const e of this._renderableTiles){if(this.pool.isFull()&&(dm(this.painter,this.terrain,this._rttTiles),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(e),e.rtt[t]){const i=this.pool.getObjectForId(e.rtt[t].id);if(i.stamp===e.rtt[t].stamp){this.pool.useObject(i);continue}}const s=this.pool.getOrCreateFreeObject();this.pool.useObject(s),this.pool.stampObject(s),e.rtt[t]={id:s.id,stamp:s.stamp},i.context.bindFramebuffer.set(s.fbo.framebuffer),i.context.clear({color:le.transparent,stencil:0}),i.currentStencilSource=void 0;for(let t=0;t{t.touchstart=t.dragStart,t.touchmoveWindow=t.dragMove,t.touchend=t.dragEnd},N_={showCompass:!0,showZoom:!0,visualizePitch:!1};class j_{constructor(t,e,i=!1){this.mousedown=t=>{this.startMouse(y({},t,{ctrlKey:!0,preventDefault:()=>t.preventDefault()}),O.mousePos(this.element,t)),O.addEventListener(window,"mousemove",this.mousemove),O.addEventListener(window,"mouseup",this.mouseup)},this.mousemove=t=>{this.moveMouse(t,O.mousePos(this.element,t))},this.mouseup=t=>{this.mouseRotate.dragEnd(t),this.mousePitch&&this.mousePitch.dragEnd(t),this.offTemp()},this.touchstart=t=>{1!==t.targetTouches.length?this.reset():(this._startPos=this._lastPos=O.touchPos(this.element,t.targetTouches)[0],this.startTouch(t,this._startPos),O.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),O.addEventListener(window,"touchend",this.touchend))},this.touchmove=t=>{1!==t.targetTouches.length?this.reset():(this._lastPos=O.touchPos(this.element,t.targetTouches)[0],this.moveTouch(t,this._lastPos))},this.touchend=t=>{0===t.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this.mouseRotate.reset(),this.mousePitch&&this.mousePitch.reset(),this.touchRotate.reset(),this.touchPitch&&this.touchPitch.reset(),delete this._startPos,delete this._lastPos,this.offTemp()},this._clickTolerance=10;const r=t.dragRotate._mouseRotate.getClickTolerance(),s=t.dragRotate._mousePitch.getClickTolerance();this.element=e,this.mouseRotate=Gm({clickTolerance:r,enable:!0}),this.touchRotate=(({enable:t,clickTolerance:e,bearingDegreesPerPixelMoved:i=.8})=>{const r=new qm;return new Nm({clickTolerance:e,move:(t,e)=>({bearingDelta:(e.x-t.x)*i}),moveStateManager:r,enable:t,assignEvents:U_})})({clickTolerance:r,enable:!0}),this.map=t,i&&(this.mousePitch=Wm({clickTolerance:s,enable:!0}),this.touchPitch=(({enable:t,clickTolerance:e,pitchDegreesPerPixelMoved:i=-.5})=>{const r=new qm;return new Nm({clickTolerance:e,move:(t,e)=>({pitchDelta:(e.y-t.y)*i}),moveStateManager:r,enable:t,assignEvents:U_})})({clickTolerance:s,enable:!0})),O.addEventListener(e,"mousedown",this.mousedown),O.addEventListener(e,"touchstart",this.touchstart,{passive:!1}),O.addEventListener(e,"touchcancel",this.reset)}startMouse(t,e){this.mouseRotate.dragStart(t,e),this.mousePitch&&this.mousePitch.dragStart(t,e),O.disableDrag()}startTouch(t,e){this.touchRotate.dragStart(t,e),this.touchPitch&&this.touchPitch.dragStart(t,e),O.disableDrag()}moveMouse(t,e){const i=this.map,{bearingDelta:r}=this.mouseRotate.dragMove(t,e)||{};if(r&&i.setBearing(i.getBearing()+r),this.mousePitch){const{pitchDelta:r}=this.mousePitch.dragMove(t,e)||{};r&&i.setPitch(i.getPitch()+r)}}moveTouch(t,e){const i=this.map,{bearingDelta:r}=this.touchRotate.dragMove(t,e)||{};if(r&&i.setBearing(i.getBearing()+r),this.touchPitch){const{pitchDelta:r}=this.touchPitch.dragMove(t,e)||{};r&&i.setPitch(i.getPitch()+r)}}off(){const t=this.element;O.removeEventListener(t,"mousedown",this.mousedown),O.removeEventListener(t,"touchstart",this.touchstart,{passive:!1}),O.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),O.removeEventListener(window,"touchend",this.touchend),O.removeEventListener(t,"touchcancel",this.reset),this.offTemp()}offTemp(){O.enableDrag(),O.removeEventListener(window,"mousemove",this.mousemove),O.removeEventListener(window,"mouseup",this.mouseup),O.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),O.removeEventListener(window,"touchend",this.touchend)}}let $_;function q_(t,e,i){const r=new fu(t.lng,t.lat);if(t=new fu(t.lng,t.lat),e){const r=new fu(t.lng-360,t.lat),s=new fu(t.lng+360,t.lat),n=i.locationPoint(t).distSqr(e);i.locationPoint(r).distSqr(e)180;){const e=i.locationPoint(t);if(e.x>=0&&e.y>=0&&e.x<=i.width&&e.y<=i.height)break;t.lng>i.center.lng?t.lng-=360:t.lng+=360}return t.lng!==r.lng&&i.locationPoint(t).y>i.height/2-i.getHorizon()?t:r}const Z_={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function G_(t,e,i){const r=t.classList;for(const t in Z_)r.remove(`maplibregl-${i}-anchor-${t}`);r.add(`maplibregl-${i}-anchor-${e}`)}class W_ extends nt{constructor(t){if(super(),this._onKeyPress=t=>{const e=t.code,i=t.charCode||t.keyCode;"Space"!==e&&"Enter"!==e&&32!==i&&13!==i||this.togglePopup()},this._onMapClick=t=>{const e=t.originalEvent.target,i=this._element;this._popup&&(e===i||i.contains(e))&&this.togglePopup()},this._update=t=>{var e;if(!this._map)return;const i=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==t?void 0:t.type)||"render"===(null==t?void 0:t.type)&&!i)&&this._map.once("render",this._update),this._lngLat=this._map.transform.renderWorldCopies?q_(this._lngLat,this._flatPos,this._map.transform):null===(e=this._lngLat)||void 0===e?void 0:e.wrap(),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationPoint(this._lngLat)._add(this._offset));let r="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?r=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(r=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let s="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?s="rotateX(0deg)":"map"===this._pitchAlignment&&(s=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||t&&"moveend"!==t.type||(this._pos=this._pos.round()),O.setTransform(this._element,`${Z_[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${s} ${r}`),F.frameAsync(new AbortController).then((()=>{this._updateOpacity(t&&"moveend"===t.type)})).catch((()=>{}))},this._onMove=t=>{if(!this._isDragging){const e=this._clickTolerance||this._map._clickTolerance;this._isDragging=t.point.dist(this._pointerdownPos)>=e}this._isDragging&&(this._pos=t.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new rt("dragstart"))),this.fire(new rt("drag")))},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new rt("dragend")),this._state="inactive"},this._addDragHandler=t=>{this._element.contains(t.originalEvent.target)&&(t.preventDefault(),this._positionDelta=t.point.sub(this._pos).add(this._offset),this._pointerdownPos=t.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp))},this._anchor=t&&t.anchor||"center",this._color=t&&t.color||"#3FB1CE",this._scale=t&&t.scale||1,this._draggable=t&&t.draggable||!1,this._clickTolerance=t&&t.clickTolerance||0,this._subpixelPositioning=t&&t.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=t&&t.rotation||0,this._rotationAlignment=t&&t.rotationAlignment||"auto",this._pitchAlignment=t&&t.pitchAlignment&&"auto"!==t.pitchAlignment?t.pitchAlignment:this._rotationAlignment,this.setOpacity(),this.setOpacity(null==t?void 0:t.opacity,null==t?void 0:t.opacityWhenCovered),t&&t.element)this._element=t.element,this._offset=a.convert(t&&t.offset||[0,0]);else{this._defaultMarker=!0,this._element=O.create("div");const e=O.createNS("http://www.w3.org/2000/svg","svg"),i=41,r=27;e.setAttributeNS(null,"display","block"),e.setAttributeNS(null,"height",`${i}px`),e.setAttributeNS(null,"width",`${r}px`),e.setAttributeNS(null,"viewBox",`0 0 ${r} ${i}`);const s=O.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"stroke","none"),s.setAttributeNS(null,"stroke-width","1"),s.setAttributeNS(null,"fill","none"),s.setAttributeNS(null,"fill-rule","evenodd");const n=O.createNS("http://www.w3.org/2000/svg","g");n.setAttributeNS(null,"fill-rule","nonzero");const o=O.createNS("http://www.w3.org/2000/svg","g");o.setAttributeNS(null,"transform","translate(3.0, 29.0)"),o.setAttributeNS(null,"fill","#000000");const l=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const t of l){const e=O.createNS("http://www.w3.org/2000/svg","ellipse");e.setAttributeNS(null,"opacity","0.04"),e.setAttributeNS(null,"cx","10.5"),e.setAttributeNS(null,"cy","5.80029008"),e.setAttributeNS(null,"rx",t.rx),e.setAttributeNS(null,"ry",t.ry),o.appendChild(e)}const c=O.createNS("http://www.w3.org/2000/svg","g");c.setAttributeNS(null,"fill",this._color);const h=O.createNS("http://www.w3.org/2000/svg","path");h.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"),c.appendChild(h);const u=O.createNS("http://www.w3.org/2000/svg","g");u.setAttributeNS(null,"opacity","0.25"),u.setAttributeNS(null,"fill","#000000");const d=O.createNS("http://www.w3.org/2000/svg","path");d.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"),u.appendChild(d);const p=O.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(6.0, 7.0)"),p.setAttributeNS(null,"fill","#FFFFFF");const f=O.createNS("http://www.w3.org/2000/svg","g");f.setAttributeNS(null,"transform","translate(8.0, 8.0)");const m=O.createNS("http://www.w3.org/2000/svg","circle");m.setAttributeNS(null,"fill","#000000"),m.setAttributeNS(null,"opacity","0.25"),m.setAttributeNS(null,"cx","5.5"),m.setAttributeNS(null,"cy","5.5"),m.setAttributeNS(null,"r","5.4999962");const _=O.createNS("http://www.w3.org/2000/svg","circle");_.setAttributeNS(null,"fill","#FFFFFF"),_.setAttributeNS(null,"cx","5.5"),_.setAttributeNS(null,"cy","5.5"),_.setAttributeNS(null,"r","5.4999962"),f.appendChild(m),f.appendChild(_),n.appendChild(o),n.appendChild(c),n.appendChild(u),n.appendChild(p),n.appendChild(f),e.appendChild(n),e.setAttributeNS(null,"height",i*this._scale+"px"),e.setAttributeNS(null,"width",r*this._scale+"px"),this._element.appendChild(e),this._offset=a.convert(t&&t.offset||[0,-14])}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(t=>{t.preventDefault()})),this._element.addEventListener("mousedown",(t=>{t.preventDefault()})),G_(this._element,this._anchor,"marker"),t&&t.className)for(const e of t.className.split(" "))this._element.classList.add(e);this._popup=null}addTo(t){return this.remove(),this._map=t,this._element.setAttribute("aria-label",t._getUIString("Marker.Title")),t.getCanvasContainer().appendChild(this._element),t.on("move",this._update),t.on("moveend",this._update),t.on("terrain",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),O.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(t){return this._lngLat=fu.convert(t),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(t){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),t){if(!("offset"in t.options)){const e=38.1,i=13.5,r=Math.abs(i)/Math.SQRT2;t.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-e],"bottom-left":[r,-1*(e-i+r)],"bottom-right":[-r,-1*(e-i+r)],left:[i,-1*(e-i)],right:[-i,-1*(e-i)]}:this._offset}this._popup=t,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress)}return this}setSubpixelPositioning(t){return this._subpixelPositioning=t,this}getPopup(){return this._popup}togglePopup(){const t=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:t?(t.isOpen()?t.remove():(t.setLngLat(this._lngLat),t.addTo(this._map)),this):this}_updateOpacity(t=!1){var e,i;if(!(null===(e=this._map)||void 0===e?void 0:e.terrain))return void(this._element.style.opacity!==this._opacity&&(this._element.style.opacity=this._opacity));if(t)this._opacityTimeout=null;else{if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null}),100)}const r=this._map,s=r.terrain.depthAtPoint(this._pos),n=r.terrain.getElevationForLngLatZoom(this._lngLat,r.transform.tileZoom);if(r.transform.lngLatToCameraDepth(this._lngLat,n)-s<.006)return void(this._element.style.opacity=this._opacity);const o=-this._offset.y/r.transform._pixelPerMeter,l=Math.sin(r.getPitch()*Math.PI/180)*o,c=r.terrain.depthAtPoint(new a(this._pos.x,this._pos.y-this._offset.y)),h=r.transform.lngLatToCameraDepth(this._lngLat,n+l)-c>.006;(null===(i=this._popup)||void 0===i?void 0:i.isOpen())&&h&&this._popup.remove(),this._element.style.opacity=h?this._opacityWhenCovered:this._opacity}getOffset(){return this._offset}setOffset(t){return this._offset=a.convert(t),this._update(),this}addClassName(t){this._element.classList.add(t)}removeClassName(t){this._element.classList.remove(t)}toggleClassName(t){return this._element.classList.toggle(t)}setDraggable(t){return this._draggable=!!t,this._map&&(t?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(t){return this._rotation=t||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(t){return this._rotationAlignment=t||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(t){return this._pitchAlignment=t&&"auto"!==t?t:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(t,e){return void 0===t&&void 0===e&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==t&&(this._opacity=t),void 0!==e&&(this._opacityWhenCovered=e),this._map&&this._updateOpacity(!0),this}}const H_={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let X_=0,K_=!1;const Y_={maxWidth:100,unit:"metric"};function J_(t,e,i){const r=i&&i.maxWidth||100,s=t._container.clientHeight/2,n=t.unproject([0,s]),a=t.unproject([r,s]),o=n.distanceTo(a);if(i&&"imperial"===i.unit){const i=3.2808*o;i>5280?Q_(e,r,i/5280,t._getUIString("ScaleControl.Miles")):Q_(e,r,i,t._getUIString("ScaleControl.Feet"))}else i&&"nautical"===i.unit?Q_(e,r,o/1852,t._getUIString("ScaleControl.NauticalMiles")):o>=1e3?Q_(e,r,o/1e3,t._getUIString("ScaleControl.Kilometers")):Q_(e,r,o,t._getUIString("ScaleControl.Meters"))}function Q_(t,e,i,r){const s=function(t){const e=Math.pow(10,`${Math.floor(t)}`.length-1);let i=t/e;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(t){const e=Math.pow(10,Math.ceil(-Math.log(t)/Math.LN10));return Math.round(t*e)/e}(i),e*i}(i);t.style.width=e*(s/i)+"px",t.innerHTML=`${s} ${r}`}const tg={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1},eg=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function ig(t){if(t){if("number"==typeof t){const e=Math.round(Math.abs(t)/Math.SQRT2);return{center:new a(0,0),top:new a(0,t),"top-left":new a(e,e),"top-right":new a(-e,e),bottom:new a(0,-t),"bottom-left":new a(e,-e),"bottom-right":new a(-e,-e),left:new a(t,0),right:new a(-t,0)}}if(t instanceof a||Array.isArray(t)){const e=a.convert(t);return{center:e,top:e,"top-left":e,"top-right":e,bottom:e,"bottom-left":e,"bottom-right":e,left:e,right:e}}return{center:a.convert(t.center||[0,0]),top:a.convert(t.top||[0,0]),"top-left":a.convert(t["top-left"]||[0,0]),"top-right":a.convert(t["top-right"]||[0,0]),bottom:a.convert(t.bottom||[0,0]),"bottom-left":a.convert(t["bottom-left"]||[0,0]),"bottom-right":a.convert(t["bottom-right"]||[0,0]),left:a.convert(t.left||[0,0]),right:a.convert(t.right||[0,0])}}return ig(new a(0,0))}const rg=e;t.AJAXError=j,t.AttributionControl=b_,t.BoxZoomHandler=Bm,t.CanvasSource=Bu,t.CooperativeGesturesHandler=f_,t.DoubleClickZoomHandler=l_,t.DragPanHandler=u_,t.DragRotateHandler=d_,t.EdgeInsets=gm,t.Evented=nt,t.FullscreenControl=class extends nt{constructor(t={}){super(),this._onFullscreenChange=()=>{var t;let e=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(t=null==e?void 0:e.shadowRoot)||void 0===t?void 0:t.fullscreenElement;)e=e.shadowRoot.fullscreenElement;e===this._container!==this._fullscreen&&this._handleFullscreenChange()},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen()},this._fullscreen=!1,t&&t.container&&(t.container instanceof HTMLElement?this._container=t.container:E("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange")}onAdd(t){return this._map=t,this._container||(this._container=this._map.getContainer()),this._controlContainer=O.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){O.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange)}_setupUI(){const t=this._fullscreenButton=O.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);O.create("span","maplibregl-ctrl-icon",t).setAttribute("aria-hidden","true"),t.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange)}_updateTitle(){const t=this._getTitle();this._fullscreenButton.setAttribute("aria-label",t),this._fullscreenButton.title=t}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new rt("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new rt("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable())}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen()}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen()}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize()}},t.GeoJSONSource=ku,t.GeolocateControl=class extends nt{constructor(t){super(),this._onSuccess=t=>{if(this._map){if(this._isOutOfMapMaxBounds(t))return this._setErrorState(),this.fire(new rt("outofmaxbounds",t)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=t,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(t),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(t),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new rt("geolocate",t)),this._finish()}},this._updateCamera=t=>{const e=new fu(t.coords.longitude,t.coords.latitude),i=t.coords.accuracy,r=y({bearing:this._map.getBearing()},this.options.fitBoundsOptions),s=mu.fromLngLat(e,i);this._map.fitBounds(s,r,{geolocateSource:!0})},this._updateMarker=t=>{if(t){const e=new fu(t.coords.longitude,t.coords.latitude);this._accuracyCircleMarker.setLngLat(e).addTo(this._map),this._userLocationDotMarker.setLngLat(e).addTo(this._map),this._accuracy=t.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()},this._onZoom=()=>{this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()},this._onError=t=>{if(this._map){if(this.options.trackUserLocation)if(1===t.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const t=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=t,this._geolocateButton.setAttribute("aria-label",t),void 0!==this._geolocationWatchID&&this._clearWatch()}else{if(3===t.code&&K_)return;this._setErrorState()}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new rt("error",t)),this._finish()}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(t=>t.preventDefault())),this._geolocateButton=O.create("button","maplibregl-ctrl-geolocate",this._container),O.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0)},this._finishSetupUI=t=>{if(this._map){if(!1===t){E("Geolocation support is not available so the GeolocateControl will be disabled.");const t=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=t,this._geolocateButton.setAttribute("aria-label",t)}else{const t=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=t,this._geolocateButton.setAttribute("aria-label",t)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=O.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new W_({element:this._dotElement}),this._circleElement=O.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new W_({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(t=>{t.geolocateSource||"ACTIVE_LOCK"!==this._watchState||t.originalEvent&&"resize"===t.originalEvent.type||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new rt("trackuserlocationend")),this.fire(new rt("userlocationlostfocus")))}))}},this.options=y({},H_,t)}onAdd(t){return this._map=t,this._container=O.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return i(this,arguments,void 0,(function*(t=!1){if(void 0!==$_&&!t)return $_;if(void 0===window.navigator.permissions)return $_=!!window.navigator.geolocation,$_;try{const t=yield window.navigator.permissions.query({name:"geolocation"});$_="denied"!==t.state}catch(t){$_=!!window.navigator.geolocation}return $_}))}().then((t=>this._finishSetupUI(t))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),O.remove(this._container),this._map.off("zoom",this._onZoom),this._map=void 0,X_=0,K_=!1}_isOutOfMapMaxBounds(t){const e=this._map.getMaxBounds(),i=t.coords;return e&&(i.longitudee.getEast()||i.latitudee.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadius(){const t=this._map.getBounds(),e=t.getSouthEast(),i=t.getNorthEast(),r=e.distanceTo(i),s=Math.ceil(this._accuracy/(r/this._map._container.clientHeight)*2);this._circleElement.style.width=`${s}px`,this._circleElement.style.height=`${s}px`}trigger(){if(!this._setup)return E("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new rt("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":X_--,K_=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new rt("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new rt("trackuserlocationstart")),this.fire(new rt("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let t;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),X_++,X_>1?(t={maximumAge:6e5,timeout:0},K_=!0):(t=this.options.positionOptions,K_=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,t)}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return!0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},t.Hash=bm,t.ImageSource=Lu,t.KeyboardHandler=s_,t.LngLat=fu,t.LngLatBounds=mu,t.LogoControl=w_,t.Map=class extends x_{constructor(t){P_.mark(S_.create);const e=Object.assign(Object.assign({},V_),t);if(null!=e.minZoom&&null!=e.maxZoom&&e.minZoom>e.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=e.minPitch&&null!=e.maxPitch&&e.minPitch>e.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=e.minPitch&&e.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=e.maxPitch&&e.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");if(super(new xm(e.minZoom,e.maxZoom,e.minPitch,e.maxPitch,e.renderWorldCopies),{bearingSnap:e.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new T_,this._controls=[],this._mapId=b(),this._contextLost=t=>{t.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new rt("webglcontextlost",{originalEvent:t}))},this._contextRestored=t=>{this._setupPainter(),this.resize(),this._update(),this.fire(new rt("webglcontextrestored",{originalEvent:t}))},this._onMapScroll=t=>{if(t.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update()},this._interactive=e.interactive,this._maxTileCacheSize=e.maxTileCacheSize,this._maxTileCacheZoomLevels=e.maxTileCacheZoomLevels,this._failIfMajorPerformanceCaveat=!0===e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=!0===e.preserveDrawingBuffer,this._antialias=!0===e.antialias,this._trackResize=!0===e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=!0===e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._crossSourceCollisions=!0===e.crossSourceCollisions,this._collectResourceTiming=!0===e.collectResourceTiming,this._locale=Object.assign(Object.assign({},F_),e.locale),this._clickTolerance=e.clickTolerance,this._overridePixelRatio=e.pixelRatio,this._maxCanvasSize=e.maxCanvasSize,this.transformCameraUpdate=e.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===e.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=Q.addThrottleControl((()=>this.isMoving())),this._requestManager=new tt(e.transformRequest),"string"==typeof e.container){if(this._container=document.getElementById(e.container),!this._container)throw new Error(`Container '${e.container}' not found.`)}else{if(!(e.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container}if(e.maxBounds&&this.setMaxBounds(e.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))).on("moveend",(()=>this._update(!1))).on("zoom",(()=>this._update(!0))).on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0)})).once("idle",(()=>{this._idleTriggered=!0})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let t=!1;const e=vm((t=>{this._trackResize&&!this._removed&&(this.resize(t),this.redraw())}),50);this._resizeObserver=new ResizeObserver((i=>{t?e(i):t=!0})),this._resizeObserver.observe(this._container)}this.handlers=new y_(this,e),this._hash=e.hash&&new bm("string"==typeof e.hash&&e.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch}),e.bounds&&(this.resize(),this.fitBounds(e.bounds,y({},e.fitBoundsOptions,{duration:0})))),this.resize(),this._localIdeographFontFamily=e.localIdeographFontFamily,this._validateStyle=e.validateStyle,e.style&&this.setStyle(e.style,{localIdeographFontFamily:e.localIdeographFontFamily}),e.attributionControl&&this.addControl(new b_("boolean"==typeof e.attributionControl?void 0:e.attributionControl)),e.maplibreLogo&&this.addControl(new w_,e.logoPosition),this.on("style.load",(()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet)})),this.on("data",(t=>{this._update("style"===t.dataType),this.fire(new rt(`${t.dataType}data`,t))})),this.on("dataloading",(t=>{this.fire(new rt(`${t.dataType}dataloading`,t))})),this.on("dataabort",(t=>{this.fire(new rt("sourcedataabort",t))}))}_getMapId(){return this._mapId}addControl(t,e){if(void 0===e&&(e=t.getDefaultPosition?t.getDefaultPosition():"top-right"),!t||!t.onAdd)return this.fire(new st(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const i=t.onAdd(this);this._controls.push(t);const r=this._controlPositions[e];return-1!==e.indexOf("bottom")?r.insertBefore(i,r.firstChild):r.appendChild(i),this}removeControl(t){if(!t||!t.onRemove)return this.fire(new st(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const e=this._controls.indexOf(t);return e>-1&&this._controls.splice(e,1),t.onRemove(this),this}hasControl(t){return this._controls.indexOf(t)>-1}calculateCameraOptionsFromTo(t,e,i,r){return null==r&&this.terrain&&(r=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(t,e,i,r)}resize(t){var e;const i=this._containerDimensions(),r=i[0],s=i[1],n=this._getClampedPixelRatio(r,s);if(this._resizeCanvas(r,s,n),this.painter.resize(r,s,n),this.painter.overLimit()){const t=this.painter.context.gl;this._maxCanvasSize=[t.drawingBufferWidth,t.drawingBufferHeight];const e=this._getClampedPixelRatio(r,s);this._resizeCanvas(r,s,e),this.painter.resize(r,s,e)}this.transform.resize(r,s),null===(e=this._requestedCameraState)||void 0===e||e.resize(r,s);const a=!this._moving;return a&&(this.stop(),this.fire(new rt("movestart",t)).fire(new rt("move",t))),this.fire(new rt("resize",t)),a&&this.fire(new rt("moveend",t)),this}_getClampedPixelRatio(t,e){const{0:i,1:r}=this._maxCanvasSize,s=this.getPixelRatio(),n=t*s,a=e*s;return Math.min(n>i?i/n:1,a>r?r/a:1)*s}getPixelRatio(){var t;return null!==(t=this._overridePixelRatio)&&void 0!==t?t:devicePixelRatio}setPixelRatio(t){this._overridePixelRatio=t,this.resize()}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(t){return this.transform.setMaxBounds(mu.convert(t)),this._update()}setMinZoom(t){if((t=null==t?-2:t)>=-2&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(t){if((t=null==t?0:t)<0)throw new Error("minPitch must be greater than or equal to 0");if(t>=0&&t<=this.transform.maxPitch)return this.transform.minPitch=t,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(t>=this.transform.minPitch)return this.transform.maxPitch=t,this._update(),this.getPitch()>t&&this.setPitch(t),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(t){return this.transform.renderWorldCopies=t,this._update()}project(t){return this.transform.locationPoint(fu.convert(t),this.style&&this.terrain)}unproject(t){return this.transform.pointLocation(a.convert(t),this.terrain)}isMoving(){var t;return this._moving||(null===(t=this.handlers)||void 0===t?void 0:t.isMoving())}isZooming(){var t;return this._zooming||(null===(t=this.handlers)||void 0===t?void 0:t.isZooming())}isRotating(){var t;return this._rotating||(null===(t=this.handlers)||void 0===t?void 0:t.isRotating())}_createDelegatedListener(t,e,i){if("mouseenter"===t||"mouseover"===t){let r=!1;const s=s=>{const n=e.filter((t=>this.getLayer(t))),a=0!==n.length?this.queryRenderedFeatures(s.point,{layers:n}):[];a.length?r||(r=!0,i.call(this,new Pm(t,this,s.originalEvent,{features:a}))):r=!1};return{layers:e,listener:i,delegates:{mousemove:s,mouseout:()=>{r=!1}}}}if("mouseleave"===t||"mouseout"===t){let r=!1;const s=s=>{const n=e.filter((t=>this.getLayer(t)));(0!==n.length?this.queryRenderedFeatures(s.point,{layers:n}):[]).length?r=!0:r&&(r=!1,i.call(this,new Pm(t,this,s.originalEvent)))},n=e=>{r&&(r=!1,i.call(this,new Pm(t,this,e.originalEvent)))};return{layers:e,listener:i,delegates:{mousemove:s,mouseout:n}}}{const r=t=>{const r=e.filter((t=>this.getLayer(t))),s=0!==r.length?this.queryRenderedFeatures(t.point,{layers:r}):[];s.length&&(t.features=s,i.call(this,t),delete t.features)};return{layers:e,listener:i,delegates:{[t]:r}}}}_saveDelegatedListener(t,e){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[t]=this._delegatedListeners[t]||[],this._delegatedListeners[t].push(e)}_removeDelegatedListener(t,e,i){if(!this._delegatedListeners||!this._delegatedListeners[t])return;const r=this._delegatedListeners[t];for(let t=0;te.includes(t)))){for(const t in s.delegates)this.off(t,s.delegates[t]);return void r.splice(t,1)}}}on(t,e,i){if(void 0===i)return super.on(t,e);const r=this._createDelegatedListener(t,"string"==typeof e?[e]:e,i);this._saveDelegatedListener(t,r);for(const t in r.delegates)this.on(t,r.delegates[t]);return this}once(t,e,i){if(void 0===i)return super.once(t,e);const r="string"==typeof e?[e]:e,s=this._createDelegatedListener(t,r,i);for(const e in s.delegates){const n=s.delegates[e];s.delegates[e]=(...e)=>{this._removeDelegatedListener(t,r,i),n(...e)}}this._saveDelegatedListener(t,s);for(const t in s.delegates)this.once(t,s.delegates[t]);return this}off(t,e,i){return void 0===i?super.off(t,e):(this._removeDelegatedListener(t,"string"==typeof e?[e]:e,i),this)}queryRenderedFeatures(t,e){if(!this.style)return[];let i;const r=t instanceof a||Array.isArray(t),s=r?t:[[0,0],[this.transform.width,this.transform.height]];if(e=e||(r?{}:t)||{},s instanceof a||"number"==typeof s[0])i=[a.convert(s)];else{const t=a.convert(s[0]),e=a.convert(s[1]);i=[t,new a(e.x,t.y),e,new a(t.x,e.y),t]}return this.style.queryRenderedFeatures(i,e,this.transform)}querySourceFeatures(t,e){return this.style.querySourceFeatures(t,e)}setStyle(t,e){return!1!==(e=y({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},e)).diff&&e.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&t?(this._diffStyle(t,e),this):(this._localIdeographFontFamily=e.localIdeographFontFamily,this._updateStyle(t,e))}setTransformRequest(t){return this._requestManager.setTransformRequest(t),this}_getUIString(t){const e=this._locale[t];if(null==e)throw new Error(`Missing UI string '${t}'`);return e}_updateStyle(t,e){if(e.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(t,e)));const i=this.style&&e.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!t)),t?(this.style=new op(this,e||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof t?this.style.loadURL(t,e,i):this.style.loadJSON(t,e,i),this):(delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new op(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}_diffStyle(t,e){if("string"==typeof t){const i=this._requestManager.transformRequest(t,"Style");Z(i,new AbortController).then((t=>{this._updateDiff(t.data,e)})).catch((t=>{t&&this.fire(new st(t))}))}else"object"==typeof t&&this._updateDiff(t,e)}_updateDiff(t,e){try{this.style.setState(t,e)&&this._update(!0)}catch(i){E(`Unable to perform style diff: ${i.message||i.error||i}. Rebuilding the style from scratch.`),this._updateStyle(t,e)}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():E("There is no style added to the map.")}addSource(t,e){return this._lazyInitEmptyStyle(),this.style.addSource(t,e),this._update(!0)}isSourceLoaded(t){const e=this.style&&this.style.sourceCaches[t];if(void 0!==e)return e.loaded();this.fire(new st(new Error(`There is no source with ID '${t}'`)))}setTerrain(t){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),t){const e=this.style.sourceCaches[t.source];if(!e)throw new Error(`cannot load terrain, because there exists no source with ID: ${t.source}`);null===this.terrain&&e.reload();for(const e in this.style._layers){const i=this.style._layers[e];"hillshade"===i.type&&i.source===t.source&&E("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.")}this.terrain=new D_(this.painter,e,t),this.painter.renderToTexture=new B_(this.painter,this.terrain),this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom),this.transform.elevation=this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom),this._terrainDataCallback=e=>{"style"===e.dataType?this.terrain.sourceCache.freeRtt():"source"===e.dataType&&e.tile&&(e.sourceId!==t.source||this._elevationFreeze||(this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom),this.transform.elevation=this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.terrain.sourceCache.freeRtt(e.tile.tileID))},this.style.on("data",this._terrainDataCallback)}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.minElevationForCurrentTile=0,this.transform.elevation=0;return this.fire(new rt("terrain",{terrain:t})),this}getTerrain(){var t,e;return null!==(e=null===(t=this.terrain)||void 0===t?void 0:t.options)&&void 0!==e?e:null}areTilesLoaded(){const t=this.style&&this.style.sourceCaches;for(const e in t){const i=t[e]._tiles;for(const t in i){const e=i[t];if("loaded"!==e.state&&"errored"!==e.state)return!1}}return!0}removeSource(t){return this.style.removeSource(t),this._update(!0)}getSource(t){return this.style.getSource(t)}addImage(t,e,i={}){const{pixelRatio:r=1,sdf:s=!1,stretchX:n,stretchY:a,content:o,textFitWidth:l,textFitHeight:c}=i;if(this._lazyInitEmptyStyle(),!(e instanceof HTMLImageElement||M(e))){if(void 0===e.width||void 0===e.height)return this.fire(new st(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:i,height:h,data:u}=e,d=e;return this.style.addImage(t,{data:new Qo({width:i,height:h},new Uint8Array(u)),pixelRatio:r,stretchX:n,stretchY:a,content:o,textFitWidth:l,textFitHeight:c,sdf:s,version:0,userImage:d}),d.onAdd&&d.onAdd(this,t),this}}{const{width:i,height:h,data:u}=F.getImageData(e);this.style.addImage(t,{data:new Qo({width:i,height:h},u),pixelRatio:r,stretchX:n,stretchY:a,content:o,textFitWidth:l,textFitHeight:c,sdf:s,version:0})}}updateImage(t,e){const i=this.style.getImage(t);if(!i)return this.fire(new st(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const r=e instanceof HTMLImageElement||M(e)?F.getImageData(e):e,{width:s,height:n,data:a}=r;if(void 0===s||void 0===n)return this.fire(new st(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(s!==i.data.width||n!==i.data.height)return this.fire(new st(new Error("The width and height of the updated image must be that same as the previous version of the image")));const o=!(e instanceof HTMLImageElement||M(e));return i.data.replace(a,o),this.style.updateImage(t,i),this}getImage(t){return this.style.getImage(t)}hasImage(t){return t?!!this.style.getImage(t):(this.fire(new st(new Error("Missing required image id"))),!1)}removeImage(t){this.style.removeImage(t)}loadImage(t){return Q.getImage(this._requestManager.transformRequest(t,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(t,e){return this._lazyInitEmptyStyle(),this.style.addLayer(t,e),this._update(!0)}moveLayer(t,e){return this.style.moveLayer(t,e),this._update(!0)}removeLayer(t){return this.style.removeLayer(t),this._update(!0)}getLayer(t){return this.style.getLayer(t)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(t,e,i){return this.style.setLayerZoomRange(t,e,i),this._update(!0)}setFilter(t,e,i={}){return this.style.setFilter(t,e,i),this._update(!0)}getFilter(t){return this.style.getFilter(t)}setPaintProperty(t,e,i,r={}){return this.style.setPaintProperty(t,e,i,r),this._update(!0)}getPaintProperty(t,e){return this.style.getPaintProperty(t,e)}setLayoutProperty(t,e,i,r={}){return this.style.setLayoutProperty(t,e,i,r),this._update(!0)}getLayoutProperty(t,e){return this.style.getLayoutProperty(t,e)}setGlyphs(t,e={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(t,e),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(t,e,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(t,e,i,(t=>{t||this._update(!0)})),this}removeSprite(t){return this._lazyInitEmptyStyle(),this.style.removeSprite(t),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(t,e={}){return this._lazyInitEmptyStyle(),this.style.setSprite(t,e,(t=>{t||this._update(!0)})),this}setLight(t,e={}){return this._lazyInitEmptyStyle(),this.style.setLight(t,e),this._update(!0)}getLight(){return this.style.getLight()}setSky(t){return this._lazyInitEmptyStyle(),this.style.setSky(t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(t,e){return this.style.setFeatureState(t,e),this._update()}removeFeatureState(t,e){return this.style.removeFeatureState(t,e),this._update()}getFeatureState(t){return this.style.getFeatureState(t)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let t=0,e=0;return this._container&&(t=this._container.clientWidth||400,e=this._container.clientHeight||300),[t,e]}_setupContainer(){const t=this._container;t.classList.add("maplibregl-map");const e=this._canvasContainer=O.create("div","maplibregl-canvas-container",t);this._interactive&&e.classList.add("maplibregl-interactive"),this._canvas=O.create("canvas","maplibregl-canvas",e),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),r=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],r);const s=this._controlContainer=O.create("div","maplibregl-control-container",t),n=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((t=>{n[t]=O.create("div",`maplibregl-ctrl-${t} `,s)})),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(t,e,i){this._canvas.width=Math.floor(i*t),this._canvas.height=Math.floor(i*e),this._canvas.style.width=`${t}px`,this._canvas.style.height=`${e}px`}_setupPainter(){const t={alpha:!0,stencil:!0,depth:!0,failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1};let e=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{e={requestedAttributes:t},i&&(e.statusMessage=i.statusMessage,e.type=i.type)}),{once:!0});const i=this._canvas.getContext("webgl2",t)||this._canvas.getContext("webgl",t);if(!i){const t="Failed to initialize WebGL";throw e?(e.message=t,new Error(JSON.stringify(e))):new Error(t)}this.painter=new fm(i,this.transform),W.testSupport(i)}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(t){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||t,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(t){return this._update(),this._renderTaskQueue.add(t)}_cancelRenderFrame(t){this._renderTaskQueue.remove(t)}_render(t){const e=this._idleTriggered?this._fadeDuration:0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(t),this._removed)return;let i=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const t=this.transform.zoom,r=F.now();this.style.zoomHistory.update(t,r);const s=new Ks(t,{now:r,fadeDuration:e,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),n=s.crossFadingFactor();1===n&&n===this._crossFadingFactor||(i=!0,this._crossFadingFactor=n),this.style.update(s)}this.style&&this._sourcesDirty&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom),this._elevationFreeze||(this.transform.elevation=this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.minElevationForCurrentTile=0,this.transform.elevation=0),this._placementDirty=this.style&&this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,e,this._crossSourceCollisions),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:e,showPadding:this.showPadding}),this.fire(new rt("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,P_.mark(S_.load),this.fire(new rt("load"))),this.style&&(this.style.hasTransitions()||i)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const r=this._sourcesDirty||this._styleDirty||this._placementDirty;return r||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new rt("idle")),!this._loaded||this._fullyLoaded||r||(this._fullyLoaded=!0,P_.mark(S_.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var t;this._hash&&this._hash.remove();for(const t of this._controls)t.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),Q.removeThrottleControl(this._imageQueueHandle),null===(t=this._resizeObserver)||void 0===t||t.disconnect();const e=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==e?void 0:e.loseContext)&&e.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),O.remove(this._canvasContainer),O.remove(this._controlContainer),this._container.classList.remove("maplibregl-map"),P_.clearMetrics(),this._removed=!0,this.fire(new rt("remove"))}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,F.frameAsync(this._frameRequest).then((t=>{P_.frame(t),this._frameRequest=null,this._render(t)})).catch((()=>{})))}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(t){this._showTileBoundaries!==t&&(this._showTileBoundaries=t,this._update())}get showPadding(){return!!this._showPadding}set showPadding(t){this._showPadding!==t&&(this._showPadding=t,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(t){this._showCollisionBoxes!==t&&(this._showCollisionBoxes=t,t?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(t){this._showOverdrawInspector!==t&&(this._showOverdrawInspector=t,this._update())}get repaint(){return!!this._repaint}set repaint(t){this._repaint!==t&&(this._repaint=t,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(t){this._vertices=t,this._update()}get version(){return O_}getCameraTargetElevation(){return this.transform.elevation}},t.MapMouseEvent=Pm,t.MapTouchEvent=Mm,t.MapWheelEvent=km,t.Marker=W_,t.MercatorCoordinate=wu,t.NavigationControl=class{constructor(t){this._updateZoomButtons=()=>{const t=this._map.getZoom(),e=t===this._map.getMaxZoom(),i=t===this._map.getMinZoom();this._zoomInButton.disabled=e,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",e.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString())},this._rotateCompassArrow=()=>{const t=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitch*(Math.PI/180)),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${this._map.transform.angle*(180/Math.PI)}deg)`:`rotate(${this._map.transform.angle*(180/Math.PI)}deg)`;this._compassIcon.style.transform=t},this._setButtonTitle=(t,e)=>{const i=this._map._getUIString(`NavigationControl.${e}`);t.title=i,t.setAttribute("aria-label",i)},this.options=y({},N_,t),this._container=O.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(t=>t.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(t=>this._map.zoomIn({},{originalEvent:t}))),O.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(t=>this._map.zoomOut({},{originalEvent:t}))),O.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(t=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:t}):this._map.resetNorth({},{originalEvent:t})})),this._compassIcon=O.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}onAdd(t){return this._map=t,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new j_(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){O.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map}_createButton(t,e){const i=O.create("button",t,this._container);return i.type="button",i.addEventListener("click",e),i}},t.Point=a,t.Popup=class extends nt{constructor(t){super(),this.remove=()=>(this._content&&O.remove(this._content),this._container&&(O.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new rt("close"))),this),this._onMouseUp=t=>{this._update(t.point)},this._onMouseMove=t=>{this._update(t.point)},this._onDrag=t=>{this._update(t.point)},this._update=t=>{var e;if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=O.create("div","maplibregl-popup",this._map.getContainer()),this._tip=O.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const t of this.options.className.split(" "))this._container.classList.add(t);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer")}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=this._map.transform.renderWorldCopies&&!this._trackPointer?q_(this._lngLat,this._flatPos,this._map.transform):null===(e=this._lngLat)||void 0===e?void 0:e.wrap(),this._trackPointer&&!t)return;const i=this._flatPos=this._pos=this._trackPointer&&t?t:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&t?t:this._map.transform.locationPoint(this._lngLat));let r=this.options.anchor;const s=ig(this.options.offset);if(!r){const t=this._container.offsetWidth,e=this._container.offsetHeight;let n;n=i.y+s.bottom.ythis._map.transform.height-e?["bottom"]:[],i.xthis._map.transform.width-t/2&&n.push("right"),r=0===n.length?"bottom":n.join("-")}let n=i.add(s[r]);this.options.subpixelPositioning||(n=n.round()),O.setTransform(this._container,`${Z_[r]} translate(${n.x}px,${n.y}px)`),G_(this._container,r,"popup")},this._onClose=()=>{this.remove()},this.options=y(Object.create(tg),t)}addTo(t){return this._map&&this.remove(),this._map=t,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new rt("open")),this}isOpen(){return!!this._map}getLngLat(){return this._lngLat}setLngLat(t){return this._lngLat=fu.convert(t),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(t){return this.setDOMContent(document.createTextNode(t))}setHTML(t){const e=document.createDocumentFragment(),i=document.createElement("body");let r;for(i.innerHTML=t;r=i.firstChild,r;)e.appendChild(r);return this.setDOMContent(e)}getMaxWidth(){var t;return null===(t=this._container)||void 0===t?void 0:t.style.maxWidth}setMaxWidth(t){return this.options.maxWidth=t,this._update(),this}setDOMContent(t){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=O.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(t),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(t){return this._container&&this._container.classList.add(t),this}removeClassName(t){return this._container&&this._container.classList.remove(t),this}setOffset(t){return this.options.offset=t,this._update(),this}toggleClassName(t){if(this._container)return this._container.classList.toggle(t)}setSubpixelPositioning(t){this.options.subpixelPositioning=t}_createCloseButton(){this.options.closeButton&&(this._closeButton=O.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose))}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const t=this._container.querySelector(eg);t&&t.focus()}},t.RasterDEMTileSource=Mu,t.RasterTileSource=Iu,t.ScaleControl=class{constructor(t){this._onMove=()=>{J_(this._map,this._container,this.options)},this.setUnit=t=>{this.options.unit=t,J_(this._map,this._container,this.options)},this.options=Object.assign(Object.assign({},Y_),t)}getDefaultPosition(){return"bottom-left"}onAdd(t){return this._map=t,this._container=O.create("div","maplibregl-ctrl maplibregl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){O.remove(this._container),this._map.off("move",this._onMove),this._map=void 0}},t.ScrollZoomHandler=o_,t.Style=op,t.TerrainControl=class{constructor(t){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon()},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"))},this.options=t}onAdd(t){return this._map=t,this._container=O.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=O.create("button","maplibregl-ctrl-terrain",this._container),O.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){O.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0}},t.TwoFingersTouchPitchHandler=i_,t.TwoFingersTouchRotateHandler=t_,t.TwoFingersTouchZoomHandler=Jm,t.TwoFingersTouchZoomRotateHandler=p_,t.VectorTileSource=Su,t.VideoSource=Ru,t.addProtocol=function(t,e){V.REGISTERED_PROTOCOLS[t]=e},t.addSourceType=(t,e)=>i(void 0,void 0,void 0,(function*(){if(Ou(t))throw new Error(`A source type called "${t}" already exists.`);((t,e)=>{Fu[t]=e})(t,e)})),t.clearPrewarmedResources=function(){const t=su;t&&(t.isPreloaded()&&1===t.numActive()?(t.release(eu),su=null):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()"))},t.config=V,t.getMaxParallelImageRequests=function(){return V.MAX_PARALLEL_IMAGE_REQUESTS},t.getRTLTextPluginStatus=function(){return Wu().getRTLTextPluginStatus()},t.getVersion=function(){return rg},t.getWorkerCount=function(){return iu.workerCount},t.getWorkerUrl=function(){return V.WORKER_URL},t.importScriptInWorkers=function(t){return lu().broadcast("IS",t)},t.prewarm=function(){au().acquire(eu)},t.removeProtocol=function(t){delete V.REGISTERED_PROTOCOLS[t]},t.setMaxParallelImageRequests=function(t){V.MAX_PARALLEL_IMAGE_REQUESTS=t},t.setRTLTextPlugin=function(t,e){return Wu().setRTLTextPlugin(t,e)},t.setWorkerCount=function(t){iu.workerCount=t},t.setWorkerUrl=function(t){V.WORKER_URL=t}})); +//# sourceMappingURL=maplibre-gl-csp.js.map diff --git a/dist/maplibre-gl-dev.js b/dist/maplibre-gl-dev.js new file mode 100644 index 0000000000..1230ce39e3 --- /dev/null +++ b/dist/maplibre-gl-dev.js @@ -0,0 +1,60817 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v4.7.0/LICENSE.txt + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.maplibregl = factory()); +})(this, (function () { 'use strict'; + +/* eslint-disable */ + +var maplibregl = {}; +var modules = {}; +function define(moduleName, _dependencies, moduleFactory) { + modules[moduleName] = moduleFactory; + + // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) + if (moduleName !== 'index') { + return; + } + + // we assume that when an index module is initializing then other modules are loaded already + var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);' + + var sharedModule = {}; + // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) + // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) + // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following + modules.shared(sharedModule); + modules.index(maplibregl, sharedModule); + + if (typeof window !== 'undefined') { + maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); + } + + return maplibregl; +}; + + + +define('shared', ['exports'], (function (exports) { 'use strict'; + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; + +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; + +function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; + +function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +}; + +function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; + +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +var __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); + +function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +/** @deprecated */ +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}; + +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +} + +function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +function __classPrivateFieldIn(state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} + +function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + +} + +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + function next() { + while (env.stack.length) { + var rec = env.stack.pop(); + try { + var result = rec.dispose && rec.dispose.call(rec.value); + if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + catch (e) { + fail(e); + } + } + if (env.hasError) throw env.error; + } + return next(); +} + +var tslib_es6 = { + __extends: __extends, + __assign: __assign, + __rest: __rest, + __decorate: __decorate, + __param: __param, + __metadata: __metadata, + __awaiter: __awaiter, + __generator: __generator, + __createBinding: __createBinding, + __exportStar: __exportStar, + __values: __values, + __read: __read, + __spread: __spread, + __spreadArrays: __spreadArrays, + __spreadArray: __spreadArray, + __await: __await, + __asyncGenerator: __asyncGenerator, + __asyncDelegator: __asyncDelegator, + __asyncValues: __asyncValues, + __makeTemplateObject: __makeTemplateObject, + __importStar: __importStar, + __importDefault: __importDefault, + __classPrivateFieldGet: __classPrivateFieldGet, + __classPrivateFieldSet: __classPrivateFieldSet, + __classPrivateFieldIn: __classPrivateFieldIn, + __addDisposableResource: __addDisposableResource, + __disposeResources: __disposeResources, +}; + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs$1 (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function getDefaultExportFromNamespaceIfPresent (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; +} + +function getDefaultExportFromNamespaceIfNotNamed (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; +} + +function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a () { + if (this instanceof a) { + return Reflect.construct(f, arguments, this.constructor); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} + +'use strict'; + +var pointGeometry = Point$1; + +/** + * A standalone point geometry with useful accessor, comparison, and + * modification methods. + * + * @class Point + * @param {Number} x the x-coordinate. this could be longitude or screen + * pixels, or any other sort of unit. + * @param {Number} y the y-coordinate. this could be latitude or screen + * pixels, or any other sort of unit. + * @example + * var point = new Point(-77, 38); + */ +function Point$1(x, y) { + this.x = x; + this.y = y; +} + +Point$1.prototype = { + + /** + * Clone this point, returning a new point that can be modified + * without affecting the old one. + * @return {Point} the clone + */ + clone: function() { return new Point$1(this.x, this.y); }, + + /** + * Add this point's x & y coordinates to another point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + add: function(p) { return this.clone()._add(p); }, + + /** + * Subtract this point's x & y coordinates to from point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + sub: function(p) { return this.clone()._sub(p); }, + + /** + * Multiply this point's x & y coordinates by point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + multByPoint: function(p) { return this.clone()._multByPoint(p); }, + + /** + * Divide this point's x & y coordinates by point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + divByPoint: function(p) { return this.clone()._divByPoint(p); }, + + /** + * Multiply this point's x & y coordinates by a factor, + * yielding a new point. + * @param {Point} k factor + * @return {Point} output point + */ + mult: function(k) { return this.clone()._mult(k); }, + + /** + * Divide this point's x & y coordinates by a factor, + * yielding a new point. + * @param {Point} k factor + * @return {Point} output point + */ + div: function(k) { return this.clone()._div(k); }, + + /** + * Rotate this point around the 0, 0 origin by an angle a, + * given in radians + * @param {Number} a angle to rotate around, in radians + * @return {Point} output point + */ + rotate: function(a) { return this.clone()._rotate(a); }, + + /** + * Rotate this point around p point by an angle a, + * given in radians + * @param {Number} a angle to rotate around, in radians + * @param {Point} p Point to rotate around + * @return {Point} output point + */ + rotateAround: function(a,p) { return this.clone()._rotateAround(a,p); }, + + /** + * Multiply this point by a 4x1 transformation matrix + * @param {Array} m transformation matrix + * @return {Point} output point + */ + matMult: function(m) { return this.clone()._matMult(m); }, + + /** + * Calculate this point but as a unit vector from 0, 0, meaning + * that the distance from the resulting point to the 0, 0 + * coordinate will be equal to 1 and the angle from the resulting + * point to the 0, 0 coordinate will be the same as before. + * @return {Point} unit vector point + */ + unit: function() { return this.clone()._unit(); }, + + /** + * Compute a perpendicular point, where the new y coordinate + * is the old x coordinate and the new x coordinate is the old y + * coordinate multiplied by -1 + * @return {Point} perpendicular point + */ + perp: function() { return this.clone()._perp(); }, + + /** + * Return a version of this point with the x & y coordinates + * rounded to integers. + * @return {Point} rounded point + */ + round: function() { return this.clone()._round(); }, + + /** + * Return the magitude of this point: this is the Euclidean + * distance from the 0, 0 coordinate to this point's x and y + * coordinates. + * @return {Number} magnitude + */ + mag: function() { + return Math.sqrt(this.x * this.x + this.y * this.y); + }, + + /** + * Judge whether this point is equal to another point, returning + * true or false. + * @param {Point} other the other point + * @return {boolean} whether the points are equal + */ + equals: function(other) { + return this.x === other.x && + this.y === other.y; + }, + + /** + * Calculate the distance from this point to another point + * @param {Point} p the other point + * @return {Number} distance + */ + dist: function(p) { + return Math.sqrt(this.distSqr(p)); + }, + + /** + * Calculate the distance from this point to another point, + * without the square root step. Useful if you're comparing + * relative distances. + * @param {Point} p the other point + * @return {Number} distance + */ + distSqr: function(p) { + var dx = p.x - this.x, + dy = p.y - this.y; + return dx * dx + dy * dy; + }, + + /** + * Get the angle from the 0, 0 coordinate to this point, in radians + * coordinates. + * @return {Number} angle + */ + angle: function() { + return Math.atan2(this.y, this.x); + }, + + /** + * Get the angle from this point to another point, in radians + * @param {Point} b the other point + * @return {Number} angle + */ + angleTo: function(b) { + return Math.atan2(this.y - b.y, this.x - b.x); + }, + + /** + * Get the angle between this point and another point, in radians + * @param {Point} b the other point + * @return {Number} angle + */ + angleWith: function(b) { + return this.angleWithSep(b.x, b.y); + }, + + /* + * Find the angle of the two vectors, solving the formula for + * the cross product a x b = |a||b|sin(θ) for θ. + * @param {Number} x the x-coordinate + * @param {Number} y the y-coordinate + * @return {Number} the angle in radians + */ + angleWithSep: function(x, y) { + return Math.atan2( + this.x * y - this.y * x, + this.x * x + this.y * y); + }, + + _matMult: function(m) { + var x = m[0] * this.x + m[1] * this.y, + y = m[2] * this.x + m[3] * this.y; + this.x = x; + this.y = y; + return this; + }, + + _add: function(p) { + this.x += p.x; + this.y += p.y; + return this; + }, + + _sub: function(p) { + this.x -= p.x; + this.y -= p.y; + return this; + }, + + _mult: function(k) { + this.x *= k; + this.y *= k; + return this; + }, + + _div: function(k) { + this.x /= k; + this.y /= k; + return this; + }, + + _multByPoint: function(p) { + this.x *= p.x; + this.y *= p.y; + return this; + }, + + _divByPoint: function(p) { + this.x /= p.x; + this.y /= p.y; + return this; + }, + + _unit: function() { + this._div(this.mag()); + return this; + }, + + _perp: function() { + var y = this.y; + this.y = this.x; + this.x = -y; + return this; + }, + + _rotate: function(angle) { + var cos = Math.cos(angle), + sin = Math.sin(angle), + x = cos * this.x - sin * this.y, + y = sin * this.x + cos * this.y; + this.x = x; + this.y = y; + return this; + }, + + _rotateAround: function(angle, p) { + var cos = Math.cos(angle), + sin = Math.sin(angle), + x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y), + y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y); + this.x = x; + this.y = y; + return this; + }, + + _round: function() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } +}; + +/** + * Construct a point from an array if necessary, otherwise if the input + * is already a Point, or an unknown type, return it unchanged + * @param {Array|Point|*} a any kind of input value + * @return {Point} constructed point, or passed-through value. + * @example + * // this + * var point = Point.convert([0, 1]); + * // is equivalent to + * var point = new Point(0, 1); + */ +Point$1.convert = function (a) { + if (a instanceof Point$1) { + return a; + } + if (Array.isArray(a)) { + return new Point$1(a[0], a[1]); + } + return a; +}; + +var Point$2 = /*@__PURE__*/getDefaultExportFromCjs$1(pointGeometry); + +'use strict'; + +var unitbezier$1 = UnitBezier$2; + +function UnitBezier$2(p1x, p1y, p2x, p2y) { + // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). + this.cx = 3.0 * p1x; + this.bx = 3.0 * (p2x - p1x) - this.cx; + this.ax = 1.0 - this.cx - this.bx; + + this.cy = 3.0 * p1y; + this.by = 3.0 * (p2y - p1y) - this.cy; + this.ay = 1.0 - this.cy - this.by; + + this.p1x = p1x; + this.p1y = p1y; + this.p2x = p2x; + this.p2y = p2y; +} + +UnitBezier$2.prototype = { + sampleCurveX: function (t) { + // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. + return ((this.ax * t + this.bx) * t + this.cx) * t; + }, + + sampleCurveY: function (t) { + return ((this.ay * t + this.by) * t + this.cy) * t; + }, + + sampleCurveDerivativeX: function (t) { + return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; + }, + + solveCurveX: function (x, epsilon) { + if (epsilon === undefined) epsilon = 1e-6; + + if (x < 0.0) return 0.0; + if (x > 1.0) return 1.0; + + var t = x; + + // First try a few iterations of Newton's method - normally very fast. + for (var i = 0; i < 8; i++) { + var x2 = this.sampleCurveX(t) - x; + if (Math.abs(x2) < epsilon) return t; + + var d2 = this.sampleCurveDerivativeX(t); + if (Math.abs(d2) < 1e-6) break; + + t = t - x2 / d2; + } + + // Fall back to the bisection method for reliability. + var t0 = 0.0; + var t1 = 1.0; + t = x; + + for (i = 0; i < 20; i++) { + x2 = this.sampleCurveX(t); + if (Math.abs(x2 - x) < epsilon) break; + + if (x > x2) { + t0 = t; + } else { + t1 = t; + } + + t = (t1 - t0) * 0.5 + t0; + } + + return t; + }, + + solve: function (x, epsilon) { + return this.sampleCurveY(this.solveCurveX(x, epsilon)); + } +}; + +var UnitBezier$3 = /*@__PURE__*/getDefaultExportFromCjs$1(unitbezier$1); + +let supportsOffscreenCanvas; +function offscreenCanvasSupported() { + if (supportsOffscreenCanvas == null) { + supportsOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && + new OffscreenCanvas(1, 1).getContext('2d') && + typeof createImageBitmap === 'function'; + } + return supportsOffscreenCanvas; +} + +let offscreenCanvasDistorted; +/** + * Some browsers don't return the exact pixels from a canvas to prevent user fingerprinting (see #3185). + * This function writes pixels to an OffscreenCanvas and reads them back using getImageData, returning false + * if they don't match. + * + * @returns true if the browser supports OffscreenCanvas but it distorts getImageData results, false otherwise. + */ +function isOffscreenCanvasDistorted() { + if (offscreenCanvasDistorted == null) { + offscreenCanvasDistorted = false; + if (offscreenCanvasSupported()) { + const size = 5; + const canvas = new OffscreenCanvas(size, size); + const context = canvas.getContext('2d', { willReadFrequently: true }); + if (context) { + // fill each pixel with an RGB value that should make the byte at index i equal to i (except alpha channel): + // [0, 1, 2, 255, 4, 5, 6, 255, 8, 9, 10, 255, ...] + for (let i = 0; i < size * size; i++) { + const base = i * 4; + context.fillStyle = `rgb(${base},${base + 1},${base + 2})`; + context.fillRect(i % size, Math.floor(i / size), 1, 1); + } + const data = context.getImageData(0, 0, size, size).data; + for (let i = 0; i < size * size * 4; i++) { + if (i % 4 !== 3 && data[i] !== i) { + offscreenCanvasDistorted = true; + break; + } + } + } + } + } + return offscreenCanvasDistorted || false; +} + +/** + * For a given collection of 2D points, returns their axis-aligned bounding box, + * in the format [minX, minY, maxX, maxY]. + */ +function getAABB(points) { + let tlX = Infinity; + let tlY = Infinity; + let brX = -Infinity; + let brY = -Infinity; + for (const p of points) { + tlX = Math.min(tlX, p.x); + tlY = Math.min(tlY, p.y); + brX = Math.max(brX, p.x); + brY = Math.max(brY, p.y); + } + return [tlX, tlY, brX, brY]; +} +/** + * Given a value `t` that varies between 0 and 1, return + * an interpolation function that eases between 0 and 1 in a pleasing + * cubic in-out fashion. + */ +function easeCubicInOut(t) { + if (t <= 0) + return 0; + if (t >= 1) + return 1; + const t2 = t * t, t3 = t2 * t; + return 4 * (t < 0.5 ? t3 : 3 * (t - t2) + t3 - 0.75); +} +/** + * Given given (x, y), (x1, y1) control points for a bezier curve, + * return a function that interpolates along that curve. + * + * @param p1x - control point 1 x coordinate + * @param p1y - control point 1 y coordinate + * @param p2x - control point 2 x coordinate + * @param p2y - control point 2 y coordinate + */ +function bezier$1(p1x, p1y, p2x, p2y) { + const bezier = new UnitBezier$3(p1x, p1y, p2x, p2y); + return (t) => { + return bezier.solve(t); + }; +} +/** + * A default bezier-curve powered easing function with + * control points (0.25, 0.1) and (0.25, 1) + */ +const defaultEasing = bezier$1(0.25, 0.1, 0.25, 1); +/** + * constrain n to the given range via min + max + * + * @param n - value + * @param min - the minimum value to be returned + * @param max - the maximum value to be returned + * @returns the clamped value + */ +function clamp$1(n, min, max) { + return Math.min(max, Math.max(min, n)); +} +/** + * constrain n to the given range, excluding the minimum, via modular arithmetic + * + * @param n - value + * @param min - the minimum value to be returned, exclusive + * @param max - the maximum value to be returned, inclusive + * @returns constrained number + */ +function wrap(n, min, max) { + const d = max - min; + const w = ((n - min) % d + d) % d + min; + return (w === min) ? max : w; +} +/** + * Compute the difference between the keys in one object and the keys + * in another object. + * + * @returns keys difference + */ +function keysDifference(obj, other) { + const difference = []; + for (const i in obj) { + if (!(i in other)) { + difference.push(i); + } + } + return difference; +} +function extend(dest, ...sources) { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; +} +/** + * Given an object and a number of properties as strings, return version + * of that object with only those properties. + * + * @param src - the object + * @param properties - an array of property names chosen + * to appear on the resulting object. + * @returns object with limited properties. + * @example + * ```ts + * let foo = { name: 'Charlie', age: 10 }; + * let justName = pick(foo, ['name']); // justName = { name: 'Charlie' } + * ``` + */ +function pick(src, properties) { + const result = {}; + for (let i = 0; i < properties.length; i++) { + const k = properties[i]; + if (k in src) { + result[k] = src[k]; + } + } + return result; +} +let id = 1; +/** + * Return a unique numeric id, starting at 1 and incrementing with + * each call. + * + * @returns unique numeric id. + */ +function uniqueId() { + return id++; +} +/** + * Return whether a given value is a power of two + */ +function isPowerOfTwo(value) { + return (Math.log(value) / Math.LN2) % 1 === 0; +} +/** + * Return the next power of two, or the input value if already a power of two + */ +function nextPowerOfTwo(value) { + if (value <= 1) + return 1; + return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2)); +} +/** + * Create an object by mapping all the values of an existing object while + * preserving their keys. + */ +function mapObject(input, iterator, context) { + const output = {}; + for (const key in input) { + output[key] = iterator.call(context || this, input[key], key, input); + } + return output; +} +/** + * Create an object by filtering out values of an existing object. + */ +function filterObject(input, iterator, context) { + const output = {}; + for (const key in input) { + if (iterator.call(context || this, input[key], key, input)) { + output[key] = input[key]; + } + } + return output; +} +/** + * Deeply compares two object literals. + * @param a - first object literal to be compared + * @param b - second object literal to be compared + * @returns true if the two object literals are deeply equal, false otherwise + */ +function deepEqual$1(a, b) { + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) { + if (!deepEqual$1(a[i], b[i])) + return false; + } + return true; + } + if (typeof a === 'object' && a !== null && b !== null) { + if (!(typeof b === 'object')) + return false; + const keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) + return false; + for (const key in a) { + if (!deepEqual$1(a[key], b[key])) + return false; + } + return true; + } + return a === b; +} +/** + * Deeply clones two objects. + */ +function clone$9(input) { + if (Array.isArray(input)) { + return input.map(clone$9); + } + else if (typeof input === 'object' && input) { + return mapObject(input, clone$9); + } + else { + return input; + } +} +/** + * Check if two arrays have at least one common element. + */ +function arraysIntersect(a, b) { + for (let l = 0; l < a.length; l++) { + if (b.indexOf(a[l]) >= 0) + return true; + } + return false; +} +/** + * Print a warning message to the console and ensure duplicate warning messages + * are not printed. + */ +const warnOnceHistory = {}; +function warnOnce(message) { + if (!warnOnceHistory[message]) { + // console isn't defined in some WebWorkers, see #2558 + if (typeof console !== 'undefined') + console.warn(message); + warnOnceHistory[message] = true; + } +} +/** + * Indicates if the provided Points are in a counter clockwise (true) or clockwise (false) order + * + * @returns true for a counter clockwise set of points + */ +// https://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/ +function isCounterClockwise(a, b, c) { + return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x); +} +/** + * For two lines a and b in 2d space, defined by any two points along the lines, + * find the intersection point, or return null if the lines are parallel + * + * @param a1 - First point on line a + * @param a2 - Second point on line a + * @param b1 - First point on line b + * @param b2 - Second point on line b + * + * @returns the intersection point of the two lines or null if they are parallel + */ +function findLineIntersection(a1, a2, b1, b2) { + const aDeltaY = a2.y - a1.y; + const aDeltaX = a2.x - a1.x; + const bDeltaY = b2.y - b1.y; + const bDeltaX = b2.x - b1.x; + const denominator = (bDeltaY * aDeltaX) - (bDeltaX * aDeltaY); + if (denominator === 0) { + // Lines are parallel + return null; + } + const originDeltaY = a1.y - b1.y; + const originDeltaX = a1.x - b1.x; + const aInterpolation = (bDeltaX * originDeltaY - bDeltaY * originDeltaX) / denominator; + // Find intersection by projecting out from origin of first segment + return new Point$2(a1.x + (aInterpolation * aDeltaX), a1.y + (aInterpolation * aDeltaY)); +} +/** + * Converts spherical coordinates to cartesian coordinates. + * + * @param spherical - Spherical coordinates, in [radial, azimuthal, polar] + * @returns cartesian coordinates in [x, y, z] + */ +function sphericalToCartesian([r, azimuthal, polar]) { + // We abstract "north"/"up" (compass-wise) to be 0° when really this is 90° (π/2): + // correct for that here + azimuthal += 90; + // Convert azimuthal and polar angles to radians + azimuthal *= Math.PI / 180; + polar *= Math.PI / 180; + return { + x: r * Math.cos(azimuthal) * Math.sin(polar), + y: r * Math.sin(azimuthal) * Math.sin(polar), + z: r * Math.cos(polar) + }; +} +/** + * Returns true if the when run in the web-worker context. + * + * @returns `true` if the when run in the web-worker context. + */ +function isWorker(self) { + // @ts-ignore + return typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof WorkerGlobalScope; +} +/** + * Parses data from 'Cache-Control' headers. + * + * @param cacheControl - Value of 'Cache-Control' header + * @returns object containing parsed header info. + */ +function parseCacheControl(cacheControl) { + // Taken from [Wreck](https://github.com/hapijs/wreck) + const re = /(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g; + const header = {}; + cacheControl.replace(re, ($0, $1, $2, $3) => { + const value = $2 || $3; + header[$1] = value ? value.toLowerCase() : true; + return ''; + }); + if (header['max-age']) { + const maxAge = parseInt(header['max-age'], 10); + if (isNaN(maxAge)) + delete header['max-age']; + else + header['max-age'] = maxAge; + } + return header; +} +let _isSafari = null; +/** + * Returns true when run in WebKit derived browsers. + * This is used as a workaround for a memory leak in Safari caused by using Transferable objects to + * transfer data between WebWorkers and the main thread. + * https://github.com/mapbox/mapbox-gl-js/issues/8771 + * + * This should be removed once the underlying Safari issue is fixed. + * + * @param scope - Since this function is used both on the main thread and WebWorker context, + * let the calling scope pass in the global scope object. + * @returns `true` when run in WebKit derived browsers. + */ +function isSafari(scope) { + if (_isSafari == null) { + const userAgent = scope.navigator ? scope.navigator.userAgent : null; + _isSafari = !!scope.safari || + !!(userAgent && (/\b(iPad|iPhone|iPod)\b/.test(userAgent) || (!!userAgent.match('Safari') && !userAgent.match('Chrome')))); + } + return _isSafari; +} +function storageAvailable(type) { + try { + const storage = window[type]; + storage.setItem('_mapbox_test_', 1); + storage.removeItem('_mapbox_test_'); + return true; + } + catch (e) { + return false; + } +} +// The following methods are from https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem +//Unicode compliant base64 encoder for strings +function b64EncodeUnicode(str) { + return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => { + return String.fromCharCode(Number('0x' + p1)); //eslint-disable-line + })); +} +// Unicode compliant decoder for base64-encoded strings +function b64DecodeUnicode(str) { + return decodeURIComponent(atob(str).split('').map((c) => { + return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); //eslint-disable-line + }).join('')); +} +function isImageBitmap(image) { + return typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap; +} +/** + * Converts an ArrayBuffer to an ImageBitmap. + * + * Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work + * perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting + * ArrayBuffers. + * + * @param data - Data to convert + * @returns - A promise resolved when the conversion is finished + */ +const arrayBufferToImageBitmap = (data) => __awaiter(void 0, void 0, void 0, function* () { + if (data.byteLength === 0) { + return createImageBitmap(new ImageData(1, 1)); + } + const blob = new Blob([new Uint8Array(data)], { type: 'image/png' }); + try { + return createImageBitmap(blob); + } + catch (e) { + throw 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.`); + } +}); +const transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII='; +/** + * Converts an ArrayBuffer to an HTMLImageElement. + * + * Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work + * perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting + * ArrayBuffers. + * + * @param data - Data to convert + * @returns - A promise resolved when the conversion is finished + */ +const arrayBufferToImage = (data) => { + return new Promise((resolve, reject) => { + const img = new Image(); + img.onload = () => { + resolve(img); + URL.revokeObjectURL(img.src); + // prevent image dataURI memory leak in Safari; + // but don't free the image immediately because it might be uploaded in the next frame + // https://github.com/mapbox/mapbox-gl-js/issues/10226 + img.onload = null; + window.requestAnimationFrame(() => { img.src = transparentPngUrl; }); + }; + img.onerror = () => reject(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.')); + const blob = new Blob([new Uint8Array(data)], { type: 'image/png' }); + img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl; + }); +}; +/** + * Computes the webcodecs VideoFrame API options to select a rectangle out of + * an image and write it into the destination rectangle. + * + * Rect (x/y/width/height) select the overlapping rectangle from the source image + * and layout (offset/stride) write that overlapping rectangle to the correct place + * in the destination image. + * + * Offset is the byte offset in the dest image that the first pixel appears at + * and stride is the number of bytes to the start of the next row: + * ┌───────────┐ + * │ dest │ + * │ ┌───┼───────┐ + * │offset→│▓▓▓│ source│ + * │ │▓▓▓│ │ + * │ └───┼───────┘ + * │stride ⇠╌╌╌│ + * │╌╌╌╌╌╌→ │ + * └───────────┘ + * + * @param image - source image containing a width and height attribute + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns the layout and rect options to pass into VideoFrame API + */ +function computeVideoFrameParameters(image, x, y, width, height) { + const destRowOffset = Math.max(-x, 0) * 4; + const firstSourceRow = Math.max(0, y); + const firstDestRow = firstSourceRow - y; + const offset = firstDestRow * width * 4 + destRowOffset; + const stride = width * 4; + const sourceLeft = Math.max(0, x); + const sourceTop = Math.max(0, y); + const sourceRight = Math.min(image.width, x + width); + const sourceBottom = Math.min(image.height, y + height); + return { + rect: { + x: sourceLeft, + y: sourceTop, + width: sourceRight - sourceLeft, + height: sourceBottom - sourceTop + }, + layout: [{ offset, stride }] + }; +} +/** + * Reads pixels from an ImageBitmap/Image/canvas using webcodec VideoFrame API. + * + * @param data - image, imagebitmap, or canvas to parse + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred + */ +function readImageUsingVideoFrame(image, x, y, width, height) { + return __awaiter(this, void 0, void 0, function* () { + if (typeof VideoFrame === 'undefined') { + throw new Error('VideoFrame not supported'); + } + const frame = new VideoFrame(image, { timestamp: 0 }); + try { + const format = frame === null || frame === void 0 ? void 0 : frame.format; + if (!format || !(format.startsWith('BGR') || format.startsWith('RGB'))) { + throw new Error(`Unrecognized format ${format}`); + } + const swapBR = format.startsWith('BGR'); + const result = new Uint8ClampedArray(width * height * 4); + yield frame.copyTo(result, computeVideoFrameParameters(image, x, y, width, height)); + if (swapBR) { + for (let i = 0; i < result.length; i += 4) { + const tmp = result[i]; + result[i] = result[i + 2]; + result[i + 2] = tmp; + } + } + return result; + } + finally { + frame.close(); + } + }); +} +let offscreenCanvas; +let offscreenCanvasContext; +/** + * Reads pixels from an ImageBitmap/Image/canvas using OffscreenCanvas + * + * @param data - image, imagebitmap, or canvas to parse + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred + */ +function readImageDataUsingOffscreenCanvas(imgBitmap, x, y, width, height) { + const origWidth = imgBitmap.width; + const origHeight = imgBitmap.height; + // Lazily initialize OffscreenCanvas + if (!offscreenCanvas || !offscreenCanvasContext) { + // Dem tiles are typically 256x256 + offscreenCanvas = new OffscreenCanvas(origWidth, origHeight); + offscreenCanvasContext = offscreenCanvas.getContext('2d', { willReadFrequently: true }); + } + offscreenCanvas.width = origWidth; + offscreenCanvas.height = origHeight; + offscreenCanvasContext.drawImage(imgBitmap, 0, 0, origWidth, origHeight); + const imgData = offscreenCanvasContext.getImageData(x, y, width, height); + offscreenCanvasContext.clearRect(0, 0, origWidth, origHeight); + return imgData.data; +} +/** + * Reads RGBA pixels from an preferring OffscreenCanvas, but falling back to VideoFrame if supported and + * the browser is mangling OffscreenCanvas getImageData results. + * + * @param data - image, imagebitmap, or canvas to parse + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns a promise containing the parsed RGBA pixel values of the image + */ +function getImageData(image, x, y, width, height) { + return __awaiter(this, void 0, void 0, function* () { + if (isOffscreenCanvasDistorted()) { + try { + return yield readImageUsingVideoFrame(image, x, y, width, height); + } + catch (e) { + // fall back to OffscreenCanvas + } + } + return readImageDataUsingOffscreenCanvas(image, x, y, width, height); + }); +} +/** + * This method is used in order to register an event listener using a lambda function. + * The return value will allow unsubscribing from the event, without the need to store the method reference. + * @param target - The target + * @param message - The message + * @param listener - The listener + * @param options - The options + * @returns a subscription object that can be used to unsubscribe from the event + */ +function subscribe(target, message, listener, options) { + target.addEventListener(message, listener, options); + return { + unsubscribe: () => { + target.removeEventListener(message, listener, options); + } + }; +} +/** + * This method converts degrees to radians. + * The return value is the radian value. + * @param degrees - The number of degrees + * @returns radians + */ +function degreesToRadians(degrees) { + return degrees * Math.PI / 180; +} +/** + * The maximum world tile zoom (Z). + * In other words, the upper bound supported for tile zoom. + */ +const MAX_TILE_ZOOM = 25; +/** + * The minimum world tile zoom (Z). + * In other words, the lower bound supported for tile zoom. + */ +const MIN_TILE_ZOOM = 0; + +/** + * An error message to use when an operation is aborted + */ +const ABORT_ERROR = 'AbortError'; +/** + * Check if an error is an abort error + * @param error - An error object + * @returns - true if the error is an abort error + */ +function isAbortError(error) { + return error.message === ABORT_ERROR; +} +/** + * Use this when you need to create an abort error. + * @returns An error object with the message "AbortError" + */ +function createAbortError() { + return new Error(ABORT_ERROR); +} + +const config = { + MAX_PARALLEL_IMAGE_REQUESTS: 16, + MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME: 8, + MAX_TILE_CACHE_ZOOM_LEVELS: 5, + REGISTERED_PROTOCOLS: {}, + WORKER_URL: '' +}; + +function getProtocol(url) { + return config.REGISTERED_PROTOCOLS[url.substring(0, url.indexOf('://'))]; +} +/** + * Adds a custom load resource function that will be called when using a URL that starts with a custom url schema. + * This will happen in the main thread, and workers might call it if they don't know how to handle the protocol. + * The example below will be triggered for custom:// urls defined in the sources list in the style definitions. + * The function passed will receive the request parameters and should return with the resulting resource, + * for example a pbf vector tile, non-compressed, represented as ArrayBuffer. + * + * @param customProtocol - the protocol to hook, for example 'custom' + * @param loadFn - the function to use when trying to fetch a tile specified by the customProtocol + * @example + * ```ts + * // This will fetch a file using the fetch API (this is obviously a non interesting example...) + * addProtocol('custom', async (params, abortController) => { + * const t = await fetch(`https://${params.url.split("://")[1]}`); + * if (t.status == 200) { + * const buffer = await t.arrayBuffer(); + * return {data: buffer} + * } else { + * throw new Error(`Tile fetch error: ${t.statusText}`); + * } + * }); + * // the following is an example of a way to return an error when trying to load a tile + * addProtocol('custom2', async (params, abortController) => { + * throw new Error('someErrorMessage')); + * }); + * ``` + */ +function addProtocol(customProtocol, loadFn) { + config.REGISTERED_PROTOCOLS[customProtocol] = loadFn; +} +/** + * Removes a previously added protocol in the main thread. + * + * @param customProtocol - the custom protocol to remove registration for + * @example + * ```ts + * removeProtocol('custom'); + * ``` + */ +function removeProtocol(customProtocol) { + delete config.REGISTERED_PROTOCOLS[customProtocol]; +} + +/** + * This is used to identify the global dispatcher id when sending a message from the worker without a target map id. + */ +const GLOBAL_DISPATCHER_ID = 'global-dispatcher'; +/** + * An error thrown when a HTTP request results in an error response. + */ +class AJAXError extends Error { + /** + * @param status - The response's HTTP status code. + * @param statusText - The response's HTTP status text. + * @param url - The request's URL. + * @param body - The response's body. + */ + constructor(status, statusText, url, body) { + super(`AJAXError: ${statusText} (${status}): ${url}`); + this.status = status; + this.statusText = statusText; + this.url = url; + this.body = body; + } +} +/** + * Ensure that we're sending the correct referrer from blob URL worker bundles. + * For files loaded from the local file system, `location.origin` will be set + * to the string(!) "null" (Firefox), or "file://" (Chrome, Safari, Edge), + * and we will set an empty referrer. Otherwise, we're using the document's URL. + */ +const getReferrer = () => isWorker(self) ? + self.worker && self.worker.referrer : + (window.location.protocol === 'blob:' ? window.parent : window).location.href; +/** + * Determines whether a URL is a file:// URL. This is obviously the case if it begins + * with file://. Relative URLs are also file:// URLs iff the original document was loaded + * via a file:// URL. + * @param url - The URL to check + * @returns `true` if the URL is a file:// URL, `false` otherwise + */ +const isFileURL = url => /^file:/.test(url) || (/^file:/.test(getReferrer()) && !/^\w+:/.test(url)); +function makeFetchRequest(requestParameters, abortController) { + return __awaiter(this, void 0, void 0, function* () { + const request = new Request(requestParameters.url, { + method: requestParameters.method || 'GET', + body: requestParameters.body, + credentials: requestParameters.credentials, + headers: requestParameters.headers, + cache: requestParameters.cache, + referrer: getReferrer(), + signal: abortController.signal + }); + // If the user has already set an Accept header, do not overwrite it here + if (requestParameters.type === 'json' && !request.headers.has('Accept')) { + request.headers.set('Accept', 'application/json'); + } + const response = yield fetch(request); + if (!response.ok) { + const body = yield response.blob(); + throw new AJAXError(response.status, response.statusText, requestParameters.url, body); + } + let parsePromise; + if ((requestParameters.type === 'arrayBuffer' || requestParameters.type === 'image')) { + parsePromise = response.arrayBuffer(); + } + else if (requestParameters.type === 'json') { + parsePromise = response.json(); + } + else { + parsePromise = response.text(); + } + const result = yield parsePromise; + if (abortController.signal.aborted) { + throw createAbortError(); + } + return { data: result, cacheControl: response.headers.get('Cache-Control'), expires: response.headers.get('Expires') }; + }); +} +function makeXMLHttpRequest(requestParameters, abortController) { + return new Promise((resolve, reject) => { + var _a; + const xhr = new XMLHttpRequest(); + xhr.open(requestParameters.method || 'GET', requestParameters.url, true); + if (requestParameters.type === 'arrayBuffer' || requestParameters.type === 'image') { + xhr.responseType = 'arraybuffer'; + } + for (const k in requestParameters.headers) { + xhr.setRequestHeader(k, requestParameters.headers[k]); + } + if (requestParameters.type === 'json') { + xhr.responseType = 'text'; + // Do not overwrite the user-provided Accept header + if (!((_a = requestParameters.headers) === null || _a === void 0 ? void 0 : _a.Accept)) { + xhr.setRequestHeader('Accept', 'application/json'); + } + } + xhr.withCredentials = requestParameters.credentials === 'include'; + xhr.onerror = () => { + reject(new Error(xhr.statusText)); + }; + xhr.onload = () => { + if (abortController.signal.aborted) { + return; + } + if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response !== null) { + let data = xhr.response; + if (requestParameters.type === 'json') { + // We're manually parsing JSON here to get better error messages. + try { + data = JSON.parse(xhr.response); + } + catch (err) { + reject(err); + return; + } + } + resolve({ data, cacheControl: xhr.getResponseHeader('Cache-Control'), expires: xhr.getResponseHeader('Expires') }); + } + else { + const body = new Blob([xhr.response], { type: xhr.getResponseHeader('Content-Type') }); + reject(new AJAXError(xhr.status, xhr.statusText, requestParameters.url, body)); + } + }; + abortController.signal.addEventListener('abort', () => { + xhr.abort(); + reject(createAbortError()); + }); + xhr.send(requestParameters.body); + }); +} +/** + * We're trying to use the Fetch API if possible. However, requests for resources with the file:// URI scheme don't work with the Fetch API. + * In this case we unconditionally use XHR on the current thread since referrers don't matter. + * This method can also use the registered method if `addProtocol` was called. + * @param requestParameters - The request parameters + * @param abortController - The abort controller allowing to cancel the request + * @returns a promise resolving to the response, including cache control and expiry data + */ +const makeRequest = function (requestParameters, abortController) { + if (/:\/\//.test(requestParameters.url) && !(/^https?:|^file:/.test(requestParameters.url))) { + const protocolLoadFn = getProtocol(requestParameters.url); + if (protocolLoadFn) { + return protocolLoadFn(requestParameters, abortController); + } + if (isWorker(self) && self.worker && self.worker.actor) { + return self.worker.actor.sendAsync({ type: "GR" /* MessageType.getResource */, data: requestParameters, targetMapId: GLOBAL_DISPATCHER_ID }, abortController); + } + } + if (!isFileURL(requestParameters.url)) { + if (fetch && Request && AbortController && Object.prototype.hasOwnProperty.call(Request.prototype, 'signal')) { + return makeFetchRequest(requestParameters, abortController); + } + if (isWorker(self) && self.worker && self.worker.actor) { + return self.worker.actor.sendAsync({ type: "GR" /* MessageType.getResource */, data: requestParameters, mustQueue: true, targetMapId: GLOBAL_DISPATCHER_ID }, abortController); + } + } + return makeXMLHttpRequest(requestParameters, abortController); +}; +const getJSON = (requestParameters, abortController) => { + return makeRequest(extend(requestParameters, { type: 'json' }), abortController); +}; +const getArrayBuffer = (requestParameters, abortController) => { + return makeRequest(extend(requestParameters, { type: 'arrayBuffer' }), abortController); +}; +function sameOrigin(inComingUrl) { + // A relative URL "/foo" or "./foo" will throw exception in URL's ctor, + // try-catch is expansive so just use a heuristic check to avoid it + // also check data URL + if (!inComingUrl || + inComingUrl.indexOf('://') <= 0 || // relative URL + inComingUrl.indexOf('data:image/') === 0 || // data image URL + inComingUrl.indexOf('blob:') === 0) { // blob + return true; + } + const urlObj = new URL(inComingUrl); + const locationObj = window.location; + return urlObj.protocol === locationObj.protocol && urlObj.host === locationObj.host; +} +const getVideo = (urls) => { + const video = window.document.createElement('video'); + video.muted = true; + return new Promise((resolve) => { + video.onloadstart = () => { + resolve(video); + }; + for (const url of urls) { + const s = window.document.createElement('source'); + if (!sameOrigin(url)) { + video.crossOrigin = 'Anonymous'; + } + s.src = url; + video.appendChild(s); + } + }); +}; + +function _addEventListener(type, listener, listenerList) { + const listenerExists = listenerList[type] && listenerList[type].indexOf(listener) !== -1; + if (!listenerExists) { + listenerList[type] = listenerList[type] || []; + listenerList[type].push(listener); + } +} +function _removeEventListener(type, listener, listenerList) { + if (listenerList && listenerList[type]) { + const index = listenerList[type].indexOf(listener); + if (index !== -1) { + listenerList[type].splice(index, 1); + } + } +} +/** + * The event class + */ +class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } +} +/** + * An error event + */ +class ErrorEvent extends Event { + constructor(error, data = {}) { + super('error', extend({ error }, data)); + } +} +/** + * Methods mixed in to other classes for event capabilities. + * + * @group Event Related + */ +class Evented { + /** + * Adds a listener to a specified event type. + * + * @param type - The event type to add a listen for. + * @param listener - The function to be called when the event is fired. + * The listener function is called with the data object passed to `fire`, + * extended with `target` and `type` properties. + */ + on(type, listener) { + this._listeners = this._listeners || {}; + _addEventListener(type, listener, this._listeners); + return this; + } + /** + * Removes a previously registered event listener. + * + * @param type - The event type to remove listeners for. + * @param listener - The listener function to remove. + */ + off(type, listener) { + _removeEventListener(type, listener, this._listeners); + _removeEventListener(type, listener, this._oneTimeListeners); + return this; + } + /** + * Adds a listener that will be called only once to a specified event type. + * + * The listener will be called first time the event fires after the listener is registered. + * + * @param type - The event type to listen for. + * @param listener - The function to be called when the event is fired the first time. + * @returns `this` or a promise if a listener is not provided + */ + once(type, listener) { + if (!listener) { + return new Promise((resolve) => this.once(type, resolve)); + } + this._oneTimeListeners = this._oneTimeListeners || {}; + _addEventListener(type, listener, this._oneTimeListeners); + return this; + } + fire(event, properties) { + // Compatibility with (type: string, properties: Object) signature from previous versions. + // See https://github.com/mapbox/mapbox-gl-js/issues/6522, + // https://github.com/mapbox/mapbox-gl-draw/issues/766 + if (typeof event === 'string') { + event = new Event(event, properties || {}); + } + const type = event.type; + if (this.listens(type)) { + event.target = this; + // make sure adding or removing listeners inside other listeners won't cause an infinite loop + const listeners = this._listeners && this._listeners[type] ? this._listeners[type].slice() : []; + for (const listener of listeners) { + listener.call(this, event); + } + const oneTimeListeners = this._oneTimeListeners && this._oneTimeListeners[type] ? this._oneTimeListeners[type].slice() : []; + for (const listener of oneTimeListeners) { + _removeEventListener(type, listener, this._oneTimeListeners); + listener.call(this, event); + } + const parent = this._eventedParent; + if (parent) { + extend(event, typeof this._eventedParentData === 'function' ? this._eventedParentData() : this._eventedParentData); + parent.fire(event); + } + // To ensure that no error events are dropped, print them to the + // console if they have no listeners. + } + else if (event instanceof ErrorEvent) { + console.error(event.error); + } + return this; + } + /** + * Returns a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type. + * + * @param type - The event type + * @returns `true` if there is at least one registered listener for specified event type, `false` otherwise + */ + listens(type) { + return ((this._listeners && this._listeners[type] && this._listeners[type].length > 0) || + (this._oneTimeListeners && this._oneTimeListeners[type] && this._oneTimeListeners[type].length > 0) || + (this._eventedParent && this._eventedParent.listens(type))); + } + /** + * Bubble all events fired by this instance of Evented to this parent instance of Evented. + */ + setEventedParent(parent, data) { + this._eventedParent = parent; + this._eventedParentData = data; + return this; + } +} + +var $version = 8; +var $root = { + version: { + required: true, + type: "enum", + values: [ + 8 + ] + }, + name: { + type: "string" + }, + metadata: { + type: "*" + }, + center: { + type: "array", + value: "number" + }, + zoom: { + type: "number" + }, + bearing: { + type: "number", + "default": 0, + period: 360, + units: "degrees" + }, + pitch: { + type: "number", + "default": 0, + units: "degrees" + }, + light: { + type: "light" + }, + sky: { + type: "sky" + }, + projection: { + type: "projection" + }, + terrain: { + type: "terrain" + }, + sources: { + required: true, + type: "sources" + }, + sprite: { + type: "sprite" + }, + glyphs: { + type: "string" + }, + transition: { + type: "transition" + }, + layers: { + required: true, + type: "array", + value: "layer" + } +}; +var sources = { + "*": { + type: "source" + } +}; +var source = [ + "source_vector", + "source_raster", + "source_raster_dem", + "source_geojson", + "source_video", + "source_image" +]; +var source_vector = { + type: { + required: true, + type: "enum", + values: { + vector: { + } + } + }, + url: { + type: "string" + }, + tiles: { + type: "array", + value: "string" + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ] + }, + scheme: { + type: "enum", + values: { + xyz: { + }, + tms: { + } + }, + "default": "xyz" + }, + minzoom: { + type: "number", + "default": 0 + }, + maxzoom: { + type: "number", + "default": 22 + }, + attribution: { + type: "string" + }, + promoteId: { + type: "promoteId" + }, + volatile: { + type: "boolean", + "default": false + }, + "*": { + type: "*" + } +}; +var source_raster = { + type: { + required: true, + type: "enum", + values: { + raster: { + } + } + }, + url: { + type: "string" + }, + tiles: { + type: "array", + value: "string" + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ] + }, + minzoom: { + type: "number", + "default": 0 + }, + maxzoom: { + type: "number", + "default": 22 + }, + tileSize: { + type: "number", + "default": 512, + units: "pixels" + }, + scheme: { + type: "enum", + values: { + xyz: { + }, + tms: { + } + }, + "default": "xyz" + }, + attribution: { + type: "string" + }, + volatile: { + type: "boolean", + "default": false + }, + "*": { + type: "*" + } +}; +var source_raster_dem = { + type: { + required: true, + type: "enum", + values: { + "raster-dem": { + } + } + }, + url: { + type: "string" + }, + tiles: { + type: "array", + value: "string" + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ] + }, + minzoom: { + type: "number", + "default": 0 + }, + maxzoom: { + type: "number", + "default": 22 + }, + tileSize: { + type: "number", + "default": 512, + units: "pixels" + }, + attribution: { + type: "string" + }, + encoding: { + type: "enum", + values: { + terrarium: { + }, + mapbox: { + }, + custom: { + } + }, + "default": "mapbox" + }, + redFactor: { + type: "number", + "default": 1 + }, + blueFactor: { + type: "number", + "default": 1 + }, + greenFactor: { + type: "number", + "default": 1 + }, + baseShift: { + type: "number", + "default": 0 + }, + volatile: { + type: "boolean", + "default": false + }, + "*": { + type: "*" + } +}; +var source_geojson = { + type: { + required: true, + type: "enum", + values: { + geojson: { + } + } + }, + data: { + required: true, + type: "*" + }, + maxzoom: { + type: "number", + "default": 18 + }, + attribution: { + type: "string" + }, + buffer: { + type: "number", + "default": 128, + maximum: 512, + minimum: 0 + }, + filter: { + type: "*" + }, + tolerance: { + type: "number", + "default": 0.375 + }, + cluster: { + type: "boolean", + "default": false + }, + clusterRadius: { + type: "number", + "default": 50, + minimum: 0 + }, + clusterMaxZoom: { + type: "number" + }, + clusterMinPoints: { + type: "number" + }, + clusterProperties: { + type: "*" + }, + lineMetrics: { + type: "boolean", + "default": false + }, + generateId: { + type: "boolean", + "default": false + }, + promoteId: { + type: "promoteId" + } +}; +var source_video = { + type: { + required: true, + type: "enum", + values: { + video: { + } + } + }, + urls: { + required: true, + type: "array", + value: "string" + }, + coordinates: { + required: true, + type: "array", + length: 4, + value: { + type: "array", + length: 2, + value: "number" + } + } +}; +var source_image = { + type: { + required: true, + type: "enum", + values: { + image: { + } + } + }, + url: { + required: true, + type: "string" + }, + coordinates: { + required: true, + type: "array", + length: 4, + value: { + type: "array", + length: 2, + value: "number" + } + } +}; +var layer = { + id: { + type: "string", + required: true + }, + type: { + type: "enum", + values: { + fill: { + }, + line: { + }, + symbol: { + }, + circle: { + }, + heatmap: { + }, + "fill-extrusion": { + }, + raster: { + }, + hillshade: { + }, + background: { + } + }, + required: true + }, + metadata: { + type: "*" + }, + source: { + type: "string" + }, + "source-layer": { + type: "string" + }, + minzoom: { + type: "number", + minimum: 0, + maximum: 24 + }, + maxzoom: { + type: "number", + minimum: 0, + maximum: 24 + }, + filter: { + type: "filter" + }, + layout: { + type: "layout" + }, + paint: { + type: "paint" + } +}; +var layout$7 = [ + "layout_fill", + "layout_line", + "layout_circle", + "layout_heatmap", + "layout_fill-extrusion", + "layout_symbol", + "layout_raster", + "layout_hillshade", + "layout_background" +]; +var layout_background = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_fill = { + "fill-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_circle = { + "circle-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_heatmap = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_line = { + "line-cap": { + type: "enum", + values: { + butt: { + }, + round: { + }, + square: { + } + }, + "default": "butt", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-join": { + type: "enum", + values: { + bevel: { + }, + round: { + }, + miter: { + } + }, + "default": "miter", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "line-miter-limit": { + type: "number", + "default": 2, + requires: [ + { + "line-join": "miter" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-round-limit": { + type: "number", + "default": 1.05, + requires: [ + { + "line-join": "round" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_symbol = { + "symbol-placement": { + type: "enum", + values: { + point: { + }, + line: { + }, + "line-center": { + } + }, + "default": "point", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-spacing": { + type: "number", + "default": 250, + minimum: 1, + units: "pixels", + requires: [ + { + "symbol-placement": "line" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-avoid-edges": { + type: "boolean", + "default": false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "symbol-z-order": { + type: "enum", + values: { + auto: { + }, + "viewport-y": { + }, + source: { + } + }, + "default": "auto", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-allow-overlap": { + type: "boolean", + "default": false, + requires: [ + "icon-image", + { + "!": "icon-overlap" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-overlap": { + type: "enum", + values: { + never: { + }, + always: { + }, + cooperative: { + } + }, + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-ignore-placement": { + type: "boolean", + "default": false, + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-optional": { + type: "boolean", + "default": false, + requires: [ + "icon-image", + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-rotation-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-size": { + type: "number", + "default": 1, + minimum: 0, + units: "factor of the original icon size", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-text-fit": { + type: "enum", + values: { + none: { + }, + width: { + }, + height: { + }, + both: { + } + }, + "default": "none", + requires: [ + "icon-image", + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-text-fit-padding": { + type: "array", + value: "number", + length: 4, + "default": [ + 0, + 0, + 0, + 0 + ], + units: "pixels", + requires: [ + "icon-image", + "text-field", + { + "icon-text-fit": [ + "both", + "width", + "height" + ] + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-image": { + type: "resolvedImage", + tokens: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-rotate": { + type: "number", + "default": 0, + period: 360, + units: "degrees", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-padding": { + type: "padding", + "default": [ + 2 + ], + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-keep-upright": { + type: "boolean", + "default": false, + requires: [ + "icon-image", + { + "icon-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-offset": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-anchor": { + type: "enum", + values: { + center: { + }, + left: { + }, + right: { + }, + top: { + }, + bottom: { + }, + "top-left": { + }, + "top-right": { + }, + "bottom-left": { + }, + "bottom-right": { + } + }, + "default": "center", + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-pitch-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-pitch-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotation-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + "viewport-glyph": { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-field": { + type: "formatted", + "default": "", + tokens: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-font": { + type: "array", + value: "string", + "default": [ + "Open Sans Regular", + "Arial Unicode MS Regular" + ], + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-size": { + type: "number", + "default": 16, + minimum: 0, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-width": { + type: "number", + "default": 10, + minimum: 0, + units: "ems", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-line-height": { + type: "number", + "default": 1.2, + units: "ems", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-letter-spacing": { + type: "number", + "default": 0, + units: "ems", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-justify": { + type: "enum", + values: { + auto: { + }, + left: { + }, + center: { + }, + right: { + } + }, + "default": "center", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-radial-offset": { + type: "number", + units: "ems", + "default": 0, + requires: [ + "text-field" + ], + "property-type": "data-driven", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + } + }, + "text-variable-anchor": { + type: "array", + value: "enum", + values: { + center: { + }, + left: { + }, + right: { + }, + top: { + }, + bottom: { + }, + "top-left": { + }, + "top-right": { + }, + "bottom-left": { + }, + "bottom-right": { + } + }, + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-variable-anchor-offset": { + type: "variableAnchorOffsetCollection", + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-anchor": { + type: "enum", + values: { + center: { + }, + left: { + }, + right: { + }, + top: { + }, + bottom: { + }, + "top-left": { + }, + "top-right": { + }, + "bottom-left": { + }, + "bottom-right": { + } + }, + "default": "center", + requires: [ + "text-field", + { + "!": "text-variable-anchor" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-angle": { + type: "number", + "default": 45, + units: "degrees", + requires: [ + "text-field", + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-writing-mode": { + type: "array", + value: "enum", + values: { + horizontal: { + }, + vertical: { + } + }, + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotate": { + type: "number", + "default": 0, + period: 360, + units: "degrees", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-padding": { + type: "number", + "default": 2, + minimum: 0, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-keep-upright": { + type: "boolean", + "default": true, + requires: [ + "text-field", + { + "text-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-transform": { + type: "enum", + values: { + none: { + }, + uppercase: { + }, + lowercase: { + } + }, + "default": "none", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-offset": { + type: "array", + value: "number", + units: "ems", + length: 2, + "default": [ + 0, + 0 + ], + requires: [ + "text-field", + { + "!": "text-radial-offset" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-allow-overlap": { + type: "boolean", + "default": false, + requires: [ + "text-field", + { + "!": "text-overlap" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-overlap": { + type: "enum", + values: { + never: { + }, + always: { + }, + cooperative: { + } + }, + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-ignore-placement": { + type: "boolean", + "default": false, + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-optional": { + type: "boolean", + "default": false, + requires: [ + "text-field", + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_raster = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_hillshade = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var filter = { + type: "array", + value: "*" +}; +var filter_operator = { + type: "enum", + values: { + "==": { + }, + "!=": { + }, + ">": { + }, + ">=": { + }, + "<": { + }, + "<=": { + }, + "in": { + }, + "!in": { + }, + all: { + }, + any: { + }, + none: { + }, + has: { + }, + "!has": { + } + } +}; +var geometry_type = { + type: "enum", + values: { + Point: { + }, + LineString: { + }, + Polygon: { + } + } +}; +var function_stop = { + type: "array", + minimum: 0, + maximum: 24, + value: [ + "number", + "color" + ], + length: 2 +}; +var expression$1 = { + type: "array", + value: "*", + minimum: 1 +}; +var light = { + anchor: { + type: "enum", + "default": "viewport", + values: { + map: { + }, + viewport: { + } + }, + "property-type": "data-constant", + transition: false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + } + }, + position: { + type: "array", + "default": [ + 1.15, + 210, + 30 + ], + length: 3, + value: "number", + "property-type": "data-constant", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + } + }, + color: { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + intensity: { + type: "number", + "property-type": "data-constant", + "default": 0.5, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + } +}; +var sky = { + "sky-color": { + type: "color", + "property-type": "data-constant", + "default": "#88C6FC", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "horizon-color": { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "fog-color": { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "fog-ground-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.5, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "horizon-fog-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.8, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "sky-horizon-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.8, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "atmosphere-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.8, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + } +}; +var terrain = { + source: { + type: "string", + required: true + }, + exaggeration: { + type: "number", + minimum: 0, + "default": 1 + } +}; +var projection$1 = { + type: { + type: "enum", + "default": "mercator", + values: { + mercator: { + }, + globe: { + } + } + } +}; +var paint$9 = [ + "paint_fill", + "paint_line", + "paint_circle", + "paint_heatmap", + "paint_fill-extrusion", + "paint_symbol", + "paint_raster", + "paint_hillshade", + "paint_background" +]; +var paint_fill = { + "fill-antialias": { + type: "boolean", + "default": true, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "fill-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-outline-color": { + type: "color", + transition: true, + requires: [ + { + "!": "fill-pattern" + }, + { + "fill-antialias": true + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "fill-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + } +}; +var paint_line = { + "line-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "line-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "line-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-width": { + type: "number", + "default": 1, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-gap-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-offset": { + type: "number", + "default": 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-dasharray": { + type: "array", + value: "number", + minimum: 0, + transition: true, + units: "line widths", + requires: [ + { + "!": "line-pattern" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "line-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "line-gradient": { + type: "color", + transition: false, + requires: [ + { + "!": "line-dasharray" + }, + { + "!": "line-pattern" + }, + { + source: "geojson", + has: { + lineMetrics: true + } + } + ], + expression: { + interpolated: true, + parameters: [ + "line-progress" + ] + }, + "property-type": "color-ramp" + } +}; +var paint_circle = { + "circle-radius": { + type: "number", + "default": 5, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-blur": { + type: "number", + "default": 0, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "circle-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-scale": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "viewport", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-stroke-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + } +}; +var paint_heatmap = { + "heatmap-radius": { + type: "number", + "default": 30, + minimum: 1, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-weight": { + type: "number", + "default": 1, + minimum: 0, + transition: false, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-intensity": { + type: "number", + "default": 1, + minimum: 0, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "heatmap-color": { + type: "color", + "default": [ + "interpolate", + [ + "linear" + ], + [ + "heatmap-density" + ], + 0, + "rgba(0, 0, 255, 0)", + 0.1, + "royalblue", + 0.3, + "cyan", + 0.5, + "lime", + 0.7, + "yellow", + 1, + "red" + ], + transition: false, + expression: { + interpolated: true, + parameters: [ + "heatmap-density" + ] + }, + "property-type": "color-ramp" + }, + "heatmap-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_symbol = { + "icon-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-color": { + type: "color", + "default": "rgba(0, 0, 0, 0)", + transition: true, + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "icon-image", + "icon-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-color": { + type: "color", + "default": "#000000", + transition: true, + overridable: true, + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-color": { + type: "color", + "default": "rgba(0, 0, 0, 0)", + transition: true, + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "text-field", + "text-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_raster = { + "raster-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-hue-rotate": { + type: "number", + "default": 0, + period: 360, + transition: true, + units: "degrees", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-min": { + type: "number", + "default": 0, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-max": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-saturation": { + type: "number", + "default": 0, + minimum: -1, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-contrast": { + type: "number", + "default": 0, + minimum: -1, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-resampling": { + type: "enum", + values: { + linear: { + }, + nearest: { + } + }, + "default": "linear", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-fade-duration": { + type: "number", + "default": 300, + minimum: 0, + transition: false, + units: "milliseconds", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_hillshade = { + "hillshade-illumination-direction": { + type: "number", + "default": 335, + minimum: 0, + maximum: 359, + transition: false, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-illumination-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "viewport", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-exaggeration": { + type: "number", + "default": 0.5, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-shadow-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-highlight-color": { + type: "color", + "default": "#FFFFFF", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-accent-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_background = { + "background-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "background-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "background-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "background-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var transition = { + duration: { + type: "number", + "default": 300, + minimum: 0, + units: "milliseconds" + }, + delay: { + type: "number", + "default": 0, + minimum: 0, + units: "milliseconds" + } +}; +var promoteId = { + "*": { + type: "string" + } +}; +var v8Spec = { + $version: $version, + $root: $root, + sources: sources, + source: source, + source_vector: source_vector, + source_raster: source_raster, + source_raster_dem: source_raster_dem, + source_geojson: source_geojson, + source_video: source_video, + source_image: source_image, + layer: layer, + layout: layout$7, + layout_background: layout_background, + layout_fill: layout_fill, + layout_circle: layout_circle, + layout_heatmap: layout_heatmap, + "layout_fill-extrusion": { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}, + layout_line: layout_line, + layout_symbol: layout_symbol, + layout_raster: layout_raster, + layout_hillshade: layout_hillshade, + filter: filter, + filter_operator: filter_operator, + geometry_type: geometry_type, + "function": { + expression: { + type: "expression" + }, + stops: { + type: "array", + value: "function_stop" + }, + base: { + type: "number", + "default": 1, + minimum: 0 + }, + property: { + type: "string", + "default": "$zoom" + }, + type: { + type: "enum", + values: { + identity: { + }, + exponential: { + }, + interval: { + }, + categorical: { + } + }, + "default": "exponential" + }, + colorSpace: { + type: "enum", + values: { + rgb: { + }, + lab: { + }, + hcl: { + } + }, + "default": "rgb" + }, + "default": { + type: "*", + required: false + } +}, + function_stop: function_stop, + expression: expression$1, + light: light, + sky: sky, + terrain: terrain, + projection: projection$1, + paint: paint$9, + paint_fill: paint_fill, + "paint_fill-extrusion": { + "fill-extrusion-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "fill-extrusion-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "fill-extrusion-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "fill-extrusion-height": { + type: "number", + "default": 0, + minimum: 0, + units: "meters", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-base": { + type: "number", + "default": 0, + minimum: 0, + units: "meters", + transition: true, + requires: [ + "fill-extrusion-height" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-vertical-gradient": { + type: "boolean", + "default": true, + transition: false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}, + paint_line: paint_line, + paint_circle: paint_circle, + paint_heatmap: paint_heatmap, + paint_symbol: paint_symbol, + paint_raster: paint_raster, + paint_hillshade: paint_hillshade, + paint_background: paint_background, + transition: transition, + "property-type": { + "data-driven": { + type: "property-type" + }, + "cross-faded": { + type: "property-type" + }, + "cross-faded-data-driven": { + type: "property-type" + }, + "color-ramp": { + type: "property-type" + }, + "data-constant": { + type: "property-type" + }, + constant: { + type: "property-type" + } +}, + promoteId: promoteId +}; + +const refProperties = ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout']; + +function deref(layer, parent) { + const result = {}; + for (const k in layer) { + if (k !== 'ref') { + result[k] = layer[k]; + } + } + refProperties.forEach((k) => { + if (k in parent) { + result[k] = parent[k]; + } + }); + return result; +} +/** + * Given an array of layers, some of which may contain `ref` properties + * whose value is the `id` of another property, return a new array where + * such layers have been augmented with the 'type', 'source', etc. properties + * from the parent layer, and the `ref` property has been removed. + * + * The input is not modified. The output may contain references to portions + * of the input. + * + * @private + * @param {Array} layers + * @returns {Array} + */ +function derefLayers(layers) { + layers = layers.slice(); + const map = Object.create(null); + for (let i = 0; i < layers.length; i++) { + map[layers[i].id] = layers[i]; + } + for (let i = 0; i < layers.length; i++) { + if ('ref' in layers[i]) { + layers[i] = deref(layers[i], map[layers[i].ref]); + } + } + return layers; +} + +/** + * Deeply compares two object literals. + * + * @private + */ +function deepEqual(a, b) { + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) { + if (!deepEqual(a[i], b[i])) + return false; + } + return true; + } + if (typeof a === 'object' && a !== null && b !== null) { + if (!(typeof b === 'object')) + return false; + const keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) + return false; + for (const key in a) { + if (!deepEqual(a[key], b[key])) + return false; + } + return true; + } + return a === b; +} + +/** + * The main reason for this method is to allow type check when adding a command to the array. + * @param commands - The commands array to add to + * @param command - The command to add + */ +function addCommand(commands, command) { + commands.push(command); +} +function addSource(sourceId, after, commands) { + addCommand(commands, { command: 'addSource', args: [sourceId, after[sourceId]] }); +} +function removeSource(sourceId, commands, sourcesRemoved) { + addCommand(commands, { command: 'removeSource', args: [sourceId] }); + sourcesRemoved[sourceId] = true; +} +function updateSource(sourceId, after, commands, sourcesRemoved) { + removeSource(sourceId, commands, sourcesRemoved); + addSource(sourceId, after, commands); +} +function canUpdateGeoJSON(before, after, sourceId) { + let prop; + for (prop in before[sourceId]) { + if (!Object.prototype.hasOwnProperty.call(before[sourceId], prop)) + continue; + if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + for (prop in after[sourceId]) { + if (!Object.prototype.hasOwnProperty.call(after[sourceId], prop)) + continue; + if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + return true; +} +function diffSources(before, after, commands, sourcesRemoved) { + before = before || {}; + after = after || {}; + let sourceId; + // look for sources to remove + for (sourceId in before) { + if (!Object.prototype.hasOwnProperty.call(before, sourceId)) + continue; + if (!Object.prototype.hasOwnProperty.call(after, sourceId)) { + removeSource(sourceId, commands, sourcesRemoved); + } + } + // look for sources to add/update + for (sourceId in after) { + if (!Object.prototype.hasOwnProperty.call(after, sourceId)) + continue; + if (!Object.prototype.hasOwnProperty.call(before, sourceId)) { + addSource(sourceId, after, commands); + } + else if (!deepEqual(before[sourceId], after[sourceId])) { + if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) { + addCommand(commands, { command: 'setGeoJSONSourceData', args: [sourceId, after[sourceId].data] }); + } + else { + // no update command, must remove then add + updateSource(sourceId, after, commands, sourcesRemoved); + } + } + } +} +function diffLayerPropertyChanges(before, after, commands, layerId, klass, command) { + before = before || {}; + after = after || {}; + for (const prop in before) { + if (!Object.prototype.hasOwnProperty.call(before, prop)) + continue; + if (!deepEqual(before[prop], after[prop])) { + commands.push({ command, args: [layerId, prop, after[prop], klass] }); + } + } + for (const prop in after) { + if (!Object.prototype.hasOwnProperty.call(after, prop) || Object.prototype.hasOwnProperty.call(before, prop)) + continue; + if (!deepEqual(before[prop], after[prop])) { + commands.push({ command, args: [layerId, prop, after[prop], klass] }); + } + } +} +function pluckId(layer) { + return layer.id; +} +function indexById(group, layer) { + group[layer.id] = layer; + return group; +} +function diffLayers(before, after, commands) { + before = before || []; + after = after || []; + // order of layers by id + const beforeOrder = before.map(pluckId); + const afterOrder = after.map(pluckId); + // index of layer by id + const beforeIndex = before.reduce(indexById, {}); + const afterIndex = after.reduce(indexById, {}); + // track order of layers as if they have been mutated + const tracker = beforeOrder.slice(); + // layers that have been added do not need to be diffed + const clean = Object.create(null); + let layerId; + let beforeLayer; + let afterLayer; + let insertBeforeLayerId; + let prop; + // remove layers + for (let i = 0, d = 0; i < beforeOrder.length; i++) { + layerId = beforeOrder[i]; + if (!Object.prototype.hasOwnProperty.call(afterIndex, layerId)) { + addCommand(commands, { command: 'removeLayer', args: [layerId] }); + tracker.splice(tracker.indexOf(layerId, d), 1); + } + else { + // limit where in tracker we need to look for a match + d++; + } + } + // add/reorder layers + for (let i = 0, d = 0; i < afterOrder.length; i++) { + // work backwards as insert is before an existing layer + layerId = afterOrder[afterOrder.length - 1 - i]; + if (tracker[tracker.length - 1 - i] === layerId) + continue; + if (Object.prototype.hasOwnProperty.call(beforeIndex, layerId)) { + // remove the layer before we insert at the correct position + addCommand(commands, { command: 'removeLayer', args: [layerId] }); + tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1); + } + else { + // limit where in tracker we need to look for a match + d++; + } + // add layer at correct position + insertBeforeLayerId = tracker[tracker.length - i]; + addCommand(commands, { command: 'addLayer', args: [afterIndex[layerId], insertBeforeLayerId] }); + tracker.splice(tracker.length - i, 0, layerId); + clean[layerId] = true; + } + // update layers + for (let i = 0; i < afterOrder.length; i++) { + layerId = afterOrder[i]; + beforeLayer = beforeIndex[layerId]; + afterLayer = afterIndex[layerId]; + // no need to update if previously added (new or moved) + if (clean[layerId] || deepEqual(beforeLayer, afterLayer)) + continue; + // If source, source-layer, or type have changes, then remove the layer + // and add it back 'from scratch'. + if (!deepEqual(beforeLayer.source, afterLayer.source) || !deepEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !deepEqual(beforeLayer.type, afterLayer.type)) { + addCommand(commands, { command: 'removeLayer', args: [layerId] }); + // we add the layer back at the same position it was already in, so + // there's no need to update the `tracker` + insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1]; + addCommand(commands, { command: 'addLayer', args: [afterLayer, insertBeforeLayerId] }); + continue; + } + // layout, paint, filter, minzoom, maxzoom + diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, 'setLayoutProperty'); + diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, 'setPaintProperty'); + if (!deepEqual(beforeLayer.filter, afterLayer.filter)) { + addCommand(commands, { command: 'setFilter', args: [layerId, afterLayer.filter] }); + } + if (!deepEqual(beforeLayer.minzoom, afterLayer.minzoom) || !deepEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) { + addCommand(commands, { command: 'setLayerZoomRange', args: [layerId, afterLayer.minzoom, afterLayer.maxzoom] }); + } + // handle all other layer props, including paint.* + for (prop in beforeLayer) { + if (!Object.prototype.hasOwnProperty.call(beforeLayer, prop)) + continue; + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || + prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') + continue; + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), 'setPaintProperty'); + } + else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) { + addCommand(commands, { command: 'setLayerProperty', args: [layerId, prop, afterLayer[prop]] }); + } + } + for (prop in afterLayer) { + if (!Object.prototype.hasOwnProperty.call(afterLayer, prop) || Object.prototype.hasOwnProperty.call(beforeLayer, prop)) + continue; + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || + prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') + continue; + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), 'setPaintProperty'); + } + else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) { + addCommand(commands, { command: 'setLayerProperty', args: [layerId, prop, afterLayer[prop]] }); + } + } + } +} +/** + * Diff two stylesheet + * + * Creates semanticly aware diffs that can easily be applied at runtime. + * Operations produced by the diff closely resemble the maplibre-gl-js API. Any + * error creating the diff will fall back to the 'setStyle' operation. + * + * Example diff: + * [ + * { command: 'setConstant', args: ['@water', '#0000FF'] }, + * { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] } + * ] + * + * @private + * @param {*} [before] stylesheet to compare from + * @param {*} after stylesheet to compare to + * @returns Array list of changes + */ +function diffStyles(before, after) { + if (!before) + return [{ command: 'setStyle', args: [after] }]; + let commands = []; + try { + // Handle changes to top-level properties + if (!deepEqual(before.version, after.version)) { + return [{ command: 'setStyle', args: [after] }]; + } + if (!deepEqual(before.center, after.center)) { + commands.push({ command: 'setCenter', args: [after.center] }); + } + if (!deepEqual(before.zoom, after.zoom)) { + commands.push({ command: 'setZoom', args: [after.zoom] }); + } + if (!deepEqual(before.bearing, after.bearing)) { + commands.push({ command: 'setBearing', args: [after.bearing] }); + } + if (!deepEqual(before.pitch, after.pitch)) { + commands.push({ command: 'setPitch', args: [after.pitch] }); + } + if (!deepEqual(before.sprite, after.sprite)) { + commands.push({ command: 'setSprite', args: [after.sprite] }); + } + if (!deepEqual(before.glyphs, after.glyphs)) { + commands.push({ command: 'setGlyphs', args: [after.glyphs] }); + } + if (!deepEqual(before.transition, after.transition)) { + commands.push({ command: 'setTransition', args: [after.transition] }); + } + if (!deepEqual(before.light, after.light)) { + commands.push({ command: 'setLight', args: [after.light] }); + } + if (!deepEqual(before.terrain, after.terrain)) { + commands.push({ command: 'setTerrain', args: [after.terrain] }); + } + if (!deepEqual(before.sky, after.sky)) { + commands.push({ command: 'setSky', args: [after.sky] }); + } + if (!deepEqual(before.projection, after.projection)) { + commands.push({ command: 'setProjection', args: [after.projection] }); + } + // Handle changes to `sources` + // If a source is to be removed, we also--before the removeSource + // command--need to remove all the style layers that depend on it. + const sourcesRemoved = {}; + // First collect the {add,remove}Source commands + const removeOrAddSourceCommands = []; + diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved); + // Push a removeLayer command for each style layer that depends on a + // source that's being removed. + // Also, exclude any such layers them from the input to `diffLayers` + // below, so that diffLayers produces the appropriate `addLayers` + // command + const beforeLayers = []; + if (before.layers) { + before.layers.forEach((layer) => { + if ('source' in layer && sourcesRemoved[layer.source]) { + commands.push({ command: 'removeLayer', args: [layer.id] }); + } + else { + beforeLayers.push(layer); + } + }); + } + commands = commands.concat(removeOrAddSourceCommands); + // Handle changes to `layers` + diffLayers(beforeLayers, after.layers, commands); + } + catch (e) { + // fall back to setStyle + console.warn('Unable to compute style diff:', e); + commands = [{ command: 'setStyle', args: [after] }]; + } + return commands; +} + +// Note: Do not inherit from Error. It breaks when transpiling to ES5. +class ValidationError { + constructor(key, value, message, identifier) { + this.message = (key ? `${key}: ` : '') + message; + if (identifier) + this.identifier = identifier; + if (value !== null && value !== undefined && value.__line__) { + this.line = value.__line__; + } + } +} + +// Note: Do not inherit from Error. It breaks when transpiling to ES5. +class ParsingError { + constructor(error) { + this.error = error; + this.message = error.message; + const match = error.message.match(/line (\d+)/); + this.line = match ? parseInt(match[1], 10) : 0; + } +} + +function extendBy(output, ...inputs) { + for (const input of inputs) { + for (const k in input) { + output[k] = input[k]; + } + } + return output; +} + +class ExpressionParsingError extends Error { + constructor(key, message) { + super(message); + this.message = message; + this.key = key; + } +} + +/** + * Tracks `let` bindings during expression parsing. + * @private + */ +class Scope { + constructor(parent, bindings = []) { + this.parent = parent; + this.bindings = {}; + for (const [name, expression] of bindings) { + this.bindings[name] = expression; + } + } + concat(bindings) { + return new Scope(this, bindings); + } + get(name) { + if (this.bindings[name]) { + return this.bindings[name]; + } + if (this.parent) { + return this.parent.get(name); + } + throw new Error(`${name} not found in scope.`); + } + has(name) { + if (this.bindings[name]) + return true; + return this.parent ? this.parent.has(name) : false; + } +} + +const NullType = { kind: 'null' }; +const NumberType = { kind: 'number' }; +const StringType = { kind: 'string' }; +const BooleanType = { kind: 'boolean' }; +const ColorType = { kind: 'color' }; +const ObjectType = { kind: 'object' }; +const ValueType = { kind: 'value' }; +const ErrorType = { kind: 'error' }; +const CollatorType = { kind: 'collator' }; +const FormattedType = { kind: 'formatted' }; +const PaddingType = { kind: 'padding' }; +const ResolvedImageType = { kind: 'resolvedImage' }; +const VariableAnchorOffsetCollectionType = { kind: 'variableAnchorOffsetCollection' }; +function array$1(itemType, N) { + return { + kind: 'array', + itemType, + N + }; +} +function toString$1(type) { + if (type.kind === 'array') { + const itemType = toString$1(type.itemType); + return typeof type.N === 'number' ? + `array<${itemType}, ${type.N}>` : + type.itemType.kind === 'value' ? 'array' : `array<${itemType}>`; + } + else { + return type.kind; + } +} +const valueMemberTypes = [ + NullType, + NumberType, + StringType, + BooleanType, + ColorType, + FormattedType, + ObjectType, + array$1(ValueType), + PaddingType, + ResolvedImageType, + VariableAnchorOffsetCollectionType +]; +/** + * Returns null if `t` is a subtype of `expected`; otherwise returns an + * error message. + * @private + */ +function checkSubtype(expected, t) { + if (t.kind === 'error') { + // Error is a subtype of every type + return null; + } + else if (expected.kind === 'array') { + if (t.kind === 'array' && + ((t.N === 0 && t.itemType.kind === 'value') || !checkSubtype(expected.itemType, t.itemType)) && + (typeof expected.N !== 'number' || expected.N === t.N)) { + return null; + } + } + else if (expected.kind === t.kind) { + return null; + } + else if (expected.kind === 'value') { + for (const memberType of valueMemberTypes) { + if (!checkSubtype(memberType, t)) { + return null; + } + } + } + return `Expected ${toString$1(expected)} but found ${toString$1(t)} instead.`; +} +function isValidType(provided, allowedTypes) { + return allowedTypes.some(t => t.kind === provided.kind); +} +function isValidNativeType(provided, allowedTypes) { + return allowedTypes.some(t => { + if (t === 'null') { + return provided === null; + } + else if (t === 'array') { + return Array.isArray(provided); + } + else if (t === 'object') { + return provided && !Array.isArray(provided) && typeof provided === 'object'; + } + else { + return t === typeof provided; + } + }); +} +/** + * Verify whether the specified type is of the same type as the specified sample. + * + * @param provided Type to verify + * @param sample Sample type to reference + * @returns `true` if both objects are of the same type, `false` otherwise + * @example basic types + * if (verifyType(outputType, ValueType)) { + * // type narrowed to: + * outputType.kind; // 'value' + * } + * @example array types + * if (verifyType(outputType, array(NumberType))) { + * // type narrowed to: + * outputType.kind; // 'array' + * outputType.itemType; // NumberTypeT + * outputType.itemType.kind; // 'number' + * } + */ +function verifyType(provided, sample) { + if (provided.kind === 'array' && sample.kind === 'array') { + return provided.itemType.kind === sample.itemType.kind && typeof provided.N === 'number'; + } + return provided.kind === sample.kind; +} + +// See https://observablehq.com/@mbostock/lab-and-rgb +const Xn = 0.96422, Yn = 1, Zn = 0.82521, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1, deg2rad = Math.PI / 180, rad2deg = 180 / Math.PI; +function constrainAngle(angle) { + angle = angle % 360; + if (angle < 0) { + angle += 360; + } + return angle; +} +function rgbToLab([r, g, b, alpha]) { + r = rgb2xyz(r); + g = rgb2xyz(g); + b = rgb2xyz(b); + let x, z; + const y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn); + if (r === g && g === b) { + x = z = y; + } + else { + x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn); + z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn); + } + const l = 116 * y - 16; + return [(l < 0) ? 0 : l, 500 * (x - y), 200 * (y - z), alpha]; +} +function rgb2xyz(x) { + return (x <= 0.04045) ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); +} +function xyz2lab(t) { + return (t > t3) ? Math.pow(t, 1 / 3) : t / t2 + t0; +} +function labToRgb([l, a, b, alpha]) { + let y = (l + 16) / 116, x = isNaN(a) ? y : y + a / 500, z = isNaN(b) ? y : y - b / 200; + y = Yn * lab2xyz(y); + x = Xn * lab2xyz(x); + z = Zn * lab2xyz(z); + return [ + xyz2rgb(3.1338561 * x - 1.6168667 * y - 0.4906146 * z), // D50 -> sRGB + xyz2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z), + xyz2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z), + alpha, + ]; +} +function xyz2rgb(x) { + x = (x <= 0.00304) ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055; + return (x < 0) ? 0 : (x > 1) ? 1 : x; // clip to 0..1 range +} +function lab2xyz(t) { + return (t > t1) ? t * t * t : t2 * (t - t0); +} +function rgbToHcl(rgbColor) { + const [l, a, b, alpha] = rgbToLab(rgbColor); + const c = Math.sqrt(a * a + b * b); + const h = Math.round(c * 10000) ? constrainAngle(Math.atan2(b, a) * rad2deg) : NaN; + return [h, c, l, alpha]; +} +function hclToRgb([h, c, l, alpha]) { + h = isNaN(h) ? 0 : h * deg2rad; + return labToRgb([l, Math.cos(h) * c, Math.sin(h) * c, alpha]); +} +// https://drafts.csswg.org/css-color-4/#hsl-to-rgb +function hslToRgb([h, s, l, alpha]) { + h = constrainAngle(h); + s /= 100; + l /= 100; + function f(n) { + const k = (n + h / 30) % 12; + const a = s * Math.min(l, 1 - l); + return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); + } + return [f(0), f(8), f(4), alpha]; +} + +/** + * CSS color parser compliant with CSS Color 4 Specification. + * Supports: named colors, `transparent` keyword, all rgb hex notations, + * rgb(), rgba(), hsl() and hsla() functions. + * Does not round the parsed values to integers from the range 0..255. + * + * Syntax: + * + * = | + * = | + * + * rgb() = rgb( {3} [ / ]? ) | rgb( {3} [ / ]? ) + * rgb() = rgb( #{3} , ? ) | rgb( #{3} , ? ) + * + * hsl() = hsl( [ / ]? ) + * hsl() = hsl( , , , ? ) + * + * Caveats: + * - - with optional `deg` suffix; `grad`, `rad`, `turn` are not supported + * - `none` keyword is not supported + * - comments inside rgb()/hsl() are not supported + * - legacy color syntax rgba() is supported with an identical grammar and behavior to rgb() + * - legacy color syntax hsla() is supported with an identical grammar and behavior to hsl() + * + * @param input CSS color string to parse. + * @returns Color in sRGB color space, with `red`, `green`, `blue` + * and `alpha` channels normalized to the range 0..1, + * or `undefined` if the input is not a valid color string. + */ +function parseCssColor(input) { + input = input.toLowerCase().trim(); + if (input === 'transparent') { + return [0, 0, 0, 0]; + } + // 'white', 'black', 'blue' + const namedColorsMatch = namedColors[input]; + if (namedColorsMatch) { + const [r, g, b] = namedColorsMatch; + return [r / 255, g / 255, b / 255, 1]; + } + // #f0c, #f0cf, #ff00cc, #ff00ccff + if (input.startsWith('#')) { + const hexRegexp = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/; + if (hexRegexp.test(input)) { + const step = input.length < 6 ? 1 : 2; + let i = 1; + return [ + parseHex(input.slice(i, i += step)), + parseHex(input.slice(i, i += step)), + parseHex(input.slice(i, i += step)), + parseHex(input.slice(i, i + step) || 'ff'), + ]; + } + } + // rgb(128 0 0), rgb(50% 0% 0%), rgba(255,0,255,0.6), rgb(255 0 255 / 60%), rgb(100% 0% 100% /.6) + if (input.startsWith('rgb')) { + const rgbRegExp = /^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/; + const rgbMatch = input.match(rgbRegExp); + if (rgbMatch) { + const [_, // eslint-disable-line @typescript-eslint/no-unused-vars + r, // + rp, // % (optional) + f1, // , (optional) + g, // + gp, // % (optional) + f2, // , (optional) + b, // + bp, // % (optional) + f3, // ,|/ (optional) + a, // (optional) + ap, // % (optional) + ] = rgbMatch; + const argFormat = [f1 || ' ', f2 || ' ', f3].join(''); + if (argFormat === ' ' || + argFormat === ' /' || + argFormat === ',,' || + argFormat === ',,,') { + const valFormat = [rp, gp, bp].join(''); + const maxValue = (valFormat === '%%%') ? 100 : + (valFormat === '') ? 255 : 0; + if (maxValue) { + const rgba = [ + clamp(+r / maxValue, 0, 1), + clamp(+g / maxValue, 0, 1), + clamp(+b / maxValue, 0, 1), + a ? parseAlpha(+a, ap) : 1, + ]; + if (validateNumbers(rgba)) { + return rgba; + } + // invalid numbers + } + // values must be all numbers or all percentages + } + return; // comma optional syntax requires no commas at all + } + } + // hsl(120 50% 80%), hsla(120deg,50%,80%,.9), hsl(12e1 50% 80% / 90%) + const hslRegExp = /^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/; + const hslMatch = input.match(hslRegExp); + if (hslMatch) { + const [_, // eslint-disable-line @typescript-eslint/no-unused-vars + h, // + f1, // , (optional) + s, // + f2, // , (optional) + l, // + f3, // ,|/ (optional) + a, // (optional) + ap, // % (optional) + ] = hslMatch; + const argFormat = [f1 || ' ', f2 || ' ', f3].join(''); + if (argFormat === ' ' || + argFormat === ' /' || + argFormat === ',,' || + argFormat === ',,,') { + const hsla = [ + +h, + clamp(+s, 0, 100), + clamp(+l, 0, 100), + a ? parseAlpha(+a, ap) : 1, + ]; + if (validateNumbers(hsla)) { + return hslToRgb(hsla); + } + // invalid numbers + } + // comma optional syntax requires no commas at all + } +} +function parseHex(hex) { + return parseInt(hex.padEnd(2, hex), 16) / 255; +} +function parseAlpha(a, asPercentage) { + return clamp(asPercentage ? (a / 100) : a, 0, 1); +} +function clamp(n, min, max) { + return Math.min(Math.max(min, n), max); +} +/** + * The regular expression for numeric values is not super specific, and it may + * happen that it will accept a value that is not a valid number. In order to + * detect and eliminate such values this function exists. + * + * @param array Array of uncertain numbers. + * @returns `true` if the specified array contains only valid numbers, `false` otherwise. + */ +function validateNumbers(array) { + return !array.some(Number.isNaN); +} +/** + * To generate: + * - visit {@link https://www.w3.org/TR/css-color-4/#named-colors} + * - run in the console: + * @example + * copy(`{\n${[...document.querySelector('.named-color-table tbody').children].map((tr) => `${tr.cells[2].textContent.trim()}: [${tr.cells[4].textContent.trim().split(/\s+/).join(', ')}],`).join('\n')}\n}`); + */ +const namedColors = { + aliceblue: [240, 248, 255], + antiquewhite: [250, 235, 215], + aqua: [0, 255, 255], + aquamarine: [127, 255, 212], + azure: [240, 255, 255], + beige: [245, 245, 220], + bisque: [255, 228, 196], + black: [0, 0, 0], + blanchedalmond: [255, 235, 205], + blue: [0, 0, 255], + blueviolet: [138, 43, 226], + brown: [165, 42, 42], + burlywood: [222, 184, 135], + cadetblue: [95, 158, 160], + chartreuse: [127, 255, 0], + chocolate: [210, 105, 30], + coral: [255, 127, 80], + cornflowerblue: [100, 149, 237], + cornsilk: [255, 248, 220], + crimson: [220, 20, 60], + cyan: [0, 255, 255], + darkblue: [0, 0, 139], + darkcyan: [0, 139, 139], + darkgoldenrod: [184, 134, 11], + darkgray: [169, 169, 169], + darkgreen: [0, 100, 0], + darkgrey: [169, 169, 169], + darkkhaki: [189, 183, 107], + darkmagenta: [139, 0, 139], + darkolivegreen: [85, 107, 47], + darkorange: [255, 140, 0], + darkorchid: [153, 50, 204], + darkred: [139, 0, 0], + darksalmon: [233, 150, 122], + darkseagreen: [143, 188, 143], + darkslateblue: [72, 61, 139], + darkslategray: [47, 79, 79], + darkslategrey: [47, 79, 79], + darkturquoise: [0, 206, 209], + darkviolet: [148, 0, 211], + deeppink: [255, 20, 147], + deepskyblue: [0, 191, 255], + dimgray: [105, 105, 105], + dimgrey: [105, 105, 105], + dodgerblue: [30, 144, 255], + firebrick: [178, 34, 34], + floralwhite: [255, 250, 240], + forestgreen: [34, 139, 34], + fuchsia: [255, 0, 255], + gainsboro: [220, 220, 220], + ghostwhite: [248, 248, 255], + gold: [255, 215, 0], + goldenrod: [218, 165, 32], + gray: [128, 128, 128], + green: [0, 128, 0], + greenyellow: [173, 255, 47], + grey: [128, 128, 128], + honeydew: [240, 255, 240], + hotpink: [255, 105, 180], + indianred: [205, 92, 92], + indigo: [75, 0, 130], + ivory: [255, 255, 240], + khaki: [240, 230, 140], + lavender: [230, 230, 250], + lavenderblush: [255, 240, 245], + lawngreen: [124, 252, 0], + lemonchiffon: [255, 250, 205], + lightblue: [173, 216, 230], + lightcoral: [240, 128, 128], + lightcyan: [224, 255, 255], + lightgoldenrodyellow: [250, 250, 210], + lightgray: [211, 211, 211], + lightgreen: [144, 238, 144], + lightgrey: [211, 211, 211], + lightpink: [255, 182, 193], + lightsalmon: [255, 160, 122], + lightseagreen: [32, 178, 170], + lightskyblue: [135, 206, 250], + lightslategray: [119, 136, 153], + lightslategrey: [119, 136, 153], + lightsteelblue: [176, 196, 222], + lightyellow: [255, 255, 224], + lime: [0, 255, 0], + limegreen: [50, 205, 50], + linen: [250, 240, 230], + magenta: [255, 0, 255], + maroon: [128, 0, 0], + mediumaquamarine: [102, 205, 170], + mediumblue: [0, 0, 205], + mediumorchid: [186, 85, 211], + mediumpurple: [147, 112, 219], + mediumseagreen: [60, 179, 113], + mediumslateblue: [123, 104, 238], + mediumspringgreen: [0, 250, 154], + mediumturquoise: [72, 209, 204], + mediumvioletred: [199, 21, 133], + midnightblue: [25, 25, 112], + mintcream: [245, 255, 250], + mistyrose: [255, 228, 225], + moccasin: [255, 228, 181], + navajowhite: [255, 222, 173], + navy: [0, 0, 128], + oldlace: [253, 245, 230], + olive: [128, 128, 0], + olivedrab: [107, 142, 35], + orange: [255, 165, 0], + orangered: [255, 69, 0], + orchid: [218, 112, 214], + palegoldenrod: [238, 232, 170], + palegreen: [152, 251, 152], + paleturquoise: [175, 238, 238], + palevioletred: [219, 112, 147], + papayawhip: [255, 239, 213], + peachpuff: [255, 218, 185], + peru: [205, 133, 63], + pink: [255, 192, 203], + plum: [221, 160, 221], + powderblue: [176, 224, 230], + purple: [128, 0, 128], + rebeccapurple: [102, 51, 153], + red: [255, 0, 0], + rosybrown: [188, 143, 143], + royalblue: [65, 105, 225], + saddlebrown: [139, 69, 19], + salmon: [250, 128, 114], + sandybrown: [244, 164, 96], + seagreen: [46, 139, 87], + seashell: [255, 245, 238], + sienna: [160, 82, 45], + silver: [192, 192, 192], + skyblue: [135, 206, 235], + slateblue: [106, 90, 205], + slategray: [112, 128, 144], + slategrey: [112, 128, 144], + snow: [255, 250, 250], + springgreen: [0, 255, 127], + steelblue: [70, 130, 180], + tan: [210, 180, 140], + teal: [0, 128, 128], + thistle: [216, 191, 216], + tomato: [255, 99, 71], + turquoise: [64, 224, 208], + violet: [238, 130, 238], + wheat: [245, 222, 179], + white: [255, 255, 255], + whitesmoke: [245, 245, 245], + yellow: [255, 255, 0], + yellowgreen: [154, 205, 50], +}; + +/** + * Color representation used by WebGL. + * Defined in sRGB color space and pre-blended with alpha. + * @private + */ +class Color { + /** + * @param r Red component premultiplied by `alpha` 0..1 + * @param g Green component premultiplied by `alpha` 0..1 + * @param b Blue component premultiplied by `alpha` 0..1 + * @param [alpha=1] Alpha component 0..1 + * @param [premultiplied=true] Whether the `r`, `g` and `b` values have already + * been multiplied by alpha. If `true` nothing happens if `false` then they will + * be multiplied automatically. + */ + constructor(r, g, b, alpha = 1, premultiplied = true) { + this.r = r; + this.g = g; + this.b = b; + this.a = alpha; + if (!premultiplied) { + this.r *= alpha; + this.g *= alpha; + this.b *= alpha; + if (!alpha) { + // alpha = 0 erases completely rgb channels. This behavior is not desirable + // if this particular color is later used in color interpolation. + // Because of that, a reference to original color is saved. + this.overwriteGetter('rgb', [r, g, b, alpha]); + } + } + } + /** + * Parses CSS color strings and converts colors to sRGB color space if needed. + * Officially supported color formats: + * - keyword, e.g. 'aquamarine' or 'steelblue' + * - hex (with 3, 4, 6 or 8 digits), e.g. '#f0f' or '#e9bebea9' + * - rgb and rgba, e.g. 'rgb(0,240,120)' or 'rgba(0%,94%,47%,0.1)' or 'rgb(0 240 120 / .3)' + * - hsl and hsla, e.g. 'hsl(0,0%,83%)' or 'hsla(0,0%,83%,.5)' or 'hsl(0 0% 83% / 20%)' + * + * @param input CSS color string to parse. + * @returns A `Color` instance, or `undefined` if the input is not a valid color string. + */ + static parse(input) { + // in zoom-and-property function input could be an instance of Color class + if (input instanceof Color) { + return input; + } + if (typeof input !== 'string') { + return; + } + const rgba = parseCssColor(input); + if (rgba) { + return new Color(...rgba, false); + } + } + /** + * Used in color interpolation and by 'to-rgba' expression. + * + * @returns Gien color, with reversed alpha blending, in sRGB color space. + */ + get rgb() { + const { r, g, b, a } = this; + const f = a || Infinity; // reverse alpha blending factor + return this.overwriteGetter('rgb', [r / f, g / f, b / f, a]); + } + /** + * Used in color interpolation. + * + * @returns Gien color, with reversed alpha blending, in HCL color space. + */ + get hcl() { + return this.overwriteGetter('hcl', rgbToHcl(this.rgb)); + } + /** + * Used in color interpolation. + * + * @returns Gien color, with reversed alpha blending, in LAB color space. + */ + get lab() { + return this.overwriteGetter('lab', rgbToLab(this.rgb)); + } + /** + * Lazy getter pattern. When getter is called for the first time lazy value + * is calculated and then overwrites getter function in given object instance. + * + * @example: + * const redColor = Color.parse('red'); + * let x = redColor.hcl; // this will invoke `get hcl()`, which will calculate + * // the value of red in HCL space and invoke this `overwriteGetter` function + * // which in turn will set a field with a key 'hcl' in the `redColor` object. + * // In other words it will override `get hcl()` from its `Color` prototype + * // with its own property: hcl = [calculated red value in hcl]. + * let y = redColor.hcl; // next call will no longer invoke getter but simply + * // return the previously calculated value + * x === y; // true - `x` is exactly the same object as `y` + * + * @param getterKey Getter key + * @param lazyValue Lazily calculated value to be memoized by current instance + * @private + */ + overwriteGetter(getterKey, lazyValue) { + Object.defineProperty(this, getterKey, { value: lazyValue }); + return lazyValue; + } + /** + * Used by 'to-string' expression. + * + * @returns Serialized color in format `rgba(r,g,b,a)` + * where r,g,b are numbers within 0..255 and alpha is number within 1..0 + * + * @example + * var purple = new Color.parse('purple'); + * purple.toString; // = "rgba(128,0,128,1)" + * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)'); + * translucentGreen.toString(); // = "rgba(26,207,26,0.73)" + */ + toString() { + const [r, g, b, a] = this.rgb; + return `rgba(${[r, g, b].map(n => Math.round(n * 255)).join(',')},${a})`; + } +} +Color.black = new Color(0, 0, 0, 1); +Color.white = new Color(1, 1, 1, 1); +Color.transparent = new Color(0, 0, 0, 0); +Color.red = new Color(1, 0, 0, 1); + +// Flow type declarations for Intl cribbed from +// https://github.com/facebook/flow/issues/1270 +class Collator { + constructor(caseSensitive, diacriticSensitive, locale) { + if (caseSensitive) + this.sensitivity = diacriticSensitive ? 'variant' : 'case'; + else + this.sensitivity = diacriticSensitive ? 'accent' : 'base'; + this.locale = locale; + this.collator = new Intl.Collator(this.locale ? this.locale : [], { sensitivity: this.sensitivity, usage: 'search' }); + } + compare(lhs, rhs) { + return this.collator.compare(lhs, rhs); + } + resolvedLocale() { + // We create a Collator without "usage: search" because we don't want + // the search options encoded in our result (e.g. "en-u-co-search") + return new Intl.Collator(this.locale ? this.locale : []) + .resolvedOptions().locale; + } +} + +class FormattedSection { + constructor(text, image, scale, fontStack, textColor) { + this.text = text; + this.image = image; + this.scale = scale; + this.fontStack = fontStack; + this.textColor = textColor; + } +} +class Formatted { + constructor(sections) { + this.sections = sections; + } + static fromString(unformatted) { + return new Formatted([new FormattedSection(unformatted, null, null, null, null)]); + } + isEmpty() { + if (this.sections.length === 0) + return true; + return !this.sections.some(section => section.text.length !== 0 || + (section.image && section.image.name.length !== 0)); + } + static factory(text) { + if (text instanceof Formatted) { + return text; + } + else { + return Formatted.fromString(text); + } + } + toString() { + if (this.sections.length === 0) + return ''; + return this.sections.map(section => section.text).join(''); + } +} + +/** + * A set of four numbers representing padding around a box. Create instances from + * bare arrays or numeric values using the static method `Padding.parse`. + * @private + */ +class Padding { + constructor(values) { + this.values = values.slice(); + } + /** + * Numeric padding values + * @param input A padding value + * @returns A `Padding` instance, or `undefined` if the input is not a valid padding value. + */ + static parse(input) { + if (input instanceof Padding) { + return input; + } + // Backwards compatibility: bare number is treated the same as array with single value. + // Padding applies to all four sides. + if (typeof input === 'number') { + return new Padding([input, input, input, input]); + } + if (!Array.isArray(input)) { + return undefined; + } + if (input.length < 1 || input.length > 4) { + return undefined; + } + for (const val of input) { + if (typeof val !== 'number') { + return undefined; + } + } + // Expand shortcut properties into explicit 4-sided values + switch (input.length) { + case 1: + input = [input[0], input[0], input[0], input[0]]; + break; + case 2: + input = [input[0], input[1], input[0], input[1]]; + break; + case 3: + input = [input[0], input[1], input[2], input[1]]; + break; + } + return new Padding(input); + } + toString() { + return JSON.stringify(this.values); + } +} + +/** Set of valid anchor positions, as a set for validation */ +const anchors = new Set(['center', 'left', 'right', 'top', 'bottom', 'top-left', 'top-right', 'bottom-left', 'bottom-right']); +/** + * Utility class to assist managing values for text-variable-anchor-offset property. Create instances from + * bare arrays using the static method `VariableAnchorOffsetCollection.parse`. + * @private + */ +class VariableAnchorOffsetCollection { + constructor(values) { + this.values = values.slice(); + } + static parse(input) { + if (input instanceof VariableAnchorOffsetCollection) { + return input; + } + if (!Array.isArray(input) || + input.length < 1 || + input.length % 2 !== 0) { + return undefined; + } + for (let i = 0; i < input.length; i += 2) { + // Elements in even positions should be anchor positions; Elements in odd positions should be offset values + const anchorValue = input[i]; + const offsetValue = input[i + 1]; + if (typeof anchorValue !== 'string' || !anchors.has(anchorValue)) { + return undefined; + } + if (!Array.isArray(offsetValue) || offsetValue.length !== 2 || typeof offsetValue[0] !== 'number' || typeof offsetValue[1] !== 'number') { + return undefined; + } + } + return new VariableAnchorOffsetCollection(input); + } + toString() { + return JSON.stringify(this.values); + } +} + +class ResolvedImage { + constructor(options) { + this.name = options.name; + this.available = options.available; + } + toString() { + return this.name; + } + static fromString(name) { + if (!name) + return null; // treat empty values as no image + return new ResolvedImage({ name, available: false }); + } +} + +function validateRGBA(r, g, b, a) { + if (!(typeof r === 'number' && r >= 0 && r <= 255 && + typeof g === 'number' && g >= 0 && g <= 255 && + typeof b === 'number' && b >= 0 && b <= 255)) { + const value = typeof a === 'number' ? [r, g, b, a] : [r, g, b]; + return `Invalid rgba value [${value.join(', ')}]: 'r', 'g', and 'b' must be between 0 and 255.`; + } + if (!(typeof a === 'undefined' || (typeof a === 'number' && a >= 0 && a <= 1))) { + return `Invalid rgba value [${[r, g, b, a].join(', ')}]: 'a' must be between 0 and 1.`; + } + return null; +} +function isValue(mixed) { + if (mixed === null || + typeof mixed === 'string' || + typeof mixed === 'boolean' || + typeof mixed === 'number' || + mixed instanceof Color || + mixed instanceof Collator || + mixed instanceof Formatted || + mixed instanceof Padding || + mixed instanceof VariableAnchorOffsetCollection || + mixed instanceof ResolvedImage) { + return true; + } + else if (Array.isArray(mixed)) { + for (const item of mixed) { + if (!isValue(item)) { + return false; + } + } + return true; + } + else if (typeof mixed === 'object') { + for (const key in mixed) { + if (!isValue(mixed[key])) { + return false; + } + } + return true; + } + else { + return false; + } +} +function typeOf(value) { + if (value === null) { + return NullType; + } + else if (typeof value === 'string') { + return StringType; + } + else if (typeof value === 'boolean') { + return BooleanType; + } + else if (typeof value === 'number') { + return NumberType; + } + else if (value instanceof Color) { + return ColorType; + } + else if (value instanceof Collator) { + return CollatorType; + } + else if (value instanceof Formatted) { + return FormattedType; + } + else if (value instanceof Padding) { + return PaddingType; + } + else if (value instanceof VariableAnchorOffsetCollection) { + return VariableAnchorOffsetCollectionType; + } + else if (value instanceof ResolvedImage) { + return ResolvedImageType; + } + else if (Array.isArray(value)) { + const length = value.length; + let itemType; + for (const item of value) { + const t = typeOf(item); + if (!itemType) { + itemType = t; + } + else if (itemType === t) { + continue; + } + else { + itemType = ValueType; + break; + } + } + return array$1(itemType || ValueType, length); + } + else { + return ObjectType; + } +} +function toString(value) { + const type = typeof value; + if (value === null) { + return ''; + } + else if (type === 'string' || type === 'number' || type === 'boolean') { + return String(value); + } + else if (value instanceof Color || value instanceof Formatted || value instanceof Padding || value instanceof VariableAnchorOffsetCollection || value instanceof ResolvedImage) { + return value.toString(); + } + else { + return JSON.stringify(value); + } +} + +class Literal { + constructor(type, value) { + this.type = type; + this.value = value; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (!isValue(args[1])) + return context.error('invalid value'); + const value = args[1]; + let type = typeOf(value); + // special case: infer the item type if possible for zero-length arrays + const expected = context.expectedType; + if (type.kind === 'array' && + type.N === 0 && + expected && + expected.kind === 'array' && + (typeof expected.N !== 'number' || expected.N === 0)) { + type = expected; + } + return new Literal(type, value); + } + evaluate() { + return this.value; + } + eachChild() { } + outputDefined() { + return true; + } +} + +class RuntimeError { + constructor(message) { + this.name = 'ExpressionEvaluationError'; + this.message = message; + } + toJSON() { + return this.message; + } +} + +const types$1 = { + string: StringType, + number: NumberType, + boolean: BooleanType, + object: ObjectType +}; +class Assertion { + constructor(type, args) { + this.type = type; + this.args = args; + } + static parse(args, context) { + if (args.length < 2) + return context.error('Expected at least one argument.'); + let i = 1; + let type; + const name = args[0]; + if (name === 'array') { + let itemType; + if (args.length > 2) { + const type = args[1]; + if (typeof type !== 'string' || !(type in types$1) || type === 'object') + return context.error('The item type argument of "array" must be one of string, number, boolean', 1); + itemType = types$1[type]; + i++; + } + else { + itemType = ValueType; + } + let N; + if (args.length > 3) { + if (args[2] !== null && + (typeof args[2] !== 'number' || + args[2] < 0 || + args[2] !== Math.floor(args[2]))) { + return context.error('The length argument to "array" must be a positive integer literal', 2); + } + N = args[2]; + i++; + } + type = array$1(itemType, N); + } + else { + if (!types$1[name]) + throw new Error(`Types doesn't contain name = ${name}`); + type = types$1[name]; + } + const parsed = []; + for (; i < args.length; i++) { + const input = context.parse(args[i], i, ValueType); + if (!input) + return null; + parsed.push(input); + } + return new Assertion(type, parsed); + } + evaluate(ctx) { + for (let i = 0; i < this.args.length; i++) { + const value = this.args[i].evaluate(ctx); + const error = checkSubtype(this.type, typeOf(value)); + if (!error) { + return value; + } + else if (i === this.args.length - 1) { + throw new RuntimeError(`Expected value to be of type ${toString$1(this.type)}, but found ${toString$1(typeOf(value))} instead.`); + } + } + throw new Error(); + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return this.args.every(arg => arg.outputDefined()); + } +} + +const types = { + 'to-boolean': BooleanType, + 'to-color': ColorType, + 'to-number': NumberType, + 'to-string': StringType +}; +/** + * Special form for error-coalescing coercion expressions "to-number", + * "to-color". Since these coercions can fail at runtime, they accept multiple + * arguments, only evaluating one at a time until one succeeds. + * + * @private + */ +class Coercion { + constructor(type, args) { + this.type = type; + this.args = args; + } + static parse(args, context) { + if (args.length < 2) + return context.error('Expected at least one argument.'); + const name = args[0]; + if (!types[name]) + throw new Error(`Can't parse ${name} as it is not part of the known types`); + if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2) + return context.error('Expected one argument.'); + const type = types[name]; + const parsed = []; + for (let i = 1; i < args.length; i++) { + const input = context.parse(args[i], i, ValueType); + if (!input) + return null; + parsed.push(input); + } + return new Coercion(type, parsed); + } + evaluate(ctx) { + switch (this.type.kind) { + case 'boolean': + return Boolean(this.args[0].evaluate(ctx)); + case 'color': { + let input; + let error; + for (const arg of this.args) { + input = arg.evaluate(ctx); + error = null; + if (input instanceof Color) { + return input; + } + else if (typeof input === 'string') { + const c = ctx.parseColor(input); + if (c) + return c; + } + else if (Array.isArray(input)) { + if (input.length < 3 || input.length > 4) { + error = `Invalid rbga value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`; + } + else { + error = validateRGBA(input[0], input[1], input[2], input[3]); + } + if (!error) { + return new Color(input[0] / 255, input[1] / 255, input[2] / 255, input[3]); + } + } + } + throw new RuntimeError(error || `Could not parse color from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`); + } + case 'padding': { + let input; + for (const arg of this.args) { + input = arg.evaluate(ctx); + const pad = Padding.parse(input); + if (pad) { + return pad; + } + } + throw new RuntimeError(`Could not parse padding from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`); + } + case 'variableAnchorOffsetCollection': { + let input; + for (const arg of this.args) { + input = arg.evaluate(ctx); + const coll = VariableAnchorOffsetCollection.parse(input); + if (coll) { + return coll; + } + } + throw new RuntimeError(`Could not parse variableAnchorOffsetCollection from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`); + } + case 'number': { + let value = null; + for (const arg of this.args) { + value = arg.evaluate(ctx); + if (value === null) + return 0; + const num = Number(value); + if (isNaN(num)) + continue; + return num; + } + throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`); + } + case 'formatted': + // There is no explicit 'to-formatted' but this coercion can be implicitly + // created by properties that expect the 'formatted' type. + return Formatted.fromString(toString(this.args[0].evaluate(ctx))); + case 'resolvedImage': + return ResolvedImage.fromString(toString(this.args[0].evaluate(ctx))); + default: + return toString(this.args[0].evaluate(ctx)); + } + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return this.args.every(arg => arg.outputDefined()); + } +} + +const geometryTypes = ['Unknown', 'Point', 'LineString', 'Polygon']; +class EvaluationContext { + constructor() { + this.globals = null; + this.feature = null; + this.featureState = null; + this.formattedSection = null; + this._parseColorCache = {}; + this.availableImages = null; + this.canonical = null; + } + id() { + return this.feature && 'id' in this.feature ? this.feature.id : null; + } + geometryType() { + return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null; + } + geometry() { + return this.feature && 'geometry' in this.feature ? this.feature.geometry : null; + } + canonicalID() { + return this.canonical; + } + properties() { + return this.feature && this.feature.properties || {}; + } + parseColor(input) { + let cached = this._parseColorCache[input]; + if (!cached) { + cached = this._parseColorCache[input] = Color.parse(input); + } + return cached; + } +} + +/** + * State associated parsing at a given point in an expression tree. + * @private + */ +class ParsingContext { + constructor(registry, isConstantFunc, path = [], expectedType, scope = new Scope(), errors = []) { + this.registry = registry; + this.path = path; + this.key = path.map(part => `[${part}]`).join(''); + this.scope = scope; + this.errors = errors; + this.expectedType = expectedType; + this._isConstant = isConstantFunc; + } + /** + * @param expr the JSON expression to parse + * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed + * @param options + * @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. + * @private + */ + parse(expr, index, expectedType, bindings, options = {}) { + if (index) { + return this.concat(index, expectedType, bindings)._parse(expr, options); + } + return this._parse(expr, options); + } + _parse(expr, options) { + if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') { + expr = ['literal', expr]; + } + function annotate(parsed, type, typeAnnotation) { + if (typeAnnotation === 'assert') { + return new Assertion(type, [parsed]); + } + else if (typeAnnotation === 'coerce') { + return new Coercion(type, [parsed]); + } + else { + return parsed; + } + } + if (Array.isArray(expr)) { + if (expr.length === 0) { + return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].'); + } + const op = expr[0]; + if (typeof op !== 'string') { + this.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use ["literal", [...]].`, 0); + return null; + } + const Expr = this.registry[op]; + if (Expr) { + let parsed = Expr.parse(expr, this); + if (!parsed) + return null; + if (this.expectedType) { + const expected = this.expectedType; + const actual = parsed.type; + // When we expect a number, string, boolean, or array but have a value, wrap it in an assertion. + // When we expect a color or formatted string, but have a string or value, wrap it in a coercion. + // Otherwise, we do static type-checking. + // + // These behaviors are overridable for: + // * The "coalesce" operator, which needs to omit type annotations. + // * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion. + // + if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') { + parsed = annotate(parsed, expected, options.typeAnnotation || 'assert'); + } + else if ((expected.kind === 'color' || expected.kind === 'formatted' || expected.kind === 'resolvedImage') && (actual.kind === 'value' || actual.kind === 'string')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } + else if (expected.kind === 'padding' && (actual.kind === 'value' || actual.kind === 'number' || actual.kind === 'array')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } + else if (expected.kind === 'variableAnchorOffsetCollection' && (actual.kind === 'value' || actual.kind === 'array')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } + else if (this.checkSubtype(expected, actual)) { + return null; + } + } + // If an expression's arguments are all literals, we can evaluate + // it immediately and replace it with a literal value in the + // parsed/compiled result. Expressions that expect an image should + // not be resolved here so we can later get the available images. + if (!(parsed instanceof Literal) && (parsed.type.kind !== 'resolvedImage') && this._isConstant(parsed)) { + const ec = new EvaluationContext(); + try { + parsed = new Literal(parsed.type, parsed.evaluate(ec)); + } + catch (e) { + this.error(e.message); + return null; + } + } + return parsed; + } + return this.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); + } + else if (typeof expr === 'undefined') { + return this.error('\'undefined\' value invalid. Use null instead.'); + } + else if (typeof expr === 'object') { + return this.error('Bare objects invalid. Use ["literal", {...}] instead.'); + } + else { + return this.error(`Expected an array, but found ${typeof expr} instead.`); + } + } + /** + * Returns a copy of this context suitable for parsing the subexpression at + * index `index`, optionally appending to 'let' binding map. + * + * Note that `errors` property, intended for collecting errors while + * parsing, is copied by reference rather than cloned. + * @private + */ + concat(index, expectedType, bindings) { + const path = typeof index === 'number' ? this.path.concat(index) : this.path; + const scope = bindings ? this.scope.concat(bindings) : this.scope; + return new ParsingContext(this.registry, this._isConstant, path, expectedType || null, scope, this.errors); + } + /** + * Push a parsing (or type checking) error into the `this.errors` + * @param error The message + * @param keys Optionally specify the source of the error at a child + * of the current expression at `this.key`. + * @private + */ + error(error, ...keys) { + const key = `${this.key}${keys.map(k => `[${k}]`).join('')}`; + this.errors.push(new ExpressionParsingError(key, error)); + } + /** + * Returns null if `t` is a subtype of `expected`; otherwise returns an + * error message and also pushes it to `this.errors`. + * @param expected The expected type + * @param t The actual type + * @returns null if `t` is a subtype of `expected`; otherwise returns an error message + */ + checkSubtype(expected, t) { + const error = checkSubtype(expected, t); + if (error) + this.error(error); + return error; + } +} + +class Let { + constructor(bindings, result) { + this.type = result.type; + this.bindings = [].concat(bindings); + this.result = result; + } + evaluate(ctx) { + return this.result.evaluate(ctx); + } + eachChild(fn) { + for (const binding of this.bindings) { + fn(binding[1]); + } + fn(this.result); + } + static parse(args, context) { + if (args.length < 4) + return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`); + const bindings = []; + for (let i = 1; i < args.length - 1; i += 2) { + const name = args[i]; + if (typeof name !== 'string') { + return context.error(`Expected string, but found ${typeof name} instead.`, i); + } + if (/[^a-zA-Z0-9_]/.test(name)) { + return context.error('Variable names must contain only alphanumeric characters or \'_\'.', i); + } + const value = context.parse(args[i + 1], i + 1); + if (!value) + return null; + bindings.push([name, value]); + } + const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings); + if (!result) + return null; + return new Let(bindings, result); + } + outputDefined() { + return this.result.outputDefined(); + } +} + +class Var { + constructor(name, boundExpression) { + this.type = boundExpression.type; + this.name = name; + this.boundExpression = boundExpression; + } + static parse(args, context) { + if (args.length !== 2 || typeof args[1] !== 'string') + return context.error('\'var\' expression requires exactly one string literal argument.'); + const name = args[1]; + if (!context.scope.has(name)) { + return context.error(`Unknown variable "${name}". Make sure "${name}" has been bound in an enclosing "let" expression before using it.`, 1); + } + return new Var(name, context.scope.get(name)); + } + evaluate(ctx) { + return this.boundExpression.evaluate(ctx); + } + eachChild() { } + outputDefined() { + return false; + } +} + +class At { + constructor(type, index, input) { + this.type = type; + this.index = index; + this.input = input; + } + static parse(args, context) { + if (args.length !== 3) + return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); + const index = context.parse(args[1], 1, NumberType); + const input = context.parse(args[2], 2, array$1(context.expectedType || ValueType)); + if (!index || !input) + return null; + const t = input.type; + return new At(t.itemType, index, input); + } + evaluate(ctx) { + const index = this.index.evaluate(ctx); + const array = this.input.evaluate(ctx); + if (index < 0) { + throw new RuntimeError(`Array index out of bounds: ${index} < 0.`); + } + if (index >= array.length) { + throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`); + } + if (index !== Math.floor(index)) { + throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`); + } + return array[index]; + } + eachChild(fn) { + fn(this.index); + fn(this.input); + } + outputDefined() { + return false; + } +} + +class In { + constructor(needle, haystack) { + this.type = BooleanType; + this.needle = needle; + this.haystack = haystack; + } + static parse(args, context) { + if (args.length !== 3) { + return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); + } + const needle = context.parse(args[1], 1, ValueType); + const haystack = context.parse(args[2], 2, ValueType); + if (!needle || !haystack) + return null; + if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) { + return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(needle.type)} instead`); + } + return new In(needle, haystack); + } + evaluate(ctx) { + const needle = this.needle.evaluate(ctx); + const haystack = this.haystack.evaluate(ctx); + if (!haystack) + return false; + if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) { + throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(typeOf(needle))} instead.`); + } + if (!isValidNativeType(haystack, ['string', 'array'])) { + throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString$1(typeOf(haystack))} instead.`); + } + return haystack.indexOf(needle) >= 0; + } + eachChild(fn) { + fn(this.needle); + fn(this.haystack); + } + outputDefined() { + return true; + } +} + +class IndexOf { + constructor(needle, haystack, fromIndex) { + this.type = NumberType; + this.needle = needle; + this.haystack = haystack; + this.fromIndex = fromIndex; + } + static parse(args, context) { + if (args.length <= 2 || args.length >= 5) { + return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`); + } + const needle = context.parse(args[1], 1, ValueType); + const haystack = context.parse(args[2], 2, ValueType); + if (!needle || !haystack) + return null; + if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) { + return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(needle.type)} instead`); + } + if (args.length === 4) { + const fromIndex = context.parse(args[3], 3, NumberType); + if (!fromIndex) + return null; + return new IndexOf(needle, haystack, fromIndex); + } + else { + return new IndexOf(needle, haystack); + } + } + evaluate(ctx) { + const needle = this.needle.evaluate(ctx); + const haystack = this.haystack.evaluate(ctx); + if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) { + throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(typeOf(needle))} instead.`); + } + let fromIndex; + if (this.fromIndex) { + fromIndex = this.fromIndex.evaluate(ctx); + } + if (isValidNativeType(haystack, ['string'])) { + const rawIndex = haystack.indexOf(needle, fromIndex); + if (rawIndex === -1) { + return -1; + } + else { + // The index may be affected by surrogate pairs, so get the length of the preceding substring. + return [...haystack.slice(0, rawIndex)].length; + } + } + else if (isValidNativeType(haystack, ['array'])) { + return haystack.indexOf(needle, fromIndex); + } + else { + throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString$1(typeOf(haystack))} instead.`); + } + } + eachChild(fn) { + fn(this.needle); + fn(this.haystack); + if (this.fromIndex) { + fn(this.fromIndex); + } + } + outputDefined() { + return false; + } +} + +class Match { + constructor(inputType, outputType, input, cases, outputs, otherwise) { + this.inputType = inputType; + this.type = outputType; + this.input = input; + this.cases = cases; + this.outputs = outputs; + this.otherwise = otherwise; + } + static parse(args, context) { + if (args.length < 5) + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + if (args.length % 2 !== 1) + return context.error('Expected an even number of arguments.'); + let inputType; + let outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + const cases = {}; + const outputs = []; + for (let i = 2; i < args.length - 1; i += 2) { + let labels = args[i]; + const value = args[i + 1]; + if (!Array.isArray(labels)) { + labels = [labels]; + } + const labelContext = context.concat(i); + if (labels.length === 0) { + return labelContext.error('Expected at least one branch label.'); + } + for (const label of labels) { + if (typeof label !== 'number' && typeof label !== 'string') { + return labelContext.error('Branch labels must be numbers or strings.'); + } + else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) { + return labelContext.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`); + } + else if (typeof label === 'number' && Math.floor(label) !== label) { + return labelContext.error('Numeric branch labels must be integer values.'); + } + else if (!inputType) { + inputType = typeOf(label); + } + else if (labelContext.checkSubtype(inputType, typeOf(label))) { + return null; + } + if (typeof cases[String(label)] !== 'undefined') { + return labelContext.error('Branch labels must be unique.'); + } + cases[String(label)] = outputs.length; + } + const result = context.parse(value, i, outputType); + if (!result) + return null; + outputType = outputType || result.type; + outputs.push(result); + } + const input = context.parse(args[1], 1, ValueType); + if (!input) + return null; + const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) + return null; + if (input.type.kind !== 'value' && context.concat(1).checkSubtype(inputType, input.type)) { + return null; + } + return new Match(inputType, outputType, input, cases, outputs, otherwise); + } + evaluate(ctx) { + const input = this.input.evaluate(ctx); + const output = (typeOf(input) === this.inputType && this.outputs[this.cases[input]]) || this.otherwise; + return output.evaluate(ctx); + } + eachChild(fn) { + fn(this.input); + this.outputs.forEach(fn); + fn(this.otherwise); + } + outputDefined() { + return this.outputs.every(out => out.outputDefined()) && this.otherwise.outputDefined(); + } +} + +class Case { + constructor(type, branches, otherwise) { + this.type = type; + this.branches = branches; + this.otherwise = otherwise; + } + static parse(args, context) { + if (args.length < 4) + return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`); + if (args.length % 2 !== 0) + return context.error('Expected an odd number of arguments.'); + let outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + const branches = []; + for (let i = 1; i < args.length - 1; i += 2) { + const test = context.parse(args[i], i, BooleanType); + if (!test) + return null; + const result = context.parse(args[i + 1], i + 1, outputType); + if (!result) + return null; + branches.push([test, result]); + outputType = outputType || result.type; + } + const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) + return null; + if (!outputType) + throw new Error('Can\'t infer output type'); + return new Case(outputType, branches, otherwise); + } + evaluate(ctx) { + for (const [test, expression] of this.branches) { + if (test.evaluate(ctx)) { + return expression.evaluate(ctx); + } + } + return this.otherwise.evaluate(ctx); + } + eachChild(fn) { + for (const [test, expression] of this.branches) { + fn(test); + fn(expression); + } + fn(this.otherwise); + } + outputDefined() { + return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined(); + } +} + +class Slice { + constructor(type, input, beginIndex, endIndex) { + this.type = type; + this.input = input; + this.beginIndex = beginIndex; + this.endIndex = endIndex; + } + static parse(args, context) { + if (args.length <= 2 || args.length >= 5) { + return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`); + } + const input = context.parse(args[1], 1, ValueType); + const beginIndex = context.parse(args[2], 2, NumberType); + if (!input || !beginIndex) + return null; + if (!isValidType(input.type, [array$1(ValueType), StringType, ValueType])) { + return context.error(`Expected first argument to be of type array or string, but found ${toString$1(input.type)} instead`); + } + if (args.length === 4) { + const endIndex = context.parse(args[3], 3, NumberType); + if (!endIndex) + return null; + return new Slice(input.type, input, beginIndex, endIndex); + } + else { + return new Slice(input.type, input, beginIndex); + } + } + evaluate(ctx) { + const input = this.input.evaluate(ctx); + const beginIndex = this.beginIndex.evaluate(ctx); + let endIndex; + if (this.endIndex) { + endIndex = this.endIndex.evaluate(ctx); + } + if (isValidNativeType(input, ['string'])) { + // Indices may be affected by surrogate pairs. + return [...input].slice(beginIndex, endIndex).join(''); + } + else if (isValidNativeType(input, ['array'])) { + return input.slice(beginIndex, endIndex); + } + else { + throw new RuntimeError(`Expected first argument to be of type array or string, but found ${toString$1(typeOf(input))} instead.`); + } + } + eachChild(fn) { + fn(this.input); + fn(this.beginIndex); + if (this.endIndex) { + fn(this.endIndex); + } + } + outputDefined() { + return false; + } +} + +/** + * Returns the index of the last stop <= input, or 0 if it doesn't exist. + * @private + */ +function findStopLessThanOrEqualTo(stops, input) { + const lastIndex = stops.length - 1; + let lowerIndex = 0; + let upperIndex = lastIndex; + let currentIndex = 0; + let currentValue, nextValue; + while (lowerIndex <= upperIndex) { + currentIndex = Math.floor((lowerIndex + upperIndex) / 2); + currentValue = stops[currentIndex]; + nextValue = stops[currentIndex + 1]; + if (currentValue <= input) { + if (currentIndex === lastIndex || input < nextValue) { // Search complete + return currentIndex; + } + lowerIndex = currentIndex + 1; + } + else if (currentValue > input) { + upperIndex = currentIndex - 1; + } + else { + throw new RuntimeError('Input is not a number.'); + } + } + return 0; +} + +class Step { + constructor(type, input, stops) { + this.type = type; + this.input = input; + this.labels = []; + this.outputs = []; + for (const [label, expression] of stops) { + this.labels.push(label); + this.outputs.push(expression); + } + } + static parse(args, context) { + if (args.length - 1 < 4) { + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + } + if ((args.length - 1) % 2 !== 0) { + return context.error('Expected an even number of arguments.'); + } + const input = context.parse(args[1], 1, NumberType); + if (!input) + return null; + const stops = []; + let outputType = null; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + for (let i = 1; i < args.length; i += 2) { + const label = i === 1 ? -Infinity : args[i]; + const value = args[i + 1]; + const labelKey = i; + const valueKey = i + 1; + if (typeof label !== 'number') { + return context.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + const parsed = context.parse(value, valueKey, outputType); + if (!parsed) + return null; + outputType = outputType || parsed.type; + stops.push([label, parsed]); + } + return new Step(outputType, input, stops); + } + evaluate(ctx) { + const labels = this.labels; + const outputs = this.outputs; + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + const value = this.input.evaluate(ctx); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + const stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + const index = findStopLessThanOrEqualTo(labels, value); + return outputs[index].evaluate(ctx); + } + eachChild(fn) { + fn(this.input); + for (const expression of this.outputs) { + fn(expression); + } + } + outputDefined() { + return this.outputs.every(out => out.outputDefined()); + } +} + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var unitbezier = UnitBezier; + +function UnitBezier(p1x, p1y, p2x, p2y) { + // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). + this.cx = 3.0 * p1x; + this.bx = 3.0 * (p2x - p1x) - this.cx; + this.ax = 1.0 - this.cx - this.bx; + + this.cy = 3.0 * p1y; + this.by = 3.0 * (p2y - p1y) - this.cy; + this.ay = 1.0 - this.cy - this.by; + + this.p1x = p1x; + this.p1y = p1y; + this.p2x = p2x; + this.p2y = p2y; +} + +UnitBezier.prototype = { + sampleCurveX: function (t) { + // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. + return ((this.ax * t + this.bx) * t + this.cx) * t; + }, + + sampleCurveY: function (t) { + return ((this.ay * t + this.by) * t + this.cy) * t; + }, + + sampleCurveDerivativeX: function (t) { + return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; + }, + + solveCurveX: function (x, epsilon) { + if (epsilon === undefined) epsilon = 1e-6; + + if (x < 0.0) return 0.0; + if (x > 1.0) return 1.0; + + var t = x; + + // First try a few iterations of Newton's method - normally very fast. + for (var i = 0; i < 8; i++) { + var x2 = this.sampleCurveX(t) - x; + if (Math.abs(x2) < epsilon) return t; + + var d2 = this.sampleCurveDerivativeX(t); + if (Math.abs(d2) < 1e-6) break; + + t = t - x2 / d2; + } + + // Fall back to the bisection method for reliability. + var t0 = 0.0; + var t1 = 1.0; + t = x; + + for (i = 0; i < 20; i++) { + x2 = this.sampleCurveX(t); + if (Math.abs(x2 - x) < epsilon) break; + + if (x > x2) { + t0 = t; + } else { + t1 = t; + } + + t = (t1 - t0) * 0.5 + t0; + } + + return t; + }, + + solve: function (x, epsilon) { + return this.sampleCurveY(this.solveCurveX(x, epsilon)); + } +}; + +var UnitBezier$1 = /*@__PURE__*/getDefaultExportFromCjs(unitbezier); + +/** + * Checks whether the specified color space is one of the supported interpolation color spaces. + * + * @param colorSpace Color space key to verify. + * @returns `true` if the specified color space is one of the supported + * interpolation color spaces, `false` otherwise + */ +function isSupportedInterpolationColorSpace(colorSpace) { + return colorSpace === 'rgb' || colorSpace === 'hcl' || colorSpace === 'lab'; +} +/** + * @param interpolationType Interpolation type + * @returns interpolation fn + * @deprecated use `interpolate[type]` instead + */ +const interpolateFactory = (interpolationType) => { + switch (interpolationType) { + case 'number': return number; + case 'color': return color; + case 'array': return array; + case 'padding': return padding; + case 'variableAnchorOffsetCollection': return variableAnchorOffsetCollection; + } +}; +function number(from, to, t) { + return from + t * (to - from); +} +function color(from, to, t, spaceKey = 'rgb') { + switch (spaceKey) { + case 'rgb': { + const [r, g, b, alpha] = array(from.rgb, to.rgb, t); + return new Color(r, g, b, alpha, false); + } + case 'hcl': { + const [hue0, chroma0, light0, alphaF] = from.hcl; + const [hue1, chroma1, light1, alphaT] = to.hcl; + // https://github.com/gka/chroma.js/blob/cd1b3c0926c7a85cbdc3b1453b3a94006de91a92/src/interpolator/_hsx.js + let hue, chroma; + if (!isNaN(hue0) && !isNaN(hue1)) { + let dh = hue1 - hue0; + if (hue1 > hue0 && dh > 180) { + dh -= 360; + } + else if (hue1 < hue0 && hue0 - hue1 > 180) { + dh += 360; + } + hue = hue0 + t * dh; + } + else if (!isNaN(hue0)) { + hue = hue0; + if (light1 === 1 || light1 === 0) + chroma = chroma0; + } + else if (!isNaN(hue1)) { + hue = hue1; + if (light0 === 1 || light0 === 0) + chroma = chroma1; + } + else { + hue = NaN; + } + const [r, g, b, alpha] = hclToRgb([ + hue, + chroma !== null && chroma !== void 0 ? chroma : number(chroma0, chroma1, t), + number(light0, light1, t), + number(alphaF, alphaT, t), + ]); + return new Color(r, g, b, alpha, false); + } + case 'lab': { + const [r, g, b, alpha] = labToRgb(array(from.lab, to.lab, t)); + return new Color(r, g, b, alpha, false); + } + } +} +function array(from, to, t) { + return from.map((d, i) => { + return number(d, to[i], t); + }); +} +function padding(from, to, t) { + return new Padding(array(from.values, to.values, t)); +} +function variableAnchorOffsetCollection(from, to, t) { + const fromValues = from.values; + const toValues = to.values; + if (fromValues.length !== toValues.length) { + throw new RuntimeError(`Cannot interpolate values of different length. from: ${from.toString()}, to: ${to.toString()}`); + } + const output = []; + for (let i = 0; i < fromValues.length; i += 2) { + // Anchor entries must match + if (fromValues[i] !== toValues[i]) { + throw new RuntimeError(`Cannot interpolate values containing mismatched anchors. from[${i}]: ${fromValues[i]}, to[${i}]: ${toValues[i]}`); + } + output.push(fromValues[i]); + // Interpolate the offset values for each anchor + const [fx, fy] = fromValues[i + 1]; + const [tx, ty] = toValues[i + 1]; + output.push([number(fx, tx, t), number(fy, ty, t)]); + } + return new VariableAnchorOffsetCollection(output); +} +const interpolate = { + number, + color, + array, + padding, + variableAnchorOffsetCollection +}; + +class Interpolate { + constructor(type, operator, interpolation, input, stops) { + this.type = type; + this.operator = operator; + this.interpolation = interpolation; + this.input = input; + this.labels = []; + this.outputs = []; + for (const [label, expression] of stops) { + this.labels.push(label); + this.outputs.push(expression); + } + } + static interpolationFactor(interpolation, input, lower, upper) { + let t = 0; + if (interpolation.name === 'exponential') { + t = exponentialInterpolation(input, interpolation.base, lower, upper); + } + else if (interpolation.name === 'linear') { + t = exponentialInterpolation(input, 1, lower, upper); + } + else if (interpolation.name === 'cubic-bezier') { + const c = interpolation.controlPoints; + const ub = new UnitBezier$1(c[0], c[1], c[2], c[3]); + t = ub.solve(exponentialInterpolation(input, 1, lower, upper)); + } + return t; + } + static parse(args, context) { + let [operator, interpolation, input, ...rest] = args; + if (!Array.isArray(interpolation) || interpolation.length === 0) { + return context.error('Expected an interpolation type expression.', 1); + } + if (interpolation[0] === 'linear') { + interpolation = { name: 'linear' }; + } + else if (interpolation[0] === 'exponential') { + const base = interpolation[1]; + if (typeof base !== 'number') + return context.error('Exponential interpolation requires a numeric base.', 1, 1); + interpolation = { + name: 'exponential', + base + }; + } + else if (interpolation[0] === 'cubic-bezier') { + const controlPoints = interpolation.slice(1); + if (controlPoints.length !== 4 || + controlPoints.some(t => typeof t !== 'number' || t < 0 || t > 1)) { + return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1); + } + interpolation = { + name: 'cubic-bezier', + controlPoints: controlPoints + }; + } + else { + return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0); + } + if (args.length - 1 < 4) { + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + } + if ((args.length - 1) % 2 !== 0) { + return context.error('Expected an even number of arguments.'); + } + input = context.parse(input, 2, NumberType); + if (!input) + return null; + const stops = []; + let outputType = null; + if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') { + outputType = ColorType; + } + else if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + for (let i = 0; i < rest.length; i += 2) { + const label = rest[i]; + const value = rest[i + 1]; + const labelKey = i + 3; + const valueKey = i + 4; + if (typeof label !== 'number') { + return context.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + const parsed = context.parse(value, valueKey, outputType); + if (!parsed) + return null; + outputType = outputType || parsed.type; + stops.push([label, parsed]); + } + if (!verifyType(outputType, NumberType) && + !verifyType(outputType, ColorType) && + !verifyType(outputType, PaddingType) && + !verifyType(outputType, VariableAnchorOffsetCollectionType) && + !verifyType(outputType, array$1(NumberType))) { + return context.error(`Type ${toString$1(outputType)} is not interpolatable.`); + } + return new Interpolate(outputType, operator, interpolation, input, stops); + } + evaluate(ctx) { + const labels = this.labels; + const outputs = this.outputs; + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + const value = this.input.evaluate(ctx); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + const stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + const index = findStopLessThanOrEqualTo(labels, value); + const lower = labels[index]; + const upper = labels[index + 1]; + const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper); + const outputLower = outputs[index].evaluate(ctx); + const outputUpper = outputs[index + 1].evaluate(ctx); + switch (this.operator) { + case 'interpolate': + return interpolate[this.type.kind](outputLower, outputUpper, t); + case 'interpolate-hcl': + return interpolate.color(outputLower, outputUpper, t, 'hcl'); + case 'interpolate-lab': + return interpolate.color(outputLower, outputUpper, t, 'lab'); + } + } + eachChild(fn) { + fn(this.input); + for (const expression of this.outputs) { + fn(expression); + } + } + outputDefined() { + return this.outputs.every(out => out.outputDefined()); + } +} +/** + * Returns a ratio that can be used to interpolate between exponential function + * stops. + * 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, + * and `a` and `b` are constants affording sufficient degrees of freedom to fit + * the function to the given stops. + * + * Here's a bit of algebra that lets us compute `f(x)` directly from the stop + * values without explicitly solving for `a` and `b`: + * + * First stop value: `f(x0) = y0 = a * base^x0 + b` + * Second stop value: `f(x1) = y1 = a * base^x1 + b` + * => `y1 - y0 = a(base^x1 - base^x0)` + * => `a = (y1 - y0)/(base^x1 - base^x0)` + * + * Desired value: `f(x) = y = a * base^x + b` + * => `f(x) = y0 + a * (base^x - base^x0)` + * + * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a + * little algebra: + * ``` + * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) + * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) + * ``` + * + * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have + * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as + * an interpolation factor between the two stops' output values. + * + * (Note: a slightly different form for `ratio`, + * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer + * expensive `Math.pow()` operations.) + * + * @private +*/ +function exponentialInterpolation(input, base, lowerValue, upperValue) { + const difference = upperValue - lowerValue; + const progress = input - lowerValue; + if (difference === 0) { + return 0; + } + else if (base === 1) { + return progress / difference; + } + else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} + +class Coalesce { + constructor(type, args) { + this.type = type; + this.args = args; + } + static parse(args, context) { + if (args.length < 2) { + return context.error('Expectected at least one argument.'); + } + let outputType = null; + const expectedType = context.expectedType; + if (expectedType && expectedType.kind !== 'value') { + outputType = expectedType; + } + const parsedArgs = []; + for (const arg of args.slice(1)) { + const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, { typeAnnotation: 'omit' }); + if (!parsed) + return null; + outputType = outputType || parsed.type; + parsedArgs.push(parsed); + } + if (!outputType) + throw new Error('No output type'); + // Above, we parse arguments without inferred type annotation so that + // they don't produce a runtime error for `null` input, which would + // preempt the desired null-coalescing behavior. + // Thus, if any of our arguments would have needed an annotation, we + // need to wrap the enclosing coalesce expression with it instead. + const needsAnnotation = expectedType && + parsedArgs.some(arg => checkSubtype(expectedType, arg.type)); + return needsAnnotation ? + new Coalesce(ValueType, parsedArgs) : + new Coalesce(outputType, parsedArgs); + } + evaluate(ctx) { + let result = null; + let argCount = 0; + let requestedImageName; + for (const arg of this.args) { + argCount++; + result = arg.evaluate(ctx); + // we need to keep track of the first requested image in a coalesce statement + // if coalesce can't find a valid image, we return the first image name so styleimagemissing can fire + if (result && result instanceof ResolvedImage && !result.available) { + if (!requestedImageName) { + requestedImageName = result.name; + } + result = null; + if (argCount === this.args.length) { + result = requestedImageName; + } + } + if (result !== null) + break; + } + return result; + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return this.args.every(arg => arg.outputDefined()); + } +} + +function isComparableType(op, type) { + if (op === '==' || op === '!=') { + // equality operator + return type.kind === 'boolean' || + type.kind === 'string' || + type.kind === 'number' || + type.kind === 'null' || + type.kind === 'value'; + } + else { + // ordering operator + return type.kind === 'string' || + type.kind === 'number' || + type.kind === 'value'; + } +} +function eq(ctx, a, b) { return a === b; } +function neq(ctx, a, b) { return a !== b; } +function lt(ctx, a, b) { return a < b; } +function gt(ctx, a, b) { return a > b; } +function lteq(ctx, a, b) { return a <= b; } +function gteq(ctx, a, b) { return a >= b; } +function eqCollate(ctx, a, b, c) { return c.compare(a, b) === 0; } +function neqCollate(ctx, a, b, c) { return !eqCollate(ctx, a, b, c); } +function ltCollate(ctx, a, b, c) { return c.compare(a, b) < 0; } +function gtCollate(ctx, a, b, c) { return c.compare(a, b) > 0; } +function lteqCollate(ctx, a, b, c) { return c.compare(a, b) <= 0; } +function gteqCollate(ctx, a, b, c) { return c.compare(a, b) >= 0; } +/** + * Special form for comparison operators, implementing the signatures: + * - (T, T, ?Collator) => boolean + * - (T, value, ?Collator) => boolean + * - (value, T, ?Collator) => boolean + * + * For inequalities, T must be either value, string, or number. For ==/!=, it + * can also be boolean or null. + * + * Equality semantics are equivalent to Javascript's strict equality (===/!==) + * -- i.e., when the arguments' types don't match, == evaluates to false, != to + * true. + * + * When types don't match in an ordering comparison, a runtime error is thrown. + * + * @private + */ +function makeComparison(op, compareBasic, compareWithCollator) { + const isOrderComparison = op !== '==' && op !== '!='; + return class Comparison { + constructor(lhs, rhs, collator) { + this.type = BooleanType; + this.lhs = lhs; + this.rhs = rhs; + this.collator = collator; + this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value'; + } + static parse(args, context) { + if (args.length !== 3 && args.length !== 4) + return context.error('Expected two or three arguments.'); + const op = args[0]; + let lhs = context.parse(args[1], 1, ValueType); + if (!lhs) + return null; + if (!isComparableType(op, lhs.type)) { + return context.concat(1).error(`"${op}" comparisons are not supported for type '${toString$1(lhs.type)}'.`); + } + let rhs = context.parse(args[2], 2, ValueType); + if (!rhs) + return null; + if (!isComparableType(op, rhs.type)) { + return context.concat(2).error(`"${op}" comparisons are not supported for type '${toString$1(rhs.type)}'.`); + } + if (lhs.type.kind !== rhs.type.kind && + lhs.type.kind !== 'value' && + rhs.type.kind !== 'value') { + return context.error(`Cannot compare types '${toString$1(lhs.type)}' and '${toString$1(rhs.type)}'.`); + } + if (isOrderComparison) { + // typing rules specific to less/greater than operators + if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') { + // (value, T) + lhs = new Assertion(rhs.type, [lhs]); + } + else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') { + // (T, value) + rhs = new Assertion(lhs.type, [rhs]); + } + } + let collator = null; + if (args.length === 4) { + if (lhs.type.kind !== 'string' && + rhs.type.kind !== 'string' && + lhs.type.kind !== 'value' && + rhs.type.kind !== 'value') { + return context.error('Cannot use collator to compare non-string types.'); + } + collator = context.parse(args[3], 3, CollatorType); + if (!collator) + return null; + } + return new Comparison(lhs, rhs, collator); + } + evaluate(ctx) { + const lhs = this.lhs.evaluate(ctx); + const rhs = this.rhs.evaluate(ctx); + if (isOrderComparison && this.hasUntypedArgument) { + const lt = typeOf(lhs); + const rt = typeOf(rhs); + // check that type is string or number, and equal + if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) { + throw new RuntimeError(`Expected arguments for "${op}" to be (string, string) or (number, number), but found (${lt.kind}, ${rt.kind}) instead.`); + } + } + if (this.collator && !isOrderComparison && this.hasUntypedArgument) { + const lt = typeOf(lhs); + const rt = typeOf(rhs); + if (lt.kind !== 'string' || rt.kind !== 'string') { + return compareBasic(ctx, lhs, rhs); + } + } + return this.collator ? + compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) : + compareBasic(ctx, lhs, rhs); + } + eachChild(fn) { + fn(this.lhs); + fn(this.rhs); + if (this.collator) { + fn(this.collator); + } + } + outputDefined() { + return true; + } + }; +} +const Equals = makeComparison('==', eq, eqCollate); +const NotEquals = makeComparison('!=', neq, neqCollate); +const LessThan = makeComparison('<', lt, ltCollate); +const GreaterThan = makeComparison('>', gt, gtCollate); +const LessThanOrEqual = makeComparison('<=', lteq, lteqCollate); +const GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate); + +class CollatorExpression { + constructor(caseSensitive, diacriticSensitive, locale) { + this.type = CollatorType; + this.locale = locale; + this.caseSensitive = caseSensitive; + this.diacriticSensitive = diacriticSensitive; + } + static parse(args, context) { + if (args.length !== 2) + return context.error('Expected one argument.'); + const options = args[1]; + if (typeof options !== 'object' || Array.isArray(options)) + return context.error('Collator options argument must be an object.'); + const caseSensitive = context.parse(options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType); + if (!caseSensitive) + return null; + const diacriticSensitive = context.parse(options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType); + if (!diacriticSensitive) + return null; + let locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) + return null; + } + return new CollatorExpression(caseSensitive, diacriticSensitive, locale); + } + evaluate(ctx) { + return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null); + } + eachChild(fn) { + fn(this.caseSensitive); + fn(this.diacriticSensitive); + if (this.locale) { + fn(this.locale); + } + } + outputDefined() { + // Technically the set of possible outputs is the combinatoric set of Collators produced + // by all possible outputs of locale/caseSensitive/diacriticSensitive + // But for the primary use of Collators in comparison operators, we ignore the Collator's + // possible outputs anyway, so we can get away with leaving this false for now. + return false; + } +} + +class NumberFormat { + constructor(number, locale, currency, minFractionDigits, maxFractionDigits) { + this.type = StringType; + this.number = number; + this.locale = locale; + this.currency = currency; + this.minFractionDigits = minFractionDigits; + this.maxFractionDigits = maxFractionDigits; + } + static parse(args, context) { + if (args.length !== 3) + return context.error('Expected two arguments.'); + const number = context.parse(args[1], 1, NumberType); + if (!number) + return null; + const options = args[2]; + if (typeof options !== 'object' || Array.isArray(options)) + return context.error('NumberFormat options argument must be an object.'); + let locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) + return null; + } + let currency = null; + if (options['currency']) { + currency = context.parse(options['currency'], 1, StringType); + if (!currency) + return null; + } + let minFractionDigits = null; + if (options['min-fraction-digits']) { + minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType); + if (!minFractionDigits) + return null; + } + let maxFractionDigits = null; + if (options['max-fraction-digits']) { + maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType); + if (!maxFractionDigits) + return null; + } + return new NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits); + } + evaluate(ctx) { + return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], { + style: this.currency ? 'currency' : 'decimal', + currency: this.currency ? this.currency.evaluate(ctx) : undefined, + minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined, + maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined, + }).format(this.number.evaluate(ctx)); + } + eachChild(fn) { + fn(this.number); + if (this.locale) { + fn(this.locale); + } + if (this.currency) { + fn(this.currency); + } + if (this.minFractionDigits) { + fn(this.minFractionDigits); + } + if (this.maxFractionDigits) { + fn(this.maxFractionDigits); + } + } + outputDefined() { + return false; + } +} + +class FormatExpression { + constructor(sections) { + this.type = FormattedType; + this.sections = sections; + } + static parse(args, context) { + if (args.length < 2) { + return context.error('Expected at least one argument.'); + } + const firstArg = args[1]; + if (!Array.isArray(firstArg) && typeof firstArg === 'object') { + return context.error('First argument must be an image or text section.'); + } + const sections = []; + let nextTokenMayBeObject = false; + for (let i = 1; i <= args.length - 1; ++i) { + const arg = args[i]; + if (nextTokenMayBeObject && typeof arg === 'object' && !Array.isArray(arg)) { + nextTokenMayBeObject = false; + let scale = null; + if (arg['font-scale']) { + scale = context.parse(arg['font-scale'], 1, NumberType); + if (!scale) + return null; + } + let font = null; + if (arg['text-font']) { + font = context.parse(arg['text-font'], 1, array$1(StringType)); + if (!font) + return null; + } + let textColor = null; + if (arg['text-color']) { + textColor = context.parse(arg['text-color'], 1, ColorType); + if (!textColor) + return null; + } + const lastExpression = sections[sections.length - 1]; + lastExpression.scale = scale; + lastExpression.font = font; + lastExpression.textColor = textColor; + } + else { + const content = context.parse(args[i], 1, ValueType); + if (!content) + return null; + const kind = content.type.kind; + if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage') + return context.error('Formatted text type must be \'string\', \'value\', \'image\' or \'null\'.'); + nextTokenMayBeObject = true; + sections.push({ content, scale: null, font: null, textColor: null }); + } + } + return new FormatExpression(sections); + } + evaluate(ctx) { + const evaluateSection = section => { + const evaluatedContent = section.content.evaluate(ctx); + if (typeOf(evaluatedContent) === ResolvedImageType) { + return new FormattedSection('', evaluatedContent, null, null, null); + } + return new FormattedSection(toString(evaluatedContent), null, section.scale ? section.scale.evaluate(ctx) : null, section.font ? section.font.evaluate(ctx).join(',') : null, section.textColor ? section.textColor.evaluate(ctx) : null); + }; + return new Formatted(this.sections.map(evaluateSection)); + } + eachChild(fn) { + for (const section of this.sections) { + fn(section.content); + if (section.scale) { + fn(section.scale); + } + if (section.font) { + fn(section.font); + } + if (section.textColor) { + fn(section.textColor); + } + } + } + outputDefined() { + // Technically the combinatoric set of all children + // Usually, this.text will be undefined anyway + return false; + } +} + +class ImageExpression { + constructor(input) { + this.type = ResolvedImageType; + this.input = input; + } + static parse(args, context) { + if (args.length !== 2) { + return context.error('Expected two arguments.'); + } + const name = context.parse(args[1], 1, StringType); + if (!name) + return context.error('No image name provided.'); + return new ImageExpression(name); + } + evaluate(ctx) { + const evaluatedImageName = this.input.evaluate(ctx); + const value = ResolvedImage.fromString(evaluatedImageName); + if (value && ctx.availableImages) + value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1; + return value; + } + eachChild(fn) { + fn(this.input); + } + outputDefined() { + // The output of image is determined by the list of available images in the evaluation context + return false; + } +} + +class Length { + constructor(input) { + this.type = NumberType; + this.input = input; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`); + const input = context.parse(args[1], 1); + if (!input) + return null; + if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value') + return context.error(`Expected argument of type string or array, but found ${toString$1(input.type)} instead.`); + return new Length(input); + } + evaluate(ctx) { + const input = this.input.evaluate(ctx); + if (typeof input === 'string') { + // The length may be affected by surrogate pairs. + return [...input].length; + } + else if (Array.isArray(input)) { + return input.length; + } + else { + throw new RuntimeError(`Expected value to be of type string or array, but found ${toString$1(typeOf(input))} instead.`); + } + } + eachChild(fn) { + fn(this.input); + } + outputDefined() { + return false; + } +} + +const EXTENT$1 = 8192; +function getTileCoordinates(p, canonical) { + const x = mercatorXfromLng$1(p[0]); + const y = mercatorYfromLat$1(p[1]); + const tilesAtZoom = Math.pow(2, canonical.z); + return [Math.round(x * tilesAtZoom * EXTENT$1), Math.round(y * tilesAtZoom * EXTENT$1)]; +} +function getLngLatFromTileCoord(coord, canonical) { + const tilesAtZoom = Math.pow(2, canonical.z); + const x = (coord[0] / EXTENT$1 + canonical.x) / tilesAtZoom; + const y = (coord[1] / EXTENT$1 + canonical.y) / tilesAtZoom; + return [lngFromMercatorXfromLng(x), latFromMercatorY$1(y)]; +} +function mercatorXfromLng$1(lng) { + return (180 + lng) / 360; +} +function lngFromMercatorXfromLng(mercatorX) { + return mercatorX * 360 - 180; +} +function mercatorYfromLat$1(lat) { + return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360; +} +function latFromMercatorY$1(mercatorY) { + return 360 / Math.PI * Math.atan(Math.exp((180 - mercatorY * 360) * Math.PI / 180)) - 90; +} +function updateBBox(bbox, coord) { + bbox[0] = Math.min(bbox[0], coord[0]); + bbox[1] = Math.min(bbox[1], coord[1]); + bbox[2] = Math.max(bbox[2], coord[0]); + bbox[3] = Math.max(bbox[3], coord[1]); +} +function boxWithinBox(bbox1, bbox2) { + if (bbox1[0] <= bbox2[0]) + return false; + if (bbox1[2] >= bbox2[2]) + return false; + if (bbox1[1] <= bbox2[1]) + return false; + if (bbox1[3] >= bbox2[3]) + return false; + return true; +} +function rayIntersect(p, p1, p2) { + 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]); +} +function pointOnBoundary(p, p1, p2) { + const x1 = p[0] - p1[0]; + const y1 = p[1] - p1[1]; + const x2 = p[0] - p2[0]; + const y2 = p[1] - p2[1]; + return (x1 * y2 - x2 * y1 === 0) && (x1 * x2 <= 0) && (y1 * y2 <= 0); +} +// a, b are end points for line segment1, c and d are end points for line segment2 +function segmentIntersectSegment(a, b, c, d) { + // check if two segments are parallel or not + // precondition is end point a, b is inside polygon, if line a->b is + // parallel to polygon edge c->d, then a->b won't intersect with c->d + const vectorP = [b[0] - a[0], b[1] - a[1]]; + const vectorQ = [d[0] - c[0], d[1] - c[1]]; + if (perp(vectorQ, vectorP) === 0) + return false; + // If lines are intersecting with each other, the relative location should be: + // a and b lie in different sides of segment c->d + // c and d lie in different sides of segment a->b + if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) + return true; + return false; +} +function lineIntersectPolygon(p1, p2, polygon) { + for (const ring of polygon) { + // loop through every edge of the ring + for (let j = 0; j < ring.length - 1; ++j) { + if (segmentIntersectSegment(p1, p2, ring[j], ring[j + 1])) { + return true; + } + } + } + return false; +} +// ray casting algorithm for detecting if point is in polygon +function pointWithinPolygon(point, rings, trueIfOnBoundary = false) { + let inside = false; + for (const ring of rings) { + for (let j = 0; j < ring.length - 1; j++) { + if (pointOnBoundary(point, ring[j], ring[j + 1])) + return trueIfOnBoundary; + if (rayIntersect(point, ring[j], ring[j + 1])) + inside = !inside; + } + } + return inside; +} +function pointWithinPolygons(point, polygons) { + for (const polygon of polygons) { + if (pointWithinPolygon(point, polygon)) + return true; + } + return false; +} +function lineStringWithinPolygon(line, polygon) { + // First, check if geometry points of line segments are all inside polygon + for (const point of line) { + if (!pointWithinPolygon(point, polygon)) { + return false; + } + } + // Second, check if there is line segment intersecting polygon edge + for (let i = 0; i < line.length - 1; ++i) { + if (lineIntersectPolygon(line[i], line[i + 1], polygon)) { + return false; + } + } + return true; +} +function lineStringWithinPolygons(line, polygons) { + for (const polygon of polygons) { + if (lineStringWithinPolygon(line, polygon)) + return true; + } + return false; +} +function perp(v1, v2) { + return (v1[0] * v2[1] - v1[1] * v2[0]); +} +// check if p1 and p2 are in different sides of line segment q1->q2 +function twoSided(p1, p2, q1, q2) { + // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3) + const x1 = p1[0] - q1[0]; + const y1 = p1[1] - q1[1]; + const x2 = p2[0] - q1[0]; + const y2 = p2[1] - q1[1]; + const x3 = q2[0] - q1[0]; + const y3 = q2[1] - q1[1]; + const det1 = (x1 * y3 - x3 * y1); + const det2 = (x2 * y3 - x3 * y2); + if ((det1 > 0 && det2 < 0) || (det1 < 0 && det2 > 0)) + return true; + return false; +} + +function getTilePolygon(coordinates, bbox, canonical) { + const polygon = []; + for (let i = 0; i < coordinates.length; i++) { + const ring = []; + for (let j = 0; j < coordinates[i].length; j++) { + const coord = getTileCoordinates(coordinates[i][j], canonical); + updateBBox(bbox, coord); + ring.push(coord); + } + polygon.push(ring); + } + return polygon; +} +function getTilePolygons(coordinates, bbox, canonical) { + const polygons = []; + for (let i = 0; i < coordinates.length; i++) { + const polygon = getTilePolygon(coordinates[i], bbox, canonical); + polygons.push(polygon); + } + return polygons; +} +function updatePoint(p, bbox, polyBBox, worldSize) { + if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) { + const halfWorldSize = worldSize * 0.5; + let shift = (p[0] - polyBBox[0] > halfWorldSize) ? -worldSize : (polyBBox[0] - p[0] > halfWorldSize) ? worldSize : 0; + if (shift === 0) { + shift = (p[0] - polyBBox[2] > halfWorldSize) ? -worldSize : (polyBBox[2] - p[0] > halfWorldSize) ? worldSize : 0; + } + p[0] += shift; + } + updateBBox(bbox, p); +} +function resetBBox(bbox) { + bbox[0] = bbox[1] = Infinity; + bbox[2] = bbox[3] = -Infinity; +} +function getTilePoints(geometry, pointBBox, polyBBox, canonical) { + const worldSize = Math.pow(2, canonical.z) * EXTENT$1; + const shifts = [canonical.x * EXTENT$1, canonical.y * EXTENT$1]; + const tilePoints = []; + for (const points of geometry) { + for (const point of points) { + const p = [point.x + shifts[0], point.y + shifts[1]]; + updatePoint(p, pointBBox, polyBBox, worldSize); + tilePoints.push(p); + } + } + return tilePoints; +} +function getTileLines(geometry, lineBBox, polyBBox, canonical) { + const worldSize = Math.pow(2, canonical.z) * EXTENT$1; + const shifts = [canonical.x * EXTENT$1, canonical.y * EXTENT$1]; + const tileLines = []; + for (const line of geometry) { + const tileLine = []; + for (const point of line) { + const p = [point.x + shifts[0], point.y + shifts[1]]; + updateBBox(lineBBox, p); + tileLine.push(p); + } + tileLines.push(tileLine); + } + if (lineBBox[2] - lineBBox[0] <= worldSize / 2) { + resetBBox(lineBBox); + for (const line of tileLines) { + for (const p of line) { + updatePoint(p, lineBBox, polyBBox, worldSize); + } + } + } + return tileLines; +} +function pointsWithinPolygons(ctx, polygonGeometry) { + const pointBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const polyBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const canonical = ctx.canonicalID(); + if (polygonGeometry.type === 'Polygon') { + const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) + return false; + for (const point of tilePoints) { + if (!pointWithinPolygon(point, tilePolygon)) + return false; + } + } + if (polygonGeometry.type === 'MultiPolygon') { + const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) + return false; + for (const point of tilePoints) { + if (!pointWithinPolygons(point, tilePolygons)) + return false; + } + } + return true; +} +function linesWithinPolygons(ctx, polygonGeometry) { + const lineBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const polyBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const canonical = ctx.canonicalID(); + if (polygonGeometry.type === 'Polygon') { + const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) + return false; + for (const line of tileLines) { + if (!lineStringWithinPolygon(line, tilePolygon)) + return false; + } + } + if (polygonGeometry.type === 'MultiPolygon') { + const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) + return false; + for (const line of tileLines) { + if (!lineStringWithinPolygons(line, tilePolygons)) + return false; + } + } + return true; +} +class Within { + constructor(geojson, geometries) { + this.type = BooleanType; + this.geojson = geojson; + this.geometries = geometries; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (isValue(args[1])) { + const geojson = args[1]; + if (geojson.type === 'FeatureCollection') { + const polygonsCoords = []; + for (const polygon of geojson.features) { + const { type, coordinates } = polygon.geometry; + if (type === 'Polygon') { + polygonsCoords.push(coordinates); + } + if (type === 'MultiPolygon') { + polygonsCoords.push(...coordinates); + } + } + if (polygonsCoords.length) { + const multipolygonWrapper = { + type: 'MultiPolygon', + coordinates: polygonsCoords + }; + return new Within(geojson, multipolygonWrapper); + } + } + else if (geojson.type === 'Feature') { + const type = geojson.geometry.type; + if (type === 'Polygon' || type === 'MultiPolygon') { + return new Within(geojson, geojson.geometry); + } + } + else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') { + return new Within(geojson, geojson); + } + } + return context.error('\'within\' expression requires valid geojson object that contains polygon geometry type.'); + } + evaluate(ctx) { + if (ctx.geometry() != null && ctx.canonicalID() != null) { + if (ctx.geometryType() === 'Point') { + return pointsWithinPolygons(ctx, this.geometries); + } + else if (ctx.geometryType() === 'LineString') { + return linesWithinPolygons(ctx, this.geometries); + } + } + return false; + } + eachChild() { } + outputDefined() { + return true; + } +} + +let TinyQueue$1 = class TinyQueue { + constructor(data = [], compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) { + this.data = data; + this.length = this.data.length; + this.compare = compare; + + if (this.length > 0) { + for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i); + } + } + + push(item) { + this.data.push(item); + this._up(this.length++); + } + + pop() { + if (this.length === 0) return undefined; + + const top = this.data[0]; + const bottom = this.data.pop(); + + if (--this.length > 0) { + this.data[0] = bottom; + this._down(0); + } + + return top; + } + + peek() { + return this.data[0]; + } + + _up(pos) { + const {data, compare} = this; + const item = data[pos]; + + while (pos > 0) { + const parent = (pos - 1) >> 1; + const current = data[parent]; + if (compare(item, current) >= 0) break; + data[pos] = current; + pos = parent; + } + + data[pos] = item; + } + + _down(pos) { + const {data, compare} = this; + const halfLength = this.length >> 1; + const item = data[pos]; + + while (pos < halfLength) { + let bestChild = (pos << 1) + 1; // initially it is the left child + const right = bestChild + 1; + + if (right < this.length && compare(data[right], data[bestChild]) < 0) { + bestChild = right; + } + if (compare(data[bestChild], item) >= 0) break; + + data[pos] = data[bestChild]; + pos = bestChild; + } + + data[pos] = item; + } +}; + +function quickselect(arr, k, left, right, compare) { + quickselectStep(arr, k, left, right || (arr.length - 1), compare || defaultCompare); +} + +function quickselectStep(arr, k, left, right, compare) { + + while (right > left) { + if (right - left > 600) { + var n = right - left + 1; + var m = k - left + 1; + var z = Math.log(n); + var s = 0.5 * Math.exp(2 * z / 3); + var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + quickselectStep(arr, k, newLeft, newRight, compare); + } + + var t = arr[k]; + var i = left; + var j = right; + + swap$2(arr, left, k); + if (compare(arr[right], t) > 0) swap$2(arr, left, right); + + while (i < j) { + swap$2(arr, i, j); + i++; + j--; + while (compare(arr[i], t) < 0) i++; + while (compare(arr[j], t) > 0) j--; + } + + if (compare(arr[left], t) === 0) swap$2(arr, left, j); + else { + j++; + swap$2(arr, j, right); + } + + if (j <= k) left = j + 1; + if (k <= j) right = j - 1; + } +} + +function swap$2(arr, i, j) { + var tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} + +function defaultCompare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * Classifies an array of rings into polygons with outer rings and holes + * @param rings - the rings to classify + * @param maxRings - the maximum number of rings to include in a polygon, use 0 to include all rings + * @returns an array of polygons with internal rings as holes + */ +function classifyRings$1(rings, maxRings) { + const len = rings.length; + if (len <= 1) + return [rings]; + const polygons = []; + let polygon; + let ccw; + for (const ring of rings) { + const area = calculateSignedArea(ring); + if (area === 0) + continue; + ring.area = Math.abs(area); + if (ccw === undefined) + ccw = area < 0; + if (ccw === area < 0) { + if (polygon) + polygons.push(polygon); + polygon = [ring]; + } + else { + polygon.push(ring); + } + } + if (polygon) + polygons.push(polygon); + // Earcut performance degrades with the # of rings in a polygon. For this + // reason, we limit strip out all but the `maxRings` largest rings. + if (maxRings > 1) { + for (let j = 0; j < polygons.length; j++) { + if (polygons[j].length <= maxRings) + continue; + quickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas); + polygons[j] = polygons[j].slice(0, maxRings); + } + } + return polygons; +} +function compareAreas(a, b) { + return b.area - a.area; +} +/** + * Returns the signed area for the polygon ring. Positive areas are exterior rings and + * have a clockwise winding. Negative areas are interior rings and have a counter clockwise + * ordering. + * + * @param ring - Exterior or interior ring + * @returns Signed area + */ +function calculateSignedArea(ring) { + let sum = 0; + for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + return sum; +} + +// This is taken from https://github.com/mapbox/cheap-ruler/ in order to take only the relevant parts +// Values that define WGS84 ellipsoid model of the Earth +const RE = 6378.137; // equatorial radius +const FE = 1 / 298.257223563; // flattening +const E2 = FE * (2 - FE); +const RAD = Math.PI / 180; +class CheapRuler { + constructor(lat) { + // Curvature formulas from https://en.wikipedia.org/wiki/Earth_radius#Meridional + const m = RAD * RE * 1000; + const coslat = Math.cos(lat * RAD); + const w2 = 1 / (1 - E2 * (1 - coslat * coslat)); + const w = Math.sqrt(w2); + // multipliers for converting longitude and latitude degrees into distance + this.kx = m * w * coslat; // based on normal radius of curvature + this.ky = m * w * w2 * (1 - E2); // based on meridonal radius of curvature + } + /** + * Given two points of the form [longitude, latitude], returns the distance. + * + * @param a - point [longitude, latitude] + * @param b - point [longitude, latitude] + * @returns distance + * @example + * const distance = ruler.distance([30.5, 50.5], [30.51, 50.49]); + * //=distance + */ + distance(a, b) { + const dx = this.wrap(a[0] - b[0]) * this.kx; + const dy = (a[1] - b[1]) * this.ky; + return Math.sqrt(dx * dx + dy * dy); + } + /** + * Returns an object of the form {point, index, t}, where point is closest point on the line + * from the given point, index is the start index of the segment with the closest point, + * and t is a parameter from 0 to 1 that indicates where the closest point is on that segment. + * + * @param line - an array of points that form the line + * @param p - point [longitude, latitude] + * @returns the nearest point, its index in the array and the proportion along the line + * @example + * const point = ruler.pointOnLine(line, [-67.04, 50.5]).point; + * //=point + */ + pointOnLine(line, p) { + let minDist = Infinity; + let minX, minY, minI, minT; + for (let i = 0; i < line.length - 1; i++) { + let x = line[i][0]; + let y = line[i][1]; + let dx = this.wrap(line[i + 1][0] - x) * this.kx; + let dy = (line[i + 1][1] - y) * this.ky; + let t = 0; + if (dx !== 0 || dy !== 0) { + t = (this.wrap(p[0] - x) * this.kx * dx + (p[1] - y) * this.ky * dy) / (dx * dx + dy * dy); + if (t > 1) { + x = line[i + 1][0]; + y = line[i + 1][1]; + } + else if (t > 0) { + x += (dx / this.kx) * t; + y += (dy / this.ky) * t; + } + } + dx = this.wrap(p[0] - x) * this.kx; + dy = (p[1] - y) * this.ky; + const sqDist = dx * dx + dy * dy; + if (sqDist < minDist) { + minDist = sqDist; + minX = x; + minY = y; + minI = i; + minT = t; + } + } + return { + point: [minX, minY], + index: minI, + t: Math.max(0, Math.min(1, minT)) + }; + } + wrap(deg) { + while (deg < -180) + deg += 360; + while (deg > 180) + deg -= 360; + return deg; + } +} + +const MinPointsSize = 100; +const MinLinePointsSize = 50; +function compareDistPair(a, b) { + return b[0] - a[0]; +} +function getRangeSize(range) { + return range[1] - range[0] + 1; +} +function isRangeSafe(range, threshold) { + return range[1] >= range[0] && range[1] < threshold; +} +function splitRange(range, isLine) { + if (range[0] > range[1]) { + return [null, null]; + } + const size = getRangeSize(range); + if (isLine) { + if (size === 2) { + return [range, null]; + } + const size1 = Math.floor(size / 2); + return [[range[0], range[0] + size1], + [range[0] + size1, range[1]]]; + } + if (size === 1) { + return [range, null]; + } + const size1 = Math.floor(size / 2) - 1; + return [[range[0], range[0] + size1], + [range[0] + size1 + 1, range[1]]]; +} +function getBBox(coords, range) { + if (!isRangeSafe(range, coords.length)) { + return [Infinity, Infinity, -Infinity, -Infinity]; + } + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + for (let i = range[0]; i <= range[1]; ++i) { + updateBBox(bbox, coords[i]); + } + return bbox; +} +function getPolygonBBox(polygon) { + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + for (const ring of polygon) { + for (const coord of ring) { + updateBBox(bbox, coord); + } + } + return bbox; +} +function isValidBBox(bbox) { + return bbox[0] !== -Infinity && bbox[1] !== -Infinity && bbox[2] !== Infinity && bbox[3] !== Infinity; +} +// Calculate the distance between two bounding boxes. +// Calculate the delta in x and y direction, and use two fake points {0.0, 0.0} +// and {dx, dy} to calculate the distance. Distance will be 0.0 if bounding box are overlapping. +function bboxToBBoxDistance(bbox1, bbox2, ruler) { + if (!isValidBBox(bbox1) || !isValidBBox(bbox2)) { + return NaN; + } + let dx = 0.0; + let dy = 0.0; + // bbox1 in left side + if (bbox1[2] < bbox2[0]) { + dx = bbox2[0] - bbox1[2]; + } + // bbox1 in right side + if (bbox1[0] > bbox2[2]) { + dx = bbox1[0] - bbox2[2]; + } + // bbox1 in above side + if (bbox1[1] > bbox2[3]) { + dy = bbox1[1] - bbox2[3]; + } + // bbox1 in down side + if (bbox1[3] < bbox2[1]) { + dy = bbox2[1] - bbox1[3]; + } + return ruler.distance([0.0, 0.0], [dx, dy]); +} +function pointToLineDistance(point, line, ruler) { + const nearestPoint = ruler.pointOnLine(line, point); + return ruler.distance(point, nearestPoint.point); +} +function segmentToSegmentDistance(p1, p2, q1, q2, ruler) { + const dist1 = Math.min(pointToLineDistance(p1, [q1, q2], ruler), pointToLineDistance(p2, [q1, q2], ruler)); + const dist2 = Math.min(pointToLineDistance(q1, [p1, p2], ruler), pointToLineDistance(q2, [p1, p2], ruler)); + return Math.min(dist1, dist2); +} +function lineToLineDistance(line1, range1, line2, range2, ruler) { + const rangeSafe = isRangeSafe(range1, line1.length) && isRangeSafe(range2, line2.length); + if (!rangeSafe) { + return Infinity; + } + let dist = Infinity; + for (let i = range1[0]; i < range1[1]; ++i) { + const p1 = line1[i]; + const p2 = line1[i + 1]; + for (let j = range2[0]; j < range2[1]; ++j) { + const q1 = line2[j]; + const q2 = line2[j + 1]; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } + dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); + } + } + return dist; +} +function pointsToPointsDistance(points1, range1, points2, range2, ruler) { + const rangeSafe = isRangeSafe(range1, points1.length) && isRangeSafe(range2, points2.length); + if (!rangeSafe) { + return NaN; + } + let dist = Infinity; + for (let i = range1[0]; i <= range1[1]; ++i) { + for (let j = range2[0]; j <= range2[1]; ++j) { + dist = Math.min(dist, ruler.distance(points1[i], points2[j])); + if (dist === 0.0) { + return dist; + } + } + } + return dist; +} +function pointToPolygonDistance(point, polygon, ruler) { + if (pointWithinPolygon(point, polygon, true)) { + return 0.0; + } + let dist = Infinity; + for (const ring of polygon) { + const front = ring[0]; + const back = ring[ring.length - 1]; + if (front !== back) { + dist = Math.min(dist, pointToLineDistance(point, [back, front], ruler)); + if (dist === 0.0) { + return dist; + } + } + const nearestPoint = ruler.pointOnLine(ring, point); + dist = Math.min(dist, ruler.distance(point, nearestPoint.point)); + if (dist === 0.0) { + return dist; + } + } + return dist; +} +function lineToPolygonDistance(line, range, polygon, ruler) { + if (!isRangeSafe(range, line.length)) { + return NaN; + } + for (let i = range[0]; i <= range[1]; ++i) { + if (pointWithinPolygon(line[i], polygon, true)) { + return 0.0; + } + } + let dist = Infinity; + for (let i = range[0]; i < range[1]; ++i) { + const p1 = line[i]; + const p2 = line[i + 1]; + for (const ring of polygon) { + for (let j = 0, len = ring.length, k = len - 1; j < len; k = j++) { + const q1 = ring[k]; + const q2 = ring[j]; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } + dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); + } + } + } + return dist; +} +function polygonIntersect(poly1, poly2) { + for (const ring of poly1) { + for (const point of ring) { + if (pointWithinPolygon(point, poly2, true)) { + return true; + } + } + } + return false; +} +function polygonToPolygonDistance(polygon1, polygon2, ruler, currentMiniDist = Infinity) { + const bbox1 = getPolygonBBox(polygon1); + const bbox2 = getPolygonBBox(polygon2); + if (currentMiniDist !== Infinity && bboxToBBoxDistance(bbox1, bbox2, ruler) >= currentMiniDist) { + return currentMiniDist; + } + if (boxWithinBox(bbox1, bbox2)) { + if (polygonIntersect(polygon1, polygon2)) { + return 0.0; + } + } + else if (polygonIntersect(polygon2, polygon1)) { + return 0.0; + } + let dist = Infinity; + for (const ring1 of polygon1) { + for (let i = 0, len1 = ring1.length, l = len1 - 1; i < len1; l = i++) { + const p1 = ring1[l]; + const p2 = ring1[i]; + for (const ring2 of polygon2) { + for (let j = 0, len2 = ring2.length, k = len2 - 1; j < len2; k = j++) { + const q1 = ring2[k]; + const q2 = ring2[j]; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } + dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); + } + } + } + } + return dist; +} +function updateQueue(distQueue, miniDist, ruler, points, polyBBox, rangeA) { + if (!rangeA) { + return; + } + const tempDist = bboxToBBoxDistance(getBBox(points, rangeA), polyBBox, ruler); + // Insert new pair to the queue if the bbox distance is less than + // miniDist, The pair with biggest distance will be at the top + if (tempDist < miniDist) { + distQueue.push([tempDist, rangeA, [0, 0]]); + } +} +function updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, range1, range2) { + if (!range1 || !range2) { + return; + } + const tempDist = bboxToBBoxDistance(getBBox(pointSet1, range1), getBBox(pointSet2, range2), ruler); + // Insert new pair to the queue if the bbox distance is less than + // miniDist, The pair with biggest distance will be at the top + if (tempDist < miniDist) { + distQueue.push([tempDist, range1, range2]); + } +} +// Divide and conquer, the time complexity is O(n*lgn), faster than Brute force +// O(n*n) Most of the time, use index for in-place processing. +function pointsToPolygonDistance(points, isLine, polygon, ruler, currentMiniDist = Infinity) { + let miniDist = Math.min(ruler.distance(points[0], polygon[0][0]), currentMiniDist); + if (miniDist === 0.0) { + return miniDist; + } + const distQueue = new TinyQueue$1([[0, [0, points.length - 1], [0, 0]]], compareDistPair); + const polyBBox = getPolygonBBox(polygon); + while (distQueue.length > 0) { + const distPair = distQueue.pop(); + if (distPair[0] >= miniDist) { + continue; + } + const range = distPair[1]; + // In case the set size are relatively small, we could use brute-force directly + const threshold = isLine ? MinLinePointsSize : MinPointsSize; + if (getRangeSize(range) <= threshold) { + if (!isRangeSafe(range, points.length)) { + return NaN; + } + if (isLine) { + const tempDist = lineToPolygonDistance(points, range, polygon, ruler); + if (isNaN(tempDist) || tempDist === 0.0) { + return tempDist; + } + miniDist = Math.min(miniDist, tempDist); + } + else { + for (let i = range[0]; i <= range[1]; ++i) { + const tempDist = pointToPolygonDistance(points[i], polygon, ruler); + miniDist = Math.min(miniDist, tempDist); + if (miniDist === 0.0) { + return 0.0; + } + } + } + } + else { + const newRangesA = splitRange(range, isLine); + updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[0]); + updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[1]); + } + } + return miniDist; +} +function pointSetToPointSetDistance(pointSet1, isLine1, pointSet2, isLine2, ruler, currentMiniDist = Infinity) { + let miniDist = Math.min(currentMiniDist, ruler.distance(pointSet1[0], pointSet2[0])); + if (miniDist === 0.0) { + return miniDist; + } + const distQueue = new TinyQueue$1([[0, [0, pointSet1.length - 1], [0, pointSet2.length - 1]]], compareDistPair); + while (distQueue.length > 0) { + const distPair = distQueue.pop(); + if (distPair[0] >= miniDist) { + continue; + } + const rangeA = distPair[1]; + const rangeB = distPair[2]; + const threshold1 = isLine1 ? MinLinePointsSize : MinPointsSize; + const threshold2 = isLine2 ? MinLinePointsSize : MinPointsSize; + // In case the set size are relatively small, we could use brute-force directly + if (getRangeSize(rangeA) <= threshold1 && getRangeSize(rangeB) <= threshold2) { + if (!isRangeSafe(rangeA, pointSet1.length) && isRangeSafe(rangeB, pointSet2.length)) { + return NaN; + } + let tempDist; + if (isLine1 && isLine2) { + tempDist = lineToLineDistance(pointSet1, rangeA, pointSet2, rangeB, ruler); + miniDist = Math.min(miniDist, tempDist); + } + else if (isLine1 && !isLine2) { + const sublibe = pointSet1.slice(rangeA[0], rangeA[1] + 1); + for (let i = rangeB[0]; i <= rangeB[1]; ++i) { + tempDist = pointToLineDistance(pointSet2[i], sublibe, ruler); + miniDist = Math.min(miniDist, tempDist); + if (miniDist === 0.0) { + return miniDist; + } + } + } + else if (!isLine1 && isLine2) { + const sublibe = pointSet2.slice(rangeB[0], rangeB[1] + 1); + for (let i = rangeA[0]; i <= rangeA[1]; ++i) { + tempDist = pointToLineDistance(pointSet1[i], sublibe, ruler); + miniDist = Math.min(miniDist, tempDist); + if (miniDist === 0.0) { + return miniDist; + } + } + } + else { + tempDist = pointsToPointsDistance(pointSet1, rangeA, pointSet2, rangeB, ruler); + miniDist = Math.min(miniDist, tempDist); + } + } + else { + const newRangesA = splitRange(rangeA, isLine1); + const newRangesB = splitRange(rangeB, isLine2); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[0]); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[1]); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[0]); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[1]); + } + } + return miniDist; +} +function pointToGeometryDistance(ctx, geometries) { + const tilePoints = ctx.geometry(); + const pointPosition = tilePoints.flat().map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); + if (tilePoints.length === 0) { + return NaN; + } + const ruler = new CheapRuler(pointPosition[0][1]); + let dist = Infinity; + for (const geometry of geometries) { + switch (geometry.type) { + case 'Point': + dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, [geometry.coordinates], false, ruler, dist)); + break; + case 'LineString': + dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, geometry.coordinates, true, ruler, dist)); + break; + case 'Polygon': + dist = Math.min(dist, pointsToPolygonDistance(pointPosition, false, geometry.coordinates, ruler, dist)); + break; + } + if (dist === 0.0) { + return dist; + } + } + return dist; +} +function lineStringToGeometryDistance(ctx, geometries) { + const tileLine = ctx.geometry(); + const linePositions = tileLine.flat().map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); + if (tileLine.length === 0) { + return NaN; + } + const ruler = new CheapRuler(linePositions[0][1]); + let dist = Infinity; + for (const geometry of geometries) { + switch (geometry.type) { + case 'Point': + dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, [geometry.coordinates], false, ruler, dist)); + break; + case 'LineString': + dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, geometry.coordinates, true, ruler, dist)); + break; + case 'Polygon': + dist = Math.min(dist, pointsToPolygonDistance(linePositions, true, geometry.coordinates, ruler, dist)); + break; + } + if (dist === 0.0) { + return dist; + } + } + return dist; +} +function polygonToGeometryDistance(ctx, geometries) { + const tilePolygon = ctx.geometry(); + if (tilePolygon.length === 0 || tilePolygon[0].length === 0) { + return NaN; + } + const polygons = classifyRings$1(tilePolygon, 0).map(polygon => { + return polygon.map(ring => { + return ring.map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); + }); + }); + const ruler = new CheapRuler(polygons[0][0][0][1]); + let dist = Infinity; + for (const geometry of geometries) { + for (const polygon of polygons) { + switch (geometry.type) { + case 'Point': + dist = Math.min(dist, pointsToPolygonDistance([geometry.coordinates], false, polygon, ruler, dist)); + break; + case 'LineString': + dist = Math.min(dist, pointsToPolygonDistance(geometry.coordinates, true, polygon, ruler, dist)); + break; + case 'Polygon': + dist = Math.min(dist, polygonToPolygonDistance(polygon, geometry.coordinates, ruler, dist)); + break; + } + if (dist === 0.0) { + return dist; + } + } + } + return dist; +} +function toSimpleGeometry(geometry) { + if (geometry.type === 'MultiPolygon') { + return geometry.coordinates.map(polygon => { + return { + type: 'Polygon', + coordinates: polygon + }; + }); + } + if (geometry.type === 'MultiLineString') { + return geometry.coordinates.map(lineString => { + return { + type: 'LineString', + coordinates: lineString + }; + }); + } + if (geometry.type === 'MultiPoint') { + return geometry.coordinates.map(point => { + return { + type: 'Point', + coordinates: point + }; + }); + } + return [geometry]; +} +class Distance { + constructor(geojson, geometries) { + this.type = NumberType; + this.geojson = geojson; + this.geometries = geometries; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`'distance' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (isValue(args[1])) { + const geojson = args[1]; + if (geojson.type === 'FeatureCollection') { + return new Distance(geojson, geojson.features.map(feature => toSimpleGeometry(feature.geometry)).flat()); + } + else if (geojson.type === 'Feature') { + return new Distance(geojson, toSimpleGeometry(geojson.geometry)); + } + else if ('type' in geojson && 'coordinates' in geojson) { + return new Distance(geojson, toSimpleGeometry(geojson)); + } + } + return context.error('\'distance\' expression requires valid geojson object that contains polygon geometry type.'); + } + evaluate(ctx) { + if (ctx.geometry() != null && ctx.canonicalID() != null) { + if (ctx.geometryType() === 'Point') { + return pointToGeometryDistance(ctx, this.geometries); + } + else if (ctx.geometryType() === 'LineString') { + return lineStringToGeometryDistance(ctx, this.geometries); + } + else if (ctx.geometryType() === 'Polygon') { + return polygonToGeometryDistance(ctx, this.geometries); + } + } + return NaN; + } + eachChild() { } + outputDefined() { + return true; + } +} + +const expressions$1 = { + // special forms + '==': Equals, + '!=': NotEquals, + '>': GreaterThan, + '<': LessThan, + '>=': GreaterThanOrEqual, + '<=': LessThanOrEqual, + 'array': Assertion, + 'at': At, + 'boolean': Assertion, + 'case': Case, + 'coalesce': Coalesce, + 'collator': CollatorExpression, + 'format': FormatExpression, + 'image': ImageExpression, + 'in': In, + 'index-of': IndexOf, + 'interpolate': Interpolate, + 'interpolate-hcl': Interpolate, + 'interpolate-lab': Interpolate, + 'length': Length, + 'let': Let, + 'literal': Literal, + 'match': Match, + 'number': Assertion, + 'number-format': NumberFormat, + 'object': Assertion, + 'slice': Slice, + 'step': Step, + 'string': Assertion, + 'to-boolean': Coercion, + 'to-color': Coercion, + 'to-number': Coercion, + 'to-string': Coercion, + 'var': Var, + 'within': Within, + 'distance': Distance +}; + +class CompoundExpression { + constructor(name, type, evaluate, args) { + this.name = name; + this.type = type; + this._evaluate = evaluate; + this.args = args; + } + evaluate(ctx) { + return this._evaluate(ctx, this.args); + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return false; + } + static parse(args, context) { + const op = args[0]; + const definition = CompoundExpression.definitions[op]; + if (!definition) { + return context.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); + } + // Now check argument types against each signature + const type = Array.isArray(definition) ? + definition[0] : definition.type; + const availableOverloads = Array.isArray(definition) ? + [[definition[1], definition[2]]] : + definition.overloads; + const overloads = availableOverloads.filter(([signature]) => (!Array.isArray(signature) || // varags + signature.length === args.length - 1 // correct param count + )); + let signatureContext = null; + for (const [params, evaluate] of overloads) { + // Use a fresh context for each attempted signature so that, if + // we eventually succeed, we haven't polluted `context.errors`. + signatureContext = new ParsingContext(context.registry, isExpressionConstant, context.path, null, context.scope); + // First parse all the args, potentially coercing to the + // types expected by this overload. + const parsedArgs = []; + let argParseFailed = false; + for (let i = 1; i < args.length; i++) { + const arg = args[i]; + const expectedType = Array.isArray(params) ? + params[i - 1] : + params.type; + const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType); + if (!parsed) { + argParseFailed = true; + break; + } + parsedArgs.push(parsed); + } + if (argParseFailed) { + // Couldn't coerce args of this overload to expected type, move + // on to next one. + continue; + } + if (Array.isArray(params)) { + if (params.length !== parsedArgs.length) { + signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`); + continue; + } + } + for (let i = 0; i < parsedArgs.length; i++) { + const expected = Array.isArray(params) ? params[i] : params.type; + const arg = parsedArgs[i]; + signatureContext.concat(i + 1).checkSubtype(expected, arg.type); + } + if (signatureContext.errors.length === 0) { + return new CompoundExpression(op, type, evaluate, parsedArgs); + } + } + if (overloads.length === 1) { + context.errors.push(...signatureContext.errors); + } + else { + const expected = overloads.length ? overloads : availableOverloads; + const signatures = expected + .map(([params]) => stringifySignature(params)) + .join(' | '); + const actualTypes = []; + // For error message, re-parse arguments without trying to + // apply any coercions + for (let i = 1; i < args.length; i++) { + const parsed = context.parse(args[i], 1 + actualTypes.length); + if (!parsed) + return null; + actualTypes.push(toString$1(parsed.type)); + } + context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`); + } + return null; + } + static register(registry, definitions) { + CompoundExpression.definitions = definitions; + for (const name in definitions) { + registry[name] = CompoundExpression; + } + } +} +function rgba(ctx, [r, g, b, a]) { + r = r.evaluate(ctx); + g = g.evaluate(ctx); + b = b.evaluate(ctx); + const alpha = a ? a.evaluate(ctx) : 1; + const error = validateRGBA(r, g, b, alpha); + if (error) + throw new RuntimeError(error); + return new Color(r / 255, g / 255, b / 255, alpha, false); +} +function has(key, obj) { + return key in obj; +} +function get(key, obj) { + const v = obj[key]; + return typeof v === 'undefined' ? null : v; +} +function binarySearch(v, a, i, j) { + while (i <= j) { + const m = (i + j) >> 1; + if (a[m] === v) + return true; + if (a[m] > v) + j = m - 1; + else + i = m + 1; + } + return false; +} +function varargs(type) { + return { type }; +} +CompoundExpression.register(expressions$1, { + 'error': [ + ErrorType, + [StringType], + (ctx, [v]) => { throw new RuntimeError(v.evaluate(ctx)); } + ], + 'typeof': [ + StringType, + [ValueType], + (ctx, [v]) => toString$1(typeOf(v.evaluate(ctx))) + ], + 'to-rgba': [ + array$1(NumberType, 4), + [ColorType], + (ctx, [v]) => { + const [r, g, b, a] = v.evaluate(ctx).rgb; + return [r * 255, g * 255, b * 255, a]; + }, + ], + 'rgb': [ + ColorType, + [NumberType, NumberType, NumberType], + rgba + ], + 'rgba': [ + ColorType, + [NumberType, NumberType, NumberType, NumberType], + rgba + ], + 'has': { + type: BooleanType, + overloads: [ + [ + [StringType], + (ctx, [key]) => has(key.evaluate(ctx), ctx.properties()) + ], [ + [StringType, ObjectType], + (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx)) + ] + ] + }, + 'get': { + type: ValueType, + overloads: [ + [ + [StringType], + (ctx, [key]) => get(key.evaluate(ctx), ctx.properties()) + ], [ + [StringType, ObjectType], + (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx)) + ] + ] + }, + 'feature-state': [ + ValueType, + [StringType], + (ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {}) + ], + 'properties': [ + ObjectType, + [], + (ctx) => ctx.properties() + ], + 'geometry-type': [ + StringType, + [], + (ctx) => ctx.geometryType() + ], + 'id': [ + ValueType, + [], + (ctx) => ctx.id() + ], + 'zoom': [ + NumberType, + [], + (ctx) => ctx.globals.zoom + ], + 'heatmap-density': [ + NumberType, + [], + (ctx) => ctx.globals.heatmapDensity || 0 + ], + 'line-progress': [ + NumberType, + [], + (ctx) => ctx.globals.lineProgress || 0 + ], + 'accumulated': [ + ValueType, + [], + (ctx) => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated + ], + '+': [ + NumberType, + varargs(NumberType), + (ctx, args) => { + let result = 0; + for (const arg of args) { + result += arg.evaluate(ctx); + } + return result; + } + ], + '*': [ + NumberType, + varargs(NumberType), + (ctx, args) => { + let result = 1; + for (const arg of args) { + result *= arg.evaluate(ctx); + } + return result; + } + ], + '-': { + type: NumberType, + overloads: [ + [ + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx) + ], [ + [NumberType], + (ctx, [a]) => -a.evaluate(ctx) + ] + ] + }, + '/': [ + NumberType, + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx) + ], + '%': [ + NumberType, + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx) + ], + 'ln2': [ + NumberType, + [], + () => Math.LN2 + ], + 'pi': [ + NumberType, + [], + () => Math.PI + ], + 'e': [ + NumberType, + [], + () => Math.E + ], + '^': [ + NumberType, + [NumberType, NumberType], + (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx)) + ], + 'sqrt': [ + NumberType, + [NumberType], + (ctx, [x]) => Math.sqrt(x.evaluate(ctx)) + ], + 'log10': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10 + ], + 'ln': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) + ], + 'log2': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2 + ], + 'sin': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.sin(n.evaluate(ctx)) + ], + 'cos': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.cos(n.evaluate(ctx)) + ], + 'tan': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.tan(n.evaluate(ctx)) + ], + 'asin': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.asin(n.evaluate(ctx)) + ], + 'acos': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.acos(n.evaluate(ctx)) + ], + 'atan': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.atan(n.evaluate(ctx)) + ], + 'min': [ + NumberType, + varargs(NumberType), + (ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx))) + ], + 'max': [ + NumberType, + varargs(NumberType), + (ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx))) + ], + 'abs': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.abs(n.evaluate(ctx)) + ], + 'round': [ + NumberType, + [NumberType], + (ctx, [n]) => { + const v = n.evaluate(ctx); + // Javascript's Math.round() rounds towards +Infinity for halfway + // values, even when they're negative. It's more common to round + // away from 0 (e.g., this is what python and C++ do) + return v < 0 ? -Math.round(-v) : Math.round(v); + } + ], + 'floor': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.floor(n.evaluate(ctx)) + ], + 'ceil': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.ceil(n.evaluate(ctx)) + ], + 'filter-==': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => ctx.properties()[k.value] === v.value + ], + 'filter-id-==': [ + BooleanType, + [ValueType], + (ctx, [v]) => ctx.id() === v.value + ], + 'filter-type-==': [ + BooleanType, + [StringType], + (ctx, [v]) => ctx.geometryType() === v.value + ], + 'filter-<': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a < b; + } + ], + 'filter-id-<': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a < b; + } + ], + 'filter->': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a > b; + } + ], + 'filter-id->': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a > b; + } + ], + 'filter-<=': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a <= b; + } + ], + 'filter-id-<=': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a <= b; + } + ], + 'filter->=': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-id->=': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-has': [ + BooleanType, + [ValueType], + (ctx, [k]) => k.value in ctx.properties() + ], + 'filter-has-id': [ + BooleanType, + [], + (ctx) => (ctx.id() !== null && ctx.id() !== undefined) + ], + 'filter-type-in': [ + BooleanType, + [array$1(StringType)], + (ctx, [v]) => v.value.indexOf(ctx.geometryType()) >= 0 + ], + 'filter-id-in': [ + BooleanType, + [array$1(ValueType)], + (ctx, [v]) => v.value.indexOf(ctx.id()) >= 0 + ], + 'filter-in-small': [ + BooleanType, + [StringType, array$1(ValueType)], + // assumes v is an array literal + (ctx, [k, v]) => v.value.indexOf(ctx.properties()[k.value]) >= 0 + ], + 'filter-in-large': [ + BooleanType, + [StringType, array$1(ValueType)], + // assumes v is a array literal with values sorted in ascending order and of a single type + (ctx, [k, v]) => binarySearch(ctx.properties()[k.value], v.value, 0, v.value.length - 1) + ], + 'all': { + type: BooleanType, + overloads: [ + [ + [BooleanType, BooleanType], + (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx) + ], + [ + varargs(BooleanType), + (ctx, args) => { + for (const arg of args) { + if (!arg.evaluate(ctx)) + return false; + } + return true; + } + ] + ] + }, + 'any': { + type: BooleanType, + overloads: [ + [ + [BooleanType, BooleanType], + (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx) + ], + [ + varargs(BooleanType), + (ctx, args) => { + for (const arg of args) { + if (arg.evaluate(ctx)) + return true; + } + return false; + } + ] + ] + }, + '!': [ + BooleanType, + [BooleanType], + (ctx, [b]) => !b.evaluate(ctx) + ], + 'is-supported-script': [ + BooleanType, + [StringType], + // At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant + (ctx, [s]) => { + const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript; + if (isSupportedScript) { + return isSupportedScript(s.evaluate(ctx)); + } + return true; + } + ], + 'upcase': [ + StringType, + [StringType], + (ctx, [s]) => s.evaluate(ctx).toUpperCase() + ], + 'downcase': [ + StringType, + [StringType], + (ctx, [s]) => s.evaluate(ctx).toLowerCase() + ], + 'concat': [ + StringType, + varargs(ValueType), + (ctx, args) => args.map(arg => toString(arg.evaluate(ctx))).join('') + ], + 'resolved-locale': [ + StringType, + [CollatorType], + (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale() + ] +}); +function stringifySignature(signature) { + if (Array.isArray(signature)) { + return `(${signature.map(toString$1).join(', ')})`; + } + else { + return `(${toString$1(signature.type)}...)`; + } +} +function isExpressionConstant(expression) { + if (expression instanceof Var) { + return isExpressionConstant(expression.boundExpression); + } + else if (expression instanceof CompoundExpression && expression.name === 'error') { + return false; + } + else if (expression instanceof CollatorExpression) { + // Although the results of a Collator expression with fixed arguments + // generally shouldn't change between executions, we can't serialize them + // as constant expressions because results change based on environment. + return false; + } + else if (expression instanceof Within) { + return false; + } + else if (expression instanceof Distance) { + return false; + } + const isTypeAnnotation = expression instanceof Coercion || + expression instanceof Assertion; + let childrenConstant = true; + expression.eachChild(child => { + // We can _almost_ assume that if `expressions` children are constant, + // they would already have been evaluated to Literal values when they + // were parsed. Type annotations are the exception, because they might + // have been inferred and added after a child was parsed. + // So we recurse into isConstant() for the children of type annotations, + // but otherwise simply check whether they are Literals. + if (isTypeAnnotation) { + childrenConstant = childrenConstant && isExpressionConstant(child); + } + else { + childrenConstant = childrenConstant && child instanceof Literal; + } + }); + if (!childrenConstant) { + return false; + } + return isFeatureConstant(expression) && + isGlobalPropertyConstant(expression, ['zoom', 'heatmap-density', 'line-progress', 'accumulated', 'is-supported-script']); +} +function isFeatureConstant(e) { + if (e instanceof CompoundExpression) { + if (e.name === 'get' && e.args.length === 1) { + return false; + } + else if (e.name === 'feature-state') { + return false; + } + else if (e.name === 'has' && e.args.length === 1) { + return false; + } + else if (e.name === 'properties' || + e.name === 'geometry-type' || + e.name === 'id') { + return false; + } + else if (/^filter-/.test(e.name)) { + return false; + } + } + if (e instanceof Within) { + return false; + } + if (e instanceof Distance) { + return false; + } + let result = true; + e.eachChild(arg => { + if (result && !isFeatureConstant(arg)) { + result = false; + } + }); + return result; +} +function isStateConstant(e) { + if (e instanceof CompoundExpression) { + if (e.name === 'feature-state') { + return false; + } + } + let result = true; + e.eachChild(arg => { + if (result && !isStateConstant(arg)) { + result = false; + } + }); + return result; +} +function isGlobalPropertyConstant(e, properties) { + if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) { + return false; + } + let result = true; + e.eachChild((arg) => { + if (result && !isGlobalPropertyConstant(arg, properties)) { + result = false; + } + }); + return result; +} + +function success(value) { + return { result: 'success', value }; +} +function error(value) { + return { result: 'error', value }; +} + +function supportsPropertyExpression(spec) { + return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-data-driven'; +} +function supportsZoomExpression(spec) { + return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1; +} +function supportsInterpolation(spec) { + return !!spec.expression && spec.expression.interpolated; +} + +function getType(val) { + if (val instanceof Number) { + return 'number'; + } + else if (val instanceof String) { + return 'string'; + } + else if (val instanceof Boolean) { + return 'boolean'; + } + else if (Array.isArray(val)) { + return 'array'; + } + else if (val === null) { + return 'null'; + } + else { + return typeof val; + } +} + +function isFunction$1(value) { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} +function identityFunction(x) { + return x; +} +function createFunction(parameters, propertySpec) { + const isColor = propertySpec.type === 'color'; + const zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object'; + const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + const zoomDependent = zoomAndFeatureDependent || !featureDependent; + const type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval'); + if (isColor || propertySpec.type === 'padding') { + const parseFn = isColor ? Color.parse : Padding.parse; + parameters = extendBy({}, parameters); + if (parameters.stops) { + parameters.stops = parameters.stops.map((stop) => { + return [stop[0], parseFn(stop[1])]; + }); + } + if (parameters.default) { + parameters.default = parseFn(parameters.default); + } + else { + parameters.default = parseFn(propertySpec.default); + } + } + if (parameters.colorSpace && !isSupportedInterpolationColorSpace(parameters.colorSpace)) { + throw new Error(`Unknown color space: "${parameters.colorSpace}"`); + } + let innerFun; + let hashedStops; + let categoricalKeyType; + if (type === 'exponential') { + innerFun = evaluateExponentialFunction; + } + else if (type === 'interval') { + innerFun = evaluateIntervalFunction; + } + else if (type === 'categorical') { + innerFun = evaluateCategoricalFunction; + // For categorical functions, generate an Object as a hashmap of the stops for fast searching + hashedStops = Object.create(null); + for (const stop of parameters.stops) { + hashedStops[stop[0]] = stop[1]; + } + // Infer key type based on first stop key-- used to encforce strict type checking later + categoricalKeyType = typeof parameters.stops[0][0]; + } + else if (type === 'identity') { + innerFun = evaluateIdentityFunction; + } + else { + throw new Error(`Unknown function type "${type}"`); + } + if (zoomAndFeatureDependent) { + const featureFunctions = {}; + const zoomStops = []; + for (let s = 0; s < parameters.stops.length; s++) { + const stop = parameters.stops[s]; + const zoom = stop[0].zoom; + if (featureFunctions[zoom] === undefined) { + featureFunctions[zoom] = { + zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default, + stops: [] + }; + zoomStops.push(zoom); + } + featureFunctions[zoom].stops.push([stop[0].value, stop[1]]); + } + const featureFunctionStops = []; + for (const z of zoomStops) { + featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]); + } + const interpolationType = { name: 'linear' }; + return { + kind: 'composite', + interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: featureFunctionStops.map(s => s[0]), + evaluate({ zoom }, properties) { + return evaluateExponentialFunction({ + stops: featureFunctionStops, + base: parameters.base + }, propertySpec, zoom).evaluate(zoom, properties); + } + }; + } + else if (zoomDependent) { + const interpolationType = type === 'exponential' ? + { name: 'exponential', base: parameters.base !== undefined ? parameters.base : 1 } : null; + return { + kind: 'camera', + interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: parameters.stops.map(s => s[0]), + evaluate: ({ zoom }) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType) + }; + } + else { + return { + kind: 'source', + evaluate(_, feature) { + const value = feature && feature.properties ? feature.properties[parameters.property] : undefined; + if (value === undefined) { + return coalesce$1(parameters.default, propertySpec.default); + } + return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType); + } + }; + } +} +function coalesce$1(a, b, c) { + if (a !== undefined) + return a; + if (b !== undefined) + return b; + if (c !== undefined) + return c; +} +function evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) { + const evaluated = typeof input === keyType ? hashedStops[input] : undefined; // Enforce strict typing on input + return coalesce$1(evaluated, parameters.default, propertySpec.default); +} +function evaluateIntervalFunction(parameters, propertySpec, input) { + // Edge cases + if (getType(input) !== 'number') + return coalesce$1(parameters.default, propertySpec.default); + const n = parameters.stops.length; + if (n === 1) + return parameters.stops[0][1]; + if (input <= parameters.stops[0][0]) + return parameters.stops[0][1]; + if (input >= parameters.stops[n - 1][0]) + return parameters.stops[n - 1][1]; + const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); + return parameters.stops[index][1]; +} +function evaluateExponentialFunction(parameters, propertySpec, input) { + const base = parameters.base !== undefined ? parameters.base : 1; + // Edge cases + if (getType(input) !== 'number') + return coalesce$1(parameters.default, propertySpec.default); + const n = parameters.stops.length; + if (n === 1) + return parameters.stops[0][1]; + if (input <= parameters.stops[0][0]) + return parameters.stops[0][1]; + if (input >= parameters.stops[n - 1][0]) + return parameters.stops[n - 1][1]; + const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); + const t = interpolationFactor(input, base, parameters.stops[index][0], parameters.stops[index + 1][0]); + const outputLower = parameters.stops[index][1]; + const outputUpper = parameters.stops[index + 1][1]; + const interp = interpolate[propertySpec.type] || identityFunction; + if (typeof outputLower.evaluate === 'function') { + return { + evaluate(...args) { + const evaluatedLower = outputLower.evaluate.apply(undefined, args); + const evaluatedUpper = outputUpper.evaluate.apply(undefined, args); + // Special case for fill-outline-color, which has no spec default. + if (evaluatedLower === undefined || evaluatedUpper === undefined) { + return undefined; + } + return interp(evaluatedLower, evaluatedUpper, t, parameters.colorSpace); + } + }; + } + return interp(outputLower, outputUpper, t, parameters.colorSpace); +} +function evaluateIdentityFunction(parameters, propertySpec, input) { + switch (propertySpec.type) { + case 'color': + input = Color.parse(input); + break; + case 'formatted': + input = Formatted.fromString(input.toString()); + break; + case 'resolvedImage': + input = ResolvedImage.fromString(input.toString()); + break; + case 'padding': + input = Padding.parse(input); + break; + default: + if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) { + input = undefined; + } + } + return coalesce$1(input, parameters.default, propertySpec.default); +} +/** + * Returns a ratio that can be used to interpolate between exponential function + * stops. + * + * 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, + * and `a` and `b` are constants affording sufficient degrees of freedom to fit + * the function to the given stops. + * + * Here's a bit of algebra that lets us compute `f(x)` directly from the stop + * values without explicitly solving for `a` and `b`: + * + * First stop value: `f(x0) = y0 = a * base^x0 + b` + * Second stop value: `f(x1) = y1 = a * base^x1 + b` + * => `y1 - y0 = a(base^x1 - base^x0)` + * => `a = (y1 - y0)/(base^x1 - base^x0)` + * + * Desired value: `f(x) = y = a * base^x + b` + * => `f(x) = y0 + a * (base^x - base^x0)` + * + * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a + * little algebra: + * ``` + * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) + * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) + * ``` + * + * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have + * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as + * an interpolation factor between the two stops' output values. + * + * (Note: a slightly different form for `ratio`, + * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer + * expensive `Math.pow()` operations.) + * + * @private + */ +function interpolationFactor(input, base, lowerValue, upperValue) { + const difference = upperValue - lowerValue; + const progress = input - lowerValue; + if (difference === 0) { + return 0; + } + else if (base === 1) { + return progress / difference; + } + else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} + +class StyleExpression { + constructor(expression, propertySpec) { + this.expression = expression; + this._warningHistory = {}; + this._evaluator = new EvaluationContext(); + this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null; + this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null; + } + evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + this._evaluator.globals = globals; + this._evaluator.feature = feature; + this._evaluator.featureState = featureState; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection; + return this.expression.evaluate(this._evaluator); + } + evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + this._evaluator.globals = globals; + this._evaluator.feature = feature || null; + this._evaluator.featureState = featureState || null; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection || null; + try { + const val = this.expression.evaluate(this._evaluator); + // eslint-disable-next-line no-self-compare + if (val === null || val === undefined || (typeof val === 'number' && val !== val)) { + return this._defaultValue; + } + if (this._enumValues && !(val in this._enumValues)) { + 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.`); + } + return val; + } + catch (e) { + if (!this._warningHistory[e.message]) { + this._warningHistory[e.message] = true; + if (typeof console !== 'undefined') { + console.warn(e.message); + } + } + return this._defaultValue; + } + } +} +function isExpression(expression) { + return Array.isArray(expression) && expression.length > 0 && + typeof expression[0] === 'string' && expression[0] in expressions$1; +} +/** + * Parse and typecheck the given style spec JSON expression. If + * options.defaultValue is provided, then the resulting StyleExpression's + * `evaluate()` method will handle errors by logging a warning (once per + * message) and returning the default value. Otherwise, it will throw + * evaluation errors. + * + * @private + */ +function createExpression(expression, propertySpec) { + const parser = new ParsingContext(expressions$1, isExpressionConstant, [], propertySpec ? getExpectedType(propertySpec) : undefined); + // For string-valued properties, coerce to string at the top level rather than asserting. + const parsed = parser.parse(expression, undefined, undefined, undefined, propertySpec && propertySpec.type === 'string' ? { typeAnnotation: 'coerce' } : undefined); + if (!parsed) { + return error(parser.errors); + } + return success(new StyleExpression(parsed, propertySpec)); +} +class ZoomConstantExpression { + constructor(kind, expression) { + this.kind = kind; + this._styleExpression = expression; + this.isStateDependent = kind !== 'constant' && !isStateConstant(expression.expression); + } + evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + } + evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + } +} +class ZoomDependentExpression { + constructor(kind, expression, zoomStops, interpolationType) { + this.kind = kind; + this.zoomStops = zoomStops; + this._styleExpression = expression; + this.isStateDependent = kind !== 'camera' && !isStateConstant(expression.expression); + this.interpolationType = interpolationType; + } + evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + } + evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + } + interpolationFactor(input, lower, upper) { + if (this.interpolationType) { + return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper); + } + else { + return 0; + } + } +} +function isZoomExpression(expression) { + return expression._styleExpression !== undefined; +} +function createPropertyExpression(expressionInput, propertySpec) { + const expression = createExpression(expressionInput, propertySpec); + if (expression.result === 'error') { + return expression; + } + const parsed = expression.value.expression; + const isFeatureConstantResult = isFeatureConstant(parsed); + if (!isFeatureConstantResult && !supportsPropertyExpression(propertySpec)) { + return error([new ExpressionParsingError('', 'data expressions not supported')]); + } + const isZoomConstant = isGlobalPropertyConstant(parsed, ['zoom']); + if (!isZoomConstant && !supportsZoomExpression(propertySpec)) { + return error([new ExpressionParsingError('', 'zoom expressions not supported')]); + } + const zoomCurve = findZoomCurve(parsed); + if (!zoomCurve && !isZoomConstant) { + return error([new ExpressionParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]); + } + else if (zoomCurve instanceof ExpressionParsingError) { + return error([zoomCurve]); + } + else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) { + return error([new ExpressionParsingError('', '"interpolate" expressions cannot be used with this property')]); + } + if (!zoomCurve) { + return success(isFeatureConstantResult ? + new ZoomConstantExpression('constant', expression.value) : + new ZoomConstantExpression('source', expression.value)); + } + const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined; + return success(isFeatureConstantResult ? + new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType) : + new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType)); +} +// serialization wrapper for old-style stop functions normalized to the +// expression interface +class StylePropertyFunction { + constructor(parameters, specification) { + this._parameters = parameters; + this._specification = specification; + extendBy(this, createFunction(this._parameters, this._specification)); + } + static deserialize(serialized) { + return new StylePropertyFunction(serialized._parameters, serialized._specification); + } + static serialize(input) { + return { + _parameters: input._parameters, + _specification: input._specification + }; + } +} +function normalizePropertyExpression(value, specification) { + if (isFunction$1(value)) { + return new StylePropertyFunction(value, specification); + } + else if (isExpression(value)) { + const expression = createPropertyExpression(value, specification); + if (expression.result === 'error') { + // this should have been caught in validation + throw new Error(expression.value.map(err => `${err.key}: ${err.message}`).join(', ')); + } + return expression.value; + } + else { + let constant = value; + if (specification.type === 'color' && typeof value === 'string') { + constant = Color.parse(value); + } + else if (specification.type === 'padding' && (typeof value === 'number' || Array.isArray(value))) { + constant = Padding.parse(value); + } + else if (specification.type === 'variableAnchorOffsetCollection' && Array.isArray(value)) { + constant = VariableAnchorOffsetCollection.parse(value); + } + return { + kind: 'constant', + evaluate: () => constant + }; + } +} +// Zoom-dependent expressions may only use ["zoom"] as the input to a top-level "step" or "interpolate" +// expression (collectively referred to as a "curve"). The curve may be wrapped in one or more "let" or +// "coalesce" expressions. +function findZoomCurve(expression) { + let result = null; + if (expression instanceof Let) { + result = findZoomCurve(expression.result); + } + else if (expression instanceof Coalesce) { + for (const arg of expression.args) { + result = findZoomCurve(arg); + if (result) { + break; + } + } + } + else if ((expression instanceof Step || expression instanceof Interpolate) && + expression.input instanceof CompoundExpression && + expression.input.name === 'zoom') { + result = expression; + } + if (result instanceof ExpressionParsingError) { + return result; + } + expression.eachChild((child) => { + const childResult = findZoomCurve(child); + if (childResult instanceof ExpressionParsingError) { + result = childResult; + } + else if (!result && childResult) { + result = new ExpressionParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'); + } + else if (result && childResult && result !== childResult) { + result = new ExpressionParsingError('', 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'); + } + }); + return result; +} +function getExpectedType(spec) { + const types = { + color: ColorType, + string: StringType, + number: NumberType, + enum: StringType, + boolean: BooleanType, + formatted: FormattedType, + padding: PaddingType, + resolvedImage: ResolvedImageType, + variableAnchorOffsetCollection: VariableAnchorOffsetCollectionType + }; + if (spec.type === 'array') { + return array$1(types[spec.value] || ValueType, spec.length); + } + return types[spec.type]; +} +function getDefaultValue(spec) { + if (spec.type === 'color' && isFunction$1(spec.default)) { + // Special case for heatmap-color: it uses the 'default:' to define a + // default color ramp, but createExpression expects a simple value to fall + // back to in case of runtime errors + return new Color(0, 0, 0, 0); + } + else if (spec.type === 'color') { + return Color.parse(spec.default) || null; + } + else if (spec.type === 'padding') { + return Padding.parse(spec.default) || null; + } + else if (spec.type === 'variableAnchorOffsetCollection') { + return VariableAnchorOffsetCollection.parse(spec.default) || null; + } + else if (spec.default === undefined) { + return null; + } + else { + return spec.default; + } +} + +function isExpressionFilter(filter) { + if (filter === true || filter === false) { + return true; + } + if (!Array.isArray(filter) || filter.length === 0) { + return false; + } + switch (filter[0]) { + case 'has': + return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type'; + case 'in': + return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2])); + case '!in': + case '!has': + case 'none': + return false; + case '==': + case '!=': + case '>': + case '>=': + case '<': + case '<=': + return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2])); + case 'any': + case 'all': + for (const f of filter.slice(1)) { + if (!isExpressionFilter(f) && typeof f !== 'boolean') { + return false; + } + } + return true; + default: + return true; + } +} +const filterSpec = { + 'type': 'boolean', + 'default': false, + 'transition': false, + 'property-type': 'data-driven', + 'expression': { + 'interpolated': false, + 'parameters': ['zoom', 'feature'] + } +}; +/** + * Given a filter expressed as nested arrays, return a new function + * that evaluates whether a given feature (with a .properties or .tags property) + * passes its test. + * + * @private + * @param {Array} filter MapLibre filter + * @returns {Function} filter-evaluating function + */ +function createFilter(filter) { + if (filter === null || filter === undefined) { + return { filter: () => true, needGeometry: false }; + } + if (!isExpressionFilter(filter)) { + filter = convertFilter$1(filter); + } + const compiled = createExpression(filter, filterSpec); + if (compiled.result === 'error') { + throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', ')); + } + else { + const needGeometry = geometryNeeded(filter); + return { filter: (globalProperties, feature, canonical) => compiled.value.evaluate(globalProperties, feature, {}, canonical), + needGeometry }; + } +} +// Comparison function to sort numbers and strings +function compare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} +function geometryNeeded(filter) { + if (!Array.isArray(filter)) + return false; + if (filter[0] === 'within' || filter[0] === 'distance') + return true; + for (let index = 1; index < filter.length; index++) { + if (geometryNeeded(filter[index])) + return true; + } + return false; +} +function convertFilter$1(filter) { + if (!filter) + return true; + const op = filter[0]; + if (filter.length <= 1) + return (op !== 'any'); + const converted = op === '==' ? convertComparisonOp$1(filter[1], filter[2], '==') : + op === '!=' ? convertNegation(convertComparisonOp$1(filter[1], filter[2], '==')) : + op === '<' || + op === '>' || + op === '<=' || + op === '>=' ? convertComparisonOp$1(filter[1], filter[2], op) : + op === 'any' ? convertDisjunctionOp(filter.slice(1)) : + op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter$1)) : + op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter$1).map(convertNegation)) : + op === 'in' ? convertInOp$1(filter[1], filter.slice(2)) : + op === '!in' ? convertNegation(convertInOp$1(filter[1], filter.slice(2))) : + op === 'has' ? convertHasOp$1(filter[1]) : + op === '!has' ? convertNegation(convertHasOp$1(filter[1])) : + true; + return converted; +} +function convertComparisonOp$1(property, value, op) { + switch (property) { + case '$type': + return [`filter-type-${op}`, value]; + case '$id': + return [`filter-id-${op}`, value]; + default: + return [`filter-${op}`, property, value]; + } +} +function convertDisjunctionOp(filters) { + return ['any'].concat(filters.map(convertFilter$1)); +} +function convertInOp$1(property, values) { + if (values.length === 0) { + return false; + } + switch (property) { + case '$type': + return ['filter-type-in', ['literal', values]]; + case '$id': + return ['filter-id-in', ['literal', values]]; + default: + if (values.length > 200 && !values.some(v => typeof v !== typeof values[0])) { + return ['filter-in-large', property, ['literal', values.sort(compare)]]; + } + else { + return ['filter-in-small', property, ['literal', values]]; + } + } +} +function convertHasOp$1(property) { + switch (property) { + case '$type': + return true; + case '$id': + return ['filter-has-id']; + default: + return ['filter-has', property]; + } +} +function convertNegation(filter) { + return ['!', filter]; +} + +/* + * Convert the given filter to an expression, storing the expected types for + * any feature properties referenced in expectedTypes. + * + * These expected types are needed in order to construct preflight type checks + * needed for handling 'any' filters. A preflight type check is necessary in + * order to mimic legacy filters' semantics around expected type mismatches. + * For example, consider the legacy filter: + * + * ["any", ["all", [">", "y", 0], [">", "y", 0]], [">", "x", 0]] + * + * Naively, we might convert this to the expression: + * + * ["any", ["all", [">", ["get", "y"], 0], [">", ["get", "z"], 0]], [">", ["get", "x"], 0]] + * + * But if we tried to evaluate this against, say `{x: 1, y: null, z: 0}`, the + * [">", ["get", "y"], 0] would cause an evaluation error, leading to the + * entire filter returning false. Legacy filter semantics, though, ask for + * [">", "y", 0] to simply return `false` when `y` is of the wrong type, + * allowing the subsequent terms of the outer "any" expression to be evaluated + * (resulting, in this case, in a `true` value, because x > 0). + * + * We account for this by inserting a preflight type-checking expression before + * each "any" term, allowing us to avoid evaluating the actual converted filter + * if any type mismatches would cause it to produce an evalaution error: + * + * ["any", + * ["case", + * ["all", ["==", ["typeof", ["get", "y"]], "number"], ["==", ["typeof", ["get", "z"], "number]], + * ["all", [">", ["get", "y"], 0], [">", ["get", "z"], 0]], + * false + * ], + * ["case", + * ["==", ["typeof", ["get", "x"], "number"]], + * [">", ["get", "x"], 0], + * false + * ] + * ] + * + * An alternative, possibly more direct approach would be to use type checks + * in the conversion of each comparison operator, so that the converted version + * of each individual ==, >=, etc. would mimic the legacy filter semantics. The + * downside of this approach is that it can lead to many more type checks than + * would otherwise be necessary: outside the context of an "any" expression, + * bailing out due to a runtime type error (expression semantics) and returning + * false (legacy filter semantics) are equivalent: they cause the filter to + * produce a `false` result. + */ +function convertFilter(filter, expectedTypes = {}) { + if (isExpressionFilter(filter)) + return filter; + if (!filter) + return true; + const legacyFilter = filter; + const legacyOp = legacyFilter[0]; + if (filter.length <= 1) + return (legacyOp !== 'any'); + switch (legacyOp) { + case '==': + case '!=': + case '<': + case '>': + case '<=': + case '>=': { + const [, property, value] = filter; + return convertComparisonOp(property, value, legacyOp, expectedTypes); + } + case 'any': { + const [, ...conditions] = legacyFilter; + const children = conditions.map((f) => { + const types = {}; + const child = convertFilter(f, types); + const typechecks = runtimeTypeChecks(types); + return typechecks === true ? child : ['case', typechecks, child, false]; + }); + return ['any', ...children]; + } + case 'all': { + const [, ...conditions] = legacyFilter; + const children = conditions.map(f => convertFilter(f, expectedTypes)); + return children.length > 1 ? ['all', ...children] : children[0]; + } + case 'none': { + const [, ...conditions] = legacyFilter; + return ['!', convertFilter(['any', ...conditions], {})]; + } + case 'in': { + const [, property, ...values] = legacyFilter; + return convertInOp(property, values); + } + case '!in': { + const [, property, ...values] = legacyFilter; + return convertInOp(property, values, true); + } + case 'has': + return convertHasOp(legacyFilter[1]); + case '!has': + return ['!', convertHasOp(legacyFilter[1])]; + default: + return true; + } +} +// Given a set of feature properties and an expected type for each one, +// construct an boolean expression that tests whether each property has the +// right type. +// E.g.: for {name: 'string', population: 'number'}, return +// [ 'all', +// ['==', ['typeof', ['get', 'name'], 'string']], +// ['==', ['typeof', ['get', 'population'], 'number]] +// ] +function runtimeTypeChecks(expectedTypes) { + const conditions = []; + for (const property in expectedTypes) { + const get = property === '$id' ? ['id'] : ['get', property]; + conditions.push(['==', ['typeof', get], expectedTypes[property]]); + } + if (conditions.length === 0) + return true; + if (conditions.length === 1) + return conditions[0]; + return ['all', ...conditions]; +} +function convertComparisonOp(property, value, op, expectedTypes) { + let get; + if (property === '$type') { + return [op, ['geometry-type'], value]; + } + else if (property === '$id') { + get = ['id']; + } + else { + get = ['get', property]; + } + if (expectedTypes && value !== null) { + const type = typeof value; + expectedTypes[property] = type; + } + if (op === '==' && property !== '$id' && value === null) { + return [ + 'all', + ['has', property], // missing property != null for legacy filters + ['==', get, null] + ]; + } + else if (op === '!=' && property !== '$id' && value === null) { + return [ + 'any', + ['!', ['has', property]], // missing property != null for legacy filters + ['!=', get, null] + ]; + } + return [op, get, value]; +} +function convertInOp(property, values, negate = false) { + if (values.length === 0) + return negate; + let get; + if (property === '$type') { + get = ['geometry-type']; + } + else if (property === '$id') { + get = ['id']; + } + else { + get = ['get', property]; + } + // Determine if the list of values to be searched is homogenously typed. + // If so (and if the type is string or number), then we can use a + // [match, input, [...values], true, false] construction rather than a + // bunch of `==` tests. + let uniformTypes = true; + const type = typeof values[0]; + for (const value of values) { + if (typeof value !== type) { + uniformTypes = false; + break; + } + } + if (uniformTypes && (type === 'string' || type === 'number')) { + // Match expressions must have unique values. + const uniqueValues = values.sort().filter((v, i) => i === 0 || values[i - 1] !== v); + return ['match', get, uniqueValues, !negate, negate]; + } + if (negate) { + return ['all', ...values.map(v => ['!=', get, v])]; + } + else { + return ['any', ...values.map(v => ['==', get, v])]; + } +} +function convertHasOp(property) { + if (property === '$type') { + return true; + } + else if (property === '$id') { + return ['!=', ['id'], null]; + } + else { + return ['has', property]; + } +} + +function convertLiteral(value) { + return typeof value === 'object' ? ['literal', value] : value; +} +function convertFunction(parameters, propertySpec) { + let stops = parameters.stops; + if (!stops) { + // identity function + return convertIdentityFunction(parameters, propertySpec); + } + const zoomAndFeatureDependent = stops && typeof stops[0][0] === 'object'; + const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + const zoomDependent = zoomAndFeatureDependent || !featureDependent; + stops = stops.map((stop) => { + if (!featureDependent && propertySpec.tokens && typeof stop[1] === 'string') { + return [stop[0], convertTokenString(stop[1])]; + } + return [stop[0], convertLiteral(stop[1])]; + }); + if (zoomAndFeatureDependent) { + return convertZoomAndPropertyFunction(parameters, propertySpec, stops); + } + else if (zoomDependent) { + return convertZoomFunction(parameters, propertySpec, stops); + } + else { + return convertPropertyFunction(parameters, propertySpec, stops); + } +} +function convertIdentityFunction(parameters, propertySpec) { + const get = ['get', parameters.property]; + if (parameters.default === undefined) { + // By default, expressions for string-valued properties get coerced. To preserve + // legacy function semantics, insert an explicit assertion instead. + return propertySpec.type === 'string' ? ['string', get] : get; + } + else if (propertySpec.type === 'enum') { + return [ + 'match', + get, + Object.keys(propertySpec.values), + get, + parameters.default + ]; + } + else { + const expression = [propertySpec.type === 'color' ? 'to-color' : propertySpec.type, get, convertLiteral(parameters.default)]; + if (propertySpec.type === 'array') { + expression.splice(1, 0, propertySpec.value, propertySpec.length || null); + } + return expression; + } +} +function getInterpolateOperator(parameters) { + switch (parameters.colorSpace) { + case 'hcl': return 'interpolate-hcl'; + case 'lab': return 'interpolate-lab'; + default: return 'interpolate'; + } +} +function convertZoomAndPropertyFunction(parameters, propertySpec, stops) { + const featureFunctionParameters = {}; + const featureFunctionStops = {}; + const zoomStops = []; + for (let s = 0; s < stops.length; s++) { + const stop = stops[s]; + const zoom = stop[0].zoom; + if (featureFunctionParameters[zoom] === undefined) { + featureFunctionParameters[zoom] = { + zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default, + }; + featureFunctionStops[zoom] = []; + zoomStops.push(zoom); + } + featureFunctionStops[zoom].push([stop[0].value, stop[1]]); + } + // the interpolation type for the zoom dimension of a zoom-and-property + // function is determined directly from the style property specification + // for which it's being used: linear for interpolatable properties, step + // otherwise. + const functionType = getFunctionType({}, propertySpec); + if (functionType === 'exponential') { + const expression = [getInterpolateOperator(parameters), ['linear'], ['zoom']]; + for (const z of zoomStops) { + const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]); + appendStopPair(expression, z, output, false); + } + return expression; + } + else { + const expression = ['step', ['zoom']]; + for (const z of zoomStops) { + const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]); + appendStopPair(expression, z, output, true); + } + fixupDegenerateStepCurve(expression); + return expression; + } +} +function coalesce(a, b) { + if (a !== undefined) + return a; + if (b !== undefined) + return b; +} +function getFallback(parameters, propertySpec) { + const defaultValue = convertLiteral(coalesce(parameters.default, propertySpec.default)); + /* + * Some fields with type: resolvedImage have an undefined default. + * Because undefined is an invalid value for resolvedImage, set fallback to + * an empty string instead of undefined to ensure output + * passes validation. + */ + if (defaultValue === undefined && propertySpec.type === 'resolvedImage') { + return ''; + } + return defaultValue; +} +function convertPropertyFunction(parameters, propertySpec, stops) { + const type = getFunctionType(parameters, propertySpec); + const get = ['get', parameters.property]; + if (type === 'categorical' && typeof stops[0][0] === 'boolean') { + const expression = ['case']; + for (const stop of stops) { + expression.push(['==', get, stop[0]], stop[1]); + } + expression.push(getFallback(parameters, propertySpec)); + return expression; + } + else if (type === 'categorical') { + const expression = ['match', get]; + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], false); + } + expression.push(getFallback(parameters, propertySpec)); + return expression; + } + else if (type === 'interval') { + const expression = ['step', ['number', get]]; + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], true); + } + fixupDegenerateStepCurve(expression); + return parameters.default === undefined ? expression : [ + 'case', + ['==', ['typeof', get], 'number'], + expression, + convertLiteral(parameters.default) + ]; + } + else if (type === 'exponential') { + const base = parameters.base !== undefined ? parameters.base : 1; + const expression = [ + getInterpolateOperator(parameters), + base === 1 ? ['linear'] : ['exponential', base], + ['number', get] + ]; + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], false); + } + return parameters.default === undefined ? expression : [ + 'case', + ['==', ['typeof', get], 'number'], + expression, + convertLiteral(parameters.default) + ]; + } + else { + throw new Error(`Unknown property function type ${type}`); + } +} +function convertZoomFunction(parameters, propertySpec, stops, input = ['zoom']) { + const type = getFunctionType(parameters, propertySpec); + let expression; + let isStep = false; + if (type === 'interval') { + expression = ['step', input]; + isStep = true; + } + else if (type === 'exponential') { + const base = parameters.base !== undefined ? parameters.base : 1; + expression = [getInterpolateOperator(parameters), base === 1 ? ['linear'] : ['exponential', base], input]; + } + else { + throw new Error(`Unknown zoom function type "${type}"`); + } + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], isStep); + } + fixupDegenerateStepCurve(expression); + return expression; +} +function fixupDegenerateStepCurve(expression) { + // degenerate step curve (i.e. a constant function): add a noop stop + if (expression[0] === 'step' && expression.length === 3) { + expression.push(0); + expression.push(expression[3]); + } +} +function appendStopPair(curve, input, output, isStep) { + // Skip duplicate stop values. They were not validated for functions, but they are for expressions. + // https://github.com/mapbox/mapbox-gl-js/issues/4107 + if (curve.length > 3 && input === curve[curve.length - 2]) { + return; + } + // step curves don't get the first input value, as it is redundant. + if (!(isStep && curve.length === 2)) { + curve.push(input); + } + curve.push(output); +} +function getFunctionType(parameters, propertySpec) { + if (parameters.type) { + return parameters.type; + } + else { + return propertySpec.expression.interpolated ? 'exponential' : 'interval'; + } +} +// "String with {name} token" => ["concat", "String with ", ["get", "name"], " token"] +function convertTokenString(s) { + const result = ['concat']; + const re = /{([^{}]+)}/g; + let pos = 0; + for (let match = re.exec(s); match !== null; match = re.exec(s)) { + const literal = s.slice(pos, re.lastIndex - match[0].length); + pos = re.lastIndex; + if (literal.length > 0) + result.push(literal); + result.push(['get', match[1]]); + } + if (result.length === 1) { + return s; + } + if (pos < s.length) { + result.push(s.slice(pos)); + } + else if (result.length === 2) { + return ['to-string', result[1]]; + } + return result; +} + +function getPropertyReference(propertyName) { + for (let i = 0; i < v8Spec.layout.length; i++) { + for (const key in v8Spec[v8Spec.layout[i]]) { + if (key === propertyName) + return v8Spec[v8Spec.layout[i]][key]; + } + } + for (let i = 0; i < v8Spec.paint.length; i++) { + for (const key in v8Spec[v8Spec.paint[i]]) { + if (key === propertyName) + return v8Spec[v8Spec.paint[i]][key]; + } + } + return null; +} +function eachSource(style, callback) { + for (const k in style.sources) { + callback(style.sources[k]); + } +} +function eachLayer(style, callback) { + for (const layer of style.layers) { + callback(layer); + } +} +function eachProperty(style, options, callback) { + function inner(layer, propertyType) { + const properties = layer[propertyType]; + if (!properties) + return; + Object.keys(properties).forEach((key) => { + callback({ + path: [layer.id, propertyType, key], + key, + value: properties[key], + reference: getPropertyReference(key), + set(x) { + properties[key] = x; + } + }); + }); + } + eachLayer(style, (layer) => { + if (options.paint) { + inner(layer, 'paint'); + } + if (options.layout) { + inner(layer, 'layout'); + } + }); +} + +function stringify$1(obj) { + const type = typeof obj; + if (type === 'number' || type === 'boolean' || type === 'string' || obj === undefined || obj === null) + return JSON.stringify(obj); + if (Array.isArray(obj)) { + let str = '['; + for (const val of obj) { + str += `${stringify$1(val)},`; + } + return `${str}]`; + } + const keys = Object.keys(obj).sort(); + let str = '{'; + for (let i = 0; i < keys.length; i++) { + str += `${JSON.stringify(keys[i])}:${stringify$1(obj[keys[i]])},`; + } + return `${str}}`; +} +function getKey(layer) { + let key = ''; + for (const k of refProperties) { + key += `/${stringify$1(layer[k])}`; + } + return key; +} +/** + * Given an array of layers, return an array of arrays of layers where all + * layers in each group have identical layout-affecting properties. These + * are the properties that were formerly used by explicit `ref` mechanism + * for layers: 'type', 'source', 'source-layer', 'minzoom', 'maxzoom', + * 'filter', and 'layout'. + * + * The input is not modified. The output layers are references to the + * input layers. + * + * @private + * @param {Array} layers + * @param {Object} [cachedKeys] - an object to keep already calculated keys. + * @returns {Array>} + */ +function groupByLayout(layers, cachedKeys) { + const groups = {}; + for (let i = 0; i < layers.length; i++) { + const k = (cachedKeys && cachedKeys[layers[i].id]) || getKey(layers[i]); + // update the cache if there is one + if (cachedKeys) + cachedKeys[layers[i].id] = k; + let group = groups[k]; + if (!group) { + group = groups[k] = []; + } + group.push(layers[i]); + } + const result = []; + for (const k in groups) { + result.push(groups[k]); + } + return result; +} + +function emptyStyle() { + const style = {}; + const version = v8Spec['$version']; + for (const styleKey in v8Spec['$root']) { + const spec = v8Spec['$root'][styleKey]; + if (spec.required) { + let value = null; + if (styleKey === 'version') { + value = version; + } + else { + if (spec.type === 'array') { + value = []; + } + else { + value = {}; + } + } + if (value != null) { + style[styleKey] = value; + } + } + } + return style; +} + +function validateConstants(options) { + const key = options.key; + const constants = options.value; + if (constants) { + return [new ValidationError(key, constants, 'constants have been deprecated as of v8')]; + } + else { + return []; + } +} + +// Turn jsonlint-lines-primitives objects into primitive objects +function unbundle(value) { + if (value instanceof Number || value instanceof String || value instanceof Boolean) { + return value.valueOf(); + } + else { + return value; + } +} +function deepUnbundle(value) { + if (Array.isArray(value)) { + return value.map(deepUnbundle); + } + else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) { + const unbundledValue = {}; + for (const key in value) { + unbundledValue[key] = deepUnbundle(value[key]); + } + return unbundledValue; + } + return unbundle(value); +} + +function validateObject(options) { + const key = options.key; + const object = options.value; + const elementSpecs = options.valueSpec || {}; + const elementValidators = options.objectElementValidators || {}; + const style = options.style; + const styleSpec = options.styleSpec; + const validateSpec = options.validateSpec; + let errors = []; + const type = getType(object); + if (type !== 'object') { + return [new ValidationError(key, object, `object expected, ${type} found`)]; + } + for (const objectKey in object) { + const elementSpecKey = objectKey.split('.')[0]; // treat 'paint.*' as 'paint' + const elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*']; + let validateElement; + if (elementValidators[elementSpecKey]) { + validateElement = elementValidators[elementSpecKey]; + } + else if (elementSpecs[elementSpecKey]) { + validateElement = validateSpec; + } + else if (elementValidators['*']) { + validateElement = elementValidators['*']; + } + else if (elementSpecs['*']) { + validateElement = validateSpec; + } + else { + errors.push(new ValidationError(key, object[objectKey], `unknown property "${objectKey}"`)); + continue; + } + errors = errors.concat(validateElement({ + key: (key ? `${key}.` : key) + objectKey, + value: object[objectKey], + valueSpec: elementSpec, + style, + styleSpec, + object, + objectKey, + validateSpec, + }, object)); + } + for (const elementSpecKey in elementSpecs) { + // Don't check `required` when there's a custom validator for that property. + if (elementValidators[elementSpecKey]) { + continue; + } + if (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey]['default'] === undefined && object[elementSpecKey] === undefined) { + errors.push(new ValidationError(key, object, `missing required property "${elementSpecKey}"`)); + } + } + return errors; +} + +function validateArray(options) { + const array = options.value; + const arraySpec = options.valueSpec; + const validateSpec = options.validateSpec; + const style = options.style; + const styleSpec = options.styleSpec; + const key = options.key; + const validateArrayElement = options.arrayElementValidator || validateSpec; + if (getType(array) !== 'array') { + return [new ValidationError(key, array, `array expected, ${getType(array)} found`)]; + } + if (arraySpec.length && array.length !== arraySpec.length) { + return [new ValidationError(key, array, `array length ${arraySpec.length} expected, length ${array.length} found`)]; + } + if (arraySpec['min-length'] && array.length < arraySpec['min-length']) { + return [new ValidationError(key, array, `array length at least ${arraySpec['min-length']} expected, length ${array.length} found`)]; + } + let arrayElementSpec = { + 'type': arraySpec.value, + 'values': arraySpec.values + }; + if (styleSpec.$version < 7) { + arrayElementSpec['function'] = arraySpec.function; + } + if (getType(arraySpec.value) === 'object') { + arrayElementSpec = arraySpec.value; + } + let errors = []; + for (let i = 0; i < array.length; i++) { + errors = errors.concat(validateArrayElement({ + array, + arrayIndex: i, + value: array[i], + valueSpec: arrayElementSpec, + validateSpec: options.validateSpec, + style, + styleSpec, + key: `${key}[${i}]` + })); + } + return errors; +} + +function validateNumber(options) { + const key = options.key; + const value = options.value; + const valueSpec = options.valueSpec; + let type = getType(value); + // eslint-disable-next-line no-self-compare + if (type === 'number' && value !== value) { + type = 'NaN'; + } + if (type !== 'number') { + return [new ValidationError(key, value, `number expected, ${type} found`)]; + } + if ('minimum' in valueSpec && value < valueSpec.minimum) { + return [new ValidationError(key, value, `${value} is less than the minimum value ${valueSpec.minimum}`)]; + } + if ('maximum' in valueSpec && value > valueSpec.maximum) { + return [new ValidationError(key, value, `${value} is greater than the maximum value ${valueSpec.maximum}`)]; + } + return []; +} + +function validateFunction(options) { + const functionValueSpec = options.valueSpec; + const functionType = unbundle(options.value.type); + let stopKeyType; + let stopDomainValues = {}; + let previousStopDomainValue; + let previousStopDomainZoom; + const isZoomFunction = functionType !== 'categorical' && options.value.property === undefined; + const isPropertyFunction = !isZoomFunction; + const isZoomAndPropertyFunction = getType(options.value.stops) === 'array' && + getType(options.value.stops[0]) === 'array' && + getType(options.value.stops[0][0]) === 'object'; + const errors = validateObject({ + key: options.key, + value: options.value, + valueSpec: options.styleSpec.function, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + stops: validateFunctionStops, + default: validateFunctionDefault + } + }); + if (functionType === 'identity' && isZoomFunction) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "property"')); + } + if (functionType !== 'identity' && !options.value.stops) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "stops"')); + } + if (functionType === 'exponential' && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'exponential functions not supported')); + } + if (options.styleSpec.$version >= 8) { + if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'property functions not supported')); + } + else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported')); + } + } + if ((functionType === 'categorical' || isZoomAndPropertyFunction) && options.value.property === undefined) { + errors.push(new ValidationError(options.key, options.value, '"property" property is required')); + } + return errors; + function validateFunctionStops(options) { + if (functionType === 'identity') { + return [new ValidationError(options.key, options.value, 'identity function may not have a "stops" property')]; + } + let errors = []; + const value = options.value; + errors = errors.concat(validateArray({ + key: options.key, + value, + valueSpec: options.valueSpec, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec, + arrayElementValidator: validateFunctionStop + })); + if (getType(value) === 'array' && value.length === 0) { + errors.push(new ValidationError(options.key, value, 'array must have at least one stop')); + } + return errors; + } + function validateFunctionStop(options) { + let errors = []; + const value = options.value; + const key = options.key; + if (getType(value) !== 'array') { + return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; + } + if (value.length !== 2) { + return [new ValidationError(key, value, `array length 2 expected, length ${value.length} found`)]; + } + if (isZoomAndPropertyFunction) { + if (getType(value[0]) !== 'object') { + return [new ValidationError(key, value, `object expected, ${getType(value[0])} found`)]; + } + if (value[0].zoom === undefined) { + return [new ValidationError(key, value, 'object stop key must have zoom')]; + } + if (value[0].value === undefined) { + return [new ValidationError(key, value, 'object stop key must have value')]; + } + if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) { + return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')]; + } + if (unbundle(value[0].zoom) !== previousStopDomainZoom) { + previousStopDomainZoom = unbundle(value[0].zoom); + previousStopDomainValue = undefined; + stopDomainValues = {}; + } + errors = errors.concat(validateObject({ + key: `${key}[0]`, + value: value[0], + valueSpec: { zoom: {} }, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { zoom: validateNumber, value: validateStopDomainValue } + })); + } + else { + errors = errors.concat(validateStopDomainValue({ + key: `${key}[0]`, + value: value[0], + valueSpec: {}, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec + }, value)); + } + if (isExpression(deepUnbundle(value[1]))) { + return errors.concat([new ValidationError(`${key}[1]`, value[1], 'expressions are not allowed in function stops.')]); + } + return errors.concat(options.validateSpec({ + key: `${key}[1]`, + value: value[1], + valueSpec: functionValueSpec, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec + })); + } + function validateStopDomainValue(options, stop) { + const type = getType(options.value); + const value = unbundle(options.value); + const reportValue = options.value !== null ? options.value : stop; + if (!stopKeyType) { + stopKeyType = type; + } + else if (type !== stopKeyType) { + return [new ValidationError(options.key, reportValue, `${type} stop domain type must match previous stop domain type ${stopKeyType}`)]; + } + if (type !== 'number' && type !== 'string' && type !== 'boolean') { + return [new ValidationError(options.key, reportValue, 'stop domain value must be a number, string, or boolean')]; + } + if (type !== 'number' && functionType !== 'categorical') { + let message = `number expected, ${type} found`; + if (supportsPropertyExpression(functionValueSpec) && functionType === undefined) { + message += '\nIf you intended to use a categorical function, specify `"type": "categorical"`.'; + } + return [new ValidationError(options.key, reportValue, message)]; + } + if (functionType === 'categorical' && type === 'number' && (!isFinite(value) || Math.floor(value) !== value)) { + return [new ValidationError(options.key, reportValue, `integer expected, found ${value}`)]; + } + if (functionType !== 'categorical' && type === 'number' && previousStopDomainValue !== undefined && value < previousStopDomainValue) { + return [new ValidationError(options.key, reportValue, 'stop domain values must appear in ascending order')]; + } + else { + previousStopDomainValue = value; + } + if (functionType === 'categorical' && value in stopDomainValues) { + return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')]; + } + else { + stopDomainValues[value] = true; + } + return []; + } + function validateFunctionDefault(options) { + return options.validateSpec({ + key: options.key, + value: options.value, + valueSpec: functionValueSpec, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec + }); + } +} + +function validateExpression(options) { + const expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec); + if (expression.result === 'error') { + return expression.value.map((error) => { + return new ValidationError(`${options.key}${error.key}`, options.value, error.message); + }); + } + const expressionObj = expression.value.expression || expression.value._styleExpression.expression; + if (options.expressionContext === 'property' && (options.propertyKey === 'text-font') && + !expressionObj.outputDefined()) { + return [new ValidationError(options.key, options.value, `Invalid data expression for "${options.propertyKey}". Output values must be contained as literals within the expression.`)]; + } + if (options.expressionContext === 'property' && options.propertyType === 'layout' && + (!isStateConstant(expressionObj))) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with layout properties.')]; + } + if (options.expressionContext === 'filter' && !isStateConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with filters.')]; + } + if (options.expressionContext && options.expressionContext.indexOf('cluster') === 0) { + if (!isGlobalPropertyConstant(expressionObj, ['zoom', 'feature-state'])) { + return [new ValidationError(options.key, options.value, '"zoom" and "feature-state" expressions are not supported with cluster properties.')]; + } + if (options.expressionContext === 'cluster-initial' && !isFeatureConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')]; + } + } + return []; +} + +function validateBoolean(options) { + const value = options.value; + const key = options.key; + const type = getType(value); + if (type !== 'boolean') { + return [new ValidationError(key, value, `boolean expected, ${type} found`)]; + } + return []; +} + +function validateColor(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + if (type !== 'string') { + return [new ValidationError(key, value, `color expected, ${type} found`)]; + } + if (!Color.parse(String(value))) { // cast String object to string primitive + return [new ValidationError(key, value, `color expected, "${value}" found`)]; + } + return []; +} + +function validateEnum(options) { + const key = options.key; + const value = options.value; + const valueSpec = options.valueSpec; + const errors = []; + if (Array.isArray(valueSpec.values)) { // <=v7 + if (valueSpec.values.indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, `expected one of [${valueSpec.values.join(', ')}], ${JSON.stringify(value)} found`)); + } + } + else { // >=v8 + if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, `expected one of [${Object.keys(valueSpec.values).join(', ')}], ${JSON.stringify(value)} found`)); + } + } + return errors; +} + +function validateFilter$1(options) { + if (isExpressionFilter(deepUnbundle(options.value))) { + return validateExpression(extendBy({}, options, { + expressionContext: 'filter', + valueSpec: { value: 'boolean' } + })); + } + else { + return validateNonExpressionFilter(options); + } +} +function validateNonExpressionFilter(options) { + const value = options.value; + const key = options.key; + if (getType(value) !== 'array') { + return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; + } + const styleSpec = options.styleSpec; + let type; + let errors = []; + if (value.length < 1) { + return [new ValidationError(key, value, 'filter array must have at least 1 element')]; + } + errors = errors.concat(validateEnum({ + key: `${key}[0]`, + value: value[0], + valueSpec: styleSpec.filter_operator, + style: options.style, + styleSpec: options.styleSpec + })); + switch (unbundle(value[0])) { + case '<': + case '<=': + case '>': + case '>=': + if (value.length >= 2 && unbundle(value[1]) === '$type') { + errors.push(new ValidationError(key, value, `"$type" cannot be use with operator "${value[0]}"`)); + } + /* falls through */ + case '==': + case '!=': + if (value.length !== 3) { + errors.push(new ValidationError(key, value, `filter array for operator "${value[0]}" must have 3 elements`)); + } + /* falls through */ + case 'in': + case '!in': + if (value.length >= 2) { + type = getType(value[1]); + if (type !== 'string') { + errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); + } + } + for (let i = 2; i < value.length; i++) { + type = getType(value[i]); + if (unbundle(value[1]) === '$type') { + errors = errors.concat(validateEnum({ + key: `${key}[${i}]`, + value: value[i], + valueSpec: styleSpec.geometry_type, + style: options.style, + styleSpec: options.styleSpec + })); + } + else if (type !== 'string' && type !== 'number' && type !== 'boolean') { + errors.push(new ValidationError(`${key}[${i}]`, value[i], `string, number, or boolean expected, ${type} found`)); + } + } + break; + case 'any': + case 'all': + case 'none': + for (let i = 1; i < value.length; i++) { + errors = errors.concat(validateNonExpressionFilter({ + key: `${key}[${i}]`, + value: value[i], + style: options.style, + styleSpec: options.styleSpec + })); + } + break; + case 'has': + case '!has': + type = getType(value[1]); + if (value.length !== 2) { + errors.push(new ValidationError(key, value, `filter array for "${value[0]}" operator must have 2 elements`)); + } + else if (type !== 'string') { + errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); + } + break; + } + return errors; +} + +function validateProperty(options, propertyType) { + const key = options.key; + const validateSpec = options.validateSpec; + const style = options.style; + const styleSpec = options.styleSpec; + const value = options.value; + const propertyKey = options.objectKey; + const layerSpec = styleSpec[`${propertyType}_${options.layerType}`]; + if (!layerSpec) + return []; + const transitionMatch = propertyKey.match(/^(.*)-transition$/); + if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) { + return validateSpec({ + key, + value, + valueSpec: styleSpec.transition, + style, + styleSpec + }); + } + const valueSpec = options.valueSpec || layerSpec[propertyKey]; + if (!valueSpec) { + return [new ValidationError(key, value, `unknown property "${propertyKey}"`)]; + } + let tokenMatch; + if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) { + return [new ValidationError(key, value, `"${propertyKey}" does not support interpolation syntax\n` + + `Use an identity property function instead: \`{ "type": "identity", "property": ${JSON.stringify(tokenMatch[1])} }\`.`)]; + } + const errors = []; + if (options.layerType === 'symbol') { + if (propertyKey === 'text-field' && style && !style.glyphs) { + errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property')); + } + if (propertyKey === 'text-font' && isFunction$1(deepUnbundle(value)) && unbundle(value.type) === 'identity') { + errors.push(new ValidationError(key, value, '"text-font" does not support identity functions')); + } + } + return errors.concat(validateSpec({ + key: options.key, + value, + valueSpec, + style, + styleSpec, + expressionContext: 'property', + propertyType, + propertyKey + })); +} + +function validatePaintProperty$1(options) { + return validateProperty(options, 'paint'); +} + +function validateLayoutProperty$1(options) { + return validateProperty(options, 'layout'); +} + +function validateLayer(options) { + let errors = []; + const layer = options.value; + const key = options.key; + const style = options.style; + const styleSpec = options.styleSpec; + if (!layer.type && !layer.ref) { + errors.push(new ValidationError(key, layer, 'either "type" or "ref" is required')); + } + let type = unbundle(layer.type); + const ref = unbundle(layer.ref); + if (layer.id) { + const layerId = unbundle(layer.id); + for (let i = 0; i < options.arrayIndex; i++) { + const otherLayer = style.layers[i]; + if (unbundle(otherLayer.id) === layerId) { + errors.push(new ValidationError(key, layer.id, `duplicate layer id "${layer.id}", previously used at line ${otherLayer.id.__line__}`)); + } + } + } + if ('ref' in layer) { + ['type', 'source', 'source-layer', 'filter', 'layout'].forEach((p) => { + if (p in layer) { + errors.push(new ValidationError(key, layer[p], `"${p}" is prohibited for ref layers`)); + } + }); + let parent; + style.layers.forEach((layer) => { + if (unbundle(layer.id) === ref) + parent = layer; + }); + if (!parent) { + errors.push(new ValidationError(key, layer.ref, `ref layer "${ref}" not found`)); + } + else if (parent.ref) { + errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer')); + } + else { + type = unbundle(parent.type); + } + } + else if (type !== 'background') { + if (!layer.source) { + errors.push(new ValidationError(key, layer, 'missing required property "source"')); + } + else { + const source = style.sources && style.sources[layer.source]; + const sourceType = source && unbundle(source.type); + if (!source) { + errors.push(new ValidationError(key, layer.source, `source "${layer.source}" not found`)); + } + else if (sourceType === 'vector' && type === 'raster') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a raster source`)); + } + else if (sourceType !== 'raster-dem' && type === 'hillshade') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a raster-dem source`)); + } + else if (sourceType === 'raster' && type !== 'raster') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a vector source`)); + } + else if (sourceType === 'vector' && !layer['source-layer']) { + errors.push(new ValidationError(key, layer, `layer "${layer.id}" must specify a "source-layer"`)); + } + else if (sourceType === 'raster-dem' && type !== 'hillshade') { + errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \'hillshade\'.')); + } + else if (type === 'line' && layer.paint && layer.paint['line-gradient'] && + (sourceType !== 'geojson' || !source.lineMetrics)) { + errors.push(new ValidationError(key, layer, `layer "${layer.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)); + } + } + } + errors = errors.concat(validateObject({ + key, + value: layer, + valueSpec: styleSpec.layer, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + objectElementValidators: { + '*'() { + return []; + }, + // We don't want to enforce the spec's `"requires": true` for backward compatibility with refs; + // the actual requirement is validated above. See https://github.com/mapbox/mapbox-gl-js/issues/5772. + type() { + return options.validateSpec({ + key: `${key}.type`, + value: layer.type, + valueSpec: styleSpec.layer.type, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + object: layer, + objectKey: 'type' + }); + }, + filter: validateFilter$1, + layout(options) { + return validateObject({ + layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + objectElementValidators: { + '*'(options) { + return validateLayoutProperty$1(extendBy({ layerType: type }, options)); + } + } + }); + }, + paint(options) { + return validateObject({ + layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + objectElementValidators: { + '*'(options) { + return validatePaintProperty$1(extendBy({ layerType: type }, options)); + } + } + }); + } + } + })); + return errors; +} + +function validateString(options) { + const value = options.value; + const key = options.key; + const type = getType(value); + if (type !== 'string') { + return [new ValidationError(key, value, `string expected, ${type} found`)]; + } + return []; +} + +function validateRasterDEMSource(options) { + var _a; + const sourceName = (_a = options.sourceName) !== null && _a !== void 0 ? _a : ''; + const rasterDEM = options.value; + const styleSpec = options.styleSpec; + const rasterDEMSpec = styleSpec.source_raster_dem; + const style = options.style; + let errors = []; + const rootType = getType(rasterDEM); + if (rasterDEM === undefined) { + return errors; + } + else if (rootType !== 'object') { + errors.push(new ValidationError('source_raster_dem', rasterDEM, `object expected, ${rootType} found`)); + return errors; + } + const encoding = unbundle(rasterDEM.encoding); + const isCustomEncoding = encoding === 'custom'; + const customEncodingKeys = ['redFactor', 'greenFactor', 'blueFactor', 'baseShift']; + const encodingName = options.value.encoding ? `"${options.value.encoding}"` : 'Default'; + for (const key in rasterDEM) { + if (!isCustomEncoding && customEncodingKeys.includes(key)) { + errors.push(new ValidationError(key, rasterDEM[key], `In "${sourceName}": "${key}" is only valid when "encoding" is set to "custom". ${encodingName} encoding found`)); + } + else if (rasterDEMSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: rasterDEM[key], + valueSpec: rasterDEMSpec[key], + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else { + errors.push(new ValidationError(key, rasterDEM[key], `unknown property "${key}"`)); + } + } + return errors; +} + +const objectElementValidators = { + promoteId: validatePromoteId +}; +function validateSource$1(options) { + const value = options.value; + const key = options.key; + const styleSpec = options.styleSpec; + const style = options.style; + const validateSpec = options.validateSpec; + if (!value.type) { + return [new ValidationError(key, value, '"type" is required')]; + } + const type = unbundle(value.type); + let errors; + switch (type) { + case 'vector': + case 'raster': + errors = validateObject({ + key, + value, + valueSpec: styleSpec[`source_${type.replace('-', '_')}`], + style: options.style, + styleSpec, + objectElementValidators, + validateSpec, + }); + return errors; + case 'raster-dem': + errors = validateRasterDEMSource({ + sourceName: key, + value, + style: options.style, + styleSpec, + validateSpec, + }); + return errors; + case 'geojson': + errors = validateObject({ + key, + value, + valueSpec: styleSpec.source_geojson, + style, + styleSpec, + validateSpec, + objectElementValidators + }); + if (value.cluster) { + for (const prop in value.clusterProperties) { + const [operator, mapExpr] = value.clusterProperties[prop]; + const reduceExpr = typeof operator === 'string' ? [operator, ['accumulated'], ['get', prop]] : operator; + errors.push(...validateExpression({ + key: `${key}.${prop}.map`, + value: mapExpr, + validateSpec, + expressionContext: 'cluster-map' + })); + errors.push(...validateExpression({ + key: `${key}.${prop}.reduce`, + value: reduceExpr, + validateSpec, + expressionContext: 'cluster-reduce' + })); + } + } + return errors; + case 'video': + return validateObject({ + key, + value, + valueSpec: styleSpec.source_video, + style, + validateSpec, + styleSpec + }); + case 'image': + return validateObject({ + key, + value, + valueSpec: styleSpec.source_image, + style, + validateSpec, + styleSpec + }); + case 'canvas': + return [new ValidationError(key, null, 'Please use runtime APIs to add canvas sources, rather than including them in stylesheets.', 'source.canvas')]; + default: + return validateEnum({ + key: `${key}.type`, + value: value.type, + valueSpec: { values: ['vector', 'raster', 'raster-dem', 'geojson', 'video', 'image'] }, + style, + validateSpec, + styleSpec + }); + } +} +function validatePromoteId({ key, value }) { + if (getType(value) === 'string') { + return validateString({ key, value }); + } + else { + const errors = []; + for (const prop in value) { + errors.push(...validateString({ key: `${key}.${prop}`, value: value[prop] })); + } + return errors; + } +} + +function validateLight$1(options) { + const light = options.value; + const styleSpec = options.styleSpec; + const lightSpec = styleSpec.light; + const style = options.style; + let errors = []; + const rootType = getType(light); + if (light === undefined) { + return errors; + } + else if (rootType !== 'object') { + errors = errors.concat([new ValidationError('light', light, `object expected, ${rootType} found`)]); + return errors; + } + for (const key in light) { + const transitionMatch = key.match(/^(.*)-transition$/); + if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) { + errors = errors.concat(options.validateSpec({ + key, + value: light[key], + valueSpec: styleSpec.transition, + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else if (lightSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: light[key], + valueSpec: lightSpec[key], + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, light[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +function validateSky$1(options) { + const sky = options.value; + const styleSpec = options.styleSpec; + const skySpec = styleSpec.sky; + const style = options.style; + const rootType = getType(sky); + if (sky === undefined) { + return []; + } + else if (rootType !== 'object') { + return [new ValidationError('sky', sky, `object expected, ${rootType} found`)]; + } + let errors = []; + for (const key in sky) { + if (skySpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: sky[key], + valueSpec: skySpec[key], + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, sky[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +function validateTerrain$1(options) { + const terrain = options.value; + const styleSpec = options.styleSpec; + const terrainSpec = styleSpec.terrain; + const style = options.style; + let errors = []; + const rootType = getType(terrain); + if (terrain === undefined) { + return errors; + } + else if (rootType !== 'object') { + errors = errors.concat([new ValidationError('terrain', terrain, `object expected, ${rootType} found`)]); + return errors; + } + for (const key in terrain) { + if (terrainSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: terrain[key], + valueSpec: terrainSpec[key], + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, terrain[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +function validateFormatted(options) { + if (validateString(options).length === 0) { + return []; + } + return validateExpression(options); +} + +function validateImage(options) { + if (validateString(options).length === 0) { + return []; + } + return validateExpression(options); +} + +function validatePadding(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + if (type === 'array') { + if (value.length < 1 || value.length > 4) { + return [new ValidationError(key, value, `padding requires 1 to 4 values; ${value.length} values found`)]; + } + const arrayElementSpec = { + type: 'number' + }; + let errors = []; + for (let i = 0; i < value.length; i++) { + errors = errors.concat(options.validateSpec({ + key: `${key}[${i}]`, + value: value[i], + validateSpec: options.validateSpec, + valueSpec: arrayElementSpec + })); + } + return errors; + } + else { + return validateNumber({ + key, + value, + valueSpec: {} + }); + } +} + +function validateVariableAnchorOffsetCollection(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + const styleSpec = options.styleSpec; + if (type !== 'array' || value.length < 1 || value.length % 2 !== 0) { + return [new ValidationError(key, value, 'variableAnchorOffsetCollection requires a non-empty array of even length')]; + } + let errors = []; + for (let i = 0; i < value.length; i += 2) { + // Elements in even positions should be values from text-anchor enum + errors = errors.concat(validateEnum({ + key: `${key}[${i}]`, + value: value[i], + valueSpec: styleSpec['layout_symbol']['text-anchor'] + })); + // Elements in odd positions should be points (2-element numeric arrays) + errors = errors.concat(validateArray({ + key: `${key}[${i + 1}]`, + value: value[i + 1], + valueSpec: { + length: 2, + value: 'number' + }, + validateSpec: options.validateSpec, + style: options.style, + styleSpec + })); + } + return errors; +} + +function validateSprite(options) { + let errors = []; + const sprite = options.value; + const key = options.key; + if (!Array.isArray(sprite)) { + return validateString({ + key, + value: sprite + }); + } + else { + const allSpriteIds = []; + const allSpriteURLs = []; + for (const i in sprite) { + if (sprite[i].id && allSpriteIds.includes(sprite[i].id)) + errors.push(new ValidationError(key, sprite, `all the sprites' ids must be unique, but ${sprite[i].id} is duplicated`)); + allSpriteIds.push(sprite[i].id); + if (sprite[i].url && allSpriteURLs.includes(sprite[i].url)) + errors.push(new ValidationError(key, sprite, `all the sprites' URLs must be unique, but ${sprite[i].url} is duplicated`)); + allSpriteURLs.push(sprite[i].url); + const pairSpec = { + id: { + type: 'string', + required: true, + }, + url: { + type: 'string', + required: true, + } + }; + errors = errors.concat(validateObject({ + key: `${key}[${i}]`, + value: sprite[i], + valueSpec: pairSpec, + validateSpec: options.validateSpec, + })); + } + return errors; + } +} + +function validateProjection(options) { + const projection = options.value; + const styleSpec = options.styleSpec; + const projectionSpec = styleSpec.projection; + const style = options.style; + const rootType = getType(projection); + if (projection === undefined) { + return []; + } + else if (rootType !== 'object') { + return [new ValidationError('projection', projection, `object expected, ${rootType} found`)]; + } + let errors = []; + for (const key in projection) { + if (projectionSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: projection[key], + valueSpec: projectionSpec[key], + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, projection[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +const VALIDATORS = { + '*'() { + return []; + }, + 'array': validateArray, + 'boolean': validateBoolean, + 'number': validateNumber, + 'color': validateColor, + 'constants': validateConstants, + 'enum': validateEnum, + 'filter': validateFilter$1, + 'function': validateFunction, + 'layer': validateLayer, + 'object': validateObject, + 'source': validateSource$1, + 'light': validateLight$1, + 'sky': validateSky$1, + 'terrain': validateTerrain$1, + 'projection': validateProjection, + 'string': validateString, + 'formatted': validateFormatted, + 'resolvedImage': validateImage, + 'padding': validatePadding, + 'variableAnchorOffsetCollection': validateVariableAnchorOffsetCollection, + 'sprite': validateSprite, +}; +/** + * Main recursive validation function used internally. + * You should use `validateStyleMin` in the browser or `validateStyle` in node env. + * @param options - the options object + * @param options.key - string representing location of validation in style tree. Used only + * for more informative error reporting. + * @param options.value - current value from style being evaluated. May be anything from a + * high level object that needs to be descended into deeper or a simple + * scalar value. + * @param options.valueSpec - current spec being evaluated. Tracks value. + * @param options.styleSpec - current full spec being evaluated. + * @param options.validateSpec - the validate function itself + * @param options.style - the style object + * @param options.objectElementValidators - optional object of functions that will be called + * @returns an array of errors, or an empty array if no errors are found. + */ +function validate(options) { + const value = options.value; + const valueSpec = options.valueSpec; + const styleSpec = options.styleSpec; + options.validateSpec = validate; + if (valueSpec.expression && isFunction$1(unbundle(value))) { + return validateFunction(options); + } + else if (valueSpec.expression && isExpression(deepUnbundle(value))) { + return validateExpression(options); + } + else if (valueSpec.type && VALIDATORS[valueSpec.type]) { + return VALIDATORS[valueSpec.type](options); + } + else { + const valid = validateObject(extendBy({}, options, { + valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec + })); + return valid; + } +} + +function validateGlyphsUrl(options) { + const value = options.value; + const key = options.key; + const errors = validateString(options); + if (errors.length) + return errors; + if (value.indexOf('{fontstack}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{fontstack}" token')); + } + if (value.indexOf('{range}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{range}" token')); + } + return errors; +} + +/** + * Validate a MapLibre style against the style specification. + * Use this when running in the browser. + * + * @param style - The style to be validated. + * @param styleSpec - The style specification to validate against. + * If omitted, the latest style spec is used. + * @returns an array of errors, or an empty array if no errors are found. + * @example + * const validate = require('@maplibre/maplibre-gl-style-spec/').validateStyleMin; + * const errors = validate(style); + */ +function validateStyleMin(style, styleSpec = v8Spec) { + let errors = []; + errors = errors.concat(validate({ + key: '', + value: style, + valueSpec: styleSpec.$root, + styleSpec, + style, + validateSpec: validate, + objectElementValidators: { + glyphs: validateGlyphsUrl, + '*'() { + return []; + } + } + })); + if (style['constants']) { + errors = errors.concat(validateConstants({ + key: 'constants', + value: style['constants'], + style, + styleSpec, + validateSpec: validate, + })); + } + return sortErrors(errors); +} +validateStyleMin.source = wrapCleanErrors(injectValidateSpec(validateSource$1)); +validateStyleMin.sprite = wrapCleanErrors(injectValidateSpec(validateSprite)); +validateStyleMin.glyphs = wrapCleanErrors(injectValidateSpec(validateGlyphsUrl)); +validateStyleMin.light = wrapCleanErrors(injectValidateSpec(validateLight$1)); +validateStyleMin.sky = wrapCleanErrors(injectValidateSpec(validateSky$1)); +validateStyleMin.terrain = wrapCleanErrors(injectValidateSpec(validateTerrain$1)); +validateStyleMin.layer = wrapCleanErrors(injectValidateSpec(validateLayer)); +validateStyleMin.filter = wrapCleanErrors(injectValidateSpec(validateFilter$1)); +validateStyleMin.paintProperty = wrapCleanErrors(injectValidateSpec(validatePaintProperty$1)); +validateStyleMin.layoutProperty = wrapCleanErrors(injectValidateSpec(validateLayoutProperty$1)); +function injectValidateSpec(validator) { + return function (options) { + return validator({ + ...options, + validateSpec: validate, + }); + }; +} +function sortErrors(errors) { + return [].concat(errors).sort((a, b) => { + return a.line - b.line; + }); +} +function wrapCleanErrors(inner) { + return function (...args) { + return sortErrors(inner.apply(this, args)); + }; +} + +// Note: This regex matches even invalid JSON strings, but since we’re +// working on the output of `JSON.stringify` we know that only valid strings +// are present (unless the user supplied a weird `options.indent` but in +// that case we don’t care since the output would be invalid anyway). +const stringOrChar = /("(?:[^\\"]|\\.)*")|[:,]/g; + +function stringify(passedObj, options = {}) { + const indent = JSON.stringify( + [1], + undefined, + options.indent === undefined ? 2 : options.indent + ).slice(2, -3); + + const maxLength = + indent === "" + ? Infinity + : options.maxLength === undefined + ? 80 + : options.maxLength; + + let { replacer } = options; + + return (function _stringify(obj, currentIndent, reserved) { + if (obj && typeof obj.toJSON === "function") { + obj = obj.toJSON(); + } + + const string = JSON.stringify(obj, replacer); + + if (string === undefined) { + return string; + } + + const length = maxLength - currentIndent.length - reserved; + + if (string.length <= length) { + const prettified = string.replace( + stringOrChar, + (match, stringLiteral) => { + return stringLiteral || `${match} `; + } + ); + if (prettified.length <= length) { + return prettified; + } + } + + if (replacer != null) { + obj = JSON.parse(string); + replacer = undefined; + } + + if (typeof obj === "object" && obj !== null) { + const nextIndent = currentIndent + indent; + const items = []; + let index = 0; + let start; + let end; + + if (Array.isArray(obj)) { + start = "["; + end = "]"; + const { length } = obj; + for (; index < length; index++) { + items.push( + _stringify(obj[index], nextIndent, index === length - 1 ? 0 : 1) || + "null" + ); + } + } else { + start = "{"; + end = "}"; + const keys = Object.keys(obj); + const { length } = keys; + for (; index < length; index++) { + const key = keys[index]; + const keyPart = `${JSON.stringify(key)}: `; + const value = _stringify( + obj[key], + nextIndent, + keyPart.length + (index === length - 1 ? 0 : 1) + ); + if (value !== undefined) { + items.push(keyPart + value); + } + } + } + + if (items.length > 0) { + return [start, indent + items.join(`,\n${nextIndent}`), end].join( + `\n${currentIndent}` + ); + } + } + + return string; + })(passedObj, "", 0); +} + +function sortKeysBy(obj, reference) { + const result = {}; + for (const key in reference) { + if (obj[key] !== undefined) { + result[key] = obj[key]; + } + } + for (const key in obj) { + if (result[key] === undefined) { + result[key] = obj[key]; + } + } + return result; +} +/** + * Format a MapLibre Style. Returns a stringified style with its keys + * sorted in the same order as the reference style. + * + * The optional `space` argument is passed to + * [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) + * to generate formatted output. + * + * If `space` is unspecified, a default of `2` spaces will be used. + * + * @private + * @param {Object} style a MapLibre Style + * @param {number} [space] space argument to pass to `JSON.stringify` + * @returns {string} stringified formatted JSON + * @example + * var fs = require('fs'); + * var format = require('maplibre-gl-style-spec').format; + * var style = fs.readFileSync('./source.json', 'utf8'); + * fs.writeFileSync('./dest.json', format(style)); + * fs.writeFileSync('./dest.min.json', format(style, 0)); + */ +function format(style, space = 2) { + style = sortKeysBy(style, v8Spec.$root); + if (style.layers) { + style.layers = style.layers.map((layer) => sortKeysBy(layer, v8Spec.layer)); + } + return stringify(style, { indent: space }); +} + +function eachLayout(layer, callback) { + for (const k in layer) { + if (k.indexOf('layout') === 0) { + callback(layer[k], k); + } + } +} +function eachPaint(layer, callback) { + for (const k in layer) { + if (k.indexOf('paint') === 0) { + callback(layer[k], k); + } + } +} +function resolveConstant(style, value) { + if (typeof value === 'string' && value[0] === '@') { + return resolveConstant(style, style.constants[value]); + } + else { + return value; + } +} +function isFunction(value) { + return Array.isArray(value.stops); +} +function renameProperty(obj, from, to) { + obj[to] = obj[from]; + delete obj[from]; +} +function migrateV8(style) { + style.version = 8; + // Rename properties, reverse coordinates in source and layers + eachSource(style, (source) => { + if (source.type === 'video' && source['url'] !== undefined) { + renameProperty(source, 'url', 'urls'); + } + if (source.type === 'video') { + source.coordinates.forEach((coord) => { + return coord.reverse(); + }); + } + }); + eachLayer(style, (layer) => { + eachLayout(layer, (layout) => { + if (layout['symbol-min-distance'] !== undefined) { + renameProperty(layout, 'symbol-min-distance', 'symbol-spacing'); + } + }); + eachPaint(layer, (paint) => { + if (paint['background-image'] !== undefined) { + renameProperty(paint, 'background-image', 'background-pattern'); + } + if (paint['line-image'] !== undefined) { + renameProperty(paint, 'line-image', 'line-pattern'); + } + if (paint['fill-image'] !== undefined) { + renameProperty(paint, 'fill-image', 'fill-pattern'); + } + }); + }); + // Inline Constants + eachProperty(style, { paint: true, layout: true }, (property) => { + const value = resolveConstant(style, property.value); + if (isFunction(value)) { + value.stops.forEach((stop) => { + stop[1] = resolveConstant(style, stop[1]); + }); + } + property.set(value); + }); + delete style['constants']; + eachLayer(style, (layer) => { + // get rid of text-max-size, icon-max-size + // turn text-size, icon-size into layout properties + // https://github.com/mapbox/mapbox-gl-style-spec/issues/255 + eachLayout(layer, (layout) => { + delete layout['text-max-size']; + delete layout['icon-max-size']; + }); + eachPaint(layer, (paint) => { + if (paint['text-size']) { + if (!layer.layout) + layer.layout = {}; + layer.layout['text-size'] = paint['text-size']; + delete paint['text-size']; + } + if (paint['icon-size']) { + if (!layer.layout) + layer.layout = {}; + layer.layout['icon-size'] = paint['icon-size']; + delete paint['icon-size']; + } + }); + }); + function migrateFontStack(font) { + function splitAndTrim(string) { + return string.split(',').map((s) => { + return s.trim(); + }); + } + if (Array.isArray(font)) { + // Assume it's a previously migrated font-array. + return font; + } + else if (typeof font === 'string') { + return splitAndTrim(font); + } + else if (typeof font === 'object') { + font.stops.forEach((stop) => { + stop[1] = splitAndTrim(stop[1]); + }); + return font; + } + else { + throw new Error('unexpected font value'); + } + } + eachLayer(style, (layer) => { + eachLayout(layer, (layout) => { + if (layout['text-font']) { + layout['text-font'] = migrateFontStack(layout['text-font']); + } + }); + }); + // Reverse order of symbol layers. This is an imperfect migration. + // + // The order of a symbol layer in the layers list affects two things: + // - how it is drawn relative to other layers (like oneway arrows below bridges) + // - the placement priority compared to other layers + // + // It's impossible to reverse the placement priority without breaking the draw order + // in some cases. This migration only reverses the order of symbol layers that + // are above all other types of layers. + // + // Symbol layers that are at the top of the map preserve their priority. + // Symbol layers that are below another type (line, fill) of layer preserve their draw order. + let firstSymbolLayer = 0; + for (let i = style.layers.length - 1; i >= 0; i--) { + const layer = style.layers[i]; + if (layer.type !== 'symbol') { + firstSymbolLayer = i + 1; + break; + } + } + const symbolLayers = style.layers.splice(firstSymbolLayer); + symbolLayers.reverse(); + style.layers = style.layers.concat(symbolLayers); + return style; +} + +/** + * Migrate the given style object in place to use expressions. Specifically, + * this will convert (a) "stop" functions, and (b) legacy filters to their + * expression equivalents. + * @param style The style object to migrate. + * @returns The migrated style object. + */ +function expressions(style) { + const converted = []; + eachLayer(style, (layer) => { + if (layer.filter) { + layer.filter = convertFilter(layer.filter); + } + }); + eachProperty(style, { paint: true, layout: true }, ({ path, value, reference, set }) => { + if (isExpression(value)) + return; + if (typeof value === 'object' && !Array.isArray(value)) { + set(convertFunction(value, reference)); + converted.push(path.join('.')); + } + else if (reference.tokens && typeof value === 'string') { + set(convertTokenString(value)); + } + }); + return style; +} + +/** + * Migrate color style values to supported format. + * + * @param colorToMigrate Color value to migrate, could be a string or an expression. + * @returns Color style value in supported format. + */ +function migrateColors(colorToMigrate) { + return JSON.parse(migrateHslColors(JSON.stringify(colorToMigrate))); +} +/** + * Created to migrate from colors supported by the former CSS color parsing + * library `csscolorparser` but not compliant with the CSS Color specification, + * like `hsl(900, 0.15, 90%)`. + * + * @param colorToMigrate Serialized color style value. + * @returns A serialized color style value in which all non-standard hsl color values + * have been converted to a format that complies with the CSS Color specification. + * + * @example + * migrateHslColors('"hsl(900, 0.15, 90%)"'); // returns '"hsl(900, 15%, 90%)"' + * migrateHslColors('"hsla(900, .15, .9)"'); // returns '"hsl(900, 15%, 90%)"' + * migrateHslColors('"hsl(900, 15%, 90%)"'); // returns '"hsl(900, 15%, 90%)"' - no changes + */ +function migrateHslColors(colorToMigrate) { + return colorToMigrate.replace(/"hsla?\((.+?)\)"/gi, (match, hslArgs) => { + const argsMatch = hslArgs.match(/^(.+?)\s*,\s*(.+?)\s*,\s*(.+?)(?:\s*,\s*(.+))?$/i); + if (argsMatch) { + let [h, s, l, a] = argsMatch.slice(1); + [s, l] = [s, l].map(v => v.endsWith('%') ? v : `${parseFloat(v) * 100}%`); + return `"hsl${typeof a === 'string' ? 'a' : ''}(${[h, s, l, a].filter(Boolean).join(',')})"`; + } + return match; + }); +} + +/** + * Migrate a Mapbox/MapLibre GL Style to the latest version. + * + * @param style - a MapLibre Style + * @returns a migrated style + * @example + * const fs = require('fs'); + * csont migrate = require('@maplibre/maplibre-gl-style-spec').migrate; + * const style = fs.readFileSync('./style.json', 'utf8'); + * fs.writeFileSync('./style.json', JSON.stringify(migrate(style))); + */ +function migrate(style) { + let migrated = false; + if (style.version === 7) { + style = migrateV8(style); + migrated = true; + } + if (style.version === 8) { + migrated = !!expressions(style); + migrated = true; + } + eachProperty(style, { paint: true, layout: true }, ({ value, reference, set }) => { + if (reference.type === 'color') { + set(migrateColors(value)); + } + }); + if (!migrated) { + throw new Error(`Cannot migrate from ${style.version}`); + } + return style; +} + +const v8 = v8Spec; +const expression = { + StyleExpression, + StylePropertyFunction, + ZoomConstantExpression, + ZoomDependentExpression, + createExpression, + createPropertyExpression, + isExpression, + isExpressionFilter, + isZoomExpression, + normalizePropertyExpression, +}; +const styleFunction = { + convertFunction, + createFunction, + isFunction: isFunction$1 +}; +const visit = { eachLayer, eachProperty, eachSource }; + +const validateStyle = validateStyleMin; +const validateSource = validateStyle.source; +const validateLight = validateStyle.light; +const validateSky = validateStyle.sky; +const validateTerrain = validateStyle.terrain; +const validateFilter = validateStyle.filter; +const validatePaintProperty = validateStyle.paintProperty; +const validateLayoutProperty = validateStyle.layoutProperty; +function emitValidationErrors(emitter, errors) { + let hasErrors = false; + if (errors && errors.length) { + for (const error of errors) { + emitter.fire(new ErrorEvent(new Error(error.message))); + hasErrors = true; + } + } + return hasErrors; +} + +/* +This file was copied from https://github.com/mapbox/grid-index and was +migrated from JavaScript to TypeScript. + +Copyright (c) 2016, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +*/ +const NUM_PARAMS = 3; +class TransferableGridIndex { + constructor(extent, n, padding) { + const cells = this.cells = []; + if (extent instanceof ArrayBuffer) { + this.arrayBuffer = extent; + const array = new Int32Array(this.arrayBuffer); + extent = array[0]; + n = array[1]; + padding = array[2]; + this.d = n + 2 * padding; + for (let k = 0; k < this.d * this.d; k++) { + const start = array[NUM_PARAMS + k]; + const end = array[NUM_PARAMS + k + 1]; + cells.push(start === end ? null : array.subarray(start, end)); + } + const keysOffset = array[NUM_PARAMS + cells.length]; + const bboxesOffset = array[NUM_PARAMS + cells.length + 1]; + this.keys = array.subarray(keysOffset, bboxesOffset); + this.bboxes = array.subarray(bboxesOffset); + this.insert = this._insertReadonly; + } + else { + this.d = n + 2 * padding; + for (let i = 0; i < this.d * this.d; i++) { + cells.push([]); + } + this.keys = []; + this.bboxes = []; + } + this.n = n; + this.extent = extent; + this.padding = padding; + this.scale = n / extent; + this.uid = 0; + const p = (padding / n) * extent; + this.min = -p; + this.max = extent + p; + } + insert(key, x1, y1, x2, y2) { + this._forEachCell(x1, y1, x2, y2, this._insertCell, this.uid++, undefined, undefined); + this.keys.push(key); + this.bboxes.push(x1); + this.bboxes.push(y1); + this.bboxes.push(x2); + this.bboxes.push(y2); + } + _insertReadonly() { + throw new Error('Cannot insert into a GridIndex created from an ArrayBuffer.'); + } + _insertCell(x1, y1, x2, y2, cellIndex, uid) { + this.cells[cellIndex].push(uid); + } + query(x1, y1, x2, y2, intersectionTest) { + const min = this.min; + const max = this.max; + if (x1 <= min && y1 <= min && max <= x2 && max <= y2 && !intersectionTest) { + // We use `Array#slice` because `this.keys` may be a `Int32Array` and + // some browsers (Safari and IE) do not support `TypedArray#slice` + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice#Browser_compatibility + return Array.prototype.slice.call(this.keys); + } + else { + const result = []; + const seenUids = {}; + this._forEachCell(x1, y1, x2, y2, this._queryCell, result, seenUids, intersectionTest); + return result; + } + } + _queryCell(x1, y1, x2, y2, cellIndex, result, seenUids, intersectionTest) { + const cell = this.cells[cellIndex]; + if (cell !== null) { + const keys = this.keys; + const bboxes = this.bboxes; + for (let u = 0; u < cell.length; u++) { + const uid = cell[u]; + if (seenUids[uid] === undefined) { + const offset = uid * 4; + if (intersectionTest ? + intersectionTest(bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) : + ((x1 <= bboxes[offset + 2]) && + (y1 <= bboxes[offset + 3]) && + (x2 >= bboxes[offset + 0]) && + (y2 >= bboxes[offset + 1]))) { + seenUids[uid] = true; + result.push(keys[uid]); + } + else { + seenUids[uid] = false; + } + } + } + } + } + _forEachCell(x1, y1, x2, y2, fn, arg1, arg2, intersectionTest) { + const cx1 = this._convertToCellCoord(x1); + const cy1 = this._convertToCellCoord(y1); + const cx2 = this._convertToCellCoord(x2); + const cy2 = this._convertToCellCoord(y2); + for (let x = cx1; x <= cx2; x++) { + for (let y = cy1; y <= cy2; y++) { + const cellIndex = this.d * y + x; + if (intersectionTest && !intersectionTest(this._convertFromCellCoord(x), this._convertFromCellCoord(y), this._convertFromCellCoord(x + 1), this._convertFromCellCoord(y + 1))) + continue; + if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, intersectionTest)) + return; + } + } + } + _convertFromCellCoord(x) { + return (x - this.padding) / this.scale; + } + _convertToCellCoord(x) { + return Math.max(0, Math.min(this.d - 1, Math.floor(x * this.scale) + this.padding)); + } + toArrayBuffer() { + if (this.arrayBuffer) + return this.arrayBuffer; + const cells = this.cells; + const metadataLength = NUM_PARAMS + this.cells.length + 1 + 1; + let totalCellLength = 0; + for (let i = 0; i < this.cells.length; i++) { + totalCellLength += this.cells[i].length; + } + const array = new Int32Array(metadataLength + totalCellLength + this.keys.length + this.bboxes.length); + array[0] = this.extent; + array[1] = this.n; + array[2] = this.padding; + let offset = metadataLength; + for (let k = 0; k < cells.length; k++) { + const cell = cells[k]; + array[NUM_PARAMS + k] = offset; + array.set(cell, offset); + offset += cell.length; + } + array[NUM_PARAMS + cells.length] = offset; + array.set(this.keys, offset); + offset += this.keys.length; + array[NUM_PARAMS + cells.length + 1] = offset; + array.set(this.bboxes, offset); + offset += this.bboxes.length; + return array.buffer; + } + static serialize(grid, transferables) { + const buffer = grid.toArrayBuffer(); + if (transferables) { + transferables.push(buffer); + } + return { buffer }; + } + static deserialize(serialized) { + return new TransferableGridIndex(serialized.buffer); + } +} + +const registry = {}; +/** + * Register the given class as serializable. + * + * @param options - the registration options + */ +function register(name, klass, options = {}) { + if (registry[name]) + throw new Error(`${name} is already registered.`); + Object.defineProperty(klass, '_classRegistryKey', { + value: name, + writeable: false + }); + registry[name] = { + klass, + omit: options.omit || [], + shallow: options.shallow || [] + }; +} +register('Object', Object); +register('TransferableGridIndex', TransferableGridIndex); +register('Color', Color); +register('Error', Error); +register('AJAXError', AJAXError); +register('ResolvedImage', ResolvedImage); +register('StylePropertyFunction', StylePropertyFunction); +register('StyleExpression', StyleExpression, { omit: ['_evaluator'] }); +register('ZoomDependentExpression', ZoomDependentExpression); +register('ZoomConstantExpression', ZoomConstantExpression); +register('CompoundExpression', CompoundExpression, { omit: ['_evaluate'] }); +for (const name in expressions$1) { + if (expressions$1[name]._classRegistryKey) + continue; + register(`Expression_${name}`, expressions$1[name]); +} +function isArrayBuffer(value) { + return value && typeof ArrayBuffer !== 'undefined' && + (value instanceof ArrayBuffer || (value.constructor && value.constructor.name === 'ArrayBuffer')); +} +function getClassRegistryKey(input) { + const klass = input.constructor; + return input.$name || klass._classRegistryKey; +} +function isRegistered(input) { + if (input === null || typeof input !== 'object') { + return false; + } + const classRegistryKey = getClassRegistryKey(input); + if (classRegistryKey && classRegistryKey !== 'Object') { + return true; + } + return false; +} +function isSerializeHandledByBuiltin(input) { + return (!isRegistered(input) && (input === null || + input === undefined || + typeof input === 'boolean' || + typeof input === 'number' || + typeof input === 'string' || + input instanceof Boolean || + input instanceof Number || + input instanceof String || + input instanceof Date || + input instanceof RegExp || + input instanceof Blob || + input instanceof Error || + isArrayBuffer(input) || + isImageBitmap(input) || + ArrayBuffer.isView(input) || + input instanceof ImageData)); +} +/** + * Serialize the given object for transfer to or from a web worker. + * + * For non-builtin types, recursively serialize each property (possibly + * omitting certain properties - see register()), and package the result along + * with the constructor's `name` so that the appropriate constructor can be + * looked up in `deserialize()`. + * + * If a `transferables` array is provided, add any transferable objects (i.e., + * any ArrayBuffers or ArrayBuffer views) to the list. (If a copy is needed, + * this should happen in the client code, before using serialize().) + */ +function serialize(input, transferables) { + if (isSerializeHandledByBuiltin(input)) { + if (isArrayBuffer(input) || isImageBitmap(input)) { + if (transferables) { + transferables.push(input); + } + } + if (ArrayBuffer.isView(input)) { + const view = input; + if (transferables) { + transferables.push(view.buffer); + } + } + if (input instanceof ImageData) { + if (transferables) { + transferables.push(input.data.buffer); + } + } + return input; + } + if (Array.isArray(input)) { + const serialized = []; + for (const item of input) { + serialized.push(serialize(item, transferables)); + } + return serialized; + } + if (typeof input !== 'object') { + throw new Error(`can't serialize object of type ${typeof input}`); + } + const classRegistryKey = getClassRegistryKey(input); + if (!classRegistryKey) { + throw new Error(`can't serialize object of unregistered class ${input.constructor.name}`); + } + if (!registry[classRegistryKey]) + throw new Error(`${classRegistryKey} is not registered.`); + const { klass } = registry[classRegistryKey]; + const properties = klass.serialize ? + // (Temporary workaround) allow a class to provide static + // `serialize()` and `deserialize()` methods to bypass the generic + // approach. + // This temporary workaround lets us use the generic serialization + // approach for objects whose members include instances of dynamic + // StructArray types. Once we refactor StructArray to be static, + // we can remove this complexity. + klass.serialize(input, transferables) : {}; + if (!klass.serialize) { + for (const key in input) { + if (!input.hasOwnProperty(key)) + continue; // eslint-disable-line no-prototype-builtins + if (registry[classRegistryKey].omit.indexOf(key) >= 0) + continue; + const property = input[key]; + properties[key] = registry[classRegistryKey].shallow.indexOf(key) >= 0 ? + property : + serialize(property, transferables); + } + if (input instanceof Error) { + properties.message = input.message; + } + } + else { + if (transferables && properties === transferables[transferables.length - 1]) { + throw new Error('statically serialized object won\'t survive transfer of $name property'); + } + } + if (properties.$name) { + throw new Error('$name property is reserved for worker serialization logic.'); + } + if (classRegistryKey !== 'Object') { + properties.$name = classRegistryKey; + } + return properties; +} +function deserialize(input) { + if (isSerializeHandledByBuiltin(input)) { + return input; + } + if (Array.isArray(input)) { + return input.map(deserialize); + } + if (typeof input !== 'object') { + throw new Error(`can't deserialize object of type ${typeof input}`); + } + const classRegistryKey = getClassRegistryKey(input) || 'Object'; + if (!registry[classRegistryKey]) { + throw new Error(`can't deserialize unregistered class ${classRegistryKey}`); + } + const { klass } = registry[classRegistryKey]; + if (!klass) { + throw new Error(`can't deserialize unregistered class ${classRegistryKey}`); + } + if (klass.deserialize) { + return klass.deserialize(input); + } + const result = Object.create(klass.prototype); + for (const key of Object.keys(input)) { + if (key === '$name') + continue; + const value = input[key]; + result[key] = registry[classRegistryKey].shallow.indexOf(key) >= 0 ? value : deserialize(value); + } + return result; +} + +class ZoomHistory { + constructor() { + this.first = true; + } + update(z, now) { + const floorZ = Math.floor(z); + if (this.first) { + this.first = false; + this.lastIntegerZoom = floorZ; + this.lastIntegerZoomTime = 0; + this.lastZoom = z; + this.lastFloorZoom = floorZ; + return true; + } + if (this.lastFloorZoom > floorZ) { + this.lastIntegerZoom = floorZ + 1; + this.lastIntegerZoomTime = now; + } + else if (this.lastFloorZoom < floorZ) { + this.lastIntegerZoom = floorZ; + this.lastIntegerZoomTime = now; + } + if (z !== this.lastZoom) { + this.lastZoom = z; + this.lastFloorZoom = floorZ; + return true; + } + return false; + } +} + +// The following table comes from . +// Keep it synchronized with . +const unicodeBlockLookup = { + // 'Basic Latin': (char) => char >= 0x0000 && char <= 0x007F, + 'Latin-1 Supplement': (char) => char >= 0x0080 && char <= 0x00FF, + // 'Latin Extended-A': (char) => char >= 0x0100 && char <= 0x017F, + // 'Latin Extended-B': (char) => char >= 0x0180 && char <= 0x024F, + // 'IPA Extensions': (char) => char >= 0x0250 && char <= 0x02AF, + // 'Spacing Modifier Letters': (char) => char >= 0x02B0 && char <= 0x02FF, + // 'Combining Diacritical Marks': (char) => char >= 0x0300 && char <= 0x036F, + // 'Greek and Coptic': (char) => char >= 0x0370 && char <= 0x03FF, + // 'Cyrillic': (char) => char >= 0x0400 && char <= 0x04FF, + // 'Cyrillic Supplement': (char) => char >= 0x0500 && char <= 0x052F, + // 'Armenian': (char) => char >= 0x0530 && char <= 0x058F, + //'Hebrew': (char) => char >= 0x0590 && char <= 0x05FF, + // 'Arabic': (char) => char >= 0x0600 && char <= 0x06FF, + //'Syriac': (char) => char >= 0x0700 && char <= 0x074F, + // 'Arabic Supplement': (char) => char >= 0x0750 && char <= 0x077F, + // 'Thaana': (char) => char >= 0x0780 && char <= 0x07BF, + // 'NKo': (char) => char >= 0x07C0 && char <= 0x07FF, + // 'Samaritan': (char) => char >= 0x0800 && char <= 0x083F, + // 'Mandaic': (char) => char >= 0x0840 && char <= 0x085F, + // 'Syriac Supplement': (char) => char >= 0x0860 && char <= 0x086F, + // 'Arabic Extended-B': (char) => char >= 0x0870 && char <= 0x089F, + // 'Arabic Extended-A': (char) => char >= 0x08A0 && char <= 0x08FF, + // 'Devanagari': (char) => char >= 0x0900 && char <= 0x097F, + // 'Bengali': (char) => char >= 0x0980 && char <= 0x09FF, + // 'Gurmukhi': (char) => char >= 0x0A00 && char <= 0x0A7F, + // 'Gujarati': (char) => char >= 0x0A80 && char <= 0x0AFF, + // 'Oriya': (char) => char >= 0x0B00 && char <= 0x0B7F, + // 'Tamil': (char) => char >= 0x0B80 && char <= 0x0BFF, + // 'Telugu': (char) => char >= 0x0C00 && char <= 0x0C7F, + // 'Kannada': (char) => char >= 0x0C80 && char <= 0x0CFF, + // 'Malayalam': (char) => char >= 0x0D00 && char <= 0x0D7F, + // 'Sinhala': (char) => char >= 0x0D80 && char <= 0x0DFF, + // 'Thai': (char) => char >= 0x0E00 && char <= 0x0E7F, + // 'Lao': (char) => char >= 0x0E80 && char <= 0x0EFF, + // 'Tibetan': (char) => char >= 0x0F00 && char <= 0x0FFF, + // 'Myanmar': (char) => char >= 0x1000 && char <= 0x109F, + // 'Georgian': (char) => char >= 0x10A0 && char <= 0x10FF, + 'Hangul Jamo': (char) => char >= 0x1100 && char <= 0x11FF, + // 'Ethiopic': (char) => char >= 0x1200 && char <= 0x137F, + // 'Ethiopic Supplement': (char) => char >= 0x1380 && char <= 0x139F, + // 'Cherokee': (char) => char >= 0x13A0 && char <= 0x13FF, + // 'Unified Canadian Aboriginal Syllabics': (char) => char >= 0x1400 && char <= 0x167F, + // 'Ogham': (char) => char >= 0x1680 && char <= 0x169F, + // 'Runic': (char) => char >= 0x16A0 && char <= 0x16FF, + // 'Tagalog': (char) => char >= 0x1700 && char <= 0x171F, + // 'Hanunoo': (char) => char >= 0x1720 && char <= 0x173F, + // 'Buhid': (char) => char >= 0x1740 && char <= 0x175F, + // 'Tagbanwa': (char) => char >= 0x1760 && char <= 0x177F, + 'Khmer': (char) => char >= 0x1780 && char <= 0x17FF, + // 'Mongolian': (char) => char >= 0x1800 && char <= 0x18AF, + // 'Unified Canadian Aboriginal Syllabics Extended': (char) => char >= 0x18B0 && char <= 0x18FF, + // 'Limbu': (char) => char >= 0x1900 && char <= 0x194F, + // 'Tai Le': (char) => char >= 0x1950 && char <= 0x197F, + // 'New Tai Lue': (char) => char >= 0x1980 && char <= 0x19DF, + // 'Khmer Symbols': (char) => char >= 0x19E0 && char <= 0x19FF, + // 'Buginese': (char) => char >= 0x1A00 && char <= 0x1A1F, + // 'Tai Tham': (char) => char >= 0x1A20 && char <= 0x1AAF, + // 'Combining Diacritical Marks Extended': (char) => char >= 0x1AB0 && char <= 0x1AFF, + // 'Balinese': (char) => char >= 0x1B00 && char <= 0x1B7F, + // 'Sundanese': (char) => char >= 0x1B80 && char <= 0x1BBF, + // 'Batak': (char) => char >= 0x1BC0 && char <= 0x1BFF, + // 'Lepcha': (char) => char >= 0x1C00 && char <= 0x1C4F, + // 'Ol Chiki': (char) => char >= 0x1C50 && char <= 0x1C7F, + // 'Cyrillic Extended-C': (char) => char >= 0x1C80 && char <= 0x1C8F, + // 'Georgian Extended': (char) => char >= 0x1C90 && char <= 0x1CBF, + // 'Sundanese Supplement': (char) => char >= 0x1CC0 && char <= 0x1CCF, + // 'Vedic Extensions': (char) => char >= 0x1CD0 && char <= 0x1CFF, + // 'Phonetic Extensions': (char) => char >= 0x1D00 && char <= 0x1D7F, + // 'Phonetic Extensions Supplement': (char) => char >= 0x1D80 && char <= 0x1DBF, + // 'Combining Diacritical Marks Supplement': (char) => char >= 0x1DC0 && char <= 0x1DFF, + // 'Latin Extended Additional': (char) => char >= 0x1E00 && char <= 0x1EFF, + // 'Greek Extended': (char) => char >= 0x1F00 && char <= 0x1FFF, + 'General Punctuation': (char) => char >= 0x2000 && char <= 0x206F, + // 'Superscripts and Subscripts': (char) => char >= 0x2070 && char <= 0x209F, + // 'Currency Symbols': (char) => char >= 0x20A0 && char <= 0x20CF, + // 'Combining Diacritical Marks for Symbols': (char) => char >= 0x20D0 && char <= 0x20FF, + 'Letterlike Symbols': (char) => char >= 0x2100 && char <= 0x214F, + 'Number Forms': (char) => char >= 0x2150 && char <= 0x218F, + // 'Arrows': (char) => char >= 0x2190 && char <= 0x21FF, + // 'Mathematical Operators': (char) => char >= 0x2200 && char <= 0x22FF, + 'Miscellaneous Technical': (char) => char >= 0x2300 && char <= 0x23FF, + 'Control Pictures': (char) => char >= 0x2400 && char <= 0x243F, + 'Optical Character Recognition': (char) => char >= 0x2440 && char <= 0x245F, + 'Enclosed Alphanumerics': (char) => char >= 0x2460 && char <= 0x24FF, + // 'Box Drawing': (char) => char >= 0x2500 && char <= 0x257F, + // 'Block Elements': (char) => char >= 0x2580 && char <= 0x259F, + 'Geometric Shapes': (char) => char >= 0x25A0 && char <= 0x25FF, + 'Miscellaneous Symbols': (char) => char >= 0x2600 && char <= 0x26FF, + // 'Dingbats': (char) => char >= 0x2700 && char <= 0x27BF, + // 'Miscellaneous Mathematical Symbols-A': (char) => char >= 0x27C0 && char <= 0x27EF, + // 'Supplemental Arrows-A': (char) => char >= 0x27F0 && char <= 0x27FF, + // 'Braille Patterns': (char) => char >= 0x2800 && char <= 0x28FF, + // 'Supplemental Arrows-B': (char) => char >= 0x2900 && char <= 0x297F, + // 'Miscellaneous Mathematical Symbols-B': (char) => char >= 0x2980 && char <= 0x29FF, + // 'Supplemental Mathematical Operators': (char) => char >= 0x2A00 && char <= 0x2AFF, + 'Miscellaneous Symbols and Arrows': (char) => char >= 0x2B00 && char <= 0x2BFF, + // 'Glagolitic': (char) => char >= 0x2C00 && char <= 0x2C5F, + // 'Latin Extended-C': (char) => char >= 0x2C60 && char <= 0x2C7F, + // 'Coptic': (char) => char >= 0x2C80 && char <= 0x2CFF, + // 'Georgian Supplement': (char) => char >= 0x2D00 && char <= 0x2D2F, + // 'Tifinagh': (char) => char >= 0x2D30 && char <= 0x2D7F, + // 'Ethiopic Extended': (char) => char >= 0x2D80 && char <= 0x2DDF, + // 'Cyrillic Extended-A': (char) => char >= 0x2DE0 && char <= 0x2DFF, + // 'Supplemental Punctuation': (char) => char >= 0x2E00 && char <= 0x2E7F, + // 'CJK Radicals Supplement': (char) => char >= 0x2E80 && char <= 0x2EFF, + // 'Kangxi Radicals': (char) => char >= 0x2F00 && char <= 0x2FDF, + 'Ideographic Description Characters': (char) => char >= 0x2FF0 && char <= 0x2FFF, + 'CJK Symbols and Punctuation': (char) => char >= 0x3000 && char <= 0x303F, + // 'Hiragana': (char) => char >= 0x3040 && char <= 0x309F, + 'Katakana': (char) => char >= 0x30A0 && char <= 0x30FF, + // 'Bopomofo': (char) => char >= 0x3100 && char <= 0x312F, + // 'Hangul Compatibility Jamo': (char) => char >= 0x3130 && char <= 0x318F, + 'Kanbun': (char) => char >= 0x3190 && char <= 0x319F, + // 'Bopomofo Extended': (char) => char >= 0x31A0 && char <= 0x31BF, + 'CJK Strokes': (char) => char >= 0x31C0 && char <= 0x31EF, + // 'Katakana Phonetic Extensions': (char) => char >= 0x31F0 && char <= 0x31FF, + 'Enclosed CJK Letters and Months': (char) => char >= 0x3200 && char <= 0x32FF, + 'CJK Compatibility': (char) => char >= 0x3300 && char <= 0x33FF, + // 'CJK Unified Ideographs Extension A': (char) => char >= 0x3400 && char <= 0x4DBF, + 'Yijing Hexagram Symbols': (char) => char >= 0x4DC0 && char <= 0x4DFF, + // 'CJK Unified Ideographs': (char) => char >= 0x4E00 && char <= 0x9FFF, + // 'Yi Syllables': (char) => char >= 0xA000 && char <= 0xA48F, + // 'Yi Radicals': (char) => char >= 0xA490 && char <= 0xA4CF, + // 'Lisu': (char) => char >= 0xA4D0 && char <= 0xA4FF, + // 'Vai': (char) => char >= 0xA500 && char <= 0xA63F, + // 'Cyrillic Extended-B': (char) => char >= 0xA640 && char <= 0xA69F, + // 'Bamum': (char) => char >= 0xA6A0 && char <= 0xA6FF, + // 'Modifier Tone Letters': (char) => char >= 0xA700 && char <= 0xA71F, + // 'Latin Extended-D': (char) => char >= 0xA720 && char <= 0xA7FF, + // 'Syloti Nagri': (char) => char >= 0xA800 && char <= 0xA82F, + // 'Common Indic Number Forms': (char) => char >= 0xA830 && char <= 0xA83F, + // 'Phags-pa': (char) => char >= 0xA840 && char <= 0xA87F, + // 'Saurashtra': (char) => char >= 0xA880 && char <= 0xA8DF, + // 'Devanagari Extended': (char) => char >= 0xA8E0 && char <= 0xA8FF, + // 'Kayah Li': (char) => char >= 0xA900 && char <= 0xA92F, + // 'Rejang': (char) => char >= 0xA930 && char <= 0xA95F, + // 'Hangul Jamo Extended-A': (char) => char >= 0xA960 && char <= 0xA97F, + // 'Javanese': (char) => char >= 0xA980 && char <= 0xA9DF, + // 'Myanmar Extended-B': (char) => char >= 0xA9E0 && char <= 0xA9FF, + // 'Cham': (char) => char >= 0xAA00 && char <= 0xAA5F, + // 'Myanmar Extended-A': (char) => char >= 0xAA60 && char <= 0xAA7F, + // 'Tai Viet': (char) => char >= 0xAA80 && char <= 0xAADF, + // 'Meetei Mayek Extensions': (char) => char >= 0xAAE0 && char <= 0xAAFF, + // 'Ethiopic Extended-A': (char) => char >= 0xAB00 && char <= 0xAB2F, + // 'Latin Extended-E': (char) => char >= 0xAB30 && char <= 0xAB6F, + // 'Cherokee Supplement': (char) => char >= 0xAB70 && char <= 0xABBF, + // 'Meetei Mayek': (char) => char >= 0xABC0 && char <= 0xABFF, + // 'Hangul Syllables': (char) => char >= 0xAC00 && char <= 0xD7AF, + // 'Hangul Jamo Extended-B': (char) => char >= 0xD7B0 && char <= 0xD7FF, + // 'High Surrogates': (char) => char >= 0xD800 && char <= 0xDB7F, + // 'High Private Use Surrogates': (char) => char >= 0xDB80 && char <= 0xDBFF, + // 'Low Surrogates': (char) => char >= 0xDC00 && char <= 0xDFFF, + 'Private Use Area': (char) => char >= 0xE000 && char <= 0xF8FF, + // 'CJK Compatibility Ideographs': (char) => char >= 0xF900 && char <= 0xFAFF, + // 'Alphabetic Presentation Forms': (char) => char >= 0xFB00 && char <= 0xFB4F, + // 'Arabic Presentation Forms-A': (char) => char >= 0xFB50 && char <= 0xFDFF, + // 'Variation Selectors': (char) => char >= 0xFE00 && char <= 0xFE0F, + 'Vertical Forms': (char) => char >= 0xFE10 && char <= 0xFE1F, + // 'Combining Half Marks': (char) => char >= 0xFE20 && char <= 0xFE2F, + 'CJK Compatibility Forms': (char) => char >= 0xFE30 && char <= 0xFE4F, + 'Small Form Variants': (char) => char >= 0xFE50 && char <= 0xFE6F, + // 'Arabic Presentation Forms-B': (char) => char >= 0xFE70 && char <= 0xFEFF, + 'Halfwidth and Fullwidth Forms': (char) => char >= 0xFF00 && char <= 0xFFEF + // 'Specials': (char) => char >= 0xFFF0 && char <= 0xFFFF, + // 'Linear B Syllabary': (char) => char >= 0x10000 && char <= 0x1007F, + // 'Linear B Ideograms': (char) => char >= 0x10080 && char <= 0x100FF, + // 'Aegean Numbers': (char) => char >= 0x10100 && char <= 0x1013F, + // 'Ancient Greek Numbers': (char) => char >= 0x10140 && char <= 0x1018F, + // 'Ancient Symbols': (char) => char >= 0x10190 && char <= 0x101CF, + // 'Phaistos Disc': (char) => char >= 0x101D0 && char <= 0x101FF, + // 'Lycian': (char) => char >= 0x10280 && char <= 0x1029F, + // 'Carian': (char) => char >= 0x102A0 && char <= 0x102DF, + // 'Coptic Epact Numbers': (char) => char >= 0x102E0 && char <= 0x102FF, + // 'Old Italic': (char) => char >= 0x10300 && char <= 0x1032F, + // 'Gothic': (char) => char >= 0x10330 && char <= 0x1034F, + // 'Old Permic': (char) => char >= 0x10350 && char <= 0x1037F, + // 'Ugaritic': (char) => char >= 0x10380 && char <= 0x1039F, + // 'Old Persian': (char) => char >= 0x103A0 && char <= 0x103DF, + // 'Deseret': (char) => char >= 0x10400 && char <= 0x1044F, + // 'Shavian': (char) => char >= 0x10450 && char <= 0x1047F, + // 'Osmanya': (char) => char >= 0x10480 && char <= 0x104AF, + // 'Osage': (char) => char >= 0x104B0 && char <= 0x104FF, + // 'Elbasan': (char) => char >= 0x10500 && char <= 0x1052F, + // 'Caucasian Albanian': (char) => char >= 0x10530 && char <= 0x1056F, + // 'Vithkuqi': (char) => char >= 0x10570 && char <= 0x105BF, + // 'Todhri': (char) => char >= 0x105C0 && char <= 0x105FF, + // 'Linear A': (char) => char >= 0x10600 && char <= 0x1077F, + // 'Latin Extended-F': (char) => char >= 0x10780 && char <= 0x107BF, + // 'Cypriot Syllabary': (char) => char >= 0x10800 && char <= 0x1083F, + // 'Imperial Aramaic': (char) => char >= 0x10840 && char <= 0x1085F, + // 'Palmyrene': (char) => char >= 0x10860 && char <= 0x1087F, + // 'Nabataean': (char) => char >= 0x10880 && char <= 0x108AF, + // 'Hatran': (char) => char >= 0x108E0 && char <= 0x108FF, + // 'Phoenician': (char) => char >= 0x10900 && char <= 0x1091F, + // 'Lydian': (char) => char >= 0x10920 && char <= 0x1093F, + // 'Meroitic Hieroglyphs': (char) => char >= 0x10980 && char <= 0x1099F, + // 'Meroitic Cursive': (char) => char >= 0x109A0 && char <= 0x109FF, + // 'Kharoshthi': (char) => char >= 0x10A00 && char <= 0x10A5F, + // 'Old South Arabian': (char) => char >= 0x10A60 && char <= 0x10A7F, + // 'Old North Arabian': (char) => char >= 0x10A80 && char <= 0x10A9F, + // 'Manichaean': (char) => char >= 0x10AC0 && char <= 0x10AFF, + // 'Avestan': (char) => char >= 0x10B00 && char <= 0x10B3F, + // 'Inscriptional Parthian': (char) => char >= 0x10B40 && char <= 0x10B5F, + // 'Inscriptional Pahlavi': (char) => char >= 0x10B60 && char <= 0x10B7F, + // 'Psalter Pahlavi': (char) => char >= 0x10B80 && char <= 0x10BAF, + // 'Old Turkic': (char) => char >= 0x10C00 && char <= 0x10C4F, + // 'Old Hungarian': (char) => char >= 0x10C80 && char <= 0x10CFF, + // 'Hanifi Rohingya': (char) => char >= 0x10D00 && char <= 0x10D3F, + // 'Garay': (char) => char >= 0x10D40 && char <= 0x10D8F, + // 'Rumi Numeral Symbols': (char) => char >= 0x10E60 && char <= 0x10E7F, + // 'Yezidi': (char) => char >= 0x10E80 && char <= 0x10EBF, + // 'Arabic Extended-C': (char) => char >= 0x10EC0 && char <= 0x10EFF, + // 'Old Sogdian': (char) => char >= 0x10F00 && char <= 0x10F2F, + // 'Sogdian': (char) => char >= 0x10F30 && char <= 0x10F6F, + // 'Old Uyghur': (char) => char >= 0x10F70 && char <= 0x10FAF, + // 'Chorasmian': (char) => char >= 0x10FB0 && char <= 0x10FDF, + // 'Elymaic': (char) => char >= 0x10FE0 && char <= 0x10FFF, + // 'Brahmi': (char) => char >= 0x11000 && char <= 0x1107F, + // 'Kaithi': (char) => char >= 0x11080 && char <= 0x110CF, + // 'Sora Sompeng': (char) => char >= 0x110D0 && char <= 0x110FF, + // 'Chakma': (char) => char >= 0x11100 && char <= 0x1114F, + // 'Mahajani': (char) => char >= 0x11150 && char <= 0x1117F, + // 'Sharada': (char) => char >= 0x11180 && char <= 0x111DF, + // 'Sinhala Archaic Numbers': (char) => char >= 0x111E0 && char <= 0x111FF, + // 'Khojki': (char) => char >= 0x11200 && char <= 0x1124F, + // 'Multani': (char) => char >= 0x11280 && char <= 0x112AF, + // 'Khudawadi': (char) => char >= 0x112B0 && char <= 0x112FF, + // 'Grantha': (char) => char >= 0x11300 && char <= 0x1137F, + // 'Tulu-Tigalari': (char) => char >= 0x11380 && char <= 0x113FF, + // 'Newa': (char) => char >= 0x11400 && char <= 0x1147F, + // 'Tirhuta': (char) => char >= 0x11480 && char <= 0x114DF, + // 'Siddham': (char) => char >= 0x11580 && char <= 0x115FF, + // 'Modi': (char) => char >= 0x11600 && char <= 0x1165F, + // 'Mongolian Supplement': (char) => char >= 0x11660 && char <= 0x1167F, + // 'Takri': (char) => char >= 0x11680 && char <= 0x116CF, + // 'Myanmar Extended-C': (char) => char >= 0x116D0 && char <= 0x116FF, + // 'Ahom': (char) => char >= 0x11700 && char <= 0x1174F, + // 'Dogra': (char) => char >= 0x11800 && char <= 0x1184F, + // 'Warang Citi': (char) => char >= 0x118A0 && char <= 0x118FF, + // 'Dives Akuru': (char) => char >= 0x11900 && char <= 0x1195F, + // 'Nandinagari': (char) => char >= 0x119A0 && char <= 0x119FF, + // 'Zanabazar Square': (char) => char >= 0x11A00 && char <= 0x11A4F, + // 'Soyombo': (char) => char >= 0x11A50 && char <= 0x11AAF, + // 'Unified Canadian Aboriginal Syllabics Extended-A': (char) => char >= 0x11AB0 && char <= 0x11ABF, + // 'Pau Cin Hau': (char) => char >= 0x11AC0 && char <= 0x11AFF, + // 'Devanagari Extended-A': (char) => char >= 0x11B00 && char <= 0x11B5F, + // 'Sunuwar': (char) => char >= 0x11BC0 && char <= 0x11BFF, + // 'Bhaiksuki': (char) => char >= 0x11C00 && char <= 0x11C6F, + // 'Marchen': (char) => char >= 0x11C70 && char <= 0x11CBF, + // 'Masaram Gondi': (char) => char >= 0x11D00 && char <= 0x11D5F, + // 'Gunjala Gondi': (char) => char >= 0x11D60 && char <= 0x11DAF, + // 'Makasar': (char) => char >= 0x11EE0 && char <= 0x11EFF, + // 'Kawi': (char) => char >= 0x11F00 && char <= 0x11F5F, + // 'Lisu Supplement': (char) => char >= 0x11FB0 && char <= 0x11FBF, + // 'Tamil Supplement': (char) => char >= 0x11FC0 && char <= 0x11FFF, + // 'Cuneiform': (char) => char >= 0x12000 && char <= 0x123FF, + // 'Cuneiform Numbers and Punctuation': (char) => char >= 0x12400 && char <= 0x1247F, + // 'Early Dynastic Cuneiform': (char) => char >= 0x12480 && char <= 0x1254F, + // 'Cypro-Minoan': (char) => char >= 0x12F90 && char <= 0x12FFF, + // 'Egyptian Hieroglyphs': (char) => char >= 0x13000 && char <= 0x1342F, + // 'Egyptian Hieroglyph Format Controls': (char) => char >= 0x13430 && char <= 0x1345F, + // 'Egyptian Hieroglyphs Extended-A': (char) => char >= 0x13460 && char <= 0x143FF, + // 'Anatolian Hieroglyphs': (char) => char >= 0x14400 && char <= 0x1467F, + // 'Gurung Khema': (char) => char >= 0x16100 && char <= 0x1613F, + // 'Bamum Supplement': (char) => char >= 0x16800 && char <= 0x16A3F, + // 'Mro': (char) => char >= 0x16A40 && char <= 0x16A6F, + // 'Tangsa': (char) => char >= 0x16A70 && char <= 0x16ACF, + // 'Bassa Vah': (char) => char >= 0x16AD0 && char <= 0x16AFF, + // 'Pahawh Hmong': (char) => char >= 0x16B00 && char <= 0x16B8F, + // 'Kirat Rai': (char) => char >= 0x16D40 && char <= 0x16D7F, + // 'Medefaidrin': (char) => char >= 0x16E40 && char <= 0x16E9F, + // 'Miao': (char) => char >= 0x16F00 && char <= 0x16F9F, + // 'Ideographic Symbols and Punctuation': (char) => char >= 0x16FE0 && char <= 0x16FFF, + // 'Tangut': (char) => char >= 0x17000 && char <= 0x187FF, + // 'Tangut Components': (char) => char >= 0x18800 && char <= 0x18AFF, + // 'Khitan Small Script': (char) => char >= 0x18B00 && char <= 0x18CFF, + // 'Tangut Supplement': (char) => char >= 0x18D00 && char <= 0x18D7F, + // 'Kana Extended-B': (char) => char >= 0x1AFF0 && char <= 0x1AFFF, + // 'Kana Supplement': (char) => char >= 0x1B000 && char <= 0x1B0FF, + // 'Kana Extended-A': (char) => char >= 0x1B100 && char <= 0x1B12F, + // 'Small Kana Extension': (char) => char >= 0x1B130 && char <= 0x1B16F, + // 'Nushu': (char) => char >= 0x1B170 && char <= 0x1B2FF, + // 'Duployan': (char) => char >= 0x1BC00 && char <= 0x1BC9F, + // 'Shorthand Format Controls': (char) => char >= 0x1BCA0 && char <= 0x1BCAF, + // 'Symbols for Legacy Computing Supplement': (char) => char >= 0x1CC00 && char <= 0x1CEBF, + // 'Znamenny Musical Notation': (char) => char >= 0x1CF00 && char <= 0x1CFCF, + // 'Byzantine Musical Symbols': (char) => char >= 0x1D000 && char <= 0x1D0FF, + // 'Musical Symbols': (char) => char >= 0x1D100 && char <= 0x1D1FF, + // 'Ancient Greek Musical Notation': (char) => char >= 0x1D200 && char <= 0x1D24F, + // 'Kaktovik Numerals': (char) => char >= 0x1D2C0 && char <= 0x1D2DF, + // 'Mayan Numerals': (char) => char >= 0x1D2E0 && char <= 0x1D2FF, + // 'Tai Xuan Jing Symbols': (char) => char >= 0x1D300 && char <= 0x1D35F, + // 'Counting Rod Numerals': (char) => char >= 0x1D360 && char <= 0x1D37F, + // 'Mathematical Alphanumeric Symbols': (char) => char >= 0x1D400 && char <= 0x1D7FF, + // 'Sutton SignWriting': (char) => char >= 0x1D800 && char <= 0x1DAAF, + // 'Latin Extended-G': (char) => char >= 0x1DF00 && char <= 0x1DFFF, + // 'Glagolitic Supplement': (char) => char >= 0x1E000 && char <= 0x1E02F, + // 'Cyrillic Extended-D': (char) => char >= 0x1E030 && char <= 0x1E08F, + // 'Nyiakeng Puachue Hmong': (char) => char >= 0x1E100 && char <= 0x1E14F, + // 'Toto': (char) => char >= 0x1E290 && char <= 0x1E2BF, + // 'Wancho': (char) => char >= 0x1E2C0 && char <= 0x1E2FF, + // 'Nag Mundari': (char) => char >= 0x1E4D0 && char <= 0x1E4FF, + // 'Ol Onal': (char) => char >= 0x1E5D0 && char <= 0x1E5FF, + // 'Ethiopic Extended-B': (char) => char >= 0x1E7E0 && char <= 0x1E7FF, + // 'Mende Kikakui': (char) => char >= 0x1E800 && char <= 0x1E8DF, + // 'Adlam': (char) => char >= 0x1E900 && char <= 0x1E95F, + // 'Indic Siyaq Numbers': (char) => char >= 0x1EC70 && char <= 0x1ECBF, + // 'Ottoman Siyaq Numbers': (char) => char >= 0x1ED00 && char <= 0x1ED4F, + // 'Arabic Mathematical Alphabetic Symbols': (char) => char >= 0x1EE00 && char <= 0x1EEFF, + // 'Mahjong Tiles': (char) => char >= 0x1F000 && char <= 0x1F02F, + // 'Domino Tiles': (char) => char >= 0x1F030 && char <= 0x1F09F, + // 'Playing Cards': (char) => char >= 0x1F0A0 && char <= 0x1F0FF, + // 'Enclosed Alphanumeric Supplement': (char) => char >= 0x1F100 && char <= 0x1F1FF, + // 'Enclosed Ideographic Supplement': (char) => char >= 0x1F200 && char <= 0x1F2FF, + // 'Miscellaneous Symbols and Pictographs': (char) => char >= 0x1F300 && char <= 0x1F5FF, + // 'Emoticons': (char) => char >= 0x1F600 && char <= 0x1F64F, + // 'Ornamental Dingbats': (char) => char >= 0x1F650 && char <= 0x1F67F, + // 'Transport and Map Symbols': (char) => char >= 0x1F680 && char <= 0x1F6FF, + // 'Alchemical Symbols': (char) => char >= 0x1F700 && char <= 0x1F77F, + // 'Geometric Shapes Extended': (char) => char >= 0x1F780 && char <= 0x1F7FF, + // 'Supplemental Arrows-C': (char) => char >= 0x1F800 && char <= 0x1F8FF, + // 'Supplemental Symbols and Pictographs': (char) => char >= 0x1F900 && char <= 0x1F9FF, + // 'Chess Symbols': (char) => char >= 0x1FA00 && char <= 0x1FA6F, + // 'Symbols and Pictographs Extended-A': (char) => char >= 0x1FA70 && char <= 0x1FAFF, + // 'Symbols for Legacy Computing': (char) => char >= 0x1FB00 && char <= 0x1FBFF, + // 'CJK Unified Ideographs Extension B': (char) => char >= 0x20000 && char <= 0x2A6DF, + // 'CJK Unified Ideographs Extension C': (char) => char >= 0x2A700 && char <= 0x2B73F, + // 'CJK Unified Ideographs Extension D': (char) => char >= 0x2B740 && char <= 0x2B81F, + // 'CJK Unified Ideographs Extension E': (char) => char >= 0x2B820 && char <= 0x2CEAF, + // 'CJK Unified Ideographs Extension F': (char) => char >= 0x2CEB0 && char <= 0x2EBEF, + // 'CJK Unified Ideographs Extension I': (char) => char >= 0x2EBF0 && char <= 0x2EE5F, + // 'CJK Unified Ideographs Extension G': (char) => char >= 0x30000 && char <= 0x3134F, + // 'CJK Unified Ideographs Extension H': (char) => char >= 0x31350 && char <= 0x323AF, + // 'CJK Compatibility Ideographs Supplement': (char) => char >= 0x2F800 && char <= 0x2FA1F, + // 'Tags': (char) => char >= 0xE0000 && char <= 0xE007F, + // 'Variation Selectors Supplement': (char) => char >= 0xE0100 && char <= 0xE01EF, + // 'Supplementary Private Use Area-A': (char) => char >= 0xF0000 && char <= 0xFFFFF, + // 'Supplementary Private Use Area-B': (char) => char >= 0x100000 && char <= 0x10FFFF, +}; + +/* eslint-disable new-cap */ +function allowsIdeographicBreaking(chars) { + for (const char of chars) { + if (!charAllowsIdeographicBreaking(char.charCodeAt(0))) + return false; + } + return true; +} +function allowsVerticalWritingMode(chars) { + for (const char of chars) { + if (charHasUprightVerticalOrientation(char.charCodeAt(0))) + return true; + } + return false; +} +function allowsLetterSpacing(chars) { + for (const char of chars) { + if (!charAllowsLetterSpacing(char.charCodeAt(0))) + return false; + } + return true; +} +/** + * Returns a regular expression matching the given script codes, excluding any + * code that the execution environment lacks support for in regular expressions. + */ +function sanitizedRegExpFromScriptCodes(scriptCodes) { + const supportedPropertyEscapes = scriptCodes.map(code => { + try { + return new RegExp(`\\p{sc=${code}}`, 'u').source; + } + catch (e) { + return null; + } + }).filter(pe => pe); + return new RegExp(supportedPropertyEscapes.join('|'), 'u'); +} +/** + * ISO 15924 script codes of scripts that disallow letter spacing as of Unicode + * 16.0.0. + * + * In general, cursive scripts are incompatible with letter spacing. + */ +const cursiveScriptCodes = [ + 'Arab', // Arabic + 'Dupl', // Duployan + 'Mong', // Mongolian + 'Ougr', // Old Uyghur + 'Syrc', // Syriac +]; +const cursiveScriptRegExp = sanitizedRegExpFromScriptCodes(cursiveScriptCodes); +function charAllowsLetterSpacing(char) { + return !cursiveScriptRegExp.test(String.fromCodePoint(char)); +} +/** + * ISO 15924 script codes of scripts that allow ideographic line breaking beyond + * the CJKV scripts that are considered ideographic in Unicode 16.0.0. + */ +const ideographicBreakingScriptCodes = [ + 'Bopo', // Bopomofo + 'Hani', // Han + 'Hira', // Hiragana + 'Kana', // Katakana + 'Kits', // Khitan Small Script + 'Nshu', // Nushu + 'Tang', // Tangut + 'Yiii', // Yi +]; +const ideographicBreakingRegExp = sanitizedRegExpFromScriptCodes(ideographicBreakingScriptCodes); +function charAllowsIdeographicBreaking(char) { + // Return early for characters outside all ideographic ranges. + if (char < 0x2E80) + return false; + if (unicodeBlockLookup['CJK Compatibility Forms'](char)) + return true; + if (unicodeBlockLookup['CJK Compatibility'](char)) + return true; + if (unicodeBlockLookup['CJK Strokes'](char)) + return true; + if (unicodeBlockLookup['CJK Symbols and Punctuation'](char)) + return true; + if (unicodeBlockLookup['Enclosed CJK Letters and Months'](char)) + return true; + if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) + return true; + if (unicodeBlockLookup['Ideographic Description Characters'](char)) + return true; + if (unicodeBlockLookup['Vertical Forms'](char)) + return true; + return ideographicBreakingRegExp.test(String.fromCodePoint(char)); +} +// The following logic comes from +// . +// Keep it synchronized with +// . +// The data file denotes with “U” or “Tu” any codepoint that may be drawn +// upright in vertical text but does not distinguish between upright and +// “neutral” characters. +// Blocks in the Unicode supplementary planes are excluded from this module due +// to . +/** + * Returns true if the given Unicode codepoint identifies a character with + * upright orientation. + * + * A character has upright orientation if it is drawn upright (unrotated) + * whether the line is oriented horizontally or vertically, even if both + * adjacent characters can be rotated. For example, a Chinese character is + * always drawn upright. An uprightly oriented character causes an adjacent + * “neutral” character to be drawn upright as well. + */ +function charHasUprightVerticalOrientation(char) { + if (char === 0x02EA /* modifier letter yin departing tone mark */ || + char === 0x02EB /* modifier letter yang departing tone mark */) { + return true; + } + // Return early for characters outside all ranges whose characters remain + // upright in vertical writing mode. + if (char < 0x1100) + return false; + if (unicodeBlockLookup['CJK Compatibility Forms'](char)) { + if (!((char >= 0xFE49 /* dashed overline */ && char <= 0xFE4F) /* wavy low line */)) { + return true; + } + } + if (unicodeBlockLookup['CJK Compatibility'](char)) + return true; + if (unicodeBlockLookup['CJK Strokes'](char)) + return true; + if (unicodeBlockLookup['CJK Symbols and Punctuation'](char)) { + if (!((char >= 0x3008 /* left angle bracket */ && char <= 0x3011) /* right black lenticular bracket */) && + !((char >= 0x3014 /* left tortoise shell bracket */ && char <= 0x301F) /* low double prime quotation mark */) && + char !== 0x3030 /* wavy dash */) { + return true; + } + } + if (unicodeBlockLookup['Enclosed CJK Letters and Months'](char)) + return true; + if (unicodeBlockLookup['Ideographic Description Characters'](char)) + return true; + if (unicodeBlockLookup['Kanbun'](char)) + return true; + if (unicodeBlockLookup['Katakana'](char)) { + if (char !== 0x30FC /* katakana-hiragana prolonged sound mark */) { + return true; + } + } + if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) { + if (char !== 0xFF08 /* fullwidth left parenthesis */ && + char !== 0xFF09 /* fullwidth right parenthesis */ && + char !== 0xFF0D /* fullwidth hyphen-minus */ && + !((char >= 0xFF1A /* fullwidth colon */ && char <= 0xFF1E) /* fullwidth greater-than sign */) && + char !== 0xFF3B /* fullwidth left square bracket */ && + char !== 0xFF3D /* fullwidth right square bracket */ && + char !== 0xFF3F /* fullwidth low line */ && + !(char >= 0xFF5B /* fullwidth left curly bracket */ && char <= 0xFFDF) && + char !== 0xFFE3 /* fullwidth macron */ && + !(char >= 0xFFE8 /* halfwidth forms light vertical */ && char <= 0xFFEF)) { + return true; + } + } + if (unicodeBlockLookup['Small Form Variants'](char)) { + if (!((char >= 0xFE58 /* small em dash */ && char <= 0xFE5E) /* small right tortoise shell bracket */) && + !((char >= 0xFE63 /* small hyphen-minus */ && char <= 0xFE66) /* small equals sign */)) { + return true; + } + } + if (unicodeBlockLookup['Vertical Forms'](char)) + return true; + if (unicodeBlockLookup['Yijing Hexagram Symbols'](char)) + return true; + if ( /* Canadian Aboriginal *//\p{sc=Cans}/u.test(String.fromCodePoint(char))) + return true; + if ( /* Hangul *//\p{sc=Hang}/u.test(String.fromCodePoint(char))) + return true; + if (ideographicBreakingRegExp.test(String.fromCodePoint(char))) + return true; + return false; +} +/** + * Returns true if the given Unicode codepoint identifies a character with + * neutral orientation. + * + * A character has neutral orientation if it may be drawn rotated or unrotated + * when the line is oriented vertically, depending on the orientation of the + * adjacent characters. For example, along a vertically oriented line, the vulgar + * fraction ½ is drawn upright among Chinese characters but rotated among Latin + * letters. A neutrally oriented character does not influence whether an + * adjacent character is drawn upright or rotated. + */ +function charHasNeutralVerticalOrientation(char) { + if (unicodeBlockLookup['Latin-1 Supplement'](char)) { + if (char === 0x00A7 /* section sign */ || + char === 0x00A9 /* copyright sign */ || + char === 0x00AE /* registered sign */ || + char === 0x00B1 /* plus-minus sign */ || + char === 0x00BC /* vulgar fraction one quarter */ || + char === 0x00BD /* vulgar fraction one half */ || + char === 0x00BE /* vulgar fraction three quarters */ || + char === 0x00D7 /* multiplication sign */ || + char === 0x00F7 /* division sign */) { + return true; + } + } + if (unicodeBlockLookup['General Punctuation'](char)) { + if (char === 0x2016 /* double vertical line */ || + char === 0x2020 /* dagger */ || + char === 0x2021 /* double dagger */ || + char === 0x2030 /* per mille sign */ || + char === 0x2031 /* per ten thousand sign */ || + char === 0x203B /* reference mark */ || + char === 0x203C /* double exclamation mark */ || + char === 0x2042 /* asterism */ || + char === 0x2047 /* double question mark */ || + char === 0x2048 /* question exclamation mark */ || + char === 0x2049 /* exclamation question mark */ || + char === 0x2051 /* two asterisks aligned vertically */) { + return true; + } + } + if (unicodeBlockLookup['Letterlike Symbols'](char)) + return true; + if (unicodeBlockLookup['Number Forms'](char)) + return true; + if (unicodeBlockLookup['Miscellaneous Technical'](char)) { + if ((char >= 0x2300 /* diameter sign */ && char <= 0x2307 /* wavy line */) || + (char >= 0x230C /* bottom right crop */ && char <= 0x231F /* bottom right corner */) || + (char >= 0x2324 /* up arrowhead between two horizontal bars */ && char <= 0x2328 /* keyboard */) || + char === 0x232B /* erase to the left */ || + (char >= 0x237D /* shouldered open box */ && char <= 0x239A /* clear screen symbol */) || + (char >= 0x23BE /* dentistry symbol light vertical and top right */ && char <= 0x23CD /* square foot */) || + char === 0x23CF /* eject symbol */ || + (char >= 0x23D1 /* metrical breve */ && char <= 0x23DB /* fuse */) || + (char >= 0x23E2 /* white trapezium */ && char <= 0x23FF)) { + return true; + } + } + if (unicodeBlockLookup['Control Pictures'](char) && char !== 0x2423 /* open box */) + return true; + if (unicodeBlockLookup['Optical Character Recognition'](char)) + return true; + if (unicodeBlockLookup['Enclosed Alphanumerics'](char)) + return true; + if (unicodeBlockLookup['Geometric Shapes'](char)) + return true; + if (unicodeBlockLookup['Miscellaneous Symbols'](char)) { + if (!((char >= 0x261A /* black left pointing index */ && char <= 0x261F) /* white down pointing index */)) { + return true; + } + } + if (unicodeBlockLookup['Miscellaneous Symbols and Arrows'](char)) { + if ((char >= 0x2B12 /* square with top half black */ && char <= 0x2B2F /* white vertical ellipse */) || + (char >= 0x2B50 /* white medium star */ && char <= 0x2B59 /* heavy circled saltire */) || + (char >= 0x2BB8 /* upwards white arrow from bar with horizontal bar */ && char <= 0x2BEB)) { + return true; + } + } + if (unicodeBlockLookup['CJK Symbols and Punctuation'](char)) + return true; + if (unicodeBlockLookup['Katakana'](char)) + return true; + if (unicodeBlockLookup['Private Use Area'](char)) + return true; + if (unicodeBlockLookup['CJK Compatibility Forms'](char)) + return true; + if (unicodeBlockLookup['Small Form Variants'](char)) + return true; + if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) + return true; + if (char === 0x221E /* infinity */ || + char === 0x2234 /* therefore */ || + char === 0x2235 /* because */ || + (char >= 0x2700 /* black safety scissors */ && char <= 0x2767 /* rotated floral heart bullet */) || + (char >= 0x2776 /* dingbat negative circled digit one */ && char <= 0x2793 /* dingbat negative circled sans-serif number ten */) || + char === 0xFFFC /* object replacement character */ || + char === 0xFFFD /* replacement character */) { + return true; + } + return false; +} +/** + * Returns true if the given Unicode codepoint identifies a character with + * rotated orientation. + * + * A character has rotated orientation if it is drawn rotated when the line is + * oriented vertically, even if both adjacent characters are upright. For + * example, a Latin letter is drawn rotated along a vertical line. A rotated + * character causes an adjacent “neutral” character to be drawn rotated as well. + */ +function charHasRotatedVerticalOrientation(char) { + return !(charHasUprightVerticalOrientation(char) || + charHasNeutralVerticalOrientation(char)); +} +function charInComplexShapingScript(char) { + return /\p{sc=Arab}/u.test(String.fromCodePoint(char)); +} +/** + * ISO 15924 script codes of scripts that are primarily written horizontally + * right-to-left according to Unicode 16.0.0. + */ +const rtlScriptCodes = [ + 'Adlm', // Adlam + 'Arab', // Arabic + 'Armi', // Imperial Aramaic + 'Avst', // Avestan + 'Chrs', // Chorasmian + 'Cprt', // Cypriot + 'Egyp', // Egyptian Hieroglyphs + 'Elym', // Elymaic + 'Gara', // Garay + 'Hatr', // Hatran + 'Hebr', // Hebrew + 'Hung', // Old Hungarian + 'Khar', // Kharoshthi + 'Lydi', // Lydian + 'Mand', // Mandaic + 'Mani', // Manichaean + 'Mend', // Mende Kikakui + 'Merc', // Meroitic Cursive + 'Mero', // Meroitic Hieroglyphs + 'Narb', // Old North Arabian + 'Nbat', // Nabataean + 'Nkoo', // NKo + 'Orkh', // Old Turkic + 'Palm', // Palmyrene + 'Phli', // Inscriptional Pahlavi + 'Phlp', // Psalter Pahlavi + 'Phnx', // Phoenician + 'Prti', // Inscriptional Parthian + 'Rohg', // Hanifi Rohingya + 'Samr', // Samaritan + 'Sarb', // Old South Arabian + 'Sogo', // Old Sogdian + 'Syrc', // Syriac + 'Thaa', // Thaana + 'Todr', // Todhri + 'Yezi', // Yezidi +]; +const rtlScriptRegExp = sanitizedRegExpFromScriptCodes(rtlScriptCodes); +function charInRTLScript(char) { + return rtlScriptRegExp.test(String.fromCodePoint(char)); +} +function charInSupportedScript(char, canRenderRTL) { + // This is a rough heuristic: whether we "can render" a script + // actually depends on the properties of the font being used + // and whether differences from the ideal rendering are considered + // semantically significant. + // Even in Latin script, we "can't render" combinations such as the fi + // ligature, but we don't consider that semantically significant. + if (!canRenderRTL && charInRTLScript(char)) { + return false; + } + if ((char >= 0x0900 && char <= 0x0DFF) || + // Main blocks for Indic scripts and Sinhala + (char >= 0x0F00 && char <= 0x109F) || + // Main blocks for Tibetan and Myanmar + unicodeBlockLookup['Khmer'](char)) { + // These blocks cover common scripts that require + // complex text shaping, based on unicode script metadata: + // https://www.unicode.org/repos/cldr/trunk/common/properties/scriptMetadata.txt + // where "Web Rank <= 32" "Shaping Required = YES" + return false; + } + return true; +} +function stringContainsRTLText(chars) { + for (const char of chars) { + if (charInRTLScript(char.charCodeAt(0))) { + return true; + } + } + return false; +} +function isStringInSupportedScript(chars, canRenderRTL) { + for (const char of chars) { + if (!charInSupportedScript(char.charCodeAt(0), canRenderRTL)) { + return false; + } + } + return true; +} + +class RTLWorkerPlugin { + constructor() { + this.applyArabicShaping = null; + this.processBidirectionalText = null; + this.processStyledBidirectionalText = null; + this.pluginStatus = 'unavailable'; + this.pluginURL = null; + } + setState(state) { + this.pluginStatus = state.pluginStatus; + this.pluginURL = state.pluginURL; + } + getState() { + return { + pluginStatus: this.pluginStatus, + pluginURL: this.pluginURL + }; + } + setMethods(rtlTextPlugin) { + this.applyArabicShaping = rtlTextPlugin.applyArabicShaping; + this.processBidirectionalText = rtlTextPlugin.processBidirectionalText; + this.processStyledBidirectionalText = rtlTextPlugin.processStyledBidirectionalText; + } + isParsed() { + return this.applyArabicShaping != null && + this.processBidirectionalText != null && + this.processStyledBidirectionalText != null; + } + getPluginURL() { + return this.pluginURL; + } + getRTLTextPluginStatus() { + return this.pluginStatus; + } +} +const rtlWorkerPlugin = new RTLWorkerPlugin(); + +/** + * @internal + * A parameter that can be evaluated to a value + */ +class EvaluationParameters { + // "options" may also be another EvaluationParameters to copy, see CrossFadedProperty.possiblyEvaluate + constructor(zoom, options) { + this.zoom = zoom; + if (options) { + this.now = options.now; + this.fadeDuration = options.fadeDuration; + this.zoomHistory = options.zoomHistory; + this.transition = options.transition; + } + else { + this.now = 0; + this.fadeDuration = 0; + this.zoomHistory = new ZoomHistory(); + this.transition = {}; + } + } + isSupportedScript(str) { + return isStringInSupportedScript(str, rtlWorkerPlugin.getRTLTextPluginStatus() === 'loaded'); + } + crossFadingFactor() { + if (this.fadeDuration === 0) { + return 1; + } + else { + return Math.min((this.now - this.zoomHistory.lastIntegerZoomTime) / this.fadeDuration, 1); + } + } + getCrossfadeParameters() { + const z = this.zoom; + const fraction = z - Math.floor(z); + const t = this.crossFadingFactor(); + return z > this.zoomHistory.lastIntegerZoom ? + { fromScale: 2, toScale: 1, t: fraction + (1 - fraction) * t } : + { fromScale: 0.5, toScale: 1, t: 1 - (1 - t) * fraction }; + } +} + +/** + * @internal + * `PropertyValue` represents the value part of a property key-value unit. It's used to represent both + * paint and layout property values, and regardless of whether or not their property supports data-driven + * expressions. + * + * `PropertyValue` stores the raw input value as seen in a style or a runtime styling API call, i.e. one of the + * following: + * + * * A constant value of the type appropriate for the property + * * A function which produces a value of that type (but functions are quasi-deprecated in favor of expressions) + * * An expression which produces a value of that type + * * "undefined"/"not present", in which case the property is assumed to take on its default value. + * + * In addition to storing the original input value, `PropertyValue` also stores a normalized representation, + * effectively treating functions as if they are expressions, and constant or default values as if they are + * (constant) expressions. + */ +class PropertyValue { + constructor(property, value) { + this.property = property; + this.value = value; + this.expression = normalizePropertyExpression(value === undefined ? property.specification.default : value, property.specification); + } + isDataDriven() { + return this.expression.kind === 'source' || this.expression.kind === 'composite'; + } + possiblyEvaluate(parameters, canonical, availableImages) { + return this.property.possiblyEvaluate(this, parameters, canonical, availableImages); + } +} +/** + * @internal + * Paint properties are _transitionable_: they can change in a fluid manner, interpolating or cross-fading between + * old and new value. The duration of the transition, and the delay before it begins, is configurable. + * + * `TransitionablePropertyValue` is a compositional class that stores both the property value and that transition + * configuration. + * + * A `TransitionablePropertyValue` can calculate the next step in the evaluation chain for paint property values: + * `TransitioningPropertyValue`. + */ +class TransitionablePropertyValue { + constructor(property) { + this.property = property; + this.value = new PropertyValue(property, undefined); + } + transitioned(parameters, prior) { + return new TransitioningPropertyValue(this.property, this.value, prior, extend({}, parameters.transition, this.transition), parameters.now); + } + untransitioned() { + return new TransitioningPropertyValue(this.property, this.value, null, {}, 0); + } +} +/** + * @internal + * `Transitionable` stores a map of all (property name, `TransitionablePropertyValue`) pairs for paint properties of a + * given layer type. It can calculate the `TransitioningPropertyValue`s for all of them at once, producing a + * `Transitioning` instance for the same set of properties. + */ +class Transitionable { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultTransitionablePropertyValues); + } + getValue(name) { + return clone$9(this._values[name].value.value); + } + setValue(name, value) { + if (!Object.prototype.hasOwnProperty.call(this._values, name)) { + this._values[name] = new TransitionablePropertyValue(this._values[name].property); + } + // Note that we do not _remove_ an own property in the case where a value is being reset + // to the default: the transition might still be non-default. + this._values[name].value = new PropertyValue(this._values[name].property, value === null ? undefined : clone$9(value)); + } + getTransition(name) { + return clone$9(this._values[name].transition); + } + setTransition(name, value) { + if (!Object.prototype.hasOwnProperty.call(this._values, name)) { + this._values[name] = new TransitionablePropertyValue(this._values[name].property); + } + this._values[name].transition = clone$9(value) || undefined; + } + serialize() { + const result = {}; + for (const property of Object.keys(this._values)) { + const value = this.getValue(property); + if (value !== undefined) { + result[property] = value; + } + const transition = this.getTransition(property); + if (transition !== undefined) { + result[`${property}-transition`] = transition; + } + } + return result; + } + transitioned(parameters, prior) { + const result = new Transitioning(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].transitioned(parameters, prior._values[property]); + } + return result; + } + untransitioned() { + const result = new Transitioning(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].untransitioned(); + } + return result; + } +} +/** + * @internal + * `TransitioningPropertyValue` implements the first of two intermediate steps in the evaluation chain of a paint + * property value. In this step, transitions between old and new values are handled: as long as the transition is in + * progress, `TransitioningPropertyValue` maintains a reference to the prior value, and interpolates between it and + * the new value based on the current time and the configured transition duration and delay. The product is the next + * step in the evaluation chain: the "possibly evaluated" result type `R`. See below for more on this concept. + */ +class TransitioningPropertyValue { + constructor(property, value, prior, transition, now) { + this.property = property; + this.value = value; + this.begin = now + transition.delay || 0; + this.end = this.begin + transition.duration || 0; + if (property.specification.transition && (transition.delay || transition.duration)) { + this.prior = prior; + } + } + possiblyEvaluate(parameters, canonical, availableImages) { + const now = parameters.now || 0; + const finalValue = this.value.possiblyEvaluate(parameters, canonical, availableImages); + const prior = this.prior; + if (!prior) { + // No prior value. + return finalValue; + } + else if (now > this.end) { + // Transition from prior value is now complete. + this.prior = null; + return finalValue; + } + else if (this.value.isDataDriven()) { + // Transitions to data-driven properties are not supported. + // We snap immediately to the data-driven value so that, when we perform layout, + // we see the data-driven function and can use it to populate vertex buffers. + this.prior = null; + return finalValue; + } + else if (now < this.begin) { + // Transition hasn't started yet. + return prior.possiblyEvaluate(parameters, canonical, availableImages); + } + else { + // Interpolate between recursively-calculated prior value and final. + const t = (now - this.begin) / (this.end - this.begin); + return this.property.interpolate(prior.possiblyEvaluate(parameters, canonical, availableImages), finalValue, easeCubicInOut(t)); + } + } +} +/** + * @internal + * `Transitioning` stores a map of all (property name, `TransitioningPropertyValue`) pairs for paint properties of a + * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a + * `PossiblyEvaluated` instance for the same set of properties. + */ +class Transitioning { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultTransitioningPropertyValues); + } + possiblyEvaluate(parameters, canonical, availableImages) { + const result = new PossiblyEvaluated(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages); + } + return result; + } + hasTransition() { + for (const property of Object.keys(this._values)) { + if (this._values[property].prior) { + return true; + } + } + return false; + } +} +// ------- Layout ------- +/** + * Because layout properties are not transitionable, they have a simpler representation and evaluation chain than + * paint properties: `PropertyValue`s are possibly evaluated, producing possibly evaluated values, which are then + * fully evaluated. + * + * `Layout` stores a map of all (property name, `PropertyValue`) pairs for layout properties of a + * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a + * `PossiblyEvaluated` instance for the same set of properties. + */ +class Layout { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultPropertyValues); + } + hasValue(name) { + return this._values[name].value !== undefined; + } + getValue(name) { + return clone$9(this._values[name].value); + } + setValue(name, value) { + this._values[name] = new PropertyValue(this._values[name].property, value === null ? undefined : clone$9(value)); + } + serialize() { + const result = {}; + for (const property of Object.keys(this._values)) { + const value = this.getValue(property); + if (value !== undefined) { + result[property] = value; + } + } + return result; + } + possiblyEvaluate(parameters, canonical, availableImages) { + const result = new PossiblyEvaluated(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages); + } + return result; + } +} +/** + * @internal + * `PossiblyEvaluatedPropertyValue` is used for data-driven paint and layout property values. It holds a + * `PossiblyEvaluatedValue` and the `GlobalProperties` that were used to generate it. You're not allowed to supply + * a different set of `GlobalProperties` when performing the final evaluation because they would be ignored in the + * case where the input value was a constant or camera function. + */ +class PossiblyEvaluatedPropertyValue { + constructor(property, value, parameters) { + this.property = property; + this.value = value; + this.parameters = parameters; + } + isConstant() { + return this.value.kind === 'constant'; + } + constantOr(value) { + if (this.value.kind === 'constant') { + return this.value.value; + } + else { + return value; + } + } + evaluate(feature, featureState, canonical, availableImages) { + return this.property.evaluate(this.value, this.parameters, feature, featureState, canonical, availableImages); + } +} +/** + * @internal + * `PossiblyEvaluated` stores a map of all (property name, `R`) pairs for paint or layout properties of a + * given layer type. + */ +class PossiblyEvaluated { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultPossiblyEvaluatedValues); + } + get(name) { + return this._values[name]; + } +} +/** + * @internal + * An implementation of `Property` for properties that do not permit data-driven (source or composite) expressions. + * This restriction allows us to declare statically that the result of possibly evaluating this kind of property + * is in fact always the scalar type `T`, and can be used without further evaluating the value on a per-feature basis. + */ +class DataConstantProperty { + constructor(specification) { + this.specification = specification; + } + possiblyEvaluate(value, parameters) { + if (value.isDataDriven()) + throw new Error('Value should not be data driven'); + return value.expression.evaluate(parameters); + } + interpolate(a, b, t) { + const interpolationType = this.specification.type; + const interpolationFn = interpolate[interpolationType]; + if (interpolationFn) { + return interpolationFn(a, b, t); + } + else { + return a; + } + } +} +/** + * @internal + * An implementation of `Property` for properties that permit data-driven (source or composite) expressions. + * The result of possibly evaluating this kind of property is `PossiblyEvaluatedPropertyValue`; obtaining + * a scalar value `T` requires further evaluation on a per-feature basis. + */ +class DataDrivenProperty { + constructor(specification, overrides) { + this.specification = specification; + this.overrides = overrides; + } + possiblyEvaluate(value, parameters, canonical, availableImages) { + if (value.expression.kind === 'constant' || value.expression.kind === 'camera') { + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: value.expression.evaluate(parameters, null, {}, canonical, availableImages) }, parameters); + } + else { + return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters); + } + } + interpolate(a, b, t) { + // If either possibly-evaluated value is non-constant, give up: we aren't able to interpolate data-driven values. + if (a.value.kind !== 'constant' || b.value.kind !== 'constant') { + return a; + } + // Special case hack solely for fill-outline-color. The undefined value is subsequently handled in + // FillStyleLayer#recalculate, which sets fill-outline-color to the fill-color value if the former + // is a PossiblyEvaluatedPropertyValue containing a constant undefined value. In addition to the + // return value here, the other source of a PossiblyEvaluatedPropertyValue containing a constant + // undefined value is the "default value" for fill-outline-color held in + // `Properties#defaultPossiblyEvaluatedValues`, which serves as the prototype of + // `PossiblyEvaluated#_values`. + if (a.value.value === undefined || b.value.value === undefined) { + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: undefined }, a.parameters); + } + const interpolationType = this.specification.type; + const interpolationFn = interpolate[interpolationType]; + if (interpolationFn) { + const interpolatedValue = interpolationFn(a.value.value, b.value.value, t); + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: interpolatedValue }, a.parameters); + } + else { + return a; + } + } + evaluate(value, parameters, feature, featureState, canonical, availableImages) { + if (value.kind === 'constant') { + return value.value; + } + else { + return value.evaluate(parameters, feature, featureState, canonical, availableImages); + } + } +} +/** + * @internal + * An implementation of `Property` for data driven `line-pattern` which are transitioned by cross-fading + * rather than interpolation. + */ +class CrossFadedDataDrivenProperty extends DataDrivenProperty { + possiblyEvaluate(value, parameters, canonical, availableImages) { + if (value.value === undefined) { + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: undefined }, parameters); + } + else if (value.expression.kind === 'constant') { + const evaluatedValue = value.expression.evaluate(parameters, null, {}, canonical, availableImages); + const isImageExpression = value.property.specification.type === 'resolvedImage'; + const constantValue = isImageExpression && typeof evaluatedValue !== 'string' ? evaluatedValue.name : evaluatedValue; + const constant = this._calculate(constantValue, constantValue, constantValue, parameters); + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: constant }, parameters); + } + else if (value.expression.kind === 'camera') { + const cameraVal = this._calculate(value.expression.evaluate({ zoom: parameters.zoom - 1.0 }), value.expression.evaluate({ zoom: parameters.zoom }), value.expression.evaluate({ zoom: parameters.zoom + 1.0 }), parameters); + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: cameraVal }, parameters); + } + else { + // source or composite expression + return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters); + } + } + evaluate(value, globals, feature, featureState, canonical, availableImages) { + if (value.kind === 'source') { + const constant = value.evaluate(globals, feature, featureState, canonical, availableImages); + return this._calculate(constant, constant, constant, globals); + } + else if (value.kind === 'composite') { + return this._calculate(value.evaluate({ zoom: Math.floor(globals.zoom) - 1.0 }, feature, featureState), value.evaluate({ zoom: Math.floor(globals.zoom) }, feature, featureState), value.evaluate({ zoom: Math.floor(globals.zoom) + 1.0 }, feature, featureState), globals); + } + else { + return value.value; + } + } + _calculate(min, mid, max, parameters) { + const z = parameters.zoom; + return z > parameters.zoomHistory.lastIntegerZoom ? { from: min, to: mid } : { from: max, to: mid }; + } + interpolate(a) { + return a; + } +} +/** + * @internal + * An implementation of `Property` for `*-pattern` and `line-dasharray`, which are transitioned by cross-fading + * rather than interpolation. + */ +class CrossFadedProperty { + constructor(specification) { + this.specification = specification; + } + possiblyEvaluate(value, parameters, canonical, availableImages) { + if (value.value === undefined) { + return undefined; + } + else if (value.expression.kind === 'constant') { + const constant = value.expression.evaluate(parameters, null, {}, canonical, availableImages); + return this._calculate(constant, constant, constant, parameters); + } + else { + return this._calculate(value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom - 1.0), parameters)), value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom), parameters)), value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom + 1.0), parameters)), parameters); + } + } + _calculate(min, mid, max, parameters) { + const z = parameters.zoom; + return z > parameters.zoomHistory.lastIntegerZoom ? { from: min, to: mid } : { from: max, to: mid }; + } + interpolate(a) { + return a; + } +} +/** + * @internal + * An implementation of `Property` for `heatmap-color` and `line-gradient`. Interpolation is a no-op, and + * evaluation returns a boolean value in order to indicate its presence, but the real + * evaluation happens in StyleLayer classes. + */ +class ColorRampProperty { + constructor(specification) { + this.specification = specification; + } + possiblyEvaluate(value, parameters, canonical, availableImages) { + return !!value.expression.evaluate(parameters, null, {}, canonical, availableImages); + } + interpolate() { return false; } +} +/** + * @internal + * `Properties` holds objects containing default values for the layout or paint property set of a given + * layer type. These objects are immutable, and they are used as the prototypes for the `_values` members of + * `Transitionable`, `Transitioning`, `Layout`, and `PossiblyEvaluated`. This allows these classes to avoid + * doing work in the common case where a property has no explicit value set and should be considered to take + * on the default value: using `for (const property of Object.keys(this._values))`, they can iterate over + * only the _own_ properties of `_values`, skipping repeated calculation of transitions and possible/final + * evaluations for defaults, the result of which will always be the same. + */ +class Properties { + constructor(properties) { + this.properties = properties; + this.defaultPropertyValues = {}; + this.defaultTransitionablePropertyValues = {}; + this.defaultTransitioningPropertyValues = {}; + this.defaultPossiblyEvaluatedValues = {}; + this.overridableProperties = []; + for (const property in properties) { + const prop = properties[property]; + if (prop.specification.overridable) { + this.overridableProperties.push(property); + } + const defaultPropertyValue = this.defaultPropertyValues[property] = + new PropertyValue(prop, undefined); + const defaultTransitionablePropertyValue = this.defaultTransitionablePropertyValues[property] = + new TransitionablePropertyValue(prop); + this.defaultTransitioningPropertyValues[property] = + defaultTransitionablePropertyValue.untransitioned(); + this.defaultPossiblyEvaluatedValues[property] = + defaultPropertyValue.possiblyEvaluate({}); + } + } +} +register('DataDrivenProperty', DataDrivenProperty); +register('DataConstantProperty', DataConstantProperty); +register('CrossFadedDataDrivenProperty', CrossFadedDataDrivenProperty); +register('CrossFadedProperty', CrossFadedProperty); +register('ColorRampProperty', ColorRampProperty); + +const TRANSITION_SUFFIX = '-transition'; +/** + * A base class for style layers + */ +class StyleLayer extends Evented { + constructor(layer, properties) { + super(); + this.id = layer.id; + this.type = layer.type; + this._featureFilter = { filter: () => true, needGeometry: false }; + if (layer.type === 'custom') + return; + layer = layer; + this.metadata = layer.metadata; + this.minzoom = layer.minzoom; + this.maxzoom = layer.maxzoom; + if (layer.type !== 'background') { + this.source = layer.source; + this.sourceLayer = layer['source-layer']; + this.filter = layer.filter; + } + if (properties.layout) { + this._unevaluatedLayout = new Layout(properties.layout); + } + if (properties.paint) { + this._transitionablePaint = new Transitionable(properties.paint); + for (const property in layer.paint) { + this.setPaintProperty(property, layer.paint[property], { validate: false }); + } + for (const property in layer.layout) { + this.setLayoutProperty(property, layer.layout[property], { validate: false }); + } + this._transitioningPaint = this._transitionablePaint.untransitioned(); + //$FlowFixMe + this.paint = new PossiblyEvaluated(properties.paint); + } + } + getCrossfadeParameters() { + return this._crossfadeParameters; + } + getLayoutProperty(name) { + if (name === 'visibility') { + return this.visibility; + } + return this._unevaluatedLayout.getValue(name); + } + setLayoutProperty(name, value, options = {}) { + if (value !== null && value !== undefined) { + const key = `layers.${this.id}.layout.${name}`; + if (this._validate(validateLayoutProperty, key, name, value, options)) { + return; + } + } + if (name === 'visibility') { + this.visibility = value; + return; + } + this._unevaluatedLayout.setValue(name, value); + } + getPaintProperty(name) { + if (name.endsWith(TRANSITION_SUFFIX)) { + return this._transitionablePaint.getTransition(name.slice(0, -TRANSITION_SUFFIX.length)); + } + else { + return this._transitionablePaint.getValue(name); + } + } + setPaintProperty(name, value, options = {}) { + if (value !== null && value !== undefined) { + const key = `layers.${this.id}.paint.${name}`; + if (this._validate(validatePaintProperty, key, name, value, options)) { + return false; + } + } + if (name.endsWith(TRANSITION_SUFFIX)) { + this._transitionablePaint.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), value || undefined); + return false; + } + else { + const transitionable = this._transitionablePaint._values[name]; + const isCrossFadedProperty = transitionable.property.specification['property-type'] === 'cross-faded-data-driven'; + const wasDataDriven = transitionable.value.isDataDriven(); + const oldValue = transitionable.value; + this._transitionablePaint.setValue(name, value); + this._handleSpecialPaintPropertyUpdate(name); + const newValue = this._transitionablePaint._values[name].value; + const isDataDriven = newValue.isDataDriven(); + // if a cross-faded value is changed, we need to make sure the new icons get added to each tile's iconAtlas + // so a call to _updateLayer is necessary, and we return true from this function so it gets called in + // Style#setPaintProperty + return isDataDriven || wasDataDriven || isCrossFadedProperty || this._handleOverridablePaintPropertyUpdate(name, oldValue, newValue); + } + } + _handleSpecialPaintPropertyUpdate(_) { + // No-op; can be overridden by derived classes. + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) { + // No-op; can be overridden by derived classes. + return false; + } + isHidden(zoom) { + if (this.minzoom && zoom < this.minzoom) + return true; + if (this.maxzoom && zoom >= this.maxzoom) + return true; + return this.visibility === 'none'; + } + updateTransitions(parameters) { + this._transitioningPaint = this._transitionablePaint.transitioned(parameters, this._transitioningPaint); + } + hasTransition() { + return this._transitioningPaint.hasTransition(); + } + recalculate(parameters, availableImages) { + if (parameters.getCrossfadeParameters) { + this._crossfadeParameters = parameters.getCrossfadeParameters(); + } + if (this._unevaluatedLayout) { + this.layout = this._unevaluatedLayout.possiblyEvaluate(parameters, undefined, availableImages); + } + this.paint = this._transitioningPaint.possiblyEvaluate(parameters, undefined, availableImages); + } + serialize() { + const output = { + 'id': this.id, + 'type': this.type, + 'source': this.source, + 'source-layer': this.sourceLayer, + 'metadata': this.metadata, + 'minzoom': this.minzoom, + 'maxzoom': this.maxzoom, + 'filter': this.filter, + 'layout': this._unevaluatedLayout && this._unevaluatedLayout.serialize(), + 'paint': this._transitionablePaint && this._transitionablePaint.serialize() + }; + if (this.visibility) { + output.layout = output.layout || {}; + output.layout.visibility = this.visibility; + } + return filterObject(output, (value, key) => { + return value !== undefined && + !(key === 'layout' && !Object.keys(value).length) && + !(key === 'paint' && !Object.keys(value).length); + }); + } + _validate(validate, key, name, value, options = {}) { + if (options && options.validate === false) { + return false; + } + return emitValidationErrors(this, validate.call(validateStyle, { + key, + layerType: this.type, + objectKey: name, + value, + styleSpec: v8Spec, + // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407 + style: { glyphs: true, sprite: true } + })); + } + is3D() { + return false; + } + isTileClipped() { + return false; + } + hasOffscreenPass() { + return false; + } + resize() { + // noop + } + isStateDependent() { + for (const property in this.paint._values) { + const value = this.paint.get(property); + if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) { + continue; + } + if ((value.value.kind === 'source' || value.value.kind === 'composite') && + value.value.isStateDependent) { + return true; + } + } + return false; + } +} + +// Note: all "sizes" are measured in bytes +/** + * @internal + * A view type size + */ +const viewTypes = { + 'Int8': Int8Array, + 'Uint8': Uint8Array, + 'Int16': Int16Array, + 'Uint16': Uint16Array, + 'Int32': Int32Array, + 'Uint32': Uint32Array, + 'Float32': Float32Array +}; +/** @internal */ +class Struct { + /** + * @param structArray - The StructArray the struct is stored in + * @param index - The index of the struct in the StructArray. + */ + constructor(structArray, index) { + this._structArray = structArray; + this._pos1 = index * this.size; + this._pos2 = this._pos1 / 2; + this._pos4 = this._pos1 / 4; + this._pos8 = this._pos1 / 8; + } +} +const DEFAULT_CAPACITY = 128; +const RESIZE_MULTIPLIER = 5; +/** + * @internal + * `StructArray` provides an abstraction over `ArrayBuffer` and `TypedArray` + * making it behave like an array of typed structs. + * + * Conceptually, a StructArray is comprised of elements, i.e., instances of its + * associated struct type. Each particular struct type, together with an + * alignment size, determines the memory layout of a StructArray whose elements + * are of that type. Thus, for each such layout that we need, we have + * a corresponding StructArrayLayout class, inheriting from StructArray and + * implementing `emplaceBack()` and `_refreshViews()`. + * + * In some cases, where we need to access particular elements of a StructArray, + * we implement a more specific subclass that inherits from one of the + * StructArrayLayouts and adds a `get(i): T` accessor that returns a structured + * object whose properties are proxies into the underlying memory space for the + * i-th element. This affords the convenience of working with (seemingly) plain + * Javascript objects without the overhead of serializing/deserializing them + * into ArrayBuffers for efficient web worker transfer. + */ +class StructArray { + constructor() { + this.isTransferred = false; + this.capacity = -1; + this.resize(0); + } + /** + * Serialize a StructArray instance. Serializes both the raw data and the + * metadata needed to reconstruct the StructArray base class during + * deserialization. + */ + static serialize(array, transferables) { + array._trim(); + if (transferables) { + array.isTransferred = true; + transferables.push(array.arrayBuffer); + } + return { + length: array.length, + arrayBuffer: array.arrayBuffer, + }; + } + static deserialize(input) { + const structArray = Object.create(this.prototype); + structArray.arrayBuffer = input.arrayBuffer; + structArray.length = input.length; + structArray.capacity = input.arrayBuffer.byteLength / structArray.bytesPerElement; + structArray._refreshViews(); + return structArray; + } + /** + * Resize the array to discard unused capacity. + */ + _trim() { + if (this.length !== this.capacity) { + this.capacity = this.length; + this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement); + this._refreshViews(); + } + } + /** + * Resets the length of the array to 0 without de-allocating capacity. + */ + clear() { + this.length = 0; + } + /** + * Resize the array. + * If `n` is greater than the current length then additional elements with undefined values are added. + * If `n` is less than the current length then the array will be reduced to the first `n` elements. + * @param n - The new size of the array. + */ + resize(n) { + this.reserve(n); + this.length = n; + } + /** + * Indicate a planned increase in size, so that any necessary allocation may + * be done once, ahead of time. + * @param n - The expected size of the array. + */ + reserve(n) { + if (n > this.capacity) { + this.capacity = Math.max(n, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY); + this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement); + const oldUint8Array = this.uint8; + this._refreshViews(); + if (oldUint8Array) + this.uint8.set(oldUint8Array); + } + } + /** + * Create TypedArray views for the current ArrayBuffer. + */ + _refreshViews() { + throw new Error('_refreshViews() must be implemented by each concrete StructArray layout'); + } +} +/** + * Given a list of member fields, create a full StructArrayLayout, in + * particular calculating the correct byte offset for each field. This data + * is used at build time to generate StructArrayLayout_*#emplaceBack() and + * other accessors, and at runtime for binding vertex buffer attributes. + */ +function createLayout(members, alignment = 1) { + let offset = 0; + let maxSize = 0; + const layoutMembers = members.map((member) => { + const typeSize = sizeOf(member.type); + const memberOffset = offset = align$1(offset, Math.max(alignment, typeSize)); + const components = member.components || 1; + maxSize = Math.max(maxSize, typeSize); + offset += typeSize * components; + return { + name: member.name, + type: member.type, + components, + offset: memberOffset, + }; + }); + const size = align$1(offset, Math.max(maxSize, alignment)); + return { + members: layoutMembers, + size, + alignment + }; +} +function sizeOf(type) { + return viewTypes[type].BYTES_PER_ELEMENT; +} +function align$1(offset, size) { + return Math.ceil(offset / size) * size; +} + +// This file is generated. Edit build/generate-struct-arrays.ts, then run `npm run codegen`. +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * + */ +class StructArrayLayout2i4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1); + } + emplace(i, v0, v1) { + const o2 = i * 2; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + return i; + } +} +StructArrayLayout2i4.prototype.bytesPerElement = 4; +register('StructArrayLayout2i4', StructArrayLayout2i4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[3] + * + */ +class StructArrayLayout3i6 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o2 = i * 3; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + return i; + } +} +StructArrayLayout3i6.prototype.bytesPerElement = 6; +register('StructArrayLayout3i6', StructArrayLayout3i6); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[4] + * + */ +class StructArrayLayout4i8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3); + } + emplace(i, v0, v1, v2, v3) { + const o2 = i * 4; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + return i; + } +} +StructArrayLayout4i8.prototype.bytesPerElement = 8; +register('StructArrayLayout4i8', StructArrayLayout4i8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Int16[4] + * + */ +class StructArrayLayout2i4i12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o2 = i * 6; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + return i; + } +} +StructArrayLayout2i4i12.prototype.bytesPerElement = 12; +register('StructArrayLayout2i4i12', StructArrayLayout2i4i12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Uint8[4] + * + */ +class StructArrayLayout2i4ub8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o2 = i * 4; + const o1 = i * 8; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.uint8[o1 + 4] = v2; + this.uint8[o1 + 5] = v3; + this.uint8[o1 + 6] = v4; + this.uint8[o1 + 7] = v5; + return i; + } +} +StructArrayLayout2i4ub8.prototype.bytesPerElement = 8; +register('StructArrayLayout2i4ub8', StructArrayLayout2i4ub8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[2] + * + */ +class StructArrayLayout2f8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1); + } + emplace(i, v0, v1) { + const o4 = i * 2; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + return i; + } +} +StructArrayLayout2f8.prototype.bytesPerElement = 8; +register('StructArrayLayout2f8', StructArrayLayout2f8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[10] + * + */ +class StructArrayLayout10ui20 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) { + const o2 = i * 10; + this.uint16[o2 + 0] = v0; + this.uint16[o2 + 1] = v1; + this.uint16[o2 + 2] = v2; + this.uint16[o2 + 3] = v3; + this.uint16[o2 + 4] = v4; + this.uint16[o2 + 5] = v5; + this.uint16[o2 + 6] = v6; + this.uint16[o2 + 7] = v7; + this.uint16[o2 + 8] = v8; + this.uint16[o2 + 9] = v9; + return i; + } +} +StructArrayLayout10ui20.prototype.bytesPerElement = 20; +register('StructArrayLayout10ui20', StructArrayLayout10ui20); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[4] + * [8] - Uint16[4] + * [16] - Int16[4] + * + */ +class StructArrayLayout4i4ui4i24 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) { + const o2 = i * 12; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.uint16[o2 + 4] = v4; + this.uint16[o2 + 5] = v5; + this.uint16[o2 + 6] = v6; + this.uint16[o2 + 7] = v7; + this.int16[o2 + 8] = v8; + this.int16[o2 + 9] = v9; + this.int16[o2 + 10] = v10; + this.int16[o2 + 11] = v11; + return i; + } +} +StructArrayLayout4i4ui4i24.prototype.bytesPerElement = 24; +register('StructArrayLayout4i4ui4i24', StructArrayLayout4i4ui4i24); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[3] + * + */ +class StructArrayLayout3f12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o4 = i * 3; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + return i; + } +} +StructArrayLayout3f12.prototype.bytesPerElement = 12; +register('StructArrayLayout3f12', StructArrayLayout3f12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint32[1] + * + */ +class StructArrayLayout1ul4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + } + emplaceBack(v0) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0); + } + emplace(i, v0) { + const o4 = i * 1; + this.uint32[o4 + 0] = v0; + return i; + } +} +StructArrayLayout1ul4.prototype.bytesPerElement = 4; +register('StructArrayLayout1ul4', StructArrayLayout1ul4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[6] + * [12] - Uint32[1] + * [16] - Uint16[2] + * + */ +class StructArrayLayout6i1ul2ui20 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8) { + const o2 = i * 10; + const o4 = i * 5; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + this.uint32[o4 + 3] = v6; + this.uint16[o2 + 8] = v7; + this.uint16[o2 + 9] = v8; + return i; + } +} +StructArrayLayout6i1ul2ui20.prototype.bytesPerElement = 20; +register('StructArrayLayout6i1ul2ui20', StructArrayLayout6i1ul2ui20); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Int16[2] + * [8] - Int16[2] + * + */ +class StructArrayLayout2i2i2i12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o2 = i * 6; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + return i; + } +} +StructArrayLayout2i2i2i12.prototype.bytesPerElement = 12; +register('StructArrayLayout2i2i2i12', StructArrayLayout2i2i2i12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[2] + * [8] - Float32[1] + * [12] - Int16[2] + * + */ +class StructArrayLayout2f1f2i16 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4); + } + emplace(i, v0, v1, v2, v3, v4) { + const o4 = i * 4; + const o2 = i * 8; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + this.int16[o2 + 6] = v3; + this.int16[o2 + 7] = v4; + return i; + } +} +StructArrayLayout2f1f2i16.prototype.bytesPerElement = 16; +register('StructArrayLayout2f1f2i16', StructArrayLayout2f1f2i16); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint8[2] + * [4] - Float32[2] + * [12] - Int16[2] + * + */ +class StructArrayLayout2ub2f2i16 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o1 = i * 16; + const o4 = i * 4; + const o2 = i * 8; + this.uint8[o1 + 0] = v0; + this.uint8[o1 + 1] = v1; + this.float32[o4 + 1] = v2; + this.float32[o4 + 2] = v3; + this.int16[o2 + 6] = v4; + this.int16[o2 + 7] = v5; + return i; + } +} +StructArrayLayout2ub2f2i16.prototype.bytesPerElement = 16; +register('StructArrayLayout2ub2f2i16', StructArrayLayout2ub2f2i16); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[3] + * + */ +class StructArrayLayout3ui6 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o2 = i * 3; + this.uint16[o2 + 0] = v0; + this.uint16[o2 + 1] = v1; + this.uint16[o2 + 2] = v2; + return i; + } +} +StructArrayLayout3ui6.prototype.bytesPerElement = 6; +register('StructArrayLayout3ui6', StructArrayLayout3ui6); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Uint16[2] + * [8] - Uint32[3] + * [20] - Uint16[3] + * [28] - Float32[2] + * [36] - Uint8[3] + * [40] - Uint32[1] + * [44] - Int16[1] + * + */ +class StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) { + const o2 = i * 24; + const o4 = i * 12; + const o1 = i * 48; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.uint16[o2 + 2] = v2; + this.uint16[o2 + 3] = v3; + this.uint32[o4 + 2] = v4; + this.uint32[o4 + 3] = v5; + this.uint32[o4 + 4] = v6; + this.uint16[o2 + 10] = v7; + this.uint16[o2 + 11] = v8; + this.uint16[o2 + 12] = v9; + this.float32[o4 + 7] = v10; + this.float32[o4 + 8] = v11; + this.uint8[o1 + 36] = v12; + this.uint8[o1 + 37] = v13; + this.uint8[o1 + 38] = v14; + this.uint32[o4 + 10] = v15; + this.int16[o2 + 22] = v16; + return i; + } +} +StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48.prototype.bytesPerElement = 48; +register('StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48', StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[8] + * [16] - Uint16[15] + * [48] - Uint32[1] + * [52] - Float32[2] + * [60] - Uint16[2] + * + */ +class StructArrayLayout8i15ui1ul2f2ui64 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(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) { + const i = this.length; + this.resize(i + 1); + 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); + } + 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) { + const o2 = i * 32; + const o4 = i * 16; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + this.int16[o2 + 6] = v6; + this.int16[o2 + 7] = v7; + this.uint16[o2 + 8] = v8; + this.uint16[o2 + 9] = v9; + this.uint16[o2 + 10] = v10; + this.uint16[o2 + 11] = v11; + this.uint16[o2 + 12] = v12; + this.uint16[o2 + 13] = v13; + this.uint16[o2 + 14] = v14; + this.uint16[o2 + 15] = v15; + this.uint16[o2 + 16] = v16; + this.uint16[o2 + 17] = v17; + this.uint16[o2 + 18] = v18; + this.uint16[o2 + 19] = v19; + this.uint16[o2 + 20] = v20; + this.uint16[o2 + 21] = v21; + this.uint16[o2 + 22] = v22; + this.uint32[o4 + 12] = v23; + this.float32[o4 + 13] = v24; + this.float32[o4 + 14] = v25; + this.uint16[o2 + 30] = v26; + this.uint16[o2 + 31] = v27; + return i; + } +} +StructArrayLayout8i15ui1ul2f2ui64.prototype.bytesPerElement = 64; +register('StructArrayLayout8i15ui1ul2f2ui64', StructArrayLayout8i15ui1ul2f2ui64); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[1] + * + */ +class StructArrayLayout1f4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0); + } + emplace(i, v0) { + const o4 = i * 1; + this.float32[o4 + 0] = v0; + return i; + } +} +StructArrayLayout1f4.prototype.bytesPerElement = 4; +register('StructArrayLayout1f4', StructArrayLayout1f4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[1] + * [4] - Float32[2] + * + */ +class StructArrayLayout1ui2f12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o2 = i * 6; + const o4 = i * 3; + this.uint16[o2 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + return i; + } +} +StructArrayLayout1ui2f12.prototype.bytesPerElement = 12; +register('StructArrayLayout1ui2f12', StructArrayLayout1ui2f12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint32[1] + * [4] - Uint16[2] + * + */ +class StructArrayLayout1ul2ui8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o4 = i * 2; + const o2 = i * 4; + this.uint32[o4 + 0] = v0; + this.uint16[o2 + 2] = v1; + this.uint16[o2 + 3] = v2; + return i; + } +} +StructArrayLayout1ul2ui8.prototype.bytesPerElement = 8; +register('StructArrayLayout1ul2ui8', StructArrayLayout1ul2ui8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[2] + * + */ +class StructArrayLayout2ui4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1); + } + emplace(i, v0, v1) { + const o2 = i * 2; + this.uint16[o2 + 0] = v0; + this.uint16[o2 + 1] = v1; + return i; + } +} +StructArrayLayout2ui4.prototype.bytesPerElement = 4; +register('StructArrayLayout2ui4', StructArrayLayout2ui4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[1] + * + */ +class StructArrayLayout1ui2 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0); + } + emplace(i, v0) { + const o2 = i * 1; + this.uint16[o2 + 0] = v0; + return i; + } +} +StructArrayLayout1ui2.prototype.bytesPerElement = 2; +register('StructArrayLayout1ui2', StructArrayLayout1ui2); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[4] + * + */ +class StructArrayLayout4f16 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3); + } + emplace(i, v0, v1, v2, v3) { + const o4 = i * 4; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + this.float32[o4 + 3] = v3; + return i; + } +} +StructArrayLayout4f16.prototype.bytesPerElement = 16; +register('StructArrayLayout4f16', StructArrayLayout4f16); +/** @internal */ +class CollisionBoxStruct extends Struct { + get anchorPointX() { return this._structArray.int16[this._pos2 + 0]; } + get anchorPointY() { return this._structArray.int16[this._pos2 + 1]; } + get x1() { return this._structArray.int16[this._pos2 + 2]; } + get y1() { return this._structArray.int16[this._pos2 + 3]; } + get x2() { return this._structArray.int16[this._pos2 + 4]; } + get y2() { return this._structArray.int16[this._pos2 + 5]; } + get featureIndex() { return this._structArray.uint32[this._pos4 + 3]; } + get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 8]; } + get bucketIndex() { return this._structArray.uint16[this._pos2 + 9]; } + get anchorPoint() { return new Point$2(this.anchorPointX, this.anchorPointY); } +} +CollisionBoxStruct.prototype.size = 20; +/** @internal */ +class CollisionBoxArray extends StructArrayLayout6i1ul2ui20 { + /** + * Return the CollisionBoxStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new CollisionBoxStruct(this, index); + } +} +register('CollisionBoxArray', CollisionBoxArray); +/** @internal */ +class PlacedSymbolStruct extends Struct { + get anchorX() { return this._structArray.int16[this._pos2 + 0]; } + get anchorY() { return this._structArray.int16[this._pos2 + 1]; } + get glyphStartIndex() { return this._structArray.uint16[this._pos2 + 2]; } + get numGlyphs() { return this._structArray.uint16[this._pos2 + 3]; } + get vertexStartIndex() { return this._structArray.uint32[this._pos4 + 2]; } + get lineStartIndex() { return this._structArray.uint32[this._pos4 + 3]; } + get lineLength() { return this._structArray.uint32[this._pos4 + 4]; } + get segment() { return this._structArray.uint16[this._pos2 + 10]; } + get lowerSize() { return this._structArray.uint16[this._pos2 + 11]; } + get upperSize() { return this._structArray.uint16[this._pos2 + 12]; } + get lineOffsetX() { return this._structArray.float32[this._pos4 + 7]; } + get lineOffsetY() { return this._structArray.float32[this._pos4 + 8]; } + get writingMode() { return this._structArray.uint8[this._pos1 + 36]; } + get placedOrientation() { return this._structArray.uint8[this._pos1 + 37]; } + set placedOrientation(x) { this._structArray.uint8[this._pos1 + 37] = x; } + get hidden() { return this._structArray.uint8[this._pos1 + 38]; } + set hidden(x) { this._structArray.uint8[this._pos1 + 38] = x; } + get crossTileID() { return this._structArray.uint32[this._pos4 + 10]; } + set crossTileID(x) { this._structArray.uint32[this._pos4 + 10] = x; } + get associatedIconIndex() { return this._structArray.int16[this._pos2 + 22]; } +} +PlacedSymbolStruct.prototype.size = 48; +/** @internal */ +class PlacedSymbolArray extends StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 { + /** + * Return the PlacedSymbolStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new PlacedSymbolStruct(this, index); + } +} +register('PlacedSymbolArray', PlacedSymbolArray); +/** @internal */ +class SymbolInstanceStruct extends Struct { + get anchorX() { return this._structArray.int16[this._pos2 + 0]; } + get anchorY() { return this._structArray.int16[this._pos2 + 1]; } + get rightJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 2]; } + get centerJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 3]; } + get leftJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 4]; } + get verticalPlacedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 5]; } + get placedIconSymbolIndex() { return this._structArray.int16[this._pos2 + 6]; } + get verticalPlacedIconSymbolIndex() { return this._structArray.int16[this._pos2 + 7]; } + get key() { return this._structArray.uint16[this._pos2 + 8]; } + get textBoxStartIndex() { return this._structArray.uint16[this._pos2 + 9]; } + get textBoxEndIndex() { return this._structArray.uint16[this._pos2 + 10]; } + get verticalTextBoxStartIndex() { return this._structArray.uint16[this._pos2 + 11]; } + get verticalTextBoxEndIndex() { return this._structArray.uint16[this._pos2 + 12]; } + get iconBoxStartIndex() { return this._structArray.uint16[this._pos2 + 13]; } + get iconBoxEndIndex() { return this._structArray.uint16[this._pos2 + 14]; } + get verticalIconBoxStartIndex() { return this._structArray.uint16[this._pos2 + 15]; } + get verticalIconBoxEndIndex() { return this._structArray.uint16[this._pos2 + 16]; } + get featureIndex() { return this._structArray.uint16[this._pos2 + 17]; } + get numHorizontalGlyphVertices() { return this._structArray.uint16[this._pos2 + 18]; } + get numVerticalGlyphVertices() { return this._structArray.uint16[this._pos2 + 19]; } + get numIconVertices() { return this._structArray.uint16[this._pos2 + 20]; } + get numVerticalIconVertices() { return this._structArray.uint16[this._pos2 + 21]; } + get useRuntimeCollisionCircles() { return this._structArray.uint16[this._pos2 + 22]; } + get crossTileID() { return this._structArray.uint32[this._pos4 + 12]; } + set crossTileID(x) { this._structArray.uint32[this._pos4 + 12] = x; } + get textBoxScale() { return this._structArray.float32[this._pos4 + 13]; } + get collisionCircleDiameter() { return this._structArray.float32[this._pos4 + 14]; } + get textAnchorOffsetStartIndex() { return this._structArray.uint16[this._pos2 + 30]; } + get textAnchorOffsetEndIndex() { return this._structArray.uint16[this._pos2 + 31]; } +} +SymbolInstanceStruct.prototype.size = 64; +/** @internal */ +class SymbolInstanceArray extends StructArrayLayout8i15ui1ul2f2ui64 { + /** + * Return the SymbolInstanceStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new SymbolInstanceStruct(this, index); + } +} +register('SymbolInstanceArray', SymbolInstanceArray); +/** @internal */ +class GlyphOffsetArray extends StructArrayLayout1f4 { + getoffsetX(index) { return this.float32[index * 1 + 0]; } +} +register('GlyphOffsetArray', GlyphOffsetArray); +/** @internal */ +class SymbolLineVertexArray extends StructArrayLayout3i6 { + getx(index) { return this.int16[index * 3 + 0]; } + gety(index) { return this.int16[index * 3 + 1]; } + gettileUnitDistanceFromAnchor(index) { return this.int16[index * 3 + 2]; } +} +register('SymbolLineVertexArray', SymbolLineVertexArray); +/** @internal */ +class TextAnchorOffsetStruct extends Struct { + get textAnchor() { return this._structArray.uint16[this._pos2 + 0]; } + get textOffset0() { return this._structArray.float32[this._pos4 + 1]; } + get textOffset1() { return this._structArray.float32[this._pos4 + 2]; } +} +TextAnchorOffsetStruct.prototype.size = 12; +/** @internal */ +class TextAnchorOffsetArray extends StructArrayLayout1ui2f12 { + /** + * Return the TextAnchorOffsetStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new TextAnchorOffsetStruct(this, index); + } +} +register('TextAnchorOffsetArray', TextAnchorOffsetArray); +/** @internal */ +class FeatureIndexStruct extends Struct { + get featureIndex() { return this._structArray.uint32[this._pos4 + 0]; } + get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 2]; } + get bucketIndex() { return this._structArray.uint16[this._pos2 + 3]; } +} +FeatureIndexStruct.prototype.size = 8; +/** @internal */ +class FeatureIndexArray extends StructArrayLayout1ul2ui8 { + /** + * Return the FeatureIndexStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new FeatureIndexStruct(this, index); + } +} +register('FeatureIndexArray', FeatureIndexArray); +class PosArray extends StructArrayLayout2i4 { +} +class Pos3dArray extends StructArrayLayout3i6 { +} +class RasterBoundsArray extends StructArrayLayout4i8 { +} +class CircleLayoutArray extends StructArrayLayout2i4 { +} +class FillLayoutArray extends StructArrayLayout2i4 { +} +class FillExtrusionLayoutArray extends StructArrayLayout2i4i12 { +} +class HeatmapLayoutArray extends StructArrayLayout2i4 { +} +class LineLayoutArray extends StructArrayLayout2i4ub8 { +} +class LineExtLayoutArray extends StructArrayLayout2f8 { +} +class PatternLayoutArray extends StructArrayLayout10ui20 { +} +class SymbolLayoutArray extends StructArrayLayout4i4ui4i24 { +} +class SymbolDynamicLayoutArray extends StructArrayLayout3f12 { +} +class SymbolOpacityArray extends StructArrayLayout1ul4 { +} +class CollisionBoxLayoutArray extends StructArrayLayout2i2i2i12 { +} +class CollisionCircleLayoutArray extends StructArrayLayout2f1f2i16 { +} +class CollisionVertexArray extends StructArrayLayout2ub2f2i16 { +} +class QuadTriangleArray extends StructArrayLayout3ui6 { +} +class TriangleIndexArray extends StructArrayLayout3ui6 { +} +class LineIndexArray extends StructArrayLayout2ui4 { +} +class LineStripIndexArray extends StructArrayLayout1ui2 { +} + +const layout$6 = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' } +], 4); +const { members: members$4, size: size$4, alignment: alignment$4 } = layout$6; + +/** + * @internal + * Used for calculations on vector segments + */ +class SegmentVector { + constructor(segments = []) { + this.segments = segments; + } + prepareSegment(numVertices, layoutVertexArray, indexArray, sortKey) { + let segment = this.segments[this.segments.length - 1]; + if (numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) + warnOnce(`Max vertices per segment is ${SegmentVector.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${numVertices}`); + if (!segment || segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH || segment.sortKey !== sortKey) { + segment = { + vertexOffset: layoutVertexArray.length, + primitiveOffset: indexArray.length, + vertexLength: 0, + primitiveLength: 0 + }; + if (sortKey !== undefined) + segment.sortKey = sortKey; + this.segments.push(segment); + } + return segment; + } + get() { + return this.segments; + } + destroy() { + for (const segment of this.segments) { + for (const k in segment.vaos) { + segment.vaos[k].destroy(); + } + } + } + static simpleSegment(vertexOffset, primitiveOffset, vertexLength, primitiveLength) { + return new SegmentVector([{ + vertexOffset, + primitiveOffset, + vertexLength, + primitiveLength, + vaos: {}, + sortKey: 0 + }]); + } +} +/** + * The maximum size of a vertex array. This limit is imposed by WebGL's 16 bit + * addressing of vertex buffers. + */ +SegmentVector.MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1; +register('SegmentVector', SegmentVector); + +/** + * Packs two numbers, interpreted as 8-bit unsigned integers, into a single + * float. Unpack them in the shader using the `unpack_float()` function, + * defined in _prelude.vertex.glsl + */ +function packUint8ToFloat(a, b) { + // coerce a and b to 8-bit ints + a = clamp$1(Math.floor(a), 0, 255); + b = clamp$1(Math.floor(b), 0, 255); + return 256 * a + b; +} + +const patternAttributes = createLayout([ + // [tl.x, tl.y, br.x, br.y] + { name: 'a_pattern_from', components: 4, type: 'Uint16' }, + { name: 'a_pattern_to', components: 4, type: 'Uint16' }, + { name: 'a_pixel_ratio_from', components: 1, type: 'Uint16' }, + { name: 'a_pixel_ratio_to', components: 1, type: 'Uint16' }, +]); + +var murmurhashJs$1 = {exports: {}}; + +var murmurhash3_gc$2 = {exports: {}}; + +/** + * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} key ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ +var murmurhash3_gc = murmurhash3_gc$2.exports; + +(function (module) { + function murmurhash3_32_gc(key, seed) { + var remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i; + + remainder = key.length & 3; // key.length % 4 + bytes = key.length - remainder; + h1 = seed; + c1 = 0xcc9e2d51; + c2 = 0x1b873593; + i = 0; + + while (i < bytes) { + k1 = + ((key.charCodeAt(i) & 0xff)) | + ((key.charCodeAt(++i) & 0xff) << 8) | + ((key.charCodeAt(++i) & 0xff) << 16) | + ((key.charCodeAt(++i) & 0xff) << 24); + ++i; + + k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff; + + h1 ^= k1; + h1 = (h1 << 13) | (h1 >>> 19); + h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff; + h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16)); + } + + k1 = 0; + + switch (remainder) { + case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; + case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; + case 1: k1 ^= (key.charCodeAt(i) & 0xff); + + k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; + h1 ^= k1; + } + + h1 ^= key.length; + + h1 ^= h1 >>> 16; + h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; + h1 ^= h1 >>> 13; + h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff; + h1 ^= h1 >>> 16; + + return h1 >>> 0; + } + + if('object' !== "undefined") { + module.exports = murmurhash3_32_gc; + } +} (murmurhash3_gc$2)); + +var murmurhash3_gcExports = murmurhash3_gc$2.exports; +var murmurhash3_gc$1 = /*@__PURE__*/getDefaultExportFromCjs$1(murmurhash3_gcExports); + +var murmurhash2_gc$2 = {exports: {}}; + +/** + * JS Implementation of MurmurHash2 + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} str ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ +var murmurhash2_gc = murmurhash2_gc$2.exports; + +(function (module) { + function murmurhash2_32_gc(str, seed) { + var + l = str.length, + h = seed ^ l, + i = 0, + k; + + while (l >= 4) { + k = + ((str.charCodeAt(i) & 0xff)) | + ((str.charCodeAt(++i) & 0xff) << 8) | + ((str.charCodeAt(++i) & 0xff) << 16) | + ((str.charCodeAt(++i) & 0xff) << 24); + + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + k ^= k >>> 24; + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; + + l -= 4; + ++i; + } + + switch (l) { + case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; + case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; + case 1: h ^= (str.charCodeAt(i) & 0xff); + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + } + + h ^= h >>> 13; + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + h ^= h >>> 15; + + return h >>> 0; + } + + if('object' !== undefined) { + module.exports = murmurhash2_32_gc; + } +} (murmurhash2_gc$2)); + +var murmurhash2_gcExports = murmurhash2_gc$2.exports; +var murmurhash2_gc$1 = /*@__PURE__*/getDefaultExportFromCjs$1(murmurhash2_gcExports); + +var murmurhashJs = murmurhashJs$1.exports; + +var murmur3 = murmurhash3_gcExports; +var murmur2 = murmurhash2_gcExports; + +murmurhashJs$1.exports = murmur3; +var murmur3_1 = murmurhashJs$1.exports.murmur3 = murmur3; +var murmur2_1 = murmurhashJs$1.exports.murmur2 = murmur2; + +var murmurhashJsExports = murmurhashJs$1.exports; +var murmur3$1 = /*@__PURE__*/getDefaultExportFromCjs$1(murmurhashJsExports); + +// A transferable data structure that maps feature ids to their indices and buffer offsets +class FeaturePositionMap { + constructor() { + this.ids = []; + this.positions = []; + this.indexed = false; + } + add(id, index, start, end) { + this.ids.push(getNumericId(id)); + this.positions.push(index, start, end); + } + getPositions(id) { + if (!this.indexed) + throw new Error('Trying to get index, but feature positions are not indexed'); + const intId = getNumericId(id); + // binary search for the first occurrence of id in this.ids; + // relies on ids/positions being sorted by id, which happens in serialization + let i = 0; + let j = this.ids.length - 1; + while (i < j) { + const m = (i + j) >> 1; + if (this.ids[m] >= intId) { + j = m; + } + else { + i = m + 1; + } + } + const positions = []; + while (this.ids[i] === intId) { + const index = this.positions[3 * i]; + const start = this.positions[3 * i + 1]; + const end = this.positions[3 * i + 2]; + positions.push({ index, start, end }); + i++; + } + return positions; + } + static serialize(map, transferables) { + const ids = new Float64Array(map.ids); + const positions = new Uint32Array(map.positions); + sort$1(ids, positions, 0, ids.length - 1); + if (transferables) { + transferables.push(ids.buffer, positions.buffer); + } + return { ids, positions }; + } + static deserialize(obj) { + const map = new FeaturePositionMap(); + // after transferring, we only use these arrays statically (no pushes), + // so TypedArray vs Array distinction that flow points out doesn't matter + map.ids = obj.ids; + map.positions = obj.positions; + map.indexed = true; + return map; + } +} +function getNumericId(value) { + const numValue = +value; + if (!isNaN(numValue) && numValue <= Number.MAX_SAFE_INTEGER) { + return numValue; + } + return murmur3$1(String(value)); +} +// custom quicksort that sorts ids, indices and offsets together (by ids) +// uses Hoare partitioning & manual tail call optimization to avoid worst case scenarios +function sort$1(ids, positions, left, right) { + while (left < right) { + const pivot = ids[(left + right) >> 1]; + let i = left - 1; + let j = right + 1; + while (true) { + do + i++; + while (ids[i] < pivot); + do + j--; + while (ids[j] > pivot); + if (i >= j) + break; + swap$1(ids, i, j); + swap$1(positions, 3 * i, 3 * j); + swap$1(positions, 3 * i + 1, 3 * j + 1); + swap$1(positions, 3 * i + 2, 3 * j + 2); + } + if (j - left < right - j) { + sort$1(ids, positions, left, j); + left = j + 1; + } + else { + sort$1(ids, positions, j + 1, right); + right = j; + } + } +} +function swap$1(arr, i, j) { + const tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} +register('FeaturePositionMap', FeaturePositionMap); + +/** + * @internal + * A base uniform abstract class + */ +class Uniform { + constructor(context, location) { + this.gl = context.gl; + this.location = location; + } +} +class Uniform1i extends Uniform { + constructor(context, location) { + super(context, location); + this.current = 0; + } + set(v) { + if (this.current !== v) { + this.current = v; + this.gl.uniform1i(this.location, v); + } + } +} +class Uniform1f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = 0; + } + set(v) { + if (this.current !== v) { + this.current = v; + this.gl.uniform1f(this.location, v); + } + } +} +class Uniform2f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = [0, 0]; + } + set(v) { + if (v[0] !== this.current[0] || v[1] !== this.current[1]) { + this.current = v; + this.gl.uniform2f(this.location, v[0], v[1]); + } + } +} +class Uniform3f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = [0, 0, 0]; + } + set(v) { + if (v[0] !== this.current[0] || v[1] !== this.current[1] || v[2] !== this.current[2]) { + this.current = v; + this.gl.uniform3f(this.location, v[0], v[1], v[2]); + } + } +} +class Uniform4f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = [0, 0, 0, 0]; + } + set(v) { + if (v[0] !== this.current[0] || v[1] !== this.current[1] || + v[2] !== this.current[2] || v[3] !== this.current[3]) { + this.current = v; + this.gl.uniform4f(this.location, v[0], v[1], v[2], v[3]); + } + } +} +class UniformColor extends Uniform { + constructor(context, location) { + super(context, location); + this.current = Color.transparent; + } + set(v) { + if (v.r !== this.current.r || v.g !== this.current.g || + v.b !== this.current.b || v.a !== this.current.a) { + this.current = v; + this.gl.uniform4f(this.location, v.r, v.g, v.b, v.a); + } + } +} +const emptyMat4 = new Float32Array(16); +class UniformMatrix4f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = emptyMat4; + } + set(v) { + // The vast majority of matrix comparisons that will trip this set + // happen at i=12 or i=0, so we check those first to avoid lots of + // unnecessary iteration: + if (v[12] !== this.current[12] || v[0] !== this.current[0]) { + this.current = v; + this.gl.uniformMatrix4fv(this.location, false, v); + return; + } + for (let i = 1; i < 16; i++) { + if (v[i] !== this.current[i]) { + this.current = v; + this.gl.uniformMatrix4fv(this.location, false, v); + break; + } + } + } +} + +function packColor(color) { + return [ + packUint8ToFloat(255 * color.r, 255 * color.g), + packUint8ToFloat(255 * color.b, 255 * color.a) + ]; +} +class ConstantBinder { + constructor(value, names, type) { + this.value = value; + this.uniformNames = names.map(name => `u_${name}`); + this.type = type; + } + setUniform(uniform, globals, currentValue) { + uniform.set(currentValue.constantOr(this.value)); + } + getBinding(context, location, _) { + return (this.type === 'color') ? + new UniformColor(context, location) : + new Uniform1f(context, location); + } +} +class CrossFadedConstantBinder { + constructor(value, names) { + this.uniformNames = names.map(name => `u_${name}`); + this.patternFrom = null; + this.patternTo = null; + this.pixelRatioFrom = 1.0; + this.pixelRatioTo = 1.0; + } + setConstantPatternPositions(posTo, posFrom) { + this.pixelRatioFrom = posFrom.pixelRatio; + this.pixelRatioTo = posTo.pixelRatio; + this.patternFrom = posFrom.tlbr; + this.patternTo = posTo.tlbr; + } + setUniform(uniform, globals, currentValue, uniformName) { + const pos = uniformName === 'u_pattern_to' ? this.patternTo : + uniformName === 'u_pattern_from' ? this.patternFrom : + uniformName === 'u_pixel_ratio_to' ? this.pixelRatioTo : + uniformName === 'u_pixel_ratio_from' ? this.pixelRatioFrom : null; + if (pos) + uniform.set(pos); + } + getBinding(context, location, name) { + return name.substr(0, 9) === 'u_pattern' ? + new Uniform4f(context, location) : + new Uniform1f(context, location); + } +} +class SourceExpressionBinder { + constructor(expression, names, type, PaintVertexArray) { + this.expression = expression; + this.type = type; + this.maxValue = 0; + this.paintVertexAttributes = names.map((name) => ({ + name: `a_${name}`, + type: 'Float32', + components: type === 'color' ? 2 : 1, + offset: 0 + })); + this.paintVertexArray = new PaintVertexArray(); + } + populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection) { + const start = this.paintVertexArray.length; + const value = this.expression.evaluate(new EvaluationParameters(0), feature, {}, canonical, [], formattedSection); + this.paintVertexArray.resize(newLength); + this._setPaintValue(start, newLength, value); + } + updatePaintArray(start, end, feature, featureState) { + const value = this.expression.evaluate({ zoom: 0 }, feature, featureState); + this._setPaintValue(start, end, value); + } + _setPaintValue(start, end, value) { + if (this.type === 'color') { + const color = packColor(value); + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, color[0], color[1]); + } + } + else { + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, value); + } + this.maxValue = Math.max(this.maxValue, Math.abs(value)); + } + } + upload(context) { + if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) { + if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) { + this.paintVertexBuffer.updateData(this.paintVertexArray); + } + else { + this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent); + } + } + } + destroy() { + if (this.paintVertexBuffer) { + this.paintVertexBuffer.destroy(); + } + } +} +class CompositeExpressionBinder { + constructor(expression, names, type, useIntegerZoom, zoom, PaintVertexArray) { + this.expression = expression; + this.uniformNames = names.map(name => `u_${name}_t`); + this.type = type; + this.useIntegerZoom = useIntegerZoom; + this.zoom = zoom; + this.maxValue = 0; + this.paintVertexAttributes = names.map((name) => ({ + name: `a_${name}`, + type: 'Float32', + components: type === 'color' ? 4 : 2, + offset: 0 + })); + this.paintVertexArray = new PaintVertexArray(); + } + populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection) { + const min = this.expression.evaluate(new EvaluationParameters(this.zoom), feature, {}, canonical, [], formattedSection); + const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1), feature, {}, canonical, [], formattedSection); + const start = this.paintVertexArray.length; + this.paintVertexArray.resize(newLength); + this._setPaintValue(start, newLength, min, max); + } + updatePaintArray(start, end, feature, featureState) { + const min = this.expression.evaluate({ zoom: this.zoom }, feature, featureState); + const max = this.expression.evaluate({ zoom: this.zoom + 1 }, feature, featureState); + this._setPaintValue(start, end, min, max); + } + _setPaintValue(start, end, min, max) { + if (this.type === 'color') { + const minColor = packColor(min); + const maxColor = packColor(max); + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, minColor[0], minColor[1], maxColor[0], maxColor[1]); + } + } + else { + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, min, max); + } + this.maxValue = Math.max(this.maxValue, Math.abs(min), Math.abs(max)); + } + } + upload(context) { + if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) { + if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) { + this.paintVertexBuffer.updateData(this.paintVertexArray); + } + else { + this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent); + } + } + } + destroy() { + if (this.paintVertexBuffer) { + this.paintVertexBuffer.destroy(); + } + } + setUniform(uniform, globals) { + const currentZoom = this.useIntegerZoom ? Math.floor(globals.zoom) : globals.zoom; + const factor = clamp$1(this.expression.interpolationFactor(currentZoom, this.zoom, this.zoom + 1), 0, 1); + uniform.set(factor); + } + getBinding(context, location, _) { + return new Uniform1f(context, location); + } +} +class CrossFadedCompositeBinder { + constructor(expression, type, useIntegerZoom, zoom, PaintVertexArray, layerId) { + this.expression = expression; + this.type = type; + this.useIntegerZoom = useIntegerZoom; + this.zoom = zoom; + this.layerId = layerId; + this.zoomInPaintVertexArray = new PaintVertexArray(); + this.zoomOutPaintVertexArray = new PaintVertexArray(); + } + populatePaintArray(length, feature, imagePositions) { + const start = this.zoomInPaintVertexArray.length; + this.zoomInPaintVertexArray.resize(length); + this.zoomOutPaintVertexArray.resize(length); + this._setPaintValues(start, length, feature.patterns && feature.patterns[this.layerId], imagePositions); + } + updatePaintArray(start, end, feature, featureState, imagePositions) { + this._setPaintValues(start, end, feature.patterns && feature.patterns[this.layerId], imagePositions); + } + _setPaintValues(start, end, patterns, positions) { + if (!positions || !patterns) + return; + const { min, mid, max } = patterns; + const imageMin = positions[min]; + const imageMid = positions[mid]; + const imageMax = positions[max]; + if (!imageMin || !imageMid || !imageMax) + return; + // We populate two paint arrays because, for cross-faded properties, we don't know which direction + // we're cross-fading to at layout time. In order to keep vertex attributes to a minimum and not pass + // unnecessary vertex data to the shaders, we determine which to upload at draw time. + for (let i = start; i < end; i++) { + this.zoomInPaintVertexArray.emplace(i, imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1], imageMin.tl[0], imageMin.tl[1], imageMin.br[0], imageMin.br[1], imageMid.pixelRatio, imageMin.pixelRatio); + this.zoomOutPaintVertexArray.emplace(i, imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1], imageMax.tl[0], imageMax.tl[1], imageMax.br[0], imageMax.br[1], imageMid.pixelRatio, imageMax.pixelRatio); + } + } + upload(context) { + if (this.zoomInPaintVertexArray && this.zoomInPaintVertexArray.arrayBuffer && this.zoomOutPaintVertexArray && this.zoomOutPaintVertexArray.arrayBuffer) { + this.zoomInPaintVertexBuffer = context.createVertexBuffer(this.zoomInPaintVertexArray, patternAttributes.members, this.expression.isStateDependent); + this.zoomOutPaintVertexBuffer = context.createVertexBuffer(this.zoomOutPaintVertexArray, patternAttributes.members, this.expression.isStateDependent); + } + } + destroy() { + if (this.zoomOutPaintVertexBuffer) + this.zoomOutPaintVertexBuffer.destroy(); + if (this.zoomInPaintVertexBuffer) + this.zoomInPaintVertexBuffer.destroy(); + } +} +/** + * @internal + * ProgramConfiguration contains the logic for binding style layer properties and tile + * layer feature data into GL program uniforms and vertex attributes. + * + * Non-data-driven property values are bound to shader uniforms. Data-driven property + * values are bound to vertex attributes. In order to support a uniform GLSL syntax over + * both, [Mapbox GL Shaders](https://github.com/mapbox/mapbox-gl-shaders) defines a `#pragma` + * abstraction, which ProgramConfiguration is responsible for implementing. At runtime, + * it examines the attributes of a particular layer, combines this with fixed knowledge + * about how layers of the particular type are implemented, and determines which uniforms + * and vertex attributes will be required. It can then substitute the appropriate text + * into the shader source code, create and link a program, and bind the uniforms and + * vertex attributes in preparation for drawing. + * + * When a vector tile is parsed, this same configuration information is used to + * populate the attribute buffers needed for data-driven styling using the zoom + * level and feature property data. + */ +class ProgramConfiguration { + constructor(layer, zoom, filterProperties) { + this.binders = {}; + this._buffers = []; + const keys = []; + for (const property in layer.paint._values) { + if (!filterProperties(property)) + continue; + const value = layer.paint.get(property); + if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) { + continue; + } + const names = paintAttributeNames(property, layer.type); + const expression = value.value; + const type = value.property.specification.type; + const useIntegerZoom = value.property.useIntegerZoom; + const propType = value.property.specification['property-type']; + const isCrossFaded = propType === 'cross-faded' || propType === 'cross-faded-data-driven'; + if (expression.kind === 'constant') { + this.binders[property] = isCrossFaded ? + new CrossFadedConstantBinder(expression.value, names) : + new ConstantBinder(expression.value, names, type); + keys.push(`/u_${property}`); + } + else if (expression.kind === 'source' || isCrossFaded) { + const StructArrayLayout = layoutType(property, type, 'source'); + this.binders[property] = isCrossFaded ? + new CrossFadedCompositeBinder(expression, type, useIntegerZoom, zoom, StructArrayLayout, layer.id) : + new SourceExpressionBinder(expression, names, type, StructArrayLayout); + keys.push(`/a_${property}`); + } + else { + const StructArrayLayout = layoutType(property, type, 'composite'); + this.binders[property] = new CompositeExpressionBinder(expression, names, type, useIntegerZoom, zoom, StructArrayLayout); + keys.push(`/z_${property}`); + } + } + this.cacheKey = keys.sort().join(''); + } + getMaxValue(property) { + const binder = this.binders[property]; + return binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder ? binder.maxValue : 0; + } + populatePaintArrays(newLength, feature, imagePositions, canonical, formattedSection) { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) + binder.populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection); + } + } + setConstantPatternPositions(posTo, posFrom) { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof CrossFadedConstantBinder) + binder.setConstantPatternPositions(posTo, posFrom); + } + } + updatePaintArrays(featureStates, featureMap, vtLayer, layer, imagePositions) { + let dirty = false; + for (const id in featureStates) { + const positions = featureMap.getPositions(id); + for (const pos of positions) { + const feature = vtLayer.feature(pos.index); + for (const property in this.binders) { + const binder = this.binders[property]; + if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || + binder instanceof CrossFadedCompositeBinder) && binder.expression.isStateDependent === true) { + //AHM: Remove after https://github.com/mapbox/mapbox-gl-js/issues/6255 + const value = layer.paint.get(property); + binder.expression = value.value; + binder.updatePaintArray(pos.start, pos.end, feature, featureStates[id], imagePositions); + dirty = true; + } + } + } + } + return dirty; + } + defines() { + const result = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder) { + result.push(...binder.uniformNames.map(name => `#define HAS_UNIFORM_${name}`)); + } + } + return result; + } + getBinderAttributes() { + const result = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) { + for (let i = 0; i < binder.paintVertexAttributes.length; i++) { + result.push(binder.paintVertexAttributes[i].name); + } + } + else if (binder instanceof CrossFadedCompositeBinder) { + for (let i = 0; i < patternAttributes.members.length; i++) { + result.push(patternAttributes.members[i].name); + } + } + } + return result; + } + getBinderUniforms() { + const uniforms = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) { + for (const uniformName of binder.uniformNames) { + uniforms.push(uniformName); + } + } + } + return uniforms; + } + getPaintVertexBuffers() { + return this._buffers; + } + getUniforms(context, locations) { + const uniforms = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) { + for (const name of binder.uniformNames) { + if (locations[name]) { + const binding = binder.getBinding(context, locations[name], name); + uniforms.push({ name, property, binding }); + } + } + } + } + return uniforms; + } + setUniforms(context, binderUniforms, properties, globals) { + // Uniform state bindings are owned by the Program, but we set them + // from within the ProgramConfiguration's binder members. + for (const { name, property, binding } of binderUniforms) { + this.binders[property].setUniform(binding, globals, properties.get(property), name); + } + } + updatePaintBuffers(crossfade) { + this._buffers = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (crossfade && binder instanceof CrossFadedCompositeBinder) { + const patternVertexBuffer = crossfade.fromScale === 2 ? binder.zoomInPaintVertexBuffer : binder.zoomOutPaintVertexBuffer; + if (patternVertexBuffer) + this._buffers.push(patternVertexBuffer); + } + else if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) && binder.paintVertexBuffer) { + this._buffers.push(binder.paintVertexBuffer); + } + } + } + upload(context) { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) + binder.upload(context); + } + this.updatePaintBuffers(); + } + destroy() { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) + binder.destroy(); + } + } +} +class ProgramConfigurationSet { + constructor(layers, zoom, filterProperties = () => true) { + this.programConfigurations = {}; + for (const layer of layers) { + this.programConfigurations[layer.id] = new ProgramConfiguration(layer, zoom, filterProperties); + } + this.needsUpload = false; + this._featureMap = new FeaturePositionMap(); + this._bufferOffset = 0; + } + populatePaintArrays(length, feature, index, imagePositions, canonical, formattedSection) { + for (const key in this.programConfigurations) { + this.programConfigurations[key].populatePaintArrays(length, feature, imagePositions, canonical, formattedSection); + } + if (feature.id !== undefined) { + this._featureMap.add(feature.id, index, this._bufferOffset, length); + } + this._bufferOffset = length; + this.needsUpload = true; + } + updatePaintArrays(featureStates, vtLayer, layers, imagePositions) { + for (const layer of layers) { + this.needsUpload = this.programConfigurations[layer.id].updatePaintArrays(featureStates, this._featureMap, vtLayer, layer, imagePositions) || this.needsUpload; + } + } + get(layerId) { + return this.programConfigurations[layerId]; + } + upload(context) { + if (!this.needsUpload) + return; + for (const layerId in this.programConfigurations) { + this.programConfigurations[layerId].upload(context); + } + this.needsUpload = false; + } + destroy() { + for (const layerId in this.programConfigurations) { + this.programConfigurations[layerId].destroy(); + } + } +} +function paintAttributeNames(property, type) { + const attributeNameExceptions = { + 'text-opacity': ['opacity'], + 'icon-opacity': ['opacity'], + 'text-color': ['fill_color'], + 'icon-color': ['fill_color'], + 'text-halo-color': ['halo_color'], + 'icon-halo-color': ['halo_color'], + 'text-halo-blur': ['halo_blur'], + 'icon-halo-blur': ['halo_blur'], + 'text-halo-width': ['halo_width'], + 'icon-halo-width': ['halo_width'], + 'line-gap-width': ['gapwidth'], + 'line-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'], + 'fill-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'], + 'fill-extrusion-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'], + }; + return attributeNameExceptions[property] || [property.replace(`${type}-`, '').replace(/-/g, '_')]; +} +function getLayoutException(property) { + const propertyExceptions = { + 'line-pattern': { + 'source': PatternLayoutArray, + 'composite': PatternLayoutArray + }, + 'fill-pattern': { + 'source': PatternLayoutArray, + 'composite': PatternLayoutArray + }, + 'fill-extrusion-pattern': { + 'source': PatternLayoutArray, + 'composite': PatternLayoutArray + } + }; + return propertyExceptions[property]; +} +function layoutType(property, type, binderType) { + const defaultLayouts = { + 'color': { + 'source': StructArrayLayout2f8, + 'composite': StructArrayLayout4f16 + }, + 'number': { + 'source': StructArrayLayout1f4, + 'composite': StructArrayLayout2f8 + } + }; + const layoutException = getLayoutException(property); + return layoutException && layoutException[binderType] || defaultLayouts[type][binderType]; +} +register('ConstantBinder', ConstantBinder); +register('CrossFadedConstantBinder', CrossFadedConstantBinder); +register('SourceExpressionBinder', SourceExpressionBinder); +register('CrossFadedCompositeBinder', CrossFadedCompositeBinder); +register('CompositeExpressionBinder', CompositeExpressionBinder); +register('ProgramConfiguration', ProgramConfiguration, { omit: ['_buffers'] }); +register('ProgramConfigurationSet', ProgramConfigurationSet); + +/** + * The maximum value of a coordinate in the internal tile coordinate system. Coordinates of + * all source features normalized to this extent upon load. + * + * The value is a consequence of the following: + * + * * Vertex buffer store positions as signed 16 bit integers. + * * One bit is lost for signedness to support tile buffers. + * * One bit is lost because the line vertex buffer used to pack 1 bit of other data into the int. + * * One bit is lost to support features extending past the extent on the right edge of the tile. + * * This leaves us with 2^13 = 8192 + */ +const EXTENT = 8192; + +// These bounds define the minimum and maximum supported coordinate values. +// While visible coordinates are within [0, EXTENT], tiles may theoretically +// contain coordinates within [-Infinity, Infinity]. Our range is limited by the +// number of bits used to represent the coordinate. +const BITS = 15; +const MAX = Math.pow(2, BITS - 1) - 1; +const MIN = -MAX - 1; +/** + * Loads a geometry from a VectorTileFeature and scales it to the common extent + * used internally. + * @param feature - the vector tile feature to load + */ +function loadGeometry(feature) { + const scale = EXTENT / feature.extent; + const geometry = feature.loadGeometry(); + for (let r = 0; r < geometry.length; r++) { + const ring = geometry[r]; + for (let p = 0; p < ring.length; p++) { + const point = ring[p]; + // round here because mapbox-gl-native uses integers to represent + // points and we need to do the same to avoid renering differences. + const x = Math.round(point.x * scale); + const y = Math.round(point.y * scale); + point.x = clamp$1(x, MIN, MAX); + point.y = clamp$1(y, MIN, MAX); + if (x < point.x || x > point.x + 1 || y < point.y || y > point.y + 1) { + // warn when exceeding allowed extent except for the 1-px-off case + // https://github.com/mapbox/mapbox-gl-js/issues/8992 + warnOnce('Geometry exceeds allowed extent, reduce your vector tile buffer size'); + } + } + } + return geometry; +} + +/** + * Construct a new feature based on a VectorTileFeature for expression evaluation, the geometry of which + * will be loaded based on necessity. + * @param feature - the feature to evaluate + * @param needGeometry - if set to true this will load the geometry + */ +function toEvaluationFeature(feature, needGeometry) { + return { type: feature.type, + id: feature.id, + properties: feature.properties, + geometry: needGeometry ? loadGeometry(feature) : [] }; +} + +function addCircleVertex(layoutVertexArray, x, y, extrudeX, extrudeY) { + layoutVertexArray.emplaceBack((x * 2) + ((extrudeX + 1) / 2), (y * 2) + ((extrudeY + 1) / 2)); +} +/** + * @internal + * Circles are represented by two triangles. + * + * Each corner has a pos that is the center of the circle and an extrusion + * vector that is where it points. + */ +class CircleBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.layoutVertexArray = new CircleLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.segments = new SegmentVector(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + const styleLayer = this.layers[0]; + const bucketFeatures = []; + let circleSortKey = null; + let sortFeaturesByKey = false; + // Heatmap layers are handled in this bucket and have no evaluated properties, so we check our access + if (styleLayer.type === 'circle') { + circleSortKey = styleLayer.layout.get('circle-sort-key'); + sortFeaturesByKey = !circleSortKey.isConstant(); + } + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const sortKey = sortFeaturesByKey ? + circleSortKey.evaluate(evaluationFeature, {}, canonical) : + undefined; + const bucketFeature = { + id, + properties: feature.properties, + type: feature.type, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + patterns: {}, + sortKey + }; + bucketFeatures.push(bucketFeature); + } + if (sortFeaturesByKey) { + bucketFeatures.sort((a, b) => a.sortKey - b.sortKey); + } + for (const bucketFeature of bucketFeatures) { + const { geometry, index, sourceLayerIndex } = bucketFeature; + const feature = features[index].feature; + this.addFeature(bucketFeature, geometry, index, canonical); + options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + isEmpty() { + return this.layoutVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$4); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + } + addFeature(feature, geometry, index, canonical) { + for (const ring of geometry) { + for (const point of ring) { + const x = point.x; + const y = point.y; + // Do not include points that are outside the tile boundaries. + if (x < 0 || x >= EXTENT || y < 0 || y >= EXTENT) + continue; + // this geometry will be of the Point type, and we'll derive + // two triangles from it. + // + // ┌─────────┐ + // │ 3 2 │ + // │ │ + // │ 0 1 │ + // └─────────┘ + const segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray, feature.sortKey); + const index = segment.vertexLength; + addCircleVertex(this.layoutVertexArray, x, y, -1, -1); + addCircleVertex(this.layoutVertexArray, x, y, 1, -1); + addCircleVertex(this.layoutVertexArray, x, y, 1, 1); + addCircleVertex(this.layoutVertexArray, x, y, -1, 1); + this.indexArray.emplaceBack(index, index + 1, index + 2); + this.indexArray.emplaceBack(index, index + 3, index + 2); + segment.vertexLength += 4; + segment.primitiveLength += 2; + } + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, {}, canonical); + } +} +register('CircleBucket', CircleBucket, { omit: ['layers'] }); + +function polygonIntersectsPolygon(polygonA, polygonB) { + for (let i = 0; i < polygonA.length; i++) { + if (polygonContainsPoint(polygonB, polygonA[i])) + return true; + } + for (let i = 0; i < polygonB.length; i++) { + if (polygonContainsPoint(polygonA, polygonB[i])) + return true; + } + if (lineIntersectsLine(polygonA, polygonB)) + return true; + return false; +} +function polygonIntersectsBufferedPoint(polygon, point, radius) { + if (polygonContainsPoint(polygon, point)) + return true; + if (pointIntersectsBufferedLine(point, polygon, radius)) + return true; + return false; +} +function polygonIntersectsMultiPolygon(polygon, multiPolygon) { + if (polygon.length === 1) { + return multiPolygonContainsPoint(multiPolygon, polygon[0]); + } + for (let m = 0; m < multiPolygon.length; m++) { + const ring = multiPolygon[m]; + for (let n = 0; n < ring.length; n++) { + if (polygonContainsPoint(polygon, ring[n])) + return true; + } + } + for (let i = 0; i < polygon.length; i++) { + if (multiPolygonContainsPoint(multiPolygon, polygon[i])) + return true; + } + for (let k = 0; k < multiPolygon.length; k++) { + if (lineIntersectsLine(polygon, multiPolygon[k])) + return true; + } + return false; +} +function polygonIntersectsBufferedMultiLine(polygon, multiLine, radius) { + for (let i = 0; i < multiLine.length; i++) { + const line = multiLine[i]; + if (polygon.length >= 3) { + for (let k = 0; k < line.length; k++) { + if (polygonContainsPoint(polygon, line[k])) + return true; + } + } + if (lineIntersectsBufferedLine(polygon, line, radius)) + return true; + } + return false; +} +function lineIntersectsBufferedLine(lineA, lineB, radius) { + if (lineA.length > 1) { + if (lineIntersectsLine(lineA, lineB)) + return true; + // Check whether any point in either line is within radius of the other line + for (let j = 0; j < lineB.length; j++) { + if (pointIntersectsBufferedLine(lineB[j], lineA, radius)) + return true; + } + } + for (let k = 0; k < lineA.length; k++) { + if (pointIntersectsBufferedLine(lineA[k], lineB, radius)) + return true; + } + return false; +} +function lineIntersectsLine(lineA, lineB) { + if (lineA.length === 0 || lineB.length === 0) + return false; + for (let i = 0; i < lineA.length - 1; i++) { + const a0 = lineA[i]; + const a1 = lineA[i + 1]; + for (let j = 0; j < lineB.length - 1; j++) { + const b0 = lineB[j]; + const b1 = lineB[j + 1]; + if (lineSegmentIntersectsLineSegment(a0, a1, b0, b1)) + return true; + } + } + return false; +} +function lineSegmentIntersectsLineSegment(a0, a1, b0, b1) { + return isCounterClockwise(a0, b0, b1) !== isCounterClockwise(a1, b0, b1) && + isCounterClockwise(a0, a1, b0) !== isCounterClockwise(a0, a1, b1); +} +function pointIntersectsBufferedLine(p, line, radius) { + const radiusSquared = radius * radius; + if (line.length === 1) + return p.distSqr(line[0]) < radiusSquared; + for (let i = 1; i < line.length; i++) { + // Find line segments that have a distance <= radius^2 to p + // In that case, we treat the line as "containing point p". + const v = line[i - 1], w = line[i]; + if (distToSegmentSquared(p, v, w) < radiusSquared) + return true; + } + return false; +} +// Code from https://stackoverflow.com/a/1501725/331379. +function distToSegmentSquared(p, v, w) { + const l2 = v.distSqr(w); + if (l2 === 0) + return p.distSqr(v); + const t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2; + if (t < 0) + return p.distSqr(v); + if (t > 1) + return p.distSqr(w); + return p.distSqr(w.sub(v)._mult(t)._add(v)); +} +// point in polygon ray casting algorithm +function multiPolygonContainsPoint(rings, p) { + let c = false, ring, p1, p2; + for (let k = 0; k < rings.length; k++) { + ring = rings[k]; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + 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)) { + c = !c; + } + } + } + return c; +} +function polygonContainsPoint(ring, p) { + let c = false; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const p1 = ring[i]; + const p2 = ring[j]; + 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)) { + c = !c; + } + } + return c; +} +function polygonIntersectsBox(ring, boxX1, boxY1, boxX2, boxY2) { + for (const p of ring) { + if (boxX1 <= p.x && + boxY1 <= p.y && + boxX2 >= p.x && + boxY2 >= p.y) + return true; + } + const corners = [ + new Point$2(boxX1, boxY1), + new Point$2(boxX1, boxY2), + new Point$2(boxX2, boxY2), + new Point$2(boxX2, boxY1) + ]; + if (ring.length > 2) { + for (const corner of corners) { + if (polygonContainsPoint(ring, corner)) + return true; + } + } + for (let i = 0; i < ring.length - 1; i++) { + const p1 = ring[i]; + const p2 = ring[i + 1]; + if (edgeIntersectsBox(p1, p2, corners)) + return true; + } + return false; +} +function edgeIntersectsBox(e1, e2, corners) { + const tl = corners[0]; + const br = corners[2]; + // the edge and box do not intersect in either the x or y dimensions + if (((e1.x < tl.x) && (e2.x < tl.x)) || + ((e1.x > br.x) && (e2.x > br.x)) || + ((e1.y < tl.y) && (e2.y < tl.y)) || + ((e1.y > br.y) && (e2.y > br.y))) + return false; + // check if all corners of the box are on the same side of the edge + const dir = isCounterClockwise(e1, e2, corners[0]); + return dir !== isCounterClockwise(e1, e2, corners[1]) || + dir !== isCounterClockwise(e1, e2, corners[2]) || + dir !== isCounterClockwise(e1, e2, corners[3]); +} + +function getMaximumPaintValue(property, layer, bucket) { + const value = layer.paint.get(property).value; + if (value.kind === 'constant') { + return value.value; + } + else { + return bucket.programConfigurations.get(layer.id).getMaxValue(property); + } +} +function translateDistance(translate) { + return Math.sqrt(translate[0] * translate[0] + translate[1] * translate[1]); +} +function translate$4(queryGeometry, translate, translateAnchor, bearing, pixelsToTileUnits) { + if (!translate[0] && !translate[1]) { + return queryGeometry; + } + const pt = Point$2.convert(translate)._mult(pixelsToTileUnits); + if (translateAnchor === 'viewport') { + pt._rotate(-bearing); + } + const translated = []; + for (let i = 0; i < queryGeometry.length; i++) { + const point = queryGeometry[i]; + translated.push(point.sub(pt)); + } + return translated; +} +function offsetLine(rings, offset) { + const newRings = []; + for (let ringIndex = 0; ringIndex < rings.length; ringIndex++) { + const ring = rings[ringIndex]; + const newRing = []; + for (let index = 0; index < ring.length; index++) { + const a = ring[index - 1]; + const b = ring[index]; + const c = ring[index + 1]; + const aToB = index === 0 ? new Point$2(0, 0) : b.sub(a)._unit()._perp(); + const bToC = index === ring.length - 1 ? new Point$2(0, 0) : c.sub(b)._unit()._perp(); + const extrude = aToB._add(bToC)._unit(); + const cosHalfAngle = extrude.x * bToC.x + extrude.y * bToC.y; + if (cosHalfAngle !== 0) { + extrude._mult(1 / cosHalfAngle); + } + newRing.push(extrude._mult(offset)._add(b)); + } + newRings.push(newRing); + } + return newRings; +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout$5; +const getLayout$3 = () => layout$5 = layout$5 || new Properties({ + "circle-sort-key": new DataDrivenProperty(v8Spec["layout_circle"]["circle-sort-key"]), +}); +let paint$8; +const getPaint$8 = () => paint$8 = paint$8 || new Properties({ + "circle-radius": new DataDrivenProperty(v8Spec["paint_circle"]["circle-radius"]), + "circle-color": new DataDrivenProperty(v8Spec["paint_circle"]["circle-color"]), + "circle-blur": new DataDrivenProperty(v8Spec["paint_circle"]["circle-blur"]), + "circle-opacity": new DataDrivenProperty(v8Spec["paint_circle"]["circle-opacity"]), + "circle-translate": new DataConstantProperty(v8Spec["paint_circle"]["circle-translate"]), + "circle-translate-anchor": new DataConstantProperty(v8Spec["paint_circle"]["circle-translate-anchor"]), + "circle-pitch-scale": new DataConstantProperty(v8Spec["paint_circle"]["circle-pitch-scale"]), + "circle-pitch-alignment": new DataConstantProperty(v8Spec["paint_circle"]["circle-pitch-alignment"]), + "circle-stroke-width": new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-width"]), + "circle-stroke-color": new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-color"]), + "circle-stroke-opacity": new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-opacity"]), +}); +var properties$8 = ({ get paint() { return getPaint$8(); }, get layout() { return getLayout$3(); } }); + +/** + * Common utilities + * @module glMatrix + */ +// Configuration Constants +var EPSILON = 0.000001; +var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; +var RANDOM = Math.random; +/** + * Sets the type of array used when creating new vectors and matrices + * + * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array + */ + +function setMatrixArrayType(type) { + ARRAY_TYPE = type; +} +var degree = Math.PI / 180; +/** + * Convert Degree To Radian + * + * @param {Number} a Angle in Degrees + */ + +function toRadian(a) { + return a * degree; +} +/** + * Tests whether or not the arguments have approximately the same value, within an absolute + * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less + * than or equal to 1.0, and a relative tolerance is used for larger values) + * + * @param {Number} a The first number to test. + * @param {Number} b The second number to test. + * @returns {Boolean} True if the numbers are approximately equal, false otherwise. + */ + +function equals$a(a, b) { + return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b)); +} +if (!Math.hypot) Math.hypot = function () { + var y = 0, + i = arguments.length; + + while (i--) { + y += arguments[i] * arguments[i]; + } + + return Math.sqrt(y); +}; + +var common = /*#__PURE__*/Object.freeze({ +__proto__: null, +get ARRAY_TYPE () { return ARRAY_TYPE; }, +EPSILON: EPSILON, +RANDOM: RANDOM, +equals: equals$a, +setMatrixArrayType: setMatrixArrayType, +toRadian: toRadian +}); + +/** + * 2x2 Matrix + * @module mat2 + */ + +/** + * Creates a new identity mat2 + * + * @returns {mat2} a new 2x2 matrix + */ + +function create$8() { + var out = new ARRAY_TYPE(4); + + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + } + + out[0] = 1; + out[3] = 1; + return out; +} +/** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param {ReadonlyMat2} a matrix to clone + * @returns {mat2} a new 2x2 matrix + */ + +function clone$8(a) { + var out = new ARRAY_TYPE(4); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +} +/** + * Copy the values from one mat2 to another + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the source matrix + * @returns {mat2} out + */ + +function copy$8(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +} +/** + * Set a mat2 to the identity matrix + * + * @param {mat2} out the receiving matrix + * @returns {mat2} out + */ + +function identity$5(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +} +/** + * Create a new mat2 with the given values + * + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m10 Component in column 1, row 0 position (index 2) + * @param {Number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out A new 2x2 matrix + */ + +function fromValues$8(m00, m01, m10, m11) { + var out = new ARRAY_TYPE(4); + out[0] = m00; + out[1] = m01; + out[2] = m10; + out[3] = m11; + return out; +} +/** + * Set the components of a mat2 to the given values + * + * @param {mat2} out the receiving matrix + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m10 Component in column 1, row 0 position (index 2) + * @param {Number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out + */ + +function set$8(out, m00, m01, m10, m11) { + out[0] = m00; + out[1] = m01; + out[2] = m10; + out[3] = m11; + return out; +} +/** + * Transpose the values of a mat2 + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the source matrix + * @returns {mat2} out + */ + +function transpose$2(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache + // some values + if (out === a) { + var a1 = a[1]; + out[1] = a[2]; + out[2] = a1; + } else { + out[0] = a[0]; + out[1] = a[2]; + out[2] = a[1]; + out[3] = a[3]; + } + + return out; +} +/** + * Inverts a mat2 + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the source matrix + * @returns {mat2} out + */ + +function invert$5(out, a) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; // Calculate the determinant + + var det = a0 * a3 - a2 * a1; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = a3 * det; + out[1] = -a1 * det; + out[2] = -a2 * det; + out[3] = a0 * det; + return out; +} +/** + * Calculates the adjugate of a mat2 + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the source matrix + * @returns {mat2} out + */ + +function adjoint$2(out, a) { + // Caching this value is nessecary if out == a + var a0 = a[0]; + out[0] = a[3]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = a0; + return out; +} +/** + * Calculates the determinant of a mat2 + * + * @param {ReadonlyMat2} a the source matrix + * @returns {Number} determinant of a + */ + +function determinant$3(a) { + return a[0] * a[3] - a[2] * a[1]; +} +/** + * Multiplies two mat2's + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the first operand + * @param {ReadonlyMat2} b the second operand + * @returns {mat2} out + */ + +function multiply$8(out, a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + out[0] = a0 * b0 + a2 * b1; + out[1] = a1 * b0 + a3 * b1; + out[2] = a0 * b2 + a2 * b3; + out[3] = a1 * b2 + a3 * b3; + return out; +} +/** + * Rotates a mat2 by the given angle + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + +function rotate$4(out, a, rad) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var s = Math.sin(rad); + var c = Math.cos(rad); + out[0] = a0 * c + a2 * s; + out[1] = a1 * c + a3 * s; + out[2] = a0 * -s + a2 * c; + out[3] = a1 * -s + a3 * c; + return out; +} +/** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the matrix to rotate + * @param {ReadonlyVec2} v the vec2 to scale the matrix by + * @returns {mat2} out + **/ + +function scale$8(out, a, v) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var v0 = v[0], + v1 = v[1]; + out[0] = a0 * v0; + out[1] = a1 * v0; + out[2] = a2 * v1; + out[3] = a3 * v1; + return out; +} +/** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.rotate(dest, dest, rad); + * + * @param {mat2} out mat2 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + +function fromRotation$4(out, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + out[0] = c; + out[1] = s; + out[2] = -s; + out[3] = c; + return out; +} +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.scale(dest, dest, vec); + * + * @param {mat2} out mat2 receiving operation result + * @param {ReadonlyVec2} v Scaling vector + * @returns {mat2} out + */ + +function fromScaling$3(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = v[1]; + return out; +} +/** + * Returns a string representation of a mat2 + * + * @param {ReadonlyMat2} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ + +function str$8(a) { + return "mat2(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ")"; +} +/** + * Returns Frobenius norm of a mat2 + * + * @param {ReadonlyMat2} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ + +function frob$3(a) { + return Math.hypot(a[0], a[1], a[2], a[3]); +} +/** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param {ReadonlyMat2} L the lower triangular matrix + * @param {ReadonlyMat2} D the diagonal matrix + * @param {ReadonlyMat2} U the upper triangular matrix + * @param {ReadonlyMat2} a the input matrix to factorize + */ + +function LDU(L, D, U, a) { + L[2] = a[2] / a[0]; + U[0] = a[0]; + U[1] = a[1]; + U[3] = a[3] - L[2] * U[1]; + return [L, D, U]; +} +/** + * Adds two mat2's + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the first operand + * @param {ReadonlyMat2} b the second operand + * @returns {mat2} out + */ + +function add$8(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + return out; +} +/** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the first operand + * @param {ReadonlyMat2} b the second operand + * @returns {mat2} out + */ + +function subtract$6(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + return out; +} +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyMat2} a The first matrix. + * @param {ReadonlyMat2} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function exactEquals$8(a, b) { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3]; +} +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {ReadonlyMat2} a The first matrix. + * @param {ReadonlyMat2} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function equals$9(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)); +} +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat2} out + */ + +function multiplyScalar$3(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + return out; +} +/** + * Adds two mat2's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2} out the receiving vector + * @param {ReadonlyMat2} a the first operand + * @param {ReadonlyMat2} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat2} out + */ + +function multiplyScalarAndAdd$3(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + return out; +} +/** + * Alias for {@link mat2.multiply} + * @function + */ + +var mul$8 = multiply$8; +/** + * Alias for {@link mat2.subtract} + * @function + */ + +var sub$6 = subtract$6; + +var mat2 = /*#__PURE__*/Object.freeze({ +__proto__: null, +LDU: LDU, +add: add$8, +adjoint: adjoint$2, +clone: clone$8, +copy: copy$8, +create: create$8, +determinant: determinant$3, +equals: equals$9, +exactEquals: exactEquals$8, +frob: frob$3, +fromRotation: fromRotation$4, +fromScaling: fromScaling$3, +fromValues: fromValues$8, +identity: identity$5, +invert: invert$5, +mul: mul$8, +multiply: multiply$8, +multiplyScalar: multiplyScalar$3, +multiplyScalarAndAdd: multiplyScalarAndAdd$3, +rotate: rotate$4, +scale: scale$8, +set: set$8, +str: str$8, +sub: sub$6, +subtract: subtract$6, +transpose: transpose$2 +}); + +/** + * 2x3 Matrix + * @module mat2d + * @description + * A mat2d contains six elements defined as: + *
+ * [a, b,
+ *  c, d,
+ *  tx, ty]
+ * 
+ * This is a short form for the 3x3 matrix: + *
+ * [a, b, 0,
+ *  c, d, 0,
+ *  tx, ty, 1]
+ * 
+ * The last column is ignored so the array is shorter and operations are faster. + */ + +/** + * Creates a new identity mat2d + * + * @returns {mat2d} a new 2x3 matrix + */ + +function create$7() { + var out = new ARRAY_TYPE(6); + + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + out[4] = 0; + out[5] = 0; + } + + out[0] = 1; + out[3] = 1; + return out; +} +/** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param {ReadonlyMat2d} a matrix to clone + * @returns {mat2d} a new 2x3 matrix + */ + +function clone$7(a) { + var out = new ARRAY_TYPE(6); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + return out; +} +/** + * Copy the values from one mat2d to another + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the source matrix + * @returns {mat2d} out + */ + +function copy$7(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + return out; +} +/** + * Set a mat2d to the identity matrix + * + * @param {mat2d} out the receiving matrix + * @returns {mat2d} out + */ + +function identity$4(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = 0; + out[5] = 0; + return out; +} +/** + * Create a new mat2d with the given values + * + * @param {Number} a Component A (index 0) + * @param {Number} b Component B (index 1) + * @param {Number} c Component C (index 2) + * @param {Number} d Component D (index 3) + * @param {Number} tx Component TX (index 4) + * @param {Number} ty Component TY (index 5) + * @returns {mat2d} A new mat2d + */ + +function fromValues$7(a, b, c, d, tx, ty) { + var out = new ARRAY_TYPE(6); + out[0] = a; + out[1] = b; + out[2] = c; + out[3] = d; + out[4] = tx; + out[5] = ty; + return out; +} +/** + * Set the components of a mat2d to the given values + * + * @param {mat2d} out the receiving matrix + * @param {Number} a Component A (index 0) + * @param {Number} b Component B (index 1) + * @param {Number} c Component C (index 2) + * @param {Number} d Component D (index 3) + * @param {Number} tx Component TX (index 4) + * @param {Number} ty Component TY (index 5) + * @returns {mat2d} out + */ + +function set$7(out, a, b, c, d, tx, ty) { + out[0] = a; + out[1] = b; + out[2] = c; + out[3] = d; + out[4] = tx; + out[5] = ty; + return out; +} +/** + * Inverts a mat2d + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the source matrix + * @returns {mat2d} out + */ + +function invert$4(out, a) { + var aa = a[0], + ab = a[1], + ac = a[2], + ad = a[3]; + var atx = a[4], + aty = a[5]; + var det = aa * ad - ab * ac; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = ad * det; + out[1] = -ab * det; + out[2] = -ac * det; + out[3] = aa * det; + out[4] = (ac * aty - ad * atx) * det; + out[5] = (ab * atx - aa * aty) * det; + return out; +} +/** + * Calculates the determinant of a mat2d + * + * @param {ReadonlyMat2d} a the source matrix + * @returns {Number} determinant of a + */ + +function determinant$2(a) { + return a[0] * a[3] - a[1] * a[2]; +} +/** + * Multiplies two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the first operand + * @param {ReadonlyMat2d} b the second operand + * @returns {mat2d} out + */ + +function multiply$7(out, a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5]; + out[0] = a0 * b0 + a2 * b1; + out[1] = a1 * b0 + a3 * b1; + out[2] = a0 * b2 + a2 * b3; + out[3] = a1 * b2 + a3 * b3; + out[4] = a0 * b4 + a2 * b5 + a4; + out[5] = a1 * b4 + a3 * b5 + a5; + return out; +} +/** + * Rotates a mat2d by the given angle + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + +function rotate$3(out, a, rad) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var s = Math.sin(rad); + var c = Math.cos(rad); + out[0] = a0 * c + a2 * s; + out[1] = a1 * c + a3 * s; + out[2] = a0 * -s + a2 * c; + out[3] = a1 * -s + a3 * c; + out[4] = a4; + out[5] = a5; + return out; +} +/** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to translate + * @param {ReadonlyVec2} v the vec2 to scale the matrix by + * @returns {mat2d} out + **/ + +function scale$7(out, a, v) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var v0 = v[0], + v1 = v[1]; + out[0] = a0 * v0; + out[1] = a1 * v0; + out[2] = a2 * v1; + out[3] = a3 * v1; + out[4] = a4; + out[5] = a5; + return out; +} +/** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to translate + * @param {ReadonlyVec2} v the vec2 to translate the matrix by + * @returns {mat2d} out + **/ + +function translate$3(out, a, v) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var v0 = v[0], + v1 = v[1]; + out[0] = a0; + out[1] = a1; + out[2] = a2; + out[3] = a3; + out[4] = a0 * v0 + a2 * v1 + a4; + out[5] = a1 * v0 + a3 * v1 + a5; + return out; +} +/** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.rotate(dest, dest, rad); + * + * @param {mat2d} out mat2d receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + +function fromRotation$3(out, rad) { + var s = Math.sin(rad), + c = Math.cos(rad); + out[0] = c; + out[1] = s; + out[2] = -s; + out[3] = c; + out[4] = 0; + out[5] = 0; + return out; +} +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.scale(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {ReadonlyVec2} v Scaling vector + * @returns {mat2d} out + */ + +function fromScaling$2(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = v[1]; + out[4] = 0; + out[5] = 0; + return out; +} +/** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.translate(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {ReadonlyVec2} v Translation vector + * @returns {mat2d} out + */ + +function fromTranslation$3(out, v) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = v[0]; + out[5] = v[1]; + return out; +} +/** + * Returns a string representation of a mat2d + * + * @param {ReadonlyMat2d} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ + +function str$7(a) { + return "mat2d(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ")"; +} +/** + * Returns Frobenius norm of a mat2d + * + * @param {ReadonlyMat2d} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ + +function frob$2(a) { + return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], 1); +} +/** + * Adds two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the first operand + * @param {ReadonlyMat2d} b the second operand + * @returns {mat2d} out + */ + +function add$7(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + out[4] = a[4] + b[4]; + out[5] = a[5] + b[5]; + return out; +} +/** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the first operand + * @param {ReadonlyMat2d} b the second operand + * @returns {mat2d} out + */ + +function subtract$5(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + out[4] = a[4] - b[4]; + out[5] = a[5] - b[5]; + return out; +} +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2d} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat2d} out + */ + +function multiplyScalar$2(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + out[4] = a[4] * b; + out[5] = a[5] * b; + return out; +} +/** + * Adds two mat2d's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2d} out the receiving vector + * @param {ReadonlyMat2d} a the first operand + * @param {ReadonlyMat2d} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat2d} out + */ + +function multiplyScalarAndAdd$2(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + out[4] = a[4] + b[4] * scale; + out[5] = a[5] + b[5] * scale; + return out; +} +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyMat2d} a The first matrix. + * @param {ReadonlyMat2d} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function exactEquals$7(a, b) { + 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]; +} +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {ReadonlyMat2d} a The first matrix. + * @param {ReadonlyMat2d} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function equals$8(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)); +} +/** + * Alias for {@link mat2d.multiply} + * @function + */ + +var mul$7 = multiply$7; +/** + * Alias for {@link mat2d.subtract} + * @function + */ + +var sub$5 = subtract$5; + +var mat2d = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$7, +clone: clone$7, +copy: copy$7, +create: create$7, +determinant: determinant$2, +equals: equals$8, +exactEquals: exactEquals$7, +frob: frob$2, +fromRotation: fromRotation$3, +fromScaling: fromScaling$2, +fromTranslation: fromTranslation$3, +fromValues: fromValues$7, +identity: identity$4, +invert: invert$4, +mul: mul$7, +multiply: multiply$7, +multiplyScalar: multiplyScalar$2, +multiplyScalarAndAdd: multiplyScalarAndAdd$2, +rotate: rotate$3, +scale: scale$7, +set: set$7, +str: str$7, +sub: sub$5, +subtract: subtract$5, +translate: translate$3 +}); + +/** + * 3x3 Matrix + * @module mat3 + */ + +/** + * Creates a new identity mat3 + * + * @returns {mat3} a new 3x3 matrix + */ + +function create$6() { + var out = new ARRAY_TYPE(9); + + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[5] = 0; + out[6] = 0; + out[7] = 0; + } + + out[0] = 1; + out[4] = 1; + out[8] = 1; + return out; +} +/** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {ReadonlyMat4} a the source 4x4 matrix + * @returns {mat3} out + */ + +function fromMat4$1(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[4]; + out[4] = a[5]; + out[5] = a[6]; + out[6] = a[8]; + out[7] = a[9]; + out[8] = a[10]; + return out; +} +/** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param {ReadonlyMat3} a matrix to clone + * @returns {mat3} a new 3x3 matrix + */ + +function clone$6(a) { + var out = new ARRAY_TYPE(9); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +} +/** + * Copy the values from one mat3 to another + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the source matrix + * @returns {mat3} out + */ + +function copy$6(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +} +/** + * Create a new mat3 with the given values + * + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m10 Component in column 1, row 0 position (index 3) + * @param {Number} m11 Component in column 1, row 1 position (index 4) + * @param {Number} m12 Component in column 1, row 2 position (index 5) + * @param {Number} m20 Component in column 2, row 0 position (index 6) + * @param {Number} m21 Component in column 2, row 1 position (index 7) + * @param {Number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} A new mat3 + */ + +function fromValues$6(m00, m01, m02, m10, m11, m12, m20, m21, m22) { + var out = new ARRAY_TYPE(9); + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m10; + out[4] = m11; + out[5] = m12; + out[6] = m20; + out[7] = m21; + out[8] = m22; + return out; +} +/** + * Set the components of a mat3 to the given values + * + * @param {mat3} out the receiving matrix + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m10 Component in column 1, row 0 position (index 3) + * @param {Number} m11 Component in column 1, row 1 position (index 4) + * @param {Number} m12 Component in column 1, row 2 position (index 5) + * @param {Number} m20 Component in column 2, row 0 position (index 6) + * @param {Number} m21 Component in column 2, row 1 position (index 7) + * @param {Number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} out + */ + +function set$6(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) { + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m10; + out[4] = m11; + out[5] = m12; + out[6] = m20; + out[7] = m21; + out[8] = m22; + return out; +} +/** + * Set a mat3 to the identity matrix + * + * @param {mat3} out the receiving matrix + * @returns {mat3} out + */ + +function identity$3(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 1; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +} +/** + * Transpose the values of a mat3 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the source matrix + * @returns {mat3} out + */ + +function transpose$1(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a[1], + a02 = a[2], + a12 = a[5]; + out[1] = a[3]; + out[2] = a[6]; + out[3] = a01; + out[5] = a[7]; + out[6] = a02; + out[7] = a12; + } else { + out[0] = a[0]; + out[1] = a[3]; + out[2] = a[6]; + out[3] = a[1]; + out[4] = a[4]; + out[5] = a[7]; + out[6] = a[2]; + out[7] = a[5]; + out[8] = a[8]; + } + + return out; +} +/** + * Inverts a mat3 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the source matrix + * @returns {mat3} out + */ + +function invert$3(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2]; + var a10 = a[3], + a11 = a[4], + a12 = a[5]; + var a20 = a[6], + a21 = a[7], + a22 = a[8]; + var b01 = a22 * a11 - a12 * a21; + var b11 = -a22 * a10 + a12 * a20; + var b21 = a21 * a10 - a11 * a20; // Calculate the determinant + + var det = a00 * b01 + a01 * b11 + a02 * b21; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = b01 * det; + out[1] = (-a22 * a01 + a02 * a21) * det; + out[2] = (a12 * a01 - a02 * a11) * det; + out[3] = b11 * det; + out[4] = (a22 * a00 - a02 * a20) * det; + out[5] = (-a12 * a00 + a02 * a10) * det; + out[6] = b21 * det; + out[7] = (-a21 * a00 + a01 * a20) * det; + out[8] = (a11 * a00 - a01 * a10) * det; + return out; +} +/** + * Calculates the adjugate of a mat3 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the source matrix + * @returns {mat3} out + */ + +function adjoint$1(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2]; + var a10 = a[3], + a11 = a[4], + a12 = a[5]; + var a20 = a[6], + a21 = a[7], + a22 = a[8]; + out[0] = a11 * a22 - a12 * a21; + out[1] = a02 * a21 - a01 * a22; + out[2] = a01 * a12 - a02 * a11; + out[3] = a12 * a20 - a10 * a22; + out[4] = a00 * a22 - a02 * a20; + out[5] = a02 * a10 - a00 * a12; + out[6] = a10 * a21 - a11 * a20; + out[7] = a01 * a20 - a00 * a21; + out[8] = a00 * a11 - a01 * a10; + return out; +} +/** + * Calculates the determinant of a mat3 + * + * @param {ReadonlyMat3} a the source matrix + * @returns {Number} determinant of a + */ + +function determinant$1(a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2]; + var a10 = a[3], + a11 = a[4], + a12 = a[5]; + var a20 = a[6], + a21 = a[7], + a22 = a[8]; + return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); +} +/** + * Multiplies two mat3's + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the first operand + * @param {ReadonlyMat3} b the second operand + * @returns {mat3} out + */ + +function multiply$6(out, a, b) { + var a00 = a[0], + a01 = a[1], + a02 = a[2]; + var a10 = a[3], + a11 = a[4], + a12 = a[5]; + var a20 = a[6], + a21 = a[7], + a22 = a[8]; + var b00 = b[0], + b01 = b[1], + b02 = b[2]; + var b10 = b[3], + b11 = b[4], + b12 = b[5]; + var b20 = b[6], + b21 = b[7], + b22 = b[8]; + out[0] = b00 * a00 + b01 * a10 + b02 * a20; + out[1] = b00 * a01 + b01 * a11 + b02 * a21; + out[2] = b00 * a02 + b01 * a12 + b02 * a22; + out[3] = b10 * a00 + b11 * a10 + b12 * a20; + out[4] = b10 * a01 + b11 * a11 + b12 * a21; + out[5] = b10 * a02 + b11 * a12 + b12 * a22; + out[6] = b20 * a00 + b21 * a10 + b22 * a20; + out[7] = b20 * a01 + b21 * a11 + b22 * a21; + out[8] = b20 * a02 + b21 * a12 + b22 * a22; + return out; +} +/** + * Translate a mat3 by the given vector + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the matrix to translate + * @param {ReadonlyVec2} v vector to translate by + * @returns {mat3} out + */ + +function translate$2(out, a, v) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a10 = a[3], + a11 = a[4], + a12 = a[5], + a20 = a[6], + a21 = a[7], + a22 = a[8], + x = v[0], + y = v[1]; + out[0] = a00; + out[1] = a01; + out[2] = a02; + out[3] = a10; + out[4] = a11; + out[5] = a12; + out[6] = x * a00 + y * a10 + a20; + out[7] = x * a01 + y * a11 + a21; + out[8] = x * a02 + y * a12 + a22; + return out; +} +/** + * Rotates a mat3 by the given angle + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + +function rotate$2(out, a, rad) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a10 = a[3], + a11 = a[4], + a12 = a[5], + a20 = a[6], + a21 = a[7], + a22 = a[8], + s = Math.sin(rad), + c = Math.cos(rad); + out[0] = c * a00 + s * a10; + out[1] = c * a01 + s * a11; + out[2] = c * a02 + s * a12; + out[3] = c * a10 - s * a00; + out[4] = c * a11 - s * a01; + out[5] = c * a12 - s * a02; + out[6] = a20; + out[7] = a21; + out[8] = a22; + return out; +} +/** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the matrix to rotate + * @param {ReadonlyVec2} v the vec2 to scale the matrix by + * @returns {mat3} out + **/ + +function scale$6(out, a, v) { + var x = v[0], + y = v[1]; + out[0] = x * a[0]; + out[1] = x * a[1]; + out[2] = x * a[2]; + out[3] = y * a[3]; + out[4] = y * a[4]; + out[5] = y * a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +} +/** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.translate(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {ReadonlyVec2} v Translation vector + * @returns {mat3} out + */ + +function fromTranslation$2(out, v) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 1; + out[5] = 0; + out[6] = v[0]; + out[7] = v[1]; + out[8] = 1; + return out; +} +/** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.rotate(dest, dest, rad); + * + * @param {mat3} out mat3 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + +function fromRotation$2(out, rad) { + var s = Math.sin(rad), + c = Math.cos(rad); + out[0] = c; + out[1] = s; + out[2] = 0; + out[3] = -s; + out[4] = c; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +} +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.scale(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {ReadonlyVec2} v Scaling vector + * @returns {mat3} out + */ + +function fromScaling$1(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = v[1]; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +} +/** + * Copies the values from a mat2d into a mat3 + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat2d} a the matrix to copy + * @returns {mat3} out + **/ + +function fromMat2d(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = 0; + out[3] = a[2]; + out[4] = a[3]; + out[5] = 0; + out[6] = a[4]; + out[7] = a[5]; + out[8] = 1; + return out; +} +/** + * Calculates a 3x3 matrix from the given quaternion + * + * @param {mat3} out mat3 receiving operation result + * @param {ReadonlyQuat} q Quaternion to create matrix from + * + * @returns {mat3} out + */ + +function fromQuat$1(out, q) { + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var yx = y * x2; + var yy = y * y2; + var zx = z * x2; + var zy = z * y2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + out[0] = 1 - yy - zz; + out[3] = yx - wz; + out[6] = zx + wy; + out[1] = yx + wz; + out[4] = 1 - xx - zz; + out[7] = zy - wx; + out[2] = zx - wy; + out[5] = zy + wx; + out[8] = 1 - xx - yy; + return out; +} +/** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param {mat3} out mat3 receiving operation result + * @param {ReadonlyMat4} a Mat4 to derive the normal matrix from + * + * @returns {mat3} out + */ + +function normalFromMat4(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; // Calculate the determinant + + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + return out; +} +/** + * Generates a 2D projection matrix with the given bounds + * + * @param {mat3} out mat3 frustum matrix will be written into + * @param {number} width Width of your gl context + * @param {number} height Height of gl context + * @returns {mat3} out + */ + +function projection(out, width, height) { + out[0] = 2 / width; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = -2 / height; + out[5] = 0; + out[6] = -1; + out[7] = 1; + out[8] = 1; + return out; +} +/** + * Returns a string representation of a mat3 + * + * @param {ReadonlyMat3} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ + +function str$6(a) { + return "mat3(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ", " + a[6] + ", " + a[7] + ", " + a[8] + ")"; +} +/** + * Returns Frobenius norm of a mat3 + * + * @param {ReadonlyMat3} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ + +function frob$1(a) { + return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]); +} +/** + * Adds two mat3's + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the first operand + * @param {ReadonlyMat3} b the second operand + * @returns {mat3} out + */ + +function add$6(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + out[4] = a[4] + b[4]; + out[5] = a[5] + b[5]; + out[6] = a[6] + b[6]; + out[7] = a[7] + b[7]; + out[8] = a[8] + b[8]; + return out; +} +/** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the first operand + * @param {ReadonlyMat3} b the second operand + * @returns {mat3} out + */ + +function subtract$4(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + out[4] = a[4] - b[4]; + out[5] = a[5] - b[5]; + out[6] = a[6] - b[6]; + out[7] = a[7] - b[7]; + out[8] = a[8] - b[8]; + return out; +} +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat3} out the receiving matrix + * @param {ReadonlyMat3} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat3} out + */ + +function multiplyScalar$1(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + out[4] = a[4] * b; + out[5] = a[5] * b; + out[6] = a[6] * b; + out[7] = a[7] * b; + out[8] = a[8] * b; + return out; +} +/** + * Adds two mat3's after multiplying each element of the second operand by a scalar value. + * + * @param {mat3} out the receiving vector + * @param {ReadonlyMat3} a the first operand + * @param {ReadonlyMat3} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat3} out + */ + +function multiplyScalarAndAdd$1(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + out[4] = a[4] + b[4] * scale; + out[5] = a[5] + b[5] * scale; + out[6] = a[6] + b[6] * scale; + out[7] = a[7] + b[7] * scale; + out[8] = a[8] + b[8] * scale; + return out; +} +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyMat3} a The first matrix. + * @param {ReadonlyMat3} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function exactEquals$6(a, b) { + 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]; +} +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {ReadonlyMat3} a The first matrix. + * @param {ReadonlyMat3} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function equals$7(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5], + a6 = a[6], + a7 = a[7], + a8 = a[8]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)); +} +/** + * Alias for {@link mat3.multiply} + * @function + */ + +var mul$6 = multiply$6; +/** + * Alias for {@link mat3.subtract} + * @function + */ + +var sub$4 = subtract$4; + +var mat3 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$6, +adjoint: adjoint$1, +clone: clone$6, +copy: copy$6, +create: create$6, +determinant: determinant$1, +equals: equals$7, +exactEquals: exactEquals$6, +frob: frob$1, +fromMat2d: fromMat2d, +fromMat4: fromMat4$1, +fromQuat: fromQuat$1, +fromRotation: fromRotation$2, +fromScaling: fromScaling$1, +fromTranslation: fromTranslation$2, +fromValues: fromValues$6, +identity: identity$3, +invert: invert$3, +mul: mul$6, +multiply: multiply$6, +multiplyScalar: multiplyScalar$1, +multiplyScalarAndAdd: multiplyScalarAndAdd$1, +normalFromMat4: normalFromMat4, +projection: projection, +rotate: rotate$2, +scale: scale$6, +set: set$6, +str: str$6, +sub: sub$4, +subtract: subtract$4, +translate: translate$2, +transpose: transpose$1 +}); + +/** + * 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied. + * @module mat4 + */ + +/** + * Creates a new identity mat4 + * + * @returns {mat4} a new 4x4 matrix + */ + +function create$5() { + var out = new ARRAY_TYPE(16); + + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + } + + out[0] = 1; + out[5] = 1; + out[10] = 1; + out[15] = 1; + return out; +} +/** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param {ReadonlyMat4} a matrix to clone + * @returns {mat4} a new 4x4 matrix + */ + +function clone$5(a) { + var out = new ARRAY_TYPE(16); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +/** + * Copy the values from one mat4 to another + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function copy$5(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +/** + * Create a new mat4 with the given values + * + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m03 Component in column 0, row 3 position (index 3) + * @param {Number} m10 Component in column 1, row 0 position (index 4) + * @param {Number} m11 Component in column 1, row 1 position (index 5) + * @param {Number} m12 Component in column 1, row 2 position (index 6) + * @param {Number} m13 Component in column 1, row 3 position (index 7) + * @param {Number} m20 Component in column 2, row 0 position (index 8) + * @param {Number} m21 Component in column 2, row 1 position (index 9) + * @param {Number} m22 Component in column 2, row 2 position (index 10) + * @param {Number} m23 Component in column 2, row 3 position (index 11) + * @param {Number} m30 Component in column 3, row 0 position (index 12) + * @param {Number} m31 Component in column 3, row 1 position (index 13) + * @param {Number} m32 Component in column 3, row 2 position (index 14) + * @param {Number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} A new mat4 + */ + +function fromValues$5(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { + var out = new ARRAY_TYPE(16); + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m03; + out[4] = m10; + out[5] = m11; + out[6] = m12; + out[7] = m13; + out[8] = m20; + out[9] = m21; + out[10] = m22; + out[11] = m23; + out[12] = m30; + out[13] = m31; + out[14] = m32; + out[15] = m33; + return out; +} +/** + * Set the components of a mat4 to the given values + * + * @param {mat4} out the receiving matrix + * @param {Number} m00 Component in column 0, row 0 position (index 0) + * @param {Number} m01 Component in column 0, row 1 position (index 1) + * @param {Number} m02 Component in column 0, row 2 position (index 2) + * @param {Number} m03 Component in column 0, row 3 position (index 3) + * @param {Number} m10 Component in column 1, row 0 position (index 4) + * @param {Number} m11 Component in column 1, row 1 position (index 5) + * @param {Number} m12 Component in column 1, row 2 position (index 6) + * @param {Number} m13 Component in column 1, row 3 position (index 7) + * @param {Number} m20 Component in column 2, row 0 position (index 8) + * @param {Number} m21 Component in column 2, row 1 position (index 9) + * @param {Number} m22 Component in column 2, row 2 position (index 10) + * @param {Number} m23 Component in column 2, row 3 position (index 11) + * @param {Number} m30 Component in column 3, row 0 position (index 12) + * @param {Number} m31 Component in column 3, row 1 position (index 13) + * @param {Number} m32 Component in column 3, row 2 position (index 14) + * @param {Number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} out + */ + +function set$5(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m03; + out[4] = m10; + out[5] = m11; + out[6] = m12; + out[7] = m13; + out[8] = m20; + out[9] = m21; + out[10] = m22; + out[11] = m23; + out[12] = m30; + out[13] = m31; + out[14] = m32; + out[15] = m33; + return out; +} +/** + * Set a mat4 to the identity matrix + * + * @param {mat4} out the receiving matrix + * @returns {mat4} out + */ + +function identity$2(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Transpose the values of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function transpose(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a12 = a[6], + a13 = a[7]; + var a23 = a[11]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a01; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a02; + out[9] = a12; + out[11] = a[14]; + out[12] = a03; + out[13] = a13; + out[14] = a23; + } else { + out[0] = a[0]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a[1]; + out[5] = a[5]; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a[2]; + out[9] = a[6]; + out[10] = a[10]; + out[11] = a[14]; + out[12] = a[3]; + out[13] = a[7]; + out[14] = a[11]; + out[15] = a[15]; + } + + return out; +} +/** + * Inverts a mat4 + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function invert$2(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; // Calculate the determinant + + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + return out; +} +/** + * Calculates the adjugate of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function adjoint(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; + out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22); + out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); + out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12); + out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); + out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); + out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22); + out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); + out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12); + out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21); + out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); + out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11); + out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); + out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); + out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21); + out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); + out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11); + return out; +} +/** + * Calculates the determinant of a mat4 + * + * @param {ReadonlyMat4} a the source matrix + * @returns {Number} determinant of a + */ + +function determinant(a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; // Calculate the determinant + + return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; +} +/** + * Multiplies two mat4s + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the first operand + * @param {ReadonlyMat4} b the second operand + * @returns {mat4} out + */ + +function multiply$5(out, a, b) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; // Cache only the current line of the second matrix + + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[4]; + b1 = b[5]; + b2 = b[6]; + b3 = b[7]; + out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[8]; + b1 = b[9]; + b2 = b[10]; + b3 = b[11]; + out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[12]; + b1 = b[13]; + b2 = b[14]; + b3 = b[15]; + out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + return out; +} +/** + * Translate a mat4 by the given vector + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to translate + * @param {ReadonlyVec3} v vector to translate by + * @returns {mat4} out + */ + +function translate$1(out, a, v) { + var x = v[0], + y = v[1], + z = v[2]; + var a00, a01, a02, a03; + var a10, a11, a12, a13; + var a20, a21, a22, a23; + + if (a === out) { + out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + } else { + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; + out[0] = a00; + out[1] = a01; + out[2] = a02; + out[3] = a03; + out[4] = a10; + out[5] = a11; + out[6] = a12; + out[7] = a13; + out[8] = a20; + out[9] = a21; + out[10] = a22; + out[11] = a23; + out[12] = a00 * x + a10 * y + a20 * z + a[12]; + out[13] = a01 * x + a11 * y + a21 * z + a[13]; + out[14] = a02 * x + a12 * y + a22 * z + a[14]; + out[15] = a03 * x + a13 * y + a23 * z + a[15]; + } + + return out; +} +/** + * Scales the mat4 by the dimensions in the given vec3 not using vectorization + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to scale + * @param {ReadonlyVec3} v the vec3 to scale the matrix by + * @returns {mat4} out + **/ + +function scale$5(out, a, v) { + var x = v[0], + y = v[1], + z = v[2]; + out[0] = a[0] * x; + out[1] = a[1] * x; + out[2] = a[2] * x; + out[3] = a[3] * x; + out[4] = a[4] * y; + out[5] = a[5] * y; + out[6] = a[6] * y; + out[7] = a[7] * y; + out[8] = a[8] * z; + out[9] = a[9] * z; + out[10] = a[10] * z; + out[11] = a[11] * z; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +/** + * Rotates a mat4 by the given angle around the given axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @param {ReadonlyVec3} axis the axis to rotate around + * @returns {mat4} out + */ + +function rotate$1(out, a, rad, axis) { + var x = axis[0], + y = axis[1], + z = axis[2]; + var len = Math.hypot(x, y, z); + var s, c, t; + var a00, a01, a02, a03; + var a10, a11, a12, a13; + var a20, a21, a22, a23; + var b00, b01, b02; + var b10, b11, b12; + var b20, b21, b22; + + if (len < EPSILON) { + return null; + } + + len = 1 / len; + x *= len; + y *= len; + z *= len; + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; // Construct the elements of the rotation matrix + + b00 = x * x * t + c; + b01 = y * x * t + z * s; + b02 = z * x * t - y * s; + b10 = x * y * t - z * s; + b11 = y * y * t + c; + b12 = z * y * t + x * s; + b20 = x * z * t + y * s; + b21 = y * z * t - x * s; + b22 = z * z * t + c; // Perform rotation-specific matrix multiplication + + out[0] = a00 * b00 + a10 * b01 + a20 * b02; + out[1] = a01 * b00 + a11 * b01 + a21 * b02; + out[2] = a02 * b00 + a12 * b01 + a22 * b02; + out[3] = a03 * b00 + a13 * b01 + a23 * b02; + out[4] = a00 * b10 + a10 * b11 + a20 * b12; + out[5] = a01 * b10 + a11 * b11 + a21 * b12; + out[6] = a02 * b10 + a12 * b11 + a22 * b12; + out[7] = a03 * b10 + a13 * b11 + a23 * b12; + out[8] = a00 * b20 + a10 * b21 + a20 * b22; + out[9] = a01 * b20 + a11 * b21 + a21 * b22; + out[10] = a02 * b20 + a12 * b21 + a22 * b22; + out[11] = a03 * b20 + a13 * b21 + a23 * b22; + + if (a !== out) { + // If the source and destination differ, copy the unchanged last row + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + + return out; +} +/** + * Rotates a matrix by the given angle around the X axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function rotateX$3(out, a, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + if (a !== out) { + // If the source and destination differ, copy the unchanged rows + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } // Perform axis-specific matrix multiplication + + + out[4] = a10 * c + a20 * s; + out[5] = a11 * c + a21 * s; + out[6] = a12 * c + a22 * s; + out[7] = a13 * c + a23 * s; + out[8] = a20 * c - a10 * s; + out[9] = a21 * c - a11 * s; + out[10] = a22 * c - a12 * s; + out[11] = a23 * c - a13 * s; + return out; +} +/** + * Rotates a matrix by the given angle around the Y axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function rotateY$3(out, a, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + if (a !== out) { + // If the source and destination differ, copy the unchanged rows + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } // Perform axis-specific matrix multiplication + + + out[0] = a00 * c - a20 * s; + out[1] = a01 * c - a21 * s; + out[2] = a02 * c - a22 * s; + out[3] = a03 * c - a23 * s; + out[8] = a00 * s + a20 * c; + out[9] = a01 * s + a21 * c; + out[10] = a02 * s + a22 * c; + out[11] = a03 * s + a23 * c; + return out; +} +/** + * Rotates a matrix by the given angle around the Z axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function rotateZ$3(out, a, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + if (a !== out) { + // If the source and destination differ, copy the unchanged last row + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } // Perform axis-specific matrix multiplication + + + out[0] = a00 * c + a10 * s; + out[1] = a01 * c + a11 * s; + out[2] = a02 * c + a12 * s; + out[3] = a03 * c + a13 * s; + out[4] = a10 * c - a00 * s; + out[5] = a11 * c - a01 * s; + out[6] = a12 * c - a02 * s; + out[7] = a13 * c - a03 * s; + return out; +} +/** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {ReadonlyVec3} v Translation vector + * @returns {mat4} out + */ + +function fromTranslation$1(out, v) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; +} +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {ReadonlyVec3} v Scaling vector + * @returns {mat4} out + */ + +function fromScaling(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = v[1]; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = v[2]; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from a given angle around a given axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotate(dest, dest, rad, axis); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @param {ReadonlyVec3} axis the axis to rotate around + * @returns {mat4} out + */ + +function fromRotation$1(out, rad, axis) { + var x = axis[0], + y = axis[1], + z = axis[2]; + var len = Math.hypot(x, y, z); + var s, c, t; + + if (len < EPSILON) { + return null; + } + + len = 1 / len; + x *= len; + y *= len; + z *= len; + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; // Perform rotation-specific matrix multiplication + + out[0] = x * x * t + c; + out[1] = y * x * t + z * s; + out[2] = z * x * t - y * s; + out[3] = 0; + out[4] = x * y * t - z * s; + out[5] = y * y * t + c; + out[6] = z * y * t + x * s; + out[7] = 0; + out[8] = x * z * t + y * s; + out[9] = y * z * t - x * s; + out[10] = z * z * t + c; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from the given angle around the X axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateX(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function fromXRotation(out, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); // Perform axis-specific matrix multiplication + + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = c; + out[6] = s; + out[7] = 0; + out[8] = 0; + out[9] = -s; + out[10] = c; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from the given angle around the Y axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateY(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function fromYRotation(out, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); // Perform axis-specific matrix multiplication + + out[0] = c; + out[1] = 0; + out[2] = -s; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = s; + out[9] = 0; + out[10] = c; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from the given angle around the Z axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateZ(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function fromZRotation(out, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); // Perform axis-specific matrix multiplication + + out[0] = c; + out[1] = s; + out[2] = 0; + out[3] = 0; + out[4] = -s; + out[5] = c; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * let quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @param {ReadonlyVec3} v Translation vector + * @returns {mat4} out + */ + +function fromRotationTranslation$1(out, q, v) { + // Quaternion math + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; +} +/** + * Creates a new mat4 from a dual quat. + * + * @param {mat4} out Matrix + * @param {ReadonlyQuat2} a Dual Quaternion + * @returns {mat4} mat4 receiving operation result + */ + +function fromQuat2(out, a) { + var translation = new ARRAY_TYPE(3); + var bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3], + ax = a[4], + ay = a[5], + az = a[6], + aw = a[7]; + var magnitude = bx * bx + by * by + bz * bz + bw * bw; //Only scale if it makes sense + + if (magnitude > 0) { + translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude; + translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude; + translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude; + } else { + translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2; + translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2; + translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2; + } + + fromRotationTranslation$1(out, a, translation); + return out; +} +/** + * Returns the translation vector component of a transformation + * matrix. If a matrix is built with fromRotationTranslation, + * the returned vector will be the same as the translation vector + * originally supplied. + * @param {vec3} out Vector to receive translation component + * @param {ReadonlyMat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + +function getTranslation$1(out, mat) { + out[0] = mat[12]; + out[1] = mat[13]; + out[2] = mat[14]; + return out; +} +/** + * Returns the scaling factor component of a transformation + * matrix. If a matrix is built with fromRotationTranslationScale + * with a normalized Quaternion paramter, the returned vector will be + * the same as the scaling vector + * originally supplied. + * @param {vec3} out Vector to receive scaling factor component + * @param {ReadonlyMat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + +function getScaling(out, mat) { + var m11 = mat[0]; + var m12 = mat[1]; + var m13 = mat[2]; + var m21 = mat[4]; + var m22 = mat[5]; + var m23 = mat[6]; + var m31 = mat[8]; + var m32 = mat[9]; + var m33 = mat[10]; + out[0] = Math.hypot(m11, m12, m13); + out[1] = Math.hypot(m21, m22, m23); + out[2] = Math.hypot(m31, m32, m33); + return out; +} +/** + * Returns a quaternion representing the rotational component + * of a transformation matrix. If a matrix is built with + * fromRotationTranslation, the returned quaternion will be the + * same as the quaternion originally supplied. + * @param {quat} out Quaternion to receive the rotation component + * @param {ReadonlyMat4} mat Matrix to be decomposed (input) + * @return {quat} out + */ + +function getRotation(out, mat) { + var scaling = new ARRAY_TYPE(3); + getScaling(scaling, mat); + var is1 = 1 / scaling[0]; + var is2 = 1 / scaling[1]; + var is3 = 1 / scaling[2]; + var sm11 = mat[0] * is1; + var sm12 = mat[1] * is2; + var sm13 = mat[2] * is3; + var sm21 = mat[4] * is1; + var sm22 = mat[5] * is2; + var sm23 = mat[6] * is3; + var sm31 = mat[8] * is1; + var sm32 = mat[9] * is2; + var sm33 = mat[10] * is3; + var trace = sm11 + sm22 + sm33; + var S = 0; + + if (trace > 0) { + S = Math.sqrt(trace + 1.0) * 2; + out[3] = 0.25 * S; + out[0] = (sm23 - sm32) / S; + out[1] = (sm31 - sm13) / S; + out[2] = (sm12 - sm21) / S; + } else if (sm11 > sm22 && sm11 > sm33) { + S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2; + out[3] = (sm23 - sm32) / S; + out[0] = 0.25 * S; + out[1] = (sm12 + sm21) / S; + out[2] = (sm31 + sm13) / S; + } else if (sm22 > sm33) { + S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2; + out[3] = (sm31 - sm13) / S; + out[0] = (sm12 + sm21) / S; + out[1] = 0.25 * S; + out[2] = (sm23 + sm32) / S; + } else { + S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2; + out[3] = (sm12 - sm21) / S; + out[0] = (sm31 + sm13) / S; + out[1] = (sm23 + sm32) / S; + out[2] = 0.25 * S; + } + + return out; +} +/** + * Creates a matrix from a quaternion rotation, vector translation and vector scale + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * let quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @param {ReadonlyVec3} v Translation vector + * @param {ReadonlyVec3} s Scaling vector + * @returns {mat4} out + */ + +function fromRotationTranslationScale(out, q, v, s) { + // Quaternion math + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + var sx = s[0]; + var sy = s[1]; + var sz = s[2]; + out[0] = (1 - (yy + zz)) * sx; + out[1] = (xy + wz) * sx; + out[2] = (xz - wy) * sx; + out[3] = 0; + out[4] = (xy - wz) * sy; + out[5] = (1 - (xx + zz)) * sy; + out[6] = (yz + wx) * sy; + out[7] = 0; + out[8] = (xz + wy) * sz; + out[9] = (yz - wx) * sz; + out[10] = (1 - (xx + yy)) * sz; + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; +} +/** + * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * mat4.translate(dest, origin); + * let quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * mat4.translate(dest, negativeOrigin); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @param {ReadonlyVec3} v Translation vector + * @param {ReadonlyVec3} s Scaling vector + * @param {ReadonlyVec3} o The origin vector around which to scale and rotate + * @returns {mat4} out + */ + +function fromRotationTranslationScaleOrigin(out, q, v, s, o) { + // Quaternion math + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var xy = x * y2; + var xz = x * z2; + var yy = y * y2; + var yz = y * z2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + var sx = s[0]; + var sy = s[1]; + var sz = s[2]; + var ox = o[0]; + var oy = o[1]; + var oz = o[2]; + var out0 = (1 - (yy + zz)) * sx; + var out1 = (xy + wz) * sx; + var out2 = (xz - wy) * sx; + var out4 = (xy - wz) * sy; + var out5 = (1 - (xx + zz)) * sy; + var out6 = (yz + wx) * sy; + var out8 = (xz + wy) * sz; + var out9 = (yz - wx) * sz; + var out10 = (1 - (xx + yy)) * sz; + out[0] = out0; + out[1] = out1; + out[2] = out2; + out[3] = 0; + out[4] = out4; + out[5] = out5; + out[6] = out6; + out[7] = 0; + out[8] = out8; + out[9] = out9; + out[10] = out10; + out[11] = 0; + out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz); + out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz); + out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz); + out[15] = 1; + return out; +} +/** + * Calculates a 4x4 matrix from the given quaternion + * + * @param {mat4} out mat4 receiving operation result + * @param {ReadonlyQuat} q Quaternion to create matrix from + * + * @returns {mat4} out + */ + +function fromQuat(out, q) { + var x = q[0], + y = q[1], + z = q[2], + w = q[3]; + var x2 = x + x; + var y2 = y + y; + var z2 = z + z; + var xx = x * x2; + var yx = y * x2; + var yy = y * y2; + var zx = z * x2; + var zy = z * y2; + var zz = z * z2; + var wx = w * x2; + var wy = w * y2; + var wz = w * z2; + out[0] = 1 - yy - zz; + out[1] = yx + wz; + out[2] = zx - wy; + out[3] = 0; + out[4] = yx - wz; + out[5] = 1 - xx - zz; + out[6] = zy + wx; + out[7] = 0; + out[8] = zx + wy; + out[9] = zy - wx; + out[10] = 1 - xx - yy; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Generates a frustum matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Number} left Left bound of the frustum + * @param {Number} right Right bound of the frustum + * @param {Number} bottom Bottom bound of the frustum + * @param {Number} top Top bound of the frustum + * @param {Number} near Near bound of the frustum + * @param {Number} far Far bound of the frustum + * @returns {mat4} out + */ + +function frustum(out, left, right, bottom, top, near, far) { + var rl = 1 / (right - left); + var tb = 1 / (top - bottom); + var nf = 1 / (near - far); + out[0] = near * 2 * rl; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = near * 2 * tb; + out[6] = 0; + out[7] = 0; + out[8] = (right + left) * rl; + out[9] = (top + bottom) * tb; + out[10] = (far + near) * nf; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = far * near * 2 * nf; + out[15] = 0; + return out; +} +/** + * Generates a perspective projection matrix with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1], + * which matches WebGL/OpenGL's clip volume. + * Passing null/undefined/no value for far will generate infinite projection matrix. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} fovy Vertical field of view in radians + * @param {number} aspect Aspect ratio. typically viewport width/height + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum, can be null or Infinity + * @returns {mat4} out + */ + +function perspectiveNO(out, fovy, aspect, near, far) { + var f = 1.0 / Math.tan(fovy / 2), + nf; + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[15] = 0; + + if (far != null && far !== Infinity) { + nf = 1 / (near - far); + out[10] = (far + near) * nf; + out[14] = 2 * far * near * nf; + } else { + out[10] = -1; + out[14] = -2 * near; + } + + return out; +} +/** + * Alias for {@link mat4.perspectiveNO} + * @function + */ + +var perspective = perspectiveNO; +/** + * Generates a perspective projection matrix suitable for WebGPU with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1], + * which matches WebGPU/Vulkan/DirectX/Metal's clip volume. + * Passing null/undefined/no value for far will generate infinite projection matrix. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} fovy Vertical field of view in radians + * @param {number} aspect Aspect ratio. typically viewport width/height + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum, can be null or Infinity + * @returns {mat4} out + */ + +function perspectiveZO(out, fovy, aspect, near, far) { + var f = 1.0 / Math.tan(fovy / 2), + nf; + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[15] = 0; + + if (far != null && far !== Infinity) { + nf = 1 / (near - far); + out[10] = far * nf; + out[14] = far * near * nf; + } else { + out[10] = -1; + out[14] = -near; + } + + return out; +} +/** + * Generates a perspective projection matrix with the given field of view. + * This is primarily useful for generating projection matrices to be used + * with the still experiemental WebVR API. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + +function perspectiveFromFieldOfView(out, fov, near, far) { + var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0); + var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0); + var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0); + var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0); + var xScale = 2.0 / (leftTan + rightTan); + var yScale = 2.0 / (upTan + downTan); + out[0] = xScale; + out[1] = 0.0; + out[2] = 0.0; + out[3] = 0.0; + out[4] = 0.0; + out[5] = yScale; + out[6] = 0.0; + out[7] = 0.0; + out[8] = -((leftTan - rightTan) * xScale * 0.5); + out[9] = (upTan - downTan) * yScale * 0.5; + out[10] = far / (near - far); + out[11] = -1.0; + out[12] = 0.0; + out[13] = 0.0; + out[14] = far * near / (near - far); + out[15] = 0.0; + return out; +} +/** + * Generates a orthogonal projection matrix with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1], + * which matches WebGL/OpenGL's clip volume. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} left Left bound of the frustum + * @param {number} right Right bound of the frustum + * @param {number} bottom Bottom bound of the frustum + * @param {number} top Top bound of the frustum + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + +function orthoNO(out, left, right, bottom, top, near, far) { + var lr = 1 / (left - right); + var bt = 1 / (bottom - top); + var nf = 1 / (near - far); + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 2 * nf; + out[11] = 0; + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = (far + near) * nf; + out[15] = 1; + return out; +} +/** + * Alias for {@link mat4.orthoNO} + * @function + */ + +var ortho = orthoNO; +/** + * Generates a orthogonal projection matrix with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1], + * which matches WebGPU/Vulkan/DirectX/Metal's clip volume. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} left Left bound of the frustum + * @param {number} right Right bound of the frustum + * @param {number} bottom Bottom bound of the frustum + * @param {number} top Top bound of the frustum + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + +function orthoZO(out, left, right, bottom, top, near, far) { + var lr = 1 / (left - right); + var bt = 1 / (bottom - top); + var nf = 1 / (near - far); + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = nf; + out[11] = 0; + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = near * nf; + out[15] = 1; + return out; +} +/** + * Generates a look-at matrix with the given eye position, focal point, and up axis. + * If you want a matrix that actually makes an object look at another object, you should use targetTo instead. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {ReadonlyVec3} eye Position of the viewer + * @param {ReadonlyVec3} center Point the viewer is looking at + * @param {ReadonlyVec3} up vec3 pointing up + * @returns {mat4} out + */ + +function lookAt(out, eye, center, up) { + var x0, x1, x2, y0, y1, y2, z0, z1, z2, len; + var eyex = eye[0]; + var eyey = eye[1]; + var eyez = eye[2]; + var upx = up[0]; + var upy = up[1]; + var upz = up[2]; + var centerx = center[0]; + var centery = center[1]; + var centerz = center[2]; + + if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) { + return identity$2(out); + } + + z0 = eyex - centerx; + z1 = eyey - centery; + z2 = eyez - centerz; + len = 1 / Math.hypot(z0, z1, z2); + z0 *= len; + z1 *= len; + z2 *= len; + x0 = upy * z2 - upz * z1; + x1 = upz * z0 - upx * z2; + x2 = upx * z1 - upy * z0; + len = Math.hypot(x0, x1, x2); + + if (!len) { + x0 = 0; + x1 = 0; + x2 = 0; + } else { + len = 1 / len; + x0 *= len; + x1 *= len; + x2 *= len; + } + + y0 = z1 * x2 - z2 * x1; + y1 = z2 * x0 - z0 * x2; + y2 = z0 * x1 - z1 * x0; + len = Math.hypot(y0, y1, y2); + + if (!len) { + y0 = 0; + y1 = 0; + y2 = 0; + } else { + len = 1 / len; + y0 *= len; + y1 *= len; + y2 *= len; + } + + out[0] = x0; + out[1] = y0; + out[2] = z0; + out[3] = 0; + out[4] = x1; + out[5] = y1; + out[6] = z1; + out[7] = 0; + out[8] = x2; + out[9] = y2; + out[10] = z2; + out[11] = 0; + out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); + out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); + out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); + out[15] = 1; + return out; +} +/** + * Generates a matrix that makes something look at something else. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {ReadonlyVec3} eye Position of the viewer + * @param {ReadonlyVec3} center Point the viewer is looking at + * @param {ReadonlyVec3} up vec3 pointing up + * @returns {mat4} out + */ + +function targetTo(out, eye, target, up) { + var eyex = eye[0], + eyey = eye[1], + eyez = eye[2], + upx = up[0], + upy = up[1], + upz = up[2]; + var z0 = eyex - target[0], + z1 = eyey - target[1], + z2 = eyez - target[2]; + var len = z0 * z0 + z1 * z1 + z2 * z2; + + if (len > 0) { + len = 1 / Math.sqrt(len); + z0 *= len; + z1 *= len; + z2 *= len; + } + + var x0 = upy * z2 - upz * z1, + x1 = upz * z0 - upx * z2, + x2 = upx * z1 - upy * z0; + len = x0 * x0 + x1 * x1 + x2 * x2; + + if (len > 0) { + len = 1 / Math.sqrt(len); + x0 *= len; + x1 *= len; + x2 *= len; + } + + out[0] = x0; + out[1] = x1; + out[2] = x2; + out[3] = 0; + out[4] = z1 * x2 - z2 * x1; + out[5] = z2 * x0 - z0 * x2; + out[6] = z0 * x1 - z1 * x0; + out[7] = 0; + out[8] = z0; + out[9] = z1; + out[10] = z2; + out[11] = 0; + out[12] = eyex; + out[13] = eyey; + out[14] = eyez; + out[15] = 1; + return out; +} +/** + * Returns a string representation of a mat4 + * + * @param {ReadonlyMat4} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ + +function str$5(a) { + 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] + ")"; +} +/** + * Returns Frobenius norm of a mat4 + * + * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ + +function frob(a) { + 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]); +} +/** + * Adds two mat4's + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the first operand + * @param {ReadonlyMat4} b the second operand + * @returns {mat4} out + */ + +function add$5(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + out[4] = a[4] + b[4]; + out[5] = a[5] + b[5]; + out[6] = a[6] + b[6]; + out[7] = a[7] + b[7]; + out[8] = a[8] + b[8]; + out[9] = a[9] + b[9]; + out[10] = a[10] + b[10]; + out[11] = a[11] + b[11]; + out[12] = a[12] + b[12]; + out[13] = a[13] + b[13]; + out[14] = a[14] + b[14]; + out[15] = a[15] + b[15]; + return out; +} +/** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the first operand + * @param {ReadonlyMat4} b the second operand + * @returns {mat4} out + */ + +function subtract$3(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + out[4] = a[4] - b[4]; + out[5] = a[5] - b[5]; + out[6] = a[6] - b[6]; + out[7] = a[7] - b[7]; + out[8] = a[8] - b[8]; + out[9] = a[9] - b[9]; + out[10] = a[10] - b[10]; + out[11] = a[11] - b[11]; + out[12] = a[12] - b[12]; + out[13] = a[13] - b[13]; + out[14] = a[14] - b[14]; + out[15] = a[15] - b[15]; + return out; +} +/** + * Multiply each element of the matrix by a scalar. + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to scale + * @param {Number} b amount to scale the matrix's elements by + * @returns {mat4} out + */ + +function multiplyScalar(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + out[4] = a[4] * b; + out[5] = a[5] * b; + out[6] = a[6] * b; + out[7] = a[7] * b; + out[8] = a[8] * b; + out[9] = a[9] * b; + out[10] = a[10] * b; + out[11] = a[11] * b; + out[12] = a[12] * b; + out[13] = a[13] * b; + out[14] = a[14] * b; + out[15] = a[15] * b; + return out; +} +/** + * Adds two mat4's after multiplying each element of the second operand by a scalar value. + * + * @param {mat4} out the receiving vector + * @param {ReadonlyMat4} a the first operand + * @param {ReadonlyMat4} b the second operand + * @param {Number} scale the amount to scale b's elements by before adding + * @returns {mat4} out + */ + +function multiplyScalarAndAdd(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + out[4] = a[4] + b[4] * scale; + out[5] = a[5] + b[5] * scale; + out[6] = a[6] + b[6] * scale; + out[7] = a[7] + b[7] * scale; + out[8] = a[8] + b[8] * scale; + out[9] = a[9] + b[9] * scale; + out[10] = a[10] + b[10] * scale; + out[11] = a[11] + b[11] * scale; + out[12] = a[12] + b[12] * scale; + out[13] = a[13] + b[13] * scale; + out[14] = a[14] + b[14] * scale; + out[15] = a[15] + b[15] * scale; + return out; +} +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyMat4} a The first matrix. + * @param {ReadonlyMat4} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function exactEquals$5(a, b) { + 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]; +} +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {ReadonlyMat4} a The first matrix. + * @param {ReadonlyMat4} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function equals$6(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var a4 = a[4], + a5 = a[5], + a6 = a[6], + a7 = a[7]; + var a8 = a[8], + a9 = a[9], + a10 = a[10], + a11 = a[11]; + var a12 = a[12], + a13 = a[13], + a14 = a[14], + a15 = a[15]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + var b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7]; + var b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11]; + var b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15)); +} +/** + * Alias for {@link mat4.multiply} + * @function + */ + +var mul$5 = multiply$5; +/** + * Alias for {@link mat4.subtract} + * @function + */ + +var sub$3 = subtract$3; + +var mat4 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$5, +adjoint: adjoint, +clone: clone$5, +copy: copy$5, +create: create$5, +determinant: determinant, +equals: equals$6, +exactEquals: exactEquals$5, +frob: frob, +fromQuat: fromQuat, +fromQuat2: fromQuat2, +fromRotation: fromRotation$1, +fromRotationTranslation: fromRotationTranslation$1, +fromRotationTranslationScale: fromRotationTranslationScale, +fromRotationTranslationScaleOrigin: fromRotationTranslationScaleOrigin, +fromScaling: fromScaling, +fromTranslation: fromTranslation$1, +fromValues: fromValues$5, +fromXRotation: fromXRotation, +fromYRotation: fromYRotation, +fromZRotation: fromZRotation, +frustum: frustum, +getRotation: getRotation, +getScaling: getScaling, +getTranslation: getTranslation$1, +identity: identity$2, +invert: invert$2, +lookAt: lookAt, +mul: mul$5, +multiply: multiply$5, +multiplyScalar: multiplyScalar, +multiplyScalarAndAdd: multiplyScalarAndAdd, +ortho: ortho, +orthoNO: orthoNO, +orthoZO: orthoZO, +perspective: perspective, +perspectiveFromFieldOfView: perspectiveFromFieldOfView, +perspectiveNO: perspectiveNO, +perspectiveZO: perspectiveZO, +rotate: rotate$1, +rotateX: rotateX$3, +rotateY: rotateY$3, +rotateZ: rotateZ$3, +scale: scale$5, +set: set$5, +str: str$5, +sub: sub$3, +subtract: subtract$3, +targetTo: targetTo, +translate: translate$1, +transpose: transpose +}); + +/** + * 3 Dimensional Vector + * @module vec3 + */ + +/** + * Creates a new, empty vec3 + * + * @returns {vec3} a new 3D vector + */ + +function create$4() { + var out = new ARRAY_TYPE(3); + + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + } + + return out; +} +/** + * Creates a new vec3 initialized with values from an existing vector + * + * @param {ReadonlyVec3} a vector to clone + * @returns {vec3} a new 3D vector + */ + +function clone$4(a) { + var out = new ARRAY_TYPE(3); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + return out; +} +/** + * Calculates the length of a vec3 + * + * @param {ReadonlyVec3} a vector to calculate length of + * @returns {Number} length of a + */ + +function length$4(a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + return Math.hypot(x, y, z); +} +/** + * Creates a new vec3 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @returns {vec3} a new 3D vector + */ + +function fromValues$4(x, y, z) { + var out = new ARRAY_TYPE(3); + out[0] = x; + out[1] = y; + out[2] = z; + return out; +} +/** + * Copy the values from one vec3 to another + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the source vector + * @returns {vec3} out + */ + +function copy$4(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + return out; +} +/** + * Set the components of a vec3 to the given values + * + * @param {vec3} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @returns {vec3} out + */ + +function set$4(out, x, y, z) { + out[0] = x; + out[1] = y; + out[2] = z; + return out; +} +/** + * Adds two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function add$4(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + return out; +} +/** + * Subtracts vector b from vector a + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function subtract$2(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + return out; +} +/** + * Multiplies two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function multiply$4(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + out[2] = a[2] * b[2]; + return out; +} +/** + * Divides two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function divide$2(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + out[2] = a[2] / b[2]; + return out; +} +/** + * Math.ceil the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to ceil + * @returns {vec3} out + */ + +function ceil$2(out, a) { + out[0] = Math.ceil(a[0]); + out[1] = Math.ceil(a[1]); + out[2] = Math.ceil(a[2]); + return out; +} +/** + * Math.floor the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to floor + * @returns {vec3} out + */ + +function floor$2(out, a) { + out[0] = Math.floor(a[0]); + out[1] = Math.floor(a[1]); + out[2] = Math.floor(a[2]); + return out; +} +/** + * Returns the minimum of two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function min$2(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + out[2] = Math.min(a[2], b[2]); + return out; +} +/** + * Returns the maximum of two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function max$2(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + out[2] = Math.max(a[2], b[2]); + return out; +} +/** + * Math.round the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to round + * @returns {vec3} out + */ + +function round$2(out, a) { + out[0] = Math.round(a[0]); + out[1] = Math.round(a[1]); + out[2] = Math.round(a[2]); + return out; +} +/** + * Scales a vec3 by a scalar number + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec3} out + */ + +function scale$4(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + return out; +} +/** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec3} out + */ + +function scaleAndAdd$2(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + return out; +} +/** + * Calculates the euclidian distance between two vec3's + * + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {Number} distance between a and b + */ + +function distance$2(a, b) { + var x = b[0] - a[0]; + var y = b[1] - a[1]; + var z = b[2] - a[2]; + return Math.hypot(x, y, z); +} +/** + * Calculates the squared euclidian distance between two vec3's + * + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {Number} squared distance between a and b + */ + +function squaredDistance$2(a, b) { + var x = b[0] - a[0]; + var y = b[1] - a[1]; + var z = b[2] - a[2]; + return x * x + y * y + z * z; +} +/** + * Calculates the squared length of a vec3 + * + * @param {ReadonlyVec3} a vector to calculate squared length of + * @returns {Number} squared length of a + */ + +function squaredLength$4(a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + return x * x + y * y + z * z; +} +/** + * Negates the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to negate + * @returns {vec3} out + */ + +function negate$2(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + return out; +} +/** + * Returns the inverse of the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to invert + * @returns {vec3} out + */ + +function inverse$2(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + out[2] = 1.0 / a[2]; + return out; +} +/** + * Normalize a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to normalize + * @returns {vec3} out + */ + +function normalize$4(out, a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + var len = x * x + y * y + z * z; + + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + } + + out[0] = a[0] * len; + out[1] = a[1] * len; + out[2] = a[2] * len; + return out; +} +/** + * Calculates the dot product of two vec3's + * + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {Number} dot product of a and b + */ + +function dot$5(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +} +/** + * Computes the cross product of two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function cross$2(out, a, b) { + var ax = a[0], + ay = a[1], + az = a[2]; + var bx = b[0], + by = b[1], + bz = b[2]; + out[0] = ay * bz - az * by; + out[1] = az * bx - ax * bz; + out[2] = ax * by - ay * bx; + return out; +} +/** + * Performs a linear interpolation between two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec3} out + */ + +function lerp$4(out, a, b, t) { + var ax = a[0]; + var ay = a[1]; + var az = a[2]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + out[2] = az + t * (b[2] - az); + return out; +} +/** + * Performs a hermite interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @param {ReadonlyVec3} c the third operand + * @param {ReadonlyVec3} d the fourth operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec3} out + */ + +function hermite(out, a, b, c, d, t) { + var factorTimes2 = t * t; + var factor1 = factorTimes2 * (2 * t - 3) + 1; + var factor2 = factorTimes2 * (t - 2) + t; + var factor3 = factorTimes2 * (t - 1); + var factor4 = factorTimes2 * (3 - 2 * t); + out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4; + out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4; + out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4; + return out; +} +/** + * Performs a bezier interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @param {ReadonlyVec3} c the third operand + * @param {ReadonlyVec3} d the fourth operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec3} out + */ + +function bezier(out, a, b, c, d, t) { + var inverseFactor = 1 - t; + var inverseFactorTimesTwo = inverseFactor * inverseFactor; + var factorTimes2 = t * t; + var factor1 = inverseFactorTimesTwo * inverseFactor; + var factor2 = 3 * t * inverseFactorTimesTwo; + var factor3 = 3 * factorTimes2 * inverseFactor; + var factor4 = factorTimes2 * t; + out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4; + out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4; + out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4; + return out; +} +/** + * Generates a random vector with the given scale + * + * @param {vec3} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec3} out + */ + +function random$3(out, scale) { + scale = scale || 1.0; + var r = RANDOM() * 2.0 * Math.PI; + var z = RANDOM() * 2.0 - 1.0; + var zScale = Math.sqrt(1.0 - z * z) * scale; + out[0] = Math.cos(r) * zScale; + out[1] = Math.sin(r) * zScale; + out[2] = z * scale; + return out; +} +/** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to transform + * @param {ReadonlyMat4} m matrix to transform with + * @returns {vec3} out + */ + +function transformMat4$2(out, a, m) { + var x = a[0], + y = a[1], + z = a[2]; + var w = m[3] * x + m[7] * y + m[11] * z + m[15]; + w = w || 1.0; + out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w; + out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w; + out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w; + return out; +} +/** + * Transforms the vec3 with a mat3. + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to transform + * @param {ReadonlyMat3} m the 3x3 matrix to transform with + * @returns {vec3} out + */ + +function transformMat3$1(out, a, m) { + var x = a[0], + y = a[1], + z = a[2]; + out[0] = x * m[0] + y * m[3] + z * m[6]; + out[1] = x * m[1] + y * m[4] + z * m[7]; + out[2] = x * m[2] + y * m[5] + z * m[8]; + return out; +} +/** + * Transforms the vec3 with a quat + * Can also be used for dual quaternions. (Multiply it with the real part) + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to transform + * @param {ReadonlyQuat} q quaternion to transform with + * @returns {vec3} out + */ + +function transformQuat$1(out, a, q) { + // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed + var qx = q[0], + qy = q[1], + qz = q[2], + qw = q[3]; + var x = a[0], + y = a[1], + z = a[2]; // var qvec = [qx, qy, qz]; + // var uv = vec3.cross([], qvec, a); + + var uvx = qy * z - qz * y, + uvy = qz * x - qx * z, + uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv); + + var uuvx = qy * uvz - qz * uvy, + uuvy = qz * uvx - qx * uvz, + uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w); + + var w2 = qw * 2; + uvx *= w2; + uvy *= w2; + uvz *= w2; // vec3.scale(uuv, uuv, 2); + + uuvx *= 2; + uuvy *= 2; + uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv)); + + out[0] = x + uvx + uuvx; + out[1] = y + uvy + uuvy; + out[2] = z + uvz + uuvz; + return out; +} +/** + * Rotate a 3D vector around the x-axis + * @param {vec3} out The receiving vec3 + * @param {ReadonlyVec3} a The vec3 point to rotate + * @param {ReadonlyVec3} b The origin of the rotation + * @param {Number} rad The angle of rotation in radians + * @returns {vec3} out + */ + +function rotateX$2(out, a, b, rad) { + var p = [], + r = []; //Translate point to the origin + + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; //perform rotation + + r[0] = p[0]; + r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad); + r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position + + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + return out; +} +/** + * Rotate a 3D vector around the y-axis + * @param {vec3} out The receiving vec3 + * @param {ReadonlyVec3} a The vec3 point to rotate + * @param {ReadonlyVec3} b The origin of the rotation + * @param {Number} rad The angle of rotation in radians + * @returns {vec3} out + */ + +function rotateY$2(out, a, b, rad) { + var p = [], + r = []; //Translate point to the origin + + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; //perform rotation + + r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad); + r[1] = p[1]; + r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position + + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + return out; +} +/** + * Rotate a 3D vector around the z-axis + * @param {vec3} out The receiving vec3 + * @param {ReadonlyVec3} a The vec3 point to rotate + * @param {ReadonlyVec3} b The origin of the rotation + * @param {Number} rad The angle of rotation in radians + * @returns {vec3} out + */ + +function rotateZ$2(out, a, b, rad) { + var p = [], + r = []; //Translate point to the origin + + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; //perform rotation + + r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad); + r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad); + r[2] = p[2]; //translate to correct position + + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + return out; +} +/** + * Get the angle between two 3D vectors + * @param {ReadonlyVec3} a The first operand + * @param {ReadonlyVec3} b The second operand + * @returns {Number} The angle in radians + */ + +function angle$1(a, b) { + var ax = a[0], + ay = a[1], + az = a[2], + bx = b[0], + by = b[1], + bz = b[2], + mag1 = Math.sqrt(ax * ax + ay * ay + az * az), + mag2 = Math.sqrt(bx * bx + by * by + bz * bz), + mag = mag1 * mag2, + cosine = mag && dot$5(a, b) / mag; + return Math.acos(Math.min(Math.max(cosine, -1), 1)); +} +/** + * Set the components of a vec3 to zero + * + * @param {vec3} out the receiving vector + * @returns {vec3} out + */ + +function zero$2(out) { + out[0] = 0.0; + out[1] = 0.0; + out[2] = 0.0; + return out; +} +/** + * Returns a string representation of a vector + * + * @param {ReadonlyVec3} a vector to represent as a string + * @returns {String} string representation of the vector + */ + +function str$4(a) { + return "vec3(" + a[0] + ", " + a[1] + ", " + a[2] + ")"; +} +/** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyVec3} a The first vector. + * @param {ReadonlyVec3} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function exactEquals$4(a, b) { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; +} +/** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {ReadonlyVec3} a The first vector. + * @param {ReadonlyVec3} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function equals$5(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2]; + var b0 = b[0], + b1 = b[1], + b2 = b[2]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)); +} +/** + * Alias for {@link vec3.subtract} + * @function + */ + +var sub$2 = subtract$2; +/** + * Alias for {@link vec3.multiply} + * @function + */ + +var mul$4 = multiply$4; +/** + * Alias for {@link vec3.divide} + * @function + */ + +var div$2 = divide$2; +/** + * Alias for {@link vec3.distance} + * @function + */ + +var dist$2 = distance$2; +/** + * Alias for {@link vec3.squaredDistance} + * @function + */ + +var sqrDist$2 = squaredDistance$2; +/** + * Alias for {@link vec3.length} + * @function + */ + +var len$4 = length$4; +/** + * Alias for {@link vec3.squaredLength} + * @function + */ + +var sqrLen$4 = squaredLength$4; +/** + * Perform some operation over an array of vec3s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ + +var forEach$2 = function () { + var vec = create$4(); + return function (a, stride, offset, count, fn, arg) { + var i, l; + + if (!stride) { + stride = 3; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min(count * stride + offset, a.length); + } else { + l = a.length; + } + + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + vec[2] = a[i + 2]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + a[i + 2] = vec[2]; + } + + return a; + }; +}(); + +var vec3 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$4, +angle: angle$1, +bezier: bezier, +ceil: ceil$2, +clone: clone$4, +copy: copy$4, +create: create$4, +cross: cross$2, +dist: dist$2, +distance: distance$2, +div: div$2, +divide: divide$2, +dot: dot$5, +equals: equals$5, +exactEquals: exactEquals$4, +floor: floor$2, +forEach: forEach$2, +fromValues: fromValues$4, +hermite: hermite, +inverse: inverse$2, +len: len$4, +length: length$4, +lerp: lerp$4, +max: max$2, +min: min$2, +mul: mul$4, +multiply: multiply$4, +negate: negate$2, +normalize: normalize$4, +random: random$3, +rotateX: rotateX$2, +rotateY: rotateY$2, +rotateZ: rotateZ$2, +round: round$2, +scale: scale$4, +scaleAndAdd: scaleAndAdd$2, +set: set$4, +sqrDist: sqrDist$2, +sqrLen: sqrLen$4, +squaredDistance: squaredDistance$2, +squaredLength: squaredLength$4, +str: str$4, +sub: sub$2, +subtract: subtract$2, +transformMat3: transformMat3$1, +transformMat4: transformMat4$2, +transformQuat: transformQuat$1, +zero: zero$2 +}); + +/** + * 4 Dimensional Vector + * @module vec4 + */ + +/** + * Creates a new, empty vec4 + * + * @returns {vec4} a new 4D vector + */ + +function create$3() { + var out = new ARRAY_TYPE(4); + + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 0; + } + + return out; +} +/** + * Creates a new vec4 initialized with values from an existing vector + * + * @param {ReadonlyVec4} a vector to clone + * @returns {vec4} a new 4D vector + */ + +function clone$3(a) { + var out = new ARRAY_TYPE(4); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +} +/** + * Creates a new vec4 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {vec4} a new 4D vector + */ + +function fromValues$3(x, y, z, w) { + var out = new ARRAY_TYPE(4); + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = w; + return out; +} +/** + * Copy the values from one vec4 to another + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the source vector + * @returns {vec4} out + */ + +function copy$3(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +} +/** + * Set the components of a vec4 to the given values + * + * @param {vec4} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {vec4} out + */ + +function set$3(out, x, y, z, w) { + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = w; + return out; +} +/** + * Adds two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function add$3(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + return out; +} +/** + * Subtracts vector b from vector a + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function subtract$1(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + return out; +} +/** + * Multiplies two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function multiply$3(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + out[2] = a[2] * b[2]; + out[3] = a[3] * b[3]; + return out; +} +/** + * Divides two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function divide$1(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + out[2] = a[2] / b[2]; + out[3] = a[3] / b[3]; + return out; +} +/** + * Math.ceil the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to ceil + * @returns {vec4} out + */ + +function ceil$1(out, a) { + out[0] = Math.ceil(a[0]); + out[1] = Math.ceil(a[1]); + out[2] = Math.ceil(a[2]); + out[3] = Math.ceil(a[3]); + return out; +} +/** + * Math.floor the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to floor + * @returns {vec4} out + */ + +function floor$1(out, a) { + out[0] = Math.floor(a[0]); + out[1] = Math.floor(a[1]); + out[2] = Math.floor(a[2]); + out[3] = Math.floor(a[3]); + return out; +} +/** + * Returns the minimum of two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function min$1(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + out[2] = Math.min(a[2], b[2]); + out[3] = Math.min(a[3], b[3]); + return out; +} +/** + * Returns the maximum of two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function max$1(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + out[2] = Math.max(a[2], b[2]); + out[3] = Math.max(a[3], b[3]); + return out; +} +/** + * Math.round the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to round + * @returns {vec4} out + */ + +function round$1(out, a) { + out[0] = Math.round(a[0]); + out[1] = Math.round(a[1]); + out[2] = Math.round(a[2]); + out[3] = Math.round(a[3]); + return out; +} +/** + * Scales a vec4 by a scalar number + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec4} out + */ + +function scale$3(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + return out; +} +/** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec4} out + */ + +function scaleAndAdd$1(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + out[2] = a[2] + b[2] * scale; + out[3] = a[3] + b[3] * scale; + return out; +} +/** + * Calculates the euclidian distance between two vec4's + * + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {Number} distance between a and b + */ + +function distance$1(a, b) { + var x = b[0] - a[0]; + var y = b[1] - a[1]; + var z = b[2] - a[2]; + var w = b[3] - a[3]; + return Math.hypot(x, y, z, w); +} +/** + * Calculates the squared euclidian distance between two vec4's + * + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {Number} squared distance between a and b + */ + +function squaredDistance$1(a, b) { + var x = b[0] - a[0]; + var y = b[1] - a[1]; + var z = b[2] - a[2]; + var w = b[3] - a[3]; + return x * x + y * y + z * z + w * w; +} +/** + * Calculates the length of a vec4 + * + * @param {ReadonlyVec4} a vector to calculate length of + * @returns {Number} length of a + */ + +function length$3(a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + var w = a[3]; + return Math.hypot(x, y, z, w); +} +/** + * Calculates the squared length of a vec4 + * + * @param {ReadonlyVec4} a vector to calculate squared length of + * @returns {Number} squared length of a + */ + +function squaredLength$3(a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + var w = a[3]; + return x * x + y * y + z * z + w * w; +} +/** + * Negates the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to negate + * @returns {vec4} out + */ + +function negate$1(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = -a[3]; + return out; +} +/** + * Returns the inverse of the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to invert + * @returns {vec4} out + */ + +function inverse$1(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + out[2] = 1.0 / a[2]; + out[3] = 1.0 / a[3]; + return out; +} +/** + * Normalize a vec4 + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a vector to normalize + * @returns {vec4} out + */ + +function normalize$3(out, a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + var w = a[3]; + var len = x * x + y * y + z * z + w * w; + + if (len > 0) { + len = 1 / Math.sqrt(len); + } + + out[0] = x * len; + out[1] = y * len; + out[2] = z * len; + out[3] = w * len; + return out; +} +/** + * Calculates the dot product of two vec4's + * + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {Number} dot product of a and b + */ + +function dot$4(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; +} +/** + * Returns the cross-product of three vectors in a 4-dimensional space + * + * @param {ReadonlyVec4} result the receiving vector + * @param {ReadonlyVec4} U the first vector + * @param {ReadonlyVec4} V the second vector + * @param {ReadonlyVec4} W the third vector + * @returns {vec4} result + */ + +function cross$1(out, u, v, w) { + var A = v[0] * w[1] - v[1] * w[0], + B = v[0] * w[2] - v[2] * w[0], + C = v[0] * w[3] - v[3] * w[0], + D = v[1] * w[2] - v[2] * w[1], + E = v[1] * w[3] - v[3] * w[1], + F = v[2] * w[3] - v[3] * w[2]; + var G = u[0]; + var H = u[1]; + var I = u[2]; + var J = u[3]; + out[0] = H * F - I * E + J * D; + out[1] = -(G * F) + I * C - J * B; + out[2] = G * E - H * C + J * A; + out[3] = -(G * D) + H * B - I * A; + return out; +} +/** + * Performs a linear interpolation between two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec4} out + */ + +function lerp$3(out, a, b, t) { + var ax = a[0]; + var ay = a[1]; + var az = a[2]; + var aw = a[3]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + out[2] = az + t * (b[2] - az); + out[3] = aw + t * (b[3] - aw); + return out; +} +/** + * Generates a random vector with the given scale + * + * @param {vec4} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec4} out + */ + +function random$2(out, scale) { + scale = scale || 1.0; // Marsaglia, George. Choosing a Point from the Surface of a + // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646. + // http://projecteuclid.org/euclid.aoms/1177692644; + + var v1, v2, v3, v4; + var s1, s2; + + do { + v1 = RANDOM() * 2 - 1; + v2 = RANDOM() * 2 - 1; + s1 = v1 * v1 + v2 * v2; + } while (s1 >= 1); + + do { + v3 = RANDOM() * 2 - 1; + v4 = RANDOM() * 2 - 1; + s2 = v3 * v3 + v4 * v4; + } while (s2 >= 1); + + var d = Math.sqrt((1 - s1) / s2); + out[0] = scale * v1; + out[1] = scale * v2; + out[2] = scale * v3 * d; + out[3] = scale * v4 * d; + return out; +} +/** + * Transforms the vec4 with a mat4. + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the vector to transform + * @param {ReadonlyMat4} m matrix to transform with + * @returns {vec4} out + */ + +function transformMat4$1(out, a, m) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w; + out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w; + out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w; + out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w; + return out; +} +/** + * Transforms the vec4 with a quat + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the vector to transform + * @param {ReadonlyQuat} q quaternion to transform with + * @returns {vec4} out + */ + +function transformQuat(out, a, q) { + var x = a[0], + y = a[1], + z = a[2]; + var qx = q[0], + qy = q[1], + qz = q[2], + qw = q[3]; // calculate quat * vec + + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; + var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat + + out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy; + out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz; + out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx; + out[3] = a[3]; + return out; +} +/** + * Set the components of a vec4 to zero + * + * @param {vec4} out the receiving vector + * @returns {vec4} out + */ + +function zero$1(out) { + out[0] = 0.0; + out[1] = 0.0; + out[2] = 0.0; + out[3] = 0.0; + return out; +} +/** + * Returns a string representation of a vector + * + * @param {ReadonlyVec4} a vector to represent as a string + * @returns {String} string representation of the vector + */ + +function str$3(a) { + return "vec4(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ")"; +} +/** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyVec4} a The first vector. + * @param {ReadonlyVec4} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function exactEquals$3(a, b) { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3]; +} +/** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {ReadonlyVec4} a The first vector. + * @param {ReadonlyVec4} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function equals$4(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)); +} +/** + * Alias for {@link vec4.subtract} + * @function + */ + +var sub$1 = subtract$1; +/** + * Alias for {@link vec4.multiply} + * @function + */ + +var mul$3 = multiply$3; +/** + * Alias for {@link vec4.divide} + * @function + */ + +var div$1 = divide$1; +/** + * Alias for {@link vec4.distance} + * @function + */ + +var dist$1 = distance$1; +/** + * Alias for {@link vec4.squaredDistance} + * @function + */ + +var sqrDist$1 = squaredDistance$1; +/** + * Alias for {@link vec4.length} + * @function + */ + +var len$3 = length$3; +/** + * Alias for {@link vec4.squaredLength} + * @function + */ + +var sqrLen$3 = squaredLength$3; +/** + * Perform some operation over an array of vec4s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ + +var forEach$1 = function () { + var vec = create$3(); + return function (a, stride, offset, count, fn, arg) { + var i, l; + + if (!stride) { + stride = 4; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min(count * stride + offset, a.length); + } else { + l = a.length; + } + + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + vec[2] = a[i + 2]; + vec[3] = a[i + 3]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + a[i + 2] = vec[2]; + a[i + 3] = vec[3]; + } + + return a; + }; +}(); + +var vec4 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$3, +ceil: ceil$1, +clone: clone$3, +copy: copy$3, +create: create$3, +cross: cross$1, +dist: dist$1, +distance: distance$1, +div: div$1, +divide: divide$1, +dot: dot$4, +equals: equals$4, +exactEquals: exactEquals$3, +floor: floor$1, +forEach: forEach$1, +fromValues: fromValues$3, +inverse: inverse$1, +len: len$3, +length: length$3, +lerp: lerp$3, +max: max$1, +min: min$1, +mul: mul$3, +multiply: multiply$3, +negate: negate$1, +normalize: normalize$3, +random: random$2, +round: round$1, +scale: scale$3, +scaleAndAdd: scaleAndAdd$1, +set: set$3, +sqrDist: sqrDist$1, +sqrLen: sqrLen$3, +squaredDistance: squaredDistance$1, +squaredLength: squaredLength$3, +str: str$3, +sub: sub$1, +subtract: subtract$1, +transformMat4: transformMat4$1, +transformQuat: transformQuat, +zero: zero$1 +}); + +/** + * Quaternion + * @module quat + */ + +/** + * Creates a new identity quat + * + * @returns {quat} a new quaternion + */ + +function create$2() { + var out = new ARRAY_TYPE(4); + + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + } + + out[3] = 1; + return out; +} +/** + * Set a quat to the identity quaternion + * + * @param {quat} out the receiving quaternion + * @returns {quat} out + */ + +function identity$1(out) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +} +/** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyVec3} axis the axis around which to rotate + * @param {Number} rad the angle in radians + * @returns {quat} out + **/ + +function setAxisAngle(out, axis, rad) { + rad = rad * 0.5; + var s = Math.sin(rad); + out[0] = s * axis[0]; + out[1] = s * axis[1]; + out[2] = s * axis[2]; + out[3] = Math.cos(rad); + return out; +} +/** + * Gets the rotation axis and angle for a given + * quaternion. If a quaternion is created with + * setAxisAngle, this method will return the same + * values as providied in the original parameter list + * OR functionally equivalent values. + * Example: The quaternion formed by axis [0, 0, 1] and + * angle -90 is the same as the quaternion formed by + * [0, 0, 1] and 270. This method favors the latter. + * @param {vec3} out_axis Vector receiving the axis of rotation + * @param {ReadonlyQuat} q Quaternion to be decomposed + * @return {Number} Angle, in radians, of the rotation + */ + +function getAxisAngle(out_axis, q) { + var rad = Math.acos(q[3]) * 2.0; + var s = Math.sin(rad / 2.0); + + if (s > EPSILON) { + out_axis[0] = q[0] / s; + out_axis[1] = q[1] / s; + out_axis[2] = q[2] / s; + } else { + // If s is zero, return any axis (no rotation - axis does not matter) + out_axis[0] = 1; + out_axis[1] = 0; + out_axis[2] = 0; + } + + return rad; +} +/** + * Gets the angular distance between two unit quaternions + * + * @param {ReadonlyQuat} a Origin unit quaternion + * @param {ReadonlyQuat} b Destination unit quaternion + * @return {Number} Angle, in radians, between the two quaternions + */ + +function getAngle(a, b) { + var dotproduct = dot$3(a, b); + return Math.acos(2 * dotproduct * dotproduct - 1); +} +/** + * Multiplies two quat's + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @returns {quat} out + */ + +function multiply$2(out, a, b) { + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var bx = b[0], + by = b[1], + bz = b[2], + bw = b[3]; + out[0] = ax * bw + aw * bx + ay * bz - az * by; + out[1] = ay * bw + aw * by + az * bx - ax * bz; + out[2] = az * bw + aw * bz + ax * by - ay * bx; + out[3] = aw * bw - ax * bx - ay * by - az * bz; + return out; +} +/** + * Rotates a quaternion by the given angle about the X axis + * + * @param {quat} out quat receiving operation result + * @param {ReadonlyQuat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ + +function rotateX$1(out, a, rad) { + rad *= 0.5; + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var bx = Math.sin(rad), + bw = Math.cos(rad); + out[0] = ax * bw + aw * bx; + out[1] = ay * bw + az * bx; + out[2] = az * bw - ay * bx; + out[3] = aw * bw - ax * bx; + return out; +} +/** + * Rotates a quaternion by the given angle about the Y axis + * + * @param {quat} out quat receiving operation result + * @param {ReadonlyQuat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ + +function rotateY$1(out, a, rad) { + rad *= 0.5; + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var by = Math.sin(rad), + bw = Math.cos(rad); + out[0] = ax * bw - az * by; + out[1] = ay * bw + aw * by; + out[2] = az * bw + ax * by; + out[3] = aw * bw - ay * by; + return out; +} +/** + * Rotates a quaternion by the given angle about the Z axis + * + * @param {quat} out quat receiving operation result + * @param {ReadonlyQuat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ + +function rotateZ$1(out, a, rad) { + rad *= 0.5; + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var bz = Math.sin(rad), + bw = Math.cos(rad); + out[0] = ax * bw + ay * bz; + out[1] = ay * bw - ax * bz; + out[2] = az * bw + aw * bz; + out[3] = aw * bw - az * bz; + return out; +} +/** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate W component of + * @returns {quat} out + */ + +function calculateW(out, a) { + var x = a[0], + y = a[1], + z = a[2]; + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z)); + return out; +} +/** + * Calculate the exponential of a unit quaternion. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate the exponential of + * @returns {quat} out + */ + +function exp(out, a) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + var r = Math.sqrt(x * x + y * y + z * z); + var et = Math.exp(w); + var s = r > 0 ? et * Math.sin(r) / r : 0; + out[0] = x * s; + out[1] = y * s; + out[2] = z * s; + out[3] = et * Math.cos(r); + return out; +} +/** + * Calculate the natural logarithm of a unit quaternion. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate the exponential of + * @returns {quat} out + */ + +function ln(out, a) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + var r = Math.sqrt(x * x + y * y + z * z); + var t = r > 0 ? Math.atan2(r, w) / r : 0; + out[0] = x * t; + out[1] = y * t; + out[2] = z * t; + out[3] = 0.5 * Math.log(x * x + y * y + z * z + w * w); + return out; +} +/** + * Calculate the scalar power of a unit quaternion. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate the exponential of + * @param {Number} b amount to scale the quaternion by + * @returns {quat} out + */ + +function pow(out, a, b) { + ln(out, a); + scale$2(out, out, b); + exp(out, out); + return out; +} +/** + * Performs a spherical linear interpolation between two quat + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {quat} out + */ + +function slerp(out, a, b, t) { + // benchmarks: + // http://jsperf.com/quaternion-slerp-implementations + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + var bx = b[0], + by = b[1], + bz = b[2], + bw = b[3]; + var omega, cosom, sinom, scale0, scale1; // calc cosine + + cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary) + + if (cosom < 0.0) { + cosom = -cosom; + bx = -bx; + by = -by; + bz = -bz; + bw = -bw; + } // calculate coefficients + + + if (1.0 - cosom > EPSILON) { + // standard case (slerp) + omega = Math.acos(cosom); + sinom = Math.sin(omega); + scale0 = Math.sin((1.0 - t) * omega) / sinom; + scale1 = Math.sin(t * omega) / sinom; + } else { + // "from" and "to" quaternions are very close + // ... so we can do a linear interpolation + scale0 = 1.0 - t; + scale1 = t; + } // calculate final values + + + out[0] = scale0 * ax + scale1 * bx; + out[1] = scale0 * ay + scale1 * by; + out[2] = scale0 * az + scale1 * bz; + out[3] = scale0 * aw + scale1 * bw; + return out; +} +/** + * Generates a random unit quaternion + * + * @param {quat} out the receiving quaternion + * @returns {quat} out + */ + +function random$1(out) { + // Implementation of http://planning.cs.uiuc.edu/node198.html + // TODO: Calling random 3 times is probably not the fastest solution + var u1 = RANDOM(); + var u2 = RANDOM(); + var u3 = RANDOM(); + var sqrt1MinusU1 = Math.sqrt(1 - u1); + var sqrtU1 = Math.sqrt(u1); + out[0] = sqrt1MinusU1 * Math.sin(2.0 * Math.PI * u2); + out[1] = sqrt1MinusU1 * Math.cos(2.0 * Math.PI * u2); + out[2] = sqrtU1 * Math.sin(2.0 * Math.PI * u3); + out[3] = sqrtU1 * Math.cos(2.0 * Math.PI * u3); + return out; +} +/** + * Calculates the inverse of a quat + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate inverse of + * @returns {quat} out + */ + +function invert$1(out, a) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; + var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 + + out[0] = -a0 * invDot; + out[1] = -a1 * invDot; + out[2] = -a2 * invDot; + out[3] = a3 * invDot; + return out; +} +/** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quat to calculate conjugate of + * @returns {quat} out + */ + +function conjugate$1(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = a[3]; + return out; +} +/** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyMat3} m rotation matrix + * @returns {quat} out + * @function + */ + +function fromMat3(out, m) { + // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes + // article "Quaternion Calculus and Fast Animation". + var fTrace = m[0] + m[4] + m[8]; + var fRoot; + + if (fTrace > 0.0) { + // |w| > 1/2, may as well choose w > 1/2 + fRoot = Math.sqrt(fTrace + 1.0); // 2w + + out[3] = 0.5 * fRoot; + fRoot = 0.5 / fRoot; // 1/(4w) + + out[0] = (m[5] - m[7]) * fRoot; + out[1] = (m[6] - m[2]) * fRoot; + out[2] = (m[1] - m[3]) * fRoot; + } else { + // |w| <= 1/2 + var i = 0; + if (m[4] > m[0]) i = 1; + if (m[8] > m[i * 3 + i]) i = 2; + var j = (i + 1) % 3; + var k = (i + 2) % 3; + fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0); + out[i] = 0.5 * fRoot; + fRoot = 0.5 / fRoot; + out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot; + out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot; + out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot; + } + + return out; +} +/** + * Creates a quaternion from the given euler angle x, y, z. + * + * @param {quat} out the receiving quaternion + * @param {x} Angle to rotate around X axis in degrees. + * @param {y} Angle to rotate around Y axis in degrees. + * @param {z} Angle to rotate around Z axis in degrees. + * @returns {quat} out + * @function + */ + +function fromEuler(out, x, y, z) { + var halfToRad = 0.5 * Math.PI / 180.0; + x *= halfToRad; + y *= halfToRad; + z *= halfToRad; + var sx = Math.sin(x); + var cx = Math.cos(x); + var sy = Math.sin(y); + var cy = Math.cos(y); + var sz = Math.sin(z); + var cz = Math.cos(z); + out[0] = sx * cy * cz - cx * sy * sz; + out[1] = cx * sy * cz + sx * cy * sz; + out[2] = cx * cy * sz - sx * sy * cz; + out[3] = cx * cy * cz + sx * sy * sz; + return out; +} +/** + * Returns a string representation of a quatenion + * + * @param {ReadonlyQuat} a vector to represent as a string + * @returns {String} string representation of the vector + */ + +function str$2(a) { + return "quat(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ")"; +} +/** + * Creates a new quat initialized with values from an existing quaternion + * + * @param {ReadonlyQuat} a quaternion to clone + * @returns {quat} a new quaternion + * @function + */ + +var clone$2 = clone$3; +/** + * Creates a new quat initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {quat} a new quaternion + * @function + */ + +var fromValues$2 = fromValues$3; +/** + * Copy the values from one quat to another + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the source quaternion + * @returns {quat} out + * @function + */ + +var copy$2 = copy$3; +/** + * Set the components of a quat to the given values + * + * @param {quat} out the receiving quaternion + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {quat} out + * @function + */ + +var set$2 = set$3; +/** + * Adds two quat's + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @returns {quat} out + * @function + */ + +var add$2 = add$3; +/** + * Alias for {@link quat.multiply} + * @function + */ + +var mul$2 = multiply$2; +/** + * Scales a quat by a scalar number + * + * @param {quat} out the receiving vector + * @param {ReadonlyQuat} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {quat} out + * @function + */ + +var scale$2 = scale$3; +/** + * Calculates the dot product of two quat's + * + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @returns {Number} dot product of a and b + * @function + */ + +var dot$3 = dot$4; +/** + * Performs a linear interpolation between two quat's + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {quat} out + * @function + */ + +var lerp$2 = lerp$3; +/** + * Calculates the length of a quat + * + * @param {ReadonlyQuat} a vector to calculate length of + * @returns {Number} length of a + */ + +var length$2 = length$3; +/** + * Alias for {@link quat.length} + * @function + */ + +var len$2 = length$2; +/** + * Calculates the squared length of a quat + * + * @param {ReadonlyQuat} a vector to calculate squared length of + * @returns {Number} squared length of a + * @function + */ + +var squaredLength$2 = squaredLength$3; +/** + * Alias for {@link quat.squaredLength} + * @function + */ + +var sqrLen$2 = squaredLength$2; +/** + * Normalize a quat + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a quaternion to normalize + * @returns {quat} out + * @function + */ + +var normalize$2 = normalize$3; +/** + * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyQuat} a The first quaternion. + * @param {ReadonlyQuat} b The second quaternion. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +var exactEquals$2 = exactEquals$3; +/** + * Returns whether or not the quaternions have approximately the same elements in the same position. + * + * @param {ReadonlyQuat} a The first vector. + * @param {ReadonlyQuat} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +var equals$3 = equals$4; +/** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {ReadonlyVec3} a the initial vector + * @param {ReadonlyVec3} b the destination vector + * @returns {quat} out + */ + +var rotationTo = function () { + var tmpvec3 = create$4(); + var xUnitVec3 = fromValues$4(1, 0, 0); + var yUnitVec3 = fromValues$4(0, 1, 0); + return function (out, a, b) { + var dot = dot$5(a, b); + + if (dot < -0.999999) { + cross$2(tmpvec3, xUnitVec3, a); + if (len$4(tmpvec3) < 0.000001) cross$2(tmpvec3, yUnitVec3, a); + normalize$4(tmpvec3, tmpvec3); + setAxisAngle(out, tmpvec3, Math.PI); + return out; + } else if (dot > 0.999999) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; + } else { + cross$2(tmpvec3, a, b); + out[0] = tmpvec3[0]; + out[1] = tmpvec3[1]; + out[2] = tmpvec3[2]; + out[3] = 1 + dot; + return normalize$2(out, out); + } + }; +}(); +/** + * Performs a spherical linear interpolation with two control points + * + * @param {quat} out the receiving quaternion + * @param {ReadonlyQuat} a the first operand + * @param {ReadonlyQuat} b the second operand + * @param {ReadonlyQuat} c the third operand + * @param {ReadonlyQuat} d the fourth operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {quat} out + */ + +var sqlerp = function () { + var temp1 = create$2(); + var temp2 = create$2(); + return function (out, a, b, c, d, t) { + slerp(temp1, a, d, t); + slerp(temp2, b, c, t); + slerp(out, temp1, temp2, 2 * t * (1 - t)); + return out; + }; +}(); +/** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {ReadonlyVec3} view the vector representing the viewing direction + * @param {ReadonlyVec3} right the vector representing the local "right" direction + * @param {ReadonlyVec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + +var setAxes = function () { + var matr = create$6(); + return function (out, view, right, up) { + matr[0] = right[0]; + matr[3] = right[1]; + matr[6] = right[2]; + matr[1] = up[0]; + matr[4] = up[1]; + matr[7] = up[2]; + matr[2] = -view[0]; + matr[5] = -view[1]; + matr[8] = -view[2]; + return normalize$2(out, fromMat3(out, matr)); + }; +}(); + +var quat = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$2, +calculateW: calculateW, +clone: clone$2, +conjugate: conjugate$1, +copy: copy$2, +create: create$2, +dot: dot$3, +equals: equals$3, +exactEquals: exactEquals$2, +exp: exp, +fromEuler: fromEuler, +fromMat3: fromMat3, +fromValues: fromValues$2, +getAngle: getAngle, +getAxisAngle: getAxisAngle, +identity: identity$1, +invert: invert$1, +len: len$2, +length: length$2, +lerp: lerp$2, +ln: ln, +mul: mul$2, +multiply: multiply$2, +normalize: normalize$2, +pow: pow, +random: random$1, +rotateX: rotateX$1, +rotateY: rotateY$1, +rotateZ: rotateZ$1, +rotationTo: rotationTo, +scale: scale$2, +set: set$2, +setAxes: setAxes, +setAxisAngle: setAxisAngle, +slerp: slerp, +sqlerp: sqlerp, +sqrLen: sqrLen$2, +squaredLength: squaredLength$2, +str: str$2 +}); + +/** + * Dual Quaternion
+ * Format: [real, dual]
+ * Quaternion format: XYZW
+ * Make sure to have normalized dual quaternions, otherwise the functions may not work as intended.
+ * @module quat2 + */ + +/** + * Creates a new identity dual quat + * + * @returns {quat2} a new dual quaternion [real -> rotation, dual -> translation] + */ + +function create$1() { + var dq = new ARRAY_TYPE(8); + + if (ARRAY_TYPE != Float32Array) { + dq[0] = 0; + dq[1] = 0; + dq[2] = 0; + dq[4] = 0; + dq[5] = 0; + dq[6] = 0; + dq[7] = 0; + } + + dq[3] = 1; + return dq; +} +/** + * Creates a new quat initialized with values from an existing quaternion + * + * @param {ReadonlyQuat2} a dual quaternion to clone + * @returns {quat2} new dual quaternion + * @function + */ + +function clone$1(a) { + var dq = new ARRAY_TYPE(8); + dq[0] = a[0]; + dq[1] = a[1]; + dq[2] = a[2]; + dq[3] = a[3]; + dq[4] = a[4]; + dq[5] = a[5]; + dq[6] = a[6]; + dq[7] = a[7]; + return dq; +} +/** + * Creates a new dual quat initialized with the given values + * + * @param {Number} x1 X component + * @param {Number} y1 Y component + * @param {Number} z1 Z component + * @param {Number} w1 W component + * @param {Number} x2 X component + * @param {Number} y2 Y component + * @param {Number} z2 Z component + * @param {Number} w2 W component + * @returns {quat2} new dual quaternion + * @function + */ + +function fromValues$1(x1, y1, z1, w1, x2, y2, z2, w2) { + var dq = new ARRAY_TYPE(8); + dq[0] = x1; + dq[1] = y1; + dq[2] = z1; + dq[3] = w1; + dq[4] = x2; + dq[5] = y2; + dq[6] = z2; + dq[7] = w2; + return dq; +} +/** + * Creates a new dual quat from the given values (quat and translation) + * + * @param {Number} x1 X component + * @param {Number} y1 Y component + * @param {Number} z1 Z component + * @param {Number} w1 W component + * @param {Number} x2 X component (translation) + * @param {Number} y2 Y component (translation) + * @param {Number} z2 Z component (translation) + * @returns {quat2} new dual quaternion + * @function + */ + +function fromRotationTranslationValues(x1, y1, z1, w1, x2, y2, z2) { + var dq = new ARRAY_TYPE(8); + dq[0] = x1; + dq[1] = y1; + dq[2] = z1; + dq[3] = w1; + var ax = x2 * 0.5, + ay = y2 * 0.5, + az = z2 * 0.5; + dq[4] = ax * w1 + ay * z1 - az * y1; + dq[5] = ay * w1 + az * x1 - ax * z1; + dq[6] = az * w1 + ax * y1 - ay * x1; + dq[7] = -ax * x1 - ay * y1 - az * z1; + return dq; +} +/** + * Creates a dual quat from a quaternion and a translation + * + * @param {ReadonlyQuat2} dual quaternion receiving operation result + * @param {ReadonlyQuat} q a normalized quaternion + * @param {ReadonlyVec3} t tranlation vector + * @returns {quat2} dual quaternion receiving operation result + * @function + */ + +function fromRotationTranslation(out, q, t) { + var ax = t[0] * 0.5, + ay = t[1] * 0.5, + az = t[2] * 0.5, + bx = q[0], + by = q[1], + bz = q[2], + bw = q[3]; + out[0] = bx; + out[1] = by; + out[2] = bz; + out[3] = bw; + out[4] = ax * bw + ay * bz - az * by; + out[5] = ay * bw + az * bx - ax * bz; + out[6] = az * bw + ax * by - ay * bx; + out[7] = -ax * bx - ay * by - az * bz; + return out; +} +/** + * Creates a dual quat from a translation + * + * @param {ReadonlyQuat2} dual quaternion receiving operation result + * @param {ReadonlyVec3} t translation vector + * @returns {quat2} dual quaternion receiving operation result + * @function + */ + +function fromTranslation(out, t) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = t[0] * 0.5; + out[5] = t[1] * 0.5; + out[6] = t[2] * 0.5; + out[7] = 0; + return out; +} +/** + * Creates a dual quat from a quaternion + * + * @param {ReadonlyQuat2} dual quaternion receiving operation result + * @param {ReadonlyQuat} q the quaternion + * @returns {quat2} dual quaternion receiving operation result + * @function + */ + +function fromRotation(out, q) { + out[0] = q[0]; + out[1] = q[1]; + out[2] = q[2]; + out[3] = q[3]; + out[4] = 0; + out[5] = 0; + out[6] = 0; + out[7] = 0; + return out; +} +/** + * Creates a new dual quat from a matrix (4x4) + * + * @param {quat2} out the dual quaternion + * @param {ReadonlyMat4} a the matrix + * @returns {quat2} dual quat receiving operation result + * @function + */ + +function fromMat4(out, a) { + //TODO Optimize this + var outer = create$2(); + getRotation(outer, a); + var t = new ARRAY_TYPE(3); + getTranslation$1(t, a); + fromRotationTranslation(out, outer, t); + return out; +} +/** + * Copy the values from one dual quat to another + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the source dual quaternion + * @returns {quat2} out + * @function + */ + +function copy$1(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + return out; +} +/** + * Set a dual quat to the identity dual quaternion + * + * @param {quat2} out the receiving quaternion + * @returns {quat2} out + */ + +function identity(out) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = 0; + out[5] = 0; + out[6] = 0; + out[7] = 0; + return out; +} +/** + * Set the components of a dual quat to the given values + * + * @param {quat2} out the receiving quaternion + * @param {Number} x1 X component + * @param {Number} y1 Y component + * @param {Number} z1 Z component + * @param {Number} w1 W component + * @param {Number} x2 X component + * @param {Number} y2 Y component + * @param {Number} z2 Z component + * @param {Number} w2 W component + * @returns {quat2} out + * @function + */ + +function set$1(out, x1, y1, z1, w1, x2, y2, z2, w2) { + out[0] = x1; + out[1] = y1; + out[2] = z1; + out[3] = w1; + out[4] = x2; + out[5] = y2; + out[6] = z2; + out[7] = w2; + return out; +} +/** + * Gets the real part of a dual quat + * @param {quat} out real part + * @param {ReadonlyQuat2} a Dual Quaternion + * @return {quat} real part + */ + +var getReal = copy$2; +/** + * Gets the dual part of a dual quat + * @param {quat} out dual part + * @param {ReadonlyQuat2} a Dual Quaternion + * @return {quat} dual part + */ + +function getDual(out, a) { + out[0] = a[4]; + out[1] = a[5]; + out[2] = a[6]; + out[3] = a[7]; + return out; +} +/** + * Set the real component of a dual quat to the given quaternion + * + * @param {quat2} out the receiving quaternion + * @param {ReadonlyQuat} q a quaternion representing the real part + * @returns {quat2} out + * @function + */ + +var setReal = copy$2; +/** + * Set the dual component of a dual quat to the given quaternion + * + * @param {quat2} out the receiving quaternion + * @param {ReadonlyQuat} q a quaternion representing the dual part + * @returns {quat2} out + * @function + */ + +function setDual(out, q) { + out[4] = q[0]; + out[5] = q[1]; + out[6] = q[2]; + out[7] = q[3]; + return out; +} +/** + * Gets the translation of a normalized dual quat + * @param {vec3} out translation + * @param {ReadonlyQuat2} a Dual Quaternion to be decomposed + * @return {vec3} translation + */ + +function getTranslation(out, a) { + var ax = a[4], + ay = a[5], + az = a[6], + aw = a[7], + bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3]; + out[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2; + out[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2; + out[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2; + return out; +} +/** + * Translates a dual quat by the given vector + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to translate + * @param {ReadonlyVec3} v vector to translate by + * @returns {quat2} out + */ + +function translate(out, a, v) { + var ax1 = a[0], + ay1 = a[1], + az1 = a[2], + aw1 = a[3], + bx1 = v[0] * 0.5, + by1 = v[1] * 0.5, + bz1 = v[2] * 0.5, + ax2 = a[4], + ay2 = a[5], + az2 = a[6], + aw2 = a[7]; + out[0] = ax1; + out[1] = ay1; + out[2] = az1; + out[3] = aw1; + out[4] = aw1 * bx1 + ay1 * bz1 - az1 * by1 + ax2; + out[5] = aw1 * by1 + az1 * bx1 - ax1 * bz1 + ay2; + out[6] = aw1 * bz1 + ax1 * by1 - ay1 * bx1 + az2; + out[7] = -ax1 * bx1 - ay1 * by1 - az1 * bz1 + aw2; + return out; +} +/** + * Rotates a dual quat around the X axis + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {number} rad how far should the rotation be + * @returns {quat2} out + */ + +function rotateX(out, a, rad) { + var bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3], + ax = a[4], + ay = a[5], + az = a[6], + aw = a[7], + ax1 = ax * bw + aw * bx + ay * bz - az * by, + ay1 = ay * bw + aw * by + az * bx - ax * bz, + az1 = az * bw + aw * bz + ax * by - ay * bx, + aw1 = aw * bw - ax * bx - ay * by - az * bz; + rotateX$1(out, a, rad); + bx = out[0]; + by = out[1]; + bz = out[2]; + bw = out[3]; + out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; + out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; + out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; + out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; + return out; +} +/** + * Rotates a dual quat around the Y axis + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {number} rad how far should the rotation be + * @returns {quat2} out + */ + +function rotateY(out, a, rad) { + var bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3], + ax = a[4], + ay = a[5], + az = a[6], + aw = a[7], + ax1 = ax * bw + aw * bx + ay * bz - az * by, + ay1 = ay * bw + aw * by + az * bx - ax * bz, + az1 = az * bw + aw * bz + ax * by - ay * bx, + aw1 = aw * bw - ax * bx - ay * by - az * bz; + rotateY$1(out, a, rad); + bx = out[0]; + by = out[1]; + bz = out[2]; + bw = out[3]; + out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; + out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; + out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; + out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; + return out; +} +/** + * Rotates a dual quat around the Z axis + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {number} rad how far should the rotation be + * @returns {quat2} out + */ + +function rotateZ(out, a, rad) { + var bx = -a[0], + by = -a[1], + bz = -a[2], + bw = a[3], + ax = a[4], + ay = a[5], + az = a[6], + aw = a[7], + ax1 = ax * bw + aw * bx + ay * bz - az * by, + ay1 = ay * bw + aw * by + az * bx - ax * bz, + az1 = az * bw + aw * bz + ax * by - ay * bx, + aw1 = aw * bw - ax * bx - ay * by - az * bz; + rotateZ$1(out, a, rad); + bx = out[0]; + by = out[1]; + bz = out[2]; + bw = out[3]; + out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; + out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; + out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; + out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; + return out; +} +/** + * Rotates a dual quat by a given quaternion (a * q) + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {ReadonlyQuat} q quaternion to rotate by + * @returns {quat2} out + */ + +function rotateByQuatAppend(out, a, q) { + var qx = q[0], + qy = q[1], + qz = q[2], + qw = q[3], + ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + out[0] = ax * qw + aw * qx + ay * qz - az * qy; + out[1] = ay * qw + aw * qy + az * qx - ax * qz; + out[2] = az * qw + aw * qz + ax * qy - ay * qx; + out[3] = aw * qw - ax * qx - ay * qy - az * qz; + ax = a[4]; + ay = a[5]; + az = a[6]; + aw = a[7]; + out[4] = ax * qw + aw * qx + ay * qz - az * qy; + out[5] = ay * qw + aw * qy + az * qx - ax * qz; + out[6] = az * qw + aw * qz + ax * qy - ay * qx; + out[7] = aw * qw - ax * qx - ay * qy - az * qz; + return out; +} +/** + * Rotates a dual quat by a given quaternion (q * a) + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat} q quaternion to rotate by + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @returns {quat2} out + */ + +function rotateByQuatPrepend(out, q, a) { + var qx = q[0], + qy = q[1], + qz = q[2], + qw = q[3], + bx = a[0], + by = a[1], + bz = a[2], + bw = a[3]; + out[0] = qx * bw + qw * bx + qy * bz - qz * by; + out[1] = qy * bw + qw * by + qz * bx - qx * bz; + out[2] = qz * bw + qw * bz + qx * by - qy * bx; + out[3] = qw * bw - qx * bx - qy * by - qz * bz; + bx = a[4]; + by = a[5]; + bz = a[6]; + bw = a[7]; + out[4] = qx * bw + qw * bx + qy * bz - qz * by; + out[5] = qy * bw + qw * by + qz * bx - qx * bz; + out[6] = qz * bw + qw * bz + qx * by - qy * bx; + out[7] = qw * bw - qx * bx - qy * by - qz * bz; + return out; +} +/** + * Rotates a dual quat around a given axis. Does the normalisation automatically + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the dual quaternion to rotate + * @param {ReadonlyVec3} axis the axis to rotate around + * @param {Number} rad how far the rotation should be + * @returns {quat2} out + */ + +function rotateAroundAxis(out, a, axis, rad) { + //Special case for rad = 0 + if (Math.abs(rad) < EPSILON) { + return copy$1(out, a); + } + + var axisLength = Math.hypot(axis[0], axis[1], axis[2]); + rad = rad * 0.5; + var s = Math.sin(rad); + var bx = s * axis[0] / axisLength; + var by = s * axis[1] / axisLength; + var bz = s * axis[2] / axisLength; + var bw = Math.cos(rad); + var ax1 = a[0], + ay1 = a[1], + az1 = a[2], + aw1 = a[3]; + out[0] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; + out[1] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; + out[2] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; + out[3] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; + var ax = a[4], + ay = a[5], + az = a[6], + aw = a[7]; + out[4] = ax * bw + aw * bx + ay * bz - az * by; + out[5] = ay * bw + aw * by + az * bx - ax * bz; + out[6] = az * bw + aw * bz + ax * by - ay * bx; + out[7] = aw * bw - ax * bx - ay * by - az * bz; + return out; +} +/** + * Adds two dual quat's + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the first operand + * @param {ReadonlyQuat2} b the second operand + * @returns {quat2} out + * @function + */ + +function add$1(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + out[4] = a[4] + b[4]; + out[5] = a[5] + b[5]; + out[6] = a[6] + b[6]; + out[7] = a[7] + b[7]; + return out; +} +/** + * Multiplies two dual quat's + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a the first operand + * @param {ReadonlyQuat2} b the second operand + * @returns {quat2} out + */ + +function multiply$1(out, a, b) { + var ax0 = a[0], + ay0 = a[1], + az0 = a[2], + aw0 = a[3], + bx1 = b[4], + by1 = b[5], + bz1 = b[6], + bw1 = b[7], + ax1 = a[4], + ay1 = a[5], + az1 = a[6], + aw1 = a[7], + bx0 = b[0], + by0 = b[1], + bz0 = b[2], + bw0 = b[3]; + out[0] = ax0 * bw0 + aw0 * bx0 + ay0 * bz0 - az0 * by0; + out[1] = ay0 * bw0 + aw0 * by0 + az0 * bx0 - ax0 * bz0; + out[2] = az0 * bw0 + aw0 * bz0 + ax0 * by0 - ay0 * bx0; + out[3] = aw0 * bw0 - ax0 * bx0 - ay0 * by0 - az0 * bz0; + out[4] = ax0 * bw1 + aw0 * bx1 + ay0 * bz1 - az0 * by1 + ax1 * bw0 + aw1 * bx0 + ay1 * bz0 - az1 * by0; + out[5] = ay0 * bw1 + aw0 * by1 + az0 * bx1 - ax0 * bz1 + ay1 * bw0 + aw1 * by0 + az1 * bx0 - ax1 * bz0; + out[6] = az0 * bw1 + aw0 * bz1 + ax0 * by1 - ay0 * bx1 + az1 * bw0 + aw1 * bz0 + ax1 * by0 - ay1 * bx0; + out[7] = aw0 * bw1 - ax0 * bx1 - ay0 * by1 - az0 * bz1 + aw1 * bw0 - ax1 * bx0 - ay1 * by0 - az1 * bz0; + return out; +} +/** + * Alias for {@link quat2.multiply} + * @function + */ + +var mul$1 = multiply$1; +/** + * Scales a dual quat by a scalar number + * + * @param {quat2} out the receiving dual quat + * @param {ReadonlyQuat2} a the dual quat to scale + * @param {Number} b amount to scale the dual quat by + * @returns {quat2} out + * @function + */ + +function scale$1(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + out[4] = a[4] * b; + out[5] = a[5] * b; + out[6] = a[6] * b; + out[7] = a[7] * b; + return out; +} +/** + * Calculates the dot product of two dual quat's (The dot product of the real parts) + * + * @param {ReadonlyQuat2} a the first operand + * @param {ReadonlyQuat2} b the second operand + * @returns {Number} dot product of a and b + * @function + */ + +var dot$2 = dot$3; +/** + * Performs a linear interpolation between two dual quats's + * NOTE: The resulting dual quaternions won't always be normalized (The error is most noticeable when t = 0.5) + * + * @param {quat2} out the receiving dual quat + * @param {ReadonlyQuat2} a the first operand + * @param {ReadonlyQuat2} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {quat2} out + */ + +function lerp$1(out, a, b, t) { + var mt = 1 - t; + if (dot$2(a, b) < 0) t = -t; + out[0] = a[0] * mt + b[0] * t; + out[1] = a[1] * mt + b[1] * t; + out[2] = a[2] * mt + b[2] * t; + out[3] = a[3] * mt + b[3] * t; + out[4] = a[4] * mt + b[4] * t; + out[5] = a[5] * mt + b[5] * t; + out[6] = a[6] * mt + b[6] * t; + out[7] = a[7] * mt + b[7] * t; + return out; +} +/** + * Calculates the inverse of a dual quat. If they are normalized, conjugate is cheaper + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a dual quat to calculate inverse of + * @returns {quat2} out + */ + +function invert(out, a) { + var sqlen = squaredLength$1(a); + out[0] = -a[0] / sqlen; + out[1] = -a[1] / sqlen; + out[2] = -a[2] / sqlen; + out[3] = a[3] / sqlen; + out[4] = -a[4] / sqlen; + out[5] = -a[5] / sqlen; + out[6] = -a[6] / sqlen; + out[7] = a[7] / sqlen; + return out; +} +/** + * Calculates the conjugate of a dual quat + * If the dual quaternion is normalized, this function is faster than quat2.inverse and produces the same result. + * + * @param {quat2} out the receiving quaternion + * @param {ReadonlyQuat2} a quat to calculate conjugate of + * @returns {quat2} out + */ + +function conjugate(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = a[3]; + out[4] = -a[4]; + out[5] = -a[5]; + out[6] = -a[6]; + out[7] = a[7]; + return out; +} +/** + * Calculates the length of a dual quat + * + * @param {ReadonlyQuat2} a dual quat to calculate length of + * @returns {Number} length of a + * @function + */ + +var length$1 = length$2; +/** + * Alias for {@link quat2.length} + * @function + */ + +var len$1 = length$1; +/** + * Calculates the squared length of a dual quat + * + * @param {ReadonlyQuat2} a dual quat to calculate squared length of + * @returns {Number} squared length of a + * @function + */ + +var squaredLength$1 = squaredLength$2; +/** + * Alias for {@link quat2.squaredLength} + * @function + */ + +var sqrLen$1 = squaredLength$1; +/** + * Normalize a dual quat + * + * @param {quat2} out the receiving dual quaternion + * @param {ReadonlyQuat2} a dual quaternion to normalize + * @returns {quat2} out + * @function + */ + +function normalize$1(out, a) { + var magnitude = squaredLength$1(a); + + if (magnitude > 0) { + magnitude = Math.sqrt(magnitude); + var a0 = a[0] / magnitude; + var a1 = a[1] / magnitude; + var a2 = a[2] / magnitude; + var a3 = a[3] / magnitude; + var b0 = a[4]; + var b1 = a[5]; + var b2 = a[6]; + var b3 = a[7]; + var a_dot_b = a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3; + out[0] = a0; + out[1] = a1; + out[2] = a2; + out[3] = a3; + out[4] = (b0 - a0 * a_dot_b) / magnitude; + out[5] = (b1 - a1 * a_dot_b) / magnitude; + out[6] = (b2 - a2 * a_dot_b) / magnitude; + out[7] = (b3 - a3 * a_dot_b) / magnitude; + } + + return out; +} +/** + * Returns a string representation of a dual quatenion + * + * @param {ReadonlyQuat2} a dual quaternion to represent as a string + * @returns {String} string representation of the dual quat + */ + +function str$1(a) { + return "quat2(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ", " + a[6] + ", " + a[7] + ")"; +} +/** + * Returns whether or not the dual quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyQuat2} a the first dual quaternion. + * @param {ReadonlyQuat2} b the second dual quaternion. + * @returns {Boolean} true if the dual quaternions are equal, false otherwise. + */ + +function exactEquals$1(a, b) { + 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]; +} +/** + * Returns whether or not the dual quaternions have approximately the same elements in the same position. + * + * @param {ReadonlyQuat2} a the first dual quat. + * @param {ReadonlyQuat2} b the second dual quat. + * @returns {Boolean} true if the dual quats are equal, false otherwise. + */ + +function equals$2(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3], + a4 = a[4], + a5 = a[5], + a6 = a[6], + a7 = a[7]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)); +} + +var quat2 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add$1, +clone: clone$1, +conjugate: conjugate, +copy: copy$1, +create: create$1, +dot: dot$2, +equals: equals$2, +exactEquals: exactEquals$1, +fromMat4: fromMat4, +fromRotation: fromRotation, +fromRotationTranslation: fromRotationTranslation, +fromRotationTranslationValues: fromRotationTranslationValues, +fromTranslation: fromTranslation, +fromValues: fromValues$1, +getDual: getDual, +getReal: getReal, +getTranslation: getTranslation, +identity: identity, +invert: invert, +len: len$1, +length: length$1, +lerp: lerp$1, +mul: mul$1, +multiply: multiply$1, +normalize: normalize$1, +rotateAroundAxis: rotateAroundAxis, +rotateByQuatAppend: rotateByQuatAppend, +rotateByQuatPrepend: rotateByQuatPrepend, +rotateX: rotateX, +rotateY: rotateY, +rotateZ: rotateZ, +scale: scale$1, +set: set$1, +setDual: setDual, +setReal: setReal, +sqrLen: sqrLen$1, +squaredLength: squaredLength$1, +str: str$1, +translate: translate +}); + +/** + * 2 Dimensional Vector + * @module vec2 + */ + +/** + * Creates a new, empty vec2 + * + * @returns {vec2} a new 2D vector + */ + +function create() { + var out = new ARRAY_TYPE(2); + + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + } + + return out; +} +/** + * Creates a new vec2 initialized with values from an existing vector + * + * @param {ReadonlyVec2} a vector to clone + * @returns {vec2} a new 2D vector + */ + +function clone(a) { + var out = new ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; +} +/** + * Creates a new vec2 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @returns {vec2} a new 2D vector + */ + +function fromValues(x, y) { + var out = new ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; +} +/** + * Copy the values from one vec2 to another + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the source vector + * @returns {vec2} out + */ + +function copy(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; +} +/** + * Set the components of a vec2 to the given values + * + * @param {vec2} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @returns {vec2} out + */ + +function set(out, x, y) { + out[0] = x; + out[1] = y; + return out; +} +/** + * Adds two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function add(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; +} +/** + * Subtracts vector b from vector a + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function subtract(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; +} +/** + * Multiplies two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function multiply(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; +} +/** + * Divides two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function divide(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; +} +/** + * Math.ceil the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to ceil + * @returns {vec2} out + */ + +function ceil(out, a) { + out[0] = Math.ceil(a[0]); + out[1] = Math.ceil(a[1]); + return out; +} +/** + * Math.floor the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to floor + * @returns {vec2} out + */ + +function floor(out, a) { + out[0] = Math.floor(a[0]); + out[1] = Math.floor(a[1]); + return out; +} +/** + * Returns the minimum of two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function min(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + return out; +} +/** + * Returns the maximum of two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec2} out + */ + +function max(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + return out; +} +/** + * Math.round the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to round + * @returns {vec2} out + */ + +function round(out, a) { + out[0] = Math.round(a[0]); + out[1] = Math.round(a[1]); + return out; +} +/** + * Scales a vec2 by a scalar number + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec2} out + */ + +function scale(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; +} +/** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec2} out + */ + +function scaleAndAdd(out, a, b, scale) { + out[0] = a[0] + b[0] * scale; + out[1] = a[1] + b[1] * scale; + return out; +} +/** + * Calculates the euclidian distance between two vec2's + * + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {Number} distance between a and b + */ + +function distance(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return Math.hypot(x, y); +} +/** + * Calculates the squared euclidian distance between two vec2's + * + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {Number} squared distance between a and b + */ + +function squaredDistance(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return x * x + y * y; +} +/** + * Calculates the length of a vec2 + * + * @param {ReadonlyVec2} a vector to calculate length of + * @returns {Number} length of a + */ + +function length(a) { + var x = a[0], + y = a[1]; + return Math.hypot(x, y); +} +/** + * Calculates the squared length of a vec2 + * + * @param {ReadonlyVec2} a vector to calculate squared length of + * @returns {Number} squared length of a + */ + +function squaredLength(a) { + var x = a[0], + y = a[1]; + return x * x + y * y; +} +/** + * Negates the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to negate + * @returns {vec2} out + */ + +function negate(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; +} +/** + * Returns the inverse of the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to invert + * @returns {vec2} out + */ + +function inverse(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + return out; +} +/** + * Normalize a vec2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a vector to normalize + * @returns {vec2} out + */ + +function normalize(out, a) { + var x = a[0], + y = a[1]; + var len = x * x + y * y; + + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + } + + out[0] = a[0] * len; + out[1] = a[1] * len; + return out; +} +/** + * Calculates the dot product of two vec2's + * + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {Number} dot product of a and b + */ + +function dot$1(a, b) { + return a[0] * b[0] + a[1] * b[1]; +} +/** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @returns {vec3} out + */ + +function cross(out, a, b) { + var z = a[0] * b[1] - a[1] * b[0]; + out[0] = out[1] = 0; + out[2] = z; + return out; +} +/** + * Performs a linear interpolation between two vec2's + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the first operand + * @param {ReadonlyVec2} b the second operand + * @param {Number} t interpolation amount, in the range [0-1], between the two inputs + * @returns {vec2} out + */ + +function lerp(out, a, b, t) { + var ax = a[0], + ay = a[1]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + return out; +} +/** + * Generates a random vector with the given scale + * + * @param {vec2} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec2} out + */ + +function random(out, scale) { + scale = scale || 1.0; + var r = RANDOM() * 2.0 * Math.PI; + out[0] = Math.cos(r) * scale; + out[1] = Math.sin(r) * scale; + return out; +} +/** + * Transforms the vec2 with a mat2 + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to transform + * @param {ReadonlyMat2} m matrix to transform with + * @returns {vec2} out + */ + +function transformMat2(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[2] * y; + out[1] = m[1] * x + m[3] * y; + return out; +} +/** + * Transforms the vec2 with a mat2d + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to transform + * @param {ReadonlyMat2d} m matrix to transform with + * @returns {vec2} out + */ + +function transformMat2d(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[2] * y + m[4]; + out[1] = m[1] * x + m[3] * y + m[5]; + return out; +} +/** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to transform + * @param {ReadonlyMat3} m matrix to transform with + * @returns {vec2} out + */ + +function transformMat3(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[3] * y + m[6]; + out[1] = m[1] * x + m[4] * y + m[7]; + return out; +} +/** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to transform + * @param {ReadonlyMat4} m matrix to transform with + * @returns {vec2} out + */ + +function transformMat4(out, a, m) { + var x = a[0]; + var y = a[1]; + out[0] = m[0] * x + m[4] * y + m[12]; + out[1] = m[1] * x + m[5] * y + m[13]; + return out; +} +/** + * Rotate a 2D vector + * @param {vec2} out The receiving vec2 + * @param {ReadonlyVec2} a The vec2 point to rotate + * @param {ReadonlyVec2} b The origin of the rotation + * @param {Number} rad The angle of rotation in radians + * @returns {vec2} out + */ + +function rotate(out, a, b, rad) { + //Translate point to the origin + var p0 = a[0] - b[0], + p1 = a[1] - b[1], + sinC = Math.sin(rad), + cosC = Math.cos(rad); //perform rotation and translate to correct position + + out[0] = p0 * cosC - p1 * sinC + b[0]; + out[1] = p0 * sinC + p1 * cosC + b[1]; + return out; +} +/** + * Get the angle between two 2D vectors + * @param {ReadonlyVec2} a The first operand + * @param {ReadonlyVec2} b The second operand + * @returns {Number} The angle in radians + */ + +function angle(a, b) { + var x1 = a[0], + y1 = a[1], + x2 = b[0], + y2 = b[1], + // mag is the product of the magnitudes of a and b + mag = Math.sqrt(x1 * x1 + y1 * y1) * Math.sqrt(x2 * x2 + y2 * y2), + // mag &&.. short circuits if mag == 0 + cosine = mag && (x1 * x2 + y1 * y2) / mag; // Math.min(Math.max(cosine, -1), 1) clamps the cosine between -1 and 1 + + return Math.acos(Math.min(Math.max(cosine, -1), 1)); +} +/** + * Set the components of a vec2 to zero + * + * @param {vec2} out the receiving vector + * @returns {vec2} out + */ + +function zero(out) { + out[0] = 0.0; + out[1] = 0.0; + return out; +} +/** + * Returns a string representation of a vector + * + * @param {ReadonlyVec2} a vector to represent as a string + * @returns {String} string representation of the vector + */ + +function str(a) { + return "vec2(" + a[0] + ", " + a[1] + ")"; +} +/** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) + * + * @param {ReadonlyVec2} a The first vector. + * @param {ReadonlyVec2} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function exactEquals(a, b) { + return a[0] === b[0] && a[1] === b[1]; +} +/** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {ReadonlyVec2} a The first vector. + * @param {ReadonlyVec2} b The second vector. + * @returns {Boolean} True if the vectors are equal, false otherwise. + */ + +function equals$1(a, b) { + var a0 = a[0], + a1 = a[1]; + var b0 = b[0], + b1 = b[1]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)); +} +/** + * Alias for {@link vec2.length} + * @function + */ + +var len = length; +/** + * Alias for {@link vec2.subtract} + * @function + */ + +var sub = subtract; +/** + * Alias for {@link vec2.multiply} + * @function + */ + +var mul = multiply; +/** + * Alias for {@link vec2.divide} + * @function + */ + +var div = divide; +/** + * Alias for {@link vec2.distance} + * @function + */ + +var dist = distance; +/** + * Alias for {@link vec2.squaredDistance} + * @function + */ + +var sqrDist = squaredDistance; +/** + * Alias for {@link vec2.squaredLength} + * @function + */ + +var sqrLen = squaredLength; +/** + * Perform some operation over an array of vec2s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ + +var forEach = function () { + var vec = create(); + return function (a, stride, offset, count, fn, arg) { + var i, l; + + if (!stride) { + stride = 2; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min(count * stride + offset, a.length); + } else { + l = a.length; + } + + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + } + + return a; + }; +}(); + +var vec2 = /*#__PURE__*/Object.freeze({ +__proto__: null, +add: add, +angle: angle, +ceil: ceil, +clone: clone, +copy: copy, +create: create, +cross: cross, +dist: dist, +distance: distance, +div: div, +divide: divide, +dot: dot$1, +equals: equals$1, +exactEquals: exactEquals, +floor: floor, +forEach: forEach, +fromValues: fromValues, +inverse: inverse, +len: len, +length: length, +lerp: lerp, +max: max, +min: min, +mul: mul, +multiply: multiply, +negate: negate, +normalize: normalize, +random: random, +rotate: rotate, +round: round, +scale: scale, +scaleAndAdd: scaleAndAdd, +set: set, +sqrDist: sqrDist, +sqrLen: sqrLen, +squaredDistance: squaredDistance, +squaredLength: squaredLength, +str: str, +sub: sub, +subtract: subtract, +transformMat2: transformMat2, +transformMat2d: transformMat2d, +transformMat3: transformMat3, +transformMat4: transformMat4, +zero: zero +}); + +/** + * A style layer that defines a circle + */ +class CircleStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$8); + } + createBucket(parameters) { + return new CircleBucket(parameters); + } + queryRadius(bucket) { + const circleBucket = bucket; + return getMaximumPaintValue('circle-radius', this, circleBucket) + + getMaximumPaintValue('circle-stroke-width', this, circleBucket) + + translateDistance(this.paint.get('circle-translate')); + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits, pixelPosMatrix) { + const translatedPolygon = translate$4(queryGeometry, this.paint.get('circle-translate'), this.paint.get('circle-translate-anchor'), transform.angle, pixelsToTileUnits); + const radius = this.paint.get('circle-radius').evaluate(feature, featureState); + const stroke = this.paint.get('circle-stroke-width').evaluate(feature, featureState); + const size = radius + stroke; + // For pitch-alignment: map, compare feature geometry to query geometry in the plane of the tile + // // Otherwise, compare geometry in the plane of the viewport + // // A circle with fixed scaling relative to the viewport gets larger in tile space as it moves into the distance + // // A circle with fixed scaling relative to the map gets smaller in viewport space as it moves into the distance + const alignWithMap = this.paint.get('circle-pitch-alignment') === 'map'; + const transformedPolygon = alignWithMap ? translatedPolygon : projectQueryGeometry$1(translatedPolygon, pixelPosMatrix); + const transformedSize = alignWithMap ? size * pixelsToTileUnits : size; + for (const ring of geometry) { + for (const point of ring) { + const transformedPoint = alignWithMap ? point : projectPoint(point, pixelPosMatrix); + let adjustedSize = transformedSize; + const projectedCenter = transformMat4$1([], [point.x, point.y, 0, 1], pixelPosMatrix); + if (this.paint.get('circle-pitch-scale') === 'viewport' && this.paint.get('circle-pitch-alignment') === 'map') { + adjustedSize *= projectedCenter[3] / transform.cameraToCenterDistance; + } + else if (this.paint.get('circle-pitch-scale') === 'map' && this.paint.get('circle-pitch-alignment') === 'viewport') { + adjustedSize *= transform.cameraToCenterDistance / projectedCenter[3]; + } + if (polygonIntersectsBufferedPoint(transformedPolygon, transformedPoint, adjustedSize)) + return true; + } + } + return false; + } +} +function projectPoint(p, pixelPosMatrix) { + const point = transformMat4$1([], [p.x, p.y, 0, 1], pixelPosMatrix); + return new Point$2(point[0] / point[3], point[1] / point[3]); +} +function projectQueryGeometry$1(queryGeometry, pixelPosMatrix) { + return queryGeometry.map((p) => { + return projectPoint(p, pixelPosMatrix); + }); +} + +class HeatmapBucket extends CircleBucket { +} +register('HeatmapBucket', HeatmapBucket, { omit: ['layers'] }); + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$7; +const getPaint$7 = () => paint$7 = paint$7 || new Properties({ + "heatmap-radius": new DataDrivenProperty(v8Spec["paint_heatmap"]["heatmap-radius"]), + "heatmap-weight": new DataDrivenProperty(v8Spec["paint_heatmap"]["heatmap-weight"]), + "heatmap-intensity": new DataConstantProperty(v8Spec["paint_heatmap"]["heatmap-intensity"]), + "heatmap-color": new ColorRampProperty(v8Spec["paint_heatmap"]["heatmap-color"]), + "heatmap-opacity": new DataConstantProperty(v8Spec["paint_heatmap"]["heatmap-opacity"]), +}); +var properties$7 = ({ get paint() { return getPaint$7(); } }); + +function createImage(image, { width, height }, channels, data) { + if (!data) { + data = new Uint8Array(width * height * channels); + } + else if (data instanceof Uint8ClampedArray) { + data = new Uint8Array(data.buffer); + } + else if (data.length !== width * height * channels) { + throw new RangeError(`mismatched image size. expected: ${data.length} but got: ${width * height * channels}`); + } + image.width = width; + image.height = height; + image.data = data; + return image; +} +function resizeImage(image, { width, height }, channels) { + if (width === image.width && height === image.height) { + return; + } + const newImage = createImage({}, { width, height }, channels); + copyImage(image, newImage, { x: 0, y: 0 }, { x: 0, y: 0 }, { + width: Math.min(image.width, width), + height: Math.min(image.height, height) + }, channels); + image.width = width; + image.height = height; + image.data = newImage.data; +} +function copyImage(srcImg, dstImg, srcPt, dstPt, size, channels) { + if (size.width === 0 || size.height === 0) { + return dstImg; + } + if (size.width > srcImg.width || + size.height > srcImg.height || + srcPt.x > srcImg.width - size.width || + srcPt.y > srcImg.height - size.height) { + throw new RangeError('out of range source coordinates for image copy'); + } + if (size.width > dstImg.width || + size.height > dstImg.height || + dstPt.x > dstImg.width - size.width || + dstPt.y > dstImg.height - size.height) { + throw new RangeError('out of range destination coordinates for image copy'); + } + const srcData = srcImg.data; + const dstData = dstImg.data; + if (srcData === dstData) + throw new Error('srcData equals dstData, so image is already copied'); + for (let y = 0; y < size.height; y++) { + const srcOffset = ((srcPt.y + y) * srcImg.width + srcPt.x) * channels; + const dstOffset = ((dstPt.y + y) * dstImg.width + dstPt.x) * channels; + for (let i = 0; i < size.width * channels; i++) { + dstData[dstOffset + i] = srcData[srcOffset + i]; + } + } + return dstImg; +} +/** + * An image with alpha color value + */ +class AlphaImage { + constructor(size, data) { + createImage(this, size, 1, data); + } + resize(size) { + resizeImage(this, size, 1); + } + clone() { + return new AlphaImage({ width: this.width, height: this.height }, new Uint8Array(this.data)); + } + static copy(srcImg, dstImg, srcPt, dstPt, size) { + copyImage(srcImg, dstImg, srcPt, dstPt, size, 1); + } +} +/** + * An object to store image data not premultiplied, because ImageData is not premultiplied. + * UNPACK_PREMULTIPLY_ALPHA_WEBGL must be used when uploading to a texture. + */ +class RGBAImage { + constructor(size, data) { + createImage(this, size, 4, data); + } + resize(size) { + resizeImage(this, size, 4); + } + replace(data, copy) { + if (copy) { + this.data.set(data); + } + else if (data instanceof Uint8ClampedArray) { + this.data = new Uint8Array(data.buffer); + } + else { + this.data = data; + } + } + clone() { + return new RGBAImage({ width: this.width, height: this.height }, new Uint8Array(this.data)); + } + static copy(srcImg, dstImg, srcPt, dstPt, size) { + copyImage(srcImg, dstImg, srcPt, dstPt, size, 4); + } +} +register('AlphaImage', AlphaImage); +register('RGBAImage', RGBAImage); + +/** + * Given an expression that should evaluate to a color ramp, + * return a RGBA image representing that ramp expression. + */ +function renderColorRamp(params) { + const evaluationGlobals = {}; + const width = params.resolution || 256; + const height = params.clips ? params.clips.length : 1; + const image = params.image || new RGBAImage({ width, height }); + if (!isPowerOfTwo(width)) + throw new Error(`width is not a power of 2 - ${width}`); + const renderPixel = (stride, index, progress) => { + evaluationGlobals[params.evaluationKey] = progress; + const pxColor = params.expression.evaluate(evaluationGlobals); + // the colors are being unpremultiplied because Color uses + // premultiplied values, and the Texture class expects unpremultiplied ones + image.data[stride + index + 0] = Math.floor(pxColor.r * 255 / pxColor.a); + image.data[stride + index + 1] = Math.floor(pxColor.g * 255 / pxColor.a); + image.data[stride + index + 2] = Math.floor(pxColor.b * 255 / pxColor.a); + image.data[stride + index + 3] = Math.floor(pxColor.a * 255); + }; + if (!params.clips) { + for (let i = 0, j = 0; i < width; i++, j += 4) { + const progress = i / (width - 1); + renderPixel(0, j, progress); + } + } + else { + for (let clip = 0, stride = 0; clip < height; ++clip, stride += width * 4) { + for (let i = 0, j = 0; i < width; i++, j += 4) { + // Remap progress between clips + const progress = i / (width - 1); + const { start, end } = params.clips[clip]; + const evaluationProgress = start * (1 - progress) + end * progress; + renderPixel(stride, j, evaluationProgress); + } + } + } + return image; +} + +const HEATMAP_FULL_RENDER_FBO_KEY = 'big-fb'; +/** + * A style layer that defines a heatmap + */ +class HeatmapStyleLayer extends StyleLayer { + createBucket(options) { + return new HeatmapBucket(options); + } + constructor(layer) { + super(layer, properties$7); + this.heatmapFbos = new Map(); + // make sure color ramp texture is generated for default heatmap color too + this._updateColorRamp(); + } + _handleSpecialPaintPropertyUpdate(name) { + if (name === 'heatmap-color') { + this._updateColorRamp(); + } + } + _updateColorRamp() { + const expression = this._transitionablePaint._values['heatmap-color'].value.expression; + this.colorRamp = renderColorRamp({ + expression, + evaluationKey: 'heatmapDensity', + image: this.colorRamp + }); + this.colorRampTexture = null; + } + resize() { + if (this.heatmapFbos.has(HEATMAP_FULL_RENDER_FBO_KEY)) { + this.heatmapFbos.delete(HEATMAP_FULL_RENDER_FBO_KEY); + } + } + queryRadius() { + return 0; + } + queryIntersectsFeature() { + return false; + } + hasOffscreenPass() { + return this.paint.get('heatmap-opacity') !== 0 && this.visibility !== 'none'; + } +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$6; +const getPaint$6 = () => paint$6 = paint$6 || new Properties({ + "hillshade-illumination-direction": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-illumination-direction"]), + "hillshade-illumination-anchor": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-illumination-anchor"]), + "hillshade-exaggeration": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-exaggeration"]), + "hillshade-shadow-color": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-shadow-color"]), + "hillshade-highlight-color": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-highlight-color"]), + "hillshade-accent-color": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-accent-color"]), +}); +var properties$6 = ({ get paint() { return getPaint$6(); } }); + +class HillshadeStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$6); + } + hasOffscreenPass() { + return this.paint.get('hillshade-exaggeration') !== 0 && this.visibility !== 'none'; + } +} + +const layout$4 = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' } +], 4); +const { members: members$3, size: size$3, alignment: alignment$3 } = layout$4; + +function earcut(data, holeIndices, dim = 2) { + + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data.length; + let outerNode = linkedList(data, 0, outerLen, dim, true); + const triangles = []; + + if (!outerNode || outerNode.next === outerNode.prev) return triangles; + + let minX, minY, invSize; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = Infinity; + minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + + for (let i = dim; i < outerLen; i += dim) { + const x = data[i]; + const y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + let last; + + if (clockwise === (signedArea$1(data, start, end, dim) > 0)) { + for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); + } else { + for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + let p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + + let stop = ear; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + const prev = ear.prev; + const next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + triangles.push(prev.i, ear.i, next.i); // cut off the triangle + + removeNode(ear); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + const a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + let p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, invSize) { + const a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + // z-order range for the current triangle bbox; + const minZ = zOrder(x0, y0, minX, minY, invSize), + maxZ = zOrder(x1, y1, minX, minY, invSize); + + let p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles) { + let p = start; + do { + const a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i, p.i, b.i); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return filterPoints(p); +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + let a = start; + do { + let b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + let c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + const queue = []; + + for (let i = 0, len = holeIndices.length; i < len; i++) { + const start = holeIndices[i] * dim; + const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + const list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (let i = 0; i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + const bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + + const bridgeReverse = splitPolygon(bridge, hole); + + // filter collinear points around the cuts + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + let p = outerNode; + const hx = hole.x; + const hy = hole.y; + let qx = -Infinity; + let m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + const stop = m; + const mx = m.x; + const my = m.y; + let tanMin = Infinity; + + p = m; + + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if (locallyInside(p, hole) && + (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } while (p !== stop); + + return m; +} + +// whether sector in vertex m contains sector in vertex p in the same coordinates +function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, invSize) { + let p = start; + do { + if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + let numMerges; + let inSize = 1; + + do { + let p = list; + let e; + list = null; + let tail = null; + numMerges = 0; + + while (p) { + numMerges++; + let q = p; + let pSize = 0; + for (let i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + let qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + let p = start, + leftmost = start; + do { + if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && + (ax - px) * (by - py) >= (bx - px) * (ay - py) && + (bx - px) * (cy - py) >= (cx - px) * (by - py); +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges + (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors + equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + const o1 = sign(area(p1, q1, p2)); + const o2 = sign(area(p1, q1, q2)); + const o3 = sign(area(p2, q2, p1)); + const o4 = sign(area(p2, q2, q1)); + + if (o1 !== o2 && o3 !== o4) return true; // general case + + if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + + return false; +} + +// for collinear points p, q, r, check if point q lies on segment pr +function onSegment(p, q, r) { + 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); +} + +function sign(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + let p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + let p = a; + let inside = false; + const px = (a.x + b.x) / 2; + const py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + const a2 = createNode(a.i, a.x, a.y), + b2 = createNode(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + const p = createNode(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function createNode(i, x, y) { + return { + i, // vertex index in coordinates array + x, y, // vertex coordinates + prev: null, // previous and next vertex nodes in a polygon ring + next: null, + z: 0, // z-order curve value + prevZ: null, // previous and next nodes in z-order + nextZ: null, + steiner: false // indicates whether this is a steiner point + }; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +function deviation(data, holeIndices, dim, triangles) { + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + let polygonArea = Math.abs(signedArea$1(data, 0, outerLen, dim)); + if (hasHoles) { + for (let i = 0, len = holeIndices.length; i < len; i++) { + const start = holeIndices[i] * dim; + const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea$1(data, start, end, dim)); + } + } + + let trianglesArea = 0; + for (let i = 0; i < triangles.length; i += 3) { + const a = triangles[i] * dim; + const b = triangles[i + 1] * dim; + const c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +} + +function signedArea$1(data, start, end, dim) { + let sum = 0; + for (let i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +function flatten(data) { + const vertices = []; + const holes = []; + const dimensions = data[0][0].length; + let holeIndex = 0; + let prevLen = 0; + + for (const ring of data) { + for (const p of ring) { + for (let d = 0; d < dimensions; d++) vertices.push(p[d]); + } + if (prevLen) { + holeIndex += prevLen; + holes.push(holeIndex); + } + prevLen = ring.length; + } + return {vertices, holes, dimensions}; +} + +function hasPattern(type, layers, options) { + const patterns = options.patternDependencies; + let hasPattern = false; + for (const layer of layers) { + const patternProperty = layer.paint.get(`${type}-pattern`); + if (!patternProperty.isConstant()) { + hasPattern = true; + } + const constantPattern = patternProperty.constantOr(null); + if (constantPattern) { + hasPattern = true; + patterns[constantPattern.to] = true; + patterns[constantPattern.from] = true; + } + } + return hasPattern; +} +function addPatternDependencies(type, layers, patternFeature, zoom, options) { + const patterns = options.patternDependencies; + for (const layer of layers) { + const patternProperty = layer.paint.get(`${type}-pattern`); + const patternPropertyValue = patternProperty.value; + if (patternPropertyValue.kind !== 'constant') { + let min = patternPropertyValue.evaluate({ zoom: zoom - 1 }, patternFeature, {}, options.availableImages); + let mid = patternPropertyValue.evaluate({ zoom }, patternFeature, {}, options.availableImages); + let max = patternPropertyValue.evaluate({ zoom: zoom + 1 }, patternFeature, {}, options.availableImages); + min = min && min.name ? min.name : min; + mid = mid && mid.name ? mid.name : mid; + max = max && max.name ? max.name : max; + // add to patternDependencies + patterns[min] = true; + patterns[mid] = true; + patterns[max] = true; + // save for layout + patternFeature.patterns[layer.id] = { min, mid, max }; + } + } + return patternFeature; +} + +const EARCUT_MAX_RINGS$1 = 500; +class FillBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.patternFeatures = []; + this.layoutVertexArray = new FillLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.indexArray2 = new LineIndexArray(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.segments = new SegmentVector(); + this.segments2 = new SegmentVector(); + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + this.hasPattern = hasPattern('fill', this.layers, options); + const fillSortKey = this.layers[0].layout.get('fill-sort-key'); + const sortFeaturesByKey = !fillSortKey.isConstant(); + const bucketFeatures = []; + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const sortKey = sortFeaturesByKey ? + fillSortKey.evaluate(evaluationFeature, {}, canonical, options.availableImages) : + undefined; + const bucketFeature = { + id, + properties: feature.properties, + type: feature.type, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + patterns: {}, + sortKey + }; + bucketFeatures.push(bucketFeature); + } + if (sortFeaturesByKey) { + bucketFeatures.sort((a, b) => a.sortKey - b.sortKey); + } + for (const bucketFeature of bucketFeatures) { + const { geometry, index, sourceLayerIndex } = bucketFeature; + if (this.hasPattern) { + const patternFeature = addPatternDependencies('fill', this.layers, bucketFeature, this.zoom, options); + // pattern features are added only once the pattern is loaded into the image atlas + // so are stored during populate until later updated with positions by tile worker in addFeatures + this.patternFeatures.push(patternFeature); + } + else { + this.addFeature(bucketFeature, geometry, index, canonical, {}); + } + const feature = features[index].feature; + options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + addFeatures(options, canonical, imagePositions) { + for (const feature of this.patternFeatures) { + this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions); + } + } + isEmpty() { + return this.layoutVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$3); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + this.indexBuffer2 = context.createIndexBuffer(this.indexArray2); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.indexBuffer2.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + this.segments2.destroy(); + } + addFeature(feature, geometry, index, canonical, imagePositions) { + for (const polygon of classifyRings$1(geometry, EARCUT_MAX_RINGS$1)) { + let numVertices = 0; + for (const ring of polygon) { + numVertices += ring.length; + } + const triangleSegment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray); + const triangleIndex = triangleSegment.vertexLength; + const flattened = []; + const holeIndices = []; + for (const ring of polygon) { + if (ring.length === 0) { + continue; + } + if (ring !== polygon[0]) { + holeIndices.push(flattened.length / 2); + } + const lineSegment = this.segments2.prepareSegment(ring.length, this.layoutVertexArray, this.indexArray2); + const lineIndex = lineSegment.vertexLength; + this.layoutVertexArray.emplaceBack(ring[0].x, ring[0].y); + this.indexArray2.emplaceBack(lineIndex + ring.length - 1, lineIndex); + flattened.push(ring[0].x); + flattened.push(ring[0].y); + for (let i = 1; i < ring.length; i++) { + this.layoutVertexArray.emplaceBack(ring[i].x, ring[i].y); + this.indexArray2.emplaceBack(lineIndex + i - 1, lineIndex + i); + flattened.push(ring[i].x); + flattened.push(ring[i].y); + } + lineSegment.vertexLength += ring.length; + lineSegment.primitiveLength += ring.length; + } + const indices = earcut(flattened, holeIndices); + for (let i = 0; i < indices.length; i += 3) { + this.indexArray.emplaceBack(triangleIndex + indices[i], triangleIndex + indices[i + 1], triangleIndex + indices[i + 2]); + } + triangleSegment.vertexLength += numVertices; + triangleSegment.primitiveLength += indices.length / 3; + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical); + } +} +register('FillBucket', FillBucket, { omit: ['layers', 'patternFeatures'] }); + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout$3; +const getLayout$2 = () => layout$3 = layout$3 || new Properties({ + "fill-sort-key": new DataDrivenProperty(v8Spec["layout_fill"]["fill-sort-key"]), +}); +let paint$5; +const getPaint$5 = () => paint$5 = paint$5 || new Properties({ + "fill-antialias": new DataConstantProperty(v8Spec["paint_fill"]["fill-antialias"]), + "fill-opacity": new DataDrivenProperty(v8Spec["paint_fill"]["fill-opacity"]), + "fill-color": new DataDrivenProperty(v8Spec["paint_fill"]["fill-color"]), + "fill-outline-color": new DataDrivenProperty(v8Spec["paint_fill"]["fill-outline-color"]), + "fill-translate": new DataConstantProperty(v8Spec["paint_fill"]["fill-translate"]), + "fill-translate-anchor": new DataConstantProperty(v8Spec["paint_fill"]["fill-translate-anchor"]), + "fill-pattern": new CrossFadedDataDrivenProperty(v8Spec["paint_fill"]["fill-pattern"]), +}); +var properties$5 = ({ get paint() { return getPaint$5(); }, get layout() { return getLayout$2(); } }); + +class FillStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$5); + } + recalculate(parameters, availableImages) { + super.recalculate(parameters, availableImages); + const outlineColor = this.paint._values['fill-outline-color']; + if (outlineColor.value.kind === 'constant' && outlineColor.value.value === undefined) { + this.paint._values['fill-outline-color'] = this.paint._values['fill-color']; + } + } + createBucket(parameters) { + return new FillBucket(parameters); + } + queryRadius() { + return translateDistance(this.paint.get('fill-translate')); + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits) { + const translatedPolygon = translate$4(queryGeometry, this.paint.get('fill-translate'), this.paint.get('fill-translate-anchor'), transform.angle, pixelsToTileUnits); + return polygonIntersectsMultiPolygon(translatedPolygon, geometry); + } + isTileClipped() { + return true; + } +} + +const layout$2 = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' }, + { name: 'a_normal_ed', components: 4, type: 'Int16' }, +], 4); +const centroidAttributes = createLayout([ + { name: 'a_centroid', components: 2, type: 'Int16' } +], 4); +const { members: members$2, size: size$2, alignment: alignment$2 } = layout$2; + +var vectorTile = {}; + +'use strict'; + +var Point = pointGeometry; + +var vectortilefeature = VectorTileFeature$2; + +function VectorTileFeature$2(pbf, end, extent, keys, values) { + // Public + this.properties = {}; + this.extent = extent; + this.type = 0; + + // Private + this._pbf = pbf; + this._geometry = -1; + this._keys = keys; + this._values = values; + + pbf.readFields(readFeature, this, end); +} + +function readFeature(tag, feature, pbf) { + if (tag == 1) feature.id = pbf.readVarint(); + else if (tag == 2) readTag(pbf, feature); + else if (tag == 3) feature.type = pbf.readVarint(); + else if (tag == 4) feature._geometry = pbf.pos; +} + +function readTag(pbf, feature) { + var end = pbf.readVarint() + pbf.pos; + + while (pbf.pos < end) { + var key = feature._keys[pbf.readVarint()], + value = feature._values[pbf.readVarint()]; + feature.properties[key] = value; + } +} + +VectorTileFeature$2.types = ['Unknown', 'Point', 'LineString', 'Polygon']; + +VectorTileFeature$2.prototype.loadGeometry = function() { + var pbf = this._pbf; + pbf.pos = this._geometry; + + var end = pbf.readVarint() + pbf.pos, + cmd = 1, + length = 0, + x = 0, + y = 0, + lines = [], + line; + + while (pbf.pos < end) { + if (length <= 0) { + var cmdLen = pbf.readVarint(); + cmd = cmdLen & 0x7; + length = cmdLen >> 3; + } + + length--; + + if (cmd === 1 || cmd === 2) { + x += pbf.readSVarint(); + y += pbf.readSVarint(); + + if (cmd === 1) { // moveTo + if (line) lines.push(line); + line = []; + } + + line.push(new Point(x, y)); + + } else if (cmd === 7) { + + // Workaround for https://github.com/mapbox/mapnik-vector-tile/issues/90 + if (line) { + line.push(line[0].clone()); // closePolygon + } + + } else { + throw new Error('unknown command ' + cmd); + } + } + + if (line) lines.push(line); + + return lines; +}; + +VectorTileFeature$2.prototype.bbox = function() { + var pbf = this._pbf; + pbf.pos = this._geometry; + + var end = pbf.readVarint() + pbf.pos, + cmd = 1, + length = 0, + x = 0, + y = 0, + x1 = Infinity, + x2 = -Infinity, + y1 = Infinity, + y2 = -Infinity; + + while (pbf.pos < end) { + if (length <= 0) { + var cmdLen = pbf.readVarint(); + cmd = cmdLen & 0x7; + length = cmdLen >> 3; + } + + length--; + + if (cmd === 1 || cmd === 2) { + x += pbf.readSVarint(); + y += pbf.readSVarint(); + if (x < x1) x1 = x; + if (x > x2) x2 = x; + if (y < y1) y1 = y; + if (y > y2) y2 = y; + + } else if (cmd !== 7) { + throw new Error('unknown command ' + cmd); + } + } + + return [x1, y1, x2, y2]; +}; + +VectorTileFeature$2.prototype.toGeoJSON = function(x, y, z) { + var size = this.extent * Math.pow(2, z), + x0 = this.extent * x, + y0 = this.extent * y, + coords = this.loadGeometry(), + type = VectorTileFeature$2.types[this.type], + i, j; + + function project(line) { + for (var j = 0; j < line.length; j++) { + var p = line[j], y2 = 180 - (p.y + y0) * 360 / size; + line[j] = [ + (p.x + x0) * 360 / size - 180, + 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90 + ]; + } + } + + switch (this.type) { + case 1: + var points = []; + for (i = 0; i < coords.length; i++) { + points[i] = coords[i][0]; + } + coords = points; + project(coords); + break; + + case 2: + for (i = 0; i < coords.length; i++) { + project(coords[i]); + } + break; + + case 3: + coords = classifyRings(coords); + for (i = 0; i < coords.length; i++) { + for (j = 0; j < coords[i].length; j++) { + project(coords[i][j]); + } + } + break; + } + + if (coords.length === 1) { + coords = coords[0]; + } else { + type = 'Multi' + type; + } + + var result = { + type: "Feature", + geometry: { + type: type, + coordinates: coords + }, + properties: this.properties + }; + + if ('id' in this) { + result.id = this.id; + } + + return result; +}; + +// classifies an array of rings into polygons with outer rings and holes + +function classifyRings(rings) { + var len = rings.length; + + if (len <= 1) return [rings]; + + var polygons = [], + polygon, + ccw; + + for (var i = 0; i < len; i++) { + var area = signedArea(rings[i]); + if (area === 0) continue; + + if (ccw === undefined) ccw = area < 0; + + if (ccw === area < 0) { + if (polygon) polygons.push(polygon); + polygon = [rings[i]]; + + } else { + polygon.push(rings[i]); + } + } + if (polygon) polygons.push(polygon); + + return polygons; +} + +function signedArea(ring) { + var sum = 0; + for (var i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + return sum; +} + +var vectortilefeature$1 = /*@__PURE__*/getDefaultExportFromCjs$1(vectortilefeature); + +'use strict'; + +var VectorTileFeature$1 = vectortilefeature; + +var vectortilelayer = VectorTileLayer$2; + +function VectorTileLayer$2(pbf, end) { + // Public + this.version = 1; + this.name = null; + this.extent = 4096; + this.length = 0; + + // Private + this._pbf = pbf; + this._keys = []; + this._values = []; + this._features = []; + + pbf.readFields(readLayer, this, end); + + this.length = this._features.length; +} + +function readLayer(tag, layer, pbf) { + if (tag === 15) layer.version = pbf.readVarint(); + else if (tag === 1) layer.name = pbf.readString(); + else if (tag === 5) layer.extent = pbf.readVarint(); + else if (tag === 2) layer._features.push(pbf.pos); + else if (tag === 3) layer._keys.push(pbf.readString()); + else if (tag === 4) layer._values.push(readValueMessage(pbf)); +} + +function readValueMessage(pbf) { + var value = null, + end = pbf.readVarint() + pbf.pos; + + while (pbf.pos < end) { + var tag = pbf.readVarint() >> 3; + + value = tag === 1 ? pbf.readString() : + tag === 2 ? pbf.readFloat() : + tag === 3 ? pbf.readDouble() : + tag === 4 ? pbf.readVarint64() : + tag === 5 ? pbf.readVarint() : + tag === 6 ? pbf.readSVarint() : + tag === 7 ? pbf.readBoolean() : null; + } + + return value; +} + +// return feature `i` from this layer as a `VectorTileFeature` +VectorTileLayer$2.prototype.feature = function(i) { + if (i < 0 || i >= this._features.length) throw new Error('feature index out of bounds'); + + this._pbf.pos = this._features[i]; + + var end = this._pbf.readVarint() + this._pbf.pos; + return new VectorTileFeature$1(this._pbf, end, this.extent, this._keys, this._values); +}; + +var vectortilelayer$1 = /*@__PURE__*/getDefaultExportFromCjs$1(vectortilelayer); + +'use strict'; + +var VectorTileLayer$1 = vectortilelayer; + +var vectortile = VectorTile$1; + +function VectorTile$1(pbf, end) { + this.layers = pbf.readFields(readTile, {}, end); +} + +function readTile(tag, layers, pbf) { + if (tag === 3) { + var layer = new VectorTileLayer$1(pbf, pbf.readVarint() + pbf.pos); + if (layer.length) layers[layer.name] = layer; + } +} + +var vectortile$1 = /*@__PURE__*/getDefaultExportFromCjs$1(vectortile); + +var VectorTile = vectorTile.VectorTile = vectortile; +var VectorTileFeature = vectorTile.VectorTileFeature = vectortilefeature; +var VectorTileLayer = vectorTile.VectorTileLayer = vectortilelayer; + +const vectorTileFeatureTypes$2 = vectorTile.VectorTileFeature.types; +const EARCUT_MAX_RINGS = 500; +const FACTOR = Math.pow(2, 13); +function addVertex$1(vertexArray, x, y, nx, ny, nz, t, e) { + vertexArray.emplaceBack( + // a_pos + x, y, + // a_normal_ed: 3-component normal and 1-component edgedistance + Math.floor(nx * FACTOR) * 2 + t, ny * FACTOR * 2, nz * FACTOR * 2, + // edgedistance (used for wrapping patterns around extrusion sides) + Math.round(e)); +} +class FillExtrusionBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.layoutVertexArray = new FillExtrusionLayoutArray(); + this.centroidVertexArray = new PosArray(); + this.indexArray = new TriangleIndexArray(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.segments = new SegmentVector(); + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + this.features = []; + this.hasPattern = hasPattern('fill-extrusion', this.layers, options); + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const bucketFeature = { + id, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + properties: feature.properties, + type: feature.type, + patterns: {} + }; + if (this.hasPattern) { + this.features.push(addPatternDependencies('fill-extrusion', this.layers, bucketFeature, this.zoom, options)); + } + else { + this.addFeature(bucketFeature, bucketFeature.geometry, index, canonical, {}); + } + options.featureIndex.insert(feature, bucketFeature.geometry, index, sourceLayerIndex, this.index, true); + } + } + addFeatures(options, canonical, imagePositions) { + for (const feature of this.features) { + const { geometry } = feature; + this.addFeature(feature, geometry, feature.index, canonical, imagePositions); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + isEmpty() { + return this.layoutVertexArray.length === 0 && this.centroidVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$2); + this.centroidVertexBuffer = context.createVertexBuffer(this.centroidVertexArray, centroidAttributes.members, true); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + this.centroidVertexBuffer.destroy(); + } + addFeature(feature, geometry, index, canonical, imagePositions) { + for (const polygon of classifyRings$1(geometry, EARCUT_MAX_RINGS)) { + const centroid = { x: 0, y: 0, vertexCount: 0 }; + let numVertices = 0; + for (const ring of polygon) { + numVertices += ring.length; + } + let segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray); + for (const ring of polygon) { + if (ring.length === 0) { + continue; + } + if (isEntirelyOutside(ring)) { + continue; + } + let edgeDistance = 0; + for (let p = 0; p < ring.length; p++) { + const p1 = ring[p]; + if (p >= 1) { + const p2 = ring[p - 1]; + if (!isBoundaryEdge(p1, p2)) { + if (segment.vertexLength + 4 > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) { + segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray); + } + const perp = p1.sub(p2)._perp()._unit(); + const dist = p2.dist(p1); + if (edgeDistance + dist > 32768) + edgeDistance = 0; + addVertex$1(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 0, edgeDistance); + addVertex$1(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 1, edgeDistance); + centroid.x += 2 * p1.x; + centroid.y += 2 * p1.y; + centroid.vertexCount += 2; + edgeDistance += dist; + addVertex$1(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 0, edgeDistance); + addVertex$1(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 1, edgeDistance); + centroid.x += 2 * p2.x; + centroid.y += 2 * p2.y; + centroid.vertexCount += 2; + const bottomRight = segment.vertexLength; + // ┌──────┐ + // │ 0 1 │ Counter-clockwise winding order. + // │ │ Triangle 1: 0 => 2 => 1 + // │ 2 3 │ Triangle 2: 1 => 2 => 3 + // └──────┘ + this.indexArray.emplaceBack(bottomRight, bottomRight + 2, bottomRight + 1); + this.indexArray.emplaceBack(bottomRight + 1, bottomRight + 2, bottomRight + 3); + segment.vertexLength += 4; + segment.primitiveLength += 2; + } + } + } + } + if (segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) { + segment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray); + } + //Only triangulate and draw the area of the feature if it is a polygon + //Other feature types (e.g. LineString) do not have area, so triangulation is pointless / undefined + if (vectorTileFeatureTypes$2[feature.type] !== 'Polygon') + continue; + const flattened = []; + const holeIndices = []; + const triangleIndex = segment.vertexLength; + for (const ring of polygon) { + if (ring.length === 0) { + continue; + } + if (ring !== polygon[0]) { + holeIndices.push(flattened.length / 2); + } + for (let i = 0; i < ring.length; i++) { + const p = ring[i]; + addVertex$1(this.layoutVertexArray, p.x, p.y, 0, 0, 1, 1, 0); + centroid.x += p.x; + centroid.y += p.y; + centroid.vertexCount += 1; + flattened.push(p.x); + flattened.push(p.y); + } + } + const indices = earcut(flattened, holeIndices); + for (let j = 0; j < indices.length; j += 3) { + // Counter-clockwise winding order. + this.indexArray.emplaceBack(triangleIndex + indices[j], triangleIndex + indices[j + 2], triangleIndex + indices[j + 1]); + } + segment.primitiveLength += indices.length / 3; + segment.vertexLength += numVertices; + // remember polygon centroid to calculate elevation in GPU + for (let i = 0; i < centroid.vertexCount; i++) { + const averageX = Math.floor(centroid.x / centroid.vertexCount); + const averageY = Math.floor(centroid.y / centroid.vertexCount); + this.centroidVertexArray.emplaceBack(averageX, averageY); + } + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical); + } +} +register('FillExtrusionBucket', FillExtrusionBucket, { omit: ['layers', 'features'] }); +function isBoundaryEdge(p1, p2) { + return (p1.x === p2.x && (p1.x < 0 || p1.x > EXTENT)) || + (p1.y === p2.y && (p1.y < 0 || p1.y > EXTENT)); +} +function isEntirelyOutside(ring) { + return ring.every(p => p.x < 0) || + ring.every(p => p.x > EXTENT) || + ring.every(p => p.y < 0) || + ring.every(p => p.y > EXTENT); +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$4; +const getPaint$4 = () => paint$4 = paint$4 || new Properties({ + "fill-extrusion-opacity": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-opacity"]), + "fill-extrusion-color": new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-color"]), + "fill-extrusion-translate": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-translate"]), + "fill-extrusion-translate-anchor": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]), + "fill-extrusion-pattern": new CrossFadedDataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-pattern"]), + "fill-extrusion-height": new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-height"]), + "fill-extrusion-base": new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-base"]), + "fill-extrusion-vertical-gradient": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"]), +}); +var properties$4 = ({ get paint() { return getPaint$4(); } }); + +class Point3D extends Point$2 { +} +class FillExtrusionStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$4); + } + createBucket(parameters) { + return new FillExtrusionBucket(parameters); + } + queryRadius() { + return translateDistance(this.paint.get('fill-extrusion-translate')); + } + is3D() { + return true; + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits, pixelPosMatrix) { + const translatedPolygon = translate$4(queryGeometry, this.paint.get('fill-extrusion-translate'), this.paint.get('fill-extrusion-translate-anchor'), transform.angle, pixelsToTileUnits); + const height = this.paint.get('fill-extrusion-height').evaluate(feature, featureState); + const base = this.paint.get('fill-extrusion-base').evaluate(feature, featureState); + const projectedQueryGeometry = projectQueryGeometry(translatedPolygon, pixelPosMatrix, transform, 0); + const projected = projectExtrusion(geometry, base, height, pixelPosMatrix); + const projectedBase = projected[0]; + const projectedTop = projected[1]; + return checkIntersection(projectedBase, projectedTop, projectedQueryGeometry); + } +} +function dot(a, b) { + return a.x * b.x + a.y * b.y; +} +function getIntersectionDistance(projectedQueryGeometry, projectedFace) { + if (projectedQueryGeometry.length === 1) { + // For point queries calculate the z at which the point intersects the face + // using barycentric coordinates. + // Find the barycentric coordinates of the projected point within the first + // triangle of the face, using only the xy plane. It doesn't matter if the + // point is outside the first triangle because all the triangles in the face + // are in the same plane. + // + // Check whether points are coincident and use other points if they are. + let i = 0; + const a = projectedFace[i++]; + let b; + while (!b || a.equals(b)) { + b = projectedFace[i++]; + if (!b) + return Infinity; + } + // Loop until point `c` is not colinear with points `a` and `b`. + for (; i < projectedFace.length; i++) { + const c = projectedFace[i]; + const p = projectedQueryGeometry[0]; + const ab = b.sub(a); + const ac = c.sub(a); + const ap = p.sub(a); + const dotABAB = dot(ab, ab); + const dotABAC = dot(ab, ac); + const dotACAC = dot(ac, ac); + const dotAPAB = dot(ap, ab); + const dotAPAC = dot(ap, ac); + const denom = dotABAB * dotACAC - dotABAC * dotABAC; + const v = (dotACAC * dotAPAB - dotABAC * dotAPAC) / denom; + const w = (dotABAB * dotAPAC - dotABAC * dotAPAB) / denom; + const u = 1 - v - w; + // Use the barycentric weighting along with the original triangle z coordinates to get the point of intersection. + const distance = a.z * u + b.z * v + c.z * w; + if (isFinite(distance)) + return distance; + } + return Infinity; + } + else { + // The counts as closest is less clear when the query is a box. This + // returns the distance to the nearest point on the face, whether it is + // within the query or not. It could be more correct to return the + // distance to the closest point within the query box but this would be + // more complicated and expensive to calculate with little benefit. + let closestDistance = Infinity; + for (const p of projectedFace) { + closestDistance = Math.min(closestDistance, p.z); + } + return closestDistance; + } +} +function checkIntersection(projectedBase, projectedTop, projectedQueryGeometry) { + let closestDistance = Infinity; + if (polygonIntersectsMultiPolygon(projectedQueryGeometry, projectedTop)) { + closestDistance = getIntersectionDistance(projectedQueryGeometry, projectedTop[0]); + } + for (let r = 0; r < projectedTop.length; r++) { + const ringTop = projectedTop[r]; + const ringBase = projectedBase[r]; + for (let p = 0; p < ringTop.length - 1; p++) { + const topA = ringTop[p]; + const topB = ringTop[p + 1]; + const baseA = ringBase[p]; + const baseB = ringBase[p + 1]; + const face = [topA, topB, baseB, baseA, topA]; + if (polygonIntersectsPolygon(projectedQueryGeometry, face)) { + closestDistance = Math.min(closestDistance, getIntersectionDistance(projectedQueryGeometry, face)); + } + } + } + return closestDistance === Infinity ? false : closestDistance; +} +/* + * Project the geometry using matrix `m`. This is essentially doing + * `vec4.transformMat4([], [p.x, p.y, z, 1], m)` but the multiplication + * is inlined so that parts of the projection that are the same across + * different points can only be done once. This produced a measurable + * performance improvement. + */ +function projectExtrusion(geometry, zBase, zTop, m) { + const projectedBase = []; + const projectedTop = []; + const baseXZ = m[8] * zBase; + const baseYZ = m[9] * zBase; + const baseZZ = m[10] * zBase; + const baseWZ = m[11] * zBase; + const topXZ = m[8] * zTop; + const topYZ = m[9] * zTop; + const topZZ = m[10] * zTop; + const topWZ = m[11] * zTop; + for (const r of geometry) { + const ringBase = []; + const ringTop = []; + for (const p of r) { + const x = p.x; + const y = p.y; + const sX = m[0] * x + m[4] * y + m[12]; + const sY = m[1] * x + m[5] * y + m[13]; + const sZ = m[2] * x + m[6] * y + m[14]; + const sW = m[3] * x + m[7] * y + m[15]; + const baseX = sX + baseXZ; + const baseY = sY + baseYZ; + const baseZ = sZ + baseZZ; + const baseW = sW + baseWZ; + const topX = sX + topXZ; + const topY = sY + topYZ; + const topZ = sZ + topZZ; + const topW = sW + topWZ; + const b = new Point$2(baseX / baseW, baseY / baseW); + b.z = baseZ / baseW; + ringBase.push(b); + const t = new Point$2(topX / topW, topY / topW); + t.z = topZ / topW; + ringTop.push(t); + } + projectedBase.push(ringBase); + projectedTop.push(ringTop); + } + return [projectedBase, projectedTop]; +} +function projectQueryGeometry(queryGeometry, pixelPosMatrix, transform, z) { + const projectedQueryGeometry = []; + for (const p of queryGeometry) { + const v = [p.x, p.y, z, 1]; + transformMat4$1(v, v, pixelPosMatrix); + projectedQueryGeometry.push(new Point$2(v[0] / v[3], v[1] / v[3])); + } + return projectedQueryGeometry; +} + +const lineLayoutAttributes = createLayout([ + { name: 'a_pos_normal', components: 2, type: 'Int16' }, + { name: 'a_data', components: 4, type: 'Uint8' } +], 4); +const { members: members$1, size: size$1, alignment: alignment$1 } = lineLayoutAttributes; + +const lineLayoutAttributesExt = createLayout([ + { name: 'a_uv_x', components: 1, type: 'Float32' }, + { name: 'a_split_index', components: 1, type: 'Float32' }, +]); +const { members, size, alignment } = lineLayoutAttributesExt; + +const vectorTileFeatureTypes$1 = vectorTile.VectorTileFeature.types; +// NOTE ON EXTRUDE SCALE: +// scale the extrusion vector so that the normal length is this value. +// contains the "texture" normals (-1..1). this is distinct from the extrude +// normals for line joins, because the x-value remains 0 for the texture +// normal array, while the extrude normal actually moves the vertex to create +// the acute/bevelled line join. +const EXTRUDE_SCALE = 63; +/* + * Sharp corners cause dashed lines to tilt because the distance along the line + * is the same at both the inner and outer corners. To improve the appearance of + * dashed lines we add extra points near sharp corners so that a smaller part + * of the line is tilted. + * + * COS_HALF_SHARP_CORNER controls how sharp a corner has to be for us to add an + * extra vertex. The default is 75 degrees. + * + * The newly created vertices are placed SHARP_CORNER_OFFSET pixels from the corner. + */ +const COS_HALF_SHARP_CORNER = Math.cos(75 / 2 * (Math.PI / 180)); +const SHARP_CORNER_OFFSET = 15; +// Angle per triangle for approximating round line joins. +const DEG_PER_TRIANGLE = 20; +// The number of bits that is used to store the line distance in the buffer. +const LINE_DISTANCE_BUFFER_BITS = 15; +// We don't have enough bits for the line distance as we'd like to have, so +// use this value to scale the line distance (in tile units) down to a smaller +// value. This lets us store longer distances while sacrificing precision. +const LINE_DISTANCE_SCALE = 1 / 2; +// The maximum line distance, in tile units, that fits in the buffer. +const MAX_LINE_DISTANCE = Math.pow(2, LINE_DISTANCE_BUFFER_BITS - 1) / LINE_DISTANCE_SCALE; +/** + * @internal + * Line bucket class + */ +class LineBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.patternFeatures = []; + this.lineClipsArray = []; + this.gradients = {}; + this.layers.forEach(layer => { + this.gradients[layer.id] = {}; + }); + this.layoutVertexArray = new LineLayoutArray(); + this.layoutVertexArray2 = new LineExtLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.segments = new SegmentVector(); + this.maxLineLength = 0; + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + this.hasPattern = hasPattern('line', this.layers, options); + const lineSortKey = this.layers[0].layout.get('line-sort-key'); + const sortFeaturesByKey = !lineSortKey.isConstant(); + const bucketFeatures = []; + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const sortKey = sortFeaturesByKey ? + lineSortKey.evaluate(evaluationFeature, {}, canonical) : + undefined; + const bucketFeature = { + id, + properties: feature.properties, + type: feature.type, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + patterns: {}, + sortKey + }; + bucketFeatures.push(bucketFeature); + } + if (sortFeaturesByKey) { + bucketFeatures.sort((a, b) => { + return (a.sortKey) - (b.sortKey); + }); + } + for (const bucketFeature of bucketFeatures) { + const { geometry, index, sourceLayerIndex } = bucketFeature; + if (this.hasPattern) { + const patternBucketFeature = addPatternDependencies('line', this.layers, bucketFeature, this.zoom, options); + // pattern features are added only once the pattern is loaded into the image atlas + // so are stored during populate until later updated with positions by tile worker in addFeatures + this.patternFeatures.push(patternBucketFeature); + } + else { + this.addFeature(bucketFeature, geometry, index, canonical, {}); + } + const feature = features[index].feature; + options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + addFeatures(options, canonical, imagePositions) { + for (const feature of this.patternFeatures) { + this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions); + } + } + isEmpty() { + return this.layoutVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + if (this.layoutVertexArray2.length !== 0) { + this.layoutVertexBuffer2 = context.createVertexBuffer(this.layoutVertexArray2, members); + } + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$1); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + } + lineFeatureClips(feature) { + if (!!feature.properties && Object.prototype.hasOwnProperty.call(feature.properties, 'mapbox_clip_start') && Object.prototype.hasOwnProperty.call(feature.properties, 'mapbox_clip_end')) { + const start = +feature.properties['mapbox_clip_start']; + const end = +feature.properties['mapbox_clip_end']; + return { start, end }; + } + } + addFeature(feature, geometry, index, canonical, imagePositions) { + const layout = this.layers[0].layout; + const join = layout.get('line-join').evaluate(feature, {}); + const cap = layout.get('line-cap'); + const miterLimit = layout.get('line-miter-limit'); + const roundLimit = layout.get('line-round-limit'); + this.lineClips = this.lineFeatureClips(feature); + for (const line of geometry) { + this.addLine(line, feature, join, cap, miterLimit, roundLimit); + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical); + } + addLine(vertices, feature, join, cap, miterLimit, roundLimit) { + this.distance = 0; + this.scaledDistance = 0; + this.totalDistance = 0; + if (this.lineClips) { + this.lineClipsArray.push(this.lineClips); + // Calculate the total distance, in tile units, of this tiled line feature + for (let i = 0; i < vertices.length - 1; i++) { + this.totalDistance += vertices[i].dist(vertices[i + 1]); + } + this.updateScaledDistance(); + this.maxLineLength = Math.max(this.maxLineLength, this.totalDistance); + } + const isPolygon = vectorTileFeatureTypes$1[feature.type] === 'Polygon'; + // If the line has duplicate vertices at the ends, adjust start/length to remove them. + let len = vertices.length; + while (len >= 2 && vertices[len - 1].equals(vertices[len - 2])) { + len--; + } + let first = 0; + while (first < len - 1 && vertices[first].equals(vertices[first + 1])) { + first++; + } + // Ignore invalid geometry. + if (len < (isPolygon ? 3 : 2)) + return; + if (join === 'bevel') + miterLimit = 1.05; + const sharpCornerOffset = this.overscaling <= 16 ? + SHARP_CORNER_OFFSET * EXTENT / (512 * this.overscaling) : + 0; + // we could be more precise, but it would only save a negligible amount of space + const segment = this.segments.prepareSegment(len * 10, this.layoutVertexArray, this.indexArray); + let currentVertex; + let prevVertex; + let nextVertex; + let prevNormal; + let nextNormal; + // the last two vertices added + this.e1 = this.e2 = -1; + if (isPolygon) { + currentVertex = vertices[len - 2]; + nextNormal = vertices[first].sub(currentVertex)._unit()._perp(); + } + for (let i = first; i < len; i++) { + nextVertex = i === len - 1 ? + (isPolygon ? vertices[first + 1] : undefined) : // if it's a polygon, treat the last vertex like the first + vertices[i + 1]; // just the next vertex + // if two consecutive vertices exist, skip the current one + if (nextVertex && vertices[i].equals(nextVertex)) + continue; + if (nextNormal) + prevNormal = nextNormal; + if (currentVertex) + prevVertex = currentVertex; + currentVertex = vertices[i]; + // Calculate the normal towards the next vertex in this line. In case + // there is no next vertex, pretend that the line is continuing straight, + // meaning that we are just using the previous normal. + nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal; + // If we still don't have a previous normal, this is the beginning of a + // non-closed line, so we're doing a straight "join". + prevNormal = prevNormal || nextNormal; + // Determine the normal of the join extrusion. It is the angle bisector + // of the segments between the previous line and the next line. + // In the case of 180° angles, the prev and next normals cancel each other out: + // prevNormal + nextNormal = (0, 0), its magnitude is 0, so the unit vector would be + // undefined. In that case, we're keeping the joinNormal at (0, 0), so that the cosHalfAngle + // below will also become 0 and miterLength will become Infinity. + let joinNormal = prevNormal.add(nextNormal); + if (joinNormal.x !== 0 || joinNormal.y !== 0) { + joinNormal._unit(); + } + /* joinNormal prevNormal + * ↖ ↑ + * .________. prevVertex + * | + * nextNormal ← | currentVertex + * | + * nextVertex ! + * + */ + // calculate cosines of the angle (and its half) using dot product + const cosAngle = prevNormal.x * nextNormal.x + prevNormal.y * nextNormal.y; + const cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y; + // Calculate the length of the miter (the ratio of the miter to the width) + // as the inverse of cosine of the angle between next and join normals + const miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity; + // approximate angle from cosine + const approxAngle = 2 * Math.sqrt(2 - 2 * cosHalfAngle); + const isSharpCorner = cosHalfAngle < COS_HALF_SHARP_CORNER && prevVertex && nextVertex; + const lineTurnsLeft = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0; + if (isSharpCorner && i > first) { + const prevSegmentLength = currentVertex.dist(prevVertex); + if (prevSegmentLength > 2 * sharpCornerOffset) { + const newPrevVertex = currentVertex.sub(currentVertex.sub(prevVertex)._mult(sharpCornerOffset / prevSegmentLength)._round()); + this.updateDistance(prevVertex, newPrevVertex); + this.addCurrentVertex(newPrevVertex, prevNormal, 0, 0, segment); + prevVertex = newPrevVertex; + } + } + // The join if a middle vertex, otherwise the cap. + const middleVertex = prevVertex && nextVertex; + let currentJoin = middleVertex ? join : isPolygon ? 'butt' : cap; + if (middleVertex && currentJoin === 'round') { + if (miterLength < roundLimit) { + currentJoin = 'miter'; + } + else if (miterLength <= 2) { + currentJoin = 'fakeround'; + } + } + if (currentJoin === 'miter' && miterLength > miterLimit) { + currentJoin = 'bevel'; + } + if (currentJoin === 'bevel') { + // The maximum extrude length is 128 / 63 = 2 times the width of the line + // so if miterLength >= 2 we need to draw a different type of bevel here. + if (miterLength > 2) + currentJoin = 'flipbevel'; + // If the miterLength is really small and the line bevel wouldn't be visible, + // just draw a miter join to save a triangle. + if (miterLength < miterLimit) + currentJoin = 'miter'; + } + // Calculate how far along the line the currentVertex is + if (prevVertex) + this.updateDistance(prevVertex, currentVertex); + if (currentJoin === 'miter') { + joinNormal._mult(miterLength); + this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); + } + else if (currentJoin === 'flipbevel') { + // miter is too big, flip the direction to make a beveled join + if (miterLength > 100) { + // Almost parallel lines + joinNormal = nextNormal.mult(-1); + } + else { + const bevelLength = miterLength * prevNormal.add(nextNormal).mag() / prevNormal.sub(nextNormal).mag(); + joinNormal._perp()._mult(bevelLength * (lineTurnsLeft ? -1 : 1)); + } + this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); + this.addCurrentVertex(currentVertex, joinNormal.mult(-1), 0, 0, segment); + } + else if (currentJoin === 'bevel' || currentJoin === 'fakeround') { + const offset = -Math.sqrt(miterLength * miterLength - 1); + const offsetA = lineTurnsLeft ? offset : 0; + const offsetB = lineTurnsLeft ? 0 : offset; + // Close previous segment with a bevel + if (prevVertex) { + this.addCurrentVertex(currentVertex, prevNormal, offsetA, offsetB, segment); + } + if (currentJoin === 'fakeround') { + // The join angle is sharp enough that a round join would be visible. + // Bevel joins fill the gap between segments with a single pie slice triangle. + // Create a round join by adding multiple pie slices. The join isn't actually round, but + // it looks like it is at the sizes we render lines at. + // pick the number of triangles for approximating round join by based on the angle between normals + const n = Math.round((approxAngle * 180 / Math.PI) / DEG_PER_TRIANGLE); + for (let m = 1; m < n; m++) { + let t = m / n; + if (t !== 0.5) { + // approximate spherical interpolation https://observablehq.com/@mourner/approximating-geometric-slerp + const t2 = t - 0.5; + const A = 1.0904 + cosAngle * (-3.2452 + cosAngle * (3.55645 - cosAngle * 1.43519)); + const B = 0.848013 + cosAngle * (-1.06021 + cosAngle * 0.215638); + t = t + t * t2 * (t - 1) * (A * t2 * t2 + B); + } + const extrude = nextNormal.sub(prevNormal)._mult(t)._add(prevNormal)._unit()._mult(lineTurnsLeft ? -1 : 1); + this.addHalfVertex(currentVertex, extrude.x, extrude.y, false, lineTurnsLeft, 0, segment); + } + } + if (nextVertex) { + // Start next segment + this.addCurrentVertex(currentVertex, nextNormal, -offsetA, -offsetB, segment); + } + } + else if (currentJoin === 'butt') { + this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); // butt cap + } + else if (currentJoin === 'square') { + const offset = prevVertex ? 1 : -1; // closing or starting square cap + this.addCurrentVertex(currentVertex, joinNormal, offset, offset, segment); + } + else if (currentJoin === 'round') { + if (prevVertex) { + // Close previous segment with butt + this.addCurrentVertex(currentVertex, prevNormal, 0, 0, segment); + // Add round cap or linejoin at end of segment + this.addCurrentVertex(currentVertex, prevNormal, 1, 1, segment, true); + } + if (nextVertex) { + // Add round cap before first segment + this.addCurrentVertex(currentVertex, nextNormal, -1, -1, segment, true); + // Start next segment with a butt + this.addCurrentVertex(currentVertex, nextNormal, 0, 0, segment); + } + } + if (isSharpCorner && i < len - 1) { + const nextSegmentLength = currentVertex.dist(nextVertex); + if (nextSegmentLength > 2 * sharpCornerOffset) { + const newCurrentVertex = currentVertex.add(nextVertex.sub(currentVertex)._mult(sharpCornerOffset / nextSegmentLength)._round()); + this.updateDistance(currentVertex, newCurrentVertex); + this.addCurrentVertex(newCurrentVertex, nextNormal, 0, 0, segment); + currentVertex = newCurrentVertex; + } + } + } + } + /** + * Add two vertices to the buffers. + * + * @param p - the line vertex to add buffer vertices for + * @param normal - vertex normal + * @param endLeft - extrude to shift the left vertex along the line + * @param endRight - extrude to shift the left vertex along the line + * @param segment - the segment object to add the vertex to + * @param round - whether this is a round cap + */ + addCurrentVertex(p, normal, endLeft, endRight, segment, round = false) { + // left and right extrude vectors, perpendicularly shifted by endLeft/endRight + const leftX = normal.x + normal.y * endLeft; + const leftY = normal.y - normal.x * endLeft; + const rightX = -normal.x + normal.y * endRight; + const rightY = -normal.y - normal.x * endRight; + this.addHalfVertex(p, leftX, leftY, round, false, endLeft, segment); + this.addHalfVertex(p, rightX, rightY, round, true, -endRight, segment); + // There is a maximum "distance along the line" that we can store in the buffers. + // When we get close to the distance, reset it to zero and add the vertex again with + // a distance of zero. The max distance is determined by the number of bits we allocate + // to `linesofar`. + if (this.distance > MAX_LINE_DISTANCE / 2 && this.totalDistance === 0) { + this.distance = 0; + this.updateScaledDistance(); + this.addCurrentVertex(p, normal, endLeft, endRight, segment, round); + } + } + addHalfVertex({ x, y }, extrudeX, extrudeY, round, up, dir, segment) { + const totalDistance = this.lineClips ? this.scaledDistance * (MAX_LINE_DISTANCE - 1) : this.scaledDistance; + // scale down so that we can store longer distances while sacrificing precision. + const linesofarScaled = totalDistance * LINE_DISTANCE_SCALE; + this.layoutVertexArray.emplaceBack( + // a_pos_normal + // Encode round/up the least significant bits + (x << 1) + (round ? 1 : 0), (y << 1) + (up ? 1 : 0), + // a_data + // add 128 to store a byte in an unsigned byte + Math.round(EXTRUDE_SCALE * extrudeX) + 128, Math.round(EXTRUDE_SCALE * extrudeY) + 128, + // Encode the -1/0/1 direction value into the first two bits of .z of a_data. + // Combine it with the lower 6 bits of `linesofarScaled` (shifted by 2 bits to make + // room for the direction value). The upper 8 bits of `linesofarScaled` are placed in + // the `w` component. + ((dir === 0 ? 0 : (dir < 0 ? -1 : 1)) + 1) | ((linesofarScaled & 0x3F) << 2), linesofarScaled >> 6); + // Constructs a second vertex buffer with higher precision line progress + if (this.lineClips) { + const progressRealigned = this.scaledDistance - this.lineClips.start; + const endClipRealigned = this.lineClips.end - this.lineClips.start; + const uvX = progressRealigned / endClipRealigned; + this.layoutVertexArray2.emplaceBack(uvX, this.lineClipsArray.length); + } + const e = segment.vertexLength++; + if (this.e1 >= 0 && this.e2 >= 0) { + this.indexArray.emplaceBack(this.e1, this.e2, e); + segment.primitiveLength++; + } + if (up) { + this.e2 = e; + } + else { + this.e1 = e; + } + } + updateScaledDistance() { + // Knowing the ratio of the full linestring covered by this tiled feature, as well + // as the total distance (in tile units) of this tiled feature, and the distance + // (in tile units) of the current vertex, we can determine the relative distance + // of this vertex along the full linestring feature and scale it to [0, 2^15) + this.scaledDistance = this.lineClips ? + this.lineClips.start + (this.lineClips.end - this.lineClips.start) * this.distance / this.totalDistance : + this.distance; + } + updateDistance(prev, next) { + this.distance += prev.dist(next); + this.updateScaledDistance(); + } +} +register('LineBucket', LineBucket, { omit: ['layers', 'patternFeatures'] }); + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout$1; +const getLayout$1 = () => layout$1 = layout$1 || new Properties({ + "line-cap": new DataConstantProperty(v8Spec["layout_line"]["line-cap"]), + "line-join": new DataDrivenProperty(v8Spec["layout_line"]["line-join"]), + "line-miter-limit": new DataConstantProperty(v8Spec["layout_line"]["line-miter-limit"]), + "line-round-limit": new DataConstantProperty(v8Spec["layout_line"]["line-round-limit"]), + "line-sort-key": new DataDrivenProperty(v8Spec["layout_line"]["line-sort-key"]), +}); +let paint$3; +const getPaint$3 = () => paint$3 = paint$3 || new Properties({ + "line-opacity": new DataDrivenProperty(v8Spec["paint_line"]["line-opacity"]), + "line-color": new DataDrivenProperty(v8Spec["paint_line"]["line-color"]), + "line-translate": new DataConstantProperty(v8Spec["paint_line"]["line-translate"]), + "line-translate-anchor": new DataConstantProperty(v8Spec["paint_line"]["line-translate-anchor"]), + "line-width": new DataDrivenProperty(v8Spec["paint_line"]["line-width"]), + "line-gap-width": new DataDrivenProperty(v8Spec["paint_line"]["line-gap-width"]), + "line-offset": new DataDrivenProperty(v8Spec["paint_line"]["line-offset"]), + "line-blur": new DataDrivenProperty(v8Spec["paint_line"]["line-blur"]), + "line-dasharray": new CrossFadedProperty(v8Spec["paint_line"]["line-dasharray"]), + "line-pattern": new CrossFadedDataDrivenProperty(v8Spec["paint_line"]["line-pattern"]), + "line-gradient": new ColorRampProperty(v8Spec["paint_line"]["line-gradient"]), +}); +var properties$3 = ({ get paint() { return getPaint$3(); }, get layout() { return getLayout$1(); } }); + +class LineFloorwidthProperty extends DataDrivenProperty { + possiblyEvaluate(value, parameters) { + parameters = new EvaluationParameters(Math.floor(parameters.zoom), { + now: parameters.now, + fadeDuration: parameters.fadeDuration, + zoomHistory: parameters.zoomHistory, + transition: parameters.transition + }); + return super.possiblyEvaluate(value, parameters); + } + evaluate(value, globals, feature, featureState) { + globals = extend({}, globals, { zoom: Math.floor(globals.zoom) }); + return super.evaluate(value, globals, feature, featureState); + } +} +let lineFloorwidthProperty; +class LineStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$3); + this.gradientVersion = 0; + if (!lineFloorwidthProperty) { + lineFloorwidthProperty = + new LineFloorwidthProperty(properties$3.paint.properties['line-width'].specification); + lineFloorwidthProperty.useIntegerZoom = true; + } + } + _handleSpecialPaintPropertyUpdate(name) { + if (name === 'line-gradient') { + const expression = this.gradientExpression(); + if (isZoomExpression(expression)) { + this.stepInterpolant = expression._styleExpression.expression instanceof Step; + } + else { + this.stepInterpolant = false; + } + this.gradientVersion = (this.gradientVersion + 1) % Number.MAX_SAFE_INTEGER; + } + } + gradientExpression() { + return this._transitionablePaint._values['line-gradient'].value.expression; + } + recalculate(parameters, availableImages) { + super.recalculate(parameters, availableImages); + this.paint._values['line-floorwidth'] = + lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values['line-width'].value, parameters); + } + createBucket(parameters) { + return new LineBucket(parameters); + } + queryRadius(bucket) { + const lineBucket = bucket; + const width = getLineWidth(getMaximumPaintValue('line-width', this, lineBucket), getMaximumPaintValue('line-gap-width', this, lineBucket)); + const offset = getMaximumPaintValue('line-offset', this, lineBucket); + return width / 2 + Math.abs(offset) + translateDistance(this.paint.get('line-translate')); + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits) { + const translatedPolygon = translate$4(queryGeometry, this.paint.get('line-translate'), this.paint.get('line-translate-anchor'), transform.angle, pixelsToTileUnits); + const halfWidth = pixelsToTileUnits / 2 * getLineWidth(this.paint.get('line-width').evaluate(feature, featureState), this.paint.get('line-gap-width').evaluate(feature, featureState)); + const lineOffset = this.paint.get('line-offset').evaluate(feature, featureState); + if (lineOffset) { + geometry = offsetLine(geometry, lineOffset * pixelsToTileUnits); + } + return polygonIntersectsBufferedMultiLine(translatedPolygon, geometry, halfWidth); + } + isTileClipped() { + return true; + } +} +function getLineWidth(lineWidth, lineGapWidth) { + if (lineGapWidth > 0) { + return lineGapWidth + 2 * lineWidth; + } + else { + return lineWidth; + } +} + +const symbolLayoutAttributes = createLayout([ + { name: 'a_pos_offset', components: 4, type: 'Int16' }, + { name: 'a_data', components: 4, type: 'Uint16' }, + { name: 'a_pixeloffset', components: 4, type: 'Int16' } +], 4); +const dynamicLayoutAttributes = createLayout([ + { name: 'a_projected_pos', components: 3, type: 'Float32' } +], 4); +const placementOpacityAttributes = createLayout([ + { name: 'a_fade_opacity', components: 1, type: 'Uint32' } +], 4); +const collisionVertexAttributes = createLayout([ + { name: 'a_placed', components: 2, type: 'Uint8' }, + { name: 'a_shift', components: 2, type: 'Float32' }, + { name: 'a_box_real', components: 2, type: 'Int16' }, +]); +const collisionBox = createLayout([ + // the box is centered around the anchor point + { type: 'Int16', name: 'anchorPointX' }, + { type: 'Int16', name: 'anchorPointY' }, + // distances to the edges from the anchor + { type: 'Int16', name: 'x1' }, + { type: 'Int16', name: 'y1' }, + { type: 'Int16', name: 'x2' }, + { type: 'Int16', name: 'y2' }, + // the index of the feature in the original vectortile + { type: 'Uint32', name: 'featureIndex' }, + // the source layer the feature appears in + { type: 'Uint16', name: 'sourceLayerIndex' }, + // the bucket the feature appears in + { type: 'Uint16', name: 'bucketIndex' }, +]); +const collisionBoxLayout = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' }, + { name: 'a_anchor_pos', components: 2, type: 'Int16' }, + { name: 'a_extrude', components: 2, type: 'Int16' } +], 4); +const collisionCircleLayout = createLayout([ + { name: 'a_pos', components: 2, type: 'Float32' }, + { name: 'a_radius', components: 1, type: 'Float32' }, + { name: 'a_flags', components: 2, type: 'Int16' } +], 4); +const quadTriangle = createLayout([ + { name: 'triangle', components: 3, type: 'Uint16' }, +]); +const placement = createLayout([ + { type: 'Int16', name: 'anchorX' }, + { type: 'Int16', name: 'anchorY' }, + { type: 'Uint16', name: 'glyphStartIndex' }, + { type: 'Uint16', name: 'numGlyphs' }, + { type: 'Uint32', name: 'vertexStartIndex' }, + { type: 'Uint32', name: 'lineStartIndex' }, + { type: 'Uint32', name: 'lineLength' }, + { type: 'Uint16', name: 'segment' }, + { type: 'Uint16', name: 'lowerSize' }, + { type: 'Uint16', name: 'upperSize' }, + { type: 'Float32', name: 'lineOffsetX' }, + { type: 'Float32', name: 'lineOffsetY' }, + { type: 'Uint8', name: 'writingMode' }, + { type: 'Uint8', name: 'placedOrientation' }, + { type: 'Uint8', name: 'hidden' }, + { type: 'Uint32', name: 'crossTileID' }, + { type: 'Int16', name: 'associatedIconIndex' } +]); +const symbolInstance = createLayout([ + { type: 'Int16', name: 'anchorX' }, + { type: 'Int16', name: 'anchorY' }, + { type: 'Int16', name: 'rightJustifiedTextSymbolIndex' }, + { type: 'Int16', name: 'centerJustifiedTextSymbolIndex' }, + { type: 'Int16', name: 'leftJustifiedTextSymbolIndex' }, + { type: 'Int16', name: 'verticalPlacedTextSymbolIndex' }, + { type: 'Int16', name: 'placedIconSymbolIndex' }, + { type: 'Int16', name: 'verticalPlacedIconSymbolIndex' }, + { type: 'Uint16', name: 'key' }, + { type: 'Uint16', name: 'textBoxStartIndex' }, + { type: 'Uint16', name: 'textBoxEndIndex' }, + { type: 'Uint16', name: 'verticalTextBoxStartIndex' }, + { type: 'Uint16', name: 'verticalTextBoxEndIndex' }, + { type: 'Uint16', name: 'iconBoxStartIndex' }, + { type: 'Uint16', name: 'iconBoxEndIndex' }, + { type: 'Uint16', name: 'verticalIconBoxStartIndex' }, + { type: 'Uint16', name: 'verticalIconBoxEndIndex' }, + { type: 'Uint16', name: 'featureIndex' }, + { type: 'Uint16', name: 'numHorizontalGlyphVertices' }, + { type: 'Uint16', name: 'numVerticalGlyphVertices' }, + { type: 'Uint16', name: 'numIconVertices' }, + { type: 'Uint16', name: 'numVerticalIconVertices' }, + { type: 'Uint16', name: 'useRuntimeCollisionCircles' }, + { type: 'Uint32', name: 'crossTileID' }, + { type: 'Float32', name: 'textBoxScale' }, + { type: 'Float32', name: 'collisionCircleDiameter' }, + { type: 'Uint16', name: 'textAnchorOffsetStartIndex' }, + { type: 'Uint16', name: 'textAnchorOffsetEndIndex' } +]); +const glyphOffset = createLayout([ + { type: 'Float32', name: 'offsetX' } +]); +const lineVertex = createLayout([ + { type: 'Int16', name: 'x' }, + { type: 'Int16', name: 'y' }, + { type: 'Int16', name: 'tileUnitDistanceFromAnchor' } +]); +const textAnchorOffset = createLayout([ + { type: 'Uint16', name: 'textAnchor' }, + { type: 'Float32', components: 2, name: 'textOffset' } +]); + +function transformTextInternal(text, layer, feature) { + const transform = layer.layout.get('text-transform').evaluate(feature, {}); + if (transform === 'uppercase') { + text = text.toLocaleUpperCase(); + } + else if (transform === 'lowercase') { + text = text.toLocaleLowerCase(); + } + if (rtlWorkerPlugin.applyArabicShaping) { + text = rtlWorkerPlugin.applyArabicShaping(text); + } + return text; +} +function transformText(text, layer, feature) { + text.sections.forEach(section => { + section.text = transformTextInternal(section.text, layer, feature); + }); + return text; +} + +function mergeLines(features) { + const leftIndex = {}; + const rightIndex = {}; + const mergedFeatures = []; + let mergedIndex = 0; + function add(k) { + mergedFeatures.push(features[k]); + mergedIndex++; + } + function mergeFromRight(leftKey, rightKey, geom) { + const i = rightIndex[leftKey]; + delete rightIndex[leftKey]; + rightIndex[rightKey] = i; + mergedFeatures[i].geometry[0].pop(); + mergedFeatures[i].geometry[0] = mergedFeatures[i].geometry[0].concat(geom[0]); + return i; + } + function mergeFromLeft(leftKey, rightKey, geom) { + const i = leftIndex[rightKey]; + delete leftIndex[rightKey]; + leftIndex[leftKey] = i; + mergedFeatures[i].geometry[0].shift(); + mergedFeatures[i].geometry[0] = geom[0].concat(mergedFeatures[i].geometry[0]); + return i; + } + function getKey(text, geom, onRight) { + const point = onRight ? geom[0][geom[0].length - 1] : geom[0][0]; + return `${text}:${point.x}:${point.y}`; + } + for (let k = 0; k < features.length; k++) { + const feature = features[k]; + const geom = feature.geometry; + const text = feature.text ? feature.text.toString() : null; + if (!text) { + add(k); + continue; + } + const leftKey = getKey(text, geom), rightKey = getKey(text, geom, true); + if ((leftKey in rightIndex) && (rightKey in leftIndex) && (rightIndex[leftKey] !== leftIndex[rightKey])) { + // found lines with the same text adjacent to both ends of the current line, merge all three + const j = mergeFromLeft(leftKey, rightKey, geom); + const i = mergeFromRight(leftKey, rightKey, mergedFeatures[j].geometry); + delete leftIndex[leftKey]; + delete rightIndex[rightKey]; + rightIndex[getKey(text, mergedFeatures[i].geometry, true)] = i; + mergedFeatures[j].geometry = null; + } + else if (leftKey in rightIndex) { + // found mergeable line adjacent to the start of the current line, merge + mergeFromRight(leftKey, rightKey, geom); + } + else if (rightKey in leftIndex) { + // found mergeable line adjacent to the end of the current line, merge + mergeFromLeft(leftKey, rightKey, geom); + } + else { + // no adjacent lines, add as a new item + add(k); + leftIndex[leftKey] = mergedIndex - 1; + rightIndex[rightKey] = mergedIndex - 1; + } + } + return mergedFeatures.filter((f) => f.geometry); +} + +const verticalizedCharacterMap = { + '!': '︕', + '#': '#', + '$': '$', + '%': '%', + '&': '&', + '(': '︵', + ')': '︶', + '*': '*', + '+': '+', + ',': '︐', + '-': '︲', + '.': '・', + '/': '/', + ':': '︓', + ';': '︔', + '<': '︿', + '=': '=', + '>': '﹀', + '?': '︖', + '@': '@', + '[': '﹇', + '\\': '\', + ']': '﹈', + '^': '^', + '_': '︳', + '`': '`', + '{': '︷', + '|': '―', + '}': '︸', + '~': '~', + '¢': '¢', + '£': '£', + '¥': '¥', + '¦': '¦', + '¬': '¬', + '¯': ' ̄', + '–': '︲', + '—': '︱', + '‘': '﹃', + '’': '﹄', + '“': '﹁', + '”': '﹂', + '…': '︙', + '‧': '・', + '₩': '₩', + '、': '︑', + '。': '︒', + '〈': '︿', + '〉': '﹀', + '《': '︽', + '》': '︾', + '「': '﹁', + '」': '﹂', + '『': '﹃', + '』': '﹄', + '【': '︻', + '】': '︼', + '〔': '︹', + '〕': '︺', + '〖': '︗', + '〗': '︘', + '!': '︕', + '(': '︵', + ')': '︶', + ',': '︐', + '-': '︲', + '.': '・', + ':': '︓', + ';': '︔', + '<': '︿', + '>': '﹀', + '?': '︖', + '[': '﹇', + ']': '﹈', + '_': '︳', + '{': '︷', + '|': '―', + '}': '︸', + '⦅': '︵', + '⦆': '︶', + '。': '︒', + '「': '﹁', + '」': '﹂' +}; +function verticalizePunctuation(input) { + let output = ''; + for (let i = 0; i < input.length; i++) { + const nextCharCode = input.charCodeAt(i + 1) || null; + const prevCharCode = input.charCodeAt(i - 1) || null; + const canReplacePunctuation = ((!nextCharCode || !charHasRotatedVerticalOrientation(nextCharCode) || verticalizedCharacterMap[input[i + 1]]) && + (!prevCharCode || !charHasRotatedVerticalOrientation(prevCharCode) || verticalizedCharacterMap[input[i - 1]])); + if (canReplacePunctuation && verticalizedCharacterMap[input[i]]) { + output += verticalizedCharacterMap[input[i]]; + } + else { + output += input[i]; + } + } + return output; +} + +// ONE_EM constant used to go between "em" units used in style spec and "points" used internally for layout +var ONE_EM = 24; + +var ieee754$1 = {}; + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + +var read = ieee754$1.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = (nBytes * 8) - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +}; + +var write = ieee754$1.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = (nBytes * 8) - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +}; + +'use strict'; + +var pbf = Pbf; + +var ieee754 = ieee754$1; + +function Pbf(buf) { + this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0); + this.pos = 0; + this.type = 0; + this.length = this.buf.length; +} + +Pbf.Varint = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum +Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64 +Pbf.Bytes = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields +Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32 + +var SHIFT_LEFT_32 = (1 << 16) * (1 << 16), + SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32; + +// Threshold chosen based on both benchmarking and knowledge about browser string +// data structures (which currently switch structure types at 12 bytes or more) +var TEXT_DECODER_MIN_LENGTH = 12; +var utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8'); + +Pbf.prototype = { + + destroy: function() { + this.buf = null; + }, + + // === READING ================================================================= + + readFields: function(readField, result, end) { + end = end || this.length; + + while (this.pos < end) { + var val = this.readVarint(), + tag = val >> 3, + startPos = this.pos; + + this.type = val & 0x7; + readField(tag, result, this); + + if (this.pos === startPos) this.skip(val); + } + return result; + }, + + readMessage: function(readField, result) { + return this.readFields(readField, result, this.readVarint() + this.pos); + }, + + readFixed32: function() { + var val = readUInt32(this.buf, this.pos); + this.pos += 4; + return val; + }, + + readSFixed32: function() { + var val = readInt32(this.buf, this.pos); + this.pos += 4; + return val; + }, + + // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed) + + readFixed64: function() { + var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; + this.pos += 8; + return val; + }, + + readSFixed64: function() { + var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; + this.pos += 8; + return val; + }, + + readFloat: function() { + var val = ieee754.read(this.buf, this.pos, true, 23, 4); + this.pos += 4; + return val; + }, + + readDouble: function() { + var val = ieee754.read(this.buf, this.pos, true, 52, 8); + this.pos += 8; + return val; + }, + + readVarint: function(isSigned) { + var buf = this.buf, + val, b; + + b = buf[this.pos++]; val = b & 0x7f; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val; + b = buf[this.pos]; val |= (b & 0x0f) << 28; + + return readVarintRemainder(val, isSigned, this); + }, + + readVarint64: function() { // for compatibility with v2.0.1 + return this.readVarint(true); + }, + + readSVarint: function() { + var num = this.readVarint(); + return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding + }, + + readBoolean: function() { + return Boolean(this.readVarint()); + }, + + readString: function() { + var end = this.readVarint() + this.pos; + var pos = this.pos; + this.pos = end; + + if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) { + // longer strings are fast with the built-in browser TextDecoder API + return readUtf8TextDecoder(this.buf, pos, end); + } + // short strings are fast with our custom implementation + return readUtf8(this.buf, pos, end); + }, + + readBytes: function() { + var end = this.readVarint() + this.pos, + buffer = this.buf.subarray(this.pos, end); + this.pos = end; + return buffer; + }, + + // verbose for performance reasons; doesn't affect gzipped size + + readPackedVarint: function(arr, isSigned) { + if (this.type !== Pbf.Bytes) return arr.push(this.readVarint(isSigned)); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readVarint(isSigned)); + return arr; + }, + readPackedSVarint: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSVarint()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSVarint()); + return arr; + }, + readPackedBoolean: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readBoolean()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readBoolean()); + return arr; + }, + readPackedFloat: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFloat()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFloat()); + return arr; + }, + readPackedDouble: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readDouble()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readDouble()); + return arr; + }, + readPackedFixed32: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFixed32()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFixed32()); + return arr; + }, + readPackedSFixed32: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed32()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSFixed32()); + return arr; + }, + readPackedFixed64: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFixed64()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFixed64()); + return arr; + }, + readPackedSFixed64: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed64()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSFixed64()); + return arr; + }, + + skip: function(val) { + var type = val & 0x7; + if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {} + else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos; + else if (type === Pbf.Fixed32) this.pos += 4; + else if (type === Pbf.Fixed64) this.pos += 8; + else throw new Error('Unimplemented type: ' + type); + }, + + // === WRITING ================================================================= + + writeTag: function(tag, type) { + this.writeVarint((tag << 3) | type); + }, + + realloc: function(min) { + var length = this.length || 16; + + while (length < this.pos + min) length *= 2; + + if (length !== this.length) { + var buf = new Uint8Array(length); + buf.set(this.buf); + this.buf = buf; + this.length = length; + } + }, + + finish: function() { + this.length = this.pos; + this.pos = 0; + return this.buf.subarray(0, this.length); + }, + + writeFixed32: function(val) { + this.realloc(4); + writeInt32(this.buf, val, this.pos); + this.pos += 4; + }, + + writeSFixed32: function(val) { + this.realloc(4); + writeInt32(this.buf, val, this.pos); + this.pos += 4; + }, + + writeFixed64: function(val) { + this.realloc(8); + writeInt32(this.buf, val & -1, this.pos); + writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4); + this.pos += 8; + }, + + writeSFixed64: function(val) { + this.realloc(8); + writeInt32(this.buf, val & -1, this.pos); + writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4); + this.pos += 8; + }, + + writeVarint: function(val) { + val = +val || 0; + + if (val > 0xfffffff || val < 0) { + writeBigVarint(val, this); + return; + } + + this.realloc(4); + + this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = (val >>> 7) & 0x7f; + }, + + writeSVarint: function(val) { + this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2); + }, + + writeBoolean: function(val) { + this.writeVarint(Boolean(val)); + }, + + writeString: function(str) { + str = String(str); + this.realloc(str.length * 4); + + this.pos++; // reserve 1 byte for short string length + + var startPos = this.pos; + // write the string directly to the buffer and see how much was written + this.pos = writeUtf8(this.buf, str, this.pos); + var len = this.pos - startPos; + + if (len >= 0x80) makeRoomForExtraLength(startPos, len, this); + + // finally, write the message length in the reserved place and restore the position + this.pos = startPos - 1; + this.writeVarint(len); + this.pos += len; + }, + + writeFloat: function(val) { + this.realloc(4); + ieee754.write(this.buf, val, this.pos, true, 23, 4); + this.pos += 4; + }, + + writeDouble: function(val) { + this.realloc(8); + ieee754.write(this.buf, val, this.pos, true, 52, 8); + this.pos += 8; + }, + + writeBytes: function(buffer) { + var len = buffer.length; + this.writeVarint(len); + this.realloc(len); + for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i]; + }, + + writeRawMessage: function(fn, obj) { + this.pos++; // reserve 1 byte for short message length + + // write the message directly to the buffer and see how much was written + var startPos = this.pos; + fn(obj, this); + var len = this.pos - startPos; + + if (len >= 0x80) makeRoomForExtraLength(startPos, len, this); + + // finally, write the message length in the reserved place and restore the position + this.pos = startPos - 1; + this.writeVarint(len); + this.pos += len; + }, + + writeMessage: function(tag, fn, obj) { + this.writeTag(tag, Pbf.Bytes); + this.writeRawMessage(fn, obj); + }, + + writePackedVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedVarint, arr); }, + writePackedSVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSVarint, arr); }, + writePackedBoolean: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedBoolean, arr); }, + writePackedFloat: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFloat, arr); }, + writePackedDouble: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedDouble, arr); }, + writePackedFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed32, arr); }, + writePackedSFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr); }, + writePackedFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed64, arr); }, + writePackedSFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr); }, + + writeBytesField: function(tag, buffer) { + this.writeTag(tag, Pbf.Bytes); + this.writeBytes(buffer); + }, + writeFixed32Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeFixed32(val); + }, + writeSFixed32Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeSFixed32(val); + }, + writeFixed64Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeFixed64(val); + }, + writeSFixed64Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeSFixed64(val); + }, + writeVarintField: function(tag, val) { + this.writeTag(tag, Pbf.Varint); + this.writeVarint(val); + }, + writeSVarintField: function(tag, val) { + this.writeTag(tag, Pbf.Varint); + this.writeSVarint(val); + }, + writeStringField: function(tag, str) { + this.writeTag(tag, Pbf.Bytes); + this.writeString(str); + }, + writeFloatField: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeFloat(val); + }, + writeDoubleField: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeDouble(val); + }, + writeBooleanField: function(tag, val) { + this.writeVarintField(tag, Boolean(val)); + } +}; + +function readVarintRemainder(l, s, p) { + var buf = p.buf, + h, b; + + b = buf[p.pos++]; h = (b & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s); + + throw new Error('Expected varint not more than 10 bytes'); +} + +function readPackedEnd(pbf) { + return pbf.type === Pbf.Bytes ? + pbf.readVarint() + pbf.pos : pbf.pos + 1; +} + +function toNum(low, high, isSigned) { + if (isSigned) { + return high * 0x100000000 + (low >>> 0); + } + + return ((high >>> 0) * 0x100000000) + (low >>> 0); +} + +function writeBigVarint(val, pbf) { + var low, high; + + if (val >= 0) { + low = (val % 0x100000000) | 0; + high = (val / 0x100000000) | 0; + } else { + low = ~(-val % 0x100000000); + high = ~(-val / 0x100000000); + + if (low ^ 0xffffffff) { + low = (low + 1) | 0; + } else { + low = 0; + high = (high + 1) | 0; + } + } + + if (val >= 0x10000000000000000 || val < -0x10000000000000000) { + throw new Error('Given varint doesn\'t fit into 10 bytes'); + } + + pbf.realloc(10); + + writeBigVarintLow(low, high, pbf); + writeBigVarintHigh(high, pbf); +} + +function writeBigVarintLow(low, high, pbf) { + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos] = low & 0x7f; +} + +function writeBigVarintHigh(high, pbf) { + var lsb = (high & 0x07) << 4; + + pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f; +} + +function makeRoomForExtraLength(startPos, len, pbf) { + var extraLen = + len <= 0x3fff ? 1 : + len <= 0x1fffff ? 2 : + len <= 0xfffffff ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7)); + + // if 1 byte isn't enough for encoding message length, shift the data to the right + pbf.realloc(extraLen); + for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i]; +} + +function writePackedVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]); } +function writePackedSVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); } +function writePackedFloat(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); } +function writePackedDouble(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); } +function writePackedBoolean(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); } +function writePackedFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); } +function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); } +function writePackedFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); } +function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); } + +// Buffer code below from https://github.com/feross/buffer, MIT-licensed + +function readUInt32(buf, pos) { + return ((buf[pos]) | + (buf[pos + 1] << 8) | + (buf[pos + 2] << 16)) + + (buf[pos + 3] * 0x1000000); +} + +function writeInt32(buf, val, pos) { + buf[pos] = val; + buf[pos + 1] = (val >>> 8); + buf[pos + 2] = (val >>> 16); + buf[pos + 3] = (val >>> 24); +} + +function readInt32(buf, pos) { + return ((buf[pos]) | + (buf[pos + 1] << 8) | + (buf[pos + 2] << 16)) + + (buf[pos + 3] << 24); +} + +function readUtf8(buf, pos, end) { + var str = ''; + var i = pos; + + while (i < end) { + var b0 = buf[i]; + var c = null; // codepoint + var bytesPerSequence = + b0 > 0xEF ? 4 : + b0 > 0xDF ? 3 : + b0 > 0xBF ? 2 : 1; + + if (i + bytesPerSequence > end) break; + + var b1, b2, b3; + + if (bytesPerSequence === 1) { + if (b0 < 0x80) { + c = b0; + } + } else if (bytesPerSequence === 2) { + b1 = buf[i + 1]; + if ((b1 & 0xC0) === 0x80) { + c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F); + if (c <= 0x7F) { + c = null; + } + } + } else if (bytesPerSequence === 3) { + b1 = buf[i + 1]; + b2 = buf[i + 2]; + if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) { + c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F); + if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) { + c = null; + } + } + } else if (bytesPerSequence === 4) { + b1 = buf[i + 1]; + b2 = buf[i + 2]; + b3 = buf[i + 3]; + if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) { + c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F); + if (c <= 0xFFFF || c >= 0x110000) { + c = null; + } + } + } + + if (c === null) { + c = 0xFFFD; + bytesPerSequence = 1; + + } else if (c > 0xFFFF) { + c -= 0x10000; + str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800); + c = 0xDC00 | c & 0x3FF; + } + + str += String.fromCharCode(c); + i += bytesPerSequence; + } + + return str; +} + +function readUtf8TextDecoder(buf, pos, end) { + return utf8TextDecoder.decode(buf.subarray(pos, end)); +} + +function writeUtf8(buf, str, pos) { + for (var i = 0, c, lead; i < str.length; i++) { + c = str.charCodeAt(i); // code point + + if (c > 0xD7FF && c < 0xE000) { + if (lead) { + if (c < 0xDC00) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + lead = c; + continue; + } else { + c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000; + lead = null; + } + } else { + if (c > 0xDBFF || (i + 1 === str.length)) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + } else { + lead = c; + } + continue; + } + } else if (lead) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + lead = null; + } + + if (c < 0x80) { + buf[pos++] = c; + } else { + if (c < 0x800) { + buf[pos++] = c >> 0x6 | 0xC0; + } else { + if (c < 0x10000) { + buf[pos++] = c >> 0xC | 0xE0; + } else { + buf[pos++] = c >> 0x12 | 0xF0; + buf[pos++] = c >> 0xC & 0x3F | 0x80; + } + buf[pos++] = c >> 0x6 & 0x3F | 0x80; + } + buf[pos++] = c & 0x3F | 0x80; + } + } + return pos; +} + +var Protobuf = /*@__PURE__*/getDefaultExportFromCjs$1(pbf); + +const border$1 = 3; +function readFontstacks(tag, glyphs, pbf) { + if (tag === 1) { + pbf.readMessage(readFontstack, glyphs); + } +} +function readFontstack(tag, glyphs, pbf) { + if (tag === 3) { + const { id, bitmap, width, height, left, top, advance } = pbf.readMessage(readGlyph, {}); + glyphs.push({ + id, + bitmap: new AlphaImage({ + width: width + 2 * border$1, + height: height + 2 * border$1 + }, bitmap), + metrics: { width, height, left, top, advance } + }); + } +} +function readGlyph(tag, glyph, pbf) { + if (tag === 1) + glyph.id = pbf.readVarint(); + else if (tag === 2) + glyph.bitmap = pbf.readBytes(); + else if (tag === 3) + glyph.width = pbf.readVarint(); + else if (tag === 4) + glyph.height = pbf.readVarint(); + else if (tag === 5) + glyph.left = pbf.readSVarint(); + else if (tag === 6) + glyph.top = pbf.readSVarint(); + else if (tag === 7) + glyph.advance = pbf.readVarint(); +} +function parseGlyphPbf(data) { + return new Protobuf(data).readFields(readFontstacks, []); +} +const GLYPH_PBF_BORDER = border$1; + +function potpack(boxes) { + + // calculate total box area and maximum box width + let area = 0; + let maxWidth = 0; + + for (const box of boxes) { + area += box.w * box.h; + maxWidth = Math.max(maxWidth, box.w); + } + + // sort the boxes for insertion by height, descending + boxes.sort((a, b) => b.h - a.h); + + // aim for a squarish resulting container, + // slightly adjusted for sub-100% space utilization + const startWidth = Math.max(Math.ceil(Math.sqrt(area / 0.95)), maxWidth); + + // start with a single empty space, unbounded at the bottom + const spaces = [{x: 0, y: 0, w: startWidth, h: Infinity}]; + + let width = 0; + let height = 0; + + for (const box of boxes) { + // look through spaces backwards so that we check smaller spaces first + for (let i = spaces.length - 1; i >= 0; i--) { + const space = spaces[i]; + + // look for empty spaces that can accommodate the current box + if (box.w > space.w || box.h > space.h) continue; + + // found the space; add the box to its top-left corner + // |-------|-------| + // | box | | + // |_______| | + // | space | + // |_______________| + box.x = space.x; + box.y = space.y; + + height = Math.max(height, box.y + box.h); + width = Math.max(width, box.x + box.w); + + if (box.w === space.w && box.h === space.h) { + // space matches the box exactly; remove it + const last = spaces.pop(); + if (i < spaces.length) spaces[i] = last; + + } else if (box.h === space.h) { + // space matches the box height; update it accordingly + // |-------|---------------| + // | box | updated space | + // |_______|_______________| + space.x += box.w; + space.w -= box.w; + + } else if (box.w === space.w) { + // space matches the box width; update it accordingly + // |---------------| + // | box | + // |_______________| + // | updated space | + // |_______________| + space.y += box.h; + space.h -= box.h; + + } else { + // otherwise the box splits the space into two spaces + // |-------|-----------| + // | box | new space | + // |_______|___________| + // | updated space | + // |___________________| + spaces.push({ + x: space.x + box.w, + y: space.y, + w: space.w - box.w, + h: box.h + }); + space.y += box.h; + space.h -= box.h; + } + break; + } + } + + return { + w: width, // container width + h: height, // container height + fill: (area / (width * height)) || 0 // space utilization + }; +} + +/* eslint-disable key-spacing */ +const IMAGE_PADDING = 1; +class ImagePosition { + constructor(paddedRect, { pixelRatio, version, stretchX, stretchY, content, textFitWidth, textFitHeight }) { + this.paddedRect = paddedRect; + this.pixelRatio = pixelRatio; + this.stretchX = stretchX; + this.stretchY = stretchY; + this.content = content; + this.version = version; + this.textFitWidth = textFitWidth; + this.textFitHeight = textFitHeight; + } + get tl() { + return [ + this.paddedRect.x + IMAGE_PADDING, + this.paddedRect.y + IMAGE_PADDING + ]; + } + get br() { + return [ + this.paddedRect.x + this.paddedRect.w - IMAGE_PADDING, + this.paddedRect.y + this.paddedRect.h - IMAGE_PADDING + ]; + } + get tlbr() { + return this.tl.concat(this.br); + } + get displaySize() { + return [ + (this.paddedRect.w - IMAGE_PADDING * 2) / this.pixelRatio, + (this.paddedRect.h - IMAGE_PADDING * 2) / this.pixelRatio + ]; + } +} +/** + * A class holding all the images + */ +class ImageAtlas { + constructor(icons, patterns) { + const iconPositions = {}, patternPositions = {}; + this.haveRenderCallbacks = []; + const bins = []; + this.addImages(icons, iconPositions, bins); + this.addImages(patterns, patternPositions, bins); + const { w, h } = potpack(bins); + const image = new RGBAImage({ width: w || 1, height: h || 1 }); + for (const id in icons) { + const src = icons[id]; + const bin = iconPositions[id].paddedRect; + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x: bin.x + IMAGE_PADDING, y: bin.y + IMAGE_PADDING }, src.data); + } + for (const id in patterns) { + const src = patterns[id]; + const bin = patternPositions[id].paddedRect; + const x = bin.x + IMAGE_PADDING, y = bin.y + IMAGE_PADDING, w = src.data.width, h = src.data.height; + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x, y }, src.data); + // Add 1 pixel wrapped padding on each side of the image. + RGBAImage.copy(src.data, image, { x: 0, y: h - 1 }, { x, y: y - 1 }, { width: w, height: 1 }); // T + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x, y: y + h }, { width: w, height: 1 }); // B + RGBAImage.copy(src.data, image, { x: w - 1, y: 0 }, { x: x - 1, y }, { width: 1, height: h }); // L + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x: x + w, y }, { width: 1, height: h }); // R + } + this.image = image; + this.iconPositions = iconPositions; + this.patternPositions = patternPositions; + } + addImages(images, positions, bins) { + for (const id in images) { + const src = images[id]; + const bin = { + x: 0, + y: 0, + w: src.data.width + 2 * IMAGE_PADDING, + h: src.data.height + 2 * IMAGE_PADDING, + }; + bins.push(bin); + positions[id] = new ImagePosition(bin, src); + if (src.hasRenderCallback) { + this.haveRenderCallbacks.push(id); + } + } + } + patchUpdatedImages(imageManager, texture) { + imageManager.dispatchRenderCallbacks(this.haveRenderCallbacks); + for (const name in imageManager.updatedImages) { + this.patchUpdatedImage(this.iconPositions[name], imageManager.getImage(name), texture); + this.patchUpdatedImage(this.patternPositions[name], imageManager.getImage(name), texture); + } + } + patchUpdatedImage(position, image, texture) { + if (!position || !image) + return; + if (position.version === image.version) + return; + position.version = image.version; + const [x, y] = position.tl; + texture.update(image.data, undefined, { x, y }); + } +} +register('ImagePosition', ImagePosition); +register('ImageAtlas', ImageAtlas); + +exports.WritingMode = void 0; +(function (WritingMode) { + WritingMode[WritingMode["none"] = 0] = "none"; + WritingMode[WritingMode["horizontal"] = 1] = "horizontal"; + WritingMode[WritingMode["vertical"] = 2] = "vertical"; + WritingMode[WritingMode["horizontalOnly"] = 3] = "horizontalOnly"; +})(exports.WritingMode || (exports.WritingMode = {})); +const SHAPING_DEFAULT_OFFSET = -17; +function isEmpty(positionedLines) { + for (const line of positionedLines) { + if (line.positionedGlyphs.length !== 0) { + return false; + } + } + return true; +} +// Max number of images in label is 6401 U+E000–U+F8FF that covers +// Basic Multilingual Plane Unicode Private Use Area (PUA). +const PUAbegin = 0xE000; +const PUAend = 0xF8FF; +class SectionOptions { + constructor() { + this.scale = 1.0; + this.fontStack = ''; + this.imageName = null; + } + static forText(scale, fontStack) { + const textOptions = new SectionOptions(); + textOptions.scale = scale || 1; + textOptions.fontStack = fontStack; + return textOptions; + } + static forImage(imageName) { + const imageOptions = new SectionOptions(); + imageOptions.imageName = imageName; + return imageOptions; + } +} +class TaggedString { + constructor() { + this.text = ''; + this.sectionIndex = []; + this.sections = []; + this.imageSectionID = null; + } + static fromFeature(text, defaultFontStack) { + const result = new TaggedString(); + for (let i = 0; i < text.sections.length; i++) { + const section = text.sections[i]; + if (!section.image) { + result.addTextSection(section, defaultFontStack); + } + else { + result.addImageSection(section); + } + } + return result; + } + length() { + return this.text.length; + } + getSection(index) { + return this.sections[this.sectionIndex[index]]; + } + getSectionIndex(index) { + return this.sectionIndex[index]; + } + getCharCode(index) { + return this.text.charCodeAt(index); + } + verticalizePunctuation() { + this.text = verticalizePunctuation(this.text); + } + trim() { + let beginningWhitespace = 0; + for (let i = 0; i < this.text.length && whitespace[this.text.charCodeAt(i)]; i++) { + beginningWhitespace++; + } + let trailingWhitespace = this.text.length; + for (let i = this.text.length - 1; i >= 0 && i >= beginningWhitespace && whitespace[this.text.charCodeAt(i)]; i--) { + trailingWhitespace--; + } + this.text = this.text.substring(beginningWhitespace, trailingWhitespace); + this.sectionIndex = this.sectionIndex.slice(beginningWhitespace, trailingWhitespace); + } + substring(start, end) { + const substring = new TaggedString(); + substring.text = this.text.substring(start, end); + substring.sectionIndex = this.sectionIndex.slice(start, end); + substring.sections = this.sections; + return substring; + } + toString() { + return this.text; + } + getMaxScale() { + return this.sectionIndex.reduce((max, index) => Math.max(max, this.sections[index].scale), 0); + } + addTextSection(section, defaultFontStack) { + this.text += section.text; + this.sections.push(SectionOptions.forText(section.scale, section.fontStack || defaultFontStack)); + const index = this.sections.length - 1; + for (let i = 0; i < section.text.length; ++i) { + this.sectionIndex.push(index); + } + } + addImageSection(section) { + const imageName = section.image ? section.image.name : ''; + if (imageName.length === 0) { + warnOnce('Can\'t add FormattedSection with an empty image.'); + return; + } + const nextImageSectionCharCode = this.getNextImageSectionCharCode(); + if (!nextImageSectionCharCode) { + warnOnce(`Reached maximum number of images ${PUAend - PUAbegin + 2}`); + return; + } + this.text += String.fromCharCode(nextImageSectionCharCode); + this.sections.push(SectionOptions.forImage(imageName)); + this.sectionIndex.push(this.sections.length - 1); + } + getNextImageSectionCharCode() { + if (!this.imageSectionID) { + this.imageSectionID = PUAbegin; + return this.imageSectionID; + } + if (this.imageSectionID >= PUAend) + return null; + return ++this.imageSectionID; + } +} +function breakLines(input, lineBreakPoints) { + const lines = []; + const text = input.text; + let start = 0; + for (const lineBreak of lineBreakPoints) { + lines.push(input.substring(start, lineBreak)); + start = lineBreak; + } + if (start < text.length) { + lines.push(input.substring(start, text.length)); + } + return lines; +} +function shapeText(text, glyphMap, glyphPositions, imagePositions, defaultFontStack, maxWidth, lineHeight, textAnchor, textJustify, spacing, translate, writingMode, allowVerticalPlacement, layoutTextSize, layoutTextSizeThisZoom) { + const logicalInput = TaggedString.fromFeature(text, defaultFontStack); + if (writingMode === exports.WritingMode.vertical) { + logicalInput.verticalizePunctuation(); + } + let lines; + const { processBidirectionalText, processStyledBidirectionalText } = rtlWorkerPlugin; + if (processBidirectionalText && logicalInput.sections.length === 1) { + // Bidi doesn't have to be style-aware + lines = []; + const untaggedLines = processBidirectionalText(logicalInput.toString(), determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + for (const line of untaggedLines) { + const taggedLine = new TaggedString(); + taggedLine.text = line; + taggedLine.sections = logicalInput.sections; + for (let i = 0; i < line.length; i++) { + taggedLine.sectionIndex.push(0); + } + lines.push(taggedLine); + } + } + else if (processStyledBidirectionalText) { + // Need version of mapbox-gl-rtl-text with style support for combining RTL text + // with formatting + lines = []; + const processedLines = processStyledBidirectionalText(logicalInput.text, logicalInput.sectionIndex, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + for (const line of processedLines) { + const taggedLine = new TaggedString(); + taggedLine.text = line[0]; + taggedLine.sectionIndex = line[1]; + taggedLine.sections = logicalInput.sections; + lines.push(taggedLine); + } + } + else { + lines = breakLines(logicalInput, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + } + const positionedLines = []; + const shaping = { + positionedLines, + text: logicalInput.toString(), + top: translate[1], + bottom: translate[1], + left: translate[0], + right: translate[0], + writingMode, + iconsInText: false, + verticalizable: false + }; + shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom); + if (isEmpty(positionedLines)) + return false; + return shaping; +} +// using computed properties due to https://github.com/facebook/flow/issues/380 +/* eslint no-useless-computed-key: 0 */ +const whitespace = { + [0x09]: true, // tab + [0x0a]: true, // newline + [0x0b]: true, // vertical tab + [0x0c]: true, // form feed + [0x0d]: true, // carriage return + [0x20]: true, // space +}; +const breakable = { + [0x0a]: true, // newline + [0x20]: true, // space + [0x26]: true, // ampersand + [0x29]: true, // right parenthesis + [0x2b]: true, // plus sign + [0x2d]: true, // hyphen-minus + [0x2f]: true, // solidus + [0xad]: true, // soft hyphen + [0xb7]: true, // middle dot + [0x200b]: true, // zero-width space + [0x2010]: true, // hyphen + [0x2013]: true, // en dash + [0x2027]: true // interpunct + // Many other characters may be reasonable breakpoints + // Consider "neutral orientation" characters at scriptDetection.charHasNeutralVerticalOrientation + // See https://github.com/mapbox/mapbox-gl-js/issues/3658 +}; +// Allow breaks depending on the following character +const breakableBefore = { + [0x28]: true, // left parenthesis +}; +function getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize) { + if (!section.imageName) { + const positions = glyphMap[section.fontStack]; + const glyph = positions && positions[codePoint]; + if (!glyph) + return 0; + return glyph.metrics.advance * section.scale + spacing; + } + else { + const imagePosition = imagePositions[section.imageName]; + if (!imagePosition) + return 0; + return imagePosition.displaySize[0] * section.scale * ONE_EM / layoutTextSize + spacing; + } +} +function determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) { + let totalWidth = 0; + for (let index = 0; index < logicalInput.length(); index++) { + const section = logicalInput.getSection(index); + totalWidth += getGlyphAdvance(logicalInput.getCharCode(index), section, glyphMap, imagePositions, spacing, layoutTextSize); + } + const lineCount = Math.max(1, Math.ceil(totalWidth / maxWidth)); + return totalWidth / lineCount; +} +function calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) { + const raggedness = Math.pow(lineWidth - targetWidth, 2); + if (isLastBreak) { + // Favor finals lines shorter than average over longer than average + if (lineWidth < targetWidth) { + return raggedness / 2; + } + else { + return raggedness * 2; + } + } + return raggedness + Math.abs(penalty) * penalty; +} +function calculatePenalty(codePoint, nextCodePoint, penalizableIdeographicBreak) { + let penalty = 0; + // Force break on newline + if (codePoint === 0x0a) { + penalty -= 10000; + } + // Penalize breaks between characters that allow ideographic breaking because + // they are less preferable than breaks at spaces (or zero width spaces). + if (penalizableIdeographicBreak) { + penalty += 150; + } + // Penalize open parenthesis at end of line + if (codePoint === 0x28 || codePoint === 0xff08) { + penalty += 50; + } + // Penalize close parenthesis at beginning of line + if (nextCodePoint === 0x29 || nextCodePoint === 0xff09) { + penalty += 50; + } + return penalty; +} +function evaluateBreak(breakIndex, breakX, targetWidth, potentialBreaks, penalty, isLastBreak) { + // We could skip evaluating breaks where the line length (breakX - priorBreak.x) > maxWidth + // ...but in fact we allow lines longer than maxWidth (if there's no break points) + // ...and when targetWidth and maxWidth are close, strictly enforcing maxWidth can give + // more lopsided results. + let bestPriorBreak = null; + let bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak); + for (const potentialBreak of potentialBreaks) { + const lineWidth = breakX - potentialBreak.x; + const breakBadness = calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness; + if (breakBadness <= bestBreakBadness) { + bestPriorBreak = potentialBreak; + bestBreakBadness = breakBadness; + } + } + return { + index: breakIndex, + x: breakX, + priorBreak: bestPriorBreak, + badness: bestBreakBadness + }; +} +function leastBadBreaks(lastLineBreak) { + if (!lastLineBreak) { + return []; + } + return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index); +} +function determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) { + if (!logicalInput) + return []; + const potentialLineBreaks = []; + const targetWidth = determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize); + const hasServerSuggestedBreakpoints = logicalInput.text.indexOf('\u200b') >= 0; + let currentX = 0; + for (let i = 0; i < logicalInput.length(); i++) { + const section = logicalInput.getSection(i); + const codePoint = logicalInput.getCharCode(i); + if (!whitespace[codePoint]) + currentX += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize); + // Ideographic characters, spaces, and word-breaking punctuation that often appear without + // surrounding spaces. + if ((i < logicalInput.length() - 1)) { + const ideographicBreak = charAllowsIdeographicBreaking(codePoint); + if (breakable[codePoint] || ideographicBreak || section.imageName || (i !== logicalInput.length() - 2 && breakableBefore[logicalInput.getCharCode(i + 1)])) { + potentialLineBreaks.push(evaluateBreak(i + 1, currentX, targetWidth, potentialLineBreaks, calculatePenalty(codePoint, logicalInput.getCharCode(i + 1), ideographicBreak && hasServerSuggestedBreakpoints), false)); + } + } + } + return leastBadBreaks(evaluateBreak(logicalInput.length(), currentX, targetWidth, potentialLineBreaks, 0, true)); +} +function getAnchorAlignment(anchor) { + let horizontalAlign = 0.5, verticalAlign = 0.5; + switch (anchor) { + case 'right': + case 'top-right': + case 'bottom-right': + horizontalAlign = 1; + break; + case 'left': + case 'top-left': + case 'bottom-left': + horizontalAlign = 0; + break; + } + switch (anchor) { + case 'bottom': + case 'bottom-right': + case 'bottom-left': + verticalAlign = 1; + break; + case 'top': + case 'top-right': + case 'top-left': + verticalAlign = 0; + break; + } + return { horizontalAlign, verticalAlign }; +} +function shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom) { + let x = 0; + let y = SHAPING_DEFAULT_OFFSET; + let maxLineLength = 0; + let maxLineHeight = 0; + const justify = textJustify === 'right' ? 1 : + textJustify === 'left' ? 0 : 0.5; + let lineIndex = 0; + for (const line of lines) { + line.trim(); + const lineMaxScale = line.getMaxScale(); + const maxLineOffset = (lineMaxScale - 1) * ONE_EM; + const positionedLine = { positionedGlyphs: [], lineOffset: 0 }; + shaping.positionedLines[lineIndex] = positionedLine; + const positionedGlyphs = positionedLine.positionedGlyphs; + let lineOffset = 0.0; + if (!line.length()) { + y += lineHeight; // Still need a line feed after empty line + ++lineIndex; + continue; + } + for (let i = 0; i < line.length(); i++) { + const section = line.getSection(i); + const sectionIndex = line.getSectionIndex(i); + const codePoint = line.getCharCode(i); + let baselineOffset = 0.0; + let metrics = null; + let rect = null; + let imageName = null; + let verticalAdvance = ONE_EM; + const vertical = !(writingMode === exports.WritingMode.horizontal || + // Don't verticalize glyphs that have no upright orientation if vertical placement is disabled. + (!allowVerticalPlacement && !charHasUprightVerticalOrientation(codePoint)) || + // If vertical placement is enabled, don't verticalize glyphs that + // are from complex text layout script, or whitespaces. + (allowVerticalPlacement && (whitespace[codePoint] || charInComplexShapingScript(codePoint)))); + if (!section.imageName) { + const positions = glyphPositions[section.fontStack]; + const glyphPosition = positions && positions[codePoint]; + if (glyphPosition && glyphPosition.rect) { + rect = glyphPosition.rect; + metrics = glyphPosition.metrics; + } + else { + const glyphs = glyphMap[section.fontStack]; + const glyph = glyphs && glyphs[codePoint]; + if (!glyph) + continue; + metrics = glyph.metrics; + } + // We don't know the baseline, but since we're laying out + // at 24 points, we can calculate how much it will move when + // we scale up or down. + baselineOffset = (lineMaxScale - section.scale) * ONE_EM; + } + else { + const imagePosition = imagePositions[section.imageName]; + if (!imagePosition) + continue; + imageName = section.imageName; + shaping.iconsInText = shaping.iconsInText || true; + rect = imagePosition.paddedRect; + const size = imagePosition.displaySize; + // If needed, allow to set scale factor for an image using + // alias "image-scale" that could be alias for "font-scale" + // when FormattedSection is an image section. + section.scale = section.scale * ONE_EM / layoutTextSizeThisZoom; + metrics = { width: size[0], + height: size[1], + left: IMAGE_PADDING, + top: -GLYPH_PBF_BORDER, + advance: vertical ? size[1] : size[0] }; + // Difference between one EM and an image size. + // Aligns bottom of an image to a baseline level. + const imageOffset = ONE_EM - size[1] * section.scale; + baselineOffset = maxLineOffset + imageOffset; + verticalAdvance = metrics.advance; + // Difference between height of an image and one EM at max line scale. + // Pushes current line down if an image size is over 1 EM at max line scale. + const offset = vertical ? size[0] * section.scale - ONE_EM * lineMaxScale : + size[1] * section.scale - ONE_EM * lineMaxScale; + if (offset > 0 && offset > lineOffset) { + lineOffset = offset; + } + } + if (!vertical) { + positionedGlyphs.push({ glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect }); + x += metrics.advance * section.scale + spacing; + } + else { + shaping.verticalizable = true; + positionedGlyphs.push({ glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect }); + x += verticalAdvance * section.scale + spacing; + } + } + // Only justify if we placed at least one glyph + if (positionedGlyphs.length !== 0) { + const lineLength = x - spacing; + maxLineLength = Math.max(lineLength, maxLineLength); + justifyLine(positionedGlyphs, 0, positionedGlyphs.length - 1, justify, lineOffset); + } + x = 0; + const currentLineHeight = lineHeight * lineMaxScale + lineOffset; + positionedLine.lineOffset = Math.max(lineOffset, maxLineOffset); + y += currentLineHeight; + maxLineHeight = Math.max(currentLineHeight, maxLineHeight); + ++lineIndex; + } + // Calculate the bounding box and justify / align text block. + const height = y - SHAPING_DEFAULT_OFFSET; + const { horizontalAlign, verticalAlign } = getAnchorAlignment(textAnchor); + align(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, height, lines.length); + shaping.top += -verticalAlign * height; + shaping.bottom = shaping.top + height; + shaping.left += -horizontalAlign * maxLineLength; + shaping.right = shaping.left + maxLineLength; +} +// justify right = 1, left = 0, center = 0.5 +function justifyLine(positionedGlyphs, start, end, justify, lineOffset) { + if (!justify && !lineOffset) + return; + const lastPositionedGlyph = positionedGlyphs[end]; + const lastAdvance = lastPositionedGlyph.metrics.advance * lastPositionedGlyph.scale; + const lineIndent = (positionedGlyphs[end].x + lastAdvance) * justify; + for (let j = start; j <= end; j++) { + positionedGlyphs[j].x -= lineIndent; + positionedGlyphs[j].y += lineOffset; + } +} +function align(positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, blockHeight, lineCount) { + const shiftX = (justify - horizontalAlign) * maxLineLength; + let shiftY = 0; + if (maxLineHeight !== lineHeight) { + shiftY = -blockHeight * verticalAlign - SHAPING_DEFAULT_OFFSET; + } + else { + shiftY = (-verticalAlign * lineCount + 0.5) * lineHeight; + } + for (const line of positionedLines) { + for (const positionedGlyph of line.positionedGlyphs) { + positionedGlyph.x += shiftX; + positionedGlyph.y += shiftY; + } + } +} +function shapeIcon(image, iconOffset, iconAnchor) { + const { horizontalAlign, verticalAlign } = getAnchorAlignment(iconAnchor); + const dx = iconOffset[0]; + const dy = iconOffset[1]; + const x1 = dx - image.displaySize[0] * horizontalAlign; + const x2 = x1 + image.displaySize[0]; + const y1 = dy - image.displaySize[1] * verticalAlign; + const y2 = y1 + image.displaySize[1]; + return { image, top: y1, bottom: y2, left: x1, right: x2 }; +} +/** + * Called after a PositionedIcon has already been run through fitIconToText, + * but needs further adjustment to apply textFitWidth and textFitHeight. + * @param shapedIcon - The icon that will be adjusted. + * @returns Extents of the shapedIcon with text fit adjustments if necessary. + */ +function applyTextFit(shapedIcon) { + var _a, _b; + // Assume shapedIcon.image is set or this wouldn't be called. + // Size of the icon after it was adjusted using stretchX and Y + let iconLeft = shapedIcon.left; + let iconTop = shapedIcon.top; + let iconWidth = shapedIcon.right - iconLeft; + let iconHeight = shapedIcon.bottom - iconTop; + // Size of the original content area + const contentWidth = shapedIcon.image.content[2] - shapedIcon.image.content[0]; + const contentHeight = shapedIcon.image.content[3] - shapedIcon.image.content[1]; + const textFitWidth = (_a = shapedIcon.image.textFitWidth) !== null && _a !== void 0 ? _a : "stretchOrShrink" /* TextFit.stretchOrShrink */; + const textFitHeight = (_b = shapedIcon.image.textFitHeight) !== null && _b !== void 0 ? _b : "stretchOrShrink" /* TextFit.stretchOrShrink */; + const contentAspectRatio = contentWidth / contentHeight; + // Scale to the proportional axis first note that height takes precedence if + // both axes are set to proportional. + if (textFitHeight === "proportional" /* TextFit.proportional */) { + if ((textFitWidth === "stretchOnly" /* TextFit.stretchOnly */ && iconWidth / iconHeight < contentAspectRatio) || textFitWidth === "proportional" /* TextFit.proportional */) { + // Push the width of the icon back out to match the content aspect ratio + const newIconWidth = Math.ceil(iconHeight * contentAspectRatio); + iconLeft *= newIconWidth / iconWidth; + iconWidth = newIconWidth; + } + } + else if (textFitWidth === "proportional" /* TextFit.proportional */) { + if (textFitHeight === "stretchOnly" /* TextFit.stretchOnly */ && contentAspectRatio !== 0 && iconWidth / iconHeight > contentAspectRatio) { + // Push the height of the icon back out to match the content aspect ratio + const newIconHeight = Math.ceil(iconWidth / contentAspectRatio); + iconTop *= newIconHeight / iconHeight; + iconHeight = newIconHeight; + } + } + else { + // If neither textFitHeight nor textFitWidth are proportional then + // there is no effect since the content rectangle should be precisely + // matched to the content + } + return { x1: iconLeft, y1: iconTop, x2: iconLeft + iconWidth, y2: iconTop + iconHeight }; +} +function fitIconToText(shapedIcon, shapedText, textFit, padding, iconOffset, fontScale) { + const image = shapedIcon.image; + let collisionPadding; + if (image.content) { + const content = image.content; + const pixelRatio = image.pixelRatio || 1; + collisionPadding = [ + content[0] / pixelRatio, + content[1] / pixelRatio, + image.displaySize[0] - content[2] / pixelRatio, + image.displaySize[1] - content[3] / pixelRatio + ]; + } + // We don't respect the icon-anchor, because icon-text-fit is set. Instead, + // the icon will be centered on the text, then stretched in the given + // dimensions. + const textLeft = shapedText.left * fontScale; + const textRight = shapedText.right * fontScale; + let top, right, bottom, left; + if (textFit === 'width' || textFit === 'both') { + // Stretched horizontally to the text width + left = iconOffset[0] + textLeft - padding[3]; + right = iconOffset[0] + textRight + padding[1]; + } + else { + // Centered on the text + left = iconOffset[0] + (textLeft + textRight - image.displaySize[0]) / 2; + right = left + image.displaySize[0]; + } + const textTop = shapedText.top * fontScale; + const textBottom = shapedText.bottom * fontScale; + if (textFit === 'height' || textFit === 'both') { + // Stretched vertically to the text height + top = iconOffset[1] + textTop - padding[0]; + bottom = iconOffset[1] + textBottom + padding[2]; + } + else { + // Centered on the text + top = iconOffset[1] + (textTop + textBottom - image.displaySize[1]) / 2; + bottom = top + image.displaySize[1]; + } + return { image, top, right, bottom, left, collisionPadding }; +} + +const MAX_GLYPH_ICON_SIZE = 255; +const SIZE_PACK_FACTOR = 128; +const MAX_PACKED_SIZE = MAX_GLYPH_ICON_SIZE * SIZE_PACK_FACTOR; +// For {text,icon}-size, get the bucket-level data that will be needed by +// the painter to set symbol-size-related uniforms +function getSizeData(tileZoom, value) { + const { expression } = value; + if (expression.kind === 'constant') { + const layoutSize = expression.evaluate(new EvaluationParameters(tileZoom + 1)); + return { kind: 'constant', layoutSize }; + } + else if (expression.kind === 'source') { + return { kind: 'source' }; + } + else { + const { zoomStops, interpolationType } = expression; + // calculate covering zoom stops for zoom-dependent values + let lower = 0; + while (lower < zoomStops.length && zoomStops[lower] <= tileZoom) + lower++; + lower = Math.max(0, lower - 1); + let upper = lower; + while (upper < zoomStops.length && zoomStops[upper] < tileZoom + 1) + upper++; + upper = Math.min(zoomStops.length - 1, upper); + const minZoom = zoomStops[lower]; + const maxZoom = zoomStops[upper]; + // We'd like to be able to use CameraExpression or CompositeExpression in these + // return types rather than ExpressionSpecification, but the former are not + // transferrable across Web Worker boundaries. + if (expression.kind === 'composite') { + return { kind: 'composite', minZoom, maxZoom, interpolationType }; + } + // for camera functions, also save off the function values + // evaluated at the covering zoom levels + const minSize = expression.evaluate(new EvaluationParameters(minZoom)); + const maxSize = expression.evaluate(new EvaluationParameters(maxZoom)); + return { kind: 'camera', minZoom, maxZoom, minSize, maxSize, interpolationType }; + } +} +function evaluateSizeForFeature(sizeData, { uSize, uSizeT }, { lowerSize, upperSize }) { + if (sizeData.kind === 'source') { + return lowerSize / SIZE_PACK_FACTOR; + } + else if (sizeData.kind === 'composite') { + return interpolate.number(lowerSize / SIZE_PACK_FACTOR, upperSize / SIZE_PACK_FACTOR, uSizeT); + } + return uSize; +} +function evaluateSizeForZoom(sizeData, zoom) { + let uSizeT = 0; + let uSize = 0; + if (sizeData.kind === 'constant') { + uSize = sizeData.layoutSize; + } + else if (sizeData.kind !== 'source') { + const { interpolationType, minZoom, maxZoom } = sizeData; + // Even though we could get the exact value of the camera function + // at z = tr.zoom, we intentionally do not: instead, we interpolate + // between the camera function values at a pair of zoom stops covering + // [tileZoom, tileZoom + 1] in order to be consistent with this + // restriction on composite functions + const t = !interpolationType ? 0 : clamp$1(Interpolate.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1); + if (sizeData.kind === 'camera') { + uSize = interpolate.number(sizeData.minSize, sizeData.maxSize, t); + } + else { + uSizeT = t; + } + } + return { uSizeT, uSize }; +} + +function getOverlapMode(layout, overlapProp, allowOverlapProp) { + let result = 'never'; + const overlap = layout.get(overlapProp); + if (overlap) { + // if -overlap is set, use it + result = overlap; + } + else if (layout.get(allowOverlapProp)) { + // fall back to -allow-overlap, with false='never', true='always' + result = 'always'; + } + return result; +} + +const vectorTileFeatureTypes = vectorTile.VectorTileFeature.types; +// Opacity arrays are frequently updated but don't contain a lot of information, so we pack them +// tight. Each Uint32 is actually four duplicate Uint8s for the four corners of a glyph +// 7 bits are for the current opacity, and the lowest bit is the target opacity +// actually defined in symbol_attributes.js +// const placementOpacityAttributes = [ +// { name: 'a_fade_opacity', components: 1, type: 'Uint32' } +// ]; +const shaderOpacityAttributes = [ + { name: 'a_fade_opacity', components: 1, type: 'Uint8', offset: 0 } +]; +function addVertex(array, anchorX, anchorY, ox, oy, tx, ty, sizeVertex, isSDF, pixelOffsetX, pixelOffsetY, minFontScaleX, minFontScaleY) { + const aSizeX = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[0])) : 0; + const aSizeY = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[1])) : 0; + array.emplaceBack( + // a_pos_offset + anchorX, anchorY, Math.round(ox * 32), Math.round(oy * 32), + // a_data + tx, // x coordinate of symbol on glyph atlas texture + ty, // y coordinate of symbol on glyph atlas texture + (aSizeX << 1) + (isSDF ? 1 : 0), aSizeY, pixelOffsetX * 16, pixelOffsetY * 16, minFontScaleX * 256, minFontScaleY * 256); +} +function addDynamicAttributes(dynamicLayoutVertexArray, p, angle) { + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); +} +function containsRTLText(formattedText) { + for (const section of formattedText.sections) { + if (stringContainsRTLText(section.text)) { + return true; + } + } + return false; +} +class SymbolBuffers { + constructor(programConfigurations) { + this.layoutVertexArray = new SymbolLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.programConfigurations = programConfigurations; + this.segments = new SegmentVector(); + this.dynamicLayoutVertexArray = new SymbolDynamicLayoutArray(); + this.opacityVertexArray = new SymbolOpacityArray(); + this.hasVisibleVertices = false; + this.placedSymbolArray = new PlacedSymbolArray(); + } + isEmpty() { + return this.layoutVertexArray.length === 0 && + this.indexArray.length === 0 && + this.dynamicLayoutVertexArray.length === 0 && + this.opacityVertexArray.length === 0; + } + upload(context, dynamicIndexBuffer, upload, update) { + if (this.isEmpty()) { + return; + } + if (upload) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members); + this.indexBuffer = context.createIndexBuffer(this.indexArray, dynamicIndexBuffer); + this.dynamicLayoutVertexBuffer = context.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, true); + this.opacityVertexBuffer = context.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, true); + // This is a performance hack so that we can write to opacityVertexArray with uint32s + // even though the shaders read uint8s + this.opacityVertexBuffer.itemSize = 1; + } + if (upload || update) { + this.programConfigurations.upload(context); + } + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + this.dynamicLayoutVertexBuffer.destroy(); + this.opacityVertexBuffer.destroy(); + } +} +register('SymbolBuffers', SymbolBuffers); +class CollisionBuffers { + constructor(LayoutArray, layoutAttributes, IndexArray) { + this.layoutVertexArray = new LayoutArray(); + this.layoutAttributes = layoutAttributes; + this.indexArray = new IndexArray(); + this.segments = new SegmentVector(); + this.collisionVertexArray = new CollisionVertexArray(); + } + upload(context) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + this.collisionVertexBuffer = context.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, true); + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.segments.destroy(); + this.collisionVertexBuffer.destroy(); + } +} +register('CollisionBuffers', CollisionBuffers); +/** + * @internal + * Unlike other buckets, which simply implement #addFeature with type-specific + * logic for (essentially) triangulating feature geometries, SymbolBucket + * requires specialized behavior: + * + * 1. WorkerTile#parse(), the logical owner of the bucket creation process, + * calls SymbolBucket#populate(), which resolves text and icon tokens on + * each feature, adds each glyphs and symbols needed to the passed-in + * collections options.glyphDependencies and options.iconDependencies, and + * stores the feature data for use in subsequent step (this.features). + * + * 2. WorkerTile asynchronously requests from the main thread all of the glyphs + * and icons needed (by this bucket and any others). When glyphs and icons + * have been received, the WorkerTile creates a CollisionIndex and invokes: + * + * 3. performSymbolLayout(bucket, stacks, icons) perform texts shaping and + * layout on a Symbol Bucket. This step populates: + * `this.symbolInstances`: metadata on generated symbols + * `this.collisionBoxArray`: collision data for use by foreground + * `this.text`: SymbolBuffers for text symbols + * `this.icons`: SymbolBuffers for icons + * `this.iconCollisionBox`: Debug SymbolBuffers for icon collision boxes + * `this.textCollisionBox`: Debug SymbolBuffers for text collision boxes + * The results are sent to the foreground for rendering + * + * 4. placement.ts is run on the foreground, + * and uses the CollisionIndex along with current camera settings to determine + * which symbols can actually show on the map. Collided symbols are hidden + * using a dynamic "OpacityVertexArray". + */ +class SymbolBucket { + constructor(options) { + this.collisionBoxArray = options.collisionBoxArray; + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.pixelRatio = options.pixelRatio; + this.sourceLayerIndex = options.sourceLayerIndex; + this.hasPattern = false; + this.hasRTLText = false; + this.sortKeyRanges = []; + this.collisionCircleArray = []; + this.placementInvProjMatrix = identity$2([]); + this.placementViewportMatrix = identity$2([]); + const layer = this.layers[0]; + const unevaluatedLayoutValues = layer._unevaluatedLayout._values; + this.textSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['text-size']); + this.iconSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['icon-size']); + const layout = this.layers[0].layout; + const sortKey = layout.get('symbol-sort-key'); + const zOrder = layout.get('symbol-z-order'); + this.canOverlap = + getOverlapMode(layout, 'text-overlap', 'text-allow-overlap') !== 'never' || + getOverlapMode(layout, 'icon-overlap', 'icon-allow-overlap') !== 'never' || + layout.get('text-ignore-placement') || + layout.get('icon-ignore-placement'); + this.sortFeaturesByKey = zOrder !== 'viewport-y' && !sortKey.isConstant(); + const zOrderByViewportY = zOrder === 'viewport-y' || (zOrder === 'auto' && !this.sortFeaturesByKey); + this.sortFeaturesByY = zOrderByViewportY && this.canOverlap; + if (layout.get('symbol-placement') === 'point') { + this.writingModes = layout.get('text-writing-mode').map(wm => exports.WritingMode[wm]); + } + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + this.sourceID = options.sourceID; + } + createArrays() { + this.text = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^text/.test(property))); + this.icon = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^icon/.test(property))); + this.glyphOffsetArray = new GlyphOffsetArray(); + this.lineVertexArray = new SymbolLineVertexArray(); + this.symbolInstances = new SymbolInstanceArray(); + this.textAnchorOffsets = new TextAnchorOffsetArray(); + } + calculateGlyphDependencies(text, stack, textAlongLine, allowVerticalPlacement, doesAllowVerticalWritingMode) { + for (let i = 0; i < text.length; i++) { + stack[text.charCodeAt(i)] = true; + if ((textAlongLine || allowVerticalPlacement) && doesAllowVerticalWritingMode) { + const verticalChar = verticalizedCharacterMap[text.charAt(i)]; + if (verticalChar) { + stack[verticalChar.charCodeAt(0)] = true; + } + } + } + } + populate(features, options, canonical) { + const layer = this.layers[0]; + const layout = layer.layout; + const textFont = layout.get('text-font'); + const textField = layout.get('text-field'); + const iconImage = layout.get('icon-image'); + const hasText = (textField.value.kind !== 'constant' || + (textField.value.value instanceof Formatted && !textField.value.value.isEmpty()) || + textField.value.value.toString().length > 0) && + (textFont.value.kind !== 'constant' || textFont.value.value.length > 0); + // we should always resolve the icon-image value if the property was defined in the style + // this allows us to fire the styleimagemissing event if image evaluation returns null + // the only way to distinguish between null returned from a coalesce statement with no valid images + // and null returned because icon-image wasn't defined is to check whether or not iconImage.parameters is an empty object + const hasIcon = iconImage.value.kind !== 'constant' || !!iconImage.value.value || Object.keys(iconImage.parameters).length > 0; + const symbolSortKey = layout.get('symbol-sort-key'); + this.features = []; + if (!hasText && !hasIcon) { + return; + } + const icons = options.iconDependencies; + const stacks = options.glyphDependencies; + const availableImages = options.availableImages; + const globalProperties = new EvaluationParameters(this.zoom); + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = layer._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) { + continue; + } + if (!needGeometry) + evaluationFeature.geometry = loadGeometry(feature); + let text; + if (hasText) { + // Expression evaluation will automatically coerce to Formatted + // but plain string token evaluation skips that pathway so do the + // conversion here. + const resolvedTokens = layer.getValueAndResolveTokens('text-field', evaluationFeature, canonical, availableImages); + const formattedText = Formatted.factory(resolvedTokens); + // on this instance: if hasRTLText is already true, all future calls to containsRTLText can be skipped. + const bucketHasRTLText = this.hasRTLText = (this.hasRTLText || containsRTLText(formattedText)); + if (!bucketHasRTLText || // non-rtl text so can proceed safely + rtlWorkerPlugin.getRTLTextPluginStatus() === 'unavailable' || // We don't intend to lazy-load the rtl text plugin, so proceed with incorrect shaping + bucketHasRTLText && rtlWorkerPlugin.isParsed() // Use the rtlText plugin to shape text + ) { + text = transformText(formattedText, layer, evaluationFeature); + } + } + let icon; + if (hasIcon) { + // Expression evaluation will automatically coerce to Image + // but plain string token evaluation skips that pathway so do the + // conversion here. + const resolvedTokens = layer.getValueAndResolveTokens('icon-image', evaluationFeature, canonical, availableImages); + if (resolvedTokens instanceof ResolvedImage) { + icon = resolvedTokens; + } + else { + icon = ResolvedImage.fromString(resolvedTokens); + } + } + if (!text && !icon) { + continue; + } + const sortKey = this.sortFeaturesByKey ? + symbolSortKey.evaluate(evaluationFeature, {}, canonical) : + undefined; + const symbolFeature = { + id, + text, + icon, + index, + sourceLayerIndex, + geometry: evaluationFeature.geometry, + properties: feature.properties, + type: vectorTileFeatureTypes[feature.type], + sortKey + }; + this.features.push(symbolFeature); + if (icon) { + icons[icon.name] = true; + } + if (text) { + const fontStack = textFont.evaluate(evaluationFeature, {}, canonical).join(','); + const textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point'; + this.allowVerticalPlacement = this.writingModes && this.writingModes.indexOf(exports.WritingMode.vertical) >= 0; + for (const section of text.sections) { + if (!section.image) { + const doesAllowVerticalWritingMode = allowsVerticalWritingMode(text.toString()); + const sectionFont = section.fontStack || fontStack; + const sectionStack = stacks[sectionFont] = stacks[sectionFont] || {}; + this.calculateGlyphDependencies(section.text, sectionStack, textAlongLine, this.allowVerticalPlacement, doesAllowVerticalWritingMode); + } + else { + // Add section image to the list of dependencies. + icons[section.image.name] = true; + } + } + } + } + if (layout.get('symbol-placement') === 'line') { + // Merge adjacent lines with the same text to improve labelling. + // It's better to place labels on one long line than on many short segments. + this.features = mergeLines(this.features); + } + if (this.sortFeaturesByKey) { + this.features.sort((a, b) => { + // a.sortKey is always a number when sortFeaturesByKey is true + return a.sortKey - b.sortKey; + }); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.text.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions); + this.icon.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions); + } + isEmpty() { + // When the bucket encounters only rtl-text but the plugin isn't loaded, no symbol instances will be created. + // In order for the bucket to be serialized, and not discarded as an empty bucket both checks are necessary. + return this.symbolInstances.length === 0 && !this.hasRTLText; + } + uploadPending() { + return !this.uploaded || this.text.programConfigurations.needsUpload || this.icon.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded && this.hasDebugData()) { + this.textCollisionBox.upload(context); + this.iconCollisionBox.upload(context); + } + this.text.upload(context, this.sortFeaturesByY, !this.uploaded, this.text.programConfigurations.needsUpload); + this.icon.upload(context, this.sortFeaturesByY, !this.uploaded, this.icon.programConfigurations.needsUpload); + this.uploaded = true; + } + destroyDebugData() { + this.textCollisionBox.destroy(); + this.iconCollisionBox.destroy(); + } + destroy() { + this.text.destroy(); + this.icon.destroy(); + if (this.hasDebugData()) { + this.destroyDebugData(); + } + } + addToLineVertexArray(anchor, line) { + const lineStartIndex = this.lineVertexArray.length; + if (anchor.segment !== undefined) { + let sumForwardLength = anchor.dist(line[anchor.segment + 1]); + let sumBackwardLength = anchor.dist(line[anchor.segment]); + const vertices = {}; + for (let i = anchor.segment + 1; i < line.length; i++) { + vertices[i] = { x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumForwardLength }; + if (i < line.length - 1) { + sumForwardLength += line[i + 1].dist(line[i]); + } + } + for (let i = anchor.segment || 0; i >= 0; i--) { + vertices[i] = { x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumBackwardLength }; + if (i > 0) { + sumBackwardLength += line[i - 1].dist(line[i]); + } + } + for (let i = 0; i < line.length; i++) { + const vertex = vertices[i]; + this.lineVertexArray.emplaceBack(vertex.x, vertex.y, vertex.tileUnitDistanceFromAnchor); + } + } + return { + lineStartIndex, + lineLength: this.lineVertexArray.length - lineStartIndex + }; + } + addSymbols(arrays, quads, sizeVertex, lineOffset, alongLine, feature, writingMode, labelAnchor, lineStartIndex, lineLength, associatedIconIndex, canonical) { + const indexArray = arrays.indexArray; + const layoutVertexArray = arrays.layoutVertexArray; + const segment = arrays.segments.prepareSegment(4 * quads.length, layoutVertexArray, indexArray, this.canOverlap ? feature.sortKey : undefined); + const glyphOffsetArrayStart = this.glyphOffsetArray.length; + const vertexStartIndex = segment.vertexLength; + const angle = (this.allowVerticalPlacement && writingMode === exports.WritingMode.vertical) ? Math.PI / 2 : 0; + const sections = feature.text && feature.text.sections; + for (let i = 0; i < quads.length; i++) { + const { tl, tr, bl, br, tex, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, glyphOffset, isSDF, sectionIndex } = quads[i]; + const index = segment.vertexLength; + const y = glyphOffset[1]; + addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY); + 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); + 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); + 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); + addDynamicAttributes(arrays.dynamicLayoutVertexArray, labelAnchor, angle); + indexArray.emplaceBack(index, index + 1, index + 2); + indexArray.emplaceBack(index + 1, index + 2, index + 3); + segment.vertexLength += 4; + segment.primitiveLength += 2; + this.glyphOffsetArray.emplaceBack(glyphOffset[0]); + if (i === quads.length - 1 || sectionIndex !== quads[i + 1].sectionIndex) { + arrays.programConfigurations.populatePaintArrays(layoutVertexArray.length, feature, feature.index, {}, canonical, sections && sections[sectionIndex]); + } + } + arrays.placedSymbolArray.emplaceBack(labelAnchor.x, labelAnchor.y, glyphOffsetArrayStart, this.glyphOffsetArray.length - glyphOffsetArrayStart, vertexStartIndex, lineStartIndex, lineLength, labelAnchor.segment, sizeVertex ? sizeVertex[0] : 0, sizeVertex ? sizeVertex[1] : 0, lineOffset[0], lineOffset[1], writingMode, + // placedOrientation is null initially; will be updated to horizontal(1)/vertical(2) if placed + 0, false, + // The crossTileID is only filled/used on the foreground for dynamic text anchors + 0, associatedIconIndex); + } + _addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, point, anchorX, anchorY, extrude) { + collisionVertexArray.emplaceBack(0, 0); + return layoutVertexArray.emplaceBack( + // pos + point.x, point.y, + // a_anchor_pos + anchorX, anchorY, + // extrude + Math.round(extrude.x), Math.round(extrude.y)); + } + addCollisionDebugVertices(x1, y1, x2, y2, arrays, boxAnchorPoint, symbolInstance) { + const segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray); + const index = segment.vertexLength; + const layoutVertexArray = arrays.layoutVertexArray; + const collisionVertexArray = arrays.collisionVertexArray; + const anchorX = symbolInstance.anchorX; + const anchorY = symbolInstance.anchorY; + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$2(x1, y1)); + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$2(x2, y1)); + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$2(x2, y2)); + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$2(x1, y2)); + segment.vertexLength += 4; + const indexArray = arrays.indexArray; + indexArray.emplaceBack(index, index + 1); + indexArray.emplaceBack(index + 1, index + 2); + indexArray.emplaceBack(index + 2, index + 3); + indexArray.emplaceBack(index + 3, index); + segment.primitiveLength += 4; + } + addDebugCollisionBoxes(startIndex, endIndex, symbolInstance, isText) { + for (let b = startIndex; b < endIndex; b++) { + const box = this.collisionBoxArray.get(b); + const x1 = box.x1; + const y1 = box.y1; + const x2 = box.x2; + const y2 = box.y2; + this.addCollisionDebugVertices(x1, y1, x2, y2, isText ? this.textCollisionBox : this.iconCollisionBox, box.anchorPoint, symbolInstance); + } + } + generateCollisionDebugBuffers() { + if (this.hasDebugData()) { + this.destroyDebugData(); + } + this.textCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray); + this.iconCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray); + for (let i = 0; i < this.symbolInstances.length; i++) { + const symbolInstance = this.symbolInstances.get(i); + this.addDebugCollisionBoxes(symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance, true); + this.addDebugCollisionBoxes(symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance, true); + this.addDebugCollisionBoxes(symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance, false); + this.addDebugCollisionBoxes(symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance, false); + } + } + // These flat arrays are meant to be quicker to iterate over than the source + // CollisionBoxArray + _deserializeCollisionBoxesForSymbol(collisionBoxArray, textStartIndex, textEndIndex, verticalTextStartIndex, verticalTextEndIndex, iconStartIndex, iconEndIndex, verticalIconStartIndex, verticalIconEndIndex) { + const collisionArrays = {}; + for (let k = textStartIndex; k < textEndIndex; k++) { + const box = collisionBoxArray.get(k); + collisionArrays.textBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.textFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + for (let k = verticalTextStartIndex; k < verticalTextEndIndex; k++) { + const box = collisionBoxArray.get(k); + collisionArrays.verticalTextBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.verticalTextFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + for (let k = iconStartIndex; k < iconEndIndex; k++) { + // An icon can only have one box now, so this indexing is a bit vestigial... + const box = collisionBoxArray.get(k); + collisionArrays.iconBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.iconFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + for (let k = verticalIconStartIndex; k < verticalIconEndIndex; k++) { + // An icon can only have one box now, so this indexing is a bit vestigial... + const box = collisionBoxArray.get(k); + collisionArrays.verticalIconBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.verticalIconFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + return collisionArrays; + } + deserializeCollisionBoxes(collisionBoxArray) { + this.collisionArrays = []; + for (let i = 0; i < this.symbolInstances.length; i++) { + const symbolInstance = this.symbolInstances.get(i); + this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(collisionBoxArray, symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex)); + } + } + hasTextData() { + return this.text.segments.get().length > 0; + } + hasIconData() { + return this.icon.segments.get().length > 0; + } + hasDebugData() { + return this.textCollisionBox && this.iconCollisionBox; + } + hasTextCollisionBoxData() { + return this.hasDebugData() && this.textCollisionBox.segments.get().length > 0; + } + hasIconCollisionBoxData() { + return this.hasDebugData() && this.iconCollisionBox.segments.get().length > 0; + } + addIndicesForPlacedSymbol(iconOrText, placedSymbolIndex) { + const placedSymbol = iconOrText.placedSymbolArray.get(placedSymbolIndex); + const endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4; + for (let vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) { + iconOrText.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2); + iconOrText.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3); + } + } + getSortedSymbolIndexes(angle) { + if (this.sortedAngle === angle && this.symbolInstanceIndexes !== undefined) { + return this.symbolInstanceIndexes; + } + const sin = Math.sin(angle); + const cos = Math.cos(angle); + const rotatedYs = []; + const featureIndexes = []; + const result = []; + for (let i = 0; i < this.symbolInstances.length; ++i) { + result.push(i); + const symbolInstance = this.symbolInstances.get(i); + rotatedYs.push(Math.round(sin * symbolInstance.anchorX + cos * symbolInstance.anchorY) | 0); + featureIndexes.push(symbolInstance.featureIndex); + } + result.sort((aIndex, bIndex) => { + return (rotatedYs[aIndex] - rotatedYs[bIndex]) || + (featureIndexes[bIndex] - featureIndexes[aIndex]); + }); + return result; + } + addToSortKeyRanges(symbolInstanceIndex, sortKey) { + const last = this.sortKeyRanges[this.sortKeyRanges.length - 1]; + if (last && last.sortKey === sortKey) { + last.symbolInstanceEnd = symbolInstanceIndex + 1; + } + else { + this.sortKeyRanges.push({ + sortKey, + symbolInstanceStart: symbolInstanceIndex, + symbolInstanceEnd: symbolInstanceIndex + 1 + }); + } + } + sortFeatures(angle) { + if (!this.sortFeaturesByY) + return; + if (this.sortedAngle === angle) + return; + // The current approach to sorting doesn't sort across segments so don't try. + // Sorting within segments separately seemed not to be worth the complexity. + if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1) + return; + // If the symbols are allowed to overlap sort them by their vertical screen position. + // The index array buffer is rewritten to reference the (unchanged) vertices in the + // sorted order. + // To avoid sorting the actual symbolInstance array we sort an array of indexes. + this.symbolInstanceIndexes = this.getSortedSymbolIndexes(angle); + this.sortedAngle = angle; + this.text.indexArray.clear(); + this.icon.indexArray.clear(); + this.featureSortOrder = []; + for (const i of this.symbolInstanceIndexes) { + const symbolInstance = this.symbolInstances.get(i); + this.featureSortOrder.push(symbolInstance.featureIndex); + [ + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.leftJustifiedTextSymbolIndex + ].forEach((index, i, array) => { + // Only add a given index the first time it shows up, + // to avoid duplicate opacity entries when multiple justifications + // share the same glyphs. + if (index >= 0 && array.indexOf(index) === i) { + this.addIndicesForPlacedSymbol(this.text, index); + } + }); + if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) { + this.addIndicesForPlacedSymbol(this.text, symbolInstance.verticalPlacedTextSymbolIndex); + } + if (symbolInstance.placedIconSymbolIndex >= 0) { + this.addIndicesForPlacedSymbol(this.icon, symbolInstance.placedIconSymbolIndex); + } + if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) { + this.addIndicesForPlacedSymbol(this.icon, symbolInstance.verticalPlacedIconSymbolIndex); + } + } + if (this.text.indexBuffer) + this.text.indexBuffer.updateData(this.text.indexArray); + if (this.icon.indexBuffer) + this.icon.indexBuffer.updateData(this.icon.indexArray); + } +} +register('SymbolBucket', SymbolBucket, { + omit: ['layers', 'collisionBoxArray', 'features', 'compareText'] +}); +// this constant is based on the size of StructArray indexes used in a symbol +// bucket--namely, glyphOffsetArrayStart +// eg the max valid UInt16 is 65,535 +// See https://github.com/mapbox/mapbox-gl-js/issues/2907 for motivation +// lineStartIndex and textBoxStartIndex could potentially be concerns +// but we expect there to be many fewer boxes/lines than glyphs +SymbolBucket.MAX_GLYPHS = 65535; +SymbolBucket.addDynamicAttributes = addDynamicAttributes; + +/** + * Replace tokens in a string template with values in an object + * + * @param properties - a key/value relationship between tokens and replacements + * @param text - the template string + * @returns the template with tokens replaced + */ +function resolveTokens(properties, text) { + return text.replace(/{([^{}]+)}/g, (match, key) => { + return properties && key in properties ? String(properties[key]) : ''; + }); +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout; +const getLayout = () => layout = layout || new Properties({ + "symbol-placement": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-placement"]), + "symbol-spacing": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-spacing"]), + "symbol-avoid-edges": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-avoid-edges"]), + "symbol-sort-key": new DataDrivenProperty(v8Spec["layout_symbol"]["symbol-sort-key"]), + "symbol-z-order": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-z-order"]), + "icon-allow-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["icon-allow-overlap"]), + "icon-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["icon-overlap"]), + "icon-ignore-placement": new DataConstantProperty(v8Spec["layout_symbol"]["icon-ignore-placement"]), + "icon-optional": new DataConstantProperty(v8Spec["layout_symbol"]["icon-optional"]), + "icon-rotation-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["icon-rotation-alignment"]), + "icon-size": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-size"]), + "icon-text-fit": new DataConstantProperty(v8Spec["layout_symbol"]["icon-text-fit"]), + "icon-text-fit-padding": new DataConstantProperty(v8Spec["layout_symbol"]["icon-text-fit-padding"]), + "icon-image": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-image"]), + "icon-rotate": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-rotate"]), + "icon-padding": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-padding"]), + "icon-keep-upright": new DataConstantProperty(v8Spec["layout_symbol"]["icon-keep-upright"]), + "icon-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-offset"]), + "icon-anchor": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-anchor"]), + "icon-pitch-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["icon-pitch-alignment"]), + "text-pitch-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["text-pitch-alignment"]), + "text-rotation-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["text-rotation-alignment"]), + "text-field": new DataDrivenProperty(v8Spec["layout_symbol"]["text-field"]), + "text-font": new DataDrivenProperty(v8Spec["layout_symbol"]["text-font"]), + "text-size": new DataDrivenProperty(v8Spec["layout_symbol"]["text-size"]), + "text-max-width": new DataDrivenProperty(v8Spec["layout_symbol"]["text-max-width"]), + "text-line-height": new DataConstantProperty(v8Spec["layout_symbol"]["text-line-height"]), + "text-letter-spacing": new DataDrivenProperty(v8Spec["layout_symbol"]["text-letter-spacing"]), + "text-justify": new DataDrivenProperty(v8Spec["layout_symbol"]["text-justify"]), + "text-radial-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["text-radial-offset"]), + "text-variable-anchor": new DataConstantProperty(v8Spec["layout_symbol"]["text-variable-anchor"]), + "text-variable-anchor-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["text-variable-anchor-offset"]), + "text-anchor": new DataDrivenProperty(v8Spec["layout_symbol"]["text-anchor"]), + "text-max-angle": new DataConstantProperty(v8Spec["layout_symbol"]["text-max-angle"]), + "text-writing-mode": new DataConstantProperty(v8Spec["layout_symbol"]["text-writing-mode"]), + "text-rotate": new DataDrivenProperty(v8Spec["layout_symbol"]["text-rotate"]), + "text-padding": new DataConstantProperty(v8Spec["layout_symbol"]["text-padding"]), + "text-keep-upright": new DataConstantProperty(v8Spec["layout_symbol"]["text-keep-upright"]), + "text-transform": new DataDrivenProperty(v8Spec["layout_symbol"]["text-transform"]), + "text-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["text-offset"]), + "text-allow-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["text-allow-overlap"]), + "text-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["text-overlap"]), + "text-ignore-placement": new DataConstantProperty(v8Spec["layout_symbol"]["text-ignore-placement"]), + "text-optional": new DataConstantProperty(v8Spec["layout_symbol"]["text-optional"]), +}); +let paint$2; +const getPaint$2 = () => paint$2 = paint$2 || new Properties({ + "icon-opacity": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-opacity"]), + "icon-color": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-color"]), + "icon-halo-color": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-color"]), + "icon-halo-width": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-width"]), + "icon-halo-blur": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-blur"]), + "icon-translate": new DataConstantProperty(v8Spec["paint_symbol"]["icon-translate"]), + "icon-translate-anchor": new DataConstantProperty(v8Spec["paint_symbol"]["icon-translate-anchor"]), + "text-opacity": new DataDrivenProperty(v8Spec["paint_symbol"]["text-opacity"]), + "text-color": new DataDrivenProperty(v8Spec["paint_symbol"]["text-color"], { runtimeType: ColorType, getOverride: (o) => o.textColor, hasOverride: (o) => !!o.textColor }), + "text-halo-color": new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-color"]), + "text-halo-width": new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-width"]), + "text-halo-blur": new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-blur"]), + "text-translate": new DataConstantProperty(v8Spec["paint_symbol"]["text-translate"]), + "text-translate-anchor": new DataConstantProperty(v8Spec["paint_symbol"]["text-translate-anchor"]), +}); +var properties$2 = ({ get paint() { return getPaint$2(); }, get layout() { return getLayout(); } }); + +// This is an internal expression class. It is only used in GL JS and +// has GL JS dependencies which can break the standalone style-spec module +class FormatSectionOverride { + constructor(defaultValue) { + if (defaultValue.property.overrides === undefined) + throw new Error('overrides must be provided to instantiate FormatSectionOverride class'); + this.type = defaultValue.property.overrides ? defaultValue.property.overrides.runtimeType : NullType; + this.defaultValue = defaultValue; + } + evaluate(ctx) { + if (ctx.formattedSection) { + const overrides = this.defaultValue.property.overrides; + if (overrides && overrides.hasOverride(ctx.formattedSection)) { + return overrides.getOverride(ctx.formattedSection); + } + } + if (ctx.feature && ctx.featureState) { + return this.defaultValue.evaluate(ctx.feature, ctx.featureState); + } + return this.defaultValue.property.specification.default; + } + eachChild(fn) { + if (!this.defaultValue.isConstant()) { + const expr = this.defaultValue.value; + fn(expr._styleExpression.expression); + } + } + // Cannot be statically evaluated, as the output depends on the evaluation context. + outputDefined() { + return false; + } + serialize() { + return null; + } +} +register('FormatSectionOverride', FormatSectionOverride, { omit: ['defaultValue'] }); + +class SymbolStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$2); + } + recalculate(parameters, availableImages) { + super.recalculate(parameters, availableImages); + if (this.layout.get('icon-rotation-alignment') === 'auto') { + if (this.layout.get('symbol-placement') !== 'point') { + this.layout._values['icon-rotation-alignment'] = 'map'; + } + else { + this.layout._values['icon-rotation-alignment'] = 'viewport'; + } + } + if (this.layout.get('text-rotation-alignment') === 'auto') { + if (this.layout.get('symbol-placement') !== 'point') { + this.layout._values['text-rotation-alignment'] = 'map'; + } + else { + this.layout._values['text-rotation-alignment'] = 'viewport'; + } + } + // If unspecified, `*-pitch-alignment` inherits `*-rotation-alignment` + if (this.layout.get('text-pitch-alignment') === 'auto') { + this.layout._values['text-pitch-alignment'] = this.layout.get('text-rotation-alignment') === 'map' ? 'map' : 'viewport'; + } + if (this.layout.get('icon-pitch-alignment') === 'auto') { + this.layout._values['icon-pitch-alignment'] = this.layout.get('icon-rotation-alignment'); + } + if (this.layout.get('symbol-placement') === 'point') { + const writingModes = this.layout.get('text-writing-mode'); + if (writingModes) { + // remove duplicates, preserving order + const deduped = []; + for (const m of writingModes) { + if (deduped.indexOf(m) < 0) + deduped.push(m); + } + this.layout._values['text-writing-mode'] = deduped; + } + else { + this.layout._values['text-writing-mode'] = ['horizontal']; + } + } + this._setPaintOverrides(); + } + getValueAndResolveTokens(name, feature, canonical, availableImages) { + const value = this.layout.get(name).evaluate(feature, {}, canonical, availableImages); + const unevaluated = this._unevaluatedLayout._values[name]; + if (!unevaluated.isDataDriven() && !isExpression(unevaluated.value) && value) { + return resolveTokens(feature.properties, value); + } + return value; + } + createBucket(parameters) { + return new SymbolBucket(parameters); + } + queryRadius() { + return 0; + } + queryIntersectsFeature() { + throw new Error('Should take a different path in FeatureIndex'); + } + _setPaintOverrides() { + for (const overridable of properties$2.paint.overridableProperties) { + if (!SymbolStyleLayer.hasPaintOverride(this.layout, overridable)) { + continue; + } + const overridden = this.paint.get(overridable); + const override = new FormatSectionOverride(overridden); + const styleExpression = new StyleExpression(override, overridden.property.specification); + let expression = null; + if (overridden.value.kind === 'constant' || overridden.value.kind === 'source') { + expression = new ZoomConstantExpression('source', styleExpression); + } + else { + expression = new ZoomDependentExpression('composite', styleExpression, overridden.value.zoomStops); + } + this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overridden.property, expression, overridden.parameters); + } + } + _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) { + if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) { + return false; + } + return SymbolStyleLayer.hasPaintOverride(this.layout, name); + } + static hasPaintOverride(layout, propertyName) { + const textField = layout.get('text-field'); + const property = properties$2.paint.properties[propertyName]; + let hasOverrides = false; + const checkSections = (sections) => { + for (const section of sections) { + if (property.overrides && property.overrides.hasOverride(section)) { + hasOverrides = true; + return; + } + } + }; + if (textField.value.kind === 'constant' && textField.value.value instanceof Formatted) { + checkSections(textField.value.value.sections); + } + else if (textField.value.kind === 'source') { + const checkExpression = (expression) => { + if (hasOverrides) + return; + if (expression instanceof Literal && typeOf(expression.value) === FormattedType) { + const formatted = expression.value; + checkSections(formatted.sections); + } + else if (expression instanceof FormatExpression) { + checkSections(expression.sections); + } + else { + expression.eachChild(checkExpression); + } + }; + const expr = textField.value; + if (expr._styleExpression) { + checkExpression(expr._styleExpression.expression); + } + } + return hasOverrides; + } +} +function getIconPadding(layout, feature, canonical, pixelRatio = 1) { + // Support text-padding in addition to icon-padding? Unclear how to apply asymmetric text-padding to the radius for collision circles. + const result = layout.get('icon-padding').evaluate(feature, {}, canonical); + const values = result && result.values; + return [ + values[0] * pixelRatio, + values[1] * pixelRatio, + values[2] * pixelRatio, + values[3] * pixelRatio, + ]; +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$1; +const getPaint$1 = () => paint$1 = paint$1 || new Properties({ + "background-color": new DataConstantProperty(v8Spec["paint_background"]["background-color"]), + "background-pattern": new CrossFadedProperty(v8Spec["paint_background"]["background-pattern"]), + "background-opacity": new DataConstantProperty(v8Spec["paint_background"]["background-opacity"]), +}); +var properties$1 = ({ get paint() { return getPaint$1(); } }); + +class BackgroundStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$1); + } +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint; +const getPaint = () => paint = paint || new Properties({ + "raster-opacity": new DataConstantProperty(v8Spec["paint_raster"]["raster-opacity"]), + "raster-hue-rotate": new DataConstantProperty(v8Spec["paint_raster"]["raster-hue-rotate"]), + "raster-brightness-min": new DataConstantProperty(v8Spec["paint_raster"]["raster-brightness-min"]), + "raster-brightness-max": new DataConstantProperty(v8Spec["paint_raster"]["raster-brightness-max"]), + "raster-saturation": new DataConstantProperty(v8Spec["paint_raster"]["raster-saturation"]), + "raster-contrast": new DataConstantProperty(v8Spec["paint_raster"]["raster-contrast"]), + "raster-resampling": new DataConstantProperty(v8Spec["paint_raster"]["raster-resampling"]), + "raster-fade-duration": new DataConstantProperty(v8Spec["paint_raster"]["raster-fade-duration"]), +}); +var properties = ({ get paint() { return getPaint(); } }); + +class RasterStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties); + } +} + +function validateCustomStyleLayer(layerObject) { + const errors = []; + const id = layerObject.id; + if (id === undefined) { + errors.push({ + message: `layers.${id}: missing required property "id"` + }); + } + if (layerObject.render === undefined) { + errors.push({ + message: `layers.${id}: missing required method "render"` + }); + } + if (layerObject.renderingMode && + layerObject.renderingMode !== '2d' && + layerObject.renderingMode !== '3d') { + errors.push({ + message: `layers.${id}: property "renderingMode" must be either "2d" or "3d"` + }); + } + return errors; +} +class CustomStyleLayer extends StyleLayer { + constructor(implementation) { + super(implementation, {}); + this.onAdd = (map) => { + if (this.implementation.onAdd) { + this.implementation.onAdd(map, map.painter.context.gl); + } + }; + this.onRemove = (map) => { + if (this.implementation.onRemove) { + this.implementation.onRemove(map, map.painter.context.gl); + } + }; + this.implementation = implementation; + } + is3D() { + return this.implementation.renderingMode === '3d'; + } + hasOffscreenPass() { + return this.implementation.prerender !== undefined; + } + recalculate() { } + updateTransitions() { } + hasTransition() { return false; } + serialize() { + throw new Error('Custom layers cannot be serialized'); + } +} + +function createStyleLayer(layer) { + if (layer.type === 'custom') { + return new CustomStyleLayer(layer); + } + switch (layer.type) { + case 'background': + return new BackgroundStyleLayer(layer); + case 'circle': + return new CircleStyleLayer(layer); + case 'fill': + return new FillStyleLayer(layer); + case 'fill-extrusion': + return new FillExtrusionStyleLayer(layer); + case 'heatmap': + return new HeatmapStyleLayer(layer); + case 'hillshade': + return new HillshadeStyleLayer(layer); + case 'line': + return new LineStyleLayer(layer); + case 'raster': + return new RasterStyleLayer(layer); + case 'symbol': + return new SymbolStyleLayer(layer); + } +} + +/** + * Invokes the wrapped function in a non-blocking way when trigger() is called. + * Invocation requests are ignored until the function was actually invoked. + */ +class ThrottledInvoker { + constructor(methodToThrottle) { + this._methodToThrottle = methodToThrottle; + this._triggered = false; + if (typeof MessageChannel !== 'undefined') { + this._channel = new MessageChannel(); + this._channel.port2.onmessage = () => { + this._triggered = false; + this._methodToThrottle(); + }; + } + } + trigger() { + if (this._triggered) { + return; + } + this._triggered = true; + if (this._channel) { + this._channel.port1.postMessage(true); + } + else { + setTimeout(() => { + this._triggered = false; + this._methodToThrottle(); + }, 0); + } + } + remove() { + delete this._channel; + this._methodToThrottle = () => { }; + } +} + +/** + * An implementation of the [Actor design pattern](https://en.wikipedia.org/wiki/Actor_model) + * that maintains the relationship between asynchronous tasks and the objects + * that spin them off - in this case, tasks like parsing parts of styles, + * owned by the styles + */ +class Actor { + /** + * @param target - The target + * @param mapId - A unique identifier for the Map instance using this Actor. + */ + constructor(target, mapId) { + this.target = target; + this.mapId = mapId; + this.resolveRejects = {}; + this.tasks = {}; + this.taskQueue = []; + this.abortControllers = {}; + this.messageHandlers = {}; + this.invoker = new ThrottledInvoker(() => this.process()); + this.subscription = subscribe(this.target, 'message', (message) => this.receive(message), false); + this.globalScope = isWorker(self) ? target : window; + } + registerMessageHandler(type, handler) { + this.messageHandlers[type] = handler; + } + /** + * Sends a message from a main-thread map to a Worker or from a Worker back to + * a main-thread map instance. + * @param message - the message to send + * @param abortController - an optional AbortController to abort the request + * @returns a promise that will be resolved with the response data + */ + sendAsync(message, abortController) { + return new Promise((resolve, reject) => { + // We're using a string ID instead of numbers because they are being used as object keys + // anyway, and thus stringified implicitly. We use random IDs because an actor may receive + // message from multiple other actors which could run in different execution context. A + // linearly increasing ID could produce collisions. + const id = Math.round((Math.random() * 1e18)).toString(36).substring(0, 10); + this.resolveRejects[id] = { + resolve, + reject + }; + if (abortController) { + abortController.signal.addEventListener('abort', () => { + delete this.resolveRejects[id]; + const cancelMessage = { + id, + type: '', + origin: location.origin, + targetMapId: message.targetMapId, + sourceMapId: this.mapId + }; + this.target.postMessage(cancelMessage); + // In case of abort the current behavior is to keep the promise pending. + }, { once: true }); + } + const buffers = []; + const messageToPost = Object.assign(Object.assign({}, message), { id, sourceMapId: this.mapId, origin: location.origin, data: serialize(message.data, buffers) }); + this.target.postMessage(messageToPost, { transfer: buffers }); + }); + } + receive(message) { + const data = message.data; + const id = data.id; + if (data.origin !== 'file://' && location.origin !== 'file://' && data.origin !== 'resource://android' && location.origin !== 'resource://android' && data.origin !== location.origin) { + return; + } + if (data.targetMapId && this.mapId !== data.targetMapId) { + return; + } + if (data.type === '') { + // Remove the original request from the queue. This is only possible if it + // hasn't been kicked off yet. The id will remain in the queue, but because + // there is no associated task, it will be dropped once it's time to execute it. + delete this.tasks[id]; + const abortController = this.abortControllers[id]; + delete this.abortControllers[id]; + if (abortController) { + abortController.abort(); + } + return; + } + if (isWorker(self) || data.mustQueue) { + // In workers, store the tasks that we need to process before actually processing them. This + // is necessary because we want to keep receiving messages, and in particular, + // messages. Some tasks may take a while in the worker thread, so before + // executing the next task in our queue, postMessage preempts this and + // messages can be processed. We're using a MessageChannel object to get throttle the + // process() flow to one at a time. + this.tasks[id] = data; + this.taskQueue.push(id); + this.invoker.trigger(); + return; + } + // In the main thread, process messages immediately so that other work does not slip in + // between getting partial data back from workers. + this.processTask(id, data); + } + process() { + if (this.taskQueue.length === 0) { + return; + } + const id = this.taskQueue.shift(); + const task = this.tasks[id]; + delete this.tasks[id]; + // Schedule another process call if we know there's more to process _before_ invoking the + // current task. This is necessary so that processing continues even if the current task + // doesn't execute successfully. + if (this.taskQueue.length > 0) { + this.invoker.trigger(); + } + if (!task) { + // If the task ID doesn't have associated task data anymore, it was canceled. + return; + } + this.processTask(id, task); + } + processTask(id, task) { + return __awaiter(this, void 0, void 0, function* () { + if (task.type === '') { + // The `completeTask` function in the counterpart actor has been called, and we are now + // resolving or rejecting the promise in the originating actor, if there is one. + const resolveReject = this.resolveRejects[id]; + delete this.resolveRejects[id]; + if (!resolveReject) { + // If we get a response, but don't have a resolve or reject, the request was canceled. + return; + } + if (task.error) { + resolveReject.reject(deserialize(task.error)); + } + else { + resolveReject.resolve(deserialize(task.data)); + } + return; + } + if (!this.messageHandlers[task.type]) { + this.completeTask(id, new Error(`Could not find a registered handler for ${task.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(', ')}`)); + return; + } + const params = deserialize(task.data); + const abortController = new AbortController(); + this.abortControllers[id] = abortController; + try { + const data = yield this.messageHandlers[task.type](task.sourceMapId, params, abortController); + this.completeTask(id, null, data); + } + catch (err) { + this.completeTask(id, err); + } + }); + } + completeTask(id, err, data) { + const buffers = []; + delete this.abortControllers[id]; + const responseMessage = { + id, + type: '', + sourceMapId: this.mapId, + origin: location.origin, + error: err ? serialize(err) : null, + data: serialize(data, buffers) + }; + this.target.postMessage(responseMessage, { transfer: buffers }); + } + remove() { + this.invoker.remove(); + this.subscription.unsubscribe(); + } +} + +/* +* Approximate radius of the earth in meters. +* 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 +* 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 +*/ +const earthRadius = 6371008.8; +/** + * A `LngLat` object represents a given longitude and latitude coordinate, measured in degrees. + * These coordinates are based on the [WGS84 (EPSG:4326) standard](https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84). + * + * MapLibre GL JS uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match the + * [GeoJSON specification](https://tools.ietf.org/html/rfc7946). + * + * Note that any MapLibre GL JS method that accepts a `LngLat` object as an argument or option + * can also accept an `Array` of two numbers and will perform an implicit conversion. + * This flexible type is documented as {@link LngLatLike}. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let ll = new LngLat(-123.9749, 40.7736); + * ll.lng; // = -123.9749 + * ``` + * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/) + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Create a timeline animation](https://maplibre.org/maplibre-gl-js/docs/examples/timeline-animation/) + */ +class LngLat { + /** + * @param lng - Longitude, measured in degrees. + * @param lat - Latitude, measured in degrees. + */ + constructor(lng, lat) { + if (isNaN(lng) || isNaN(lat)) { + throw new Error(`Invalid LngLat object: (${lng}, ${lat})`); + } + this.lng = +lng; + this.lat = +lat; + if (this.lat > 90 || this.lat < -90) { + throw new Error('Invalid LngLat latitude value: must be between -90 and 90'); + } + } + /** + * Returns a new `LngLat` object whose longitude is wrapped to the range (-180, 180). + * + * @returns The wrapped `LngLat` object. + * @example + * ```ts + * let ll = new LngLat(286.0251, 40.7736); + * let wrapped = ll.wrap(); + * wrapped.lng; // = -73.9749 + * ``` + */ + wrap() { + return new LngLat(wrap(this.lng, -180, 180), this.lat); + } + /** + * Returns the coordinates represented as an array of two numbers. + * + * @returns The coordinates represented as an array of longitude and latitude. + * @example + * ```ts + * let ll = new LngLat(-73.9749, 40.7736); + * ll.toArray(); // = [-73.9749, 40.7736] + * ``` + */ + toArray() { + return [this.lng, this.lat]; + } + /** + * Returns the coordinates represent as a string. + * + * @returns The coordinates represented as a string of the format `'LngLat(lng, lat)'`. + * @example + * ```ts + * let ll = new LngLat(-73.9749, 40.7736); + * ll.toString(); // = "LngLat(-73.9749, 40.7736)" + * ``` + */ + toString() { + return `LngLat(${this.lng}, ${this.lat})`; + } + /** + * Returns the approximate distance between a pair of coordinates in meters + * Uses the Haversine Formula (from R.W. Sinnott, "Virtues of the Haversine", Sky and Telescope, vol. 68, no. 2, 1984, p. 159) + * + * @param lngLat - coordinates to compute the distance to + * @returns Distance in meters between the two coordinates. + * @example + * ```ts + * let new_york = new LngLat(-74.0060, 40.7128); + * let los_angeles = new LngLat(-118.2437, 34.0522); + * new_york.distanceTo(los_angeles); // = 3935751.690893987, "true distance" using a non-spherical approximation is ~3966km + * ``` + */ + distanceTo(lngLat) { + const rad = Math.PI / 180; + const lat1 = this.lat * rad; + const lat2 = lngLat.lat * rad; + const a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((lngLat.lng - this.lng) * rad); + const maxMeters = earthRadius * Math.acos(Math.min(a, 1)); + return maxMeters; + } + /** + * Converts an array of two numbers or an object with `lng` and `lat` or `lon` and `lat` properties + * to a `LngLat` object. + * + * If a `LngLat` object is passed in, the function returns it unchanged. + * + * @param input - An array of two numbers or object to convert, or a `LngLat` object to return. + * @returns A new `LngLat` object, if a conversion occurred, or the original `LngLat` object. + * @example + * ```ts + * let arr = [-73.9749, 40.7736]; + * let ll = LngLat.convert(arr); + * ll; // = LngLat {lng: -73.9749, lat: 40.7736} + * ``` + */ + static convert(input) { + if (input instanceof LngLat) { + return input; + } + if (Array.isArray(input) && (input.length === 2 || input.length === 3)) { + return new LngLat(Number(input[0]), Number(input[1])); + } + if (!Array.isArray(input) && typeof input === 'object' && input !== null) { + return new LngLat( + // flow can't refine this to have one of lng or lat, so we have to cast to any + Number('lng' in input ? input.lng : input.lon), Number(input.lat)); + } + throw new Error('`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]'); + } +} + +/* + * The average circumference of the world in meters. + */ +const earthCircumference = 2 * Math.PI * earthRadius; // meters +/* + * The circumference at a line of latitude in meters. + */ +function circumferenceAtLatitude(latitude) { + return earthCircumference * Math.cos(latitude * Math.PI / 180); +} +function mercatorXfromLng(lng) { + return (180 + lng) / 360; +} +function mercatorYfromLat(lat) { + return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360; +} +function mercatorZfromAltitude(altitude, lat) { + return altitude / circumferenceAtLatitude(lat); +} +function lngFromMercatorX(x) { + return x * 360 - 180; +} +function latFromMercatorY(y) { + const y2 = 180 - y * 360; + return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90; +} +function altitudeFromMercatorZ(z, y) { + return z * circumferenceAtLatitude(latFromMercatorY(y)); +} +/** + * Determine the Mercator scale factor for a given latitude, see + * https://en.wikipedia.org/wiki/Mercator_projection#Scale_factor + * + * At the equator the scale factor will be 1, which increases at higher latitudes. + * + * @param lat - Latitude + * @returns scale factor + */ +function mercatorScale(lat) { + return 1 / Math.cos(lat * Math.PI / 180); +} +/** + * A `MercatorCoordinate` object represents a projected three dimensional position. + * + * `MercatorCoordinate` uses the web mercator projection ([EPSG:3857](https://epsg.io/3857)) with slightly different units: + * + * - the size of 1 unit is the width of the projected world instead of the "mercator meter" + * - the origin of the coordinate space is at the north-west corner instead of the middle + * + * For example, `MercatorCoordinate(0, 0, 0)` is the north-west corner of the mercator world and + * `MercatorCoordinate(1, 1, 0)` is the south-east corner. If you are familiar with + * [vector tiles](https://github.com/mapbox/vector-tile-spec) it may be helpful to think + * of the coordinate space as the `0/0/0` tile with an extent of `1`. + * + * The `z` dimension of `MercatorCoordinate` is conformal. A cube in the mercator coordinate space would be rendered as a cube. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let nullIsland = new MercatorCoordinate(0.5, 0.5, 0); + * ``` + * @see [Add a custom style layer](https://maplibre.org/maplibre-gl-js/docs/examples/custom-style-layer/) + */ +class MercatorCoordinate { + /** + * @param x - The x component of the position. + * @param y - The y component of the position. + * @param z - The z component of the position. + */ + constructor(x, y, z = 0) { + this.x = +x; + this.y = +y; + this.z = +z; + } + /** + * Project a `LngLat` to a `MercatorCoordinate`. + * + * @param lngLatLike - The location to project. + * @param altitude - The altitude in meters of the position. + * @returns The projected mercator coordinate. + * @example + * ```ts + * let coord = MercatorCoordinate.fromLngLat({ lng: 0, lat: 0}, 0); + * coord; // MercatorCoordinate(0.5, 0.5, 0) + * ``` + */ + static fromLngLat(lngLatLike, altitude = 0) { + const lngLat = LngLat.convert(lngLatLike); + return new MercatorCoordinate(mercatorXfromLng(lngLat.lng), mercatorYfromLat(lngLat.lat), mercatorZfromAltitude(altitude, lngLat.lat)); + } + /** + * Returns the `LngLat` for the coordinate. + * + * @returns The `LngLat` object. + * @example + * ```ts + * let coord = new MercatorCoordinate(0.5, 0.5, 0); + * let lngLat = coord.toLngLat(); // LngLat(0, 0) + * ``` + */ + toLngLat() { + return new LngLat(lngFromMercatorX(this.x), latFromMercatorY(this.y)); + } + /** + * Returns the altitude in meters of the coordinate. + * + * @returns The altitude in meters. + * @example + * ```ts + * let coord = new MercatorCoordinate(0, 0, 0.02); + * coord.toAltitude(); // 6914.281956295339 + * ``` + */ + toAltitude() { + return altitudeFromMercatorZ(this.z, this.y); + } + /** + * Returns the distance of 1 meter in `MercatorCoordinate` units at this latitude. + * + * For coordinates in real world units using meters, this naturally provides the scale + * to transform into `MercatorCoordinate`s. + * + * @returns Distance of 1 meter in `MercatorCoordinate` units. + */ + meterInMercatorCoordinateUnits() { + // 1 meter / circumference at equator in meters * Mercator projection scale factor at this latitude + return 1 / earthCircumference * mercatorScale(latFromMercatorY(this.y)); + } +} + +/** + * getURL + * + * @param {String} baseUrl Base url of the WMS server + * @param {String} layer Layer name + * @param {Number} x Tile coordinate x + * @param {Number} y Tile coordinate y + * @param {Number} z Tile zoom + * @param {Object} [options] + * @param {String} [options.format='image/png'] + * @param {String} [options.service='WMS'] + * @param {String} [options.version='1.1.1'] + * @param {String} [options.request='GetMap'] + * @param {String} [options.srs='EPSG:3857'] + * @param {Number} [options.width='256'] + * @param {Number} [options.height='256'] + * @returns {String} url + * @example + * var baseUrl = 'http://geodata.state.nj.us/imagerywms/Natural2015'; + * var layer = 'Natural2015'; + * var url = whoots.getURL(baseUrl, layer, 154308, 197167, 19); + */ +function getURL(baseUrl, layer, x, y, z, options) { + options = options || {}; + + var url = baseUrl + '?' + [ + 'bbox=' + getTileBBox(x, y, z), + 'format=' + (options.format || 'image/png'), + 'service=' + (options.service || 'WMS'), + 'version=' + (options.version || '1.1.1'), + 'request=' + (options.request || 'GetMap'), + 'srs=' + (options.srs || 'EPSG:3857'), + 'width=' + (options.width || 256), + 'height=' + (options.height || 256), + 'layers=' + layer + ].join('&'); + + return url; +} + + +/** + * getTileBBox + * + * @param {Number} x Tile coordinate x + * @param {Number} y Tile coordinate y + * @param {Number} z Tile zoom + * @returns {String} String of the bounding box + */ +function getTileBBox(x, y, z) { + // for Google/OSM tile scheme we need to alter the y + y = (Math.pow(2, z) - y - 1); + + var min = getMercCoords(x * 256, y * 256, z), + max = getMercCoords((x + 1) * 256, (y + 1) * 256, z); + + return min[0] + ',' + min[1] + ',' + max[0] + ',' + max[1]; +} + + +/** + * getMercCoords + * + * @param {Number} x Pixel coordinate x + * @param {Number} y Pixel coordinate y + * @param {Number} z Tile zoom + * @returns {Array} [x, y] + */ +function getMercCoords(x, y, z) { + var resolution = (2 * Math.PI * 6378137 / 256) / Math.pow(2, z), + merc_x = (x * resolution - 2 * Math.PI * 6378137 / 2.0), + merc_y = (y * resolution - 2 * Math.PI * 6378137 / 2.0); + + return [merc_x, merc_y]; +} + +/** + * Returns true if a given tile zoom (Z), X, and Y are in the bounds of the world. + * Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive). + * X and Y bounds are 0 (inclusive) to their respective zoom-dependent maxima (exclusive). + * + * @param zoom - the tile zoom (Z) + * @param x - the tile X + * @param y - the tile Y + * @returns `true` if a given tile zoom, X, and Y are in the bounds of the world. + */ +function isInBoundsForTileZoomXY(zoom, x, y) { + return !(zoom < MIN_TILE_ZOOM || + zoom > MAX_TILE_ZOOM || + y < 0 || + y >= Math.pow(2, zoom) || + x < 0 || + x >= Math.pow(2, zoom)); +} +/** + * Returns true if a given zoom and `LngLat` are in the bounds of the world. + * Does not wrap `LngLat` when checking if in bounds. + * Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive). + * `LngLat` bounds are the mercator world's north-west corner (inclusive) to its south-east corner (exclusive). + * + * @param zoom - the tile zoom (Z) + * @param LngLat - the `LngLat` object containing the longitude and latitude + * @returns `true` if a given zoom and `LngLat` are in the bounds of the world. + */ +function isInBoundsForZoomLngLat(zoom, lnglat) { + const { x, y } = MercatorCoordinate.fromLngLat(lnglat); + return !(zoom < MIN_TILE_ZOOM || + zoom > MAX_TILE_ZOOM || + y < 0 || + y >= 1 || + x < 0 || + x >= 1); +} + +/** + * A canonical way to define a tile ID + */ +class CanonicalTileID { + constructor(z, x, y) { + if (!isInBoundsForTileZoomXY(z, x, y)) { + throw new Error(`x=${x}, y=${y}, z=${z} outside of bounds. 0<=x<${Math.pow(2, z)}, 0<=y<${Math.pow(2, z)} ${MIN_TILE_ZOOM}<=z<=${MAX_TILE_ZOOM} `); + } + this.z = z; + this.x = x; + this.y = y; + this.key = calculateKey(0, z, z, x, y); + } + equals(id) { + return this.z === id.z && this.x === id.x && this.y === id.y; + } + // given a list of urls, choose a url template and return a tile URL + url(urls, pixelRatio, scheme) { + const bbox = getTileBBox(this.x, this.y, this.z); + const quadkey = getQuadkey(this.z, this.x, this.y); + return urls[(this.x + this.y) % urls.length] + .replace(/{prefix}/g, (this.x % 16).toString(16) + (this.y % 16).toString(16)) + .replace(/{z}/g, String(this.z)) + .replace(/{x}/g, String(this.x)) + .replace(/{y}/g, String(scheme === 'tms' ? (Math.pow(2, this.z) - this.y - 1) : this.y)) + .replace(/{ratio}/g, pixelRatio > 1 ? '@2x' : '') + .replace(/{quadkey}/g, quadkey) + .replace(/{bbox-epsg-3857}/g, bbox); + } + isChildOf(parent) { + const dz = this.z - parent.z; + return dz > 0 && parent.x === (this.x >> dz) && parent.y === (this.y >> dz); + } + getTilePoint(coord) { + const tilesAtZoom = Math.pow(2, this.z); + return new Point$2((coord.x * tilesAtZoom - this.x) * EXTENT, (coord.y * tilesAtZoom - this.y) * EXTENT); + } + toString() { + return `${this.z}/${this.x}/${this.y}`; + } +} +/** + * @internal + * An unwrapped tile identifier + */ +class UnwrappedTileID { + constructor(wrap, canonical) { + this.wrap = wrap; + this.canonical = canonical; + this.key = calculateKey(wrap, canonical.z, canonical.z, canonical.x, canonical.y); + } +} +/** + * An overscaled tile identifier + */ +class OverscaledTileID { + constructor(overscaledZ, wrap, z, x, y) { + if (overscaledZ < z) + throw new Error(`overscaledZ should be >= z; overscaledZ = ${overscaledZ}; z = ${z}`); + this.overscaledZ = overscaledZ; + this.wrap = wrap; + this.canonical = new CanonicalTileID(z, +x, +y); + this.key = calculateKey(wrap, overscaledZ, z, x, y); + } + clone() { + return new OverscaledTileID(this.overscaledZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } + equals(id) { + return this.overscaledZ === id.overscaledZ && this.wrap === id.wrap && this.canonical.equals(id.canonical); + } + scaledTo(targetZ) { + if (targetZ > this.overscaledZ) + throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`); + const zDifference = this.canonical.z - targetZ; + if (targetZ > this.canonical.z) { + return new OverscaledTileID(targetZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } + else { + return new OverscaledTileID(targetZ, this.wrap, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference); + } + } + /* + * calculateScaledKey is an optimization: + * when withWrap == true, implements the same as this.scaledTo(z).key, + * when withWrap == false, implements the same as this.scaledTo(z).wrapped().key. + */ + calculateScaledKey(targetZ, withWrap) { + if (targetZ > this.overscaledZ) + throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`); + const zDifference = this.canonical.z - targetZ; + if (targetZ > this.canonical.z) { + return calculateKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y); + } + else { + return calculateKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference); + } + } + isChildOf(parent) { + if (parent.wrap !== this.wrap) { + // We can't be a child if we're in a different world copy + return false; + } + const zDifference = this.canonical.z - parent.canonical.z; + // We're first testing for z == 0, to avoid a 32 bit shift, which is undefined. + return parent.overscaledZ === 0 || (parent.overscaledZ < this.overscaledZ && + parent.canonical.x === (this.canonical.x >> zDifference) && + parent.canonical.y === (this.canonical.y >> zDifference)); + } + children(sourceMaxZoom) { + if (this.overscaledZ >= sourceMaxZoom) { + // return a single tile coord representing a an overscaled tile + return [new OverscaledTileID(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)]; + } + const z = this.canonical.z + 1; + const x = this.canonical.x * 2; + const y = this.canonical.y * 2; + return [ + new OverscaledTileID(z, this.wrap, z, x, y), + new OverscaledTileID(z, this.wrap, z, x + 1, y), + new OverscaledTileID(z, this.wrap, z, x, y + 1), + new OverscaledTileID(z, this.wrap, z, x + 1, y + 1) + ]; + } + isLessThan(rhs) { + if (this.wrap < rhs.wrap) + return true; + if (this.wrap > rhs.wrap) + return false; + if (this.overscaledZ < rhs.overscaledZ) + return true; + if (this.overscaledZ > rhs.overscaledZ) + return false; + if (this.canonical.x < rhs.canonical.x) + return true; + if (this.canonical.x > rhs.canonical.x) + return false; + if (this.canonical.y < rhs.canonical.y) + return true; + return false; + } + wrapped() { + return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y); + } + unwrapTo(wrap) { + return new OverscaledTileID(this.overscaledZ, wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } + overscaleFactor() { + return Math.pow(2, this.overscaledZ - this.canonical.z); + } + toUnwrapped() { + return new UnwrappedTileID(this.wrap, this.canonical); + } + toString() { + return `${this.overscaledZ}/${this.canonical.x}/${this.canonical.y}`; + } + getTilePoint(coord) { + return this.canonical.getTilePoint(new MercatorCoordinate(coord.x - this.wrap, coord.y)); + } +} +function calculateKey(wrap, overscaledZ, z, x, y) { + wrap *= 2; + if (wrap < 0) + wrap = wrap * -1 - 1; + const dim = 1 << z; + return (dim * dim * wrap + dim * y + x).toString(36) + z.toString(36) + overscaledZ.toString(36); +} +function getQuadkey(z, x, y) { + let quadkey = '', mask; + for (let i = z; i > 0; i--) { + mask = 1 << (i - 1); + quadkey += ((x & mask ? 1 : 0) + (y & mask ? 2 : 0)); + } + return quadkey; +} +register('CanonicalTileID', CanonicalTileID); +register('OverscaledTileID', OverscaledTileID, { omit: ['posMatrix'] }); + +/** + * DEMData is a data structure for decoding, backfilling, and storing elevation data for processing in the hillshade shaders + * data can be populated either from a pngraw image tile or from serialized data sent back from a worker. When data is initially + * loaded from a image tile, we decode the pixel values using the appropriate decoding formula, but we store the + * elevation data as an Int32 value. we add 65536 (2^16) to eliminate negative values and enable the use of + * integer overflow when creating the texture used in the hillshadePrepare step. + * + * DEMData also handles the backfilling of data from a tile's neighboring tiles. This is necessary because we use a pixel's 8 + * surrounding pixel values to compute the slope at that pixel, and we cannot accurately calculate the slope at pixels on a + * tile's edge without backfilling from neighboring tiles. + */ +class DEMData { + /** + * Constructs a `DEMData` object + * @param uid - the tile's unique id + * @param data - RGBAImage data has uniform 1px padding on all sides: square tile edge size defines stride + // and dim is calculated as stride - 2. + * @param encoding - the encoding type of the data + * @param redFactor - the red channel factor used to unpack the data, used for `custom` encoding only + * @param greenFactor - the green channel factor used to unpack the data, used for `custom` encoding only + * @param blueFactor - the blue channel factor used to unpack the data, used for `custom` encoding only + * @param baseShift - the base shift used to unpack the data, used for `custom` encoding only + */ + constructor(uid, data, encoding, redFactor = 1.0, greenFactor = 1.0, blueFactor = 1.0, baseShift = 0.0) { + this.uid = uid; + if (data.height !== data.width) + throw new RangeError('DEM tiles must be square'); + if (encoding && !['mapbox', 'terrarium', 'custom'].includes(encoding)) { + warnOnce(`"${encoding}" is not a valid encoding type. Valid types include "mapbox", "terrarium" and "custom".`); + return; + } + this.stride = data.height; + const dim = this.dim = data.height - 2; + this.data = new Uint32Array(data.data.buffer); + switch (encoding) { + case 'terrarium': + // unpacking formula for mapzen terrarium: + // https://aws.amazon.com/public-datasets/terrain/ + this.redFactor = 256.0; + this.greenFactor = 1.0; + this.blueFactor = 1.0 / 256.0; + this.baseShift = 32768.0; + break; + case 'custom': + this.redFactor = redFactor; + this.greenFactor = greenFactor; + this.blueFactor = blueFactor; + this.baseShift = baseShift; + break; + case 'mapbox': + default: + // unpacking formula for mapbox.terrain-rgb: + // https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb + this.redFactor = 6553.6; + this.greenFactor = 25.6; + this.blueFactor = 0.1; + this.baseShift = 10000.0; + break; + } + // in order to avoid flashing seams between tiles, here we are initially populating a 1px border of pixels around the image + // with the data of the nearest pixel from the image. this data is eventually replaced when the tile's neighboring + // tiles are loaded and the accurate data can be backfilled using DEMData#backfillBorder + for (let x = 0; x < dim; x++) { + // left vertical border + this.data[this._idx(-1, x)] = this.data[this._idx(0, x)]; + // right vertical border + this.data[this._idx(dim, x)] = this.data[this._idx(dim - 1, x)]; + // left horizontal border + this.data[this._idx(x, -1)] = this.data[this._idx(x, 0)]; + // right horizontal border + this.data[this._idx(x, dim)] = this.data[this._idx(x, dim - 1)]; + } + // corners + this.data[this._idx(-1, -1)] = this.data[this._idx(0, 0)]; + this.data[this._idx(dim, -1)] = this.data[this._idx(dim - 1, 0)]; + this.data[this._idx(-1, dim)] = this.data[this._idx(0, dim - 1)]; + this.data[this._idx(dim, dim)] = this.data[this._idx(dim - 1, dim - 1)]; + // calculate min/max values + this.min = Number.MAX_SAFE_INTEGER; + this.max = Number.MIN_SAFE_INTEGER; + for (let x = 0; x < dim; x++) { + for (let y = 0; y < dim; y++) { + const ele = this.get(x, y); + if (ele > this.max) + this.max = ele; + if (ele < this.min) + this.min = ele; + } + } + } + get(x, y) { + const pixels = new Uint8Array(this.data.buffer); + const index = this._idx(x, y) * 4; + return this.unpack(pixels[index], pixels[index + 1], pixels[index + 2]); + } + getUnpackVector() { + return [this.redFactor, this.greenFactor, this.blueFactor, this.baseShift]; + } + _idx(x, y) { + if (x < -1 || x >= this.dim + 1 || y < -1 || y >= this.dim + 1) + throw new RangeError('out of range source coordinates for DEM data'); + return (y + 1) * this.stride + (x + 1); + } + unpack(r, g, b) { + return (r * this.redFactor + g * this.greenFactor + b * this.blueFactor - this.baseShift); + } + getPixels() { + return new RGBAImage({ width: this.stride, height: this.stride }, new Uint8Array(this.data.buffer)); + } + backfillBorder(borderTile, dx, dy) { + if (this.dim !== borderTile.dim) + throw new Error('dem dimension mismatch'); + let xMin = dx * this.dim, xMax = dx * this.dim + this.dim, yMin = dy * this.dim, yMax = dy * this.dim + this.dim; + switch (dx) { + case -1: + xMin = xMax - 1; + break; + case 1: + xMax = xMin + 1; + break; + } + switch (dy) { + case -1: + yMin = yMax - 1; + break; + case 1: + yMax = yMin + 1; + break; + } + const ox = -dx * this.dim; + const oy = -dy * this.dim; + for (let y = yMin; y < yMax; y++) { + for (let x = xMin; x < xMax; x++) { + this.data[this._idx(x, y)] = borderTile.data[this._idx(x + ox, y + oy)]; + } + } + } +} +register('DEMData', DEMData); + +class DictionaryCoder { + constructor(strings) { + this._stringToNumber = {}; + this._numberToString = []; + for (let i = 0; i < strings.length; i++) { + const string = strings[i]; + this._stringToNumber[string] = i; + this._numberToString[i] = string; + } + } + encode(string) { + return this._stringToNumber[string]; + } + decode(n) { + if (n >= this._numberToString.length) + throw new Error(`Out of bounds. Index requested n=${n} can't be >= this._numberToString.length ${this._numberToString.length}`); + return this._numberToString[n]; + } +} + +/** + * A geojson feature + */ +class GeoJSONFeature { + constructor(vectorTileFeature, z, x, y, id) { + this.type = 'Feature'; + this._vectorTileFeature = vectorTileFeature; + vectorTileFeature._z = z; + vectorTileFeature._x = x; + vectorTileFeature._y = y; + this.properties = vectorTileFeature.properties; + this.id = id; + } + get geometry() { + if (this._geometry === undefined) { + this._geometry = this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x, this._vectorTileFeature._y, this._vectorTileFeature._z).geometry; + } + return this._geometry; + } + set geometry(g) { + this._geometry = g; + } + toJSON() { + const json = { + geometry: this.geometry + }; + for (const i in this) { + if (i === '_geometry' || i === '_vectorTileFeature') + continue; + json[i] = (this)[i]; + } + return json; + } +} + +/** + * An in memory index class to allow fast interaction with features + */ +class FeatureIndex { + constructor(tileID, promoteId) { + this.tileID = tileID; + this.x = tileID.canonical.x; + this.y = tileID.canonical.y; + this.z = tileID.canonical.z; + this.grid = new TransferableGridIndex(EXTENT, 16, 0); + this.grid3D = new TransferableGridIndex(EXTENT, 16, 0); + this.featureIndexArray = new FeatureIndexArray(); + this.promoteId = promoteId; + } + insert(feature, geometry, featureIndex, sourceLayerIndex, bucketIndex, is3D) { + const key = this.featureIndexArray.length; + this.featureIndexArray.emplaceBack(featureIndex, sourceLayerIndex, bucketIndex); + const grid = is3D ? this.grid3D : this.grid; + for (let r = 0; r < geometry.length; r++) { + const ring = geometry[r]; + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + for (let i = 0; i < ring.length; i++) { + const p = ring[i]; + bbox[0] = Math.min(bbox[0], p.x); + bbox[1] = Math.min(bbox[1], p.y); + bbox[2] = Math.max(bbox[2], p.x); + bbox[3] = Math.max(bbox[3], p.y); + } + if (bbox[0] < EXTENT && + bbox[1] < EXTENT && + bbox[2] >= 0 && + bbox[3] >= 0) { + grid.insert(key, bbox[0], bbox[1], bbox[2], bbox[3]); + } + } + } + loadVTLayers() { + if (!this.vtLayers) { + this.vtLayers = new vectorTile.VectorTile(new Protobuf(this.rawTileData)).layers; + this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : ['_geojsonTileLayer']); + } + return this.vtLayers; + } + // Finds non-symbol features in this tile at a particular position. + query(args, styleLayers, serializedLayers, sourceFeatureState) { + this.loadVTLayers(); + const params = args.params || {}, pixelsToTileUnits = EXTENT / args.tileSize / args.scale, filter = createFilter(params.filter); + const queryGeometry = args.queryGeometry; + const queryPadding = args.queryPadding * pixelsToTileUnits; + const bounds = getBounds(queryGeometry); + const matching = this.grid.query(bounds.minX - queryPadding, bounds.minY - queryPadding, bounds.maxX + queryPadding, bounds.maxY + queryPadding); + const cameraBounds = getBounds(args.cameraQueryGeometry); + const matching3D = this.grid3D.query(cameraBounds.minX - queryPadding, cameraBounds.minY - queryPadding, cameraBounds.maxX + queryPadding, cameraBounds.maxY + queryPadding, (bx1, by1, bx2, by2) => { + return polygonIntersectsBox(args.cameraQueryGeometry, bx1 - queryPadding, by1 - queryPadding, bx2 + queryPadding, by2 + queryPadding); + }); + for (const key of matching3D) { + matching.push(key); + } + matching.sort(topDownFeatureComparator); + const result = {}; + let previousIndex; + for (let k = 0; k < matching.length; k++) { + const index = matching[k]; + // don't check the same feature more than once + if (index === previousIndex) + continue; + previousIndex = index; + const match = this.featureIndexArray.get(index); + let featureGeometry = null; + this.loadMatchingFeature(result, match.bucketIndex, match.sourceLayerIndex, match.featureIndex, filter, params.layers, params.availableImages, styleLayers, serializedLayers, sourceFeatureState, (feature, styleLayer, featureState) => { + if (!featureGeometry) { + featureGeometry = loadGeometry(feature); + } + return styleLayer.queryIntersectsFeature(queryGeometry, feature, featureState, featureGeometry, this.z, args.transform, pixelsToTileUnits, args.pixelPosMatrix); + }); + } + return result; + } + loadMatchingFeature(result, bucketIndex, sourceLayerIndex, featureIndex, filter, filterLayerIDs, availableImages, styleLayers, serializedLayers, sourceFeatureState, intersectionTest) { + const layerIDs = this.bucketLayerIDs[bucketIndex]; + if (filterLayerIDs && !arraysIntersect(filterLayerIDs, layerIDs)) + return; + const sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex); + const sourceLayer = this.vtLayers[sourceLayerName]; + const feature = sourceLayer.feature(featureIndex); + if (filter.needGeometry) { + const evaluationFeature = toEvaluationFeature(feature, true); + if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) { + return; + } + } + else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) { + return; + } + const id = this.getId(feature, sourceLayerName); + for (let l = 0; l < layerIDs.length; l++) { + const layerID = layerIDs[l]; + if (filterLayerIDs && filterLayerIDs.indexOf(layerID) < 0) { + continue; + } + const styleLayer = styleLayers[layerID]; + if (!styleLayer) + continue; + let featureState = {}; + if (id && sourceFeatureState) { + // `feature-state` expression evaluation requires feature state to be available + featureState = sourceFeatureState.getState(styleLayer.sourceLayer || '_geojsonTileLayer', id); + } + const serializedLayer = extend({}, serializedLayers[layerID]); + serializedLayer.paint = evaluateProperties(serializedLayer.paint, styleLayer.paint, feature, featureState, availableImages); + serializedLayer.layout = evaluateProperties(serializedLayer.layout, styleLayer.layout, feature, featureState, availableImages); + const intersectionZ = !intersectionTest || intersectionTest(feature, styleLayer, featureState); + if (!intersectionZ) { + // Only applied for non-symbol features + continue; + } + const geojsonFeature = new GeoJSONFeature(feature, this.z, this.x, this.y, id); + geojsonFeature.layer = serializedLayer; + let layerResult = result[layerID]; + if (layerResult === undefined) { + layerResult = result[layerID] = []; + } + layerResult.push({ featureIndex, feature: geojsonFeature, intersectionZ }); + } + } + // Given a set of symbol indexes that have already been looked up, + // return a matching set of GeoJSONFeatures + lookupSymbolFeatures(symbolFeatureIndexes, serializedLayers, bucketIndex, sourceLayerIndex, filterSpec, filterLayerIDs, availableImages, styleLayers) { + const result = {}; + this.loadVTLayers(); + const filter = createFilter(filterSpec); + for (const symbolFeatureIndex of symbolFeatureIndexes) { + this.loadMatchingFeature(result, bucketIndex, sourceLayerIndex, symbolFeatureIndex, filter, filterLayerIDs, availableImages, styleLayers, serializedLayers); + } + return result; + } + hasLayer(id) { + for (const layerIDs of this.bucketLayerIDs) { + for (const layerID of layerIDs) { + if (id === layerID) + return true; + } + } + return false; + } + getId(feature, sourceLayerId) { + let id = feature.id; + if (this.promoteId) { + const propName = typeof this.promoteId === 'string' ? this.promoteId : this.promoteId[sourceLayerId]; + id = feature.properties[propName]; + if (typeof id === 'boolean') + id = Number(id); + } + return id; + } +} +register('FeatureIndex', FeatureIndex, { omit: ['rawTileData', 'sourceLayerCoder'] }); +function evaluateProperties(serializedProperties, styleLayerProperties, feature, featureState, availableImages) { + return mapObject(serializedProperties, (property, key) => { + const prop = styleLayerProperties instanceof PossiblyEvaluated ? styleLayerProperties.get(key) : null; + return prop && prop.evaluate ? prop.evaluate(feature, featureState, availableImages) : prop; + }); +} +function getBounds(geometry) { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const p of geometry) { + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + return { minX, minY, maxX, maxY }; +} +function topDownFeatureComparator(a, b) { + return b - a; +} + +/** + * Returns the part of a multiline that intersects with the provided rectangular box. + * + * @param lines - the lines to check + * @param x1 - the left edge of the box + * @param y1 - the top edge of the box + * @param x2 - the right edge of the box + * @param y2 - the bottom edge of the box + * @returns lines + */ +function clipLine(lines, x1, y1, x2, y2) { + const clippedLines = []; + for (let l = 0; l < lines.length; l++) { + const line = lines[l]; + let clippedLine; + for (let i = 0; i < line.length - 1; i++) { + let p0 = line[i]; + let p1 = line[i + 1]; + if (p0.x < x1 && p1.x < x1) { + continue; + } + else if (p0.x < x1) { + p0 = new Point$2(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); + } + else if (p1.x < x1) { + p1 = new Point$2(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); + } + if (p0.y < y1 && p1.y < y1) { + continue; + } + else if (p0.y < y1) { + p0 = new Point$2(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); + } + else if (p1.y < y1) { + p1 = new Point$2(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); + } + if (p0.x >= x2 && p1.x >= x2) { + continue; + } + else if (p0.x >= x2) { + p0 = new Point$2(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); + } + else if (p1.x >= x2) { + p1 = new Point$2(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); + } + if (p0.y >= y2 && p1.y >= y2) { + continue; + } + else if (p0.y >= y2) { + p0 = new Point$2(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); + } + else if (p1.y >= y2) { + p1 = new Point$2(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); + } + if (!clippedLine || !p0.equals(clippedLine[clippedLine.length - 1])) { + clippedLine = [p0]; + clippedLines.push(clippedLine); + } + clippedLine.push(p1); + } + } + return clippedLines; +} + +class Anchor extends Point$2 { + constructor(x, y, angle, segment) { + super(x, y); + this.angle = angle; + if (segment !== undefined) { + this.segment = segment; + } + } + clone() { + return new Anchor(this.x, this.y, this.angle, this.segment); + } +} +register('Anchor', Anchor); + +/** + * Labels placed around really sharp angles aren't readable. Check if any + * part of the potential label has a combined angle that is too big. + * + * @param line - The line to check + * @param anchor - The point on the line around which the label is anchored. + * @param labelLength - The length of the label in geometry units. + * @param windowSize - The check fails if the combined angles within a part of the line that is `windowSize` long is too big. + * @param maxAngle - The maximum combined angle that any window along the label is allowed to have. + * + * @returns whether the label should be placed + */ +function checkMaxAngle(line, anchor, labelLength, windowSize, maxAngle) { + // horizontal labels and labels with length 0 always pass + if (anchor.segment === undefined || labelLength === 0) + return true; + let p = anchor; + let index = anchor.segment + 1; + let anchorDistance = 0; + // move backwards along the line to the first segment the label appears on + while (anchorDistance > -labelLength / 2) { + index--; + // there isn't enough room for the label after the beginning of the line + if (index < 0) + return false; + anchorDistance -= line[index].dist(p); + p = line[index]; + } + anchorDistance += line[index].dist(line[index + 1]); + index++; + // store recent corners and their total angle difference + const recentCorners = []; + let recentAngleDelta = 0; + // move forwards by the length of the label and check angles along the way + while (anchorDistance < labelLength / 2) { + const prev = line[index - 1]; + const current = line[index]; + const next = line[index + 1]; + // there isn't enough room for the label before the end of the line + if (!next) + return false; + let angleDelta = prev.angleTo(current) - current.angleTo(next); + // restrict angle to -pi..pi range + angleDelta = Math.abs(((angleDelta + 3 * Math.PI) % (Math.PI * 2)) - Math.PI); + recentCorners.push({ + distance: anchorDistance, + angleDelta + }); + recentAngleDelta += angleDelta; + // remove corners that are far enough away from the list of recent anchors + while (anchorDistance - recentCorners[0].distance > windowSize) { + recentAngleDelta -= recentCorners.shift().angleDelta; + } + // the sum of angles within the window area exceeds the maximum allowed value. check fails. + if (recentAngleDelta > maxAngle) + return false; + index++; + anchorDistance += current.dist(next); + } + // no part of the line had an angle greater than the maximum allowed. check passes. + return true; +} + +function getLineLength(line) { + let lineLength = 0; + for (let k = 0; k < line.length - 1; k++) { + lineLength += line[k].dist(line[k + 1]); + } + return lineLength; +} +function getAngleWindowSize(shapedText, glyphSize, boxScale) { + return shapedText ? + 3 / 5 * glyphSize * boxScale : + 0; +} +function getShapedLabelLength(shapedText, shapedIcon) { + return Math.max(shapedText ? shapedText.right - shapedText.left : 0, shapedIcon ? shapedIcon.right - shapedIcon.left : 0); +} +function getCenterAnchor(line, maxAngle, shapedText, shapedIcon, glyphSize, boxScale) { + const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); + const labelLength = getShapedLabelLength(shapedText, shapedIcon) * boxScale; + let prevDistance = 0; + const centerDistance = getLineLength(line) / 2; + for (let i = 0; i < line.length - 1; i++) { + const a = line[i], b = line[i + 1]; + const segmentDistance = a.dist(b); + if (prevDistance + segmentDistance > centerDistance) { + // The center is on this segment + const t = (centerDistance - prevDistance) / segmentDistance, x = interpolate.number(a.x, b.x, t), y = interpolate.number(a.y, b.y, t); + const anchor = new Anchor(x, y, b.angleTo(a), i); + anchor._round(); + if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { + return anchor; + } + else { + return; + } + } + prevDistance += segmentDistance; + } +} +function getAnchors(line, spacing, maxAngle, shapedText, shapedIcon, glyphSize, boxScale, overscaling, tileExtent) { + // Resample a line to get anchor points for labels and check that each + // potential label passes text-max-angle check and has enough room to fit + // on the line. + const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); + const shapedLabelLength = getShapedLabelLength(shapedText, shapedIcon); + const labelLength = shapedLabelLength * boxScale; + // Is the line continued from outside the tile boundary? + const isLineContinued = line[0].x === 0 || line[0].x === tileExtent || line[0].y === 0 || line[0].y === tileExtent; + // Is the label long, relative to the spacing? + // If so, adjust the spacing so there is always a minimum space of `spacing / 4` between label edges. + if (spacing - labelLength < spacing / 4) { + spacing = labelLength + spacing / 4; + } + // Offset the first anchor by: + // Either half the label length plus a fixed extra offset if the line is not continued + // Or half the spacing if the line is continued. + // For non-continued lines, add a bit of fixed extra offset to avoid collisions at T intersections. + const fixedExtraOffset = glyphSize * 2; + const offset = !isLineContinued ? + ((shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling) % spacing : + (spacing / 2 * overscaling) % spacing; + return resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, false, tileExtent); +} +function resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, placeAtMiddle, tileExtent) { + const halfLabelLength = labelLength / 2; + const lineLength = getLineLength(line); + let distance = 0, markedDistance = offset - spacing; + let anchors = []; + for (let i = 0; i < line.length - 1; i++) { + const a = line[i], b = line[i + 1]; + const segmentDist = a.dist(b), angle = b.angleTo(a); + while (markedDistance + spacing < distance + segmentDist) { + markedDistance += spacing; + const t = (markedDistance - distance) / segmentDist, x = interpolate.number(a.x, b.x, t), y = interpolate.number(a.y, b.y, t); + // Check that the point is within the tile boundaries and that + // the label would fit before the beginning and end of the line + // if placed at this point. + if (x >= 0 && x < tileExtent && y >= 0 && y < tileExtent && + markedDistance - halfLabelLength >= 0 && + markedDistance + halfLabelLength <= lineLength) { + const anchor = new Anchor(x, y, angle, i); + anchor._round(); + if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { + anchors.push(anchor); + } + } + } + distance += segmentDist; + } + if (!placeAtMiddle && !anchors.length && !isLineContinued) { + // The first attempt at finding anchors at which labels can be placed failed. + // Try again, but this time just try placing one anchor at the middle of the line. + // This has the most effect for short lines in overscaled tiles, since the + // initial offset used in overscaled tiles is calculated to align labels with positions in + // parent tiles instead of placing the label as close to the beginning as possible. + anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, true, tileExtent); + } + return anchors; +} + +// If you have a 10px icon that isn't perfectly aligned to the pixel grid it will cover 11 actual +// pixels. The quad needs to be padded to account for this, otherwise they'll look slightly clipped +// on one edge in some cases. +const border = IMAGE_PADDING; +/** + * Create the quads used for rendering an icon. + */ +function getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit) { + const quads = []; + const image = shapedIcon.image; + const pixelRatio = image.pixelRatio; + const imageWidth = image.paddedRect.w - 2 * border; + const imageHeight = image.paddedRect.h - 2 * border; + let icon = { + x1: shapedIcon.left, + y1: shapedIcon.top, + x2: shapedIcon.right, + y2: shapedIcon.bottom + }; + const stretchX = image.stretchX || [[0, imageWidth]]; + const stretchY = image.stretchY || [[0, imageHeight]]; + const reduceRanges = (sum, range) => sum + range[1] - range[0]; + const stretchWidth = stretchX.reduce(reduceRanges, 0); + const stretchHeight = stretchY.reduce(reduceRanges, 0); + const fixedWidth = imageWidth - stretchWidth; + const fixedHeight = imageHeight - stretchHeight; + let stretchOffsetX = 0; + let stretchContentWidth = stretchWidth; + let stretchOffsetY = 0; + let stretchContentHeight = stretchHeight; + let fixedOffsetX = 0; + let fixedContentWidth = fixedWidth; + let fixedOffsetY = 0; + let fixedContentHeight = fixedHeight; + if (image.content && hasIconTextFit) { + const content = image.content; + const contentWidth = content[2] - content[0]; + const contentHeight = content[3] - content[1]; + // Constrict content area to fit target aspect ratio + if (image.textFitWidth || image.textFitHeight) { + icon = applyTextFit(shapedIcon); + } + stretchOffsetX = sumWithinRange(stretchX, 0, content[0]); + stretchOffsetY = sumWithinRange(stretchY, 0, content[1]); + stretchContentWidth = sumWithinRange(stretchX, content[0], content[2]); + stretchContentHeight = sumWithinRange(stretchY, content[1], content[3]); + fixedOffsetX = content[0] - stretchOffsetX; + fixedOffsetY = content[1] - stretchOffsetY; + fixedContentWidth = contentWidth - stretchContentWidth; + fixedContentHeight = contentHeight - stretchContentHeight; + } + const iconLeft = icon.x1; + const iconTop = icon.y1; + const iconWidth = icon.x2 - iconLeft; + const iconHeight = icon.y2 - iconTop; + const makeBox = (left, top, right, bottom) => { + const leftEm = getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, iconLeft); + const leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth); + const topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, iconTop); + const topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight); + const rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, iconLeft); + const rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth); + const bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, iconTop); + const bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight); + const tl = new Point$2(leftEm, topEm); + const tr = new Point$2(rightEm, topEm); + const br = new Point$2(rightEm, bottomEm); + const bl = new Point$2(leftEm, bottomEm); + const pixelOffsetTL = new Point$2(leftPx / pixelRatio, topPx / pixelRatio); + const pixelOffsetBR = new Point$2(rightPx / pixelRatio, bottomPx / pixelRatio); + const angle = iconRotate * Math.PI / 180; + if (angle) { + const sin = Math.sin(angle), cos = Math.cos(angle), matrix = [cos, -sin, sin, cos]; + tl._matMult(matrix); + tr._matMult(matrix); + bl._matMult(matrix); + br._matMult(matrix); + } + const x1 = left.stretch + left.fixed; + const x2 = right.stretch + right.fixed; + const y1 = top.stretch + top.fixed; + const y2 = bottom.stretch + bottom.fixed; + const subRect = { + x: image.paddedRect.x + border + x1, + y: image.paddedRect.y + border + y1, + w: x2 - x1, + h: y2 - y1 + }; + const minFontScaleX = fixedContentWidth / pixelRatio / iconWidth; + const minFontScaleY = fixedContentHeight / pixelRatio / iconHeight; + // Icon quad is padded, so texture coordinates also need to be padded. + return { tl, tr, bl, br, tex: subRect, writingMode: undefined, glyphOffset: [0, 0], sectionIndex: 0, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, isSDF: isSDFIcon }; + }; + if (!hasIconTextFit || (!image.stretchX && !image.stretchY)) { + quads.push(makeBox({ fixed: 0, stretch: -1 }, { fixed: 0, stretch: -1 }, { fixed: 0, stretch: imageWidth + 1 }, { fixed: 0, stretch: imageHeight + 1 })); + } + else { + const xCuts = stretchZonesToCuts(stretchX, fixedWidth, stretchWidth); + const yCuts = stretchZonesToCuts(stretchY, fixedHeight, stretchHeight); + for (let xi = 0; xi < xCuts.length - 1; xi++) { + const x1 = xCuts[xi]; + const x2 = xCuts[xi + 1]; + for (let yi = 0; yi < yCuts.length - 1; yi++) { + const y1 = yCuts[yi]; + const y2 = yCuts[yi + 1]; + quads.push(makeBox(x1, y1, x2, y2)); + } + } + } + return quads; +} +function sumWithinRange(ranges, min, max) { + let sum = 0; + for (const range of ranges) { + sum += Math.max(min, Math.min(max, range[1])) - Math.max(min, Math.min(max, range[0])); + } + return sum; +} +function stretchZonesToCuts(stretchZones, fixedSize, stretchSize) { + const cuts = [{ fixed: -border, stretch: 0 }]; + for (const [c1, c2] of stretchZones) { + const last = cuts[cuts.length - 1]; + cuts.push({ + fixed: c1 - last.stretch, + stretch: last.stretch + }); + cuts.push({ + fixed: c1 - last.stretch, + stretch: last.stretch + (c2 - c1) + }); + } + cuts.push({ + fixed: fixedSize + border, + stretch: stretchSize + }); + return cuts; +} +function getEmOffset(stretchOffset, stretchSize, iconSize, iconOffset) { + return stretchOffset / stretchSize * iconSize + iconOffset; +} +function getPxOffset(fixedOffset, fixedSize, stretchOffset, stretchSize) { + return fixedOffset - fixedSize * stretchOffset / stretchSize; +} +/** + * Create the quads used for rendering a text label. + */ +function getGlyphQuads(anchor, shaping, textOffset, layer, alongLine, feature, imageMap, allowVerticalPlacement) { + const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}) * Math.PI / 180; + const quads = []; + for (const line of shaping.positionedLines) { + for (const positionedGlyph of line.positionedGlyphs) { + if (!positionedGlyph.rect) + continue; + const textureRect = positionedGlyph.rect || {}; + // The rects have an additional buffer that is not included in their size. + const glyphPadding = 1.0; + let rectBuffer = GLYPH_PBF_BORDER + glyphPadding; + let isSDF = true; + let pixelRatio = 1.0; + let lineOffset = 0.0; + const rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical; + const halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2; + // Align images and scaled glyphs in the middle of a vertical line. + if (allowVerticalPlacement && shaping.verticalizable) { + const scaledGlyphOffset = (positionedGlyph.scale - 1) * ONE_EM; + const imageOffset = (ONE_EM - positionedGlyph.metrics.width * positionedGlyph.scale) / 2; + lineOffset = line.lineOffset / 2 - (positionedGlyph.imageName ? -imageOffset : scaledGlyphOffset); + } + if (positionedGlyph.imageName) { + const image = imageMap[positionedGlyph.imageName]; + isSDF = image.sdf; + pixelRatio = image.pixelRatio; + rectBuffer = IMAGE_PADDING / pixelRatio; + } + const glyphOffset = alongLine ? + [positionedGlyph.x + halfAdvance, positionedGlyph.y] : + [0, 0]; + let builtInOffset = alongLine ? + [0, 0] : + [positionedGlyph.x + halfAdvance + textOffset[0], positionedGlyph.y + textOffset[1] - lineOffset]; + let verticalizedLabelOffset = [0, 0]; + if (rotateVerticalGlyph) { + // Vertical POI labels that are rotated 90deg CW and whose glyphs must preserve upright orientation + // need to be rotated 90deg CCW. After a quad is rotated, it is translated to the original built-in offset. + verticalizedLabelOffset = builtInOffset; + builtInOffset = [0, 0]; + } + const textureScale = positionedGlyph.metrics.isDoubleResolution ? 2 : 1; + const x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0]; + const y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1]; + const x2 = x1 + textureRect.w / textureScale * positionedGlyph.scale / pixelRatio; + const y2 = y1 + textureRect.h / textureScale * positionedGlyph.scale / pixelRatio; + const tl = new Point$2(x1, y1); + const tr = new Point$2(x2, y1); + const bl = new Point$2(x1, y2); + const br = new Point$2(x2, y2); + if (rotateVerticalGlyph) { + // Vertical-supporting glyphs are laid out in 24x24 point boxes (1 square em) + // In horizontal orientation, the y values for glyphs are below the midline + // and we use a "yOffset" of -17 to pull them up to the middle. + // By rotating counter-clockwise around the point at the center of the left + // edge of a 24x24 layout box centered below the midline, we align the center + // of the glyphs with the horizontal midline, so the yOffset is no longer + // necessary, but we also pull the glyph to the left along the x axis. + // The y coordinate includes baseline yOffset, thus needs to be accounted + // for when glyph is rotated and translated. + const center = new Point$2(-halfAdvance, halfAdvance - SHAPING_DEFAULT_OFFSET); + const verticalRotation = -Math.PI / 2; + // xHalfWidthOffsetCorrection is a difference between full-width and half-width + // advance, should be 0 for full-width glyphs and will pull up half-width glyphs. + const xHalfWidthOffsetCorrection = ONE_EM / 2 - halfAdvance; + const yImageOffsetCorrection = positionedGlyph.imageName ? xHalfWidthOffsetCorrection : 0.0; + const halfWidthOffsetCorrection = new Point$2(5 - SHAPING_DEFAULT_OFFSET - xHalfWidthOffsetCorrection, -yImageOffsetCorrection); + const verticalOffsetCorrection = new Point$2(...verticalizedLabelOffset); + tl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + tr._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + bl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + br._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + } + if (textRotate) { + const sin = Math.sin(textRotate), cos = Math.cos(textRotate), matrix = [cos, -sin, sin, cos]; + tl._matMult(matrix); + tr._matMult(matrix); + bl._matMult(matrix); + br._matMult(matrix); + } + const pixelOffsetTL = new Point$2(0, 0); + const pixelOffsetBR = new Point$2(0, 0); + const minFontScaleX = 0; + const minFontScaleY = 0; + quads.push({ tl, tr, bl, br, tex: textureRect, writingMode: shaping.writingMode, glyphOffset, sectionIndex: positionedGlyph.sectionIndex, isSDF, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY }); + } + } + return quads; +} + +/** + * A CollisionFeature represents the area of the tile covered by a single label. + * It is used with CollisionIndex to check if the label overlaps with any + * previous labels. A CollisionFeature is mostly just a set of CollisionBox + * objects. + */ +class CollisionFeature { + /** + * Create a CollisionFeature, adding its collision box data to the given collisionBoxArray in the process. + * For line aligned labels a collision circle diameter is computed instead. + * + * @param anchor - The point along the line around which the label is anchored. + * @param shaped - The text or icon shaping results. + * @param boxScale - A magic number used to convert from glyph metrics units to geometry units. + * @param padding - The amount of padding to add around the label edges. + * @param alignLine - Whether the label is aligned with the line or the viewport. + */ + constructor(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaped, boxScale, padding, alignLine, rotate) { + var _a; + this.boxStartIndex = collisionBoxArray.length; + if (alignLine) { + // Compute height of the shape in glyph metrics and apply collision padding. + // Note that the pixel based 'text-padding' is applied at runtime + let top = shaped.top; + let bottom = shaped.bottom; + const collisionPadding = shaped.collisionPadding; + if (collisionPadding) { + top -= collisionPadding[1]; + bottom += collisionPadding[3]; + } + let height = bottom - top; + if (height > 0) { + // set minimum box height to avoid very many small labels + height = Math.max(10, height); + this.circleDiameter = height; + } + } + else { + const icon = ((_a = shaped.image) === null || _a === void 0 ? void 0 : _a.content) && (shaped.image.textFitWidth || shaped.image.textFitHeight) ? + applyTextFit(shaped) : + { + x1: shaped.left, + y1: shaped.top, + x2: shaped.right, + y2: shaped.bottom + }; + // margin is in CSS order: [top, right, bottom, left] + icon.y1 = icon.y1 * boxScale - padding[0]; + icon.y2 = icon.y2 * boxScale + padding[2]; + icon.x1 = icon.x1 * boxScale - padding[3]; + icon.x2 = icon.x2 * boxScale + padding[1]; + const collisionPadding = shaped.collisionPadding; + if (collisionPadding) { + icon.x1 -= collisionPadding[0] * boxScale; + icon.y1 -= collisionPadding[1] * boxScale; + icon.x2 += collisionPadding[2] * boxScale; + icon.y2 += collisionPadding[3] * boxScale; + } + if (rotate) { + // Account for *-rotate in point collision boxes + // See https://github.com/mapbox/mapbox-gl-js/issues/6075 + // Doesn't account for icon-text-fit + const tl = new Point$2(icon.x1, icon.y1); + const tr = new Point$2(icon.x2, icon.y1); + const bl = new Point$2(icon.x1, icon.y2); + const br = new Point$2(icon.x2, icon.y2); + const rotateRadians = rotate * Math.PI / 180; + tl._rotate(rotateRadians); + tr._rotate(rotateRadians); + bl._rotate(rotateRadians); + br._rotate(rotateRadians); + // Collision features require an "on-axis" geometry, + // so take the envelope of the rotated geometry + // (may be quite large for wide labels rotated 45 degrees) + icon.x1 = Math.min(tl.x, tr.x, bl.x, br.x); + icon.x2 = Math.max(tl.x, tr.x, bl.x, br.x); + icon.y1 = Math.min(tl.y, tr.y, bl.y, br.y); + icon.y2 = Math.max(tl.y, tr.y, bl.y, br.y); + } + collisionBoxArray.emplaceBack(anchor.x, anchor.y, icon.x1, icon.y1, icon.x2, icon.y2, featureIndex, sourceLayerIndex, bucketIndex); + } + this.boxEndIndex = collisionBoxArray.length; + } +} + +class TinyQueue { + constructor(data = [], compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) { + this.data = data; + this.length = this.data.length; + this.compare = compare; + + if (this.length > 0) { + for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i); + } + } + + push(item) { + this.data.push(item); + this._up(this.length++); + } + + pop() { + if (this.length === 0) return undefined; + + const top = this.data[0]; + const bottom = this.data.pop(); + + if (--this.length > 0) { + this.data[0] = bottom; + this._down(0); + } + + return top; + } + + peek() { + return this.data[0]; + } + + _up(pos) { + const {data, compare} = this; + const item = data[pos]; + + while (pos > 0) { + const parent = (pos - 1) >> 1; + const current = data[parent]; + if (compare(item, current) >= 0) break; + data[pos] = current; + pos = parent; + } + + data[pos] = item; + } + + _down(pos) { + const {data, compare} = this; + const halfLength = this.length >> 1; + const item = data[pos]; + + while (pos < halfLength) { + let bestChild = (pos << 1) + 1; // initially it is the left child + const right = bestChild + 1; + + if (right < this.length && compare(data[right], data[bestChild]) < 0) { + bestChild = right; + } + if (compare(data[bestChild], item) >= 0) break; + + data[pos] = data[bestChild]; + pos = bestChild; + } + + data[pos] = item; + } +} + +/** + * Finds an approximation of a polygon's Pole Of Inaccessibility https://en.wikipedia.org/wiki/Pole_of_inaccessibility + * This is a copy of https://github.com/mapbox/polylabel adapted to use Points + * + * @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 + * @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 + * @param debug - Print some statistics to the console during execution + * @returns Pole of Inaccessibility. + */ +function findPoleOfInaccessibility(polygonRings, precision = 1, debug = false) { + // find the bounding box of the outer ring + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + const outerRing = polygonRings[0]; + for (let i = 0; i < outerRing.length; i++) { + const p = outerRing[i]; + if (!i || p.x < minX) + minX = p.x; + if (!i || p.y < minY) + minY = p.y; + if (!i || p.x > maxX) + maxX = p.x; + if (!i || p.y > maxY) + maxY = p.y; + } + const width = maxX - minX; + const height = maxY - minY; + const cellSize = Math.min(width, height); + let h = cellSize / 2; + // a priority queue of cells in order of their "potential" (max distance to polygon) + const cellQueue = new TinyQueue([], compareMax); + if (cellSize === 0) + return new Point$2(minX, minY); + // cover polygon with initial cells + for (let x = minX; x < maxX; x += cellSize) { + for (let y = minY; y < maxY; y += cellSize) { + cellQueue.push(new Cell(x + h, y + h, h, polygonRings)); + } + } + // take centroid as the first best guess + let bestCell = getCentroidCell(polygonRings); + let numProbes = cellQueue.length; + while (cellQueue.length) { + // pick the most promising cell from the queue + const cell = cellQueue.pop(); + // update the best cell if we found a better one + if (cell.d > bestCell.d || !bestCell.d) { + bestCell = cell; + if (debug) + console.log('found best %d after %d probes', Math.round(1e4 * cell.d) / 1e4, numProbes); + } + // do not drill down further if there's no chance of a better solution + if (cell.max - bestCell.d <= precision) + continue; + // split the cell into four cells + h = cell.h / 2; + cellQueue.push(new Cell(cell.p.x - h, cell.p.y - h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x + h, cell.p.y - h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x - h, cell.p.y + h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x + h, cell.p.y + h, h, polygonRings)); + numProbes += 4; + } + if (debug) { + console.log(`num probes: ${numProbes}`); + console.log(`best distance: ${bestCell.d}`); + } + return bestCell.p; +} +function compareMax(a, b) { + return b.max - a.max; +} +function Cell(x, y, h, polygon) { + this.p = new Point$2(x, y); + this.h = h; // half the cell size + this.d = pointToPolygonDist(this.p, polygon); // distance from cell center to polygon + this.max = this.d + this.h * Math.SQRT2; // max distance to polygon within a cell +} +// signed distance from point to polygon outline (negative if point is outside) +function pointToPolygonDist(p, polygon) { + let inside = false; + let minDistSq = Infinity; + for (let k = 0; k < polygon.length; k++) { + const ring = polygon[k]; + for (let i = 0, len = ring.length, j = len - 1; i < len; j = i++) { + const a = ring[i]; + const b = ring[j]; + if ((a.y > p.y !== b.y > p.y) && + (p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x)) + inside = !inside; + minDistSq = Math.min(minDistSq, distToSegmentSquared(p, a, b)); + } + } + return (inside ? 1 : -1) * Math.sqrt(minDistSq); +} +// get polygon centroid +function getCentroidCell(polygon) { + let area = 0; + let x = 0; + let y = 0; + const points = polygon[0]; + for (let i = 0, len = points.length, j = len - 1; i < len; j = i++) { + const a = points[i]; + const b = points[j]; + const f = a.x * b.y - b.x * a.y; + x += (a.x + b.x) * f; + y += (a.y + b.y) * f; + area += f * 3; + } + return new Cell(x / area, y / area, 0, polygon); +} + +exports.TextAnchorEnum = void 0; +(function (TextAnchorEnum) { + TextAnchorEnum[TextAnchorEnum["center"] = 1] = "center"; + TextAnchorEnum[TextAnchorEnum["left"] = 2] = "left"; + TextAnchorEnum[TextAnchorEnum["right"] = 3] = "right"; + TextAnchorEnum[TextAnchorEnum["top"] = 4] = "top"; + TextAnchorEnum[TextAnchorEnum["bottom"] = 5] = "bottom"; + TextAnchorEnum[TextAnchorEnum["top-left"] = 6] = "top-left"; + TextAnchorEnum[TextAnchorEnum["top-right"] = 7] = "top-right"; + TextAnchorEnum[TextAnchorEnum["bottom-left"] = 8] = "bottom-left"; + TextAnchorEnum[TextAnchorEnum["bottom-right"] = 9] = "bottom-right"; +})(exports.TextAnchorEnum || (exports.TextAnchorEnum = {})); +// The radial offset is to the edge of the text box +// In the horizontal direction, the edge of the text box is where glyphs start +// But in the vertical direction, the glyphs appear to "start" at the baseline +// We don't actually load baseline data, but we assume an offset of ONE_EM - 17 +// (see "yOffset" in shaping.js) +const baselineOffset = 7; +const INVALID_TEXT_OFFSET = Number.POSITIVE_INFINITY; +function evaluateVariableOffset(anchor, offset) { + function fromRadialOffset(anchor, radialOffset) { + let x = 0, y = 0; + if (radialOffset < 0) + radialOffset = 0; // Ignore negative offset. + // solve for r where r^2 + r^2 = radialOffset^2 + const hypotenuse = radialOffset / Math.SQRT2; + switch (anchor) { + case 'top-right': + case 'top-left': + y = hypotenuse - baselineOffset; + break; + case 'bottom-right': + case 'bottom-left': + y = -hypotenuse + baselineOffset; + break; + case 'bottom': + y = -radialOffset + baselineOffset; + break; + case 'top': + y = radialOffset - baselineOffset; + break; + } + switch (anchor) { + case 'top-right': + case 'bottom-right': + x = -hypotenuse; + break; + case 'top-left': + case 'bottom-left': + x = hypotenuse; + break; + case 'left': + x = radialOffset; + break; + case 'right': + x = -radialOffset; + break; + } + return [x, y]; + } + function fromTextOffset(anchor, offsetX, offsetY) { + let x = 0, y = 0; + // Use absolute offset values. + offsetX = Math.abs(offsetX); + offsetY = Math.abs(offsetY); + switch (anchor) { + case 'top-right': + case 'top-left': + case 'top': + y = offsetY - baselineOffset; + break; + case 'bottom-right': + case 'bottom-left': + case 'bottom': + y = -offsetY + baselineOffset; + break; + } + switch (anchor) { + case 'top-right': + case 'bottom-right': + case 'right': + x = -offsetX; + break; + case 'top-left': + case 'bottom-left': + case 'left': + x = offsetX; + break; + } + return [x, y]; + } + return (offset[1] !== INVALID_TEXT_OFFSET) ? fromTextOffset(anchor, offset[0], offset[1]) : fromRadialOffset(anchor, offset[0]); +} +// Helper to support both text-variable-anchor and text-variable-anchor-offset. Offset values converted from EMs to PXs +function getTextVariableAnchorOffset(layer, feature, canonical) { + var _a; + const layout = layer.layout; + // If style specifies text-variable-anchor-offset, just return it + const variableAnchorOffset = (_a = layout.get('text-variable-anchor-offset')) === null || _a === void 0 ? void 0 : _a.evaluate(feature, {}, canonical); + if (variableAnchorOffset) { + const sourceValues = variableAnchorOffset.values; + const destValues = []; + // Convert offsets from EM to PX, and apply baseline shift + for (let i = 0; i < sourceValues.length; i += 2) { + const anchor = destValues[i] = sourceValues[i]; + const offset = sourceValues[i + 1].map(t => t * ONE_EM); + if (anchor.startsWith('top')) { + offset[1] -= baselineOffset; + } + else if (anchor.startsWith('bottom')) { + offset[1] += baselineOffset; + } + destValues[i + 1] = offset; + } + return new VariableAnchorOffsetCollection(destValues); + } + // If style specifies text-variable-anchor, convert to the new format + const variableAnchor = layout.get('text-variable-anchor'); + if (variableAnchor) { + let textOffset; + const unevaluatedLayout = layer._unevaluatedLayout; + // The style spec says don't use `text-offset` and `text-radial-offset` together + // but doesn't actually specify what happens if you use both. We go with the radial offset. + if (unevaluatedLayout.getValue('text-radial-offset') !== undefined) { + textOffset = [layout.get('text-radial-offset').evaluate(feature, {}, canonical) * ONE_EM, INVALID_TEXT_OFFSET]; + } + else { + textOffset = layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM); + } + const anchorOffsets = []; + for (const anchor of variableAnchor) { + anchorOffsets.push(anchor, evaluateVariableOffset(anchor, textOffset)); + } + return new VariableAnchorOffsetCollection(anchorOffsets); + } + return null; +} + +function performSymbolLayout(args) { + args.bucket.createArrays(); + const tileSize = 512 * args.bucket.overscaling; + args.bucket.tilePixelRatio = EXTENT / tileSize; + args.bucket.compareText = {}; + args.bucket.iconsNeedLinear = false; + const layer = args.bucket.layers[0]; + const layout = layer.layout; + const unevaluatedLayoutValues = layer._unevaluatedLayout._values; + const sizes = { + // Filled in below, if *SizeData.kind is 'composite' + // compositeIconSizes: undefined, + // compositeTextSizes: undefined, + layoutIconSize: unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical), + layoutTextSize: unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical), + textMaxSize: unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(18)) + }; + if (args.bucket.textSizeData.kind === 'composite') { + const { minZoom, maxZoom } = args.bucket.textSizeData; + sizes.compositeTextSizes = [ + unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical), + unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical) + ]; + } + if (args.bucket.iconSizeData.kind === 'composite') { + const { minZoom, maxZoom } = args.bucket.iconSizeData; + sizes.compositeIconSizes = [ + unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical), + unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical) + ]; + } + const lineHeight = layout.get('text-line-height') * ONE_EM; + const textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point'; + const keepUpright = layout.get('text-keep-upright'); + const textSize = layout.get('text-size'); + for (const feature of args.bucket.features) { + const fontstack = layout.get('text-font').evaluate(feature, {}, args.canonical).join(','); + const layoutTextSizeThisZoom = textSize.evaluate(feature, {}, args.canonical); + const layoutTextSize = sizes.layoutTextSize.evaluate(feature, {}, args.canonical); + const layoutIconSize = sizes.layoutIconSize.evaluate(feature, {}, args.canonical); + const shapedTextOrientations = { + horizontal: {}, + vertical: undefined + }; + const text = feature.text; + let textOffset = [0, 0]; + if (text) { + const unformattedText = text.toString(); + const spacing = layout.get('text-letter-spacing').evaluate(feature, {}, args.canonical) * ONE_EM; + const spacingIfAllowed = allowsLetterSpacing(unformattedText) ? spacing : 0; + const textAnchor = layout.get('text-anchor').evaluate(feature, {}, args.canonical); + const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, args.canonical); + if (!variableAnchorOffset) { + const radialOffset = layout.get('text-radial-offset').evaluate(feature, {}, args.canonical); + // Layers with variable anchors use the `text-radial-offset` property and the [x, y] offset vector + // is calculated at placement time instead of layout time + if (radialOffset) { + // The style spec says don't use `text-offset` and `text-radial-offset` together + // but doesn't actually specify what happens if you use both. We go with the radial offset. + textOffset = evaluateVariableOffset(textAnchor, [radialOffset * ONE_EM, INVALID_TEXT_OFFSET]); + } + else { + textOffset = layout.get('text-offset').evaluate(feature, {}, args.canonical).map(t => t * ONE_EM); + } + } + let textJustify = textAlongLine ? + 'center' : + layout.get('text-justify').evaluate(feature, {}, args.canonical); + const symbolPlacement = layout.get('symbol-placement'); + const maxWidth = symbolPlacement === 'point' ? + layout.get('text-max-width').evaluate(feature, {}, args.canonical) * ONE_EM : + Infinity; + const addVerticalShapingForPointLabelIfNeeded = () => { + if (args.bucket.allowVerticalPlacement && allowsVerticalWritingMode(unformattedText)) { + // Vertical POI label placement is meant to be used for scripts that support vertical + // writing mode, thus, default left justification is used. If Latin + // scripts would need to be supported, this should take into account other justifications. + shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, 'left', spacingIfAllowed, textOffset, exports.WritingMode.vertical, true, layoutTextSize, layoutTextSizeThisZoom); + } + }; + // If this layer uses text-variable-anchor, generate shapings for all justification possibilities. + if (!textAlongLine && variableAnchorOffset) { + const justifications = new Set(); + if (textJustify === 'auto') { + for (let i = 0; i < variableAnchorOffset.values.length; i += 2) { + justifications.add(getAnchorJustification(variableAnchorOffset.values[i])); + } + } + else { + justifications.add(textJustify); + } + let singleLine = false; + for (const justification of justifications) { + if (shapedTextOrientations.horizontal[justification]) + continue; + if (singleLine) { + // If the shaping for the first justification was only a single line, we + // can re-use it for the other justifications + shapedTextOrientations.horizontal[justification] = shapedTextOrientations.horizontal[0]; + } + else { + // If using text-variable-anchor for the layer, we use a center anchor for all shapings and apply + // the offsets for the anchor in the placement step. + const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, 'center', justification, spacingIfAllowed, textOffset, exports.WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom); + if (shaping) { + shapedTextOrientations.horizontal[justification] = shaping; + singleLine = shaping.positionedLines.length === 1; + } + } + } + addVerticalShapingForPointLabelIfNeeded(); + } + else { + if (textJustify === 'auto') { + textJustify = getAnchorJustification(textAnchor); + } + // Horizontal point or line label. + const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, exports.WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom); + if (shaping) + shapedTextOrientations.horizontal[textJustify] = shaping; + // Vertical point label (if allowVerticalPlacement is enabled). + addVerticalShapingForPointLabelIfNeeded(); + // Verticalized line label. + if (allowsVerticalWritingMode(unformattedText) && textAlongLine && keepUpright) { + shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, exports.WritingMode.vertical, false, layoutTextSize, layoutTextSizeThisZoom); + } + } + } + let shapedIcon; + let isSDFIcon = false; + if (feature.icon && feature.icon.name) { + const image = args.imageMap[feature.icon.name]; + if (image) { + shapedIcon = shapeIcon(args.imagePositions[feature.icon.name], layout.get('icon-offset').evaluate(feature, {}, args.canonical), layout.get('icon-anchor').evaluate(feature, {}, args.canonical)); + // null/undefined SDF property treated same as default (false) + isSDFIcon = !!image.sdf; + if (args.bucket.sdfIcons === undefined) { + args.bucket.sdfIcons = isSDFIcon; + } + else if (args.bucket.sdfIcons !== isSDFIcon) { + warnOnce('Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer'); + } + if (image.pixelRatio !== args.bucket.pixelRatio) { + args.bucket.iconsNeedLinear = true; + } + else if (layout.get('icon-rotate').constantOr(1) !== 0) { + args.bucket.iconsNeedLinear = true; + } + } + } + const shapedText = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical; + args.bucket.iconsInText = shapedText ? shapedText.iconsInText : false; + if (shapedText || shapedIcon) { + addFeature(args.bucket, feature, shapedTextOrientations, shapedIcon, args.imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, args.canonical); + } + } + if (args.showCollisionBoxes) { + args.bucket.generateCollisionDebugBuffers(); + } +} +// Choose the justification that matches the direction of the TextAnchor +function getAnchorJustification(anchor) { + switch (anchor) { + case 'right': + case 'top-right': + case 'bottom-right': + return 'right'; + case 'left': + case 'top-left': + case 'bottom-left': + return 'left'; + } + return 'center'; +} +/** + * Given a feature and its shaped text and icon data, add a 'symbol + * instance' for each _possible_ placement of the symbol feature. + * (At render timePlaceSymbols#place() selects which of these instances to + * show or hide based on collisions with symbols in other layers.) + */ +function addFeature(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, canonical) { + // To reduce the number of labels that jump around when zooming we need + // to use a text-size value that is the same for all zoom levels. + // bucket calculates text-size at a high zoom level so that all tiles can + // use the same value when calculating anchor positions. + let textMaxSize = sizes.textMaxSize.evaluate(feature, {}); + if (textMaxSize === undefined) { + textMaxSize = layoutTextSize; + } + const layout = bucket.layers[0].layout; + const iconOffset = layout.get('icon-offset').evaluate(feature, {}, canonical); + const defaultHorizontalShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal); + const glyphSize = 24, fontScale = layoutTextSize / glyphSize, textBoxScale = bucket.tilePixelRatio * fontScale, textMaxBoxScale = bucket.tilePixelRatio * textMaxSize / glyphSize, iconBoxScale = bucket.tilePixelRatio * layoutIconSize, symbolMinDistance = bucket.tilePixelRatio * layout.get('symbol-spacing'), textPadding = layout.get('text-padding') * bucket.tilePixelRatio, iconPadding = getIconPadding(layout, feature, canonical, bucket.tilePixelRatio), textMaxAngle = layout.get('text-max-angle') / 180 * Math.PI, textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point', iconAlongLine = layout.get('icon-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point', symbolPlacement = layout.get('symbol-placement'), textRepeatDistance = symbolMinDistance / 2; + const iconTextFit = layout.get('icon-text-fit'); + let verticallyShapedIcon; + // Adjust shaped icon size when icon-text-fit is used. + if (shapedIcon && iconTextFit !== 'none') { + if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) { + verticallyShapedIcon = fitIconToText(shapedIcon, shapedTextOrientations.vertical, iconTextFit, layout.get('icon-text-fit-padding'), iconOffset, fontScale); + } + if (defaultHorizontalShaping) { + shapedIcon = fitIconToText(shapedIcon, defaultHorizontalShaping, iconTextFit, layout.get('icon-text-fit-padding'), iconOffset, fontScale); + } + } + const addSymbolAtAnchor = (line, anchor) => { + if (anchor.x < 0 || anchor.x >= EXTENT || anchor.y < 0 || anchor.y >= EXTENT) { + // Symbol layers are drawn across tile boundaries, We filter out symbols + // outside our tile boundaries (which may be included in vector tile buffers) + // to prevent double-drawing symbols. + return; + } + addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, bucket.layers[0], bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex, bucket.index, textBoxScale, [textPadding, textPadding, textPadding, textPadding], textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, canonical, layoutTextSize); + }; + if (symbolPlacement === 'line') { + for (const line of clipLine(feature.geometry, 0, 0, EXTENT, EXTENT)) { + const anchors = getAnchors(line, symbolMinDistance, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale, bucket.overscaling, EXTENT); + for (const anchor of anchors) { + const shapedText = defaultHorizontalShaping; + if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) { + addSymbolAtAnchor(line, anchor); + } + } + } + } + else if (symbolPlacement === 'line-center') { + // No clipping, multiple lines per feature are allowed + // "lines" with only one point are ignored as in clipLines + for (const line of feature.geometry) { + if (line.length > 1) { + const anchor = getCenterAnchor(line, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale); + if (anchor) { + addSymbolAtAnchor(line, anchor); + } + } + } + } + else if (feature.type === 'Polygon') { + for (const polygon of classifyRings$1(feature.geometry, 0)) { + // 16 here represents 2 pixels + const poi = findPoleOfInaccessibility(polygon, 16); + addSymbolAtAnchor(polygon[0], new Anchor(poi.x, poi.y, 0)); + } + } + else if (feature.type === 'LineString') { + // https://github.com/mapbox/mapbox-gl-js/issues/3808 + for (const line of feature.geometry) { + addSymbolAtAnchor(line, new Anchor(line[0].x, line[0].y, 0)); + } + } + else if (feature.type === 'Point') { + for (const points of feature.geometry) { + for (const point of points) { + addSymbolAtAnchor([point], new Anchor(point.x, point.y, 0)); + } + } + } +} +function addTextVariableAnchorOffsets(textAnchorOffsets, variableAnchorOffset) { + const startIndex = textAnchorOffsets.length; + const values = variableAnchorOffset === null || variableAnchorOffset === void 0 ? void 0 : variableAnchorOffset.values; + if ((values === null || values === void 0 ? void 0 : values.length) > 0) { + for (let i = 0; i < values.length; i += 2) { + const anchor = exports.TextAnchorEnum[values[i]]; + const offset = values[i + 1]; + textAnchorOffsets.emplaceBack(anchor, offset[0], offset[1]); + } + } + return [startIndex, textAnchorOffsets.length]; +} +function addTextVertices(bucket, anchor, shapedText, imageMap, layer, textAlongLine, feature, textOffset, lineArray, writingMode, placementTypes, placedTextSymbolIndices, placedIconIndex, sizes, canonical) { + const glyphQuads = getGlyphQuads(anchor, shapedText, textOffset, layer, textAlongLine, feature, imageMap, bucket.allowVerticalPlacement); + const sizeData = bucket.textSizeData; + let textSizeData = null; + if (sizeData.kind === 'source') { + textSizeData = [ + SIZE_PACK_FACTOR * layer.layout.get('text-size').evaluate(feature, {}) + ]; + if (textSizeData[0] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`); + } + } + else if (sizeData.kind === 'composite') { + textSizeData = [ + SIZE_PACK_FACTOR * sizes.compositeTextSizes[0].evaluate(feature, {}, canonical), + SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical) + ]; + if (textSizeData[0] > MAX_PACKED_SIZE || textSizeData[1] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`); + } + } + bucket.addSymbols(bucket.text, glyphQuads, textSizeData, textOffset, textAlongLine, feature, writingMode, anchor, lineArray.lineStartIndex, lineArray.lineLength, placedIconIndex, canonical); + // The placedSymbolArray is used at render time in drawTileSymbols + // These indices allow access to the array at collision detection time + for (const placementType of placementTypes) { + placedTextSymbolIndices[placementType] = bucket.text.placedSymbolArray.length - 1; + } + return glyphQuads.length * 4; +} +function getDefaultHorizontalShaping(horizontalShaping) { + // We don't care which shaping we get because this is used for collision purposes + // and all the justifications have the same collision box + for (const justification in horizontalShaping) { + return horizontalShaping[justification]; + } + return null; +} +/** + * Add a single label & icon placement. + */ +function addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, layer, collisionBoxArray, featureIndex, sourceLayerIndex, bucketIndex, textBoxScale, textPadding, textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, canonical, layoutTextSize) { + const lineArray = bucket.addToLineVertexArray(anchor, line); + let textCollisionFeature, iconCollisionFeature, verticalTextCollisionFeature, verticalIconCollisionFeature; + let numIconVertices = 0; + let numVerticalIconVertices = 0; + let numHorizontalGlyphVertices = 0; + let numVerticalGlyphVertices = 0; + let placedIconSymbolIndex = -1; + let verticalPlacedIconSymbolIndex = -1; + const placedTextSymbolIndices = {}; + let key = murmur3$1(''); + if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) { + const textRotation = layer.layout.get('text-rotate').evaluate(feature, {}, canonical); + const verticalTextRotation = textRotation + 90.0; + const verticalShaping = shapedTextOrientations.vertical; + verticalTextCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textBoxScale, textPadding, textAlongLine, verticalTextRotation); + if (verticallyShapedIcon) { + verticalIconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconBoxScale, iconPadding, textAlongLine, verticalTextRotation); + } + } + //Place icon first, so text can have a reference to its index in the placed symbol array. + //Text symbols can lazily shift at render-time because of variable anchor placement. + //If the style specifies an `icon-text-fit` then the icon would have to shift along with it. + // For more info check `updateVariableAnchors` in `draw_symbol.js` . + if (shapedIcon) { + const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {}); + const hasIconTextFit = layer.layout.get('icon-text-fit') !== 'none'; + const iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit); + const verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit) : undefined; + iconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconBoxScale, iconPadding, /*align boxes to line*/ false, iconRotate); + numIconVertices = iconQuads.length * 4; + const sizeData = bucket.iconSizeData; + let iconSizeData = null; + if (sizeData.kind === 'source') { + iconSizeData = [ + SIZE_PACK_FACTOR * layer.layout.get('icon-size').evaluate(feature, {}) + ]; + if (iconSizeData[0] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`); + } + } + else if (sizeData.kind === 'composite') { + iconSizeData = [ + SIZE_PACK_FACTOR * sizes.compositeIconSizes[0].evaluate(feature, {}, canonical), + SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical) + ]; + if (iconSizeData[0] > MAX_PACKED_SIZE || iconSizeData[1] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`); + } + } + bucket.addSymbols(bucket.icon, iconQuads, iconSizeData, iconOffset, iconAlongLine, feature, exports.WritingMode.none, anchor, lineArray.lineStartIndex, lineArray.lineLength, + // The icon itself does not have an associated symbol since the text isn't placed yet + -1, canonical); + placedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; + if (verticalIconQuads) { + numVerticalIconVertices = verticalIconQuads.length * 4; + bucket.addSymbols(bucket.icon, verticalIconQuads, iconSizeData, iconOffset, iconAlongLine, feature, exports.WritingMode.vertical, anchor, lineArray.lineStartIndex, lineArray.lineLength, + // The icon itself does not have an associated symbol since the text isn't placed yet + -1, canonical); + verticalPlacedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; + } + } + const justifications = Object.keys(shapedTextOrientations.horizontal); + for (const justification of justifications) { + const shaping = shapedTextOrientations.horizontal[justification]; + if (!textCollisionFeature) { + key = murmur3$1(shaping.text); + const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}, canonical); + // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature + // We're counting on all versions having similar dimensions + textCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textBoxScale, textPadding, textAlongLine, textRotate); + } + const singleLine = shaping.positionedLines.length === 1; + numHorizontalGlyphVertices += addTextVertices(bucket, anchor, shaping, imageMap, layer, textAlongLine, feature, textOffset, lineArray, shapedTextOrientations.vertical ? exports.WritingMode.horizontal : exports.WritingMode.horizontalOnly, singleLine ? justifications : [justification], placedTextSymbolIndices, placedIconSymbolIndex, sizes, canonical); + if (singleLine) { + break; + } + } + if (shapedTextOrientations.vertical) { + numVerticalGlyphVertices += addTextVertices(bucket, anchor, shapedTextOrientations.vertical, imageMap, layer, textAlongLine, feature, textOffset, lineArray, exports.WritingMode.vertical, ['vertical'], placedTextSymbolIndices, verticalPlacedIconSymbolIndex, sizes, canonical); + } + const textBoxStartIndex = textCollisionFeature ? textCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const textBoxEndIndex = textCollisionFeature ? textCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + const verticalTextBoxStartIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const verticalTextBoxEndIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + const iconBoxStartIndex = iconCollisionFeature ? iconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const iconBoxEndIndex = iconCollisionFeature ? iconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + const verticalIconBoxStartIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const verticalIconBoxEndIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + // Check if runtime collision circles should be used for any of the collision features. + // It is enough to choose the tallest feature shape as circles are always placed on a line. + // All measurements are in glyph metrics and later converted into pixels using proper font size "layoutTextSize" + let collisionCircleDiameter = -1; + const getCollisionCircleHeight = (feature, prevHeight) => { + if (feature && feature.circleDiameter) + return Math.max(feature.circleDiameter, prevHeight); + return prevHeight; + }; + collisionCircleDiameter = getCollisionCircleHeight(textCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(verticalTextCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(iconCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(verticalIconCollisionFeature, collisionCircleDiameter); + const useRuntimeCollisionCircles = (collisionCircleDiameter > -1) ? 1 : 0; + // Convert circle collision height into pixels + if (useRuntimeCollisionCircles) + collisionCircleDiameter *= layoutTextSize / ONE_EM; + if (bucket.glyphOffsetArray.length >= SymbolBucket.MAX_GLYPHS) + warnOnce('Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907'); + if (feature.sortKey !== undefined) { + bucket.addToSortKeyRanges(bucket.symbolInstances.length, feature.sortKey); + } + const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, canonical); + const [textAnchorOffsetStartIndex, textAnchorOffsetEndIndex] = addTextVariableAnchorOffsets(bucket.textAnchorOffsets, variableAnchorOffset); + bucket.symbolInstances.emplaceBack(anchor.x, anchor.y, placedTextSymbolIndices.right >= 0 ? placedTextSymbolIndices.right : -1, placedTextSymbolIndices.center >= 0 ? placedTextSymbolIndices.center : -1, placedTextSymbolIndices.left >= 0 ? placedTextSymbolIndices.left : -1, placedTextSymbolIndices.vertical || -1, placedIconSymbolIndex, verticalPlacedIconSymbolIndex, key, textBoxStartIndex, textBoxEndIndex, verticalTextBoxStartIndex, verticalTextBoxEndIndex, iconBoxStartIndex, iconBoxEndIndex, verticalIconBoxStartIndex, verticalIconBoxEndIndex, featureIndex, numHorizontalGlyphVertices, numVerticalGlyphVertices, numIconVertices, numVerticalIconVertices, useRuntimeCollisionCircles, 0, textBoxScale, collisionCircleDiameter, textAnchorOffsetStartIndex, textAnchorOffsetEndIndex); +} +function anchorIsTooClose(bucket, text, repeatDistance, anchor) { + const compareText = bucket.compareText; + if (!(text in compareText)) { + compareText[text] = []; + } + else { + const otherAnchors = compareText[text]; + for (let k = otherAnchors.length - 1; k >= 0; k--) { + if (anchor.dist(otherAnchors[k]) < repeatDistance) { + // If it's within repeatDistance of one anchor, stop looking + return true; + } + } + } + // If anchor is not within repeatDistance of any other anchor, add to array + compareText[text].push(anchor); + return false; +} + +const ARRAY_TYPES = [ + Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, + Int32Array, Uint32Array, Float32Array, Float64Array +]; + +/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */ + +const VERSION = 1; // serialized format version +const HEADER_SIZE = 8; + +class KDBush { + + /** + * Creates an index from raw `ArrayBuffer` data. + * @param {ArrayBuffer} data + */ + static from(data) { + if (!(data instanceof ArrayBuffer)) { + throw new Error('Data must be an instance of ArrayBuffer.'); + } + const [magic, versionAndType] = new Uint8Array(data, 0, 2); + if (magic !== 0xdb) { + throw new Error('Data does not appear to be in a KDBush format.'); + } + const version = versionAndType >> 4; + if (version !== VERSION) { + throw new Error(`Got v${version} data when expected v${VERSION}.`); + } + const ArrayType = ARRAY_TYPES[versionAndType & 0x0f]; + if (!ArrayType) { + throw new Error('Unrecognized array type.'); + } + const [nodeSize] = new Uint16Array(data, 2, 1); + const [numItems] = new Uint32Array(data, 4, 1); + + return new KDBush(numItems, nodeSize, ArrayType, data); + } + + /** + * Creates an index that will hold a given number of items. + * @param {number} numItems + * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default). + * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default). + * @param {ArrayBuffer} [data] (For internal use only) + */ + constructor(numItems, nodeSize = 64, ArrayType = Float64Array, data) { + if (isNaN(numItems) || numItems < 0) throw new Error(`Unpexpected numItems value: ${numItems}.`); + + this.numItems = +numItems; + this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535); + this.ArrayType = ArrayType; + this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array; + + const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType); + const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT; + const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT; + const padCoords = (8 - idsByteSize % 8) % 8; + + if (arrayTypeIndex < 0) { + throw new Error(`Unexpected typed array class: ${ArrayType}.`); + } + + if (data && (data instanceof ArrayBuffer)) { // reconstruct an index from a buffer + this.data = data; + this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems); + this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2); + this._pos = numItems * 2; + this._finished = true; + } else { // initialize a new index + this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords); + this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems); + this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2); + this._pos = 0; + this._finished = false; + + // set header + new Uint8Array(this.data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]); + new Uint16Array(this.data, 2, 1)[0] = nodeSize; + new Uint32Array(this.data, 4, 1)[0] = numItems; + } + } + + /** + * Add a point to the index. + * @param {number} x + * @param {number} y + * @returns {number} An incremental index associated with the added item (starting from `0`). + */ + add(x, y) { + const index = this._pos >> 1; + this.ids[index] = index; + this.coords[this._pos++] = x; + this.coords[this._pos++] = y; + return index; + } + + /** + * Perform indexing of the added points. + */ + finish() { + const numAdded = this._pos >> 1; + if (numAdded !== this.numItems) { + throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`); + } + // kd-sort both arrays for efficient search + sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0); + + this._finished = true; + return this; + } + + /** + * Search the index for items within a given bounding box. + * @param {number} minX + * @param {number} minY + * @param {number} maxX + * @param {number} maxY + * @returns {number[]} An array of indices correponding to the found items. + */ + range(minX, minY, maxX, maxY) { + if (!this._finished) throw new Error('Data not yet indexed - call index.finish().'); + + const {ids, coords, nodeSize} = this; + const stack = [0, ids.length - 1, 0]; + const result = []; + + // recursively search for items in range in the kd-sorted arrays + while (stack.length) { + const axis = stack.pop() || 0; + const right = stack.pop() || 0; + const left = stack.pop() || 0; + + // if we reached "tree node", search linearly + if (right - left <= nodeSize) { + for (let i = left; i <= right; i++) { + const x = coords[2 * i]; + const y = coords[2 * i + 1]; + if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]); + } + continue; + } + + // otherwise find the middle index + const m = (left + right) >> 1; + + // include the middle item if it's in range + const x = coords[2 * m]; + const y = coords[2 * m + 1]; + if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]); + + // queue search in halves that intersect the query + if (axis === 0 ? minX <= x : minY <= y) { + stack.push(left); + stack.push(m - 1); + stack.push(1 - axis); + } + if (axis === 0 ? maxX >= x : maxY >= y) { + stack.push(m + 1); + stack.push(right); + stack.push(1 - axis); + } + } + + return result; + } + + /** + * Search the index for items within a given radius. + * @param {number} qx + * @param {number} qy + * @param {number} r Query radius. + * @returns {number[]} An array of indices correponding to the found items. + */ + within(qx, qy, r) { + if (!this._finished) throw new Error('Data not yet indexed - call index.finish().'); + + const {ids, coords, nodeSize} = this; + const stack = [0, ids.length - 1, 0]; + const result = []; + const r2 = r * r; + + // recursively search for items within radius in the kd-sorted arrays + while (stack.length) { + const axis = stack.pop() || 0; + const right = stack.pop() || 0; + const left = stack.pop() || 0; + + // if we reached "tree node", search linearly + if (right - left <= nodeSize) { + for (let i = left; i <= right; i++) { + if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]); + } + continue; + } + + // otherwise find the middle index + const m = (left + right) >> 1; + + // include the middle item if it's in range + const x = coords[2 * m]; + const y = coords[2 * m + 1]; + if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]); + + // queue search in halves that intersect the query + if (axis === 0 ? qx - r <= x : qy - r <= y) { + stack.push(left); + stack.push(m - 1); + stack.push(1 - axis); + } + if (axis === 0 ? qx + r >= x : qy + r >= y) { + stack.push(m + 1); + stack.push(right); + stack.push(1 - axis); + } + } + + return result; + } +} + +/** + * @param {Uint16Array | Uint32Array} ids + * @param {InstanceType} coords + * @param {number} nodeSize + * @param {number} left + * @param {number} right + * @param {number} axis + */ +function sort(ids, coords, nodeSize, left, right, axis) { + if (right - left <= nodeSize) return; + + const m = (left + right) >> 1; // middle index + + // sort ids and coords around the middle index so that the halves lie + // either left/right or top/bottom correspondingly (taking turns) + select(ids, coords, m, left, right, axis); + + // recursively kd-sort first half and second half on the opposite axis + sort(ids, coords, nodeSize, left, m - 1, 1 - axis); + sort(ids, coords, nodeSize, m + 1, right, 1 - axis); +} + +/** + * Custom Floyd-Rivest selection algorithm: sort ids and coords so that + * [left..k-1] items are smaller than k-th item (on either x or y axis) + * @param {Uint16Array | Uint32Array} ids + * @param {InstanceType} coords + * @param {number} k + * @param {number} left + * @param {number} right + * @param {number} axis + */ +function select(ids, coords, k, left, right, axis) { + + while (right > left) { + if (right - left > 600) { + const n = right - left + 1; + const m = k - left + 1; + const z = Math.log(n); + const s = 0.5 * Math.exp(2 * z / 3); + const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + const newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + select(ids, coords, k, newLeft, newRight, axis); + } + + const t = coords[2 * k + axis]; + let i = left; + let j = right; + + swapItem(ids, coords, left, k); + if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right); + + while (i < j) { + swapItem(ids, coords, i, j); + i++; + j--; + while (coords[2 * i + axis] < t) i++; + while (coords[2 * j + axis] > t) j--; + } + + if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j); + else { + j++; + swapItem(ids, coords, j, right); + } + + if (j <= k) left = j + 1; + if (k <= j) right = j - 1; + } +} + +/** + * @param {Uint16Array | Uint32Array} ids + * @param {InstanceType} coords + * @param {number} i + * @param {number} j + */ +function swapItem(ids, coords, i, j) { + swap(ids, i, j); + swap(coords, 2 * i, 2 * j); + swap(coords, 2 * i + 1, 2 * j + 1); +} + +/** + * @param {InstanceType} arr + * @param {number} i + * @param {number} j + */ +function swap(arr, i, j) { + const tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} + +/** + * @param {number} ax + * @param {number} ay + * @param {number} bx + * @param {number} by + */ +function sqDist(ax, ay, bx, by) { + const dx = ax - bx; + const dy = ay - by; + return dx * dx + dy * dy; +} + +exports.PerformanceMarkers = void 0; +(function (PerformanceMarkers) { + PerformanceMarkers["create"] = "create"; + PerformanceMarkers["load"] = "load"; + PerformanceMarkers["fullLoad"] = "fullLoad"; +})(exports.PerformanceMarkers || (exports.PerformanceMarkers = {})); +let lastFrameTime = null; +let frameTimes = []; +const minFramerateTarget = 60; +const frameTimeTarget = 1000 / minFramerateTarget; +const loadTimeKey = 'loadTime'; +const fullLoadTimeKey = 'fullLoadTime'; +const PerformanceUtils = { + mark(marker) { + performance.mark(marker); + }, + frame(timestamp) { + const currTimestamp = timestamp; + if (lastFrameTime != null) { + const frameTime = currTimestamp - lastFrameTime; + frameTimes.push(frameTime); + } + lastFrameTime = currTimestamp; + }, + clearMetrics() { + lastFrameTime = null; + frameTimes = []; + performance.clearMeasures(loadTimeKey); + performance.clearMeasures(fullLoadTimeKey); + for (const marker in exports.PerformanceMarkers) { + performance.clearMarks(exports.PerformanceMarkers[marker]); + } + }, + getPerformanceMetrics() { + performance.measure(loadTimeKey, exports.PerformanceMarkers.create, exports.PerformanceMarkers.load); + performance.measure(fullLoadTimeKey, exports.PerformanceMarkers.create, exports.PerformanceMarkers.fullLoad); + const loadTime = performance.getEntriesByName(loadTimeKey)[0].duration; + const fullLoadTime = performance.getEntriesByName(fullLoadTimeKey)[0].duration; + const totalFrames = frameTimes.length; + const avgFrameTime = frameTimes.reduce((prev, curr) => prev + curr, 0) / totalFrames / 1000; + const fps = 1 / avgFrameTime; + // count frames that missed our framerate target + const droppedFrames = frameTimes + .filter((frameTime) => frameTime > frameTimeTarget) + .reduce((acc, curr) => { + return acc + (curr - frameTimeTarget) / frameTimeTarget; + }, 0); + const percentDroppedFrames = (droppedFrames / (totalFrames + droppedFrames)) * 100; + return { + loadTime, + fullLoadTime, + fps, + percentDroppedFrames, + totalFrames + }; + } +}; +/** + * @internal + * Safe wrapper for the performance resource timing API in web workers with graceful degradation + */ +class RequestPerformance { + constructor(request) { + this._marks = { + start: [request.url, 'start'].join('#'), + end: [request.url, 'end'].join('#'), + measure: request.url.toString() + }; + performance.mark(this._marks.start); + } + finish() { + performance.mark(this._marks.end); + let resourceTimingData = performance.getEntriesByName(this._marks.measure); + // fallback if web worker implementation of perf.getEntriesByName returns empty + if (resourceTimingData.length === 0) { + performance.measure(this._marks.measure, this._marks.start, this._marks.end); + resourceTimingData = performance.getEntriesByName(this._marks.measure); + // cleanup + performance.clearMarks(this._marks.start); + performance.clearMarks(this._marks.end); + performance.clearMeasures(this._marks.measure); + } + return resourceTimingData; + } +} +var performance$1 = performance; + +exports.AJAXError = AJAXError; +exports.Actor = Actor; +exports.AlphaImage = AlphaImage; +exports.CanonicalTileID = CanonicalTileID; +exports.CollisionBoxArray = CollisionBoxArray; +exports.CollisionCircleLayoutArray = CollisionCircleLayoutArray; +exports.Color = Color; +exports.DEMData = DEMData; +exports.DataConstantProperty = DataConstantProperty; +exports.DictionaryCoder = DictionaryCoder; +exports.EXTENT = EXTENT; +exports.ErrorEvent = ErrorEvent; +exports.EvaluationParameters = EvaluationParameters; +exports.Event = Event; +exports.Evented = Evented; +exports.FeatureIndex = FeatureIndex; +exports.FillBucket = FillBucket; +exports.FillExtrusionBucket = FillExtrusionBucket; +exports.GLOBAL_DISPATCHER_ID = GLOBAL_DISPATCHER_ID; +exports.GeoJSONFeature = GeoJSONFeature; +exports.HEATMAP_FULL_RENDER_FBO_KEY = HEATMAP_FULL_RENDER_FBO_KEY; +exports.ImageAtlas = ImageAtlas; +exports.ImagePosition = ImagePosition; +exports.KDBush = KDBush; +exports.LineBucket = LineBucket; +exports.LineStripIndexArray = LineStripIndexArray; +exports.LngLat = LngLat; +exports.MercatorCoordinate = MercatorCoordinate; +exports.ONE_EM = ONE_EM; +exports.OverscaledTileID = OverscaledTileID; +exports.PerformanceUtils = PerformanceUtils; +exports.Point = Point$2; +exports.Pos3dArray = Pos3dArray; +exports.PosArray = PosArray; +exports.Properties = Properties; +exports.Protobuf = Protobuf; +exports.QuadTriangleArray = QuadTriangleArray; +exports.RGBAImage = RGBAImage; +exports.RasterBoundsArray = RasterBoundsArray; +exports.RequestPerformance = RequestPerformance; +exports.SegmentVector = SegmentVector; +exports.SymbolBucket = SymbolBucket; +exports.Transitionable = Transitionable; +exports.TriangleIndexArray = TriangleIndexArray; +exports.Uniform1f = Uniform1f; +exports.Uniform1i = Uniform1i; +exports.Uniform2f = Uniform2f; +exports.Uniform3f = Uniform3f; +exports.Uniform4f = Uniform4f; +exports.UniformColor = UniformColor; +exports.UniformMatrix4f = UniformMatrix4f; +exports.UnwrappedTileID = UnwrappedTileID; +exports.ValidationError = ValidationError; +exports.ZoomHistory = ZoomHistory; +exports.__awaiter = __awaiter; +exports.add = add$4; +exports.addDynamicAttributes = addDynamicAttributes; +exports.addProtocol = addProtocol; +exports.arrayBufferToImage = arrayBufferToImage; +exports.arrayBufferToImageBitmap = arrayBufferToImageBitmap; +exports.bezier = bezier$1; +exports.clamp = clamp$1; +exports.clipLine = clipLine; +exports.clone = clone$5; +exports.clone$1 = clone$9; +exports.clone$2 = clone$4; +exports.collisionCircleLayout = collisionCircleLayout; +exports.config = config; +exports.copy = copy$5; +exports.create = create$5; +exports.create$1 = create$6; +exports.create$2 = create$8; +exports.createAbortError = createAbortError; +exports.createExpression = createExpression; +exports.createFilter = createFilter; +exports.createLayout = createLayout; +exports.createStyleLayer = createStyleLayer; +exports.cross = cross$2; +exports.deepEqual = deepEqual$1; +exports.defaultEasing = defaultEasing; +exports.degreesToRadians = degreesToRadians; +exports.derefLayers = derefLayers; +exports.diffStyles = diffStyles; +exports.dot = dot$5; +exports.dot$1 = dot$4; +exports.earthRadius = earthRadius; +exports.emitValidationErrors = emitValidationErrors; +exports.emptyStyle = emptyStyle; +exports.equals = equals$6; +exports.evaluateSizeForFeature = evaluateSizeForFeature; +exports.evaluateSizeForZoom = evaluateSizeForZoom; +exports.exactEquals = exactEquals$5; +exports.extend = extend; +exports.filterObject = filterObject; +exports.findLineIntersection = findLineIntersection; +exports.fromRotation = fromRotation$2; +exports.fromScaling = fromScaling; +exports.getAABB = getAABB; +exports.getAnchorAlignment = getAnchorAlignment; +exports.getAnchorJustification = getAnchorJustification; +exports.getArrayBuffer = getArrayBuffer; +exports.getDefaultExportFromCjs = getDefaultExportFromCjs$1; +exports.getImageData = getImageData; +exports.getJSON = getJSON; +exports.getOverlapMode = getOverlapMode; +exports.getProtocol = getProtocol; +exports.getReferrer = getReferrer; +exports.getVideo = getVideo; +exports.groupByLayout = groupByLayout; +exports.identity = identity$2; +exports.interpolate = interpolate; +exports.invert = invert$2; +exports.isAbortError = isAbortError; +exports.isImageBitmap = isImageBitmap; +exports.isInBoundsForZoomLngLat = isInBoundsForZoomLngLat; +exports.isOffscreenCanvasDistorted = isOffscreenCanvasDistorted; +exports.isSafari = isSafari; +exports.isWorker = isWorker; +exports.keysDifference = keysDifference; +exports.makeRequest = makeRequest; +exports.mapObject = mapObject; +exports.mercatorXfromLng = mercatorXfromLng; +exports.mercatorYfromLat = mercatorYfromLat; +exports.mercatorZfromAltitude = mercatorZfromAltitude; +exports.mul = mul$5; +exports.mul$1 = mul$3; +exports.multiply = multiply$5; +exports.nextPowerOfTwo = nextPowerOfTwo; +exports.normalize = normalize$4; +exports.offscreenCanvasSupported = offscreenCanvasSupported; +exports.ortho = ortho; +exports.parseCacheControl = parseCacheControl; +exports.parseGlyphPbf = parseGlyphPbf; +exports.pbf = pbf; +exports.performSymbolLayout = performSymbolLayout; +exports.perspective = perspective; +exports.pick = pick; +exports.pointGeometry = pointGeometry; +exports.polygonIntersectsPolygon = polygonIntersectsPolygon; +exports.potpack = potpack; +exports.readImageUsingVideoFrame = readImageUsingVideoFrame; +exports.register = register; +exports.removeProtocol = removeProtocol; +exports.renderColorRamp = renderColorRamp; +exports.rotate = rotate$4; +exports.rotateX = rotateX$3; +exports.rotateZ = rotateZ$3; +exports.rtlWorkerPlugin = rtlWorkerPlugin; +exports.sameOrigin = sameOrigin; +exports.scale = scale$5; +exports.scale$1 = scale$4; +exports.sphericalToCartesian = sphericalToCartesian; +exports.sqrLen = sqrLen; +exports.sub = sub$2; +exports.toEvaluationFeature = toEvaluationFeature; +exports.transformMat3 = transformMat3$1; +exports.transformMat4 = transformMat4$1; +exports.transformMat4$1 = transformMat4; +exports.translate = translate$1; +exports.uniqueId = uniqueId; +exports.v8Spec = v8Spec; +exports.validateCustomStyleLayer = validateCustomStyleLayer; +exports.validateLight = validateLight; +exports.validateSky = validateSky; +exports.validateStyle = validateStyle; +exports.vectorTile = vectorTile; +exports.warnOnce = warnOnce; +exports.wrap = wrap; + +})); + +define('worker', ['./shared'], (function (performance) { 'use strict'; + +class StyleLayerIndex { + constructor(layerConfigs) { + this.keyCache = {}; + if (layerConfigs) { + this.replace(layerConfigs); + } + } + replace(layerConfigs) { + this._layerConfigs = {}; + this._layers = {}; + this.update(layerConfigs, []); + } + update(layerConfigs, removedIds) { + for (const layerConfig of layerConfigs) { + this._layerConfigs[layerConfig.id] = layerConfig; + const layer = this._layers[layerConfig.id] = performance.createStyleLayer(layerConfig); + layer._featureFilter = performance.createFilter(layer.filter); + if (this.keyCache[layerConfig.id]) + delete this.keyCache[layerConfig.id]; + } + for (const id of removedIds) { + delete this.keyCache[id]; + delete this._layerConfigs[id]; + delete this._layers[id]; + } + this.familiesBySource = {}; + const groups = performance.groupByLayout(Object.values(this._layerConfigs), this.keyCache); + for (const layerConfigs of groups) { + const layers = layerConfigs.map((layerConfig) => this._layers[layerConfig.id]); + const layer = layers[0]; + if (layer.visibility === 'none') { + continue; + } + const sourceId = layer.source || ''; + let sourceGroup = this.familiesBySource[sourceId]; + if (!sourceGroup) { + sourceGroup = this.familiesBySource[sourceId] = {}; + } + const sourceLayerId = layer.sourceLayer || '_geojsonTileLayer'; + let sourceLayerFamilies = sourceGroup[sourceLayerId]; + if (!sourceLayerFamilies) { + sourceLayerFamilies = sourceGroup[sourceLayerId] = []; + } + sourceLayerFamilies.push(layers); + } + } +} + +const padding = 1; +class GlyphAtlas { + constructor(stacks) { + const positions = {}; + const bins = []; + for (const stack in stacks) { + const glyphs = stacks[stack]; + const stackPositions = positions[stack] = {}; + for (const id in glyphs) { + const src = glyphs[+id]; + if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) + continue; + const bin = { + x: 0, + y: 0, + w: src.bitmap.width + 2 * padding, + h: src.bitmap.height + 2 * padding + }; + bins.push(bin); + stackPositions[id] = { rect: bin, metrics: src.metrics }; + } + } + const { w, h } = performance.potpack(bins); + const image = new performance.AlphaImage({ width: w || 1, height: h || 1 }); + for (const stack in stacks) { + const glyphs = stacks[stack]; + for (const id in glyphs) { + const src = glyphs[+id]; + if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) + continue; + const bin = positions[stack][id].rect; + performance.AlphaImage.copy(src.bitmap, image, { x: 0, y: 0 }, { x: bin.x + padding, y: bin.y + padding }, src.bitmap); + } + } + this.image = image; + this.positions = positions; + } +} +performance.register('GlyphAtlas', GlyphAtlas); + +class WorkerTile { + constructor(params) { + this.tileID = new performance.OverscaledTileID(params.tileID.overscaledZ, params.tileID.wrap, params.tileID.canonical.z, params.tileID.canonical.x, params.tileID.canonical.y); + this.uid = params.uid; + this.zoom = params.zoom; + this.pixelRatio = params.pixelRatio; + this.tileSize = params.tileSize; + this.source = params.source; + this.overscaling = this.tileID.overscaleFactor(); + this.showCollisionBoxes = params.showCollisionBoxes; + this.collectResourceTiming = !!params.collectResourceTiming; + this.returnDependencies = !!params.returnDependencies; + this.promoteId = params.promoteId; + this.inFlightDependencies = []; + } + parse(data, layerIndex, availableImages, actor) { + return performance.__awaiter(this, void 0, void 0, function* () { + this.status = 'parsing'; + this.data = data; + this.collisionBoxArray = new performance.CollisionBoxArray(); + const sourceLayerCoder = new performance.DictionaryCoder(Object.keys(data.layers).sort()); + const featureIndex = new performance.FeatureIndex(this.tileID, this.promoteId); + featureIndex.bucketLayerIDs = []; + const buckets = {}; + const options = { + featureIndex, + iconDependencies: {}, + patternDependencies: {}, + glyphDependencies: {}, + availableImages + }; + const layerFamilies = layerIndex.familiesBySource[this.source]; + for (const sourceLayerId in layerFamilies) { + const sourceLayer = data.layers[sourceLayerId]; + if (!sourceLayer) { + continue; + } + if (sourceLayer.version === 1) { + performance.warnOnce(`Vector tile source "${this.source}" layer "${sourceLayerId}" ` + + 'does not use vector tile spec v2 and therefore may have some rendering errors.'); + } + const sourceLayerIndex = sourceLayerCoder.encode(sourceLayerId); + const features = []; + for (let index = 0; index < sourceLayer.length; index++) { + const feature = sourceLayer.feature(index); + const id = featureIndex.getId(feature, sourceLayerId); + features.push({ feature, id, index, sourceLayerIndex }); + } + for (const family of layerFamilies[sourceLayerId]) { + const layer = family[0]; + if (layer.source !== this.source) { + performance.warnOnce(`layer.source = ${layer.source} does not equal this.source = ${this.source}`); + } + if (layer.minzoom && this.zoom < Math.floor(layer.minzoom)) + continue; + if (layer.maxzoom && this.zoom >= layer.maxzoom) + continue; + if (layer.visibility === 'none') + continue; + recalculateLayers(family, this.zoom, availableImages); + const bucket = buckets[layer.id] = layer.createBucket({ + index: featureIndex.bucketLayerIDs.length, + layers: family, + zoom: this.zoom, + pixelRatio: this.pixelRatio, + overscaling: this.overscaling, + collisionBoxArray: this.collisionBoxArray, + sourceLayerIndex, + sourceID: this.source + }); + bucket.populate(features, options, this.tileID.canonical); + featureIndex.bucketLayerIDs.push(family.map((l) => l.id)); + } + } + // options.glyphDependencies looks like: {"SomeFontName":{"10":true,"32":true}} + // this line makes an object like: {"SomeFontName":[10,32]} + const stacks = performance.mapObject(options.glyphDependencies, (glyphs) => Object.keys(glyphs).map(Number)); + this.inFlightDependencies.forEach((request) => request === null || request === void 0 ? void 0 : request.abort()); + this.inFlightDependencies = []; + let getGlyphsPromise = Promise.resolve({}); + if (Object.keys(stacks).length) { + const abortController = new AbortController(); + this.inFlightDependencies.push(abortController); + getGlyphsPromise = actor.sendAsync({ type: "GG" /* MessageType.getGlyphs */, data: { stacks, source: this.source, tileID: this.tileID, type: 'glyphs' } }, abortController); + } + const icons = Object.keys(options.iconDependencies); + let getIconsPromise = Promise.resolve({}); + let getIconBackgroundsPromise = Promise.resolve({}); + if (icons.length) { + const abortController = new AbortController(); + this.inFlightDependencies.push(abortController); + getIconsPromise = actor.sendAsync({ type: "GI" /* MessageType.getImages */, data: { icons, source: this.source, tileID: this.tileID, type: 'icons' } }, abortController); + // If there are MSDF icons we also need to add the background + const msdfIcons = icons.filter(i => i.includes('msdf')); + const backgroundIcons = msdfIcons.map(i => i.replace('msdf', 'msdf-backgrounds')); + if (backgroundIcons.length) { + getIconBackgroundsPromise = actor.sendAsync({ type: "GI" /* MessageType.getImages */, data: { icons: backgroundIcons, source: this.source, tileID: this.tileID, type: 'icons' } }, abortController); + } + } + const patterns = Object.keys(options.patternDependencies); + let getPatternsPromise = Promise.resolve({}); + if (patterns.length) { + const abortController = new AbortController(); + this.inFlightDependencies.push(abortController); + getPatternsPromise = actor.sendAsync({ type: "GI" /* MessageType.getImages */, data: { icons: patterns, source: this.source, tileID: this.tileID, type: 'patterns' } }, abortController); + } + const [glyphMap, iconMap, iconBackgroundsMap, patternMap] = yield Promise.all([getGlyphsPromise, getIconsPromise, getIconBackgroundsPromise, getPatternsPromise]); + const glyphAtlas = new GlyphAtlas(glyphMap); + const imageAtlas = new performance.ImageAtlas(iconMap, patternMap); + const imageBackgroundsAtlas = new performance.ImageAtlas(iconBackgroundsMap, {}); + for (const key in buckets) { + const bucket = buckets[key]; + if (bucket instanceof performance.SymbolBucket) { + recalculateLayers(bucket.layers, this.zoom, availableImages); + performance.performSymbolLayout({ + bucket, + glyphMap, + glyphPositions: glyphAtlas.positions, + imageMap: iconMap, + imagePositions: imageAtlas.iconPositions, + showCollisionBoxes: this.showCollisionBoxes, + canonical: this.tileID.canonical + }); + } + else if (bucket.hasPattern && + (bucket instanceof performance.LineBucket || + bucket instanceof performance.FillBucket || + bucket instanceof performance.FillExtrusionBucket)) { + recalculateLayers(bucket.layers, this.zoom, availableImages); + bucket.addFeatures(options, this.tileID.canonical, imageAtlas.patternPositions); + } + } + this.status = 'done'; + return { + buckets: Object.values(buckets).filter(b => !b.isEmpty()), + featureIndex, + collisionBoxArray: this.collisionBoxArray, + glyphAtlasImage: glyphAtlas.image, + imageAtlas, + imageBackgroundsAtlas, + // Only used for benchmarking: + glyphMap: this.returnDependencies ? glyphMap : null, + iconMap: this.returnDependencies ? iconMap : null, + glyphPositions: this.returnDependencies ? glyphAtlas.positions : null + }; + }); + } +} +function recalculateLayers(layers, zoom, availableImages) { + // Layers are shared and may have been used by a WorkerTile with a different zoom. + const parameters = new performance.EvaluationParameters(zoom); + for (const layer of layers) { + layer.recalculate(parameters, availableImages); + } +} + +/** + * The {@link WorkerSource} implementation that supports {@link VectorTileSource}. + * This class is designed to be easily reused to support custom source types + * for data formats that can be parsed/converted into an in-memory VectorTile + * representation. To do so, override its `loadVectorTile` method. + */ +class VectorTileWorkerSource { + /** + * @param loadVectorData - Optional method for custom loading of a VectorTile + * object based on parameters passed from the main-thread Source. See + * {@link VectorTileWorkerSource#loadTile}. The default implementation simply + * loads the pbf at `params.url`. + */ + constructor(actor, layerIndex, availableImages) { + this.actor = actor; + this.layerIndex = layerIndex; + this.availableImages = availableImages; + this.fetching = {}; + this.loading = {}; + this.loaded = {}; + } + /** + * Loads a vector tile + */ + loadVectorTile(params, abortController) { + return performance.__awaiter(this, void 0, void 0, function* () { + const response = yield performance.getArrayBuffer(params.request, abortController); + try { + const vectorTile = new performance.vectorTile.VectorTile(new performance.Protobuf(response.data)); + return { + vectorTile, + rawData: response.data, + cacheControl: response.cacheControl, + expires: response.expires + }; + } + catch (ex) { + const bytes = new Uint8Array(response.data); + const isGzipped = bytes[0] === 0x1f && bytes[1] === 0x8b; + let errorMessage = `Unable to parse the tile at ${params.request.url}, `; + if (isGzipped) { + errorMessage += 'please make sure the data is not gzipped and that you have configured the relevant header in the server'; + } + else { + errorMessage += `got error: ${ex.message}`; + } + throw new Error(errorMessage); + } + }); + } + /** + * Implements {@link WorkerSource#loadTile}. Delegates to + * {@link VectorTileWorkerSource#loadVectorData} (which by default expects + * a `params.url` property) for fetching and producing a VectorTile object. + */ + loadTile(params) { + return performance.__awaiter(this, void 0, void 0, function* () { + const tileUid = params.uid; + const perf = (params && params.request && params.request.collectResourceTiming) ? + new performance.RequestPerformance(params.request) : false; + const workerTile = new WorkerTile(params); + this.loading[tileUid] = workerTile; + const abortController = new AbortController(); + workerTile.abort = abortController; + try { + const response = yield this.loadVectorTile(params, abortController); + delete this.loading[tileUid]; + if (!response) { + return null; + } + const rawTileData = response.rawData; + const cacheControl = {}; + if (response.expires) + cacheControl.expires = response.expires; + if (response.cacheControl) + cacheControl.cacheControl = response.cacheControl; + const resourceTiming = {}; + if (perf) { + const resourceTimingData = perf.finish(); + // it's necessary to eval the result of getEntriesByName() here via parse/stringify + // late evaluation in the main thread causes TypeError: illegal invocation + if (resourceTimingData) + resourceTiming.resourceTiming = JSON.parse(JSON.stringify(resourceTimingData)); + } + workerTile.vectorTile = response.vectorTile; + const parsePromise = workerTile.parse(response.vectorTile, this.layerIndex, this.availableImages, this.actor); + this.loaded[tileUid] = workerTile; + // keep the original fetching state so that reload tile can pick it up if the original parse is cancelled by reloads' parse + this.fetching[tileUid] = { rawTileData, cacheControl, resourceTiming }; + try { + const result = yield parsePromise; + // Transferring a copy of rawTileData because the worker needs to retain its copy. + return performance.extend({ rawTileData: rawTileData.slice(0) }, result, cacheControl, resourceTiming); + } + finally { + delete this.fetching[tileUid]; + } + } + catch (err) { + delete this.loading[tileUid]; + workerTile.status = 'done'; + this.loaded[tileUid] = workerTile; + throw err; + } + }); + } + /** + * Implements {@link WorkerSource#reloadTile}. + */ + reloadTile(params) { + return performance.__awaiter(this, void 0, void 0, function* () { + const uid = params.uid; + if (!this.loaded || !this.loaded[uid]) { + throw new Error('Should not be trying to reload a tile that was never loaded or has been removed'); + } + const workerTile = this.loaded[uid]; + workerTile.showCollisionBoxes = params.showCollisionBoxes; + if (workerTile.status === 'parsing') { + const result = yield workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor); + // if we have cancelled the original parse, make sure to pass the rawTileData from the original fetch + let parseResult; + if (this.fetching[uid]) { + const { rawTileData, cacheControl, resourceTiming } = this.fetching[uid]; + delete this.fetching[uid]; + parseResult = performance.extend({ rawTileData: rawTileData.slice(0) }, result, cacheControl, resourceTiming); + } + else { + parseResult = result; + } + return parseResult; + } + // if there was no vector tile data on the initial load, don't try and re-parse tile + if (workerTile.status === 'done' && workerTile.vectorTile) { + // this seems like a missing case where cache control is lost? see #3309 + return workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor); + } + }); + } + /** + * Implements {@link WorkerSource#abortTile}. + */ + abortTile(params) { + return performance.__awaiter(this, void 0, void 0, function* () { + const loading = this.loading; + const uid = params.uid; + if (loading && loading[uid] && loading[uid].abort) { + loading[uid].abort.abort(); + delete loading[uid]; + } + }); + } + /** + * Implements {@link WorkerSource#removeTile}. + */ + removeTile(params) { + return performance.__awaiter(this, void 0, void 0, function* () { + if (this.loaded && this.loaded[params.uid]) { + delete this.loaded[params.uid]; + } + }); + } +} + +class RasterDEMTileWorkerSource { + constructor() { + this.loaded = {}; + } + loadTile(params) { + return performance.__awaiter(this, void 0, void 0, function* () { + const { uid, encoding, rawImageData, redFactor, greenFactor, blueFactor, baseShift } = params; + const width = rawImageData.width + 2; + const height = rawImageData.height + 2; + const imagePixels = performance.isImageBitmap(rawImageData) ? + new performance.RGBAImage({ width, height }, yield performance.getImageData(rawImageData, -1, -1, width, height)) : + rawImageData; + const dem = new performance.DEMData(uid, imagePixels, encoding, redFactor, greenFactor, blueFactor, baseShift); + this.loaded = this.loaded || {}; + this.loaded[uid] = dem; + return dem; + }); + } + removeTile(params) { + const loaded = this.loaded, uid = params.uid; + if (loaded && loaded[uid]) { + delete loaded[uid]; + } + } +} + +var geojsonRewind = rewind$1; + +function rewind$1(gj, outer) { + var type = gj && gj.type, i; + + if (type === 'FeatureCollection') { + for (i = 0; i < gj.features.length; i++) rewind$1(gj.features[i], outer); + + } else if (type === 'GeometryCollection') { + for (i = 0; i < gj.geometries.length; i++) rewind$1(gj.geometries[i], outer); + + } else if (type === 'Feature') { + rewind$1(gj.geometry, outer); + + } else if (type === 'Polygon') { + rewindRings(gj.coordinates, outer); + + } else if (type === 'MultiPolygon') { + for (i = 0; i < gj.coordinates.length; i++) rewindRings(gj.coordinates[i], outer); + } + + return gj; +} + +function rewindRings(rings, outer) { + if (rings.length === 0) return; + + rewindRing(rings[0], outer); + for (var i = 1; i < rings.length; i++) { + rewindRing(rings[i], !outer); + } +} + +function rewindRing(ring, dir) { + var area = 0, err = 0; + for (var i = 0, len = ring.length, j = len - 1; i < len; j = i++) { + var k = (ring[i][0] - ring[j][0]) * (ring[j][1] + ring[i][1]); + var m = area + k; + err += Math.abs(area) >= Math.abs(k) ? area - m + k : k - m + area; + area = m; + } + if (area + err >= 0 !== !!dir) ring.reverse(); +} + +var rewind$2 = /*@__PURE__*/performance.getDefaultExportFromCjs(geojsonRewind); + +const toGeoJSON = performance.vectorTile.VectorTileFeature.prototype.toGeoJSON; +let FeatureWrapper$1 = class FeatureWrapper { + constructor(feature) { + this._feature = feature; + this.extent = performance.EXTENT; + this.type = feature.type; + this.properties = feature.tags; + // If the feature has a top-level `id` property, copy it over, but only + // if it can be coerced to an integer, because this wrapper is used for + // serializing geojson feature data into vector tile PBF data, and the + // vector tile spec only supports integer values for feature ids -- + // allowing non-integer values here results in a non-compliant PBF + // that causes an exception when it is parsed with vector-tile-js + if ('id' in feature && !isNaN(feature.id)) { + this.id = parseInt(feature.id, 10); + } + } + loadGeometry() { + if (this._feature.type === 1) { + const geometry = []; + for (const point of this._feature.geometry) { + geometry.push([new performance.Point(point[0], point[1])]); + } + return geometry; + } + else { + const geometry = []; + for (const ring of this._feature.geometry) { + const newRing = []; + for (const point of ring) { + newRing.push(new performance.Point(point[0], point[1])); + } + geometry.push(newRing); + } + return geometry; + } + } + toGeoJSON(x, y, z) { + return toGeoJSON.call(this, x, y, z); + } +}; +let GeoJSONWrapper$2 = class GeoJSONWrapper { + constructor(features) { + this.layers = { '_geojsonTileLayer': this }; + this.name = '_geojsonTileLayer'; + this.extent = performance.EXTENT; + this.length = features.length; + this._features = features; + } + feature(i) { + return new FeatureWrapper$1(this._features[i]); + } +}; + +var vtPbf$1 = {exports: {}}; + +'use strict'; + +var Point = performance.pointGeometry; +var VectorTileFeature = performance.vectorTile.VectorTileFeature; + +var geojson_wrapper = GeoJSONWrapper$1; + +// conform to vectortile api +function GeoJSONWrapper$1 (features, options) { + this.options = options || {}; + this.features = features; + this.length = features.length; +} + +GeoJSONWrapper$1.prototype.feature = function (i) { + return new FeatureWrapper(this.features[i], this.options.extent) +}; + +function FeatureWrapper (feature, extent) { + this.id = typeof feature.id === 'number' ? feature.id : undefined; + this.type = feature.type; + this.rawGeometry = feature.type === 1 ? [feature.geometry] : feature.geometry; + this.properties = feature.tags; + this.extent = extent || 4096; +} + +FeatureWrapper.prototype.loadGeometry = function () { + var rings = this.rawGeometry; + this.geometry = []; + + for (var i = 0; i < rings.length; i++) { + var ring = rings[i]; + var newRing = []; + for (var j = 0; j < ring.length; j++) { + newRing.push(new Point(ring[j][0], ring[j][1])); + } + this.geometry.push(newRing); + } + return this.geometry +}; + +FeatureWrapper.prototype.bbox = function () { + if (!this.geometry) this.loadGeometry(); + + var rings = this.geometry; + var x1 = Infinity; + var x2 = -Infinity; + var y1 = Infinity; + var y2 = -Infinity; + + for (var i = 0; i < rings.length; i++) { + var ring = rings[i]; + + for (var j = 0; j < ring.length; j++) { + var coord = ring[j]; + + x1 = Math.min(x1, coord.x); + x2 = Math.max(x2, coord.x); + y1 = Math.min(y1, coord.y); + y2 = Math.max(y2, coord.y); + } + } + + return [x1, y1, x2, y2] +}; + +FeatureWrapper.prototype.toGeoJSON = VectorTileFeature.prototype.toGeoJSON; + +var geojson_wrapper$1 = /*@__PURE__*/performance.getDefaultExportFromCjs(geojson_wrapper); + +var vtPbf = vtPbf$1.exports; + +var Pbf = performance.pbf; +var GeoJSONWrapper = geojson_wrapper; + +vtPbf$1.exports = fromVectorTileJs; +var fromVectorTileJs_1 = vtPbf$1.exports.fromVectorTileJs = fromVectorTileJs; +var fromGeojsonVt_1 = vtPbf$1.exports.fromGeojsonVt = fromGeojsonVt; +var GeoJSONWrapper_1 = vtPbf$1.exports.GeoJSONWrapper = GeoJSONWrapper; + +/** + * Serialize a vector-tile-js-created tile to pbf + * + * @param {Object} tile + * @return {Buffer} uncompressed, pbf-serialized tile data + */ +function fromVectorTileJs (tile) { + var out = new Pbf(); + writeTile(tile, out); + return out.finish() +} + +/** + * Serialized a geojson-vt-created tile to pbf. + * + * @param {Object} layers - An object mapping layer names to geojson-vt-created vector tile objects + * @param {Object} [options] - An object specifying the vector-tile specification version and extent that were used to create `layers`. + * @param {Number} [options.version=1] - Version of vector-tile spec used + * @param {Number} [options.extent=4096] - Extent of the vector tile + * @return {Buffer} uncompressed, pbf-serialized tile data + */ +function fromGeojsonVt (layers, options) { + options = options || {}; + var l = {}; + for (var k in layers) { + l[k] = new GeoJSONWrapper(layers[k].features, options); + l[k].name = k; + l[k].version = options.version; + l[k].extent = options.extent; + } + return fromVectorTileJs({ layers: l }) +} + +function writeTile (tile, pbf) { + for (var key in tile.layers) { + pbf.writeMessage(3, writeLayer, tile.layers[key]); + } +} + +function writeLayer (layer, pbf) { + pbf.writeVarintField(15, layer.version || 1); + pbf.writeStringField(1, layer.name || ''); + pbf.writeVarintField(5, layer.extent || 4096); + + var i; + var context = { + keys: [], + values: [], + keycache: {}, + valuecache: {} + }; + + for (i = 0; i < layer.length; i++) { + context.feature = layer.feature(i); + pbf.writeMessage(2, writeFeature, context); + } + + var keys = context.keys; + for (i = 0; i < keys.length; i++) { + pbf.writeStringField(3, keys[i]); + } + + var values = context.values; + for (i = 0; i < values.length; i++) { + pbf.writeMessage(4, writeValue, values[i]); + } +} + +function writeFeature (context, pbf) { + var feature = context.feature; + + if (feature.id !== undefined) { + pbf.writeVarintField(1, feature.id); + } + + pbf.writeMessage(2, writeProperties, context); + pbf.writeVarintField(3, feature.type); + pbf.writeMessage(4, writeGeometry, feature); +} + +function writeProperties (context, pbf) { + var feature = context.feature; + var keys = context.keys; + var values = context.values; + var keycache = context.keycache; + var valuecache = context.valuecache; + + for (var key in feature.properties) { + var value = feature.properties[key]; + + var keyIndex = keycache[key]; + if (value === null) continue // don't encode null value properties + + if (typeof keyIndex === 'undefined') { + keys.push(key); + keyIndex = keys.length - 1; + keycache[key] = keyIndex; + } + pbf.writeVarint(keyIndex); + + var type = typeof value; + if (type !== 'string' && type !== 'boolean' && type !== 'number') { + value = JSON.stringify(value); + } + var valueKey = type + ':' + value; + var valueIndex = valuecache[valueKey]; + if (typeof valueIndex === 'undefined') { + values.push(value); + valueIndex = values.length - 1; + valuecache[valueKey] = valueIndex; + } + pbf.writeVarint(valueIndex); + } +} + +function command (cmd, length) { + return (length << 3) + (cmd & 0x7) +} + +function zigzag (num) { + return (num << 1) ^ (num >> 31) +} + +function writeGeometry (feature, pbf) { + var geometry = feature.loadGeometry(); + var type = feature.type; + var x = 0; + var y = 0; + var rings = geometry.length; + for (var r = 0; r < rings; r++) { + var ring = geometry[r]; + var count = 1; + if (type === 1) { + count = ring.length; + } + pbf.writeVarint(command(1, count)); // moveto + // do not write polygon closing path as lineto + var lineCount = type === 3 ? ring.length - 1 : ring.length; + for (var i = 0; i < lineCount; i++) { + if (i === 1 && type !== 1) { + pbf.writeVarint(command(2, lineCount - 1)); // lineto + } + var dx = ring[i].x - x; + var dy = ring[i].y - y; + pbf.writeVarint(zigzag(dx)); + pbf.writeVarint(zigzag(dy)); + x += dx; + y += dy; + } + if (type === 3) { + pbf.writeVarint(command(7, 1)); // closepath + } + } +} + +function writeValue (value, pbf) { + var type = typeof value; + if (type === 'string') { + pbf.writeStringField(1, value); + } else if (type === 'boolean') { + pbf.writeBooleanField(7, value); + } else if (type === 'number') { + if (value % 1 !== 0) { + pbf.writeDoubleField(3, value); + } else if (value < 0) { + pbf.writeSVarintField(6, value); + } else { + pbf.writeVarintField(5, value); + } + } +} + +var vtPbfExports = vtPbf$1.exports; +var vtpbf = /*@__PURE__*/performance.getDefaultExportFromCjs(vtPbfExports); + +const defaultOptions$1 = { + minZoom: 0, // min zoom to generate clusters on + maxZoom: 16, // max zoom level to cluster the points on + minPoints: 2, // minimum points to form a cluster + radius: 40, // cluster radius in pixels + extent: 512, // tile extent (radius is calculated relative to it) + nodeSize: 64, // size of the KD-tree leaf node, affects performance + log: false, // whether to log timing info + + // whether to generate numeric ids for input features (in vector tiles) + generateId: false, + + // a reduce function for calculating custom cluster properties + reduce: null, // (accumulated, props) => { accumulated.sum += props.sum; } + + // properties to use for individual points when running the reducer + map: props => props // props => ({sum: props.my_value}) +}; + +const fround = Math.fround || (tmp => ((x) => { tmp[0] = +x; return tmp[0]; }))(new Float32Array(1)); + +const OFFSET_ZOOM = 2; +const OFFSET_ID = 3; +const OFFSET_PARENT = 4; +const OFFSET_NUM = 5; +const OFFSET_PROP = 6; + +class Supercluster { + constructor(options) { + this.options = Object.assign(Object.create(defaultOptions$1), options); + this.trees = new Array(this.options.maxZoom + 1); + this.stride = this.options.reduce ? 7 : 6; + this.clusterProps = []; + } + + load(points) { + const {log, minZoom, maxZoom} = this.options; + + if (log) console.time('total time'); + + const timerId = `prepare ${ points.length } points`; + if (log) console.time(timerId); + + this.points = points; + + // generate a cluster object for each point and index input points into a KD-tree + const data = []; + + for (let i = 0; i < points.length; i++) { + const p = points[i]; + if (!p.geometry) continue; + + const [lng, lat] = p.geometry.coordinates; + const x = fround(lngX(lng)); + const y = fround(latY(lat)); + // store internal point/cluster data in flat numeric arrays for performance + data.push( + x, y, // projected point coordinates + Infinity, // the last zoom the point was processed at + i, // index of the source feature in the original input array + -1, // parent cluster id + 1 // number of points in a cluster + ); + if (this.options.reduce) data.push(0); // noop + } + let tree = this.trees[maxZoom + 1] = this._createTree(data); + + if (log) console.timeEnd(timerId); + + // cluster points on max zoom, then cluster the results on previous zoom, etc.; + // results in a cluster hierarchy across zoom levels + for (let z = maxZoom; z >= minZoom; z--) { + const now = +Date.now(); + + // create a new set of clusters for the zoom and index them with a KD-tree + tree = this.trees[z] = this._createTree(this._cluster(tree, z)); + + if (log) console.log('z%d: %d clusters in %dms', z, tree.numItems, +Date.now() - now); + } + + if (log) console.timeEnd('total time'); + + return this; + } + + getClusters(bbox, zoom) { + let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180; + const minLat = Math.max(-90, Math.min(90, bbox[1])); + let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180; + const maxLat = Math.max(-90, Math.min(90, bbox[3])); + + if (bbox[2] - bbox[0] >= 360) { + minLng = -180; + maxLng = 180; + } else if (minLng > maxLng) { + const easternHem = this.getClusters([minLng, minLat, 180, maxLat], zoom); + const westernHem = this.getClusters([-180, minLat, maxLng, maxLat], zoom); + return easternHem.concat(westernHem); + } + + const tree = this.trees[this._limitZoom(zoom)]; + const ids = tree.range(lngX(minLng), latY(maxLat), lngX(maxLng), latY(minLat)); + const data = tree.data; + const clusters = []; + for (const id of ids) { + const k = this.stride * id; + clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]); + } + return clusters; + } + + getChildren(clusterId) { + const originId = this._getOriginId(clusterId); + const originZoom = this._getOriginZoom(clusterId); + const errorMsg = 'No cluster with the specified id.'; + + const tree = this.trees[originZoom]; + if (!tree) throw new Error(errorMsg); + + const data = tree.data; + if (originId * this.stride >= data.length) throw new Error(errorMsg); + + const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1)); + const x = data[originId * this.stride]; + const y = data[originId * this.stride + 1]; + const ids = tree.within(x, y, r); + const children = []; + for (const id of ids) { + const k = id * this.stride; + if (data[k + OFFSET_PARENT] === clusterId) { + children.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]); + } + } + + if (children.length === 0) throw new Error(errorMsg); + + return children; + } + + getLeaves(clusterId, limit, offset) { + limit = limit || 10; + offset = offset || 0; + + const leaves = []; + this._appendLeaves(leaves, clusterId, limit, offset, 0); + + return leaves; + } + + getTile(z, x, y) { + const tree = this.trees[this._limitZoom(z)]; + const z2 = Math.pow(2, z); + const {extent, radius} = this.options; + const p = radius / extent; + const top = (y - p) / z2; + const bottom = (y + 1 + p) / z2; + + const tile = { + features: [] + }; + + this._addTileFeatures( + tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), + tree.data, x, y, z2, tile); + + if (x === 0) { + this._addTileFeatures( + tree.range(1 - p / z2, top, 1, bottom), + tree.data, z2, y, z2, tile); + } + if (x === z2 - 1) { + this._addTileFeatures( + tree.range(0, top, p / z2, bottom), + tree.data, -1, y, z2, tile); + } + + return tile.features.length ? tile : null; + } + + getClusterExpansionZoom(clusterId) { + let expansionZoom = this._getOriginZoom(clusterId) - 1; + while (expansionZoom <= this.options.maxZoom) { + const children = this.getChildren(clusterId); + expansionZoom++; + if (children.length !== 1) break; + clusterId = children[0].properties.cluster_id; + } + return expansionZoom; + } + + _appendLeaves(result, clusterId, limit, offset, skipped) { + const children = this.getChildren(clusterId); + + for (const child of children) { + const props = child.properties; + + if (props && props.cluster) { + if (skipped + props.point_count <= offset) { + // skip the whole cluster + skipped += props.point_count; + } else { + // enter the cluster + skipped = this._appendLeaves(result, props.cluster_id, limit, offset, skipped); + // exit the cluster + } + } else if (skipped < offset) { + // skip a single point + skipped++; + } else { + // add a single point + result.push(child); + } + if (result.length === limit) break; + } + + return skipped; + } + + _createTree(data) { + const tree = new performance.KDBush(data.length / this.stride | 0, this.options.nodeSize, Float32Array); + for (let i = 0; i < data.length; i += this.stride) tree.add(data[i], data[i + 1]); + tree.finish(); + tree.data = data; + return tree; + } + + _addTileFeatures(ids, data, x, y, z2, tile) { + for (const i of ids) { + const k = i * this.stride; + const isCluster = data[k + OFFSET_NUM] > 1; + + let tags, px, py; + if (isCluster) { + tags = getClusterProperties(data, k, this.clusterProps); + px = data[k]; + py = data[k + 1]; + } else { + const p = this.points[data[k + OFFSET_ID]]; + tags = p.properties; + const [lng, lat] = p.geometry.coordinates; + px = lngX(lng); + py = latY(lat); + } + + const f = { + type: 1, + geometry: [[ + Math.round(this.options.extent * (px * z2 - x)), + Math.round(this.options.extent * (py * z2 - y)) + ]], + tags + }; + + // assign id + let id; + if (isCluster || this.options.generateId) { + // optionally generate id for points + id = data[k + OFFSET_ID]; + } else { + // keep id if already assigned + id = this.points[data[k + OFFSET_ID]].id; + } + + if (id !== undefined) f.id = id; + + tile.features.push(f); + } + } + + _limitZoom(z) { + return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1)); + } + + _cluster(tree, zoom) { + const {radius, extent, reduce, minPoints} = this.options; + const r = radius / (extent * Math.pow(2, zoom)); + const data = tree.data; + const nextData = []; + const stride = this.stride; + + // loop through each point + for (let i = 0; i < data.length; i += stride) { + // if we've already visited the point at this zoom level, skip it + if (data[i + OFFSET_ZOOM] <= zoom) continue; + data[i + OFFSET_ZOOM] = zoom; + + // find all nearby points + const x = data[i]; + const y = data[i + 1]; + const neighborIds = tree.within(data[i], data[i + 1], r); + + const numPointsOrigin = data[i + OFFSET_NUM]; + let numPoints = numPointsOrigin; + + // count the number of points in a potential cluster + for (const neighborId of neighborIds) { + const k = neighborId * stride; + // filter out neighbors that are already processed + if (data[k + OFFSET_ZOOM] > zoom) numPoints += data[k + OFFSET_NUM]; + } + + // if there were neighbors to merge, and there are enough points to form a cluster + if (numPoints > numPointsOrigin && numPoints >= minPoints) { + let wx = x * numPointsOrigin; + let wy = y * numPointsOrigin; + + let clusterProperties; + let clusterPropIndex = -1; + + // encode both zoom and point index on which the cluster originated -- offset by total length of features + const id = ((i / stride | 0) << 5) + (zoom + 1) + this.points.length; + + for (const neighborId of neighborIds) { + const k = neighborId * stride; + + if (data[k + OFFSET_ZOOM] <= zoom) continue; + data[k + OFFSET_ZOOM] = zoom; // save the zoom (so it doesn't get processed twice) + + const numPoints2 = data[k + OFFSET_NUM]; + wx += data[k] * numPoints2; // accumulate coordinates for calculating weighted center + wy += data[k + 1] * numPoints2; + + data[k + OFFSET_PARENT] = id; + + if (reduce) { + if (!clusterProperties) { + clusterProperties = this._map(data, i, true); + clusterPropIndex = this.clusterProps.length; + this.clusterProps.push(clusterProperties); + } + reduce(clusterProperties, this._map(data, k)); + } + } + + data[i + OFFSET_PARENT] = id; + nextData.push(wx / numPoints, wy / numPoints, Infinity, id, -1, numPoints); + if (reduce) nextData.push(clusterPropIndex); + + } else { // left points as unclustered + for (let j = 0; j < stride; j++) nextData.push(data[i + j]); + + if (numPoints > 1) { + for (const neighborId of neighborIds) { + const k = neighborId * stride; + if (data[k + OFFSET_ZOOM] <= zoom) continue; + data[k + OFFSET_ZOOM] = zoom; + for (let j = 0; j < stride; j++) nextData.push(data[k + j]); + } + } + } + } + + return nextData; + } + + // get index of the point from which the cluster originated + _getOriginId(clusterId) { + return (clusterId - this.points.length) >> 5; + } + + // get zoom of the point from which the cluster originated + _getOriginZoom(clusterId) { + return (clusterId - this.points.length) % 32; + } + + _map(data, i, clone) { + if (data[i + OFFSET_NUM] > 1) { + const props = this.clusterProps[data[i + OFFSET_PROP]]; + return clone ? Object.assign({}, props) : props; + } + const original = this.points[data[i + OFFSET_ID]].properties; + const result = this.options.map(original); + return clone && result === original ? Object.assign({}, result) : result; + } +} + +function getClusterJSON(data, i, clusterProps) { + return { + type: 'Feature', + id: data[i + OFFSET_ID], + properties: getClusterProperties(data, i, clusterProps), + geometry: { + type: 'Point', + coordinates: [xLng(data[i]), yLat(data[i + 1])] + } + }; +} + +function getClusterProperties(data, i, clusterProps) { + const count = data[i + OFFSET_NUM]; + const abbrev = + count >= 10000 ? `${Math.round(count / 1000) }k` : + count >= 1000 ? `${Math.round(count / 100) / 10 }k` : count; + const propIndex = data[i + OFFSET_PROP]; + const properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]); + return Object.assign(properties, { + cluster: true, + cluster_id: data[i + OFFSET_ID], + point_count: count, + point_count_abbreviated: abbrev + }); +} + +// longitude/latitude to spherical mercator in [0..1] range +function lngX(lng) { + return lng / 360 + 0.5; +} +function latY(lat) { + const sin = Math.sin(lat * Math.PI / 180); + const y = (0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI); + return y < 0 ? 0 : y > 1 ? 1 : y; +} + +// spherical mercator to longitude/latitude +function xLng(x) { + return (x - 0.5) * 360; +} +function yLat(y) { + const y2 = (180 - y * 360) * Math.PI / 180; + return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90; +} + +// calculate simplification data using optimized Douglas-Peucker algorithm + +function simplify(coords, first, last, sqTolerance) { + let maxSqDist = sqTolerance; + const mid = first + ((last - first) >> 1); + let minPosToMid = last - first; + let index; + + const ax = coords[first]; + const ay = coords[first + 1]; + const bx = coords[last]; + const by = coords[last + 1]; + + for (let i = first + 3; i < last; i += 3) { + const d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by); + + if (d > maxSqDist) { + index = i; + maxSqDist = d; + + } else if (d === maxSqDist) { + // a workaround to ensure we choose a pivot close to the middle of the list, + // reducing recursion depth, for certain degenerate inputs + // https://github.com/mapbox/geojson-vt/issues/104 + const posToMid = Math.abs(i - mid); + if (posToMid < minPosToMid) { + index = i; + minPosToMid = posToMid; + } + } + } + + if (maxSqDist > sqTolerance) { + if (index - first > 3) simplify(coords, first, index, sqTolerance); + coords[index + 2] = maxSqDist; + if (last - index > 3) simplify(coords, index, last, sqTolerance); + } +} + +// square distance from a point to a segment +function getSqSegDist(px, py, x, y, bx, by) { + + let dx = bx - x; + let dy = by - y; + + if (dx !== 0 || dy !== 0) { + + const t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy); + + if (t > 1) { + x = bx; + y = by; + + } else if (t > 0) { + x += dx * t; + y += dy * t; + } + } + + dx = px - x; + dy = py - y; + + return dx * dx + dy * dy; +} + +function createFeature(id, type, geom, tags) { + const feature = { + id: id == null ? null : id, + type, + geometry: geom, + tags, + minX: Infinity, + minY: Infinity, + maxX: -Infinity, + maxY: -Infinity + }; + + if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') { + calcLineBBox(feature, geom); + + } else if (type === 'Polygon') { + // the outer ring (ie [0]) contains all inner rings + calcLineBBox(feature, geom[0]); + + } else if (type === 'MultiLineString') { + for (const line of geom) { + calcLineBBox(feature, line); + } + + } else if (type === 'MultiPolygon') { + for (const polygon of geom) { + // the outer ring (ie [0]) contains all inner rings + calcLineBBox(feature, polygon[0]); + } + } + + return feature; +} + +function calcLineBBox(feature, geom) { + for (let i = 0; i < geom.length; i += 3) { + feature.minX = Math.min(feature.minX, geom[i]); + feature.minY = Math.min(feature.minY, geom[i + 1]); + feature.maxX = Math.max(feature.maxX, geom[i]); + feature.maxY = Math.max(feature.maxY, geom[i + 1]); + } +} + +// converts GeoJSON feature into an intermediate projected JSON vector format with simplification data + +function convert(data, options) { + const features = []; + if (data.type === 'FeatureCollection') { + for (let i = 0; i < data.features.length; i++) { + convertFeature(features, data.features[i], options, i); + } + + } else if (data.type === 'Feature') { + convertFeature(features, data, options); + + } else { + // single geometry or a geometry collection + convertFeature(features, {geometry: data}, options); + } + + return features; +} + +function convertFeature(features, geojson, options, index) { + if (!geojson.geometry) return; + + const coords = geojson.geometry.coordinates; + if (coords && coords.length === 0) return; + + const type = geojson.geometry.type; + const tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2); + let geometry = []; + let id = geojson.id; + if (options.promoteId) { + id = geojson.properties[options.promoteId]; + } else if (options.generateId) { + id = index || 0; + } + if (type === 'Point') { + convertPoint(coords, geometry); + + } else if (type === 'MultiPoint') { + for (const p of coords) { + convertPoint(p, geometry); + } + + } else if (type === 'LineString') { + convertLine(coords, geometry, tolerance, false); + + } else if (type === 'MultiLineString') { + if (options.lineMetrics) { + // explode into linestrings to be able to track metrics + for (const line of coords) { + geometry = []; + convertLine(line, geometry, tolerance, false); + features.push(createFeature(id, 'LineString', geometry, geojson.properties)); + } + return; + } else { + convertLines(coords, geometry, tolerance, false); + } + + } else if (type === 'Polygon') { + convertLines(coords, geometry, tolerance, true); + + } else if (type === 'MultiPolygon') { + for (const polygon of coords) { + const newPolygon = []; + convertLines(polygon, newPolygon, tolerance, true); + geometry.push(newPolygon); + } + } else if (type === 'GeometryCollection') { + for (const singleGeometry of geojson.geometry.geometries) { + convertFeature(features, { + id, + geometry: singleGeometry, + properties: geojson.properties + }, options, index); + } + return; + } else { + throw new Error('Input data is not a valid GeoJSON object.'); + } + + features.push(createFeature(id, type, geometry, geojson.properties)); +} + +function convertPoint(coords, out) { + out.push(projectX(coords[0]), projectY(coords[1]), 0); +} + +function convertLine(ring, out, tolerance, isPolygon) { + let x0, y0; + let size = 0; + + for (let j = 0; j < ring.length; j++) { + const x = projectX(ring[j][0]); + const y = projectY(ring[j][1]); + + out.push(x, y, 0); + + if (j > 0) { + if (isPolygon) { + size += (x0 * y - x * y0) / 2; // area + } else { + size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)); // length + } + } + x0 = x; + y0 = y; + } + + const last = out.length - 3; + out[2] = 1; + simplify(out, 0, last, tolerance); + out[last + 2] = 1; + + out.size = Math.abs(size); + out.start = 0; + out.end = out.size; +} + +function convertLines(rings, out, tolerance, isPolygon) { + for (let i = 0; i < rings.length; i++) { + const geom = []; + convertLine(rings[i], geom, tolerance, isPolygon); + out.push(geom); + } +} + +function projectX(x) { + return x / 360 + 0.5; +} + +function projectY(y) { + const sin = Math.sin(y * Math.PI / 180); + const y2 = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI; + return y2 < 0 ? 0 : y2 > 1 ? 1 : y2; +} + +/* clip features between two vertical or horizontal axis-parallel lines: + * | | + * ___|___ | / + * / | \____|____/ + * | | + * + * k1 and k2 are the line coordinates + * axis: 0 for x, 1 for y + * minAll and maxAll: minimum and maximum coordinate value for all features + */ +function clip(features, scale, k1, k2, axis, minAll, maxAll, options) { + k1 /= scale; + k2 /= scale; + + if (minAll >= k1 && maxAll < k2) return features; // trivial accept + else if (maxAll < k1 || minAll >= k2) return null; // trivial reject + + const clipped = []; + + for (const feature of features) { + const geometry = feature.geometry; + let type = feature.type; + + const min = axis === 0 ? feature.minX : feature.minY; + const max = axis === 0 ? feature.maxX : feature.maxY; + + if (min >= k1 && max < k2) { // trivial accept + clipped.push(feature); + continue; + } else if (max < k1 || min >= k2) { // trivial reject + continue; + } + + let newGeometry = []; + + if (type === 'Point' || type === 'MultiPoint') { + clipPoints(geometry, newGeometry, k1, k2, axis); + + } else if (type === 'LineString') { + clipLine(geometry, newGeometry, k1, k2, axis, false, options.lineMetrics); + + } else if (type === 'MultiLineString') { + clipLines(geometry, newGeometry, k1, k2, axis, false); + + } else if (type === 'Polygon') { + clipLines(geometry, newGeometry, k1, k2, axis, true); + + } else if (type === 'MultiPolygon') { + for (const polygon of geometry) { + const newPolygon = []; + clipLines(polygon, newPolygon, k1, k2, axis, true); + if (newPolygon.length) { + newGeometry.push(newPolygon); + } + } + } + + if (newGeometry.length) { + if (options.lineMetrics && type === 'LineString') { + for (const line of newGeometry) { + clipped.push(createFeature(feature.id, type, line, feature.tags)); + } + continue; + } + + if (type === 'LineString' || type === 'MultiLineString') { + if (newGeometry.length === 1) { + type = 'LineString'; + newGeometry = newGeometry[0]; + } else { + type = 'MultiLineString'; + } + } + if (type === 'Point' || type === 'MultiPoint') { + type = newGeometry.length === 3 ? 'Point' : 'MultiPoint'; + } + + clipped.push(createFeature(feature.id, type, newGeometry, feature.tags)); + } + } + + return clipped.length ? clipped : null; +} + +function clipPoints(geom, newGeom, k1, k2, axis) { + for (let i = 0; i < geom.length; i += 3) { + const a = geom[i + axis]; + + if (a >= k1 && a <= k2) { + addPoint(newGeom, geom[i], geom[i + 1], geom[i + 2]); + } + } +} + +function clipLine(geom, newGeom, k1, k2, axis, isPolygon, trackMetrics) { + + let slice = newSlice(geom); + const intersect = axis === 0 ? intersectX : intersectY; + let len = geom.start; + let segLen, t; + + for (let i = 0; i < geom.length - 3; i += 3) { + const ax = geom[i]; + const ay = geom[i + 1]; + const az = geom[i + 2]; + const bx = geom[i + 3]; + const by = geom[i + 4]; + const a = axis === 0 ? ax : ay; + const b = axis === 0 ? bx : by; + let exited = false; + + if (trackMetrics) segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2)); + + if (a < k1) { + // ---|--> | (line enters the clip region from the left) + if (b > k1) { + t = intersect(slice, ax, ay, bx, by, k1); + if (trackMetrics) slice.start = len + segLen * t; + } + } else if (a > k2) { + // | <--|--- (line enters the clip region from the right) + if (b < k2) { + t = intersect(slice, ax, ay, bx, by, k2); + if (trackMetrics) slice.start = len + segLen * t; + } + } else { + addPoint(slice, ax, ay, az); + } + if (b < k1 && a >= k1) { + // <--|--- | or <--|-----|--- (line exits the clip region on the left) + t = intersect(slice, ax, ay, bx, by, k1); + exited = true; + } + if (b > k2 && a <= k2) { + // | ---|--> or ---|-----|--> (line exits the clip region on the right) + t = intersect(slice, ax, ay, bx, by, k2); + exited = true; + } + + if (!isPolygon && exited) { + if (trackMetrics) slice.end = len + segLen * t; + newGeom.push(slice); + slice = newSlice(geom); + } + + if (trackMetrics) len += segLen; + } + + // add the last point + let last = geom.length - 3; + const ax = geom[last]; + const ay = geom[last + 1]; + const az = geom[last + 2]; + const a = axis === 0 ? ax : ay; + if (a >= k1 && a <= k2) addPoint(slice, ax, ay, az); + + // close the polygon if its endpoints are not the same after clipping + last = slice.length - 3; + if (isPolygon && last >= 3 && (slice[last] !== slice[0] || slice[last + 1] !== slice[1])) { + addPoint(slice, slice[0], slice[1], slice[2]); + } + + // add the final slice + if (slice.length) { + newGeom.push(slice); + } +} + +function newSlice(line) { + const slice = []; + slice.size = line.size; + slice.start = line.start; + slice.end = line.end; + return slice; +} + +function clipLines(geom, newGeom, k1, k2, axis, isPolygon) { + for (const line of geom) { + clipLine(line, newGeom, k1, k2, axis, isPolygon, false); + } +} + +function addPoint(out, x, y, z) { + out.push(x, y, z); +} + +function intersectX(out, ax, ay, bx, by, x) { + const t = (x - ax) / (bx - ax); + addPoint(out, x, ay + (by - ay) * t, 1); + return t; +} + +function intersectY(out, ax, ay, bx, by, y) { + const t = (y - ay) / (by - ay); + addPoint(out, ax + (bx - ax) * t, y, 1); + return t; +} + +function wrap(features, options) { + const buffer = options.buffer / options.extent; + let merged = features; + const left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options); // left world copy + const right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2, options); // right world copy + + if (left || right) { + merged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2, options) || []; // center world copy + + if (left) merged = shiftFeatureCoords(left, 1).concat(merged); // merge left into center + if (right) merged = merged.concat(shiftFeatureCoords(right, -1)); // merge right into center + } + + return merged; +} + +function shiftFeatureCoords(features, offset) { + const newFeatures = []; + + for (let i = 0; i < features.length; i++) { + const feature = features[i]; + const type = feature.type; + + let newGeometry; + + if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') { + newGeometry = shiftCoords(feature.geometry, offset); + + } else if (type === 'MultiLineString' || type === 'Polygon') { + newGeometry = []; + for (const line of feature.geometry) { + newGeometry.push(shiftCoords(line, offset)); + } + } else if (type === 'MultiPolygon') { + newGeometry = []; + for (const polygon of feature.geometry) { + const newPolygon = []; + for (const line of polygon) { + newPolygon.push(shiftCoords(line, offset)); + } + newGeometry.push(newPolygon); + } + } + + newFeatures.push(createFeature(feature.id, type, newGeometry, feature.tags)); + } + + return newFeatures; +} + +function shiftCoords(points, offset) { + const newPoints = []; + newPoints.size = points.size; + + if (points.start !== undefined) { + newPoints.start = points.start; + newPoints.end = points.end; + } + + for (let i = 0; i < points.length; i += 3) { + newPoints.push(points[i] + offset, points[i + 1], points[i + 2]); + } + return newPoints; +} + +// Transforms the coordinates of each feature in the given tile from +// mercator-projected space into (extent x extent) tile space. +function transformTile(tile, extent) { + if (tile.transformed) return tile; + + const z2 = 1 << tile.z; + const tx = tile.x; + const ty = tile.y; + + for (const feature of tile.features) { + const geom = feature.geometry; + const type = feature.type; + + feature.geometry = []; + + if (type === 1) { + for (let j = 0; j < geom.length; j += 2) { + feature.geometry.push(transformPoint(geom[j], geom[j + 1], extent, z2, tx, ty)); + } + } else { + for (let j = 0; j < geom.length; j++) { + const ring = []; + for (let k = 0; k < geom[j].length; k += 2) { + ring.push(transformPoint(geom[j][k], geom[j][k + 1], extent, z2, tx, ty)); + } + feature.geometry.push(ring); + } + } + } + + tile.transformed = true; + + return tile; +} + +function transformPoint(x, y, extent, z2, tx, ty) { + return [ + Math.round(extent * (x * z2 - tx)), + Math.round(extent * (y * z2 - ty))]; +} + +function createTile(features, z, tx, ty, options) { + const tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent); + const tile = { + features: [], + numPoints: 0, + numSimplified: 0, + numFeatures: features.length, + source: null, + x: tx, + y: ty, + z, + transformed: false, + minX: 2, + minY: 1, + maxX: -1, + maxY: 0 + }; + for (const feature of features) { + addFeature(tile, feature, tolerance, options); + } + return tile; +} + +function addFeature(tile, feature, tolerance, options) { + const geom = feature.geometry; + const type = feature.type; + const simplified = []; + + tile.minX = Math.min(tile.minX, feature.minX); + tile.minY = Math.min(tile.minY, feature.minY); + tile.maxX = Math.max(tile.maxX, feature.maxX); + tile.maxY = Math.max(tile.maxY, feature.maxY); + + if (type === 'Point' || type === 'MultiPoint') { + for (let i = 0; i < geom.length; i += 3) { + simplified.push(geom[i], geom[i + 1]); + tile.numPoints++; + tile.numSimplified++; + } + + } else if (type === 'LineString') { + addLine(simplified, geom, tile, tolerance, false, false); + + } else if (type === 'MultiLineString' || type === 'Polygon') { + for (let i = 0; i < geom.length; i++) { + addLine(simplified, geom[i], tile, tolerance, type === 'Polygon', i === 0); + } + + } else if (type === 'MultiPolygon') { + + for (let k = 0; k < geom.length; k++) { + const polygon = geom[k]; + for (let i = 0; i < polygon.length; i++) { + addLine(simplified, polygon[i], tile, tolerance, true, i === 0); + } + } + } + + if (simplified.length) { + let tags = feature.tags || null; + + if (type === 'LineString' && options.lineMetrics) { + tags = {}; + for (const key in feature.tags) tags[key] = feature.tags[key]; + tags['mapbox_clip_start'] = geom.start / geom.size; + tags['mapbox_clip_end'] = geom.end / geom.size; + } + + const tileFeature = { + geometry: simplified, + type: type === 'Polygon' || type === 'MultiPolygon' ? 3 : + (type === 'LineString' || type === 'MultiLineString' ? 2 : 1), + tags + }; + if (feature.id !== null) { + tileFeature.id = feature.id; + } + tile.features.push(tileFeature); + } +} + +function addLine(result, geom, tile, tolerance, isPolygon, isOuter) { + const sqTolerance = tolerance * tolerance; + + if (tolerance > 0 && (geom.size < (isPolygon ? sqTolerance : tolerance))) { + tile.numPoints += geom.length / 3; + return; + } + + const ring = []; + + for (let i = 0; i < geom.length; i += 3) { + if (tolerance === 0 || geom[i + 2] > sqTolerance) { + tile.numSimplified++; + ring.push(geom[i], geom[i + 1]); + } + tile.numPoints++; + } + + if (isPolygon) rewind(ring, isOuter); + + result.push(ring); +} + +function rewind(ring, clockwise) { + let area = 0; + for (let i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) { + area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]); + } + if (area > 0 === clockwise) { + for (let i = 0, len = ring.length; i < len / 2; i += 2) { + const x = ring[i]; + const y = ring[i + 1]; + ring[i] = ring[len - 2 - i]; + ring[i + 1] = ring[len - 1 - i]; + ring[len - 2 - i] = x; + ring[len - 1 - i] = y; + } + } +} + +const defaultOptions = { + maxZoom: 14, // max zoom to preserve detail on + indexMaxZoom: 5, // max zoom in the tile index + indexMaxPoints: 100000, // max number of points per tile in the tile index + tolerance: 3, // simplification tolerance (higher means simpler) + extent: 4096, // tile extent + buffer: 64, // tile buffer on each side + lineMetrics: false, // whether to calculate line metrics + promoteId: null, // name of a feature property to be promoted to feature.id + generateId: false, // whether to generate feature ids. Cannot be used with promoteId + debug: 0 // logging level (0, 1 or 2) +}; + +class GeoJSONVT { + constructor(data, options) { + options = this.options = extend(Object.create(defaultOptions), options); + + const debug = options.debug; + + if (debug) console.time('preprocess data'); + + if (options.maxZoom < 0 || options.maxZoom > 24) throw new Error('maxZoom should be in the 0-24 range'); + if (options.promoteId && options.generateId) throw new Error('promoteId and generateId cannot be used together.'); + + // projects and adds simplification info + let features = convert(data, options); + + // tiles and tileCoords are part of the public API + this.tiles = {}; + this.tileCoords = []; + + if (debug) { + console.timeEnd('preprocess data'); + console.log('index: maxZoom: %d, maxPoints: %d', options.indexMaxZoom, options.indexMaxPoints); + console.time('generate tiles'); + this.stats = {}; + this.total = 0; + } + + // wraps features (ie extreme west and extreme east) + features = wrap(features, options); + + // start slicing from the top tile down + if (features.length) this.splitTile(features, 0, 0, 0); + + if (debug) { + if (features.length) console.log('features: %d, points: %d', this.tiles[0].numFeatures, this.tiles[0].numPoints); + console.timeEnd('generate tiles'); + console.log('tiles generated:', this.total, JSON.stringify(this.stats)); + } + } + + // splits features from a parent tile to sub-tiles. + // z, x, and y are the coordinates of the parent tile + // cz, cx, and cy are the coordinates of the target tile + // + // If no target tile is specified, splitting stops when we reach the maximum + // zoom or the number of points is low as specified in the options. + splitTile(features, z, x, y, cz, cx, cy) { + + const stack = [features, z, x, y]; + const options = this.options; + const debug = options.debug; + + // avoid recursion by using a processing queue + while (stack.length) { + y = stack.pop(); + x = stack.pop(); + z = stack.pop(); + features = stack.pop(); + + const z2 = 1 << z; + const id = toID(z, x, y); + let tile = this.tiles[id]; + + if (!tile) { + if (debug > 1) console.time('creation'); + + tile = this.tiles[id] = createTile(features, z, x, y, options); + this.tileCoords.push({z, x, y}); + + if (debug) { + if (debug > 1) { + console.log('tile z%d-%d-%d (features: %d, points: %d, simplified: %d)', + z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified); + console.timeEnd('creation'); + } + const key = `z${ z}`; + this.stats[key] = (this.stats[key] || 0) + 1; + this.total++; + } + } + + // save reference to original geometry in tile so that we can drill down later if we stop now + tile.source = features; + + // if it's the first-pass tiling + if (cz == null) { + // stop tiling if we reached max zoom, or if the tile is too simple + if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints) continue; + // if a drilldown to a specific tile + } else if (z === options.maxZoom || z === cz) { + // stop tiling if we reached base zoom or our target tile zoom + continue; + } else if (cz != null) { + // stop tiling if it's not an ancestor of the target tile + const zoomSteps = cz - z; + if (x !== cx >> zoomSteps || y !== cy >> zoomSteps) continue; + } + + // if we slice further down, no need to keep source geometry + tile.source = null; + + if (features.length === 0) continue; + + if (debug > 1) console.time('clipping'); + + // values we'll use for clipping + const k1 = 0.5 * options.buffer / options.extent; + const k2 = 0.5 - k1; + const k3 = 0.5 + k1; + const k4 = 1 + k1; + + let tl = null; + let bl = null; + let tr = null; + let br = null; + + let left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options); + let right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX, options); + features = null; + + if (left) { + tl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options); + bl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options); + left = null; + } + + if (right) { + tr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options); + br = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options); + right = null; + } + + if (debug > 1) console.timeEnd('clipping'); + + stack.push(tl || [], z + 1, x * 2, y * 2); + stack.push(bl || [], z + 1, x * 2, y * 2 + 1); + stack.push(tr || [], z + 1, x * 2 + 1, y * 2); + stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1); + } + } + + getTile(z, x, y) { + z = +z; + x = +x; + y = +y; + + const options = this.options; + const {extent, debug} = options; + + if (z < 0 || z > 24) return null; + + const z2 = 1 << z; + x = (x + z2) & (z2 - 1); // wrap tile x coordinate + + const id = toID(z, x, y); + if (this.tiles[id]) return transformTile(this.tiles[id], extent); + + if (debug > 1) console.log('drilling down to z%d-%d-%d', z, x, y); + + let z0 = z; + let x0 = x; + let y0 = y; + let parent; + + while (!parent && z0 > 0) { + z0--; + x0 = x0 >> 1; + y0 = y0 >> 1; + parent = this.tiles[toID(z0, x0, y0)]; + } + + if (!parent || !parent.source) return null; + + // if we found a parent tile containing the original geometry, we can drill down from it + if (debug > 1) { + console.log('found parent tile z%d-%d-%d', z0, x0, y0); + console.time('drilling down'); + } + this.splitTile(parent.source, z0, x0, y0, z, x, y); + if (debug > 1) console.timeEnd('drilling down'); + + return this.tiles[id] ? transformTile(this.tiles[id], extent) : null; + } +} + +function toID(z, x, y) { + return (((1 << z) * y + x) * 32) + z; +} + +function extend(dest, src) { + for (const i in src) dest[i] = src[i]; + return dest; +} + +function geojsonvt(data, options) { + return new GeoJSONVT(data, options); +} + +function getFeatureId(feature, promoteId) { + return promoteId ? feature.properties[promoteId] : feature.id; +} +function isUpdateableGeoJSON(data, promoteId) { + // null can be updated + if (data == null) { + return true; + } + // a single feature with an id can be updated, need to explicitly check against null because 0 is a valid feature id that is falsy + if (data.type === 'Feature') { + return getFeatureId(data, promoteId) != null; + } + // a feature collection can be updated if every feature has an id, and the ids are all unique + // this prevents us from silently dropping features if ids get reused + if (data.type === 'FeatureCollection') { + const seenIds = new Set(); + for (const feature of data.features) { + const id = getFeatureId(feature, promoteId); + if (id == null) { + return false; + } + if (seenIds.has(id)) { + return false; + } + seenIds.add(id); + } + return true; + } + return false; +} +function toUpdateable(data, promoteId) { + const result = new Map(); + if (data == null) { + // empty result + } + else if (data.type === 'Feature') { + result.set(getFeatureId(data, promoteId), data); + } + else { + for (const feature of data.features) { + result.set(getFeatureId(feature, promoteId), feature); + } + } + return result; +} +// mutates updateable +function applySourceDiff(updateable, diff, promoteId) { + var _a, _b, _c, _d; + if (diff.removeAll) { + updateable.clear(); + } + if (diff.remove) { + for (const id of diff.remove) { + updateable.delete(id); + } + } + if (diff.add) { + for (const feature of diff.add) { + const id = getFeatureId(feature, promoteId); + if (id != null) { + updateable.set(id, feature); + } + } + } + if (diff.update) { + for (const update of diff.update) { + let feature = updateable.get(update.id); + if (feature == null) { + continue; + } + // be careful to clone the feature and/or properties objects to avoid mutating our input + const cloneFeature = update.newGeometry || update.removeAllProperties; + // note: removeAllProperties gives us a new properties object, so we can skip the clone step + const cloneProperties = !update.removeAllProperties && (((_a = update.removeProperties) === null || _a === void 0 ? void 0 : _a.length) > 0 || ((_b = update.addOrUpdateProperties) === null || _b === void 0 ? void 0 : _b.length) > 0); + if (cloneFeature || cloneProperties) { + feature = Object.assign({}, feature); + updateable.set(update.id, feature); + if (cloneProperties) { + feature.properties = Object.assign({}, feature.properties); + } + } + if (update.newGeometry) { + feature.geometry = update.newGeometry; + } + if (update.removeAllProperties) { + feature.properties = {}; + } + else if (((_c = update.removeProperties) === null || _c === void 0 ? void 0 : _c.length) > 0) { + for (const prop of update.removeProperties) { + if (Object.prototype.hasOwnProperty.call(feature.properties, prop)) { + delete feature.properties[prop]; + } + } + } + if (((_d = update.addOrUpdateProperties) === null || _d === void 0 ? void 0 : _d.length) > 0) { + for (const { key, value } of update.addOrUpdateProperties) { + feature.properties[key] = value; + } + } + } + } +} + +/** + * The {@link WorkerSource} implementation that supports {@link GeoJSONSource}. + * This class is designed to be easily reused to support custom source types + * for data formats that can be parsed/converted into an in-memory GeoJSON + * representation. To do so, create it with + * `new GeoJSONWorkerSource(actor, layerIndex, customLoadGeoJSONFunction)`. + * For a full example, see [mapbox-gl-topojson](https://github.com/developmentseed/mapbox-gl-topojson). + */ +class GeoJSONWorkerSource extends VectorTileWorkerSource { + constructor() { + super(...arguments); + this._dataUpdateable = new Map(); + } + loadVectorTile(params, _abortController) { + return performance.__awaiter(this, void 0, void 0, function* () { + const canonical = params.tileID.canonical; + if (!this._geoJSONIndex) { + throw new Error('Unable to parse the data into a cluster or geojson'); + } + const geoJSONTile = this._geoJSONIndex.getTile(canonical.z, canonical.x, canonical.y); + if (!geoJSONTile) { + return null; + } + const geojsonWrapper = new GeoJSONWrapper$2(geoJSONTile.features); + // Encode the geojson-vt tile into binary vector tile form. This + // is a convenience that allows `FeatureIndex` to operate the same way + // across `VectorTileSource` and `GeoJSONSource` data. + let pbf = vtpbf(geojsonWrapper); + if (pbf.byteOffset !== 0 || pbf.byteLength !== pbf.buffer.byteLength) { + // Compatibility with node Buffer (https://github.com/mapbox/pbf/issues/35) + pbf = new Uint8Array(pbf); + } + return { + vectorTile: geojsonWrapper, + rawData: pbf.buffer + }; + }); + } + /** + * Fetches (if appropriate), parses, and index geojson data into tiles. This + * preparatory method must be called before {@link GeoJSONWorkerSource#loadTile} + * can correctly serve up tiles. + * + * Defers to {@link GeoJSONWorkerSource#loadAndProcessGeoJSON} for the pre-processing. + * + * When a `loadData` request comes in while a previous one is being processed, + * the previous one is aborted. + * + * @param params - the parameters + * @returns a promise that resolves when the data is loaded and parsed into a GeoJSON object + */ + loadData(params) { + return performance.__awaiter(this, void 0, void 0, function* () { + var _a; + (_a = this._pendingRequest) === null || _a === void 0 ? void 0 : _a.abort(); + const perf = (params && params.request && params.request.collectResourceTiming) ? + new performance.RequestPerformance(params.request) : false; + this._pendingRequest = new AbortController(); + try { + this._pendingData = this.loadAndProcessGeoJSON(params, this._pendingRequest); + this._geoJSONIndex = params.cluster ? + new Supercluster(getSuperclusterOptions(params)).load((yield this._pendingData).features) : + geojsonvt(yield this._pendingData, params.geojsonVtOptions); + this.loaded = {}; + const result = {}; + if (perf) { + const resourceTimingData = perf.finish(); + // it's necessary to eval the result of getEntriesByName() here via parse/stringify + // late evaluation in the main thread causes TypeError: illegal invocation + if (resourceTimingData) { + result.resourceTiming = {}; + result.resourceTiming[params.source] = JSON.parse(JSON.stringify(resourceTimingData)); + } + } + return result; + } + catch (err) { + delete this._pendingRequest; + if (performance.isAbortError(err)) { + return { abandoned: true }; + } + throw err; + } + }); + } + /** + * Allows to get the source's actual GeoJSON. + * + * @returns a promise which is resolved with the source's actual GeoJSON + */ + getData() { + return performance.__awaiter(this, void 0, void 0, function* () { + return this._pendingData; + }); + } + /** + * Implements {@link WorkerSource#reloadTile}. + * + * If the tile is loaded, uses the implementation in VectorTileWorkerSource. + * Otherwise, such as after a setData() call, we load the tile fresh. + * + * @param params - the parameters + * @returns A promise that resolves when the tile is reloaded + */ + reloadTile(params) { + const loaded = this.loaded, uid = params.uid; + if (loaded && loaded[uid]) { + return super.reloadTile(params); + } + else { + return this.loadTile(params); + } + } + /** + * Fetch, parse and process GeoJSON according to the given params. + * + * Defers to {@link GeoJSONWorkerSource#loadGeoJSON} for the fetching and parsing. + * + * @param params - the parameters + * @param abortController - the abort controller that allows aborting this operation + * @returns a promise that is resolved with the processes GeoJSON + */ + loadAndProcessGeoJSON(params, abortController) { + return performance.__awaiter(this, void 0, void 0, function* () { + let data = yield this.loadGeoJSON(params, abortController); + delete this._pendingRequest; + if (typeof data !== 'object') { + throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`); + } + rewind$2(data, true); + if (params.filter) { + const compiled = performance.createExpression(params.filter, { type: 'boolean', 'property-type': 'data-driven', overridable: false, transition: false }); + if (compiled.result === 'error') + throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', ')); + const features = data.features.filter(feature => compiled.value.evaluate({ zoom: 0 }, feature)); + data = { type: 'FeatureCollection', features }; + } + return data; + }); + } + /** + * Fetch and parse GeoJSON according to the given params. + * + * GeoJSON is loaded and parsed from `params.url` if it exists, or else + * expected as a literal (string or object) `params.data`. + * + * @param params - the parameters + * @param abortController - the abort controller that allows aborting this operation + * @returns a promise that resolves when the data is loaded + */ + loadGeoJSON(params, abortController) { + return performance.__awaiter(this, void 0, void 0, function* () { + const { promoteId } = params; + if (params.request) { + const response = yield performance.getJSON(params.request, abortController); + this._dataUpdateable = isUpdateableGeoJSON(response.data, promoteId) ? toUpdateable(response.data, promoteId) : undefined; + return response.data; + } + if (typeof params.data === 'string') { + try { + const parsed = JSON.parse(params.data); + this._dataUpdateable = isUpdateableGeoJSON(parsed, promoteId) ? toUpdateable(parsed, promoteId) : undefined; + return parsed; + } + catch (e) { + throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`); + } + } + if (!params.dataDiff) { + throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`); + } + if (!this._dataUpdateable) { + throw new Error(`Cannot update existing geojson data in ${params.source}`); + } + applySourceDiff(this._dataUpdateable, params.dataDiff, promoteId); + return { type: 'FeatureCollection', features: Array.from(this._dataUpdateable.values()) }; + }); + } + removeSource(_params) { + return performance.__awaiter(this, void 0, void 0, function* () { + if (this._pendingRequest) { + this._pendingRequest.abort(); + } + }); + } + getClusterExpansionZoom(params) { + return this._geoJSONIndex.getClusterExpansionZoom(params.clusterId); + } + getClusterChildren(params) { + return this._geoJSONIndex.getChildren(params.clusterId); + } + getClusterLeaves(params) { + return this._geoJSONIndex.getLeaves(params.clusterId, params.limit, params.offset); + } +} +function getSuperclusterOptions({ superclusterOptions, clusterProperties }) { + if (!clusterProperties || !superclusterOptions) + return superclusterOptions; + const mapExpressions = {}; + const reduceExpressions = {}; + const globals = { accumulated: null, zoom: 0 }; + const feature = { properties: null }; + const propertyNames = Object.keys(clusterProperties); + for (const key of propertyNames) { + const [operator, mapExpression] = clusterProperties[key]; + const mapExpressionParsed = performance.createExpression(mapExpression); + const reduceExpressionParsed = performance.createExpression(typeof operator === 'string' ? [operator, ['accumulated'], ['get', key]] : operator); + mapExpressions[key] = mapExpressionParsed.value; + reduceExpressions[key] = reduceExpressionParsed.value; + } + superclusterOptions.map = (pointProperties) => { + feature.properties = pointProperties; + const properties = {}; + for (const key of propertyNames) { + properties[key] = mapExpressions[key].evaluate(globals, feature); + } + return properties; + }; + superclusterOptions.reduce = (accumulated, clusterProperties) => { + feature.properties = clusterProperties; + for (const key of propertyNames) { + globals.accumulated = accumulated[key]; + accumulated[key] = reduceExpressions[key].evaluate(globals, feature); + } + }; + return superclusterOptions; +} + +/** + * The Worker class responsible for background thread related execution + */ +class Worker { + constructor(self) { + this.self = self; + this.actor = new performance.Actor(self); + this.layerIndexes = {}; + this.availableImages = {}; + this.workerSources = {}; + this.demWorkerSources = {}; + this.externalWorkerSourceTypes = {}; + this.self.registerWorkerSource = (name, WorkerSource) => { + if (this.externalWorkerSourceTypes[name]) { + throw new Error(`Worker source with name "${name}" already registered.`); + } + this.externalWorkerSourceTypes[name] = WorkerSource; + }; + this.self.addProtocol = performance.addProtocol; + this.self.removeProtocol = performance.removeProtocol; + // This is invoked by the RTL text plugin when the download via the `importScripts` call has finished, and the code has been parsed. + this.self.registerRTLTextPlugin = (rtlTextPlugin) => { + if (performance.rtlWorkerPlugin.isParsed()) { + throw new Error('RTL text plugin already registered.'); + } + performance.rtlWorkerPlugin.setMethods(rtlTextPlugin); + }; + this.actor.registerMessageHandler("LDT" /* MessageType.loadDEMTile */, (mapId, params) => { + return this._getDEMWorkerSource(mapId, params.source).loadTile(params); + }); + this.actor.registerMessageHandler("RDT" /* MessageType.removeDEMTile */, (mapId, params) => performance.__awaiter(this, void 0, void 0, function* () { + this._getDEMWorkerSource(mapId, params.source).removeTile(params); + })); + this.actor.registerMessageHandler("GCEZ" /* MessageType.getClusterExpansionZoom */, (mapId, params) => performance.__awaiter(this, void 0, void 0, function* () { + return this._getWorkerSource(mapId, params.type, params.source).getClusterExpansionZoom(params); + })); + this.actor.registerMessageHandler("GCC" /* MessageType.getClusterChildren */, (mapId, params) => performance.__awaiter(this, void 0, void 0, function* () { + return this._getWorkerSource(mapId, params.type, params.source).getClusterChildren(params); + })); + this.actor.registerMessageHandler("GCL" /* MessageType.getClusterLeaves */, (mapId, params) => performance.__awaiter(this, void 0, void 0, function* () { + return this._getWorkerSource(mapId, params.type, params.source).getClusterLeaves(params); + })); + this.actor.registerMessageHandler("LD" /* MessageType.loadData */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).loadData(params); + }); + this.actor.registerMessageHandler("GD" /* MessageType.getData */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).getData(); + }); + this.actor.registerMessageHandler("LT" /* MessageType.loadTile */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).loadTile(params); + }); + this.actor.registerMessageHandler("RT" /* MessageType.reloadTile */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).reloadTile(params); + }); + this.actor.registerMessageHandler("AT" /* MessageType.abortTile */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).abortTile(params); + }); + this.actor.registerMessageHandler("RMT" /* MessageType.removeTile */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).removeTile(params); + }); + this.actor.registerMessageHandler("RS" /* MessageType.removeSource */, (mapId, params) => performance.__awaiter(this, void 0, void 0, function* () { + if (!this.workerSources[mapId] || + !this.workerSources[mapId][params.type] || + !this.workerSources[mapId][params.type][params.source]) { + return; + } + const worker = this.workerSources[mapId][params.type][params.source]; + delete this.workerSources[mapId][params.type][params.source]; + if (worker.removeSource !== undefined) { + worker.removeSource(params); + } + })); + this.actor.registerMessageHandler("RM" /* MessageType.removeMap */, (mapId) => performance.__awaiter(this, void 0, void 0, function* () { + delete this.layerIndexes[mapId]; + delete this.availableImages[mapId]; + delete this.workerSources[mapId]; + delete this.demWorkerSources[mapId]; + })); + this.actor.registerMessageHandler("SR" /* MessageType.setReferrer */, (_mapId, params) => performance.__awaiter(this, void 0, void 0, function* () { + this.referrer = params; + })); + this.actor.registerMessageHandler("SRPS" /* MessageType.syncRTLPluginState */, (mapId, params) => { + return this._syncRTLPluginState(mapId, params); + }); + this.actor.registerMessageHandler("IS" /* MessageType.importScript */, (_mapId, params) => performance.__awaiter(this, void 0, void 0, function* () { + this.self.importScripts(params); + })); + this.actor.registerMessageHandler("SI" /* MessageType.setImages */, (mapId, params) => { + return this._setImages(mapId, params); + }); + this.actor.registerMessageHandler("UL" /* MessageType.updateLayers */, (mapId, params) => performance.__awaiter(this, void 0, void 0, function* () { + this._getLayerIndex(mapId).update(params.layers, params.removedIds); + })); + this.actor.registerMessageHandler("SL" /* MessageType.setLayers */, (mapId, params) => performance.__awaiter(this, void 0, void 0, function* () { + this._getLayerIndex(mapId).replace(params); + })); + } + _setImages(mapId, images) { + return performance.__awaiter(this, void 0, void 0, function* () { + this.availableImages[mapId] = images; + for (const workerSource in this.workerSources[mapId]) { + const ws = this.workerSources[mapId][workerSource]; + for (const source in ws) { + ws[source].availableImages = images; + } + } + }); + } + _syncRTLPluginState(mapId, incomingState) { + return performance.__awaiter(this, void 0, void 0, function* () { + // Parsed plugin cannot be changed, so just return its current state. + if (performance.rtlWorkerPlugin.isParsed()) { + return performance.rtlWorkerPlugin.getState(); + } + if (incomingState.pluginStatus !== 'loading') { + // simply sync and done + performance.rtlWorkerPlugin.setState(incomingState); + return incomingState; + } + const urlToLoad = incomingState.pluginURL; + this.self.importScripts(urlToLoad); + const complete = performance.rtlWorkerPlugin.isParsed(); + if (complete) { + const loadedState = { + pluginStatus: 'loaded', + pluginURL: urlToLoad + }; + performance.rtlWorkerPlugin.setState(loadedState); + return loadedState; + } + // error case + performance.rtlWorkerPlugin.setState({ + pluginStatus: 'error', + pluginURL: '' + }); + throw new Error(`RTL Text Plugin failed to import scripts from ${urlToLoad}`); + }); + } + _getAvailableImages(mapId) { + let availableImages = this.availableImages[mapId]; + if (!availableImages) { + availableImages = []; + } + return availableImages; + } + _getLayerIndex(mapId) { + let layerIndexes = this.layerIndexes[mapId]; + if (!layerIndexes) { + layerIndexes = this.layerIndexes[mapId] = new StyleLayerIndex(); + } + return layerIndexes; + } + /** + * This is basically a lazy initialization of a worker per mapId and sourceType and sourceName + * @param mapId - the mapId + * @param sourceType - the source type - 'vector' for example + * @param sourceName - the source name - 'osm' for example + * @returns a new instance or a cached one + */ + _getWorkerSource(mapId, sourceType, sourceName) { + if (!this.workerSources[mapId]) + this.workerSources[mapId] = {}; + if (!this.workerSources[mapId][sourceType]) + this.workerSources[mapId][sourceType] = {}; + if (!this.workerSources[mapId][sourceType][sourceName]) { + // use a wrapped actor so that we can attach a target mapId param + // to any messages invoked by the WorkerSource, this is very important when there are multiple maps + const actor = { + sendAsync: (message, abortController) => { + message.targetMapId = mapId; + return this.actor.sendAsync(message, abortController); + } + }; + switch (sourceType) { + case 'vector': + this.workerSources[mapId][sourceType][sourceName] = new VectorTileWorkerSource(actor, this._getLayerIndex(mapId), this._getAvailableImages(mapId)); + break; + case 'geojson': + this.workerSources[mapId][sourceType][sourceName] = new GeoJSONWorkerSource(actor, this._getLayerIndex(mapId), this._getAvailableImages(mapId)); + break; + default: + this.workerSources[mapId][sourceType][sourceName] = new (this.externalWorkerSourceTypes[sourceType])(actor, this._getLayerIndex(mapId), this._getAvailableImages(mapId)); + break; + } + } + return this.workerSources[mapId][sourceType][sourceName]; + } + /** + * This is basically a lazy initialization of a worker per mapId and source + * @param mapId - the mapId + * @param sourceType - the source type - 'raster-dem' for example + * @returns a new instance or a cached one + */ + _getDEMWorkerSource(mapId, sourceType) { + if (!this.demWorkerSources[mapId]) + this.demWorkerSources[mapId] = {}; + if (!this.demWorkerSources[mapId][sourceType]) { + this.demWorkerSources[mapId][sourceType] = new RasterDEMTileWorkerSource(); + } + return this.demWorkerSources[mapId][sourceType]; + } +} +if (performance.isWorker(self)) { + self.worker = new Worker(self); +} + +return Worker; + +})); + +define('index', ['exports', './shared'], (function (exports, performance$1) { 'use strict'; + +var name = "maplibre-gl"; +var description = "BSD licensed community fork of mapbox-gl, a WebGL interactive maps library"; +var version$2 = "4.7.0"; +var main = "dist/maplibre-gl.js"; +var style = "dist/maplibre-gl.css"; +var license = "BSD-3-Clause"; +var homepage = "https://maplibre.org/"; +var funding = "https://github.com/maplibre/maplibre-gl-js?sponsor=1"; +var bugs = { + url: "https://github.com/maplibre/maplibre-gl-js/issues/" +}; +var repository = { + type: "git", + url: "git://github.com/maplibre/maplibre-gl-js.git" +}; +var types = "dist/maplibre-gl.d.ts"; +var type = "module"; +var dependencies = { + "@mapbox/geojson-rewind": "^0.5.2", + "@mapbox/jsonlint-lines-primitives": "^2.0.2", + "@mapbox/point-geometry": "^0.1.0", + "@mapbox/tiny-sdf": "^2.0.6", + "@mapbox/unitbezier": "^0.0.1", + "@mapbox/vector-tile": "^1.3.1", + "@mapbox/whoots-js": "^3.1.0", + "@maplibre/maplibre-gl-style-spec": "^20.3.1", + "@types/geojson": "^7946.0.14", + "@types/geojson-vt": "3.2.5", + "@types/mapbox__point-geometry": "^0.1.4", + "@types/mapbox__vector-tile": "^1.3.4", + "@types/pbf": "^3.0.5", + "@types/supercluster": "^7.1.3", + earcut: "^3.0.0", + "geojson-vt": "^4.0.2", + "gl-matrix": "^3.4.3", + "global-prefix": "^4.0.0", + kdbush: "^4.0.2", + "murmurhash-js": "^1.0.0", + pbf: "^3.3.0", + potpack: "^2.0.0", + quickselect: "^3.0.0", + supercluster: "^8.0.1", + tinyqueue: "^3.0.0", + "vt-pbf": "^3.1.3" +}; +var devDependencies = { + autoprefixer: "^10.4.20", + "@mapbox/mapbox-gl-rtl-text": "^0.3.0", + "@mapbox/mvt-fixtures": "^3.10.0", + "@rollup/plugin-commonjs": "^26.0.1", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-replace": "^5.0.7", + "@rollup/plugin-strip": "^3.0.4", + "@rollup/plugin-terser": "^0.4.4", + "@rollup/plugin-typescript": "^11.1.6", + "@types/benchmark": "^2.1.5", + "@types/cssnano": "^5.0.0", + "@types/d3": "^7.4.3", + "@types/diff": "^5.2.2", + "@types/earcut": "^2.1.4", + "@types/eslint": "^8.56.7", + "@types/gl": "^6.0.5", + "@types/glob": "^8.1.0", + "@types/jest": "^29.5.12", + "@types/jsdom": "^21.1.7", + "@types/minimist": "^1.2.5", + "@types/murmurhash-js": "^1.0.6", + "@types/nise": "^1.4.5", + "@types/node": "^22.5.4", + "@types/offscreencanvas": "^2019.7.3", + "@types/pixelmatch": "^5.2.6", + "@types/pngjs": "^6.0.5", + "@types/react": "^18.3.5", + "@types/react-dom": "^18.3.0", + "@types/request": "^2.48.12", + "@types/shuffle-seed": "^1.1.3", + "@types/window-or-global": "^1.0.6", + "@typescript-eslint/eslint-plugin": "^7.18.0", + "@typescript-eslint/parser": "^7.18.0", + address: "^2.0.3", + benchmark: "^2.1.4", + canvas: "^2.11.2", + cssnano: "^7.0.6", + d3: "^7.9.0", + "d3-queue": "^3.0.7", + "devtools-protocol": "^0.0.1352404", + diff: "^7.0.0", + "dts-bundle-generator": "^9.5.1", + eslint: "^8.57.0", + "eslint-config-mourner": "^3.0.0", + "eslint-plugin-html": "^8.1.1", + "eslint-plugin-import": "^2.30.0", + "eslint-plugin-jest": "^28.8.3", + "eslint-plugin-react": "^7.35.2", + "eslint-plugin-tsdoc": "0.3.0", + expect: "^29.7.0", + glob: "^11.0.0", + "is-builtin-module": "^4.0.0", + jest: "^29.7.0", + "jest-environment-jsdom": "^29.7.0", + "jest-junit": "^16.0.0", + "jest-monocart-coverage": "^1.1.1", + "jest-webgl-canvas-mock": "^2.5.3", + jsdom: "^25.0.0", + "junit-report-builder": "^5.0.0", + minimist: "^1.2.8", + "mock-geolocation": "^1.0.11", + "monocart-coverage-reports": "^2.10.3", + nise: "^6.0.0", + "npm-font-open-sans": "^1.1.0", + "npm-run-all": "^4.1.5", + "pdf-merger-js": "^5.1.2", + pixelmatch: "^6.0.0", + pngjs: "^7.0.0", + postcss: "^8.4.45", + "postcss-cli": "^11.0.0", + "postcss-inline-svg": "^6.0.0", + "pretty-bytes": "^6.1.1", + puppeteer: "^23.3.0", + react: "^18.3.1", + "react-dom": "^18.3.1", + rollup: "^4.21.2", + "rollup-plugin-sourcemaps": "^0.6.3", + rw: "^1.3.3", + semver: "^7.6.3", + "shuffle-seed": "^1.1.6", + "source-map-explorer": "^2.5.3", + st: "^3.0.0", + stylelint: "^16.9.0", + "stylelint-config-standard": "^36.0.1", + "ts-jest": "^29.2.5", + "ts-node": "^10.9.2", + tslib: "^2.7.0", + typedoc: "^0.26.6", + "typedoc-plugin-markdown": "^4.2.7", + "typedoc-plugin-missing-exports": "^3.0.0", + typescript: "^5.5.4" +}; +var scripts = { + "generate-dist-package": "node --no-warnings --loader ts-node/esm build/generate-dist-package.js", + "generate-shaders": "node --no-warnings --loader ts-node/esm build/generate-shaders.ts", + "generate-struct-arrays": "node --no-warnings --loader ts-node/esm build/generate-struct-arrays.ts", + "generate-style-code": "node --no-warnings --loader ts-node/esm build/generate-style-code.ts", + "generate-typings": "dts-bundle-generator --export-referenced-types --umd-module-name=maplibregl -o ./dist/maplibre-gl.d.ts ./src/index.ts", + "generate-docs": "typedoc && node --no-warnings --loader ts-node/esm build/generate-docs.ts", + "generate-images": "node --no-warnings --loader ts-node/esm build/generate-doc-images.ts", + "build-dist": "npm run build-css && npm run generate-typings && npm run build-dev && npm run build-csp-dev && npm run build-prod && npm run build-prod-unminified && npm run build-csp", + "build-dev": "rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:dev", + "watch-dev": "rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:dev --watch", + "build-prod": "rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:production,MINIFY:true", + "build-prod-unminified": "rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:production", + "build-csp": "rollup --configPlugin @rollup/plugin-typescript -c rollup.config.csp.ts --environment BUILD:production,MINIFY:true", + "build-csp-dev": "rollup --configPlugin @rollup/plugin-typescript -c rollup.config.csp.ts --environment BUILD:dev", + "build-css": "postcss -o dist/maplibre-gl.css src/css/maplibre-gl.css", + "watch-css": "postcss --watch -o dist/maplibre-gl.css src/css/maplibre-gl.css", + "build-benchmarks": "npm run build-dev && rollup --configPlugin @rollup/plugin-typescript -c test/bench/rollup_config_benchmarks.ts", + "watch-benchmarks": "rollup --configPlugin @rollup/plugin-typescript -c test/bench/rollup_config_benchmarks.ts --watch", + "start-server": "st --no-cache -H localhost --port 9966 .", + "start-docs": "docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material", + start: "run-p watch-css watch-dev start-server", + "start-bench": "run-p watch-css watch-benchmarks start-server", + lint: "eslint --cache --ext .ts,.tsx,.js,.html --ignore-path .gitignore .", + "lint-css": "stylelint **/*.css --fix -f verbose", + test: "run-p lint lint-css test-render jest", + jest: "jest", + "test-build": "jest --selectProjects=build --reporters=default", + "test-build-ci": "jest --selectProjects=build", + "test-integration": "jest --selectProjects=integration --reporters=default", + "test-integration-ci": "jest --coverage --selectProjects=integration", + "test-render": "node --no-warnings --loader ts-node/esm test/integration/render/run_render_tests.ts", + "test-unit": "jest --selectProjects=unit --reporters=default", + "test-unit-ci": "jest --coverage --selectProjects unit", + "test-watch-roots": "jest --watch", + codegen: "run-p --print-label generate-dist-package generate-style-code generate-struct-arrays generate-shaders && npm run generate-typings", + benchmark: "node --no-warnings --loader ts-node/esm test/bench/run-benchmarks.ts", + "gl-stats": "node --no-warnings --loader ts-node/esm test/bench/gl-stats.ts", + prepare: "npm run codegen", + typecheck: "tsc --noEmit && tsc --project tsconfig.dist.json", + tsnode: "node --experimental-loader=ts-node/esm --no-warnings" +}; +var files = [ + "build/", + "dist/*", + "src/" +]; +var engines = { + npm: ">=8.1.0", + node: ">=16.14.0" +}; +var packageJSON = { + name: name, + description: description, + version: version$2, + main: main, + style: style, + license: license, + homepage: homepage, + funding: funding, + bugs: bugs, + repository: repository, + types: types, + type: type, + dependencies: dependencies, + devDependencies: devDependencies, + scripts: scripts, + files: files, + engines: engines +}; + +const now = typeof performance !== 'undefined' && performance && performance.now ? + performance.now.bind(performance) : + Date.now.bind(Date); +let linkEl; +let reducedMotionQuery; +/** */ +const browser = { + /** + * Provides a function that outputs milliseconds: either performance.now() + * or a fallback to Date.now() + */ + now, + frameAsync(abortController) { + return new Promise((resolve, reject) => { + const frame = requestAnimationFrame(resolve); + abortController.signal.addEventListener('abort', () => { + cancelAnimationFrame(frame); + reject(performance$1.createAbortError()); + }); + }); + }, + getImageData(img, padding = 0) { + const context = this.getImageCanvasContext(img); + return context.getImageData(-padding, -padding, img.width + 2 * padding, img.height + 2 * padding); + }, + getImageCanvasContext(img) { + const canvas = window.document.createElement('canvas'); + const context = canvas.getContext('2d', { willReadFrequently: true }); + if (!context) { + throw new Error('failed to create canvas 2d context'); + } + canvas.width = img.width; + canvas.height = img.height; + context.drawImage(img, 0, 0, img.width, img.height); + return context; + }, + resolveURL(path) { + if (!linkEl) + linkEl = document.createElement('a'); + linkEl.href = path; + return linkEl.href; + }, + hardwareConcurrency: typeof navigator !== 'undefined' && navigator.hardwareConcurrency || 4, + get prefersReducedMotion() { + // In case your test crashes when checking matchMedia, call setMatchMedia from 'src/util/test/util' + if (!matchMedia) + return false; + //Lazily initialize media query + if (reducedMotionQuery == null) { + reducedMotionQuery = matchMedia('(prefers-reduced-motion: reduce)'); + } + return reducedMotionQuery.matches; + }, +}; + +class DOM { + static testProp(props) { + if (!DOM.docStyle) + return props[0]; + for (let i = 0; i < props.length; i++) { + if (props[i] in DOM.docStyle) { + return props[i]; + } + } + return props[0]; + } + static create(tagName, className, container) { + const el = window.document.createElement(tagName); + if (className !== undefined) + el.className = className; + if (container) + container.appendChild(el); + return el; + } + static createNS(namespaceURI, tagName) { + const el = window.document.createElementNS(namespaceURI, tagName); + return el; + } + static disableDrag() { + if (DOM.docStyle && DOM.selectProp) { + DOM.userSelect = DOM.docStyle[DOM.selectProp]; + DOM.docStyle[DOM.selectProp] = 'none'; + } + } + static enableDrag() { + if (DOM.docStyle && DOM.selectProp) { + DOM.docStyle[DOM.selectProp] = DOM.userSelect; + } + } + static setTransform(el, value) { + el.style[DOM.transformProp] = value; + } + static addEventListener(target, type, callback, options = {}) { + if ('passive' in options) { + target.addEventListener(type, callback, options); + } + else { + target.addEventListener(type, callback, options.capture); + } + } + static removeEventListener(target, type, callback, options = {}) { + if ('passive' in options) { + target.removeEventListener(type, callback, options); + } + else { + target.removeEventListener(type, callback, options.capture); + } + } + // Suppress the next click, but only if it's immediate. + static suppressClickInternal(e) { + e.preventDefault(); + e.stopPropagation(); + window.removeEventListener('click', DOM.suppressClickInternal, true); + } + static suppressClick() { + window.addEventListener('click', DOM.suppressClickInternal, true); + window.setTimeout(() => { + window.removeEventListener('click', DOM.suppressClickInternal, true); + }, 0); + } + static getScale(element) { + const rect = element.getBoundingClientRect(); + return { + x: (rect.width / element.offsetWidth) || 1, + y: (rect.height / element.offsetHeight) || 1, + boundingClientRect: rect, + }; + } + static getPoint(el, scale, e) { + const rect = scale.boundingClientRect; + return new performance$1.Point( + // rect.left/top values are in page scale (like clientX/Y), + // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies). + ((e.clientX - rect.left) / scale.x) - el.clientLeft, ((e.clientY - rect.top) / scale.y) - el.clientTop); + } + static mousePos(el, e) { + const scale = DOM.getScale(el); + return DOM.getPoint(el, scale, e); + } + static touchPos(el, touches) { + const points = []; + const scale = DOM.getScale(el); + for (let i = 0; i < touches.length; i++) { + points.push(DOM.getPoint(el, scale, touches[i])); + } + return points; + } + static mouseButton(e) { + return e.button; + } + static remove(node) { + if (node.parentNode) { + node.parentNode.removeChild(node); + } + } +} +DOM.docStyle = typeof window !== 'undefined' && window.document && window.document.documentElement.style; +DOM.selectProp = DOM.testProp(['userSelect', 'MozUserSelect', 'WebkitUserSelect', 'msUserSelect']); +DOM.transformProp = DOM.testProp(['transform', 'WebkitTransform']); + +const webpSupported = { + supported: false, + testSupport +}; +let glForTesting; +let webpCheckComplete = false; +let webpImgTest; +let webpImgTestOnloadComplete = false; +if (typeof document !== 'undefined') { + webpImgTest = document.createElement('img'); + webpImgTest.onload = () => { + if (glForTesting) + testWebpTextureUpload(glForTesting); + glForTesting = null; + webpImgTestOnloadComplete = true; + }; + webpImgTest.onerror = () => { + webpCheckComplete = true; + glForTesting = null; + }; + webpImgTest.src = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA='; +} +function testSupport(gl) { + if (webpCheckComplete || !webpImgTest) + return; + // HTMLImageElement.complete is set when an image is done loading it's source + // regardless of whether the load was successful or not. + // It's possible for an error to set HTMLImageElement.complete to true which would trigger + // testWebpTextureUpload and mistakenly set exported.supported to true in browsers which don't support webp + // To avoid this, we set a flag in the image's onload handler and only call testWebpTextureUpload + // after a successful image load event. + if (webpImgTestOnloadComplete) { + testWebpTextureUpload(gl); + } + else { + glForTesting = gl; + } +} +function testWebpTextureUpload(gl) { + // Edge 18 supports WebP but not uploading a WebP image to a gl texture + // Test support for this before allowing WebP images. + // https://github.com/mapbox/mapbox-gl-js/issues/7671 + const texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + try { + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, webpImgTest); + // The error does not get triggered in Edge if the context is lost + if (gl.isContextLost()) + return; + webpSupported.supported = true; + } + catch (e) { + // Catch "Unspecified Error." in Edge 18. + } + gl.deleteTexture(texture); + webpCheckComplete = true; +} + +/** + * By default, the image queue is self driven, meaning as soon as one requested item is processed, + * it will move on to next one as quickly as it can while limiting + * the number of concurrent requests to MAX_PARALLEL_IMAGE_REQUESTS. The default behavior + * ensures that static views of the map can be rendered with minimal delay. + * + * However, the default behavior can prevent dynamic views of the map from rendering + * smoothly in that many requests can finish in one render frame, putting too much pressure on GPU. + * + * When the view of the map is moving dynamically, smoother frame rates can be achieved + * by throttling the number of items processed by the queue per frame. This can be + * accomplished by using {@link addThrottleControl} to allow the caller to + * use a lambda function to determine when the queue should be throttled (e.g. when isMoving()) + * and manually calling {@link processQueue} in the render loop. + */ +var ImageRequest; +(function (ImageRequest) { + let imageRequestQueue; + let currentParallelImageRequests; + let throttleControlCallbackHandleCounter; + let throttleControlCallbacks; + /** + * Reset the image request queue, removing all pending requests. + */ + ImageRequest.resetRequestQueue = () => { + imageRequestQueue = []; + currentParallelImageRequests = 0; + throttleControlCallbackHandleCounter = 0; + throttleControlCallbacks = {}; + }; + /** + * Install a callback to control when image queue throttling is desired. + * (e.g. when the map view is moving) + * @param callback - The callback function to install + * @returns handle that identifies the installed callback. + */ + ImageRequest.addThrottleControl = (callback) => { + const handle = throttleControlCallbackHandleCounter++; + throttleControlCallbacks[handle] = callback; + return handle; + }; + /** + * Remove a previously installed callback by passing in the handle returned + * by {@link addThrottleControl}. + * @param callbackHandle - The handle for the callback to remove. + */ + ImageRequest.removeThrottleControl = (callbackHandle) => { + delete throttleControlCallbacks[callbackHandle]; + // Try updating the queue + processQueue(); + }; + /** + * Check to see if any of the installed callbacks are requesting the queue + * to be throttled. + * @returns `true` if any callback is causing the queue to be throttled. + */ + const isThrottled = () => { + for (const key of Object.keys(throttleControlCallbacks)) { + if (throttleControlCallbacks[key]()) { + return true; + } + } + return false; + }; + /** + * Request to load an image. + * @param requestParameters - Request parameters. + * @param abortController - allows to abort the request. + * @param supportImageRefresh - `true`, if the image request need to support refresh based on cache headers. + * @returns - A promise resolved when the image is loaded. + */ + ImageRequest.getImage = (requestParameters, abortController, supportImageRefresh = true) => { + return new Promise((resolve, reject) => { + if (webpSupported.supported) { + if (!requestParameters.headers) { + requestParameters.headers = {}; + } + requestParameters.headers.accept = 'image/webp,*/*'; + } + performance$1.extend(requestParameters, { type: 'image' }); + const request = { + abortController, + requestParameters, + supportImageRefresh, + state: 'queued', + onError: (error) => { + reject(error); + }, + onSuccess: (response) => { + resolve(response); + } + }; + imageRequestQueue.push(request); + processQueue(); + }); + }; + const arrayBufferToCanvasImageSource = (data) => { + const imageBitmapSupported = typeof createImageBitmap === 'function'; + if (imageBitmapSupported) { + return performance$1.arrayBufferToImageBitmap(data); + } + else { + return performance$1.arrayBufferToImage(data); + } + }; + const doImageRequest = (itemInQueue) => performance$1.__awaiter(this, void 0, void 0, function* () { + itemInQueue.state = 'running'; + const { requestParameters, supportImageRefresh, onError, onSuccess, abortController } = itemInQueue; + // - If refreshExpiredTiles is false, then we can use HTMLImageElement to download raster images. + // - Fetch/XHR (via MakeRequest API) will be used to download images for following scenarios: + // 1. Style image sprite will had a issue with HTMLImageElement as described + // here: https://github.com/mapbox/mapbox-gl-js/issues/1470 + // 2. If refreshExpiredTiles is true (default), then in order to read the image cache header, + // fetch/XHR request will be required + // - For any special case handling like use of AddProtocol, worker initiated request or additional headers + // let makeRequest handle it. + // - HtmlImageElement request automatically adds accept header for all the browser supported images + const canUseHTMLImageElement = supportImageRefresh === false && + !performance$1.isWorker(self) && + !performance$1.getProtocol(requestParameters.url) && + (!requestParameters.headers || + Object.keys(requestParameters.headers).reduce((acc, item) => acc && item === 'accept', true)); + currentParallelImageRequests++; + const getImagePromise = canUseHTMLImageElement ? + getImageUsingHtmlImage(requestParameters, abortController) : + performance$1.makeRequest(requestParameters, abortController); + try { + const response = yield getImagePromise; + delete itemInQueue.abortController; + itemInQueue.state = 'completed'; + if (response.data instanceof HTMLImageElement || performance$1.isImageBitmap(response.data)) { + // User using addProtocol can directly return HTMLImageElement/ImageBitmap type + // If HtmlImageElement is used to get image then response type will be HTMLImageElement + onSuccess(response); + } + else if (response.data) { + const img = yield arrayBufferToCanvasImageSource(response.data); + onSuccess({ data: img, cacheControl: response.cacheControl, expires: response.expires }); + } + } + catch (err) { + delete itemInQueue.abortController; + onError(err); + } + finally { + currentParallelImageRequests--; + processQueue(); + } + }); + /** + * Process some number of items in the image request queue. + */ + const processQueue = () => { + const maxImageRequests = isThrottled() ? + performance$1.config.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME : + performance$1.config.MAX_PARALLEL_IMAGE_REQUESTS; + // limit concurrent image loads to help with raster sources performance on big screens + for (let numImageRequests = currentParallelImageRequests; numImageRequests < maxImageRequests && imageRequestQueue.length > 0; numImageRequests++) { + const topItemInQueue = imageRequestQueue.shift(); + if (topItemInQueue.abortController.signal.aborted) { + numImageRequests--; + continue; + } + doImageRequest(topItemInQueue); + } + }; + const getImageUsingHtmlImage = (requestParameters, abortController) => { + return new Promise((resolve, reject) => { + const image = new Image(); + const url = requestParameters.url; + const credentials = requestParameters.credentials; + if (credentials && credentials === 'include') { + image.crossOrigin = 'use-credentials'; + } + else if ((credentials && credentials === 'same-origin') || !performance$1.sameOrigin(url)) { + image.crossOrigin = 'anonymous'; + } + abortController.signal.addEventListener('abort', () => { + // Set src to '' to actually cancel the request + image.src = ''; + reject(performance$1.createAbortError()); + }); + image.fetchPriority = 'high'; + image.onload = () => { + image.onerror = image.onload = null; + resolve({ data: image }); + }; + image.onerror = () => { + image.onerror = image.onload = null; + if (abortController.signal.aborted) { + return; + } + reject(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.')); + }; + image.src = url; + }); + }; +})(ImageRequest || (ImageRequest = {})); +ImageRequest.resetRequestQueue(); + +class RequestManager { + constructor(transformRequestFn) { + this._transformRequestFn = transformRequestFn; + } + transformRequest(url, type) { + if (this._transformRequestFn) { + return this._transformRequestFn(url, type) || { url }; + } + return { url }; + } + setTransformRequest(transformRequest) { + this._transformRequestFn = transformRequest; + } +} + +/** + * Takes a SpriteSpecification value and returns it in its array form. If `undefined` is passed as an input value, an + * empty array is returned. + * duplicated entries with identical id/url will be removed in returned array + * @param sprite - optional sprite to coerce + * @returns an empty array in case `undefined` is passed; id-url pairs otherwise + */ +function coerceSpriteToArray(sprite) { + const resultArray = []; + if (typeof sprite === 'string') { + resultArray.push({ id: 'default', url: sprite }); + } + else if (sprite && sprite.length > 0) { + const dedupArray = []; + for (const { id, url } of sprite) { + const key = `${id}${url}`; + if (dedupArray.indexOf(key) === -1) { + dedupArray.push(key); + resultArray.push({ id, url }); + } + } + } + return resultArray; +} + +function normalizeSpriteURL(url, format, extension) { + const split = url.split('?'); + split[0] += `${format}${extension}`; + return split.join('?'); +} +function loadSprite(originalSprite, requestManager, pixelRatio, abortController) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + const spriteArray = coerceSpriteToArray(originalSprite); + const format = pixelRatio > 1 ? '@2x' : ''; + const jsonsMap = {}; + const imagesMap = {}; + for (const { id, url } of spriteArray) { + const jsonRequestParameters = requestManager.transformRequest(normalizeSpriteURL(url, format, '.json'), "SpriteJSON" /* ResourceType.SpriteJSON */); + jsonsMap[id] = performance$1.getJSON(jsonRequestParameters, abortController); + const imageRequestParameters = requestManager.transformRequest(normalizeSpriteURL(url, format, '.png'), "SpriteImage" /* ResourceType.SpriteImage */); + imagesMap[id] = ImageRequest.getImage(imageRequestParameters, abortController); + } + yield Promise.all([...Object.values(jsonsMap), ...Object.values(imagesMap)]); + return doOnceCompleted(jsonsMap, imagesMap); + }); +} +/** + * @param jsonsMap - JSON data map + * @param imagesMap - image data map + */ +function doOnceCompleted(jsonsMap, imagesMap) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + const result = {}; + for (const spriteName in jsonsMap) { + result[spriteName] = {}; + const context = browser.getImageCanvasContext((yield imagesMap[spriteName]).data); + const json = (yield jsonsMap[spriteName]).data; + for (const id in json) { + const { width, height, x, y, sdf, pixelRatio, stretchX, stretchY, content, textFitWidth, textFitHeight } = json[id]; + const spriteData = { width, height, x, y, context }; + result[spriteName][id] = { data: null, pixelRatio, sdf, stretchX, stretchY, content, textFitWidth, textFitHeight, spriteData }; + } + } + return result; + }); +} + +/** + * @internal + * A `Texture` GL related object + */ +class Texture { + constructor(context, image, format, options) { + this.context = context; + this.format = format; + this.texture = context.gl.createTexture(); + this.update(image, options); + } + update(image, options, position) { + const { width, height } = image; + const resize = (!this.size || this.size[0] !== width || this.size[1] !== height) && !position; + const { context } = this; + const { gl } = context; + this.useMipmap = Boolean(options && options.useMipmap); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + context.pixelStoreUnpackFlipY.set(false); + context.pixelStoreUnpack.set(1); + context.pixelStoreUnpackPremultiplyAlpha.set(this.format === gl.RGBA && (!options || options.premultiply !== false)); + if (resize) { + this.size = [width, height]; + if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || performance$1.isImageBitmap(image)) { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, gl.UNSIGNED_BYTE, image); + } + else { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, gl.UNSIGNED_BYTE, image.data); + } + } + else { + const { x, y } = position || { x: 0, y: 0 }; + if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || performance$1.isImageBitmap(image)) { + gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, gl.RGBA, gl.UNSIGNED_BYTE, image); + } + else { + gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, image.data); + } + } + if (this.useMipmap && this.isSizePowerOfTwo()) { + gl.generateMipmap(gl.TEXTURE_2D); + } + } + bind(filter, wrap, minFilter) { + const { context } = this; + const { gl } = context; + gl.bindTexture(gl.TEXTURE_2D, this.texture); + if (minFilter === gl.LINEAR_MIPMAP_NEAREST && !this.isSizePowerOfTwo()) { + minFilter = gl.LINEAR; + } + if (filter !== this.filter) { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter || filter); + this.filter = filter; + } + if (wrap !== this.wrap) { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap); + this.wrap = wrap; + } + } + isSizePowerOfTwo() { + return this.size[0] === this.size[1] && (Math.log(this.size[0]) / Math.LN2) % 1 === 0; + } + destroy() { + const { gl } = this.context; + gl.deleteTexture(this.texture); + this.texture = null; + } +} + +function renderStyleImage(image) { + const { userImage } = image; + if (userImage && userImage.render) { + const updated = userImage.render(); + if (updated) { + image.data.replace(new Uint8Array(userImage.data.buffer)); + return true; + } + } + return false; +} + +/* eslint-disable key-spacing */ +/** + * When copied into the atlas texture, image data is padded by one pixel on each side. Icon + * images are padded with fully transparent pixels, while pattern images are padded with a + * copy of the image data wrapped from the opposite side. In both cases, this ensures the + * correct behavior of GL_LINEAR texture sampling mode. + */ +const padding = 1; +/** + * ImageManager does three things: + * + * 1. Tracks requests for icon images from tile workers and sends responses when the requests are fulfilled. + * 2. Builds a texture atlas for pattern images. + * 3. Rerenders renderable images once per frame + * + * These are disparate responsibilities and should eventually be handled by different classes. When we implement + * data-driven support for `*-pattern`, we'll likely use per-bucket pattern atlases, and that would be a good time + * to refactor this. +*/ +class ImageManager extends performance$1.Evented { + constructor() { + super(); + this.images = {}; + this.updatedImages = {}; + this.callbackDispatchedThisFrame = {}; + this.loaded = false; + this.requestors = []; + this.patterns = {}; + this.atlasImage = new performance$1.RGBAImage({ width: 1, height: 1 }); + this.dirty = true; + } + isLoaded() { + return this.loaded; + } + setLoaded(loaded) { + if (this.loaded === loaded) { + return; + } + this.loaded = loaded; + if (loaded) { + for (const { ids, promiseResolve } of this.requestors) { + promiseResolve(this._getImagesForIds(ids)); + } + this.requestors = []; + } + } + getImage(id) { + const image = this.images[id]; + // Extract sprite image data on demand + if (image && !image.data && image.spriteData) { + const spriteData = image.spriteData; + image.data = new performance$1.RGBAImage({ + width: spriteData.width, + height: spriteData.height + }, spriteData.context.getImageData(spriteData.x, spriteData.y, spriteData.width, spriteData.height).data); + image.spriteData = null; + } + return image; + } + addImage(id, image) { + if (this.images[id]) + throw new Error(`Image id ${id} already exist, use updateImage instead`); + if (this._validate(id, image)) { + this.images[id] = image; + } + } + _validate(id, image) { + let valid = true; + const data = image.data || image.spriteData; + if (!this._validateStretch(image.stretchX, data && data.width)) { + this.fire(new performance$1.ErrorEvent(new Error(`Image "${id}" has invalid "stretchX" value`))); + valid = false; + } + if (!this._validateStretch(image.stretchY, data && data.height)) { + this.fire(new performance$1.ErrorEvent(new Error(`Image "${id}" has invalid "stretchY" value`))); + valid = false; + } + if (!this._validateContent(image.content, image)) { + this.fire(new performance$1.ErrorEvent(new Error(`Image "${id}" has invalid "content" value`))); + valid = false; + } + return valid; + } + _validateStretch(stretch, size) { + if (!stretch) + return true; + let last = 0; + for (const part of stretch) { + if (part[0] < last || part[1] < part[0] || size < part[1]) + return false; + last = part[1]; + } + return true; + } + _validateContent(content, image) { + if (!content) + return true; + if (content.length !== 4) + return false; + const spriteData = image.spriteData; + const width = (spriteData && spriteData.width) || image.data.width; + const height = (spriteData && spriteData.height) || image.data.height; + if (content[0] < 0 || width < content[0]) + return false; + if (content[1] < 0 || height < content[1]) + return false; + if (content[2] < 0 || width < content[2]) + return false; + if (content[3] < 0 || height < content[3]) + return false; + if (content[2] < content[0]) + return false; + if (content[3] < content[1]) + return false; + return true; + } + updateImage(id, image, validate = true) { + const oldImage = this.getImage(id); + if (validate && (oldImage.data.width !== image.data.width || oldImage.data.height !== image.data.height)) { + throw new Error(`size mismatch between old image (${oldImage.data.width}x${oldImage.data.height}) and new image (${image.data.width}x${image.data.height}).`); + } + image.version = oldImage.version + 1; + this.images[id] = image; + this.updatedImages[id] = true; + } + removeImage(id) { + const image = this.images[id]; + delete this.images[id]; + delete this.patterns[id]; + if (image.userImage && image.userImage.onRemove) { + image.userImage.onRemove(); + } + } + listImages() { + return Object.keys(this.images); + } + getImages(ids) { + return new Promise((resolve, _reject) => { + // If the sprite has been loaded, or if all the icon dependencies are already present + // (i.e. if they've been added via runtime styling), then notify the requestor immediately. + // Otherwise, delay notification until the sprite is loaded. At that point, if any of the + // dependencies are still unavailable, we'll just assume they are permanently missing. + let hasAllDependencies = true; + if (!this.isLoaded()) { + for (const id of ids) { + if (!this.images[id]) { + hasAllDependencies = false; + } + } + } + if (this.isLoaded() || hasAllDependencies) { + resolve(this._getImagesForIds(ids)); + } + else { + this.requestors.push({ ids, promiseResolve: resolve }); + } + }); + } + _getImagesForIds(ids) { + const response = {}; + for (const id of ids) { + let image = this.getImage(id); + if (!image) { + this.fire(new performance$1.Event('styleimagemissing', { id })); + //Try to acquire image again in case styleimagemissing has populated it + image = this.getImage(id); + } + if (image) { + // Clone the image so that our own copy of its ArrayBuffer doesn't get transferred. + response[id] = { + data: image.data.clone(), + pixelRatio: image.pixelRatio, + sdf: image.sdf, + version: image.version, + stretchX: image.stretchX, + stretchY: image.stretchY, + content: image.content, + textFitWidth: image.textFitWidth, + textFitHeight: image.textFitHeight, + hasRenderCallback: Boolean(image.userImage && image.userImage.render) + }; + } + else { + performance$1.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.`); + } + } + return response; + } + // Pattern stuff + getPixelSize() { + const { width, height } = this.atlasImage; + return { width, height }; + } + getPattern(id) { + const pattern = this.patterns[id]; + const image = this.getImage(id); + if (!image) { + return null; + } + if (pattern && pattern.position.version === image.version) { + return pattern.position; + } + if (!pattern) { + const w = image.data.width + padding * 2; + const h = image.data.height + padding * 2; + const bin = { w, h, x: 0, y: 0 }; + const position = new performance$1.ImagePosition(bin, image); + this.patterns[id] = { bin, position }; + } + else { + pattern.position.version = image.version; + } + this._updatePatternAtlas(); + return this.patterns[id].position; + } + bind(context) { + const gl = context.gl; + if (!this.atlasTexture) { + this.atlasTexture = new Texture(context, this.atlasImage, gl.RGBA); + } + else if (this.dirty) { + this.atlasTexture.update(this.atlasImage); + this.dirty = false; + } + this.atlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + } + _updatePatternAtlas() { + const bins = []; + for (const id in this.patterns) { + bins.push(this.patterns[id].bin); + } + const { w, h } = performance$1.potpack(bins); + const dst = this.atlasImage; + dst.resize({ width: w || 1, height: h || 1 }); + for (const id in this.patterns) { + const { bin } = this.patterns[id]; + const x = bin.x + padding; + const y = bin.y + padding; + const src = this.getImage(id).data; + const w = src.width; + const h = src.height; + performance$1.RGBAImage.copy(src, dst, { x: 0, y: 0 }, { x, y }, { width: w, height: h }); + // Add 1 pixel wrapped padding on each side of the image. + performance$1.RGBAImage.copy(src, dst, { x: 0, y: h - 1 }, { x, y: y - 1 }, { width: w, height: 1 }); // T + performance$1.RGBAImage.copy(src, dst, { x: 0, y: 0 }, { x, y: y + h }, { width: w, height: 1 }); // B + performance$1.RGBAImage.copy(src, dst, { x: w - 1, y: 0 }, { x: x - 1, y }, { width: 1, height: h }); // L + performance$1.RGBAImage.copy(src, dst, { x: 0, y: 0 }, { x: x + w, y }, { width: 1, height: h }); // R + } + this.dirty = true; + } + beginFrame() { + this.callbackDispatchedThisFrame = {}; + } + dispatchRenderCallbacks(ids) { + for (const id of ids) { + // the callback for the image was already dispatched for a different frame + if (this.callbackDispatchedThisFrame[id]) + continue; + this.callbackDispatchedThisFrame[id] = true; + const image = this.getImage(id); + if (!image) + performance$1.warnOnce(`Image with ID: "${id}" was not found`); + const updated = renderStyleImage(image); + if (updated) { + this.updateImage(id, image); + } + } + } +} + +function loadGlyphRange(fontstack, range, urlTemplate, requestManager) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + const begin = range * 256; + const end = begin + 255; + const request = requestManager.transformRequest(urlTemplate.replace('{fontstack}', fontstack).replace('{range}', `${begin}-${end}`), "Glyphs" /* ResourceType.Glyphs */); + const response = yield performance$1.getArrayBuffer(request, new AbortController()); + if (!response || !response.data) { + throw new Error(`Could not load glyph range. range: ${range}, ${begin}-${end}`); + } + const glyphs = {}; + for (const glyph of performance$1.parseGlyphPbf(response.data)) { + glyphs[glyph.id] = glyph; + } + return glyphs; + }); +} + +const INF = 1e20; + +class TinySDF { + constructor({ + fontSize = 24, + buffer = 3, + radius = 8, + cutoff = 0.25, + fontFamily = 'sans-serif', + fontWeight = 'normal', + fontStyle = 'normal' + } = {}) { + this.buffer = buffer; + this.cutoff = cutoff; + this.radius = radius; + + // make the canvas size big enough to both have the specified buffer around the glyph + // for "halo", and account for some glyphs possibly being larger than their font size + const size = this.size = fontSize + buffer * 4; + + const canvas = this._createCanvas(size); + const ctx = this.ctx = canvas.getContext('2d', {willReadFrequently: true}); + ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`; + + ctx.textBaseline = 'alphabetic'; + ctx.textAlign = 'left'; // Necessary so that RTL text doesn't have different alignment + ctx.fillStyle = 'black'; + + // temporary arrays for the distance transform + this.gridOuter = new Float64Array(size * size); + this.gridInner = new Float64Array(size * size); + this.f = new Float64Array(size); + this.z = new Float64Array(size + 1); + this.v = new Uint16Array(size); + } + + _createCanvas(size) { + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = size; + return canvas; + } + + draw(char) { + const { + width: glyphAdvance, + actualBoundingBoxAscent, + actualBoundingBoxDescent, + actualBoundingBoxLeft, + actualBoundingBoxRight + } = this.ctx.measureText(char); + + // The integer/pixel part of the top alignment is encoded in metrics.glyphTop + // The remainder is implicitly encoded in the rasterization + const glyphTop = Math.ceil(actualBoundingBoxAscent); + const glyphLeft = 0; + + // If the glyph overflows the canvas size, it will be clipped at the bottom/right + const glyphWidth = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(actualBoundingBoxRight - actualBoundingBoxLeft))); + const glyphHeight = Math.min(this.size - this.buffer, glyphTop + Math.ceil(actualBoundingBoxDescent)); + + const width = glyphWidth + 2 * this.buffer; + const height = glyphHeight + 2 * this.buffer; + + const len = Math.max(width * height, 0); + const data = new Uint8ClampedArray(len); + const glyph = {data, width, height, glyphWidth, glyphHeight, glyphTop, glyphLeft, glyphAdvance}; + if (glyphWidth === 0 || glyphHeight === 0) return glyph; + + const {ctx, buffer, gridInner, gridOuter} = this; + ctx.clearRect(buffer, buffer, glyphWidth, glyphHeight); + ctx.fillText(char, buffer, buffer + glyphTop); + const imgData = ctx.getImageData(buffer, buffer, glyphWidth, glyphHeight); + + // Initialize grids outside the glyph range to alpha 0 + gridOuter.fill(INF, 0, len); + gridInner.fill(0, 0, len); + + for (let y = 0; y < glyphHeight; y++) { + for (let x = 0; x < glyphWidth; x++) { + const a = imgData.data[4 * (y * glyphWidth + x) + 3] / 255; // alpha value + if (a === 0) continue; // empty pixels + + const j = (y + buffer) * width + x + buffer; + + if (a === 1) { // fully drawn pixels + gridOuter[j] = 0; + gridInner[j] = INF; + + } else { // aliased pixels + const d = 0.5 - a; + gridOuter[j] = d > 0 ? d * d : 0; + gridInner[j] = d < 0 ? d * d : 0; + } + } + } + + edt(gridOuter, 0, 0, width, height, width, this.f, this.v, this.z); + edt(gridInner, buffer, buffer, glyphWidth, glyphHeight, width, this.f, this.v, this.z); + + for (let i = 0; i < len; i++) { + const d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]); + data[i] = Math.round(255 - 255 * (d / this.radius + this.cutoff)); + } + + return glyph; + } +} + +// 2D Euclidean squared distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf +function edt(data, x0, y0, width, height, gridSize, f, v, z) { + for (let x = x0; x < x0 + width; x++) edt1d(data, y0 * gridSize + x, gridSize, height, f, v, z); + for (let y = y0; y < y0 + height; y++) edt1d(data, y * gridSize + x0, 1, width, f, v, z); +} + +// 1D squared distance transform +function edt1d(grid, offset, stride, length, f, v, z) { + v[0] = 0; + z[0] = -INF; + z[1] = INF; + f[0] = grid[offset]; + + for (let q = 1, k = 0, s = 0; q < length; q++) { + f[q] = grid[offset + q * stride]; + const q2 = q * q; + do { + const r = v[k]; + s = (f[q] - f[r] + q2 - r * r) / (q - r) / 2; + } while (s <= z[k] && --k > -1); + + k++; + v[k] = q; + z[k] = s; + z[k + 1] = INF; + } + + for (let q = 0, k = 0; q < length; q++) { + while (z[k + 1] < q) k++; + const r = v[k]; + const qr = q - r; + grid[offset + q * stride] = f[r] + qr * qr; + } +} + +class GlyphManager { + constructor(requestManager, localIdeographFontFamily) { + this.requestManager = requestManager; + this.localIdeographFontFamily = localIdeographFontFamily; + this.entries = {}; + } + setURL(url) { + this.url = url; + } + getGlyphs(glyphs) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + const glyphsPromises = []; + for (const stack in glyphs) { + for (const id of glyphs[stack]) { + glyphsPromises.push(this._getAndCacheGlyphsPromise(stack, id)); + } + } + const updatedGlyphs = yield Promise.all(glyphsPromises); + const result = {}; + for (const { stack, id, glyph } of updatedGlyphs) { + if (!result[stack]) { + result[stack] = {}; + } + // Clone the glyph so that our own copy of its ArrayBuffer doesn't get transferred. + result[stack][id] = glyph && { + id: glyph.id, + bitmap: glyph.bitmap.clone(), + metrics: glyph.metrics + }; + } + return result; + }); + } + _getAndCacheGlyphsPromise(stack, id) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + let entry = this.entries[stack]; + if (!entry) { + entry = this.entries[stack] = { + glyphs: {}, + requests: {}, + ranges: {} + }; + } + let glyph = entry.glyphs[id]; + if (glyph !== undefined) { + return { stack, id, glyph }; + } + glyph = this._tinySDF(entry, stack, id); + if (glyph) { + entry.glyphs[id] = glyph; + return { stack, id, glyph }; + } + const range = Math.floor(id / 256); + if (range * 256 > 65535) { + throw new Error('glyphs > 65535 not supported'); + } + if (entry.ranges[range]) { + return { stack, id, glyph }; + } + if (!this.url) { + throw new Error('glyphsUrl is not set'); + } + if (!entry.requests[range]) { + const promise = GlyphManager.loadGlyphRange(stack, range, this.url, this.requestManager); + entry.requests[range] = promise; + } + const response = yield entry.requests[range]; + for (const id in response) { + if (!this._doesCharSupportLocalGlyph(+id)) { + entry.glyphs[+id] = response[+id]; + } + } + entry.ranges[range] = true; + return { stack, id, glyph: response[id] || null }; + }); + } + _doesCharSupportLocalGlyph(id) { + // The CJK Unified Ideographs blocks and Hangul Syllables blocks are + // spread across many glyph PBFs and are typically accessed very + // randomly. Preferring local rendering for these blocks reduces + // wasteful bandwidth consumption. For visual consistency within CJKV + // text, also include any other CJKV or siniform ideograph or hangul, + // hiragana, or katakana character. + return !!this.localIdeographFontFamily && + /\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(id)); + } + _tinySDF(entry, stack, id) { + const fontFamily = this.localIdeographFontFamily; + if (!fontFamily) { + return; + } + if (!this._doesCharSupportLocalGlyph(id)) { + return; + } + // Client-generated glyphs are rendered at 2x texture scale, + // because CJK glyphs are more detailed than others. + const textureScale = 2; + let tinySDF = entry.tinySDF; + if (!tinySDF) { + let fontWeight = '400'; + if (/bold/i.test(stack)) { + fontWeight = '900'; + } + else if (/medium/i.test(stack)) { + fontWeight = '500'; + } + else if (/light/i.test(stack)) { + fontWeight = '200'; + } + tinySDF = entry.tinySDF = new GlyphManager.TinySDF({ + fontSize: 24 * textureScale, + buffer: 3 * textureScale, + radius: 8 * textureScale, + cutoff: 0.25, + fontFamily, + fontWeight + }); + } + const char = tinySDF.draw(String.fromCharCode(id)); + /** + * TinySDF's "top" is the distance from the alphabetic baseline to the top of the glyph. + * Server-generated fonts specify "top" relative to an origin above the em box (the origin + * comes from FreeType, but I'm unclear on exactly how it's derived) + * ref: https://github.com/mapbox/sdf-glyph-foundry + * + * Server fonts don't yet include baseline information, so we can't line up exactly with them + * (and they don't line up with each other) + * ref: https://github.com/mapbox/node-fontnik/pull/160 + * + * To approximately align TinySDF glyphs with server-provided glyphs, we use this baseline adjustment + * factor calibrated to be in between DIN Pro and Arial Unicode (but closer to Arial Unicode) + */ + const topAdjustment = 27.5; + const leftAdjustment = 0.5; + return { + id, + bitmap: new performance$1.AlphaImage({ width: char.width || 30 * textureScale, height: char.height || 30 * textureScale }, char.data), + metrics: { + width: char.glyphWidth / textureScale || 24, + height: char.glyphHeight / textureScale || 24, + left: (char.glyphLeft / textureScale + leftAdjustment) || 0, + top: char.glyphTop / textureScale - topAdjustment || -8, + advance: char.glyphAdvance / textureScale || 24, + isDoubleResolution: true + } + }; + } +} +// exposed as statics to enable stubbing in unit tests +GlyphManager.loadGlyphRange = loadGlyphRange; +GlyphManager.TinySDF = TinySDF; + +class LightPositionProperty { + constructor() { + this.specification = performance$1.v8Spec.light.position; + } + possiblyEvaluate(value, parameters) { + return performance$1.sphericalToCartesian(value.expression.evaluate(parameters)); + } + interpolate(a, b, t) { + return { + x: performance$1.interpolate.number(a.x, b.x, t), + y: performance$1.interpolate.number(a.y, b.y, t), + z: performance$1.interpolate.number(a.z, b.z, t), + }; + } +} +const TRANSITION_SUFFIX$1 = '-transition'; +let lightProperties; +/* + * Represents the light used to light extruded features. + */ +class Light extends performance$1.Evented { + constructor(lightOptions) { + super(); + lightProperties = lightProperties || new performance$1.Properties({ + 'anchor': new performance$1.DataConstantProperty(performance$1.v8Spec.light.anchor), + 'position': new LightPositionProperty(), + 'color': new performance$1.DataConstantProperty(performance$1.v8Spec.light.color), + 'intensity': new performance$1.DataConstantProperty(performance$1.v8Spec.light.intensity), + }); + this._transitionable = new performance$1.Transitionable(lightProperties); + this.setLight(lightOptions); + this._transitioning = this._transitionable.untransitioned(); + } + getLight() { + return this._transitionable.serialize(); + } + setLight(light, options = {}) { + if (this._validate(performance$1.validateLight, light, options)) { + return; + } + for (const name in light) { + const value = light[name]; + if (name.endsWith(TRANSITION_SUFFIX$1)) { + this._transitionable.setTransition(name.slice(0, -TRANSITION_SUFFIX$1.length), value); + } + else { + this._transitionable.setValue(name, value); + } + } + } + updateTransitions(parameters) { + this._transitioning = this._transitionable.transitioned(parameters, this._transitioning); + } + hasTransition() { + return this._transitioning.hasTransition(); + } + recalculate(parameters) { + this.properties = this._transitioning.possiblyEvaluate(parameters); + } + _validate(validate, value, options) { + if (options && options.validate === false) { + return false; + } + return performance$1.emitValidationErrors(this, validate.call(performance$1.validateStyle, { + value, + // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407 + style: { glyphs: true, sprite: true }, + styleSpec: performance$1.v8Spec + })); + } +} + +const properties = new performance$1.Properties({ + 'sky-color': new performance$1.DataConstantProperty(performance$1.v8Spec.sky['sky-color']), + 'horizon-color': new performance$1.DataConstantProperty(performance$1.v8Spec.sky['horizon-color']), + 'fog-color': new performance$1.DataConstantProperty(performance$1.v8Spec.sky['fog-color']), + 'fog-ground-blend': new performance$1.DataConstantProperty(performance$1.v8Spec.sky['fog-ground-blend']), + 'horizon-fog-blend': new performance$1.DataConstantProperty(performance$1.v8Spec.sky['horizon-fog-blend']), + 'sky-horizon-blend': new performance$1.DataConstantProperty(performance$1.v8Spec.sky['sky-horizon-blend']), + 'atmosphere-blend': new performance$1.DataConstantProperty(performance$1.v8Spec.sky['atmosphere-blend']) +}); +const TRANSITION_SUFFIX = '-transition'; +class Sky extends performance$1.Evented { + constructor(sky) { + super(); + this._transitionable = new performance$1.Transitionable(properties); + this.setSky(sky); + this._transitioning = this._transitionable.untransitioned(); + this.recalculate(new performance$1.EvaluationParameters(0)); + } + setSky(sky, options = {}) { + if (this._validate(performance$1.validateSky, sky, options)) + return; + if (!sky) { + sky = { + 'sky-color': 'transparent', + 'horizon-color': 'transparent', + 'fog-color': 'transparent', + 'fog-ground-blend': 1, + 'atmosphere-blend': 0, + }; + } + for (const name in sky) { + const value = sky[name]; + if (name.endsWith(TRANSITION_SUFFIX)) { + this._transitionable.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), value); + } + else { + this._transitionable.setValue(name, value); + } + } + } + getSky() { + return this._transitionable.serialize(); + } + updateTransitions(parameters) { + this._transitioning = this._transitionable.transitioned(parameters, this._transitioning); + } + hasTransition() { + return this._transitioning.hasTransition(); + } + recalculate(parameters) { + this.properties = this._transitioning.possiblyEvaluate(parameters); + } + _validate(validate, value, options = {}) { + if ((options === null || options === void 0 ? void 0 : options.validate) === false) { + return false; + } + return performance$1.emitValidationErrors(this, validate.call(performance$1.validateStyle, performance$1.extend({ + value, + // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407 + style: { glyphs: true, sprite: true }, + styleSpec: performance$1.v8Spec + }))); + } + /** + * Currently fog is a very simple implementation, and should only used + * to create an atmosphere near the horizon. + * But because the fog is drawn from the far-clipping-plane to + * map-center, and because the fog does nothing know about the horizon, + * this method does a fadeout in respect of pitch. So, when the horizon + * gets out of view, which is at about pitch 70, this methods calculates + * the corresponding opacity values. Below pitch 60 the fog is completely + * invisible. + */ + calculateFogBlendOpacity(pitch) { + if (pitch < 60) + return 0; // disable + if (pitch < 70) + return (pitch - 60) / 10; // fade in + return 1; + } +} + +/** + * @internal + * A LineAtlas lets us reuse rendered dashed lines + * by writing many of them to a texture and then fetching their positions + * using {@link LineAtlas#getDash}. + * + * @param width - the width + * @param height - the height + */ +class LineAtlas { + constructor(width, height) { + this.width = width; + this.height = height; + this.nextRow = 0; + this.data = new Uint8Array(this.width * this.height); + this.dashEntry = {}; + } + /** + * Get or create a dash line pattern. + * + * @param dasharray - the key (represented by numbers) to get the dash texture + * @param round - whether to add circle caps in between dash segments + * @returns position of dash texture in {@link DashEntry} + */ + getDash(dasharray, round) { + const key = dasharray.join(',') + String(round); + if (!this.dashEntry[key]) { + this.dashEntry[key] = this.addDash(dasharray, round); + } + return this.dashEntry[key]; + } + getDashRanges(dasharray, lineAtlasWidth, stretch) { + // If dasharray has an odd length, both the first and last parts + // are dashes and should be joined seamlessly. + const oddDashArray = dasharray.length % 2 === 1; + const ranges = []; + let left = oddDashArray ? -dasharray[dasharray.length - 1] * stretch : 0; + let right = dasharray[0] * stretch; + let isDash = true; + ranges.push({ left, right, isDash, zeroLength: dasharray[0] === 0 }); + let currentDashLength = dasharray[0]; + for (let i = 1; i < dasharray.length; i++) { + isDash = !isDash; + const dashLength = dasharray[i]; + left = currentDashLength * stretch; + currentDashLength += dashLength; + right = currentDashLength * stretch; + ranges.push({ left, right, isDash, zeroLength: dashLength === 0 }); + } + return ranges; + } + addRoundDash(ranges, stretch, n) { + const halfStretch = stretch / 2; + for (let y = -n; y <= n; y++) { + const row = this.nextRow + n + y; + const index = this.width * row; + let currIndex = 0; + let range = ranges[currIndex]; + for (let x = 0; x < this.width; x++) { + if (x / range.right > 1) { + range = ranges[++currIndex]; + } + const distLeft = Math.abs(x - range.left); + const distRight = Math.abs(x - range.right); + const minDist = Math.min(distLeft, distRight); + let signedDistance; + const distMiddle = y / n * (halfStretch + 1); + if (range.isDash) { + const distEdge = halfStretch - Math.abs(distMiddle); + signedDistance = Math.sqrt(minDist * minDist + distEdge * distEdge); + } + else { + signedDistance = halfStretch - Math.sqrt(minDist * minDist + distMiddle * distMiddle); + } + this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128)); + } + } + } + addRegularDash(ranges) { + // Collapse any zero-length range + // Collapse neighbouring same-type parts into a single part + for (let i = ranges.length - 1; i >= 0; --i) { + const part = ranges[i]; + const next = ranges[i + 1]; + if (part.zeroLength) { + ranges.splice(i, 1); + } + else if (next && next.isDash === part.isDash) { + next.left = part.left; + ranges.splice(i, 1); + } + } + // Combine the first and last parts if possible + const first = ranges[0]; + const last = ranges[ranges.length - 1]; + if (first.isDash === last.isDash) { + first.left = last.left - this.width; + last.right = first.right + this.width; + } + const index = this.width * this.nextRow; + let currIndex = 0; + let range = ranges[currIndex]; + for (let x = 0; x < this.width; x++) { + if (x / range.right > 1) { + range = ranges[++currIndex]; + } + const distLeft = Math.abs(x - range.left); + const distRight = Math.abs(x - range.right); + const minDist = Math.min(distLeft, distRight); + const signedDistance = range.isDash ? minDist : -minDist; + this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128)); + } + } + addDash(dasharray, round) { + const n = round ? 7 : 0; + const height = 2 * n + 1; + if (this.nextRow + height > this.height) { + performance$1.warnOnce('LineAtlas out of space'); + return null; + } + let length = 0; + for (let i = 0; i < dasharray.length; i++) { + length += dasharray[i]; + } + if (length !== 0) { + const stretch = this.width / length; + const ranges = this.getDashRanges(dasharray, this.width, stretch); + if (round) { + this.addRoundDash(ranges, stretch, n); + } + else { + this.addRegularDash(ranges); + } + } + const dashEntry = { + y: (this.nextRow + n + 0.5) / this.height, + height: 2 * n / this.height, + width: length + }; + this.nextRow += height; + this.dirty = true; + return dashEntry; + } + bind(context) { + const gl = context.gl; + if (!this.texture) { + this.texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, this.width, this.height, 0, gl.ALPHA, gl.UNSIGNED_BYTE, this.data); + } + else { + gl.bindTexture(gl.TEXTURE_2D, this.texture); + if (this.dirty) { + this.dirty = false; + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.width, this.height, gl.ALPHA, gl.UNSIGNED_BYTE, this.data); + } + } + } +} + +function workerFactory() { + return new Worker(performance$1.config.WORKER_URL); +} + +const PRELOAD_POOL_ID = 'maplibre_preloaded_worker_pool'; +/** + * Constructs a worker pool. + */ +class WorkerPool { + constructor() { + this.active = {}; + } + acquire(mapId) { + if (!this.workers) { + // Lazily look up the value of getWorkerCount so that + // client code has had a chance to set it. + this.workers = []; + while (this.workers.length < WorkerPool.workerCount) { + this.workers.push(workerFactory()); + } + } + this.active[mapId] = true; + return this.workers.slice(); + } + release(mapId) { + delete this.active[mapId]; + if (this.numActive() === 0) { + this.workers.forEach((w) => { + w.terminate(); + }); + this.workers = null; + } + } + isPreloaded() { + return !!this.active[PRELOAD_POOL_ID]; + } + numActive() { + return Object.keys(this.active).length; + } +} +// Based on results from A/B testing: https://github.com/maplibre/maplibre-gl-js/pull/2354 +const availableLogicalProcessors = Math.floor(browser.hardwareConcurrency / 2); +WorkerPool.workerCount = performance$1.isSafari(globalThis) ? Math.max(Math.min(availableLogicalProcessors, 3), 1) : 1; + +let globalWorkerPool; +/** + * Creates (if necessary) and returns the single, global WorkerPool instance + * to be shared across each Map + */ +function getGlobalWorkerPool() { + if (!globalWorkerPool) { + globalWorkerPool = new WorkerPool(); + } + return globalWorkerPool; +} +/** + * Initializes resources like WebWorkers that can be shared across maps to lower load + * times in some situations. `setWorkerUrl()` and `setWorkerCount()`, if being + * used, must be set before `prewarm()` is called to have an effect. + * + * By default, the lifecycle of these resources is managed automatically, and they are + * lazily initialized when a Map is first created. By invoking `prewarm()`, these + * resources will be created ahead of time, and will not be cleared when the last Map + * is removed from the page. This allows them to be re-used by new Map instances that + * are created later. They can be manually cleared by calling + * `clearPrewarmedResources()`. This is only necessary if your web page remains + * active but stops using maps altogether. + * + * This is primarily useful when using GL-JS maps in a single page app, wherein a user + * would navigate between various views that can cause Map instances to constantly be + * created and destroyed. + * + * @example + * ```ts + * prewarm() + * ``` + */ +function prewarm() { + const workerPool = getGlobalWorkerPool(); + workerPool.acquire(PRELOAD_POOL_ID); +} +/** + * Clears up resources that have previously been created by `prewarm()`. + * Note that this is typically not necessary. You should only call this function + * if you expect the user of your app to not return to a Map view at any point + * in your application. + * + * @example + * ```ts + * clearPrewarmedResources() + * ``` + */ +function clearPrewarmedResources() { + const pool = globalWorkerPool; + if (pool) { + // Remove the pool only if all maps that referenced the preloaded global worker pool have been removed. + if (pool.isPreloaded() && pool.numActive() === 1) { + pool.release(PRELOAD_POOL_ID); + globalWorkerPool = null; + } + else { + 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()'); + } + } +} + +/** + * Responsible for sending messages from a {@link Source} to an associated + * {@link WorkerSource}. + */ +class Dispatcher { + constructor(workerPool, mapId) { + this.workerPool = workerPool; + this.actors = []; + this.currentActor = 0; + this.id = mapId; + const workers = this.workerPool.acquire(mapId); + for (let i = 0; i < workers.length; i++) { + const worker = workers[i]; + const actor = new performance$1.Actor(worker, mapId); + actor.name = `Worker ${i}`; + this.actors.push(actor); + } + if (!this.actors.length) + throw new Error('No actors found'); + } + /** + * Broadcast a message to all Workers. + */ + broadcast(type, data) { + const promises = []; + for (const actor of this.actors) { + promises.push(actor.sendAsync({ type, data })); + } + return Promise.all(promises); + } + /** + * Acquires an actor to dispatch messages to. The actors are distributed in round-robin fashion. + * @returns An actor object backed by a web worker for processing messages. + */ + getActor() { + this.currentActor = (this.currentActor + 1) % this.actors.length; + return this.actors[this.currentActor]; + } + remove(mapRemoved = true) { + this.actors.forEach((actor) => { actor.remove(); }); + this.actors = []; + if (mapRemoved) + this.workerPool.release(this.id); + } + registerMessageHandler(type, handler) { + for (const actor of this.actors) { + actor.registerMessageHandler(type, handler); + } + } +} +let globalDispatcher; +function getGlobalDispatcher() { + if (!globalDispatcher) { + globalDispatcher = new Dispatcher(getGlobalWorkerPool(), performance$1.GLOBAL_DISPATCHER_ID); + globalDispatcher.registerMessageHandler("GR" /* MessageType.getResource */, (_mapId, params, abortController) => { + return performance$1.makeRequest(params, abortController); + }); + } + return globalDispatcher; +} + +/* + * Returns a matrix that can be used to convert from tile coordinates to viewport pixel coordinates. + */ +function getPixelPosMatrix(transform, tileID) { + const t = performance$1.create(); + performance$1.translate(t, t, [1, 1, 0]); + performance$1.scale(t, t, [transform.width * 0.5, transform.height * 0.5, 1]); + return performance$1.multiply(t, t, transform.calculatePosMatrix(tileID.toUnwrapped())); +} +function queryIncludes3DLayer(layers, styleLayers, sourceID) { + if (layers) { + for (const layerID of layers) { + const layer = styleLayers[layerID]; + if (layer && layer.source === sourceID && layer.type === 'fill-extrusion') { + return true; + } + } + } + else { + for (const key in styleLayers) { + const layer = styleLayers[key]; + if (layer.source === sourceID && layer.type === 'fill-extrusion') { + return true; + } + } + } + return false; +} +function queryRenderedFeatures(sourceCache, styleLayers, serializedLayers, queryGeometry, params, transform) { + const has3DLayer = queryIncludes3DLayer(params && params.layers, styleLayers, sourceCache.id); + const maxPitchScaleFactor = transform.maxPitchScaleFactor(); + const tilesIn = sourceCache.tilesIn(queryGeometry, maxPitchScaleFactor, has3DLayer); + tilesIn.sort(sortTilesIn); + const renderedFeatureLayers = []; + for (const tileIn of tilesIn) { + renderedFeatureLayers.push({ + wrappedTileID: tileIn.tileID.wrapped().key, + queryResults: tileIn.tile.queryRenderedFeatures(styleLayers, serializedLayers, sourceCache._state, tileIn.queryGeometry, tileIn.cameraQueryGeometry, tileIn.scale, params, transform, maxPitchScaleFactor, getPixelPosMatrix(sourceCache.transform, tileIn.tileID)) + }); + } + const result = mergeRenderedFeatureLayers(renderedFeatureLayers); + // Merge state from SourceCache into the results + for (const layerID in result) { + result[layerID].forEach((featureWrapper) => { + const feature = featureWrapper.feature; + const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id); + feature.source = feature.layer.source; + if (feature.layer['source-layer']) { + feature.sourceLayer = feature.layer['source-layer']; + } + feature.state = state; + }); + } + return result; +} +function queryRenderedSymbols(styleLayers, serializedLayers, sourceCaches, queryGeometry, params, collisionIndex, retainedQueryData) { + const result = {}; + const renderedSymbols = collisionIndex.queryRenderedSymbols(queryGeometry); + const bucketQueryData = []; + for (const bucketInstanceId of Object.keys(renderedSymbols).map(Number)) { + bucketQueryData.push(retainedQueryData[bucketInstanceId]); + } + bucketQueryData.sort(sortTilesIn); + for (const queryData of bucketQueryData) { + const bucketSymbols = queryData.featureIndex.lookupSymbolFeatures(renderedSymbols[queryData.bucketInstanceId], serializedLayers, queryData.bucketIndex, queryData.sourceLayerIndex, params.filter, params.layers, params.availableImages, styleLayers); + for (const layerID in bucketSymbols) { + const resultFeatures = result[layerID] = result[layerID] || []; + const layerSymbols = bucketSymbols[layerID]; + layerSymbols.sort((a, b) => { + // Match topDownFeatureComparator from FeatureIndex, but using + // most recent sorting of features from bucket.sortFeatures + const featureSortOrder = queryData.featureSortOrder; + if (featureSortOrder) { + // queryRenderedSymbols documentation says we'll return features in + // "top-to-bottom" rendering order (aka last-to-first). + // Actually there can be multiple symbol instances per feature, so + // we sort each feature based on the first matching symbol instance. + const sortedA = featureSortOrder.indexOf(a.featureIndex); + const sortedB = featureSortOrder.indexOf(b.featureIndex); + return sortedB - sortedA; + } + else { + // Bucket hasn't been re-sorted based on angle, so use the + // reverse of the order the features appeared in the data. + return b.featureIndex - a.featureIndex; + } + }); + for (const symbolFeature of layerSymbols) { + resultFeatures.push(symbolFeature); + } + } + } + // Merge state from SourceCache into the results + for (const layerName in result) { + result[layerName].forEach((featureWrapper) => { + const feature = featureWrapper.feature; + const layer = styleLayers[layerName]; + const sourceCache = sourceCaches[layer.source]; + const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id); + feature.source = feature.layer.source; + if (feature.layer['source-layer']) { + feature.sourceLayer = feature.layer['source-layer']; + } + feature.state = state; + }); + } + return result; +} +function querySourceFeatures(sourceCache, params) { + const tiles = sourceCache.getRenderableIds().map((id) => { + return sourceCache.getTileByID(id); + }); + const result = []; + const dataTiles = {}; + for (let i = 0; i < tiles.length; i++) { + const tile = tiles[i]; + const dataID = tile.tileID.canonical.key; + if (!dataTiles[dataID]) { + dataTiles[dataID] = true; + tile.querySourceFeatures(result, params); + } + } + return result; +} +function sortTilesIn(a, b) { + const idA = a.tileID; + const idB = b.tileID; + return (idA.overscaledZ - idB.overscaledZ) || (idA.canonical.y - idB.canonical.y) || (idA.wrap - idB.wrap) || (idA.canonical.x - idB.canonical.x); +} +function mergeRenderedFeatureLayers(tiles) { + // Merge results from all tiles, but if two tiles share the same + // wrapped ID, don't duplicate features between the two tiles + const result = {}; + const wrappedIDLayerMap = {}; + for (const tile of tiles) { + const queryResults = tile.queryResults; + const wrappedID = tile.wrappedTileID; + const wrappedIDLayers = wrappedIDLayerMap[wrappedID] = wrappedIDLayerMap[wrappedID] || {}; + for (const layerID in queryResults) { + const tileFeatures = queryResults[layerID]; + const wrappedIDFeatures = wrappedIDLayers[layerID] = wrappedIDLayers[layerID] || {}; + const resultFeatures = result[layerID] = result[layerID] || []; + for (const tileFeature of tileFeatures) { + if (!wrappedIDFeatures[tileFeature.featureIndex]) { + wrappedIDFeatures[tileFeature.featureIndex] = true; + resultFeatures.push(tileFeature); + } + } + } + } + return result; +} + +function loadTileJson(options, requestManager, abortController) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + let tileJSON = options; + if (options.url) { + const response = yield performance$1.getJSON(requestManager.transformRequest(options.url, "Source" /* ResourceType.Source */), abortController); + tileJSON = response.data; + } + else { + yield browser.frameAsync(abortController); + } + if (!tileJSON) { + return null; + } + const result = performance$1.pick( + // explicit source options take precedence over TileJSON + performance$1.extend(tileJSON, options), ['tiles', 'minzoom', 'maxzoom', 'attribution', 'bounds', 'scheme', 'tileSize', 'encoding']); + if ('vector_layers' in tileJSON && tileJSON.vector_layers) { + result.vectorLayerIds = tileJSON.vector_layers.map((layer) => { return layer.id; }); + } + return result; + }); +} + +/** + * A `LngLatBounds` object represents a geographical bounding box, + * defined by its southwest and northeast points in longitude and latitude. + * + * If no arguments are provided to the constructor, a `null` bounding box is created. + * + * Note that any Mapbox GL method that accepts a `LngLatBounds` object as an argument or option + * can also accept an `Array` of two {@link LngLatLike} constructs and will perform an implicit conversion. + * This flexible type is documented as {@link LngLatBoundsLike}. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let sw = new LngLat(-73.9876, 40.7661); + * let ne = new LngLat(-73.9397, 40.8002); + * let llb = new LngLatBounds(sw, ne); + * ``` + */ +class LngLatBounds { + /** + * @param sw - The southwest corner of the bounding box. + * OR array of 4 numbers in the order of west, south, east, north + * OR array of 2 LngLatLike: [sw,ne] + * @param ne - The northeast corner of the bounding box. + * @example + * ```ts + * let sw = new LngLat(-73.9876, 40.7661); + * let ne = new LngLat(-73.9397, 40.8002); + * let llb = new LngLatBounds(sw, ne); + * ``` + * OR + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661, -73.9397, 40.8002]); + * ``` + * OR + * ```ts + * let llb = new LngLatBounds([sw, ne]); + * ``` + */ + constructor(sw, ne) { + if (!sw) { + // noop + } + else if (ne) { + this.setSouthWest(sw).setNorthEast(ne); + } + else if (Array.isArray(sw)) { + if (sw.length === 4) { + // 4 element array: west, south, east, north + this.setSouthWest([sw[0], sw[1]]).setNorthEast([sw[2], sw[3]]); + } + else { + this.setSouthWest(sw[0]).setNorthEast(sw[1]); + } + } + } + /** + * Set the northeast corner of the bounding box + * + * @param ne - a {@link LngLatLike} object describing the northeast corner of the bounding box. + */ + setNorthEast(ne) { + this._ne = ne instanceof performance$1.LngLat ? new performance$1.LngLat(ne.lng, ne.lat) : performance$1.LngLat.convert(ne); + return this; + } + /** + * Set the southwest corner of the bounding box + * + * @param sw - a {@link LngLatLike} object describing the southwest corner of the bounding box. + */ + setSouthWest(sw) { + this._sw = sw instanceof performance$1.LngLat ? new performance$1.LngLat(sw.lng, sw.lat) : performance$1.LngLat.convert(sw); + return this; + } + /** + * Extend the bounds to include a given LngLatLike or LngLatBoundsLike. + * + * @param obj - object to extend to + */ + extend(obj) { + const sw = this._sw, ne = this._ne; + let sw2, ne2; + if (obj instanceof performance$1.LngLat) { + sw2 = obj; + ne2 = obj; + } + else if (obj instanceof LngLatBounds) { + sw2 = obj._sw; + ne2 = obj._ne; + if (!sw2 || !ne2) + return this; + } + else { + if (Array.isArray(obj)) { + if (obj.length === 4 || obj.every(Array.isArray)) { + const lngLatBoundsObj = obj; + return this.extend(LngLatBounds.convert(lngLatBoundsObj)); + } + else { + const lngLatObj = obj; + return this.extend(performance$1.LngLat.convert(lngLatObj)); + } + } + else if (obj && ('lng' in obj || 'lon' in obj) && 'lat' in obj) { + return this.extend(performance$1.LngLat.convert(obj)); + } + return this; + } + if (!sw && !ne) { + this._sw = new performance$1.LngLat(sw2.lng, sw2.lat); + this._ne = new performance$1.LngLat(ne2.lng, ne2.lat); + } + else { + sw.lng = Math.min(sw2.lng, sw.lng); + sw.lat = Math.min(sw2.lat, sw.lat); + ne.lng = Math.max(ne2.lng, ne.lng); + ne.lat = Math.max(ne2.lat, ne.lat); + } + return this; + } + /** + * Returns the geographical coordinate equidistant from the bounding box's corners. + * + * @returns The bounding box's center. + * @example + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]); + * llb.getCenter(); // = LngLat {lng: -73.96365, lat: 40.78315} + * ``` + */ + getCenter() { + return new performance$1.LngLat((this._sw.lng + this._ne.lng) / 2, (this._sw.lat + this._ne.lat) / 2); + } + /** + * Returns the southwest corner of the bounding box. + * + * @returns The southwest corner of the bounding box. + */ + getSouthWest() { return this._sw; } + /** + * Returns the northeast corner of the bounding box. + * + * @returns The northeast corner of the bounding box. + */ + getNorthEast() { return this._ne; } + /** + * Returns the northwest corner of the bounding box. + * + * @returns The northwest corner of the bounding box. + */ + getNorthWest() { return new performance$1.LngLat(this.getWest(), this.getNorth()); } + /** + * Returns the southeast corner of the bounding box. + * + * @returns The southeast corner of the bounding box. + */ + getSouthEast() { return new performance$1.LngLat(this.getEast(), this.getSouth()); } + /** + * Returns the west edge of the bounding box. + * + * @returns The west edge of the bounding box. + */ + getWest() { return this._sw.lng; } + /** + * Returns the south edge of the bounding box. + * + * @returns The south edge of the bounding box. + */ + getSouth() { return this._sw.lat; } + /** + * Returns the east edge of the bounding box. + * + * @returns The east edge of the bounding box. + */ + getEast() { return this._ne.lng; } + /** + * Returns the north edge of the bounding box. + * + * @returns The north edge of the bounding box. + */ + getNorth() { return this._ne.lat; } + /** + * Returns the bounding box represented as an array. + * + * @returns The bounding box represented as an array, consisting of the + * southwest and northeast coordinates of the bounding represented as arrays of numbers. + * @example + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]); + * llb.toArray(); // = [[-73.9876, 40.7661], [-73.9397, 40.8002]] + * ``` + */ + toArray() { + return [this._sw.toArray(), this._ne.toArray()]; + } + /** + * Return the bounding box represented as a string. + * + * @returns The bounding box represents as a string of the format + * `'LngLatBounds(LngLat(lng, lat), LngLat(lng, lat))'`. + * @example + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]); + * llb.toString(); // = "LngLatBounds(LngLat(-73.9876, 40.7661), LngLat(-73.9397, 40.8002))" + * ``` + */ + toString() { + return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`; + } + /** + * Check if the bounding box is an empty/`null`-type box. + * + * @returns True if bounds have been defined, otherwise false. + */ + isEmpty() { + return !(this._sw && this._ne); + } + /** + * Check if the point is within the bounding box. + * + * @param lnglat - geographic point to check against. + * @returns `true` if the point is within the bounding box. + * @example + * ```ts + * let llb = new LngLatBounds( + * new LngLat(-73.9876, 40.7661), + * new LngLat(-73.9397, 40.8002) + * ); + * + * let ll = new LngLat(-73.9567, 40.7789); + * + * console.log(llb.contains(ll)); // = true + * ``` + */ + contains(lnglat) { + const { lng, lat } = performance$1.LngLat.convert(lnglat); + const containsLatitude = this._sw.lat <= lat && lat <= this._ne.lat; + let containsLongitude = this._sw.lng <= lng && lng <= this._ne.lng; + if (this._sw.lng > this._ne.lng) { // wrapped coordinates + containsLongitude = this._sw.lng >= lng && lng >= this._ne.lng; + } + return containsLatitude && containsLongitude; + } + /** + * Converts an array to a `LngLatBounds` object. + * + * If a `LngLatBounds` object is passed in, the function returns it unchanged. + * + * Internally, the function calls `LngLat#convert` to convert arrays to `LngLat` values. + * + * @param input - An array of two coordinates to convert, or a `LngLatBounds` object to return. + * @returns A new `LngLatBounds` object, if a conversion occurred, or the original `LngLatBounds` object. + * @example + * ```ts + * let arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]]; + * let llb = LngLatBounds.convert(arr); // = LngLatBounds {_sw: LngLat {lng: -73.9876, lat: 40.7661}, _ne: LngLat {lng: -73.9397, lat: 40.8002}} + * ``` + */ + static convert(input) { + if (input instanceof LngLatBounds) + return input; + if (!input) + return input; + return new LngLatBounds(input); + } + /** + * Returns a `LngLatBounds` from the coordinates extended by a given `radius`. The returned `LngLatBounds` completely contains the `radius`. + * + * @param center - center coordinates of the new bounds. + * @param radius - Distance in meters from the coordinates to extend the bounds. + * @returns A new `LngLatBounds` object representing the coordinates extended by the `radius`. + * @example + * ```ts + * let center = new LngLat(-73.9749, 40.7736); + * LngLatBounds.fromLngLat(100).toArray(); // = [[-73.97501862141328, 40.77351016847229], [-73.97478137858673, 40.77368983152771]] + * ``` + */ + static fromLngLat(center, radius = 0) { + const earthCircumferenceInMetersAtEquator = 40075017; + const latAccuracy = 360 * radius / earthCircumferenceInMetersAtEquator, lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * center.lat); + return new LngLatBounds(new performance$1.LngLat(center.lng - lngAccuracy, center.lat - latAccuracy), new performance$1.LngLat(center.lng + lngAccuracy, center.lat + latAccuracy)); + } + /** + * Adjusts the given bounds to handle the case where the bounds cross the 180th meridian (antimeridian). + * + * @returns The adjusted LngLatBounds + * @example + * ```ts + * let bounds = new LngLatBounds([175.813127, -20.157768], [-178. 340903, -15.449124]); + * let adjustedBounds = bounds.adjustAntiMeridian(); + * // adjustedBounds will be: [[175.813127, -20.157768], [181.659097, -15.449124]] + * ``` + */ + adjustAntiMeridian() { + const sw = new performance$1.LngLat(this._sw.lng, this._sw.lat); + const ne = new performance$1.LngLat(this._ne.lng, this._ne.lat); + if (sw.lng > ne.lng) { + return new LngLatBounds(sw, new performance$1.LngLat(ne.lng + 360, ne.lat)); + } + return new LngLatBounds(sw, ne); + } +} + +class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + } + validateBounds(bounds) { + // make sure the bounds property contains valid longitude and latitudes + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [Math.max(-180, bounds[0]), Math.max(-90, bounds[1]), Math.min(180, bounds[2]), Math.min(90, bounds[3])]; + } + contains(tileID) { + const worldSize = Math.pow(2, tileID.z); + const level = { + minX: Math.floor(performance$1.mercatorXfromLng(this.bounds.getWest()) * worldSize), + minY: Math.floor(performance$1.mercatorYfromLat(this.bounds.getNorth()) * worldSize), + maxX: Math.ceil(performance$1.mercatorXfromLng(this.bounds.getEast()) * worldSize), + maxY: Math.ceil(performance$1.mercatorYfromLat(this.bounds.getSouth()) * worldSize) + }; + const hit = tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY; + return hit; + } +} + +/** + * A source containing vector tiles in [Mapbox Vector Tile format](https://docs.mapbox.com/vector-tiles/reference/). + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'vector', + * url: 'https://demotiles.maplibre.org/tiles/tiles.json' + * }); + * ``` + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'vector', + * tiles: ['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt'], + * minzoom: 6, + * maxzoom: 14 + * }); + * ``` + * + * @example + * ```ts + * map.getSource('some id').setUrl("https://demotiles.maplibre.org/tiles/tiles.json"); + * ``` + * + * @example + * ```ts + * map.getSource('some id').setTiles(['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt']); + * ``` + * @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/vector-source/) + */ +class VectorTileSource extends performance$1.Evented { + constructor(id, options, dispatcher, eventedParent) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.type = 'vector'; + this.minzoom = 0; + this.maxzoom = 22; + this.scheme = 'xyz'; + this.tileSize = 512; + this.reparseOverscaled = true; + this.isTileClipped = true; + this._loaded = false; + performance$1.extend(this, performance$1.pick(options, ['url', 'scheme', 'tileSize', 'promoteId'])); + this._options = performance$1.extend({ type: 'vector' }, options); + this._collectResourceTiming = options.collectResourceTiming; + if (this.tileSize !== 512) { + throw new Error('vector tile sources must have a tileSize of 512'); + } + this.setEventedParent(eventedParent); + } + load() { + return performance$1.__awaiter(this, void 0, void 0, function* () { + this._loaded = false; + this.fire(new performance$1.Event('dataloading', { dataType: 'source' })); + this._tileJSONRequest = new AbortController(); + try { + const tileJSON = yield loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest); + this._tileJSONRequest = null; + this._loaded = true; + this.map.style.sourceCaches[this.id].clearTiles(); + if (tileJSON) { + performance$1.extend(this, tileJSON); + if (tileJSON.bounds) + this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom); + // `content` is included here to prevent a race condition where `Style#_updateSources` is called + // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives + // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088 + this.fire(new performance$1.Event('data', { dataType: 'source', sourceDataType: 'metadata' })); + this.fire(new performance$1.Event('data', { dataType: 'source', sourceDataType: 'content' })); + } + } + catch (err) { + this._tileJSONRequest = null; + this.fire(new performance$1.ErrorEvent(err)); + } + }); + } + loaded() { + return this._loaded; + } + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + onAdd(map) { + this.map = map; + this.load(); + } + setSourceProperty(callback) { + if (this._tileJSONRequest) { + this._tileJSONRequest.abort(); + } + callback(); + this.load(); + } + /** + * Sets the source `tiles` property and re-renders the map. + * + * @param tiles - An array of one or more tile source URLs, as in the TileJSON spec. + */ + setTiles(tiles) { + this.setSourceProperty(() => { + this._options.tiles = tiles; + }); + return this; + } + /** + * Sets the source `url` property and re-renders the map. + * + * @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`. + */ + setUrl(url) { + this.setSourceProperty(() => { + this.url = url; + this._options.url = url; + }); + return this; + } + onRemove() { + if (this._tileJSONRequest) { + this._tileJSONRequest.abort(); + this._tileJSONRequest = null; + } + } + serialize() { + return performance$1.extend({}, this._options); + } + loadTile(tile) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme); + const params = { + request: this.map._requestManager.transformRequest(url, "Tile" /* ResourceType.Tile */), + uid: tile.uid, + tileID: tile.tileID, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: this.type, + source: this.id, + pixelRatio: this.map.getPixelRatio(), + showCollisionBoxes: this.map.showCollisionBoxes, + promoteId: this.promoteId + }; + params.request.collectResourceTiming = this._collectResourceTiming; + let messageType = "RT" /* MessageType.reloadTile */; + if (!tile.actor || tile.state === 'expired') { + tile.actor = this.dispatcher.getActor(); + messageType = "LT" /* MessageType.loadTile */; + } + else if (tile.state === 'loading') { + return new Promise((resolve, reject) => { + tile.reloadPromise = { resolve, reject }; + }); + } + tile.abortController = new AbortController(); + try { + const data = yield tile.actor.sendAsync({ type: messageType, data: params }, tile.abortController); + delete tile.abortController; + if (tile.aborted) { + return; + } + this._afterTileLoadWorkerResponse(tile, data); + } + catch (err) { + delete tile.abortController; + if (tile.aborted) { + return; + } + if (err && err.status !== 404) { + throw err; + } + this._afterTileLoadWorkerResponse(tile, null); + } + }); + } + _afterTileLoadWorkerResponse(tile, data) { + if (data && data.resourceTiming) { + tile.resourceTiming = data.resourceTiming; + } + if (data && this.map._refreshExpiredTiles) { + tile.setExpiryData(data); + } + tile.loadVectorData(data, this.map.painter); + if (tile.reloadPromise) { + const reloadPromise = tile.reloadPromise; + tile.reloadPromise = null; + this.loadTile(tile).then(reloadPromise.resolve).catch(reloadPromise.reject); + } + } + abortTile(tile) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + if (tile.abortController) { + tile.abortController.abort(); + delete tile.abortController; + } + if (tile.actor) { + yield tile.actor.sendAsync({ + type: "AT" /* MessageType.abortTile */, + data: { uid: tile.uid, type: this.type, source: this.id } + }); + } + }); + } + unloadTile(tile) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + tile.unloadVectorData(); + if (tile.actor) { + yield tile.actor.sendAsync({ + type: "RMT" /* MessageType.removeTile */, + data: { + uid: tile.uid, + type: this.type, + source: this.id + } + }); + } + }); + } + hasTransition() { + return false; + } +} + +/** + * A source containing raster tiles (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * map.addSource('raster-source', { + * 'type': 'raster', + * 'tiles': ['https://tiles.stadiamaps.com/tiles/stamen_watercolor/{z}/{x}/{y}.jpg'], + * 'tileSize': 256, + * }); + * ``` + * + * @example + * ```ts + * map.addSource('wms-test-source', { + * 'type': 'raster', + * // use the tiles option to specify a WMS tile source URL + * 'tiles': [ + * 'https://img.nj.gov/imagerywms/Natural2015?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&transparent=true&width=256&height=256&layers=Natural2015' + * ], + * 'tileSize': 256 + * }); + * ``` + * @see [Add a raster tile source](https://maplibre.org/maplibre-gl-js/docs/examples/map-tiles/) + * @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/wms/) + * @see [Display a satellite map](https://maplibre.org/maplibre-gl-js/docs/examples/satellite-map/) + */ +class RasterTileSource extends performance$1.Evented { + constructor(id, options, dispatcher, eventedParent) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.setEventedParent(eventedParent); + this.type = 'raster'; + this.minzoom = 0; + this.maxzoom = 22; + this.roundZoom = true; + this.scheme = 'xyz'; + this.tileSize = 512; + this._loaded = false; + this._options = performance$1.extend({ type: 'raster' }, options); + performance$1.extend(this, performance$1.pick(options, ['url', 'scheme', 'tileSize'])); + } + load() { + return performance$1.__awaiter(this, void 0, void 0, function* () { + this._loaded = false; + this.fire(new performance$1.Event('dataloading', { dataType: 'source' })); + this._tileJSONRequest = new AbortController(); + try { + const tileJSON = yield loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest); + this._tileJSONRequest = null; + this._loaded = true; + if (tileJSON) { + performance$1.extend(this, tileJSON); + if (tileJSON.bounds) + this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom); + // `content` is included here to prevent a race condition where `Style#_updateSources` is called + // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives + // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088 + this.fire(new performance$1.Event('data', { dataType: 'source', sourceDataType: 'metadata' })); + this.fire(new performance$1.Event('data', { dataType: 'source', sourceDataType: 'content' })); + } + } + catch (err) { + this._tileJSONRequest = null; + this.fire(new performance$1.ErrorEvent(err)); + } + }); + } + loaded() { + return this._loaded; + } + onAdd(map) { + this.map = map; + this.load(); + } + onRemove() { + if (this._tileJSONRequest) { + this._tileJSONRequest.abort(); + this._tileJSONRequest = null; + } + } + setSourceProperty(callback) { + if (this._tileJSONRequest) { + this._tileJSONRequest.abort(); + this._tileJSONRequest = null; + } + callback(); + this.load(); + } + /** + * Sets the source `tiles` property and re-renders the map. + * + * @param tiles - An array of one or more tile source URLs, as in the raster tiles spec (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) + */ + setTiles(tiles) { + this.setSourceProperty(() => { + this._options.tiles = tiles; + }); + return this; + } + /** + * Sets the source `url` property and re-renders the map. + * + * @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`. + */ + setUrl(url) { + this.setSourceProperty(() => { + this.url = url; + this._options.url = url; + }); + return this; + } + serialize() { + return performance$1.extend({}, this._options); + } + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + loadTile(tile) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme); + tile.abortController = new AbortController(); + try { + const response = yield ImageRequest.getImage(this.map._requestManager.transformRequest(url, "Tile" /* ResourceType.Tile */), tile.abortController, this.map._refreshExpiredTiles); + delete tile.abortController; + if (tile.aborted) { + tile.state = 'unloaded'; + return; + } + if (response && response.data) { + if (this.map._refreshExpiredTiles && response.cacheControl && response.expires) { + tile.setExpiryData({ cacheControl: response.cacheControl, expires: response.expires }); + } + const context = this.map.painter.context; + const gl = context.gl; + const img = response.data; + tile.texture = this.map.painter.getTileTexture(img.width); + if (tile.texture) { + tile.texture.update(img, { useMipmap: true }); + } + else { + tile.texture = new Texture(context, img, gl.RGBA, { useMipmap: true }); + tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST); + } + tile.state = 'loaded'; + } + } + catch (err) { + delete tile.abortController; + if (tile.aborted) { + tile.state = 'unloaded'; + } + else if (err) { + tile.state = 'errored'; + throw err; + } + } + }); + } + abortTile(tile) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + if (tile.abortController) { + tile.abortController.abort(); + delete tile.abortController; + } + }); + } + unloadTile(tile) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + if (tile.texture) { + this.map.painter.saveTileTexture(tile.texture); + } + }); + } + hasTransition() { + return false; + } +} + +/** + * A source containing raster DEM tiles (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.) + * This source can be used to show hillshading and 3D terrain + * + * @group Sources + * + * @example + * ```ts + * map.addSource('raster-dem-source', { + * type: 'raster-dem', + * url: 'https://demotiles.maplibre.org/terrain-tiles/tiles.json', + * tileSize: 256 + * }); + * ``` + * @see [3D Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/3d-terrain/) + */ +class RasterDEMTileSource extends RasterTileSource { + constructor(id, options, dispatcher, eventedParent) { + super(id, options, dispatcher, eventedParent); + this.type = 'raster-dem'; + this.maxzoom = 22; + this._options = performance$1.extend({ type: 'raster-dem' }, options); + this.encoding = options.encoding || 'mapbox'; + this.redFactor = options.redFactor; + this.greenFactor = options.greenFactor; + this.blueFactor = options.blueFactor; + this.baseShift = options.baseShift; + } + loadTile(tile) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme); + const request = this.map._requestManager.transformRequest(url, "Tile" /* ResourceType.Tile */); + tile.neighboringTiles = this._getNeighboringTiles(tile.tileID); + tile.abortController = new AbortController(); + try { + const response = yield ImageRequest.getImage(request, tile.abortController, this.map._refreshExpiredTiles); + delete tile.abortController; + if (tile.aborted) { + tile.state = 'unloaded'; + return; + } + if (response && response.data) { + const img = response.data; + if (this.map._refreshExpiredTiles && response.cacheControl && response.expires) { + tile.setExpiryData({ cacheControl: response.cacheControl, expires: response.expires }); + } + const transfer = performance$1.isImageBitmap(img) && performance$1.offscreenCanvasSupported(); + const rawImageData = transfer ? img : yield this.readImageNow(img); + const params = { + type: this.type, + uid: tile.uid, + source: this.id, + rawImageData, + encoding: this.encoding, + redFactor: this.redFactor, + greenFactor: this.greenFactor, + blueFactor: this.blueFactor, + baseShift: this.baseShift + }; + if (!tile.actor || tile.state === 'expired') { + tile.actor = this.dispatcher.getActor(); + /* eslint-disable require-atomic-updates */ + const data = yield tile.actor.sendAsync({ type: "LDT" /* MessageType.loadDEMTile */, data: params }); + tile.dem = data; + tile.needsHillshadePrepare = true; + tile.needsTerrainPrepare = true; + tile.state = 'loaded'; + /* eslint-enable require-atomic-updates */ + } + } + } + catch (err) { + delete tile.abortController; + if (tile.aborted) { + tile.state = 'unloaded'; + } + else if (err) { + tile.state = 'errored'; + throw err; + } + } + }); + } + readImageNow(img) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + if (typeof VideoFrame !== 'undefined' && performance$1.isOffscreenCanvasDistorted()) { + const width = img.width + 2; + const height = img.height + 2; + try { + return new performance$1.RGBAImage({ width, height }, yield performance$1.readImageUsingVideoFrame(img, -1, -1, width, height)); + } + catch (e) { + // fall-back to browser canvas decoding + } + } + return browser.getImageData(img, 1); + }); + } + _getNeighboringTiles(tileID) { + const canonical = tileID.canonical; + const dim = Math.pow(2, canonical.z); + const px = (canonical.x - 1 + dim) % dim; + const pxw = canonical.x === 0 ? tileID.wrap - 1 : tileID.wrap; + const nx = (canonical.x + 1 + dim) % dim; + const nxw = canonical.x + 1 === dim ? tileID.wrap + 1 : tileID.wrap; + const neighboringTiles = {}; + // add adjacent tiles + neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y).key] = { backfilled: false }; + neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y).key] = { backfilled: false }; + // Add upper neighboringTiles + if (canonical.y > 0) { + neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y - 1).key] = { backfilled: false }; + neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y - 1).key] = { backfilled: false }; + neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y - 1).key] = { backfilled: false }; + } + // Add lower neighboringTiles + if (canonical.y + 1 < dim) { + neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y + 1).key] = { backfilled: false }; + neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y + 1).key] = { backfilled: false }; + neighboringTiles[new performance$1.OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y + 1).key] = { backfilled: false }; + } + return neighboringTiles; + } + unloadTile(tile) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + if (tile.demTexture) + this.map.painter.saveTileTexture(tile.demTexture); + if (tile.fbo) { + tile.fbo.destroy(); + delete tile.fbo; + } + if (tile.dem) + delete tile.dem; + delete tile.neighboringTiles; + tile.state = 'unloaded'; + if (tile.actor) { + yield tile.actor.sendAsync({ type: "RDT" /* MessageType.removeDEMTile */, data: { type: this.type, uid: tile.uid, source: this.id } }); + } + }); + } +} + +/** + * A source containing GeoJSON. + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-geojson) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'geojson', + * data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson' + * }); + * ``` + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'geojson', + * data: { + * "type": "FeatureCollection", + * "features": [{ + * "type": "Feature", + * "properties": {}, + * "geometry": { + * "type": "Point", + * "coordinates": [ + * -76.53063297271729, + * 39.18174077994108 + * ] + * } + * }] + * } + * }); + * ``` + * + * @example + * ```ts + * map.getSource('some id').setData({ + * "type": "FeatureCollection", + * "features": [{ + * "type": "Feature", + * "properties": { "name": "Null Island" }, + * "geometry": { + * "type": "Point", + * "coordinates": [ 0, 0 ] + * } + * }] + * }); + * ``` + * @see [Draw GeoJSON points](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-markers/) + * @see [Add a GeoJSON line](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-line/) + * @see [Create a heatmap from points](https://maplibre.org/maplibre-gl-js/docs/examples/heatmap-layer/) + * @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/cluster/) + */ +class GeoJSONSource extends performance$1.Evented { + /** @internal */ + constructor(id, options, dispatcher, eventedParent) { + super(); + this.id = id; + // `type` is a property rather than a constant to make it easy for 3rd + // parties to use GeoJSONSource to build their own source types. + this.type = 'geojson'; + this.minzoom = 0; + this.maxzoom = 18; + this.tileSize = 512; + this.isTileClipped = true; + this.reparseOverscaled = true; + this._removed = false; + this._pendingLoads = 0; + this.actor = dispatcher.getActor(); + this.setEventedParent(eventedParent); + this._data = options.data; + this._options = performance$1.extend({}, options); + this._collectResourceTiming = options.collectResourceTiming; + if (options.maxzoom !== undefined) + this.maxzoom = options.maxzoom; + if (options.type) + this.type = options.type; + if (options.attribution) + this.attribution = options.attribution; + this.promoteId = options.promoteId; + const scale = performance$1.EXTENT / this.tileSize; + if (options.clusterMaxZoom !== undefined && this.maxzoom <= options.clusterMaxZoom) { + performance$1.warnOnce(`The maxzoom value "${this.maxzoom}" is expected to be greater than the clusterMaxZoom value "${options.clusterMaxZoom}".`); + } + // sent to the worker, along with `url: ...` or `data: literal geojson`, + // so that it can load/parse/index the geojson data + // extending with `options.workerOptions` helps to make it easy for + // third-party sources to hack/reuse GeoJSONSource. + this.workerOptions = performance$1.extend({ + source: this.id, + cluster: options.cluster || false, + geojsonVtOptions: { + buffer: (options.buffer !== undefined ? options.buffer : 128) * scale, + tolerance: (options.tolerance !== undefined ? options.tolerance : 0.375) * scale, + extent: performance$1.EXTENT, + maxZoom: this.maxzoom, + lineMetrics: options.lineMetrics || false, + generateId: options.generateId || false + }, + superclusterOptions: { + maxZoom: options.clusterMaxZoom !== undefined ? options.clusterMaxZoom : this.maxzoom - 1, + minPoints: Math.max(2, options.clusterMinPoints || 2), + extent: performance$1.EXTENT, + radius: (options.clusterRadius || 50) * scale, + log: false, + generateId: options.generateId || false + }, + clusterProperties: options.clusterProperties, + filter: options.filter + }, options.workerOptions); + // send the promoteId to the worker to have more flexible updates, but only if it is a string + if (typeof this.promoteId === 'string') { + this.workerOptions.promoteId = this.promoteId; + } + } + load() { + return performance$1.__awaiter(this, void 0, void 0, function* () { + yield this._updateWorkerData(); + }); + } + onAdd(map) { + this.map = map; + this.load(); + } + /** + * Sets the GeoJSON data and re-renders the map. + * + * @param data - A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files. + */ + setData(data) { + this._data = data; + this._updateWorkerData(); + return this; + } + /** + * Updates the source's GeoJSON, and re-renders the map. + * + * For sources with lots of features, this method can be used to make updates more quickly. + * + * This approach requires unique IDs for every feature in the source. The IDs can either be specified on the feature, + * or by using the promoteId option to specify which property should be used as the ID. + * + * It is an error to call updateData on a source that did not have unique IDs for each of its features already. + * + * Updates are applied on a best-effort basis, updating an ID that does not exist will not result in an error. + * + * @param diff - The changes that need to be applied. + */ + updateData(diff) { + this._updateWorkerData(diff); + return this; + } + /** + * Allows to get the source's actual GeoJSON data. + * + * @returns a promise which resolves to the source's actual GeoJSON data + */ + getData() { + return performance$1.__awaiter(this, void 0, void 0, function* () { + const options = performance$1.extend({ type: this.type }, this.workerOptions); + return this.actor.sendAsync({ type: "GD" /* MessageType.getData */, data: options }); + }); + } + /** + * To disable/enable clustering on the source options + * @param options - The options to set + * @example + * ```ts + * map.getSource('some id').setClusterOptions({cluster: false}); + * map.getSource('some id').setClusterOptions({cluster: false, clusterRadius: 50, clusterMaxZoom: 14}); + * ``` + */ + setClusterOptions(options) { + this.workerOptions.cluster = options.cluster; + if (options) { + if (options.clusterRadius !== undefined) + this.workerOptions.superclusterOptions.radius = options.clusterRadius; + if (options.clusterMaxZoom !== undefined) + this.workerOptions.superclusterOptions.maxZoom = options.clusterMaxZoom; + } + this._updateWorkerData(); + return this; + } + /** + * For clustered sources, fetches the zoom at which the given cluster expands. + * + * @param clusterId - The value of the cluster's `cluster_id` property. + * @returns a promise that is resolved with the zoom number + */ + getClusterExpansionZoom(clusterId) { + return this.actor.sendAsync({ type: "GCEZ" /* MessageType.getClusterExpansionZoom */, data: { type: this.type, clusterId, source: this.id } }); + } + /** + * For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features). + * + * @param clusterId - The value of the cluster's `cluster_id` property. + * @returns a promise that is resolved when the features are retrieved + */ + getClusterChildren(clusterId) { + return this.actor.sendAsync({ type: "GCC" /* MessageType.getClusterChildren */, data: { type: this.type, clusterId, source: this.id } }); + } + /** + * For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features). + * + * @param clusterId - The value of the cluster's `cluster_id` property. + * @param limit - The maximum number of features to return. + * @param offset - The number of features to skip (e.g. for pagination). + * @returns a promise that is resolved when the features are retrieved + * @example + * Retrieve cluster leaves on click + * ```ts + * map.on('click', 'clusters', (e) => { + * let features = map.queryRenderedFeatures(e.point, { + * layers: ['clusters'] + * }); + * + * let clusterId = features[0].properties.cluster_id; + * let pointCount = features[0].properties.point_count; + * let clusterSource = map.getSource('clusters'); + * + * const features = await clusterSource.getClusterLeaves(clusterId, pointCount); + * // Print cluster leaves in the console + * console.log('Cluster leaves:', features); + * }); + * ``` + */ + getClusterLeaves(clusterId, limit, offset) { + return this.actor.sendAsync({ type: "GCL" /* MessageType.getClusterLeaves */, data: { + type: this.type, + source: this.id, + clusterId, + limit, + offset + } }); + } + /** + * Responsible for invoking WorkerSource's geojson.loadData target, which + * handles loading the geojson data and preparing to serve it up as tiles, + * using geojson-vt or supercluster as appropriate. + * @param diff - the diff object + */ + _updateWorkerData(diff) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + const options = performance$1.extend({ type: this.type }, this.workerOptions); + if (diff) { + options.dataDiff = diff; + } + else if (typeof this._data === 'string') { + options.request = this.map._requestManager.transformRequest(browser.resolveURL(this._data), "Source" /* ResourceType.Source */); + options.request.collectResourceTiming = this._collectResourceTiming; + } + else { + options.data = JSON.stringify(this._data); + } + this._pendingLoads++; + this.fire(new performance$1.Event('dataloading', { dataType: 'source' })); + try { + const result = yield this.actor.sendAsync({ type: "LD" /* MessageType.loadData */, data: options }); + this._pendingLoads--; + if (this._removed || result.abandoned) { + this.fire(new performance$1.Event('dataabort', { dataType: 'source' })); + return; + } + let resourceTiming = null; + if (result.resourceTiming && result.resourceTiming[this.id]) { + resourceTiming = result.resourceTiming[this.id].slice(0); + } + const data = { dataType: 'source' }; + if (this._collectResourceTiming && resourceTiming && resourceTiming.length > 0) { + performance$1.extend(data, { resourceTiming }); + } + // although GeoJSON sources contain no metadata, we fire this event to let the SourceCache + // know its ok to start requesting tiles. + this.fire(new performance$1.Event('data', Object.assign(Object.assign({}, data), { sourceDataType: 'metadata' }))); + this.fire(new performance$1.Event('data', Object.assign(Object.assign({}, data), { sourceDataType: 'content' }))); + } + catch (err) { + this._pendingLoads--; + if (this._removed) { + this.fire(new performance$1.Event('dataabort', { dataType: 'source' })); + return; + } + this.fire(new performance$1.ErrorEvent(err)); + } + }); + } + loaded() { + return this._pendingLoads === 0; + } + loadTile(tile) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + const message = !tile.actor ? "LT" /* MessageType.loadTile */ : "RT" /* MessageType.reloadTile */; + tile.actor = this.actor; + const params = { + type: this.type, + uid: tile.uid, + tileID: tile.tileID, + zoom: tile.tileID.overscaledZ, + maxZoom: this.maxzoom, + tileSize: this.tileSize, + source: this.id, + pixelRatio: this.map.getPixelRatio(), + showCollisionBoxes: this.map.showCollisionBoxes, + promoteId: this.promoteId + }; + tile.abortController = new AbortController(); + const data = yield this.actor.sendAsync({ type: message, data: params }, tile.abortController); + delete tile.abortController; + tile.unloadVectorData(); + if (!tile.aborted) { + tile.loadVectorData(data, this.map.painter, message === "RT" /* MessageType.reloadTile */); + } + }); + } + abortTile(tile) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + if (tile.abortController) { + tile.abortController.abort(); + delete tile.abortController; + } + tile.aborted = true; + }); + } + unloadTile(tile) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + tile.unloadVectorData(); + yield this.actor.sendAsync({ type: "RMT" /* MessageType.removeTile */, data: { uid: tile.uid, type: this.type, source: this.id } }); + }); + } + onRemove() { + this._removed = true; + this.actor.sendAsync({ type: "RS" /* MessageType.removeSource */, data: { type: this.type, source: this.id } }); + } + serialize() { + return performance$1.extend({}, this._options, { + type: this.type, + data: this._data + }); + } + hasTransition() { + return false; + } +} + +var rasterBoundsAttributes = performance$1.createLayout([ + { name: 'a_pos', type: 'Int16', components: 2 }, + { name: 'a_texture_pos', type: 'Int16', components: 2 } +]); + +/** + * A data source containing an image. + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-image) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * // add to map + * map.addSource('some id', { + * type: 'image', + * url: 'https://www.maplibre.org/images/foo.png', + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update coordinates + * let mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * // update url and coordinates simultaneously + * mySource.updateImage({ + * url: 'https://www.maplibre.org/images/bar.png', + * coordinates: [ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ] + * }) + * + * map.removeSource('some id'); // remove + * ``` + */ +class ImageSource extends performance$1.Evented { + /** @internal */ + constructor(id, options, dispatcher, eventedParent) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.coordinates = options.coordinates; + this.type = 'image'; + this.minzoom = 0; + this.maxzoom = 22; + this.tileSize = 512; + this.tiles = {}; + this._loaded = false; + this.setEventedParent(eventedParent); + this.options = options; + } + load(newCoordinates) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + this._loaded = false; + this.fire(new performance$1.Event('dataloading', { dataType: 'source' })); + this.url = this.options.url; + this._request = new AbortController(); + try { + const image = yield ImageRequest.getImage(this.map._requestManager.transformRequest(this.url, "Image" /* ResourceType.Image */), this._request); + this._request = null; + this._loaded = true; + if (image && image.data) { + this.image = image.data; + if (newCoordinates) { + this.coordinates = newCoordinates; + } + this._finishLoading(); + } + } + catch (err) { + this._request = null; + this._loaded = true; + this.fire(new performance$1.ErrorEvent(err)); + } + }); + } + loaded() { + return this._loaded; + } + /** + * Updates the image URL and, optionally, the coordinates. To avoid having the image flash after changing, + * set the `raster-fade-duration` paint property on the raster layer to 0. + * + * @param options - The options object. + */ + updateImage(options) { + if (!options.url) { + return this; + } + if (this._request) { + this._request.abort(); + this._request = null; + } + this.options.url = options.url; + this.load(options.coordinates).finally(() => { this.texture = null; }); + return this; + } + _finishLoading() { + if (this.map) { + this.setCoordinates(this.coordinates); + this.fire(new performance$1.Event('data', { dataType: 'source', sourceDataType: 'metadata' })); + } + } + onAdd(map) { + this.map = map; + this.load(); + } + onRemove() { + if (this._request) { + this._request.abort(); + this._request = null; + } + } + /** + * Sets the image's coordinates and re-renders the map. + * + * @param coordinates - Four geographical coordinates, + * represented as arrays of longitude and latitude numbers, which define the corners of the image. + * The coordinates start at the top left corner of the image and proceed in clockwise order. + * They do not have to represent a rectangle. + */ + setCoordinates(coordinates) { + this.coordinates = coordinates; + // Calculate which mercator tile is suitable for rendering the video in + // and create a buffer with the corner coordinates. These coordinates + // may be outside the tile, because raster tiles aren't clipped when rendering. + // transform the geo coordinates into (zoom 0) tile space coordinates + const cornerCoords = coordinates.map(performance$1.MercatorCoordinate.fromLngLat); + // Compute the coordinates of the tile we'll use to hold this image's + // render data + this.tileID = getCoordinatesCenterTileID(cornerCoords); + // Constrain min/max zoom to our tile's zoom level in order to force + // SourceCache to request this tile (no matter what the map's zoom + // level) + this.minzoom = this.maxzoom = this.tileID.z; + // Transform the corner coordinates into the coordinate space of our + // tile. + const tileCoords = cornerCoords.map((coord) => this.tileID.getTilePoint(coord)._round()); + this._boundsArray = new performance$1.RasterBoundsArray(); + this._boundsArray.emplaceBack(tileCoords[0].x, tileCoords[0].y, 0, 0); + this._boundsArray.emplaceBack(tileCoords[1].x, tileCoords[1].y, performance$1.EXTENT, 0); + this._boundsArray.emplaceBack(tileCoords[3].x, tileCoords[3].y, 0, performance$1.EXTENT); + this._boundsArray.emplaceBack(tileCoords[2].x, tileCoords[2].y, performance$1.EXTENT, performance$1.EXTENT); + if (this.boundsBuffer) { + this.boundsBuffer.destroy(); + delete this.boundsBuffer; + } + this.fire(new performance$1.Event('data', { dataType: 'source', sourceDataType: 'content' })); + return this; + } + prepare() { + if (Object.keys(this.tiles).length === 0 || !this.image) { + return; + } + const context = this.map.painter.context; + const gl = context.gl; + if (!this.boundsBuffer) { + this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members); + } + if (!this.boundsSegments) { + this.boundsSegments = performance$1.SegmentVector.simpleSegment(0, 0, 4, 2); + } + if (!this.texture) { + this.texture = new Texture(context, this.image, gl.RGBA); + this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + } + let newTilesLoaded = false; + for (const w in this.tiles) { + const tile = this.tiles[w]; + if (tile.state !== 'loaded') { + tile.state = 'loaded'; + tile.texture = this.texture; + newTilesLoaded = true; + } + } + if (newTilesLoaded) { + this.fire(new performance$1.Event('data', { dataType: 'source', sourceDataType: 'idle', sourceId: this.id })); + } + } + loadTile(tile) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + // We have a single tile -- whose coordinates are this.tileID -- that + // covers the image we want to render. If that's the one being + // requested, set it up with the image; otherwise, mark the tile as + // `errored` to indicate that we have no data for it. + // If the world wraps, we may have multiple "wrapped" copies of the + // single tile. + if (this.tileID && this.tileID.equals(tile.tileID.canonical)) { + this.tiles[String(tile.tileID.wrap)] = tile; + tile.buckets = {}; + } + else { + tile.state = 'errored'; + } + }); + } + serialize() { + return { + type: 'image', + url: this.options.url, + coordinates: this.coordinates + }; + } + hasTransition() { + return false; + } +} +/** + * Given a list of coordinates, get their center as a coordinate. + * + * @returns centerpoint + * @internal + */ +function getCoordinatesCenterTileID(coords) { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const coord of coords) { + minX = Math.min(minX, coord.x); + minY = Math.min(minY, coord.y); + maxX = Math.max(maxX, coord.x); + maxY = Math.max(maxY, coord.y); + } + const dx = maxX - minX; + const dy = maxY - minY; + const dMax = Math.max(dx, dy); + const zoom = Math.max(0, Math.floor(-Math.log(dMax) / Math.LN2)); + const tilesAtZoom = Math.pow(2, zoom); + return new performance$1.CanonicalTileID(zoom, Math.floor((minX + maxX) / 2 * tilesAtZoom), Math.floor((minY + maxY) / 2 * tilesAtZoom)); +} + +/** + * A data source containing video. + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-video) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * // add to map + * map.addSource('some id', { + * type: 'video', + * url: [ + * 'https://www.mapbox.com/blog/assets/baltimore-smoke.mp4', + * 'https://www.mapbox.com/blog/assets/baltimore-smoke.webm' + * ], + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update + * let mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * map.removeSource('some id'); // remove + * ``` + * @see [Add a video](https://maplibre.org/maplibre-gl-js/docs/examples/video-on-a-map/) + * + * Note that when rendered as a raster layer, the layer's `raster-fade-duration` property will cause the video to fade in. + * This happens when playback is started, paused and resumed, or when the video's coordinates are updated. To avoid this behavior, + * set the layer's `raster-fade-duration` property to `0`. + */ +class VideoSource extends ImageSource { + constructor(id, options, dispatcher, eventedParent) { + super(id, options, dispatcher, eventedParent); + this.roundZoom = true; + this.type = 'video'; + this.options = options; + } + load() { + return performance$1.__awaiter(this, void 0, void 0, function* () { + this._loaded = false; + const options = this.options; + this.urls = []; + for (const url of options.urls) { + this.urls.push(this.map._requestManager.transformRequest(url, "Source" /* ResourceType.Source */).url); + } + try { + const video = yield performance$1.getVideo(this.urls); + this._loaded = true; + if (!video) { + return; + } + this.video = video; + this.video.loop = true; + // Start repainting when video starts playing. hasTransition() will then return + // true to trigger additional frames as long as the videos continues playing. + this.video.addEventListener('playing', () => { + this.map.triggerRepaint(); + }); + if (this.map) { + this.video.play(); + } + this._finishLoading(); + } + catch (err) { + this.fire(new performance$1.ErrorEvent(err)); + } + }); + } + /** + * Pauses the video. + */ + pause() { + if (this.video) { + this.video.pause(); + } + } + /** + * Plays the video. + */ + play() { + if (this.video) { + this.video.play(); + } + } + /** + * Sets playback to a timestamp, in seconds. + */ + seek(seconds) { + if (this.video) { + const seekableRange = this.video.seekable; + if (seconds < seekableRange.start(0) || seconds > seekableRange.end(0)) { + this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${this.id}`, null, `Playback for this video can be set only between the ${seekableRange.start(0)} and ${seekableRange.end(0)}-second mark.`))); + } + else + this.video.currentTime = seconds; + } + } + /** + * Returns the HTML `video` element. + * + * @returns The HTML `video` element. + */ + getVideo() { + return this.video; + } + onAdd(map) { + if (this.map) + return; + this.map = map; + this.load(); + if (this.video) { + this.video.play(); + this.setCoordinates(this.coordinates); + } + } + /** + * Sets the video's coordinates and re-renders the map. + */ + prepare() { + if (Object.keys(this.tiles).length === 0 || this.video.readyState < 2) { + return; // not enough data for current position + } + const context = this.map.painter.context; + const gl = context.gl; + if (!this.boundsBuffer) { + this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members); + } + if (!this.boundsSegments) { + this.boundsSegments = performance$1.SegmentVector.simpleSegment(0, 0, 4, 2); + } + if (!this.texture) { + this.texture = new Texture(context, this.video, gl.RGBA); + this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + } + else if (!this.video.paused) { + this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.video); + } + let newTilesLoaded = false; + for (const w in this.tiles) { + const tile = this.tiles[w]; + if (tile.state !== 'loaded') { + tile.state = 'loaded'; + tile.texture = this.texture; + newTilesLoaded = true; + } + } + if (newTilesLoaded) { + this.fire(new performance$1.Event('data', { dataType: 'source', sourceDataType: 'idle', sourceId: this.id })); + } + } + serialize() { + return { + type: 'video', + urls: this.urls, + coordinates: this.coordinates + }; + } + hasTransition() { + return this.video && !this.video.paused; + } +} + +/** + * A data source containing the contents of an HTML canvas. See {@link CanvasSourceSpecification} for detailed documentation of options. + * + * @group Sources + * + * @example + * ```ts + * // add to map + * map.addSource('some id', { + * type: 'canvas', + * canvas: 'idOfMyHTMLCanvas', + * animate: true, + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update + * let mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * map.removeSource('some id'); // remove + * ``` + */ +class CanvasSource extends ImageSource { + /** @internal */ + constructor(id, options, dispatcher, eventedParent) { + super(id, options, dispatcher, eventedParent); + // We build in some validation here, since canvas sources aren't included in the style spec: + if (!options.coordinates) { + this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`, null, 'missing required property "coordinates"'))); + } + else if (!Array.isArray(options.coordinates) || options.coordinates.length !== 4 || + options.coordinates.some(c => !Array.isArray(c) || c.length !== 2 || c.some(l => typeof l !== 'number'))) { + this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`, null, '"coordinates" property must be an array of 4 longitude/latitude array pairs'))); + } + if (options.animate && typeof options.animate !== 'boolean') { + this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`, null, 'optional "animate" property must be a boolean value'))); + } + if (!options.canvas) { + this.fire(new performance$1.ErrorEvent(new performance$1.ValidationError(`sources.${id}`, null, 'missing required property "canvas"'))); + } + else if (typeof options.canvas !== 'string' && !(options.canvas instanceof HTMLCanvasElement)) { + this.fire(new performance$1.ErrorEvent(new performance$1.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'))); + } + this.options = options; + this.animate = options.animate !== undefined ? options.animate : true; + } + load() { + return performance$1.__awaiter(this, void 0, void 0, function* () { + this._loaded = true; + if (!this.canvas) { + this.canvas = (this.options.canvas instanceof HTMLCanvasElement) ? + this.options.canvas : + document.getElementById(this.options.canvas); + // cast to HTMLCanvasElement in else of ternary + // should we do a safety check and throw if it's not actually HTMLCanvasElement? + } + this.width = this.canvas.width; + this.height = this.canvas.height; + if (this._hasInvalidDimensions()) { + this.fire(new performance$1.ErrorEvent(new Error('Canvas dimensions cannot be less than or equal to zero.'))); + return; + } + this.play = function () { + this._playing = true; + this.map.triggerRepaint(); + }; + this.pause = function () { + if (this._playing) { + this.prepare(); + this._playing = false; + } + }; + this._finishLoading(); + }); + } + /** + * Returns the HTML `canvas` element. + * + * @returns The HTML `canvas` element. + */ + getCanvas() { + return this.canvas; + } + onAdd(map) { + this.map = map; + this.load(); + if (this.canvas) { + if (this.animate) + this.play(); + } + } + onRemove() { + this.pause(); + } + prepare() { + let resize = false; + if (this.canvas.width !== this.width) { + this.width = this.canvas.width; + resize = true; + } + if (this.canvas.height !== this.height) { + this.height = this.canvas.height; + resize = true; + } + if (this._hasInvalidDimensions()) + return; + if (Object.keys(this.tiles).length === 0) + return; // not enough data for current position + const context = this.map.painter.context; + const gl = context.gl; + if (!this.boundsBuffer) { + this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members); + } + if (!this.boundsSegments) { + this.boundsSegments = performance$1.SegmentVector.simpleSegment(0, 0, 4, 2); + } + if (!this.texture) { + this.texture = new Texture(context, this.canvas, gl.RGBA, { premultiply: true }); + } + else if (resize || this._playing) { + this.texture.update(this.canvas, { premultiply: true }); + } + let newTilesLoaded = false; + for (const w in this.tiles) { + const tile = this.tiles[w]; + if (tile.state !== 'loaded') { + tile.state = 'loaded'; + tile.texture = this.texture; + newTilesLoaded = true; + } + } + if (newTilesLoaded) { + this.fire(new performance$1.Event('data', { dataType: 'source', sourceDataType: 'idle', sourceId: this.id })); + } + } + serialize() { + return { + type: 'canvas', + coordinates: this.coordinates + }; + } + hasTransition() { + return this._playing; + } + _hasInvalidDimensions() { + for (const x of [this.canvas.width, this.canvas.height]) { + if (isNaN(x) || x <= 0) + return true; + } + return false; + } +} + +const registeredSources = {}; +/** + * Creates a tiled data source instance given an options object. + * + * @param id - The id for the source. Must not be used by any existing source. + * @param specification - Source options, specific to the source type (except for `options.type`, which is always required). + * @param source - A source definition object compliant with + * [`maplibre-gl-style-spec`](https://maplibre.org/maplibre-style-spec/#sources) or, for a third-party source type, + * with that type's requirements. + * @param dispatcher - A {@link Dispatcher} instance, which can be used to send messages to the workers. + * @returns a newly created source + */ +const create = (id, specification, dispatcher, eventedParent) => { + const Class = getSourceType(specification.type); + const source = new Class(id, specification, dispatcher, eventedParent); + if (source.id !== id) { + throw new Error(`Expected Source id to be ${id} instead of ${source.id}`); + } + return source; +}; +const getSourceType = (name) => { + switch (name) { + case 'geojson': + return GeoJSONSource; + case 'image': + return ImageSource; + case 'raster': + return RasterTileSource; + case 'raster-dem': + return RasterDEMTileSource; + case 'vector': + return VectorTileSource; + case 'video': + return VideoSource; + case 'canvas': + return CanvasSource; + } + return registeredSources[name]; +}; +const setSourceType = (name, type) => { + registeredSources[name] = type; +}; +/** + * Adds a custom source type, making it available for use with {@link Map#addSource}. + * @param name - The name of the source type; source definition objects use this name in the `{type: ...}` field. + * @param SourceType - A {@link SourceClass} - which is a constructor for the `Source` interface. + * @returns a promise that is resolved when the source type is ready or rejected with an error. + */ +const addSourceType = (name, SourceType) => performance$1.__awaiter(void 0, void 0, void 0, function* () { + if (getSourceType(name)) { + throw new Error(`A source type called "${name}" already exists.`); + } + setSourceType(name, SourceType); +}); + +function deserialize(input, style) { + const output = {}; + // Guard against the case where the map's style has been set to null while + // this bucket has been parsing. + if (!style) + return output; + for (const bucket of input) { + const layers = bucket.layerIds + .map((id) => style.getLayer(id)) + .filter(Boolean); + if (layers.length === 0) { + continue; + } + // look up StyleLayer objects from layer ids (since we don't + // want to waste time serializing/copying them from the worker) + bucket.layers = layers; + if (bucket.stateDependentLayerIds) { + bucket.stateDependentLayers = bucket.stateDependentLayerIds.map((lId) => layers.filter((l) => l.id === lId)[0]); + } + for (const layer of layers) { + output[layer.id] = bucket; + } + } + return output; +} + +const RTLPluginLoadedEventName = 'RTLPluginLoaded'; + +class RTLMainThreadPlugin extends performance$1.Evented { + constructor() { + super(...arguments); + this.status = 'unavailable'; + this.url = null; + this.dispatcher = getGlobalDispatcher(); + } + /** Sync RTL plugin state by broadcasting a message to the worker */ + _syncState(statusToSend) { + this.status = statusToSend; + return this.dispatcher.broadcast("SRPS" /* MessageType.syncRTLPluginState */, { pluginStatus: statusToSend, pluginURL: this.url }) + .catch((e) => { + this.status = 'error'; + throw e; + }); + } + /** This one is exposed to outside */ + getRTLTextPluginStatus() { + return this.status; + } + clearRTLTextPlugin() { + this.status = 'unavailable'; + this.url = null; + } + setRTLTextPlugin(url_1) { + return performance$1.__awaiter(this, arguments, void 0, function* (url, deferred = false) { + if (this.url) { + // error + throw new Error('setRTLTextPlugin cannot be called multiple times.'); + } + this.url = browser.resolveURL(url); + if (!this.url) { + throw new Error(`requested url ${url} is invalid`); + } + if (this.status === 'unavailable') { + // from initial state: + if (deferred) { + this.status = 'deferred'; + // fire and forget: in this case it does not need wait for the broadcasting result + // it is important to sync the deferred status once because + // symbol_bucket will be checking it in worker + this._syncState(this.status); + } + else { + return this._requestImport(); + } + } + else if (this.status === 'requested') { + return this._requestImport(); + } + }); + } + /** Send a message to worker which will import the RTL plugin script */ + _requestImport() { + return performance$1.__awaiter(this, void 0, void 0, function* () { + // all errors/exceptions will be handled by _syncState + yield this._syncState('loading'); + this.status = 'loaded'; + this.fire(new performance$1.Event(RTLPluginLoadedEventName)); + }); + } + /** Start a lazy loading process of RTL plugin */ + lazyLoad() { + if (this.status === 'unavailable') { + this.status = 'requested'; + } + else if (this.status === 'deferred') { + this._requestImport(); + } + } +} +let rtlMainThreadPlugin = null; +function rtlMainThreadPluginFactory() { + if (!rtlMainThreadPlugin) { + rtlMainThreadPlugin = new RTLMainThreadPlugin(); + } + return rtlMainThreadPlugin; +} + +const CLOCK_SKEW_RETRY_TIMEOUT = 30000; +/** + * A tile object is the combination of a Coordinate, which defines + * its place, as well as a unique ID and data tracking for its content + */ +class Tile { + /** + * @param tileID - the tile ID + * @param size - The tile size + */ + constructor(tileID, size) { + this.timeAdded = 0; + this.fadeEndTime = 0; + this.tileID = tileID; + this.uid = performance$1.uniqueId(); + this.uses = 0; + this.tileSize = size; + this.buckets = {}; + this.expirationTime = null; + this.queryPadding = 0; + this.hasSymbolBuckets = false; + this.hasRTLText = false; + this.dependencies = {}; + this.rtt = []; + this.rttCoords = {}; + // Counts the number of times a response was already expired when + // received. We're using this to add a delay when making a new request + // so we don't have to keep retrying immediately in case of a server + // serving expired tiles. + this.expiredRequestCount = 0; + this.state = 'loading'; + } + registerFadeDuration(duration) { + const fadeEndTime = duration + this.timeAdded; + if (fadeEndTime < this.fadeEndTime) { + return; + } + this.fadeEndTime = fadeEndTime; + } + wasRequested() { + return this.state === 'errored' || this.state === 'loaded' || this.state === 'reloading'; + } + clearTextures(painter) { + if (this.demTexture) + painter.saveTileTexture(this.demTexture); + this.demTexture = null; + } + /** + * Given a data object with a 'buffers' property, load it into + * this tile's elementGroups and buffers properties and set loaded + * to true. If the data is null, like in the case of an empty + * GeoJSON tile, no-op but still set loaded to true. + * @param data - The data from the worker + * @param painter - the painter + * @param justReloaded - `true` to just reload + */ + loadVectorData(data, painter, justReloaded) { + if (this.hasData()) { + this.unloadVectorData(); + } + this.state = 'loaded'; + // empty GeoJSON tile + if (!data) { + this.collisionBoxArray = new performance$1.CollisionBoxArray(); + return; + } + if (data.featureIndex) { + this.latestFeatureIndex = data.featureIndex; + if (data.rawTileData) { + // Only vector tiles have rawTileData, and they won't update it for + // 'reloadTile' + this.latestRawTileData = data.rawTileData; + this.latestFeatureIndex.rawTileData = data.rawTileData; + } + else if (this.latestRawTileData) { + // If rawTileData hasn't updated, hold onto a pointer to the last + // one we received + this.latestFeatureIndex.rawTileData = this.latestRawTileData; + } + } + this.collisionBoxArray = data.collisionBoxArray; + this.buckets = deserialize(data.buckets, painter.style); + this.hasSymbolBuckets = false; + for (const id in this.buckets) { + const bucket = this.buckets[id]; + if (bucket instanceof performance$1.SymbolBucket) { + this.hasSymbolBuckets = true; + if (justReloaded) { + bucket.justReloaded = true; + } + else { + break; + } + } + } + this.hasRTLText = false; + if (this.hasSymbolBuckets) { + for (const id in this.buckets) { + const bucket = this.buckets[id]; + if (bucket instanceof performance$1.SymbolBucket) { + if (bucket.hasRTLText) { + this.hasRTLText = true; + rtlMainThreadPluginFactory().lazyLoad(); + break; + } + } + } + } + this.queryPadding = 0; + for (const id in this.buckets) { + const bucket = this.buckets[id]; + this.queryPadding = Math.max(this.queryPadding, painter.style.getLayer(id).queryRadius(bucket)); + } + if (data.imageAtlas) { + this.imageAtlas = data.imageAtlas; + } + if (data.imageBackgroundsAtlas) { + this.imageBackgroundsAtlas = data.imageBackgroundsAtlas; + } + if (data.glyphAtlasImage) { + this.glyphAtlasImage = data.glyphAtlasImage; + } + } + /** + * Release any data or WebGL resources referenced by this tile. + */ + unloadVectorData() { + for (const id in this.buckets) { + this.buckets[id].destroy(); + } + this.buckets = {}; + if (this.imageAtlasTexture) { + this.imageAtlasTexture.destroy(); + } + if (this.imageBackgroundsAtlasTexture) { + this.imageBackgroundsAtlasTexture.destroy(); + } + if (this.imageAtlas) { + this.imageAtlas = null; + } + if (this.imageBackgroundsAtlas) { + this.imageBackgroundsAtlas = null; + } + if (this.glyphAtlasTexture) { + this.glyphAtlasTexture.destroy(); + } + this.latestFeatureIndex = null; + this.state = 'unloaded'; + } + getBucket(layer) { + return this.buckets[layer.id]; + } + upload(context) { + for (const id in this.buckets) { + const bucket = this.buckets[id]; + if (bucket.uploadPending()) { + bucket.upload(context); + } + } + const gl = context.gl; + if (this.imageAtlas && !this.imageAtlas.uploaded) { + this.imageAtlasTexture = new Texture(context, this.imageAtlas.image, gl.RGBA); + this.imageAtlas.uploaded = true; + } + if (this.imageBackgroundsAtlas && !this.imageBackgroundsAtlas.uploaded) { + this.imageBackgroundsAtlasTexture = new Texture(context, this.imageBackgroundsAtlas.image, gl.RGBA); + this.imageBackgroundsAtlas.uploaded = true; + } + if (this.glyphAtlasImage) { + this.glyphAtlasTexture = new Texture(context, this.glyphAtlasImage, gl.ALPHA); + this.glyphAtlasImage = null; + } + } + prepare(imageManager) { + if (this.imageAtlas) { + this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture); + } + if (this.imageBackgroundsAtlas) { + this.imageBackgroundsAtlas.patchUpdatedImages(imageManager, this.imageBackgroundsAtlasTexture); + } + } + // Queries non-symbol features rendered for this tile. + // Symbol features are queried globally + queryRenderedFeatures(layers, serializedLayers, sourceFeatureState, queryGeometry, cameraQueryGeometry, scale, params, transform, maxPitchScaleFactor, pixelPosMatrix) { + if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData) + return {}; + return this.latestFeatureIndex.query({ + queryGeometry, + cameraQueryGeometry, + scale, + tileSize: this.tileSize, + pixelPosMatrix, + transform, + params, + queryPadding: this.queryPadding * maxPitchScaleFactor + }, layers, serializedLayers, sourceFeatureState); + } + querySourceFeatures(result, params) { + const featureIndex = this.latestFeatureIndex; + if (!featureIndex || !featureIndex.rawTileData) + return; + const vtLayers = featureIndex.loadVTLayers(); + const sourceLayer = params && params.sourceLayer ? params.sourceLayer : ''; + const layer = vtLayers._geojsonTileLayer || vtLayers[sourceLayer]; + if (!layer) + return; + const filter = performance$1.createFilter(params && params.filter); + const { z, x, y } = this.tileID.canonical; + const coord = { z, x, y }; + for (let i = 0; i < layer.length; i++) { + const feature = layer.feature(i); + if (filter.needGeometry) { + const evaluationFeature = performance$1.toEvaluationFeature(feature, true); + if (!filter.filter(new performance$1.EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) + continue; + } + else if (!filter.filter(new performance$1.EvaluationParameters(this.tileID.overscaledZ), feature)) { + continue; + } + const id = featureIndex.getId(feature, sourceLayer); + const geojsonFeature = new performance$1.GeoJSONFeature(feature, z, x, y, id); + geojsonFeature.tile = coord; + result.push(geojsonFeature); + } + } + hasData() { + return this.state === 'loaded' || this.state === 'reloading' || this.state === 'expired'; + } + patternsLoaded() { + return this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length; + } + setExpiryData(data) { + const prior = this.expirationTime; + if (data.cacheControl) { + const parsedCC = performance$1.parseCacheControl(data.cacheControl); + if (parsedCC['max-age']) + this.expirationTime = Date.now() + parsedCC['max-age'] * 1000; + } + else if (data.expires) { + this.expirationTime = new Date(data.expires).getTime(); + } + if (this.expirationTime) { + const now = Date.now(); + let isExpired = false; + if (this.expirationTime > now) { + isExpired = false; + } + else if (!prior) { + isExpired = true; + } + else if (this.expirationTime < prior) { + // Expiring date is going backwards: + // fall back to exponential backoff + isExpired = true; + } + else { + const delta = this.expirationTime - prior; + if (!delta) { + // Server is serving the same expired resource over and over: fall + // back to exponential backoff. + isExpired = true; + } + else { + // Assume that either the client or the server clock is wrong and + // try to interpolate a valid expiration date (from the client POV) + // observing a minimum timeout. + this.expirationTime = now + Math.max(delta, CLOCK_SKEW_RETRY_TIMEOUT); + } + } + if (isExpired) { + this.expiredRequestCount++; + this.state = 'expired'; + } + else { + this.expiredRequestCount = 0; + } + } + } + getExpiryTimeout() { + if (this.expirationTime) { + if (this.expiredRequestCount) { + return 1000 * (1 << Math.min(this.expiredRequestCount - 1, 31)); + } + else { + // Max value for `setTimeout` implementations is a 32 bit integer; cap this accordingly + return Math.min(this.expirationTime - new Date().getTime(), Math.pow(2, 31) - 1); + } + } + } + setFeatureState(states, painter) { + if (!this.latestFeatureIndex || + !this.latestFeatureIndex.rawTileData || + Object.keys(states).length === 0) { + return; + } + const vtLayers = this.latestFeatureIndex.loadVTLayers(); + for (const id in this.buckets) { + if (!painter.style.hasLayer(id)) + continue; + const bucket = this.buckets[id]; + // Buckets are grouped by common source-layer + const sourceLayerId = bucket.layers[0]['sourceLayer'] || '_geojsonTileLayer'; + const sourceLayer = vtLayers[sourceLayerId]; + const sourceLayerStates = states[sourceLayerId]; + if (!sourceLayer || !sourceLayerStates || Object.keys(sourceLayerStates).length === 0) + continue; + bucket.update(sourceLayerStates, sourceLayer, this.imageAtlas && this.imageAtlas.patternPositions || {}); + const layer = painter && painter.style && painter.style.getLayer(id); + if (layer) { + this.queryPadding = Math.max(this.queryPadding, layer.queryRadius(bucket)); + } + } + } + holdingForFade() { + return this.symbolFadeHoldUntil !== undefined; + } + symbolFadeFinished() { + return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < browser.now(); + } + clearFadeHold() { + this.symbolFadeHoldUntil = undefined; + } + setHoldDuration(duration) { + this.symbolFadeHoldUntil = browser.now() + duration; + } + setDependencies(namespace, dependencies) { + const index = {}; + for (const dep of dependencies) { + index[dep] = true; + } + this.dependencies[namespace] = index; + } + hasDependency(namespaces, keys) { + for (const namespace of namespaces) { + const dependencies = this.dependencies[namespace]; + if (dependencies) { + for (const key of keys) { + if (dependencies[key]) { + return true; + } + } + } + } + return false; + } +} + +/** + * @internal + * A [least-recently-used cache](https://en.wikipedia.org/wiki/Cache_algorithms) + * with hash lookup made possible by keeping a list of keys in parallel to + * an array of dictionary of values + */ +class TileCache { + /** + * @param max - number of permitted values + * @param onRemove - callback called with items when they expire + */ + constructor(max, onRemove) { + this.max = max; + this.onRemove = onRemove; + this.reset(); + } + /** + * Clear the cache + * + * @returns this cache + */ + reset() { + for (const key in this.data) { + for (const removedData of this.data[key]) { + if (removedData.timeout) + clearTimeout(removedData.timeout); + this.onRemove(removedData.value); + } + } + this.data = {}; + this.order = []; + return this; + } + /** + * Add a key, value combination to the cache, trimming its size if this pushes + * it over max length. + * + * @param tileID - lookup key for the item + * @param data - tile data + * + * @returns this cache + */ + add(tileID, data, expiryTimeout) { + const key = tileID.wrapped().key; + if (this.data[key] === undefined) { + this.data[key] = []; + } + const dataWrapper = { + value: data, + timeout: undefined + }; + if (expiryTimeout !== undefined) { + dataWrapper.timeout = setTimeout(() => { + this.remove(tileID, dataWrapper); + }, expiryTimeout); + } + this.data[key].push(dataWrapper); + this.order.push(key); + if (this.order.length > this.max) { + const removedData = this._getAndRemoveByKey(this.order[0]); + if (removedData) + this.onRemove(removedData); + } + return this; + } + /** + * Determine whether the value attached to `key` is present + * + * @param tileID - the key to be looked-up + * @returns whether the cache has this value + */ + has(tileID) { + return tileID.wrapped().key in this.data; + } + /** + * Get the value attached to a specific key and remove data from cache. + * If the key is not found, returns `null` + * + * @param tileID - the key to look up + * @returns the tile data, or null if it isn't found + */ + getAndRemove(tileID) { + if (!this.has(tileID)) { + return null; + } + return this._getAndRemoveByKey(tileID.wrapped().key); + } + /* + * Get and remove the value with the specified key. + */ + _getAndRemoveByKey(key) { + const data = this.data[key].shift(); + if (data.timeout) + clearTimeout(data.timeout); + if (this.data[key].length === 0) { + delete this.data[key]; + } + this.order.splice(this.order.indexOf(key), 1); + return data.value; + } + /* + * Get the value with the specified (wrapped tile) key. + */ + getByKey(key) { + const data = this.data[key]; + return data ? data[0].value : null; + } + /** + * Get the value attached to a specific key without removing data + * from the cache. If the key is not found, returns `null` + * + * @param tileID - the key to look up + * @returns the tile data, or null if it isn't found + */ + get(tileID) { + if (!this.has(tileID)) { + return null; + } + const data = this.data[tileID.wrapped().key][0]; + return data.value; + } + /** + * Remove a key/value combination from the cache. + * + * @param tileID - the key for the pair to delete + * @param value - If a value is provided, remove that exact version of the value. + * @returns this cache + */ + remove(tileID, value) { + if (!this.has(tileID)) { + return this; + } + const key = tileID.wrapped().key; + const dataIndex = value === undefined ? 0 : this.data[key].indexOf(value); + const data = this.data[key][dataIndex]; + this.data[key].splice(dataIndex, 1); + if (data.timeout) + clearTimeout(data.timeout); + if (this.data[key].length === 0) { + delete this.data[key]; + } + this.onRemove(data.value); + this.order.splice(this.order.indexOf(key), 1); + return this; + } + /** + * Change the max size of the cache. + * + * @param max - the max size of the cache + * @returns this cache + */ + setMaxSize(max) { + this.max = max; + while (this.order.length > this.max) { + const removedData = this._getAndRemoveByKey(this.order[0]); + if (removedData) + this.onRemove(removedData); + } + return this; + } + /** + * Remove entries that do not pass a filter function. Used for removing + * stale tiles from the cache. + * + * @param filterFn - Determines whether the tile is filtered. If the supplied function returns false, the tile will be filtered out. + */ + filter(filterFn) { + const removed = []; + for (const key in this.data) { + for (const entry of this.data[key]) { + if (!filterFn(entry.value)) { + removed.push(entry); + } + } + } + for (const r of removed) { + this.remove(r.value.tileID, r); + } + } +} + +/** + * @internal + * SourceFeatureState manages the state and pending changes + * to features in a source, separated by source layer. + * stateChanges and deletedStates batch all changes to the tile (updates and removes, respectively) + * between coalesce() events. addFeatureState() and removeFeatureState() also update their counterpart's + * list of changes, such that coalesce() can apply the proper state changes while agnostic to the order of operations. + * In deletedStates, all null's denote complete removal of state at that scope +*/ +class SourceFeatureState { + constructor() { + this.state = {}; + this.stateChanges = {}; + this.deletedStates = {}; + } + updateState(sourceLayer, featureId, newState) { + const feature = String(featureId); + this.stateChanges[sourceLayer] = this.stateChanges[sourceLayer] || {}; + this.stateChanges[sourceLayer][feature] = this.stateChanges[sourceLayer][feature] || {}; + performance$1.extend(this.stateChanges[sourceLayer][feature], newState); + if (this.deletedStates[sourceLayer] === null) { + this.deletedStates[sourceLayer] = {}; + for (const ft in this.state[sourceLayer]) { + if (ft !== feature) + this.deletedStates[sourceLayer][ft] = null; + } + } + else { + const featureDeletionQueued = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] === null; + if (featureDeletionQueued) { + this.deletedStates[sourceLayer][feature] = {}; + for (const prop in this.state[sourceLayer][feature]) { + if (!newState[prop]) + this.deletedStates[sourceLayer][feature][prop] = null; + } + } + else { + for (const key in newState) { + const deletionInQueue = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] && this.deletedStates[sourceLayer][feature][key] === null; + if (deletionInQueue) + delete this.deletedStates[sourceLayer][feature][key]; + } + } + } + } + removeFeatureState(sourceLayer, featureId, key) { + const sourceLayerDeleted = this.deletedStates[sourceLayer] === null; + if (sourceLayerDeleted) + return; + const feature = String(featureId); + this.deletedStates[sourceLayer] = this.deletedStates[sourceLayer] || {}; + if (key && featureId !== undefined) { + if (this.deletedStates[sourceLayer][feature] !== null) { + this.deletedStates[sourceLayer][feature] = this.deletedStates[sourceLayer][feature] || {}; + this.deletedStates[sourceLayer][feature][key] = null; + } + } + else if (featureId !== undefined) { + const updateInQueue = this.stateChanges[sourceLayer] && this.stateChanges[sourceLayer][feature]; + if (updateInQueue) { + this.deletedStates[sourceLayer][feature] = {}; + for (key in this.stateChanges[sourceLayer][feature]) + this.deletedStates[sourceLayer][feature][key] = null; + } + else { + this.deletedStates[sourceLayer][feature] = null; + } + } + else { + this.deletedStates[sourceLayer] = null; + } + } + getState(sourceLayer, featureId) { + const feature = String(featureId); + const base = this.state[sourceLayer] || {}; + const changes = this.stateChanges[sourceLayer] || {}; + const reconciledState = performance$1.extend({}, base[feature], changes[feature]); + //return empty object if the whole source layer is awaiting deletion + if (this.deletedStates[sourceLayer] === null) + return {}; + else if (this.deletedStates[sourceLayer]) { + const featureDeletions = this.deletedStates[sourceLayer][featureId]; + if (featureDeletions === null) + return {}; + for (const prop in featureDeletions) + delete reconciledState[prop]; + } + return reconciledState; + } + initializeTileState(tile, painter) { + tile.setFeatureState(this.state, painter); + } + coalesceChanges(tiles, painter) { + //track changes with full state objects, but only for features that got modified + const featuresChanged = {}; + for (const sourceLayer in this.stateChanges) { + this.state[sourceLayer] = this.state[sourceLayer] || {}; + const layerStates = {}; + for (const feature in this.stateChanges[sourceLayer]) { + if (!this.state[sourceLayer][feature]) + this.state[sourceLayer][feature] = {}; + performance$1.extend(this.state[sourceLayer][feature], this.stateChanges[sourceLayer][feature]); + layerStates[feature] = this.state[sourceLayer][feature]; + } + featuresChanged[sourceLayer] = layerStates; + } + for (const sourceLayer in this.deletedStates) { + this.state[sourceLayer] = this.state[sourceLayer] || {}; + const layerStates = {}; + if (this.deletedStates[sourceLayer] === null) { + for (const ft in this.state[sourceLayer]) { + layerStates[ft] = {}; + this.state[sourceLayer][ft] = {}; + } + } + else { + for (const feature in this.deletedStates[sourceLayer]) { + const deleteWholeFeatureState = this.deletedStates[sourceLayer][feature] === null; + if (deleteWholeFeatureState) + this.state[sourceLayer][feature] = {}; + else { + for (const key of Object.keys(this.deletedStates[sourceLayer][feature])) { + delete this.state[sourceLayer][feature][key]; + } + } + layerStates[feature] = this.state[sourceLayer][feature]; + } + } + featuresChanged[sourceLayer] = featuresChanged[sourceLayer] || {}; + performance$1.extend(featuresChanged[sourceLayer], layerStates); + } + this.stateChanges = {}; + this.deletedStates = {}; + if (Object.keys(featuresChanged).length === 0) + return; + for (const id in tiles) { + const tile = tiles[id]; + tile.setFeatureState(featuresChanged, painter); + } + } +} + +/** + * @internal + * `SourceCache` is responsible for + * + * - creating an instance of `Source` + * - forwarding events from `Source` + * - caching tiles loaded from an instance of `Source` + * - loading the tiles needed to render a given viewport + * - unloading the cached tiles not needed to render a given viewport + */ +class SourceCache extends performance$1.Evented { + constructor(id, options, dispatcher) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.on('data', (e) => this._dataHandler(e)); + this.on('dataloading', () => { + this._sourceErrored = false; + }); + this.on('error', () => { + // Only set _sourceErrored if the source does not have pending loads. + this._sourceErrored = this._source.loaded(); + }); + this._source = create(id, options, dispatcher, this); + this._tiles = {}; + this._cache = new TileCache(0, (tile) => this._unloadTile(tile)); + this._timers = {}; + this._cacheTimers = {}; + this._maxTileCacheSize = null; + this._maxTileCacheZoomLevels = null; + this._loadedParentTiles = {}; + this._coveredTiles = {}; + this._state = new SourceFeatureState(); + this._didEmitContent = false; + this._updated = false; + } + onAdd(map) { + this.map = map; + this._maxTileCacheSize = map ? map._maxTileCacheSize : null; + this._maxTileCacheZoomLevels = map ? map._maxTileCacheZoomLevels : null; + if (this._source && this._source.onAdd) { + this._source.onAdd(map); + } + } + onRemove(map) { + this.clearTiles(); + if (this._source && this._source.onRemove) { + this._source.onRemove(map); + } + } + /** + * Return true if no tile data is pending, tiles will not change unless + * an additional API call is received. + */ + loaded() { + if (this._sourceErrored) { + return true; + } + if (!this._sourceLoaded) { + return false; + } + if (!this._source.loaded()) { + return false; + } + if ((this.used !== undefined || this.usedForTerrain !== undefined) && !this.used && !this.usedForTerrain) { + return true; + } + // do not consider as loaded if the update hasn't been called yet (we do not know if we will have any tiles to fetch) + if (!this._updated) { + return false; + } + for (const t in this._tiles) { + const tile = this._tiles[t]; + if (tile.state !== 'loaded' && tile.state !== 'errored') + return false; + } + return true; + } + getSource() { + return this._source; + } + pause() { + this._paused = true; + } + resume() { + if (!this._paused) + return; + const shouldReload = this._shouldReloadOnResume; + this._paused = false; + this._shouldReloadOnResume = false; + if (shouldReload) + this.reload(); + if (this.transform) + this.update(this.transform, this.terrain); + } + _loadTile(tile, id, state) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + try { + yield this._source.loadTile(tile); + this._tileLoaded(tile, id, state); + } + catch (err) { + tile.state = 'errored'; + if (err.status !== 404) { + this._source.fire(new performance$1.ErrorEvent(err, { tile })); + } + else { + // continue to try loading parent/children tiles if a tile doesn't exist (404) + this.update(this.transform, this.terrain); + } + } + }); + } + _unloadTile(tile) { + if (this._source.unloadTile) + this._source.unloadTile(tile); + } + _abortTile(tile) { + if (this._source.abortTile) + this._source.abortTile(tile); + this._source.fire(new performance$1.Event('dataabort', { tile, coord: tile.tileID, dataType: 'source' })); + } + serialize() { + return this._source.serialize(); + } + prepare(context) { + if (this._source.prepare) { + this._source.prepare(); + } + this._state.coalesceChanges(this._tiles, this.map ? this.map.painter : null); + for (const i in this._tiles) { + const tile = this._tiles[i]; + tile.upload(context); + tile.prepare(this.map.style.imageManager); + } + } + /** + * Return all tile ids ordered with z-order, and cast to numbers + */ + getIds() { + return Object.values(this._tiles).map((tile) => tile.tileID).sort(compareTileId).map(id => id.key); + } + getRenderableIds(symbolLayer) { + const renderables = []; + for (const id in this._tiles) { + if (this._isIdRenderable(id, symbolLayer)) + renderables.push(this._tiles[id]); + } + if (symbolLayer) { + return renderables.sort((a_, b_) => { + const a = a_.tileID; + const b = b_.tileID; + const rotatedA = (new performance$1.Point(a.canonical.x, a.canonical.y))._rotate(this.transform.angle); + const rotatedB = (new performance$1.Point(b.canonical.x, b.canonical.y))._rotate(this.transform.angle); + return a.overscaledZ - b.overscaledZ || rotatedB.y - rotatedA.y || rotatedB.x - rotatedA.x; + }).map(tile => tile.tileID.key); + } + return renderables.map(tile => tile.tileID).sort(compareTileId).map(id => id.key); + } + hasRenderableParent(tileID) { + const parentTile = this.findLoadedParent(tileID, 0); + if (parentTile) { + return this._isIdRenderable(parentTile.tileID.key); + } + return false; + } + _isIdRenderable(id, symbolLayer) { + return this._tiles[id] && this._tiles[id].hasData() && + !this._coveredTiles[id] && (symbolLayer || !this._tiles[id].holdingForFade()); + } + reload() { + if (this._paused) { + this._shouldReloadOnResume = true; + return; + } + this._cache.reset(); + for (const i in this._tiles) { + if (this._tiles[i].state !== 'errored') + this._reloadTile(i, 'reloading'); + } + } + _reloadTile(id, state) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + const tile = this._tiles[id]; + // this potentially does not address all underlying + // issues https://github.com/mapbox/mapbox-gl-js/issues/4252 + // - hard to tell without repro steps + if (!tile) + return; + // The difference between "loading" tiles and "reloading" or "expired" + // tiles is that "reloading"/"expired" tiles are "renderable". + // Therefore, a "loading" tile cannot become a "reloading" tile without + // first becoming a "loaded" tile. + if (tile.state !== 'loading') { + tile.state = state; + } + yield this._loadTile(tile, id, state); + }); + } + _tileLoaded(tile, id, previousState) { + tile.timeAdded = browser.now(); + if (previousState === 'expired') + tile.refreshedUponExpiration = true; + this._setTileReloadTimer(id, tile); + if (this.getSource().type === 'raster-dem' && tile.dem) + this._backfillDEM(tile); + this._state.initializeTileState(tile, this.map ? this.map.painter : null); + if (!tile.aborted) { + this._source.fire(new performance$1.Event('data', { dataType: 'source', tile, coord: tile.tileID })); + } + } + /** + * For raster terrain source, backfill DEM to eliminate visible tile boundaries + */ + _backfillDEM(tile) { + const renderables = this.getRenderableIds(); + for (let i = 0; i < renderables.length; i++) { + const borderId = renderables[i]; + if (tile.neighboringTiles && tile.neighboringTiles[borderId]) { + const borderTile = this.getTileByID(borderId); + fillBorder(tile, borderTile); + fillBorder(borderTile, tile); + } + } + function fillBorder(tile, borderTile) { + tile.needsHillshadePrepare = true; + tile.needsTerrainPrepare = true; + let dx = borderTile.tileID.canonical.x - tile.tileID.canonical.x; + const dy = borderTile.tileID.canonical.y - tile.tileID.canonical.y; + const dim = Math.pow(2, tile.tileID.canonical.z); + const borderId = borderTile.tileID.key; + if (dx === 0 && dy === 0) + return; + if (Math.abs(dy) > 1) { + return; + } + if (Math.abs(dx) > 1) { + // Adjust the delta coordinate for world wraparound. + if (Math.abs(dx + dim) === 1) { + dx += dim; + } + else if (Math.abs(dx - dim) === 1) { + dx -= dim; + } + } + if (!borderTile.dem || !tile.dem) + return; + tile.dem.backfillBorder(borderTile.dem, dx, dy); + if (tile.neighboringTiles && tile.neighboringTiles[borderId]) + tile.neighboringTiles[borderId].backfilled = true; + } + } + /** + * Get a specific tile by TileID + */ + getTile(tileID) { + return this.getTileByID(tileID.key); + } + /** + * Get a specific tile by id + */ + getTileByID(id) { + return this._tiles[id]; + } + /** + * For a given set of tiles, retain children that are loaded and have a zoom + * between `zoom` (exclusive) and `maxCoveringZoom` (inclusive) + */ + _retainLoadedChildren(idealTiles, zoom, maxCoveringZoom, retain) { + for (const id in this._tiles) { + let tile = this._tiles[id]; + // only consider renderable tiles up to maxCoveringZoom + if (retain[id] || + !tile.hasData() || + tile.tileID.overscaledZ <= zoom || + tile.tileID.overscaledZ > maxCoveringZoom) + continue; + // loop through parents and retain the topmost loaded one if found + let topmostLoadedID = tile.tileID; + while (tile && tile.tileID.overscaledZ > zoom + 1) { + const parentID = tile.tileID.scaledTo(tile.tileID.overscaledZ - 1); + tile = this._tiles[parentID.key]; + if (tile && tile.hasData()) { + topmostLoadedID = parentID; + } + } + // loop through ancestors of the topmost loaded child to see if there's one that needed it + let tileID = topmostLoadedID; + while (tileID.overscaledZ > zoom) { + tileID = tileID.scaledTo(tileID.overscaledZ - 1); + if (idealTiles[tileID.key]) { + // found a parent that needed a loaded child; retain that child + retain[topmostLoadedID.key] = topmostLoadedID; + break; + } + } + } + } + /** + * Find a loaded parent of the given tile (up to minCoveringZoom) + */ + findLoadedParent(tileID, minCoveringZoom) { + if (tileID.key in this._loadedParentTiles) { + const parent = this._loadedParentTiles[tileID.key]; + if (parent && parent.tileID.overscaledZ >= minCoveringZoom) { + return parent; + } + else { + return null; + } + } + for (let z = tileID.overscaledZ - 1; z >= minCoveringZoom; z--) { + const parentTileID = tileID.scaledTo(z); + const tile = this._getLoadedTile(parentTileID); + if (tile) { + return tile; + } + } + } + /** + * Find a loaded sibling of the given tile + */ + findLoadedSibling(tileID) { + // If a tile with this ID already exists, return it + return this._getLoadedTile(tileID); + } + _getLoadedTile(tileID) { + const tile = this._tiles[tileID.key]; + if (tile && tile.hasData()) { + return tile; + } + // TileCache ignores wrap in lookup. + const cachedTile = this._cache.getByKey(tileID.wrapped().key); + return cachedTile; + } + /** + * Resizes the tile cache based on the current viewport's size + * or the maxTileCacheSize option passed during map creation + * + * Larger viewports use more tiles and need larger caches. Larger viewports + * are more likely to be found on devices with more memory and on pages where + * the map is more important. + */ + updateCacheSize(transform) { + const widthInTiles = Math.ceil(transform.width / this._source.tileSize) + 1; + const heightInTiles = Math.ceil(transform.height / this._source.tileSize) + 1; + const approxTilesInView = widthInTiles * heightInTiles; + const commonZoomRange = this._maxTileCacheZoomLevels === null ? + performance$1.config.MAX_TILE_CACHE_ZOOM_LEVELS : this._maxTileCacheZoomLevels; + const viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange); + const maxSize = typeof this._maxTileCacheSize === 'number' ? + Math.min(this._maxTileCacheSize, viewDependentMaxSize) : viewDependentMaxSize; + this._cache.setMaxSize(maxSize); + } + handleWrapJump(lng) { + // On top of the regular z/x/y values, TileIDs have a `wrap` value that specify + // which cppy of the world the tile belongs to. For example, at `lng: 10` you + // might render z/x/y/0 while at `lng: 370` you would render z/x/y/1. + // + // When lng values get wrapped (going from `lng: 370` to `long: 10`) you expect + // to see the same thing on the screen (370 degrees and 10 degrees is the same + // place in the world) but all the TileIDs will have different wrap values. + // + // In order to make this transition seamless, we calculate the rounded difference of + // "worlds" between the last frame and the current frame. If the map panned by + // a world, then we can assign all the tiles new TileIDs with updated wrap values. + // For example, assign z/x/y/1 a new id: z/x/y/0. It is the same tile, just rendered + // in a different position. + // + // This enables us to reuse the tiles at more ideal locations and prevent flickering. + const prevLng = this._prevLng === undefined ? lng : this._prevLng; + const lngDifference = lng - prevLng; + const worldDifference = lngDifference / 360; + const wrapDelta = Math.round(worldDifference); + this._prevLng = lng; + if (wrapDelta) { + const tiles = {}; + for (const key in this._tiles) { + const tile = this._tiles[key]; + tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta); + tiles[tile.tileID.key] = tile; + } + this._tiles = tiles; + // Reset tile reload timers + for (const id in this._timers) { + clearTimeout(this._timers[id]); + delete this._timers[id]; + } + for (const id in this._tiles) { + const tile = this._tiles[id]; + this._setTileReloadTimer(id, tile); + } + } + } + _updateCoveredAndRetainedTiles(retain, minCoveringZoom, maxCoveringZoom, zoom, idealTileIDs, terrain) { + const tilesForFading = {}; + const fadingTiles = {}; + const ids = Object.keys(retain); + const now = browser.now(); + for (const id of ids) { + const tileID = retain[id]; + const tile = this._tiles[id]; + // when fadeEndTime is 0, the tile is created but registerFadeDuration + // has not been called, therefore must be kept in fadingTiles dictionary + // for next round of rendering + if (!tile || (tile.fadeEndTime !== 0 && tile.fadeEndTime <= now)) { + continue; + } + // if the tile is loaded but still fading in, find parents to cross-fade with it + const parentTile = this.findLoadedParent(tileID, minCoveringZoom); + const siblingTile = this.findLoadedSibling(tileID); + const fadeTileRef = parentTile || siblingTile || null; + if (fadeTileRef) { + this._addTile(fadeTileRef.tileID); + tilesForFading[fadeTileRef.tileID.key] = fadeTileRef.tileID; + } + fadingTiles[id] = tileID; + } + // for tiles that are still fading in, also find children to cross-fade with + this._retainLoadedChildren(fadingTiles, zoom, maxCoveringZoom, retain); + for (const id in tilesForFading) { + if (!retain[id]) { + // If a tile is only needed for fading, mark it as covered so that it isn't rendered on it's own. + this._coveredTiles[id] = true; + retain[id] = tilesForFading[id]; + } + } + // disable fading logic in terrain3D mode to avoid rendering two tiles on the same place + if (terrain) { + const idealRasterTileIDs = {}; + const missingTileIDs = {}; + for (const tileID of idealTileIDs) { + if (this._tiles[tileID.key].hasData()) + idealRasterTileIDs[tileID.key] = tileID; + else + missingTileIDs[tileID.key] = tileID; + } + // search for a complete set of children for each missing tile + for (const key in missingTileIDs) { + const children = missingTileIDs[key].children(this._source.maxzoom); + if (this._tiles[children[0].key] && this._tiles[children[1].key] && this._tiles[children[2].key] && this._tiles[children[3].key]) { + idealRasterTileIDs[children[0].key] = retain[children[0].key] = children[0]; + idealRasterTileIDs[children[1].key] = retain[children[1].key] = children[1]; + idealRasterTileIDs[children[2].key] = retain[children[2].key] = children[2]; + idealRasterTileIDs[children[3].key] = retain[children[3].key] = children[3]; + delete missingTileIDs[key]; + } + } + // search for parent or sibling for each missing tile + for (const key in missingTileIDs) { + const tileID = missingTileIDs[key]; + const parentTile = this.findLoadedParent(tileID, this._source.minzoom); + const siblingTile = this.findLoadedSibling(tileID); + const fadeTileRef = parentTile || siblingTile || null; + if (fadeTileRef) { + idealRasterTileIDs[fadeTileRef.tileID.key] = retain[fadeTileRef.tileID.key] = fadeTileRef.tileID; + // remove idealTiles which would be rendered twice + for (const key in idealRasterTileIDs) { + if (idealRasterTileIDs[key].isChildOf(fadeTileRef.tileID)) + delete idealRasterTileIDs[key]; + } + } + } + // cover all tiles which are not needed + for (const key in this._tiles) { + if (!idealRasterTileIDs[key]) + this._coveredTiles[key] = true; + } + } + } + /** + * Removes tiles that are outside the viewport and adds new tiles that + * are inside the viewport. + */ + update(transform, terrain) { + if (!this._sourceLoaded || this._paused) { + return; + } + this.transform = transform; + this.terrain = terrain; + this.updateCacheSize(transform); + this.handleWrapJump(this.transform.center.lng); + // Covered is a list of retained tiles who's areas are fully covered by other, + // better, retained tiles. They are not drawn separately. + this._coveredTiles = {}; + let idealTileIDs; + if (!this.used && !this.usedForTerrain) { + idealTileIDs = []; + } + else if (this._source.tileID) { + idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID) + .map((unwrapped) => new performance$1.OverscaledTileID(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y)); + } + else { + idealTileIDs = transform.coveringTiles({ + tileSize: this.usedForTerrain ? this.tileSize : this._source.tileSize, + minzoom: this._source.minzoom, + maxzoom: this._source.maxzoom, + roundZoom: this.usedForTerrain ? false : this._source.roundZoom, + reparseOverscaled: this._source.reparseOverscaled, + terrain + }); + if (this._source.hasTile) { + idealTileIDs = idealTileIDs.filter((coord) => this._source.hasTile(coord)); + } + } + // Determine the overzooming/underzooming amounts. + const zoom = transform.coveringZoomLevel(this._source); + const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom); + const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom); + // When sourcecache is used for terrain also load parent tiles to avoid flickering when zooming out + if (this.usedForTerrain) { + const parents = {}; + for (const tileID of idealTileIDs) { + if (tileID.canonical.z > this._source.minzoom) { + const parent = tileID.scaledTo(tileID.canonical.z - 1); + parents[parent.key] = parent; + // load very low zoom to calculate tile visibility in transform.coveringTiles and high zoomlevels correct + const parent2 = tileID.scaledTo(Math.max(this._source.minzoom, Math.min(tileID.canonical.z, 5))); + parents[parent2.key] = parent2; + } + } + idealTileIDs = idealTileIDs.concat(Object.values(parents)); + } + const noPendingDataEmissions = idealTileIDs.length === 0 && !this._updated && this._didEmitContent; + this._updated = true; + // if we won't have any tiles to fetch and content is already emitted + // there will be no more data emissions, so we need to emit the event with isSourceLoaded = true + if (noPendingDataEmissions) { + this.fire(new performance$1.Event('data', { sourceDataType: 'idle', dataType: 'source', sourceId: this.id })); + } + // Retain is a list of tiles that we shouldn't delete, even if they are not + // the most ideal tile for the current viewport. This may include tiles like + // parent or child tiles that are *already* loaded. + const retain = this._updateRetainedTiles(idealTileIDs, zoom); + if (isRasterType(this._source.type)) { + this._updateCoveredAndRetainedTiles(retain, minCoveringZoom, maxCoveringZoom, zoom, idealTileIDs, terrain); + } + for (const retainedId in retain) { + // Make sure retained tiles always clear any existing fade holds + // so that if they're removed again their fade timer starts fresh. + this._tiles[retainedId].clearFadeHold(); + } + // Remove the tiles we don't need anymore. + const remove = performance$1.keysDifference(this._tiles, retain); + for (const tileID of remove) { + const tile = this._tiles[tileID]; + if (tile.hasSymbolBuckets && !tile.holdingForFade()) { + tile.setHoldDuration(this.map._fadeDuration); + } + else if (!tile.hasSymbolBuckets || tile.symbolFadeFinished()) { + this._removeTile(tileID); + } + } + // Construct caches of loaded parents & siblings + this._updateLoadedParentTileCache(); + this._updateLoadedSiblingTileCache(); + } + releaseSymbolFadeTiles() { + for (const id in this._tiles) { + if (this._tiles[id].holdingForFade()) { + this._removeTile(id); + } + } + } + _updateRetainedTiles(idealTileIDs, zoom) { + var _a; + const retain = {}; + const checked = {}; + const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom); + const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom); + const missingTiles = {}; + for (const tileID of idealTileIDs) { + const tile = this._addTile(tileID); + // retain the tile even if it's not loaded because it's an ideal tile. + retain[tileID.key] = tileID; + if (tile.hasData()) + continue; + if (zoom < this._source.maxzoom) { + // save missing tiles that potentially have loaded children + missingTiles[tileID.key] = tileID; + } + } + // retain any loaded children of ideal tiles up to maxCoveringZoom + this._retainLoadedChildren(missingTiles, zoom, maxCoveringZoom, retain); + for (const tileID of idealTileIDs) { + let tile = this._tiles[tileID.key]; + if (tile.hasData()) + continue; + // The tile we require is not yet loaded or does not exist; + // Attempt to find children that fully cover it. + if (zoom + 1 > this._source.maxzoom) { + // We're looking for an overzoomed child tile. + const childCoord = tileID.children(this._source.maxzoom)[0]; + const childTile = this.getTile(childCoord); + if (!!childTile && childTile.hasData()) { + retain[childCoord.key] = childCoord; + continue; // tile is covered by overzoomed child + } + } + else { + // check if all 4 immediate children are loaded (i.e. the missing ideal tile is covered) + const children = tileID.children(this._source.maxzoom); + if (retain[children[0].key] && + retain[children[1].key] && + retain[children[2].key] && + retain[children[3].key]) + continue; // tile is covered by children + } + // We couldn't find child tiles that entirely cover the ideal tile; look for parents now. + // As we ascend up the tile pyramid of the ideal tile, we check whether the parent + // tile has been previously requested (and errored because we only loop over tiles with no data) + // in order to determine if we need to request its parent. + let parentWasRequested = tile.wasRequested(); + for (let overscaledZ = tileID.overscaledZ - 1; overscaledZ >= minCoveringZoom; --overscaledZ) { + const parentId = tileID.scaledTo(overscaledZ); + // Break parent tile ascent if this route has been previously checked by another child. + if (checked[parentId.key]) + break; + checked[parentId.key] = true; + tile = this.getTile(parentId); + if (!tile && parentWasRequested) { + tile = this._addTile(parentId); + } + if (tile) { + const hasData = tile.hasData(); + if (hasData || !((_a = this.map) === null || _a === void 0 ? void 0 : _a.cancelPendingTileRequestsWhileZooming) || parentWasRequested) { + retain[parentId.key] = parentId; + } + // Save the current values, since they're the parent of the next iteration + // of the parent tile ascent loop. + parentWasRequested = tile.wasRequested(); + if (hasData) + break; + } + } + } + return retain; + } + _updateLoadedParentTileCache() { + this._loadedParentTiles = {}; + for (const tileKey in this._tiles) { + const path = []; + let parentTile; + let currentId = this._tiles[tileKey].tileID; + // Find the closest loaded ancestor by traversing the tile tree towards the root and + // caching results along the way + while (currentId.overscaledZ > 0) { + // Do we have a cached result from previous traversals? + if (currentId.key in this._loadedParentTiles) { + parentTile = this._loadedParentTiles[currentId.key]; + break; + } + path.push(currentId.key); + // Is the parent loaded? + const parentId = currentId.scaledTo(currentId.overscaledZ - 1); + parentTile = this._getLoadedTile(parentId); + if (parentTile) { + break; + } + currentId = parentId; + } + // Cache the result of this traversal to all newly visited tiles + for (const key of path) { + this._loadedParentTiles[key] = parentTile; + } + } + } + /** + * Update the cache of loaded sibling tiles + * + * Sibling tiles are tiles that share the same zoom level and + * x/y position but have different wrap values + * Maintaining sibling tile cache allows fading from old to new tiles + * of the same position and zoom level + */ + _updateLoadedSiblingTileCache() { + this._loadedSiblingTiles = {}; + for (const tileKey in this._tiles) { + const currentId = this._tiles[tileKey].tileID; + const siblingTile = this._getLoadedTile(currentId); + this._loadedSiblingTiles[currentId.key] = siblingTile; + } + } + /** + * Add a tile, given its coordinate, to the pyramid. + */ + _addTile(tileID) { + let tile = this._tiles[tileID.key]; + if (tile) + return tile; + tile = this._cache.getAndRemove(tileID); + if (tile) { + this._setTileReloadTimer(tileID.key, tile); + // set the tileID because the cached tile could have had a different wrap value + tile.tileID = tileID; + this._state.initializeTileState(tile, this.map ? this.map.painter : null); + if (this._cacheTimers[tileID.key]) { + clearTimeout(this._cacheTimers[tileID.key]); + delete this._cacheTimers[tileID.key]; + this._setTileReloadTimer(tileID.key, tile); + } + } + const cached = tile; + if (!tile) { + tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor()); + this._loadTile(tile, tileID.key, tile.state); + } + tile.uses++; + this._tiles[tileID.key] = tile; + if (!cached) { + this._source.fire(new performance$1.Event('dataloading', { tile, coord: tile.tileID, dataType: 'source' })); + } + return tile; + } + _setTileReloadTimer(id, tile) { + if (id in this._timers) { + clearTimeout(this._timers[id]); + delete this._timers[id]; + } + const expiryTimeout = tile.getExpiryTimeout(); + if (expiryTimeout) { + this._timers[id] = setTimeout(() => { + this._reloadTile(id, 'expired'); + delete this._timers[id]; + }, expiryTimeout); + } + } + /** + * Remove a tile, given its id, from the pyramid + */ + _removeTile(id) { + const tile = this._tiles[id]; + if (!tile) + return; + tile.uses--; + delete this._tiles[id]; + if (this._timers[id]) { + clearTimeout(this._timers[id]); + delete this._timers[id]; + } + if (tile.uses > 0) + return; + if (tile.hasData() && tile.state !== 'reloading') { + this._cache.add(tile.tileID, tile, tile.getExpiryTimeout()); + } + else { + tile.aborted = true; + this._abortTile(tile); + this._unloadTile(tile); + } + } + /** @internal */ + _dataHandler(e) { + const eventSourceDataType = e.sourceDataType; + if (e.dataType === 'source' && eventSourceDataType === 'metadata') { + this._sourceLoaded = true; + } + // for sources with mutable data, this event fires when the underlying data + // to a source is changed. (i.e. GeoJSONSource#setData and ImageSource#serCoordinates) + if (this._sourceLoaded && !this._paused && e.dataType === 'source' && eventSourceDataType === 'content') { + this.reload(); + if (this.transform) { + this.update(this.transform, this.terrain); + } + this._didEmitContent = true; + } + } + /** + * Remove all tiles from this pyramid + */ + clearTiles() { + this._shouldReloadOnResume = false; + this._paused = false; + for (const id in this._tiles) + this._removeTile(id); + this._cache.reset(); + } + /** + * Search through our current tiles and attempt to find the tiles that + * cover the given bounds. + * @param pointQueryGeometry - coordinates of the corners of bounding rectangle + * @returns result items have `{tile, minX, maxX, minY, maxY}`, where min/max bounding values are the given bounds transformed in into the coordinate space of this tile. + */ + tilesIn(pointQueryGeometry, maxPitchScaleFactor, has3DLayer) { + const tileResults = []; + const transform = this.transform; + if (!transform) + return tileResults; + const cameraPointQueryGeometry = has3DLayer ? + transform.getCameraQueryGeometry(pointQueryGeometry) : + pointQueryGeometry; + const queryGeometry = pointQueryGeometry.map((p) => transform.pointCoordinate(p, this.terrain)); + const cameraQueryGeometry = cameraPointQueryGeometry.map((p) => transform.pointCoordinate(p, this.terrain)); + const ids = this.getIds(); + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const p of cameraQueryGeometry) { + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + for (let i = 0; i < ids.length; i++) { + const tile = this._tiles[ids[i]]; + if (tile.holdingForFade()) { + // Tiles held for fading are covered by tiles that are closer to ideal + continue; + } + const tileID = tile.tileID; + const scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ); + const queryPadding = maxPitchScaleFactor * tile.queryPadding * performance$1.EXTENT / tile.tileSize / scale; + const tileSpaceBounds = [ + tileID.getTilePoint(new performance$1.MercatorCoordinate(minX, minY)), + tileID.getTilePoint(new performance$1.MercatorCoordinate(maxX, maxY)) + ]; + if (tileSpaceBounds[0].x - queryPadding < performance$1.EXTENT && tileSpaceBounds[0].y - queryPadding < performance$1.EXTENT && + tileSpaceBounds[1].x + queryPadding >= 0 && tileSpaceBounds[1].y + queryPadding >= 0) { + const tileSpaceQueryGeometry = queryGeometry.map((c) => tileID.getTilePoint(c)); + const tileSpaceCameraQueryGeometry = cameraQueryGeometry.map((c) => tileID.getTilePoint(c)); + tileResults.push({ + tile, + tileID, + queryGeometry: tileSpaceQueryGeometry, + cameraQueryGeometry: tileSpaceCameraQueryGeometry, + scale + }); + } + } + return tileResults; + } + getVisibleCoordinates(symbolLayer) { + const coords = this.getRenderableIds(symbolLayer).map((id) => this._tiles[id].tileID); + for (const coord of coords) { + coord.posMatrix = this.transform.calculatePosMatrix(coord.toUnwrapped()); + } + return coords; + } + hasTransition() { + if (this._source.hasTransition()) { + return true; + } + if (isRasterType(this._source.type)) { + const now = browser.now(); + for (const id in this._tiles) { + const tile = this._tiles[id]; + if (tile.fadeEndTime >= now) { + return true; + } + } + } + return false; + } + /** + * Set the value of a particular state for a feature + */ + setFeatureState(sourceLayer, featureId, state) { + sourceLayer = sourceLayer || '_geojsonTileLayer'; + this._state.updateState(sourceLayer, featureId, state); + } + /** + * Resets the value of a particular state key for a feature + */ + removeFeatureState(sourceLayer, featureId, key) { + sourceLayer = sourceLayer || '_geojsonTileLayer'; + this._state.removeFeatureState(sourceLayer, featureId, key); + } + /** + * Get the entire state object for a feature + */ + getFeatureState(sourceLayer, featureId) { + sourceLayer = sourceLayer || '_geojsonTileLayer'; + return this._state.getState(sourceLayer, featureId); + } + /** + * Sets the set of keys that the tile depends on. This allows tiles to + * be reloaded when their dependencies change. + */ + setDependencies(tileKey, namespace, dependencies) { + const tile = this._tiles[tileKey]; + if (tile) { + tile.setDependencies(namespace, dependencies); + } + } + /** + * Reloads all tiles that depend on the given keys. + */ + reloadTilesForDependencies(namespaces, keys) { + for (const id in this._tiles) { + const tile = this._tiles[id]; + if (tile.hasDependency(namespaces, keys)) { + this._reloadTile(id, 'reloading'); + } + } + this._cache.filter(tile => !tile.hasDependency(namespaces, keys)); + } +} +SourceCache.maxOverzooming = 10; +SourceCache.maxUnderzooming = 3; +function compareTileId(a, b) { + // Different copies of the world are sorted based on their distance to the center. + // Wrap values are converted to unsigned distances by reserving odd number for copies + // with negative wrap and even numbers for copies with positive wrap. + const aWrap = Math.abs(a.wrap * 2) - +(a.wrap < 0); + const bWrap = Math.abs(b.wrap * 2) - +(b.wrap < 0); + return a.overscaledZ - b.overscaledZ || bWrap - aWrap || b.canonical.y - a.canonical.y || b.canonical.x - a.canonical.x; +} +function isRasterType(type) { + return type === 'raster' || type === 'image' || type === 'video'; +} + +class PathInterpolator { + constructor(points_, padding_) { + this.reset(points_, padding_); + } + reset(points_, padding_) { + this.points = points_ || []; + // Compute cumulative distance from first point to every other point in the segment. + // Last entry in the array is total length of the path + this._distances = [0.0]; + for (let i = 1; i < this.points.length; i++) { + this._distances[i] = this._distances[i - 1] + this.points[i].dist(this.points[i - 1]); + } + this.length = this._distances[this._distances.length - 1]; + this.padding = Math.min(padding_ || 0, this.length * 0.5); + this.paddedLength = this.length - this.padding * 2.0; + } + lerp(t) { + if (this.points.length === 1) { + return this.points[0]; + } + t = performance$1.clamp(t, 0, 1); + // Find the correct segment [p0, p1] where p0 <= x < p1 + let currentIndex = 1; + let distOfCurrentIdx = this._distances[currentIndex]; + const distToTarget = t * this.paddedLength + this.padding; + while (distOfCurrentIdx < distToTarget && currentIndex < this._distances.length) { + distOfCurrentIdx = this._distances[++currentIndex]; + } + // Interpolate between the two points of the segment + const idxOfPrevPoint = currentIndex - 1; + const distOfPrevIdx = this._distances[idxOfPrevPoint]; + const segmentLength = distOfCurrentIdx - distOfPrevIdx; + const segmentT = segmentLength > 0 ? (distToTarget - distOfPrevIdx) / segmentLength : 0; + return this.points[idxOfPrevPoint].mult(1.0 - segmentT).add(this.points[currentIndex].mult(segmentT)); + } +} + +function overlapAllowed(overlapA, overlapB) { + let allowed = true; + if (overlapA === 'always') { + // symbol A using 'always' overlap - allowed to overlap anything. + } + else if (overlapA === 'never' || overlapB === 'never') { + // symbol A using 'never' overlap - can't overlap anything + // symbol A using 'cooperative' overlap - can overlap 'always' or 'cooperative' symbol; can't overlap 'never' + allowed = false; + } + return allowed; +} +/** + * @internal + * GridIndex is a data structure for testing the intersection of + * circles and rectangles in a 2d plane. + * It is optimized for rapid insertion and querying. + * GridIndex splits the plane into a set of "cells" and keeps track + * of which geometries intersect with each cell. At query time, + * full geometry comparisons are only done for items that share + * at least one cell. As long as the geometries are relatively + * uniformly distributed across the plane, this greatly reduces + * the number of comparisons necessary. + */ +class GridIndex { + constructor(width, height, cellSize) { + const boxCells = this.boxCells = []; + const circleCells = this.circleCells = []; + // More cells -> fewer geometries to check per cell, but items tend + // to be split across more cells. + // Sweet spot allows most small items to fit in one cell + this.xCellCount = Math.ceil(width / cellSize); + this.yCellCount = Math.ceil(height / cellSize); + for (let i = 0; i < this.xCellCount * this.yCellCount; i++) { + boxCells.push([]); + circleCells.push([]); + } + this.circleKeys = []; + this.boxKeys = []; + this.bboxes = []; + this.circles = []; + this.width = width; + this.height = height; + this.xScale = this.xCellCount / width; + this.yScale = this.yCellCount / height; + this.boxUid = 0; + this.circleUid = 0; + } + keysLength() { + return this.boxKeys.length + this.circleKeys.length; + } + insert(key, x1, y1, x2, y2) { + this._forEachCell(x1, y1, x2, y2, this._insertBoxCell, this.boxUid++); + this.boxKeys.push(key); + this.bboxes.push(x1); + this.bboxes.push(y1); + this.bboxes.push(x2); + this.bboxes.push(y2); + } + insertCircle(key, x, y, radius) { + // Insert circle into grid for all cells in the circumscribing square + // It's more than necessary (by a factor of 4/PI), but fast to insert + this._forEachCell(x - radius, y - radius, x + radius, y + radius, this._insertCircleCell, this.circleUid++); + this.circleKeys.push(key); + this.circles.push(x); + this.circles.push(y); + this.circles.push(radius); + } + _insertBoxCell(x1, y1, x2, y2, cellIndex, uid) { + this.boxCells[cellIndex].push(uid); + } + _insertCircleCell(x1, y1, x2, y2, cellIndex, uid) { + this.circleCells[cellIndex].push(uid); + } + _query(x1, y1, x2, y2, hitTest, overlapMode, predicate) { + if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) { + return []; + } + const result = []; + if (x1 <= 0 && y1 <= 0 && this.width <= x2 && this.height <= y2) { + if (hitTest) { + // Covers the entire grid, so collides with everything + return [{ + key: null, + x1, + y1, + x2, + y2 + }]; + } + for (let boxUid = 0; boxUid < this.boxKeys.length; boxUid++) { + result.push({ + key: this.boxKeys[boxUid], + x1: this.bboxes[boxUid * 4], + y1: this.bboxes[boxUid * 4 + 1], + x2: this.bboxes[boxUid * 4 + 2], + y2: this.bboxes[boxUid * 4 + 3] + }); + } + for (let circleUid = 0; circleUid < this.circleKeys.length; circleUid++) { + const x = this.circles[circleUid * 3]; + const y = this.circles[circleUid * 3 + 1]; + const radius = this.circles[circleUid * 3 + 2]; + result.push({ + key: this.circleKeys[circleUid], + x1: x - radius, + y1: y - radius, + x2: x + radius, + y2: y + radius + }); + } + } + else { + const queryArgs = { + hitTest, + overlapMode, + seenUids: { box: {}, circle: {} } + }; + this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate); + } + return result; + } + query(x1, y1, x2, y2) { + return this._query(x1, y1, x2, y2, false, null); + } + hitTest(x1, y1, x2, y2, overlapMode, predicate) { + return this._query(x1, y1, x2, y2, true, overlapMode, predicate).length > 0; + } + hitTestCircle(x, y, radius, overlapMode, predicate) { + // Insert circle into grid for all cells in the circumscribing square + // It's more than necessary (by a factor of 4/PI), but fast to insert + const x1 = x - radius; + const x2 = x + radius; + const y1 = y - radius; + const y2 = y + radius; + if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) { + return false; + } + // Box query early exits if the bounding box is larger than the grid, but we don't do + // the equivalent calculation for circle queries because early exit is less likely + // and the calculation is more expensive + const result = []; + const queryArgs = { + hitTest: true, + overlapMode, + circle: { x, y, radius }, + seenUids: { box: {}, circle: {} } + }; + this._forEachCell(x1, y1, x2, y2, this._queryCellCircle, result, queryArgs, predicate); + return result.length > 0; + } + _queryCell(x1, y1, x2, y2, cellIndex, result, queryArgs, predicate) { + const { seenUids, hitTest, overlapMode } = queryArgs; + const boxCell = this.boxCells[cellIndex]; + if (boxCell !== null) { + const bboxes = this.bboxes; + for (const boxUid of boxCell) { + if (!seenUids.box[boxUid]) { + seenUids.box[boxUid] = true; + const offset = boxUid * 4; + const key = this.boxKeys[boxUid]; + if ((x1 <= bboxes[offset + 2]) && + (y1 <= bboxes[offset + 3]) && + (x2 >= bboxes[offset + 0]) && + (y2 >= bboxes[offset + 1]) && + (!predicate || predicate(key))) { + if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) { + result.push({ + key, + x1: bboxes[offset], + y1: bboxes[offset + 1], + x2: bboxes[offset + 2], + y2: bboxes[offset + 3] + }); + if (hitTest) { + // true return value stops the query after first match + return true; + } + } + } + } + } + } + const circleCell = this.circleCells[cellIndex]; + if (circleCell !== null) { + const circles = this.circles; + for (const circleUid of circleCell) { + if (!seenUids.circle[circleUid]) { + seenUids.circle[circleUid] = true; + const offset = circleUid * 3; + const key = this.circleKeys[circleUid]; + if (this._circleAndRectCollide(circles[offset], circles[offset + 1], circles[offset + 2], x1, y1, x2, y2) && + (!predicate || predicate(key))) { + if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) { + const x = circles[offset]; + const y = circles[offset + 1]; + const radius = circles[offset + 2]; + result.push({ + key, + x1: x - radius, + y1: y - radius, + x2: x + radius, + y2: y + radius + }); + if (hitTest) { + // true return value stops the query after first match + return true; + } + } + } + } + } + } + // false return to continue query + return false; + } + _queryCellCircle(x1, y1, x2, y2, cellIndex, result, queryArgs, predicate) { + const { circle, seenUids, overlapMode } = queryArgs; + const boxCell = this.boxCells[cellIndex]; + if (boxCell !== null) { + const bboxes = this.bboxes; + for (const boxUid of boxCell) { + if (!seenUids.box[boxUid]) { + seenUids.box[boxUid] = true; + const offset = boxUid * 4; + const key = this.boxKeys[boxUid]; + if (this._circleAndRectCollide(circle.x, circle.y, circle.radius, bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) && + (!predicate || predicate(key)) && + !overlapAllowed(overlapMode, key.overlapMode)) { + result.push(true); + return true; + } + } + } + } + const circleCell = this.circleCells[cellIndex]; + if (circleCell !== null) { + const circles = this.circles; + for (const circleUid of circleCell) { + if (!seenUids.circle[circleUid]) { + seenUids.circle[circleUid] = true; + const offset = circleUid * 3; + const key = this.circleKeys[circleUid]; + if (this._circlesCollide(circles[offset], circles[offset + 1], circles[offset + 2], circle.x, circle.y, circle.radius) && + (!predicate || predicate(key)) && + !overlapAllowed(overlapMode, key.overlapMode)) { + result.push(true); + return true; + } + } + } + } + } + _forEachCell(x1, y1, x2, y2, fn, arg1, arg2, predicate) { + const cx1 = this._convertToXCellCoord(x1); + const cy1 = this._convertToYCellCoord(y1); + const cx2 = this._convertToXCellCoord(x2); + const cy2 = this._convertToYCellCoord(y2); + for (let x = cx1; x <= cx2; x++) { + for (let y = cy1; y <= cy2; y++) { + const cellIndex = this.xCellCount * y + x; + if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, predicate)) + return; + } + } + } + _convertToXCellCoord(x) { + return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(x * this.xScale))); + } + _convertToYCellCoord(y) { + return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(y * this.yScale))); + } + _circlesCollide(x1, y1, r1, x2, y2, r2) { + const dx = x2 - x1; + const dy = y2 - y1; + const bothRadii = r1 + r2; + return (bothRadii * bothRadii) > (dx * dx + dy * dy); + } + _circleAndRectCollide(circleX, circleY, radius, x1, y1, x2, y2) { + const halfRectWidth = (x2 - x1) / 2; + const distX = Math.abs(circleX - (x1 + halfRectWidth)); + if (distX > (halfRectWidth + radius)) { + return false; + } + const halfRectHeight = (y2 - y1) / 2; + const distY = Math.abs(circleY - (y1 + halfRectHeight)); + if (distY > (halfRectHeight + radius)) { + return false; + } + if (distX <= halfRectWidth || distY <= halfRectHeight) { + return true; + } + const dx = distX - halfRectWidth; + const dy = distY - halfRectHeight; + return (dx * dx + dy * dy <= (radius * radius)); + } +} + +/* + * # Overview of coordinate spaces + * + * ## Tile coordinate spaces + * Each label has an anchor. Some labels have corresponding line geometries. + * The points for both anchors and lines are stored in tile units. Each tile has it's own + * coordinate space going from (0, 0) at the top left to (EXTENT, EXTENT) at the bottom right. + * + * ## Clip space (GL coordinate space) + * At the end of everything, the vertex shader needs to produce a position in clip space, + * which is (-1, 1) at the top left and (1, -1) in the bottom right. + * In the depth buffer, values are between 0 (near plane) to 1 (far plane). + * + * ## Map pixel coordinate spaces + * Each tile has a pixel coordinate space. It's just the tile units scaled so that one unit is + * whatever counts as 1 pixel at the current zoom. + * This space is used for pitch-alignment=map, rotation-alignment=map + * + * ## Rotated map pixel coordinate spaces + * Like the above, but rotated so axis of the space are aligned with the viewport instead of the tile. + * This space is used for pitch-alignment=map, rotation-alignment=viewport + * + * ## Viewport pixel coordinate space + * (0, 0) is at the top left of the canvas and (pixelWidth, pixelHeight) is at the bottom right corner + * of the canvas. This space is used for pitch-alignment=viewport + * + * + * # Vertex projection + * It goes roughly like this: + * 1. project the anchor and line from tile units into the correct label coordinate space + * - map pixel space pitch-alignment=map rotation-alignment=map + * - rotated map pixel space pitch-alignment=map rotation-alignment=viewport + * - viewport pixel space pitch-alignment=viewport rotation-alignment=* + * 2. if the label follows a line, find the point along the line that is the correct distance from the anchor. + * 3. add the glyph's corner offset to the point from step 3 + * 4. convert from the label coordinate space to clip space + * + * For horizontal labels we want to do step 1 in the shader for performance reasons (no cpu work). + * This is what `u_label_plane_matrix` is used for. + * For labels aligned with lines we have to steps 1 and 2 on the cpu since we need access to the line geometry. + * This is what `updateLineLabels(...)` does. + * Since the conversion is handled on the cpu we just set `u_label_plane_matrix` to an identity matrix. + * + * Steps 3 and 4 are done in the shaders for all labels. + */ +/* + * Returns a matrix for converting from tile units to the correct label coordinate space. + */ +function getLabelPlaneMatrix(posMatrix, pitchWithMap, rotateWithMap, transform, pixelsToTileUnits) { + const m = performance$1.create(); + if (pitchWithMap) { + performance$1.scale(m, m, [1 / pixelsToTileUnits, 1 / pixelsToTileUnits, 1]); + if (!rotateWithMap) { + performance$1.rotateZ(m, m, transform.angle); + } + } + else { + performance$1.multiply(m, transform.labelPlaneMatrix, posMatrix); + } + return m; +} +/* + * Returns a matrix for converting from the correct label coordinate space to clip space. + */ +function getGlCoordMatrix(posMatrix, pitchWithMap, rotateWithMap, transform, pixelsToTileUnits) { + if (pitchWithMap) { + const m = performance$1.clone(posMatrix); + performance$1.scale(m, m, [pixelsToTileUnits, pixelsToTileUnits, 1]); + if (!rotateWithMap) { + performance$1.rotateZ(m, m, -transform.angle); + } + return m; + } + else { + return transform.glCoordMatrix; + } +} +function project(x, y, matrix, getElevation) { + let pos; + if (getElevation) { // slow because of handle z-index + pos = [x, y, getElevation(x, y), 1]; + performance$1.transformMat4(pos, pos, matrix); + } + else { // fast because of ignore z-index + pos = [x, y, 0, 1]; + xyTransformMat4(pos, pos, matrix); + } + const w = pos[3]; + return { + point: new performance$1.Point(pos[0] / w, pos[1] / w), + signedDistanceFromCamera: w, + isOccluded: false + }; +} +function getPerspectiveRatio(cameraToCenterDistance, signedDistanceFromCamera) { + return 0.5 + 0.5 * (cameraToCenterDistance / signedDistanceFromCamera); +} +function isVisible(p, clippingBuffer) { + const inPaddedViewport = (p.x >= -clippingBuffer[0] && + p.x <= clippingBuffer[0] && + p.y >= -clippingBuffer[1] && + p.y <= clippingBuffer[1]); + return inPaddedViewport; +} +/* + * Update the `dynamicLayoutVertexBuffer` for the buffer with the correct glyph positions for the current map view. + * This is only run on labels that are aligned with lines. Horizontal labels are handled entirely in the shader. + */ +function updateLineLabels(bucket, posMatrix, painter, isText, labelPlaneMatrix, glCoordMatrix, pitchWithMap, keepUpright, rotateToLine, projection, unwrappedTileID, viewportWidth, viewportHeight, translation, getElevation) { + const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData; + const partiallyEvaluatedSize = performance$1.evaluateSizeForZoom(sizeData, painter.transform.zoom); + const clippingBuffer = [256 / painter.width * 2 + 1, 256 / painter.height * 2 + 1]; + const dynamicLayoutVertexArray = isText ? + bucket.text.dynamicLayoutVertexArray : + bucket.icon.dynamicLayoutVertexArray; + dynamicLayoutVertexArray.clear(); + const lineVertexArray = bucket.lineVertexArray; + const placedSymbols = isText ? bucket.text.placedSymbolArray : bucket.icon.placedSymbolArray; + const aspectRatio = painter.transform.width / painter.transform.height; + let useVertical = false; + for (let s = 0; s < placedSymbols.length; s++) { + const symbol = placedSymbols.get(s); + // Don't do calculations for vertical glyphs unless the previous symbol was horizontal + // and we determined that vertical glyphs were necessary. + // Also don't do calculations for symbols that are collided and fully faded out + if (symbol.hidden || symbol.writingMode === performance$1.WritingMode.vertical && !useVertical) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + continue; + } + // Awkward... but we're counting on the paired "vertical" symbol coming immediately after its horizontal counterpart + useVertical = false; + const anchorPos = project(symbol.anchorX, symbol.anchorY, posMatrix, getElevation); + // Don't bother calculating the correct point for invisible labels. + if (!isVisible(anchorPos.point, clippingBuffer)) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + continue; + } + const cameraToAnchorDistance = anchorPos.signedDistanceFromCamera; + const perspectiveRatio = getPerspectiveRatio(painter.transform.cameraToCenterDistance, cameraToAnchorDistance); + const fontSize = performance$1.evaluateSizeForFeature(sizeData, partiallyEvaluatedSize, symbol); + const pitchScaledFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio; + const tileAnchorPoint = new performance$1.Point(symbol.anchorX, symbol.anchorY); + const projectionCache = { projections: {}, offsets: {}, cachedAnchorPoint: undefined, anyProjectionOccluded: false }; + const projectionContext = { + getElevation, + labelPlaneMatrix, + lineVertexArray, + pitchWithMap, + projectionCache, + projection, + tileAnchorPoint, + unwrappedTileID, + width: viewportWidth, + height: viewportHeight, + translation + }; + const placeUnflipped = placeGlyphsAlongLine(projectionContext, symbol, pitchScaledFontSize, false /*unflipped*/, keepUpright, posMatrix, glCoordMatrix, bucket.glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine); + useVertical = placeUnflipped.useVertical; + if (placeUnflipped.notEnoughRoom || useVertical || + (placeUnflipped.needsFlipping && + placeGlyphsAlongLine(projectionContext, symbol, pitchScaledFontSize, true /*flipped*/, keepUpright, posMatrix, glCoordMatrix, bucket.glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine).notEnoughRoom)) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + } + } + if (isText) { + bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray); + } + else { + bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray); + } +} +/* + * Place the first and last glyph of a line label, projected to the label plane. + * This function is called both during collision detection (to determine the label's size) + * and during line label rendering (to make sure the label fits on the line geometry with + * the current camera position, which may differ from the position used during collision detection). + * + * Calling this function has the effect of populating the "projectionCache" with all projected + * vertex locations the label will need, making future calls to placeGlyphAlongLine (for all the + * intermediate glyphs) much cheaper. + * + * Returns null if the label can't fit on the geometry + */ +function placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, symbol, rotateToLine, projectionContext) { + const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs; + const lineStartIndex = symbol.lineStartIndex; + const lineEndIndex = symbol.lineStartIndex + symbol.lineLength; + const firstGlyphOffset = glyphOffsetArray.getoffsetX(symbol.glyphStartIndex); + const lastGlyphOffset = glyphOffsetArray.getoffsetX(glyphEndIndex - 1); + const firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, lineOffsetX, lineOffsetY, flip, symbol.segment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine); + if (!firstPlacedGlyph) + return null; + const lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, symbol.segment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine); + if (!lastPlacedGlyph) + return null; + if (projectionContext.projectionCache.anyProjectionOccluded) { + return null; + } + return { first: firstPlacedGlyph, last: lastPlacedGlyph }; +} +function requiresOrientationChange(writingMode, firstPoint, lastPoint, aspectRatio) { + if (writingMode === performance$1.WritingMode.horizontal) { + // On top of choosing whether to flip, choose whether to render this version of the glyphs or the alternate + // vertical glyphs. We can't just filter out vertical glyphs in the horizontal range because the horizontal + // and vertical versions can have slightly different projections which could lead to angles where both or + // neither showed. + const rise = Math.abs(lastPoint.y - firstPoint.y); + const run = Math.abs(lastPoint.x - firstPoint.x) * aspectRatio; + if (rise > run) { + return { useVertical: true }; + } + } + if (writingMode === performance$1.WritingMode.vertical ? firstPoint.y < lastPoint.y : firstPoint.x > lastPoint.x) { + // Includes "horizontalOnly" case for labels without vertical glyphs + return { needsFlipping: true }; + } + return null; +} +/* +* Place first and last glyph along the line projected to label plane, and if they fit +* iterate through all the intermediate glyphs, calculating their label plane positions +* from the projected line. +* +* Finally, add resulting glyph position calculations to dynamicLayoutVertexArray for +* upload to the GPU +*/ +function placeGlyphsAlongLine(projectionContext, symbol, fontSize, flip, keepUpright, posMatrix, glCoordMatrix, glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine) { + const fontScale = fontSize / 24; + const lineOffsetX = symbol.lineOffsetX * fontScale; + const lineOffsetY = symbol.lineOffsetY * fontScale; + let placedGlyphs; + if (symbol.numGlyphs > 1) { + const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs; + const lineStartIndex = symbol.lineStartIndex; + const lineEndIndex = symbol.lineStartIndex + symbol.lineLength; + // Place the first and the last glyph in the label first, so we can figure out + // the overall orientation of the label and determine whether it needs to be flipped in keepUpright mode + const firstAndLastGlyph = placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, symbol, rotateToLine, projectionContext); + if (!firstAndLastGlyph) { + return { notEnoughRoom: true }; + } + const firstPoint = project(firstAndLastGlyph.first.point.x, firstAndLastGlyph.first.point.y, glCoordMatrix, projectionContext.getElevation).point; + const lastPoint = project(firstAndLastGlyph.last.point.x, firstAndLastGlyph.last.point.y, glCoordMatrix, projectionContext.getElevation).point; + if (keepUpright && !flip) { + const orientationChange = requiresOrientationChange(symbol.writingMode, firstPoint, lastPoint, aspectRatio); + if (orientationChange) { + return orientationChange; + } + } + placedGlyphs = [firstAndLastGlyph.first]; + for (let glyphIndex = symbol.glyphStartIndex + 1; glyphIndex < glyphEndIndex - 1; glyphIndex++) { + // Since first and last glyph fit on the line, we're sure that the rest of the glyphs can be placed + placedGlyphs.push(placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphIndex), lineOffsetX, lineOffsetY, flip, symbol.segment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine)); + } + placedGlyphs.push(firstAndLastGlyph.last); + } + else { + // Only a single glyph to place + // So, determine whether to flip based on projected angle of the line segment it's on + if (keepUpright && !flip) { + const a = project(projectionContext.tileAnchorPoint.x, projectionContext.tileAnchorPoint.y, posMatrix, projectionContext.getElevation).point; + const tileVertexIndex = (symbol.lineStartIndex + symbol.segment + 1); + const tileSegmentEnd = new performance$1.Point(projectionContext.lineVertexArray.getx(tileVertexIndex), projectionContext.lineVertexArray.gety(tileVertexIndex)); + const projectedVertex = project(tileSegmentEnd.x, tileSegmentEnd.y, posMatrix, projectionContext.getElevation); + // We know the anchor will be in the viewport, but the end of the line segment may be + // behind the plane of the camera, in which case we can use a point at any arbitrary (closer) + // point on the segment. + const b = (projectedVertex.signedDistanceFromCamera > 0) ? + projectedVertex.point : + projectTruncatedLineSegmentToLabelPlane(projectionContext.tileAnchorPoint, tileSegmentEnd, a, 1, posMatrix, projectionContext); + const orientationChange = requiresOrientationChange(symbol.writingMode, a, b, aspectRatio); + if (orientationChange) { + return orientationChange; + } + } + const singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(symbol.glyphStartIndex), lineOffsetX, lineOffsetY, flip, symbol.segment, symbol.lineStartIndex, symbol.lineStartIndex + symbol.lineLength, projectionContext, rotateToLine); + if (!singleGlyph || projectionContext.projectionCache.anyProjectionOccluded) + return { notEnoughRoom: true }; + placedGlyphs = [singleGlyph]; + } + for (const glyph of placedGlyphs) { + performance$1.addDynamicAttributes(dynamicLayoutVertexArray, glyph.point, glyph.angle); + } + return {}; +} +/** + * Takes a line and direction from `previousTilePoint` to `currentTilePoint`, + * projects it to *label plane*, + * and returns a projected point along this projected line that is `minimumLength` distance away from `previousProjectedPoint`. + * @param previousTilePoint - Line start point, in tile coordinates. + * @param currentTilePoint - Line end point, in tile coordinates. + * @param previousProjectedPoint - Projection of `previousTilePoint` into *label plane*. + * @param minimumLength - Distance in the projected space along the line for the returned point. + * @param projectionMatrix - Matrix to use during projection. + * @param projectionContext - Projection context, used only for terrain's `getElevation`. + */ +function projectTruncatedLineSegmentToLabelPlane(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionMatrix, projectionContext) { + return _projectTruncatedLineSegment(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionMatrix, projectionContext); +} +/** + * Takes a line and direction from `previousTilePoint` to `currentTilePoint`, + * projects it to *viewport*, + * and returns a projected point along this projected line that is `minimumLength` distance away from `previousProjectedPoint`. + * @param previousTilePoint - Line start point, in tile coordinates. + * @param currentTilePoint - Line end point, in tile coordinates. + * @param previousProjectedPoint - Projection of `previousTilePoint` into *viewport*. + * @param minimumLength - Distance in the projected space along the line for the returned point. + * @param projectionContext - Projection context, used for terrain's `getElevation`, and either the `labelPlaneMatrix` or the map's special projection (mostly for globe). + */ +function projectTruncatedLineSegmentToViewport(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionContext) { + return _projectTruncatedLineSegment(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, undefined, projectionContext); +} +/** + * Do not use directly, use {@link projectTruncatedLineSegmentToLabelPlane} or {@link projectTruncatedLineSegmentToViewport} instead, + * depending on the target space. + * + * Projects a "virtual" vertex along a line segment. + * If `projectionMatrix` is not undefined, does a simple projection using this matrix. + * Otherwise, either projects to label plane using the `labelPlaneMatrix` + * or projects to viewport using the special map projection (mostly for globe) by calling {@link projectTileCoordinatesToViewport}. + */ +function _projectTruncatedLineSegment(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionMatrix, projectionContext) { + // We are assuming "previousTilePoint" won't project to a point within one unit of the camera plane + // If it did, that would mean our label extended all the way out from within the viewport to a (very distant) + // point near the plane of the camera. We wouldn't be able to render the label anyway once it crossed the + // plane of the camera. + const unitVertexToBeProjected = previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit()); + const projectedUnitVertex = projectionMatrix !== undefined ? + project(unitVertexToBeProjected.x, unitVertexToBeProjected.y, projectionMatrix, projectionContext.getElevation).point : + projectTileCoordinatesToViewport(unitVertexToBeProjected.x, unitVertexToBeProjected.y, projectionContext).point; + const projectedUnitSegment = previousProjectedPoint.sub(projectedUnitVertex); + return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength / projectedUnitSegment.mag())); +} +/** + * Transform a vertex from tile coordinates to label plane coordinates + * @param index - index of vertex to project + * @param projectionContext - necessary data to project a vertex + * @returns the vertex projected to the label plane + */ +function projectLineVertexToViewport(index, projectionContext, syntheticVertexArgs) { + const cache = projectionContext.projectionCache; + if (cache.projections[index]) { + return cache.projections[index]; + } + const currentVertex = new performance$1.Point(projectionContext.lineVertexArray.getx(index), projectionContext.lineVertexArray.gety(index)); + const projection = projectTileCoordinatesToViewport(currentVertex.x, currentVertex.y, projectionContext); + if (projection.signedDistanceFromCamera > 0) { + cache.projections[index] = projection.point; + cache.anyProjectionOccluded = cache.anyProjectionOccluded || projection.isOccluded; + return projection.point; + } + // The vertex is behind the plane of the camera, so we can't project it + // Instead, we'll create a vertex along the line that's far enough to include the glyph + const previousLineVertexIndex = index - syntheticVertexArgs.direction; + const previousTilePoint = syntheticVertexArgs.distanceFromAnchor === 0 ? + projectionContext.tileAnchorPoint : + new performance$1.Point(projectionContext.lineVertexArray.getx(previousLineVertexIndex), projectionContext.lineVertexArray.gety(previousLineVertexIndex)); + // Don't cache because the new vertex might not be far enough out for future glyphs on the same segment + const minimumLength = syntheticVertexArgs.absOffsetX - syntheticVertexArgs.distanceFromAnchor + 1; + return projectTruncatedLineSegmentToViewport(previousTilePoint, currentVertex, syntheticVertexArgs.previousVertex, minimumLength, projectionContext); +} +function projectTileCoordinatesToViewport(x, y, projectionContext) { + const translatedX = x + projectionContext.translation[0]; + const translatedY = y + projectionContext.translation[1]; + let projection; + if (!projectionContext.pitchWithMap && projectionContext.projection.useSpecialProjectionForSymbols) { + projection = projectionContext.projection.projectTileCoordinates(translatedX, translatedY, projectionContext.unwrappedTileID, projectionContext.getElevation); + projection.point.x = (projection.point.x * 0.5 + 0.5) * projectionContext.width; + projection.point.y = (-projection.point.y * 0.5 + 0.5) * projectionContext.height; + } + else { + projection = project(translatedX, translatedY, projectionContext.labelPlaneMatrix, projectionContext.getElevation); + projection.isOccluded = false; + } + return projection; +} +/** + * Calculate the normal vector for a line segment + * @param segmentVector - will be mutated as a tiny optimization + * @param offset - magnitude of resulting vector + * @param direction - direction of line traversal + * @returns a normal vector from the segment, with magnitude equal to offset amount + */ +function transformToOffsetNormal(segmentVector, offset, direction) { + return segmentVector._unit()._perp()._mult(offset * direction); +} +/** + * Construct offset line segments for the current segment and the next segment, then extend/shrink + * the segments until they intersect. If the segments are parallel, then they will touch with no modification. + * + * @param index - Index of the current vertex + * @param prevToCurrentOffsetNormal - Normal vector of the line segment from the previous vertex to the current vertex + * @param currentVertex - Current (non-offset) vertex projected to the label plane + * @param lineStartIndex - Beginning index for the line this label is on + * @param lineEndIndex - End index for the line this label is on + * @param offsetPreviousVertex - The previous vertex projected to the label plane, and then offset along the previous segments normal + * @param lineOffsetY - Magnitude of the offset + * @param projectionContext - Necessary data for tile-to-label-plane projection + * @returns The point at which the current and next line segments intersect, once offset and extended/shrunk to their meeting point + */ +function findOffsetIntersectionPoint(index, prevToCurrentOffsetNormal, currentVertex, lineStartIndex, lineEndIndex, offsetPreviousVertex, lineOffsetY, projectionContext, syntheticVertexArgs) { + if (projectionContext.projectionCache.offsets[index]) { + return projectionContext.projectionCache.offsets[index]; + } + const offsetCurrentVertex = currentVertex.add(prevToCurrentOffsetNormal); + if (index + syntheticVertexArgs.direction < lineStartIndex || index + syntheticVertexArgs.direction >= lineEndIndex) { + // This is the end of the line, no intersection to calculate + projectionContext.projectionCache.offsets[index] = offsetCurrentVertex; + return offsetCurrentVertex; + } + // Offset the vertices for the next segment + const nextVertex = projectLineVertexToViewport(index + syntheticVertexArgs.direction, projectionContext, syntheticVertexArgs); + const currentToNextOffsetNormal = transformToOffsetNormal(nextVertex.sub(currentVertex), lineOffsetY, syntheticVertexArgs.direction); + const offsetNextSegmentBegin = currentVertex.add(currentToNextOffsetNormal); + const offsetNextSegmentEnd = nextVertex.add(currentToNextOffsetNormal); + // find the intersection of these two lines + // if the lines are parallel, offsetCurrent/offsetNextBegin will touch + projectionContext.projectionCache.offsets[index] = performance$1.findLineIntersection(offsetPreviousVertex, offsetCurrentVertex, offsetNextSegmentBegin, offsetNextSegmentEnd) || offsetCurrentVertex; + return projectionContext.projectionCache.offsets[index]; +} +/* + * Place a single glyph along its line, projected into the label plane, by iterating outward + * from the anchor point until the distance traversed in the label plane equals the glyph's + * offsetX. Returns null if the glyph can't fit on the line geometry. + */ +function placeGlyphAlongLine(offsetX, lineOffsetX, lineOffsetY, flip, anchorSegment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine) { + const combinedOffsetX = flip ? + offsetX - lineOffsetX : + offsetX + lineOffsetX; + let direction = combinedOffsetX > 0 ? 1 : -1; + let angle = 0; + if (flip) { + // The label needs to be flipped to keep text upright. + // Iterate in the reverse direction. + direction *= -1; + angle = Math.PI; + } + if (direction < 0) + angle += Math.PI; + let currentIndex = direction > 0 ? + lineStartIndex + anchorSegment : + lineStartIndex + anchorSegment + 1; + // Project anchor point to proper label plane and cache it + let anchorPoint; + if (projectionContext.projectionCache.cachedAnchorPoint) { + anchorPoint = projectionContext.projectionCache.cachedAnchorPoint; + } + else { + anchorPoint = projectTileCoordinatesToViewport(projectionContext.tileAnchorPoint.x, projectionContext.tileAnchorPoint.y, projectionContext).point; + projectionContext.projectionCache.cachedAnchorPoint = anchorPoint; + } + let currentVertex = anchorPoint; + let previousVertex = anchorPoint; + // offsetPrev and intersectionPoint are analogous to previousVertex and currentVertex + // but if there's a line offset they are calculated in parallel as projection happens + let offsetIntersectionPoint; + let offsetPreviousVertex; + let distanceFromAnchor = 0; + let currentSegmentDistance = 0; + const absOffsetX = Math.abs(combinedOffsetX); + const pathVertices = []; + let currentLineSegment; + while (distanceFromAnchor + currentSegmentDistance <= absOffsetX) { + currentIndex += direction; + // offset does not fit on the projected line + if (currentIndex < lineStartIndex || currentIndex >= lineEndIndex) + return null; + // accumulate values from last iteration + distanceFromAnchor += currentSegmentDistance; + previousVertex = currentVertex; + offsetPreviousVertex = offsetIntersectionPoint; + const syntheticVertexArgs = { + absOffsetX, + direction, + distanceFromAnchor, + previousVertex + }; + // find next vertex in viewport space + currentVertex = projectLineVertexToViewport(currentIndex, projectionContext, syntheticVertexArgs); + if (lineOffsetY === 0) { + // Store vertices for collision detection and update current segment geometry + pathVertices.push(previousVertex); + currentLineSegment = currentVertex.sub(previousVertex); + } + else { + // Calculate the offset for this section + let prevToCurrentOffsetNormal; + const prevToCurrent = currentVertex.sub(previousVertex); + if (prevToCurrent.mag() === 0) { + // We are starting with our anchor point directly on the vertex, so look one vertex ahead + // to calculate a normal + const nextVertex = projectLineVertexToViewport(currentIndex + direction, projectionContext, syntheticVertexArgs); + prevToCurrentOffsetNormal = transformToOffsetNormal(nextVertex.sub(currentVertex), lineOffsetY, direction); + } + else { + prevToCurrentOffsetNormal = transformToOffsetNormal(prevToCurrent, lineOffsetY, direction); + } + // Initialize offsetPrev on our first iteration, after that it will be pre-calculated + if (!offsetPreviousVertex) + offsetPreviousVertex = previousVertex.add(prevToCurrentOffsetNormal); + offsetIntersectionPoint = findOffsetIntersectionPoint(currentIndex, prevToCurrentOffsetNormal, currentVertex, lineStartIndex, lineEndIndex, offsetPreviousVertex, lineOffsetY, projectionContext, syntheticVertexArgs); + pathVertices.push(offsetPreviousVertex); + currentLineSegment = offsetIntersectionPoint.sub(offsetPreviousVertex); + } + currentSegmentDistance = currentLineSegment.mag(); + } + // The point is on the current segment. Interpolate to find it. + const segmentInterpolationT = (absOffsetX - distanceFromAnchor) / currentSegmentDistance; + const p = currentLineSegment._mult(segmentInterpolationT)._add(offsetPreviousVertex || previousVertex); + const segmentAngle = angle + Math.atan2(currentVertex.y - previousVertex.y, currentVertex.x - previousVertex.x); + pathVertices.push(p); + return { + point: p, + angle: rotateToLine ? segmentAngle : 0.0, + path: pathVertices + }; +} +const hiddenGlyphAttributes = new Float32Array([-Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0]); +// Hide them by moving them offscreen. We still need to add them to the buffer +// because the dynamic buffer is paired with a static buffer that doesn't get updated. +function hideGlyphs(num, dynamicLayoutVertexArray) { + for (let i = 0; i < num; i++) { + const offset = dynamicLayoutVertexArray.length; + dynamicLayoutVertexArray.resize(offset + 4); + // Since all hidden glyphs have the same attributes, we can build up the array faster with a single call to Float32Array.set + // for each set of four vertices, instead of calling addDynamicAttributes for each vertex. + dynamicLayoutVertexArray.float32.set(hiddenGlyphAttributes, offset * 3); + } +} +// For line label layout, we're not using z output and our w input is always 1 +// This custom matrix transformation ignores those components to make projection faster +function xyTransformMat4(out, a, m) { + const x = a[0], y = a[1]; + out[0] = m[0] * x + m[4] * y + m[12]; + out[1] = m[1] * x + m[5] * y + m[13]; + out[3] = m[3] * x + m[7] * y + m[15]; + return out; +} + +// When a symbol crosses the edge that causes it to be included in +// collision detection, it will cause changes in the symbols around +// it. This constant specifies how many pixels to pad the edge of +// the viewport for collision detection so that the bulk of the changes +// occur offscreen. Making this constant greater increases label +// stability, but it's expensive. +const viewportPadding = 100; +/** + * @internal + * A collision index used to prevent symbols from overlapping. It keep tracks of + * where previous symbols have been placed and is used to check if a new + * symbol overlaps with any previously added symbols. + * + * There are two steps to insertion: first placeCollisionBox/Circles checks if + * there's room for a symbol, then insertCollisionBox/Circles actually puts the + * symbol in the index. The two step process allows paired symbols to be inserted + * together even if they overlap. + */ +class CollisionIndex { + constructor(transform, projection, grid = new GridIndex(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25), ignoredGrid = new GridIndex(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25)) { + this.transform = transform; + this.mapProjection = projection; + this.grid = grid; + this.ignoredGrid = ignoredGrid; + this.pitchFactor = Math.cos(transform._pitch) * transform.cameraToCenterDistance; + this.screenRightBoundary = transform.width + viewportPadding; + this.screenBottomBoundary = transform.height + viewportPadding; + this.gridRightBoundary = transform.width + 2 * viewportPadding; + this.gridBottomBoundary = transform.height + 2 * viewportPadding; + this.perspectiveRatioCutoff = 0.6; + } + placeCollisionBox(collisionBox, overlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translation, collisionGroupPredicate, getElevation, shift) { + const x = collisionBox.anchorPointX + translation[0]; + const y = collisionBox.anchorPointY + translation[1]; + const projectedPoint = this.projectAndGetPerspectiveRatio(posMatrix, x, y, unwrappedTileID, getElevation); + const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio; + let projectedBox; + if (!pitchWithMap && !rotateWithMap) { + // Fast path for common symbols + const pointX = projectedPoint.point.x + (shift ? shift.x * tileToViewport : 0); + const pointY = projectedPoint.point.y + (shift ? shift.y * tileToViewport : 0); + projectedBox = { + allPointsOccluded: false, + box: [ + pointX + collisionBox.x1 * tileToViewport, + pointY + collisionBox.y1 * tileToViewport, + pointX + collisionBox.x2 * tileToViewport, + pointY + collisionBox.y2 * tileToViewport, + ] + }; + } + else { + projectedBox = this._projectCollisionBox(collisionBox, tileToViewport, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translation, projectedPoint, getElevation, shift); + } + const [tlX, tlY, brX, brY] = projectedBox.box; + const projectionOccluded = this.mapProjection.useSpecialProjectionForSymbols ? (pitchWithMap ? projectedBox.allPointsOccluded : this.mapProjection.isOccluded(x, y, unwrappedTileID)) : false; + if (projectionOccluded || projectedPoint.perspectiveRatio < this.perspectiveRatioCutoff || !this.isInsideGrid(tlX, tlY, brX, brY) || + (overlapMode !== 'always' && this.grid.hitTest(tlX, tlY, brX, brY, overlapMode, collisionGroupPredicate))) { + return { + box: [tlX, tlY, brX, brY], + placeable: false, + offscreen: false + }; + } + return { + box: [tlX, tlY, brX, brY], + placeable: true, + offscreen: this.isOffscreen(tlX, tlY, brX, brY) + }; + } + placeCollisionCircles(overlapMode, symbol, lineVertexArray, glyphOffsetArray, fontSize, posMatrix, unwrappedTileID, labelPlaneMatrix, labelToScreenMatrix, showCollisionCircles, pitchWithMap, collisionGroupPredicate, circlePixelDiameter, textPixelPadding, translation, getElevation) { + const placedCollisionCircles = []; + const tileUnitAnchorPoint = new performance$1.Point(symbol.anchorX, symbol.anchorY); + const perspectiveRatio = this.getPerspectiveRatio(posMatrix, tileUnitAnchorPoint.x, tileUnitAnchorPoint.y, unwrappedTileID, getElevation); + const labelPlaneFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio; + const labelPlaneFontScale = labelPlaneFontSize / performance$1.ONE_EM; + const projectionCache = { projections: {}, offsets: {}, cachedAnchorPoint: undefined, anyProjectionOccluded: false }; + const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale; + const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale; + const projectionContext = { + getElevation, + labelPlaneMatrix, + lineVertexArray, + pitchWithMap, + projectionCache, + projection: this.mapProjection, + tileAnchorPoint: tileUnitAnchorPoint, + unwrappedTileID, + width: this.transform.width, + height: this.transform.height, + translation + }; + const firstAndLastGlyph = placeFirstAndLastGlyph(labelPlaneFontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, + /*flip*/ false, symbol, false, projectionContext); + let collisionDetected = false; + let inGrid = false; + let entirelyOffscreen = true; + if (firstAndLastGlyph) { + const radius = circlePixelDiameter * 0.5 * perspectiveRatio + textPixelPadding; + const screenPlaneMin = new performance$1.Point(-viewportPadding, -viewportPadding); + const screenPlaneMax = new performance$1.Point(this.screenRightBoundary, this.screenBottomBoundary); + const interpolator = new PathInterpolator(); + // Construct a projected path from projected line vertices. Anchor points are ignored and removed + const first = firstAndLastGlyph.first; + const last = firstAndLastGlyph.last; + let projectedPath = []; + for (let i = first.path.length - 1; i >= 1; i--) { + projectedPath.push(first.path[i]); + } + for (let i = 1; i < last.path.length; i++) { + projectedPath.push(last.path[i]); + } + // Tolerate a slightly longer distance than one diameter between two adjacent circles + const circleDist = radius * 2.5; + // The path might need to be converted into screen space if a pitched map is used as the label space + if (labelToScreenMatrix) { + const screenSpacePath = this.projectPathToScreenSpace(projectedPath, projectionContext, labelToScreenMatrix); + // Do not try to place collision circles if even one of the points is behind the camera. + // This is a plausible scenario with big camera pitch angles + if (screenSpacePath.some(point => point.signedDistanceFromCamera <= 0)) { + projectedPath = []; + } + else { + projectedPath = screenSpacePath.map(p => p.point); + } + } + let segments = []; + if (projectedPath.length > 0) { + // Quickly check if the path is fully inside or outside of the padded collision region. + // For overlapping paths we'll only create collision circles for the visible segments + const minPoint = projectedPath[0].clone(); + const maxPoint = projectedPath[0].clone(); + for (let i = 1; i < projectedPath.length; i++) { + minPoint.x = Math.min(minPoint.x, projectedPath[i].x); + minPoint.y = Math.min(minPoint.y, projectedPath[i].y); + maxPoint.x = Math.max(maxPoint.x, projectedPath[i].x); + maxPoint.y = Math.max(maxPoint.y, projectedPath[i].y); + } + if (minPoint.x >= screenPlaneMin.x && maxPoint.x <= screenPlaneMax.x && + minPoint.y >= screenPlaneMin.y && maxPoint.y <= screenPlaneMax.y) { + // Quad fully visible + segments = [projectedPath]; + } + else if (maxPoint.x < screenPlaneMin.x || minPoint.x > screenPlaneMax.x || + maxPoint.y < screenPlaneMin.y || minPoint.y > screenPlaneMax.y) { + // Not visible + segments = []; + } + else { + segments = performance$1.clipLine([projectedPath], screenPlaneMin.x, screenPlaneMin.y, screenPlaneMax.x, screenPlaneMax.y); + } + } + for (const seg of segments) { + // interpolate positions for collision circles. Add a small padding to both ends of the segment + interpolator.reset(seg, radius * 0.25); + let numCircles = 0; + if (interpolator.length <= 0.5 * radius) { + numCircles = 1; + } + else { + numCircles = Math.ceil(interpolator.paddedLength / circleDist) + 1; + } + for (let i = 0; i < numCircles; i++) { + const t = i / Math.max(numCircles - 1, 1); + const circlePosition = interpolator.lerp(t); + // add viewport padding to the position and perform initial collision check + const centerX = circlePosition.x + viewportPadding; + const centerY = circlePosition.y + viewportPadding; + placedCollisionCircles.push(centerX, centerY, radius, 0); + const x1 = centerX - radius; + const y1 = centerY - radius; + const x2 = centerX + radius; + const y2 = centerY + radius; + entirelyOffscreen = entirelyOffscreen && this.isOffscreen(x1, y1, x2, y2); + inGrid = inGrid || this.isInsideGrid(x1, y1, x2, y2); + if (overlapMode !== 'always' && this.grid.hitTestCircle(centerX, centerY, radius, overlapMode, collisionGroupPredicate)) { + // Don't early exit if we're showing the debug circles because we still want to calculate + // which circles are in use + collisionDetected = true; + if (!showCollisionCircles) { + return { + circles: [], + offscreen: false, + collisionDetected + }; + } + } + } + } + } + return { + circles: ((!showCollisionCircles && collisionDetected) || !inGrid || perspectiveRatio < this.perspectiveRatioCutoff) ? [] : placedCollisionCircles, + offscreen: entirelyOffscreen, + collisionDetected + }; + } + projectPathToScreenSpace(projectedPath, projectionContext, labelToScreenMatrix) { + return projectedPath.map(p => project(p.x, p.y, labelToScreenMatrix, projectionContext.getElevation)); + } + /** + * Because the geometries in the CollisionIndex are an approximation of the shape of + * symbols on the map, we use the CollisionIndex to look up the symbol part of + * `queryRenderedFeatures`. + */ + queryRenderedSymbols(viewportQueryGeometry) { + if (viewportQueryGeometry.length === 0 || (this.grid.keysLength() === 0 && this.ignoredGrid.keysLength() === 0)) { + return {}; + } + const query = []; + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const point of viewportQueryGeometry) { + const gridPoint = new performance$1.Point(point.x + viewportPadding, point.y + viewportPadding); + minX = Math.min(minX, gridPoint.x); + minY = Math.min(minY, gridPoint.y); + maxX = Math.max(maxX, gridPoint.x); + maxY = Math.max(maxY, gridPoint.y); + query.push(gridPoint); + } + const features = this.grid.query(minX, minY, maxX, maxY) + .concat(this.ignoredGrid.query(minX, minY, maxX, maxY)); + const seenFeatures = {}; + const result = {}; + for (const feature of features) { + const featureKey = feature.key; + // Skip already seen features. + if (seenFeatures[featureKey.bucketInstanceId] === undefined) { + seenFeatures[featureKey.bucketInstanceId] = {}; + } + if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) { + continue; + } + // Check if query intersects with the feature box + // "Collision Circles" for line labels are treated as boxes here + // Since there's no actual collision taking place, the circle vs. square + // distinction doesn't matter as much, and box geometry is easier + // to work with. + const bbox = [ + new performance$1.Point(feature.x1, feature.y1), + new performance$1.Point(feature.x2, feature.y1), + new performance$1.Point(feature.x2, feature.y2), + new performance$1.Point(feature.x1, feature.y2) + ]; + if (!performance$1.polygonIntersectsPolygon(query, bbox)) { + continue; + } + seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true; + if (result[featureKey.bucketInstanceId] === undefined) { + result[featureKey.bucketInstanceId] = []; + } + result[featureKey.bucketInstanceId].push(featureKey.featureIndex); + } + return result; + } + insertCollisionBox(collisionBox, overlapMode, ignorePlacement, bucketInstanceId, featureIndex, collisionGroupID) { + const grid = ignorePlacement ? this.ignoredGrid : this.grid; + const key = { bucketInstanceId, featureIndex, collisionGroupID, overlapMode }; + grid.insert(key, collisionBox[0], collisionBox[1], collisionBox[2], collisionBox[3]); + } + insertCollisionCircles(collisionCircles, overlapMode, ignorePlacement, bucketInstanceId, featureIndex, collisionGroupID) { + const grid = ignorePlacement ? this.ignoredGrid : this.grid; + const key = { bucketInstanceId, featureIndex, collisionGroupID, overlapMode }; + for (let k = 0; k < collisionCircles.length; k += 4) { + grid.insertCircle(key, collisionCircles[k], collisionCircles[k + 1], collisionCircles[k + 2]); + } + } + projectAndGetPerspectiveRatio(posMatrix, x, y, _unwrappedTileID, getElevation) { + // The code here is duplicated from "projection.ts" for performance. + // Code here is subject to change once globe is merged. + let pos; + if (getElevation) { // slow because of handle z-index + pos = [x, y, getElevation(x, y), 1]; + performance$1.transformMat4(pos, pos, posMatrix); + } + else { // fast because of ignore z-index + pos = [x, y, 0, 1]; + xyTransformMat4(pos, pos, posMatrix); + } + const w = pos[3]; + return { + point: new performance$1.Point((((pos[0] / w + 1) / 2) * this.transform.width) + viewportPadding, (((-pos[1] / w + 1) / 2) * this.transform.height) + viewportPadding), + // See perspective ratio comment in symbol_sdf.vertex + // We're doing collision detection in viewport space so we need + // to scale down boxes in the distance + perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / w), + isOccluded: false, + signedDistanceFromCamera: w + }; + } + getPerspectiveRatio(posMatrix, x, y, unwrappedTileID, getElevation) { + // We don't care about the actual projected point, just its W component. + const projected = this.mapProjection.useSpecialProjectionForSymbols ? + this.mapProjection.projectTileCoordinates(x, y, unwrappedTileID, getElevation) : + project(x, y, posMatrix, getElevation); + return 0.5 + 0.5 * (this.transform.cameraToCenterDistance / projected.signedDistanceFromCamera); + } + isOffscreen(x1, y1, x2, y2) { + return x2 < viewportPadding || x1 >= this.screenRightBoundary || y2 < viewportPadding || y1 > this.screenBottomBoundary; + } + isInsideGrid(x1, y1, x2, y2) { + return x2 >= 0 && x1 < this.gridRightBoundary && y2 >= 0 && y1 < this.gridBottomBoundary; + } + /* + * Returns a matrix for transforming collision shapes to viewport coordinate space. + * Use this function to render e.g. collision circles on the screen. + * example transformation: clipPos = glCoordMatrix * viewportMatrix * circle_pos + */ + getViewportMatrix() { + const m = performance$1.identity([]); + performance$1.translate(m, m, [-viewportPadding, -viewportPadding, 0.0]); + return m; + } + /** + * Applies all layout+paint properties of the given box in order to find as good approximation of its screen-space bounding box as possible. + */ + _projectCollisionBox(collisionBox, tileToViewport, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translation, projectedPoint, getElevation, shift) { + // These vectors are valid both for screen space viewport-rotation-aligned texts and for pitch-align: map texts that are map-rotation-aligned. + let vecEast = new performance$1.Point(1, 0); + let vecSouth = new performance$1.Point(0, 1); + const translatedAnchor = new performance$1.Point(collisionBox.anchorPointX + translation[0], collisionBox.anchorPointY + translation[1]); + if (rotateWithMap && !pitchWithMap) { + // Handles screen space texts that are always aligned east-west. + const projectedEast = this.projectAndGetPerspectiveRatio(posMatrix, translatedAnchor.x + 1, translatedAnchor.y, unwrappedTileID, getElevation).point; + const toEast = projectedEast.sub(projectedPoint.point).unit(); + const angle = Math.atan(toEast.y / toEast.x) + (toEast.x < 0 ? Math.PI : 0); + const sin = Math.sin(angle); + const cos = Math.cos(angle); + vecEast = new performance$1.Point(cos, sin); + vecSouth = new performance$1.Point(-sin, cos); + } + else if (!rotateWithMap && pitchWithMap) { + // Handles pitch-align: map texts that are always aligned with the viewport's X axis. + const angle = -this.transform.angle; + const sin = Math.sin(angle); + const cos = Math.cos(angle); + vecEast = new performance$1.Point(cos, sin); + vecSouth = new performance$1.Point(-sin, cos); + } + // Configuration for screen space offsets + let basePoint = projectedPoint.point; + let distanceMultiplier = tileToViewport; + if (pitchWithMap) { + // Configuration for tile space (map-pitch-aligned) offsets + basePoint = translatedAnchor; + const zoomFraction = this.transform.zoom - Math.floor(this.transform.zoom); + distanceMultiplier = Math.pow(2, -zoomFraction); + distanceMultiplier *= this.mapProjection.getPitchedTextCorrection(this.transform, translatedAnchor, unwrappedTileID); + // This next correction can't be applied when variable anchors are in use. + if (!shift) { + // Shader applies a perspective size correction, we need to apply the same correction. + // For non-pitchWithMap texts, this is handled above by multiplying `textPixelRatio` with `projectedPoint.perspectiveRatio`, + // which is equivalent to the non-pitchWithMap branch of the GLSL code. + // Here, we compute and apply the pitchWithMap branch. + // See the computation of `perspective_ratio` in the symbol vertex shaders for the GLSL code. + const distanceRatio = projectedPoint.signedDistanceFromCamera / this.transform.cameraToCenterDistance; + const perspectiveRatio = performance$1.clamp(0.5 + 0.5 * distanceRatio, 0.0, 4.0); // Same clamp as what is used in the shader. + distanceMultiplier *= perspectiveRatio; + } + } + if (shift) { + // Variable anchors are in use + basePoint = basePoint.add(vecEast.mult(shift.x * distanceMultiplier)).add(vecSouth.mult(shift.y * distanceMultiplier)); + } + const offsetXmin = collisionBox.x1 * distanceMultiplier; + const offsetXmax = collisionBox.x2 * distanceMultiplier; + const offsetXhalf = (offsetXmin + offsetXmax) / 2; + const offsetYmin = collisionBox.y1 * distanceMultiplier; + const offsetYmax = collisionBox.y2 * distanceMultiplier; + const offsetYhalf = (offsetYmin + offsetYmax) / 2; + // 0--1--2 + // | | + // 7 3 + // | | + // 6--5--4 + const offsetsArray = [ + { offsetX: offsetXmin, offsetY: offsetYmin }, + { offsetX: offsetXhalf, offsetY: offsetYmin }, + { offsetX: offsetXmax, offsetY: offsetYmin }, + { offsetX: offsetXmax, offsetY: offsetYhalf }, + { offsetX: offsetXmax, offsetY: offsetYmax }, + { offsetX: offsetXhalf, offsetY: offsetYmax }, + { offsetX: offsetXmin, offsetY: offsetYmax }, + { offsetX: offsetXmin, offsetY: offsetYhalf } + ]; + let points = []; + for (const { offsetX, offsetY } of offsetsArray) { + points.push(new performance$1.Point(basePoint.x + vecEast.x * offsetX + vecSouth.x * offsetY, basePoint.y + vecEast.y * offsetX + vecSouth.y * offsetY)); + } + // Is any point of the collision shape visible on the globe (on beyond horizon)? + let anyPointVisible = false; + if (pitchWithMap) { + const projected = points.map(p => this.projectAndGetPerspectiveRatio(posMatrix, p.x, p.y, unwrappedTileID, getElevation)); + // Is at least one of the projected points NOT behind the horizon? + anyPointVisible = projected.some(p => !p.isOccluded); + points = projected.map(p => p.point); + } + else { + // Labels that are not pitchWithMap cannot ever hide behind the horizon. + anyPointVisible = true; + } + return { + box: performance$1.getAABB(points), + allPointsOccluded: !anyPointVisible + }; + } +} + +/** + * Converts a pixel value at a the given zoom level to tile units. + * + * The shaders mostly calculate everything in tile units so style + * properties need to be converted from pixels to tile units using this. + * + * For example, a translation by 30 pixels at zoom 6.5 will be a + * translation by pixelsToTileUnits(30, 6.5) tile units. + * + * @returns value in tile units + */ +function pixelsToTileUnits(tile, pixelValue, z) { + return pixelValue * (performance$1.EXTENT / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ))); +} + +class OpacityState { + constructor(prevState, increment, placed, skipFade) { + if (prevState) { + this.opacity = Math.max(0, Math.min(1, prevState.opacity + (prevState.placed ? increment : -increment))); + } + else { + this.opacity = (skipFade && placed) ? 1 : 0; + } + this.placed = placed; + } + isHidden() { + return this.opacity === 0 && !this.placed; + } +} +class JointOpacityState { + constructor(prevState, increment, placedText, placedIcon, skipFade) { + this.text = new OpacityState(prevState ? prevState.text : null, increment, placedText, skipFade); + this.icon = new OpacityState(prevState ? prevState.icon : null, increment, placedIcon, skipFade); + } + isHidden() { + return this.text.isHidden() && this.icon.isHidden(); + } +} +class JointPlacement { + constructor(text, icon, skipFade) { + this.text = text; + this.icon = icon; + this.skipFade = skipFade; + } +} +class CollisionCircleArray { + constructor() { + this.invProjMatrix = performance$1.create(); + this.viewportMatrix = performance$1.create(); + this.circles = []; + } +} +class RetainedQueryData { + constructor(bucketInstanceId, featureIndex, sourceLayerIndex, bucketIndex, tileID) { + this.bucketInstanceId = bucketInstanceId; + this.featureIndex = featureIndex; + this.sourceLayerIndex = sourceLayerIndex; + this.bucketIndex = bucketIndex; + this.tileID = tileID; + } +} +class CollisionGroups { + constructor(crossSourceCollisions) { + this.crossSourceCollisions = crossSourceCollisions; + this.maxGroupID = 0; + this.collisionGroups = {}; + } + get(sourceID) { + // The predicate/groupID mechanism allows for arbitrary grouping, + // but the current interface defines one source == one group when + // crossSourceCollisions == true. + if (!this.crossSourceCollisions) { + if (!this.collisionGroups[sourceID]) { + const nextGroupID = ++this.maxGroupID; + this.collisionGroups[sourceID] = { + ID: nextGroupID, + predicate: (key) => { + return key.collisionGroupID === nextGroupID; + } + }; + } + return this.collisionGroups[sourceID]; + } + else { + return { ID: 0, predicate: null }; + } + } +} +function calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale) { + const { horizontalAlign, verticalAlign } = performance$1.getAnchorAlignment(anchor); + const shiftX = -(horizontalAlign - 0.5) * width; + const shiftY = -(verticalAlign - 0.5) * height; + return new performance$1.Point(shiftX + textOffset[0] * textBoxScale, shiftY + textOffset[1] * textBoxScale); +} +class Placement { + constructor(transform, projection, terrain, fadeDuration, crossSourceCollisions, prevPlacement) { + this.transform = transform.clone(); + this.terrain = terrain; + this.collisionIndex = new CollisionIndex(this.transform, projection); + this.placements = {}; + this.opacities = {}; + this.variableOffsets = {}; + this.stale = false; + this.commitTime = 0; + this.fadeDuration = fadeDuration; + this.retainedQueryData = {}; + this.collisionGroups = new CollisionGroups(crossSourceCollisions); + this.collisionCircleArrays = {}; + this.collisionBoxArrays = new Map(); + this.prevPlacement = prevPlacement; + if (prevPlacement) { + prevPlacement.prevPlacement = undefined; // Only hold on to one placement back + } + this.placedOrientations = {}; + } + _getTerrainElevationFunc(tileID) { + const terrain = this.terrain; + return terrain ? (x, y) => terrain.getElevation(tileID, x, y) : null; + } + getBucketParts(results, styleLayer, tile, sortAcrossTiles) { + const symbolBucket = tile.getBucket(styleLayer); + const bucketFeatureIndex = tile.latestFeatureIndex; + if (!symbolBucket || !bucketFeatureIndex || styleLayer.id !== symbolBucket.layerIds[0]) + return; + const collisionBoxArray = tile.collisionBoxArray; + const layout = symbolBucket.layers[0].layout; + const paint = symbolBucket.layers[0].paint; + const scale = Math.pow(2, this.transform.zoom - tile.tileID.overscaledZ); + const textPixelRatio = tile.tileSize / performance$1.EXTENT; + const unwrappedTileID = tile.tileID.toUnwrapped(); + const posMatrix = this.transform.calculatePosMatrix(unwrappedTileID); + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pixelsToTiles = pixelsToTileUnits(tile, 1, this.transform.zoom); + const translationText = this.collisionIndex.mapProjection.translatePosition(this.transform, tile, paint.get('text-translate'), paint.get('text-translate-anchor')); + const translationIcon = this.collisionIndex.mapProjection.translatePosition(this.transform, tile, paint.get('icon-translate'), paint.get('icon-translate-anchor')); + const textLabelPlaneMatrix = getLabelPlaneMatrix(posMatrix, pitchWithMap, rotateWithMap, this.transform, pixelsToTiles); + let labelToScreenMatrix = null; + if (pitchWithMap) { + const glMatrix = getGlCoordMatrix(posMatrix, pitchWithMap, rotateWithMap, this.transform, pixelsToTiles); + labelToScreenMatrix = performance$1.multiply([], this.transform.labelPlaneMatrix, glMatrix); + } + // As long as this placement lives, we have to hold onto this bucket's + // matching FeatureIndex/data for querying purposes + this.retainedQueryData[symbolBucket.bucketInstanceId] = new RetainedQueryData(symbolBucket.bucketInstanceId, bucketFeatureIndex, symbolBucket.sourceLayerIndex, symbolBucket.index, tile.tileID); + const parameters = { + bucket: symbolBucket, + layout, + translationText, + translationIcon, + posMatrix, + unwrappedTileID, + textLabelPlaneMatrix, + labelToScreenMatrix, + scale, + textPixelRatio, + holdingForFade: tile.holdingForFade(), + collisionBoxArray, + partiallyEvaluatedTextSize: performance$1.evaluateSizeForZoom(symbolBucket.textSizeData, this.transform.zoom), + collisionGroup: this.collisionGroups.get(symbolBucket.sourceID) + }; + if (sortAcrossTiles) { + for (const range of symbolBucket.sortKeyRanges) { + const { sortKey, symbolInstanceStart, symbolInstanceEnd } = range; + results.push({ sortKey, symbolInstanceStart, symbolInstanceEnd, parameters }); + } + } + else { + results.push({ + symbolInstanceStart: 0, + symbolInstanceEnd: symbolBucket.symbolInstances.length, + parameters + }); + } + } + attemptAnchorPlacement(textAnchorOffset, textBox, width, height, textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix, unwrappedTileID, collisionGroup, textOverlapMode, symbolInstance, bucket, orientation, translationText, translationIcon, iconBox, getElevation) { + const anchor = performance$1.TextAnchorEnum[textAnchorOffset.textAnchor]; + const textOffset = [textAnchorOffset.textOffset0, textAnchorOffset.textOffset1]; + const shift = calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale); + const placedGlyphBoxes = this.collisionIndex.placeCollisionBox(textBox, textOverlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation, shift); + if (iconBox) { + const placedIconBoxes = this.collisionIndex.placeCollisionBox(iconBox, textOverlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationIcon, collisionGroup.predicate, getElevation, shift); + if (!placedIconBoxes.placeable) + return; + } + if (placedGlyphBoxes.placeable) { + let prevAnchor; + // If this label was placed in the previous placement, record the anchor position + // to allow us to animate the transition + if (this.prevPlacement && + this.prevPlacement.variableOffsets[symbolInstance.crossTileID] && + this.prevPlacement.placements[symbolInstance.crossTileID] && + this.prevPlacement.placements[symbolInstance.crossTileID].text) { + prevAnchor = this.prevPlacement.variableOffsets[symbolInstance.crossTileID].anchor; + } + if (symbolInstance.crossTileID === 0) + throw new Error('symbolInstance.crossTileID can\'t be 0'); + this.variableOffsets[symbolInstance.crossTileID] = { + textOffset, + width, + height, + anchor, + textBoxScale, + prevAnchor + }; + this.markUsedJustification(bucket, anchor, symbolInstance, orientation); + if (bucket.allowVerticalPlacement) { + this.markUsedOrientation(bucket, orientation, symbolInstance); + this.placedOrientations[symbolInstance.crossTileID] = orientation; + } + return { shift, placedGlyphBoxes }; + } + } + placeLayerBucketPart(bucketPart, seenCrossTileIDs, showCollisionBoxes) { + const { bucket, layout, translationText, translationIcon, posMatrix, unwrappedTileID, textLabelPlaneMatrix, labelToScreenMatrix, textPixelRatio, holdingForFade, collisionBoxArray, partiallyEvaluatedTextSize, collisionGroup } = bucketPart.parameters; + const textOptional = layout.get('text-optional'); + const iconOptional = layout.get('icon-optional'); + const textOverlapMode = performance$1.getOverlapMode(layout, 'text-overlap', 'text-allow-overlap'); + const textAlwaysOverlap = textOverlapMode === 'always'; + const iconOverlapMode = performance$1.getOverlapMode(layout, 'icon-overlap', 'icon-allow-overlap'); + const iconAlwaysOverlap = iconOverlapMode === 'always'; + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const hasIconTextFit = layout.get('icon-text-fit') !== 'none'; + const zOrderByViewportY = layout.get('symbol-z-order') === 'viewport-y'; + // This logic is similar to the "defaultOpacityState" logic below in updateBucketOpacities + // If we know a symbol is always supposed to show, force it to be marked visible even if + // it wasn't placed into the collision index (because some or all of it was outside the range + // of the collision grid). + // There is a subtle edge case here we're accepting: + // Symbol A has text-allow-overlap: true, icon-allow-overlap: true, icon-optional: false + // A's icon is outside the grid, so doesn't get placed + // A's text would be inside grid, but doesn't get placed because of icon-optional: false + // We still show A because of the allow-overlap settings. + // Symbol B has allow-overlap: false, and gets placed where A's text would be + // On panning in, there is a short period when Symbol B and Symbol A will overlap + // This is the reverse of our normal policy of "fade in on pan", but should look like any other + // collision and hopefully not be too noticeable. + // See https://github.com/mapbox/mapbox-gl-js/issues/7172 + const alwaysShowText = textAlwaysOverlap && (iconAlwaysOverlap || !bucket.hasIconData() || iconOptional); + const alwaysShowIcon = iconAlwaysOverlap && (textAlwaysOverlap || !bucket.hasTextData() || textOptional); + if (!bucket.collisionArrays && collisionBoxArray) { + bucket.deserializeCollisionBoxes(collisionBoxArray); + } + const tileID = this.retainedQueryData[bucket.bucketInstanceId].tileID; + const getElevation = this._getTerrainElevationFunc(tileID); + const placeSymbol = (symbolInstance, collisionArrays, symbolIndex) => { + var _a, _b; + if (seenCrossTileIDs[symbolInstance.crossTileID]) + return; + if (holdingForFade) { + // Mark all symbols from this tile as "not placed", but don't add to seenCrossTileIDs, because we don't + // know yet if we have a duplicate in a parent tile that _should_ be placed. + this.placements[symbolInstance.crossTileID] = new JointPlacement(false, false, false); + return; + } + let placeText = false; + let placeIcon = false; + let offscreen = true; + let shift = null; + let placed = { box: null, placeable: false, offscreen: null }; + let placedVerticalText = { box: null, placeable: false, offscreen: null }; + let placedGlyphBoxes = null; + let placedGlyphCircles = null; + let placedIconBoxes = null; + let textFeatureIndex = 0; + let verticalTextFeatureIndex = 0; + let iconFeatureIndex = 0; + if (collisionArrays.textFeatureIndex) { + textFeatureIndex = collisionArrays.textFeatureIndex; + } + else if (symbolInstance.useRuntimeCollisionCircles) { + textFeatureIndex = symbolInstance.featureIndex; + } + if (collisionArrays.verticalTextFeatureIndex) { + verticalTextFeatureIndex = collisionArrays.verticalTextFeatureIndex; + } + const textBox = collisionArrays.textBox; + if (textBox) { + const updatePreviousOrientationIfNotPlaced = (isPlaced) => { + let previousOrientation = performance$1.WritingMode.horizontal; + if (bucket.allowVerticalPlacement && !isPlaced && this.prevPlacement) { + const prevPlacedOrientation = this.prevPlacement.placedOrientations[symbolInstance.crossTileID]; + if (prevPlacedOrientation) { + this.placedOrientations[symbolInstance.crossTileID] = prevPlacedOrientation; + previousOrientation = prevPlacedOrientation; + this.markUsedOrientation(bucket, previousOrientation, symbolInstance); + } + } + return previousOrientation; + }; + const placeTextForPlacementModes = (placeHorizontalFn, placeVerticalFn) => { + if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && collisionArrays.verticalTextBox) { + for (const placementMode of bucket.writingModes) { + if (placementMode === performance$1.WritingMode.vertical) { + placed = placeVerticalFn(); + placedVerticalText = placed; + } + else { + placed = placeHorizontalFn(); + } + if (placed && placed.placeable) + break; + } + } + else { + placed = placeHorizontalFn(); + } + }; + const textAnchorOffsetStart = symbolInstance.textAnchorOffsetStartIndex; + const textAnchorOffsetEnd = symbolInstance.textAnchorOffsetEndIndex; + // If start+end indices match, text-variable-anchor is not in play. + if (textAnchorOffsetEnd === textAnchorOffsetStart) { + const placeBox = (collisionTextBox, orientation) => { + const placedFeature = this.collisionIndex.placeCollisionBox(collisionTextBox, textOverlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation); + if (placedFeature && placedFeature.placeable) { + this.markUsedOrientation(bucket, orientation, symbolInstance); + this.placedOrientations[symbolInstance.crossTileID] = orientation; + } + return placedFeature; + }; + const placeHorizontal = () => { + return placeBox(textBox, performance$1.WritingMode.horizontal); + }; + const placeVertical = () => { + const verticalTextBox = collisionArrays.verticalTextBox; + if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) { + return placeBox(verticalTextBox, performance$1.WritingMode.vertical); + } + return { box: null, offscreen: null }; + }; + placeTextForPlacementModes(placeHorizontal, placeVertical); + updatePreviousOrientationIfNotPlaced(placed && placed.placeable); + } + else { + // If this symbol was in the last placement, prefer placement using same anchor, if it's still available + let prevAnchor = performance$1.TextAnchorEnum[(_b = (_a = this.prevPlacement) === null || _a === void 0 ? void 0 : _a.variableOffsets[symbolInstance.crossTileID]) === null || _b === void 0 ? void 0 : _b.anchor]; + const placeBoxForVariableAnchors = (collisionTextBox, collisionIconBox, orientation) => { + const width = collisionTextBox.x2 - collisionTextBox.x1; + const height = collisionTextBox.y2 - collisionTextBox.y1; + const textBoxScale = symbolInstance.textBoxScale; + const variableIconBox = hasIconTextFit && (iconOverlapMode === 'never') ? collisionIconBox : null; + let placedBox = null; + let placementPasses = (textOverlapMode === 'never') ? 1 : 2; + let overlapMode = 'never'; + if (prevAnchor) { + placementPasses++; + } + for (let pass = 0; pass < placementPasses; pass++) { + for (let i = textAnchorOffsetStart; i < textAnchorOffsetEnd; i++) { + const textAnchorOffset = bucket.textAnchorOffsets.get(i); + if (prevAnchor && textAnchorOffset.textAnchor !== prevAnchor) { + continue; + } + const result = this.attemptAnchorPlacement(textAnchorOffset, collisionTextBox, width, height, textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix, unwrappedTileID, collisionGroup, overlapMode, symbolInstance, bucket, orientation, translationText, translationIcon, variableIconBox, getElevation); + if (result) { + placedBox = result.placedGlyphBoxes; + if (placedBox && placedBox.placeable) { + placeText = true; + shift = result.shift; + return placedBox; + } + } + } + if (prevAnchor) { + prevAnchor = null; + } + else { + overlapMode = textOverlapMode; + } + } + if (showCollisionBoxes && !placedBox) { + // No box was successfully placed + // Generate bounds for a fake centered box, so that we can at least display something for collision debug. + const placedFakeGlyphBox = this.collisionIndex.placeCollisionBox(textBox, 'always', // Skips expensive collision check with already placed boxes + textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation, new performance$1.Point(0, 0)); + placedBox = { + box: placedFakeGlyphBox.box, + offscreen: false, + placeable: false + }; + } + return placedBox; + }; + const placeHorizontal = () => { + return placeBoxForVariableAnchors(textBox, collisionArrays.iconBox, performance$1.WritingMode.horizontal); + }; + const placeVertical = () => { + const verticalTextBox = collisionArrays.verticalTextBox; + const wasPlaced = placed && placed.placeable; + if (bucket.allowVerticalPlacement && !wasPlaced && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) { + return placeBoxForVariableAnchors(verticalTextBox, collisionArrays.verticalIconBox, performance$1.WritingMode.vertical); + } + return { box: null, occluded: true, offscreen: null }; + }; + placeTextForPlacementModes(placeHorizontal, placeVertical); + if (placed) { + placeText = placed.placeable; + offscreen = placed.offscreen; + } + const prevOrientation = updatePreviousOrientationIfNotPlaced(placed && placed.placeable); + // If we didn't get placed, we still need to copy our position from the last placement for + // fade animations + if (!placeText && this.prevPlacement) { + const prevOffset = this.prevPlacement.variableOffsets[symbolInstance.crossTileID]; + if (prevOffset) { + this.variableOffsets[symbolInstance.crossTileID] = prevOffset; + this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, prevOrientation); + } + } + } + } + placedGlyphBoxes = placed; + placeText = placedGlyphBoxes && placedGlyphBoxes.placeable; + offscreen = placedGlyphBoxes && placedGlyphBoxes.offscreen; + if (symbolInstance.useRuntimeCollisionCircles) { + const placedSymbol = bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex); + const fontSize = performance$1.evaluateSizeForFeature(bucket.textSizeData, partiallyEvaluatedTextSize, placedSymbol); + const textPixelPadding = layout.get('text-padding'); + const circlePixelDiameter = symbolInstance.collisionCircleDiameter; + placedGlyphCircles = this.collisionIndex.placeCollisionCircles(textOverlapMode, placedSymbol, bucket.lineVertexArray, bucket.glyphOffsetArray, fontSize, posMatrix, unwrappedTileID, textLabelPlaneMatrix, labelToScreenMatrix, showCollisionBoxes, pitchWithMap, collisionGroup.predicate, circlePixelDiameter, textPixelPadding, translationText, getElevation); + if (placedGlyphCircles.circles.length && placedGlyphCircles.collisionDetected && !showCollisionBoxes) { + performance$1.warnOnce('Collisions detected, but collision boxes are not shown'); + } + // If text-overlap is set to 'always', force "placedCircles" to true + // In theory there should always be at least one circle placed + // in this case, but for now quirks in text-anchor + // and text-offset may prevent that from being true. + placeText = textAlwaysOverlap || (placedGlyphCircles.circles.length > 0 && !placedGlyphCircles.collisionDetected); + offscreen = offscreen && placedGlyphCircles.offscreen; + } + if (collisionArrays.iconFeatureIndex) { + iconFeatureIndex = collisionArrays.iconFeatureIndex; + } + if (collisionArrays.iconBox) { + const placeIconFeature = iconBox => { + return this.collisionIndex.placeCollisionBox(iconBox, iconOverlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationIcon, collisionGroup.predicate, getElevation, (hasIconTextFit && shift) ? shift : undefined); + }; + if (placedVerticalText && placedVerticalText.placeable && collisionArrays.verticalIconBox) { + placedIconBoxes = placeIconFeature(collisionArrays.verticalIconBox); + placeIcon = placedIconBoxes.placeable; + } + else { + placedIconBoxes = placeIconFeature(collisionArrays.iconBox); + placeIcon = placedIconBoxes.placeable; + } + offscreen = offscreen && placedIconBoxes.offscreen; + } + const iconWithoutText = textOptional || + (symbolInstance.numHorizontalGlyphVertices === 0 && symbolInstance.numVerticalGlyphVertices === 0); + const textWithoutIcon = iconOptional || symbolInstance.numIconVertices === 0; + // Combine the scales for icons and text. + if (!iconWithoutText && !textWithoutIcon) { + placeIcon = placeText = placeIcon && placeText; + } + else if (!textWithoutIcon) { + placeText = placeIcon && placeText; + } + else if (!iconWithoutText) { + placeIcon = placeIcon && placeText; + } + const hasTextBox = placeText && placedGlyphBoxes.placeable; + const hasIconBox = placeIcon && placedIconBoxes.placeable; + if (hasTextBox) { + if (placedVerticalText && placedVerticalText.placeable && verticalTextFeatureIndex) { + this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, textOverlapMode, layout.get('text-ignore-placement'), bucket.bucketInstanceId, verticalTextFeatureIndex, collisionGroup.ID); + } + else { + this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, textOverlapMode, layout.get('text-ignore-placement'), bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID); + } + } + if (hasIconBox) { + this.collisionIndex.insertCollisionBox(placedIconBoxes.box, iconOverlapMode, layout.get('icon-ignore-placement'), bucket.bucketInstanceId, iconFeatureIndex, collisionGroup.ID); + } + if (placedGlyphCircles) { + if (placeText) { + this.collisionIndex.insertCollisionCircles(placedGlyphCircles.circles, textOverlapMode, layout.get('text-ignore-placement'), bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID); + } + } + if (showCollisionBoxes) { + this.storeCollisionData(bucket.bucketInstanceId, symbolIndex, collisionArrays, placedGlyphBoxes, placedIconBoxes, placedGlyphCircles); + } + if (symbolInstance.crossTileID === 0) + throw new Error('symbolInstance.crossTileID can\'t be 0'); + if (bucket.bucketInstanceId === 0) + throw new Error('bucket.bucketInstanceId can\'t be 0'); + this.placements[symbolInstance.crossTileID] = new JointPlacement(placeText || alwaysShowText, placeIcon || alwaysShowIcon, offscreen || bucket.justReloaded); + seenCrossTileIDs[symbolInstance.crossTileID] = true; + }; + if (zOrderByViewportY) { + if (bucketPart.symbolInstanceStart !== 0) + throw new Error('bucket.bucketInstanceId should be 0'); + const symbolIndexes = bucket.getSortedSymbolIndexes(this.transform.angle); + for (let i = symbolIndexes.length - 1; i >= 0; --i) { + const symbolIndex = symbolIndexes[i]; + placeSymbol(bucket.symbolInstances.get(symbolIndex), bucket.collisionArrays[symbolIndex], symbolIndex); + } + } + else { + for (let i = bucketPart.symbolInstanceStart; i < bucketPart.symbolInstanceEnd; i++) { + placeSymbol(bucket.symbolInstances.get(i), bucket.collisionArrays[i], i); + } + } + if (showCollisionBoxes && bucket.bucketInstanceId in this.collisionCircleArrays) { + const circleArray = this.collisionCircleArrays[bucket.bucketInstanceId]; + // Store viewport and inverse projection matrices per bucket + performance$1.invert(circleArray.invProjMatrix, posMatrix); + circleArray.viewportMatrix = this.collisionIndex.getViewportMatrix(); + } + bucket.justReloaded = false; + } + storeCollisionData(bucketInstanceId, symbolIndex, collisionArrays, placedGlyphBoxes, placedIconBoxes, placedGlyphCircles) { + if (collisionArrays.textBox || collisionArrays.iconBox) { + // Store the actually used collision box for debug draw + let boxArray; + if (this.collisionBoxArrays.has(bucketInstanceId)) { + boxArray = this.collisionBoxArrays.get(bucketInstanceId); + } + else { + boxArray = new Map(); + this.collisionBoxArrays.set(bucketInstanceId, boxArray); + } + let realCollisionBox; + if (boxArray.has(symbolIndex)) { + realCollisionBox = boxArray.get(symbolIndex); + } + else { + realCollisionBox = { + text: null, + icon: null + }; + boxArray.set(symbolIndex, realCollisionBox); + } + if (collisionArrays.textBox) { + realCollisionBox.text = placedGlyphBoxes.box; + } + if (collisionArrays.iconBox) { + realCollisionBox.icon = placedIconBoxes.box; + } + } + if (placedGlyphCircles) { + let circleArray = this.collisionCircleArrays[bucketInstanceId]; + // Group collision circles together by bucket. Circles can't be pushed forward for rendering yet as the symbol placement + // for a bucket is not guaranteed to be complete before the commit-function has been called + if (circleArray === undefined) + circleArray = this.collisionCircleArrays[bucketInstanceId] = new CollisionCircleArray(); + for (let i = 0; i < placedGlyphCircles.circles.length; i += 4) { + circleArray.circles.push(placedGlyphCircles.circles[i + 0]); // x + circleArray.circles.push(placedGlyphCircles.circles[i + 1]); // y + circleArray.circles.push(placedGlyphCircles.circles[i + 2]); // radius + circleArray.circles.push(placedGlyphCircles.collisionDetected ? 1 : 0); // collisionDetected-flag + } + } + } + markUsedJustification(bucket, placedAnchor, symbolInstance, orientation) { + const justifications = { + 'left': symbolInstance.leftJustifiedTextSymbolIndex, + 'center': symbolInstance.centerJustifiedTextSymbolIndex, + 'right': symbolInstance.rightJustifiedTextSymbolIndex + }; + let autoIndex; + if (orientation === performance$1.WritingMode.vertical) { + autoIndex = symbolInstance.verticalPlacedTextSymbolIndex; + } + else { + autoIndex = justifications[performance$1.getAnchorJustification(placedAnchor)]; + } + const indexes = [ + symbolInstance.leftJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.verticalPlacedTextSymbolIndex + ]; + for (const index of indexes) { + if (index >= 0) { + if (autoIndex >= 0 && index !== autoIndex) { + // There are multiple justifications and this one isn't it: shift offscreen + bucket.text.placedSymbolArray.get(index).crossTileID = 0; + } + else { + // Either this is the chosen justification or the justification is hardwired: use this one + bucket.text.placedSymbolArray.get(index).crossTileID = symbolInstance.crossTileID; + } + } + } + } + markUsedOrientation(bucket, orientation, symbolInstance) { + const horizontal = (orientation === performance$1.WritingMode.horizontal || orientation === performance$1.WritingMode.horizontalOnly) ? orientation : 0; + const vertical = orientation === performance$1.WritingMode.vertical ? orientation : 0; + const horizontalIndexes = [ + symbolInstance.leftJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.rightJustifiedTextSymbolIndex + ]; + for (const index of horizontalIndexes) { + bucket.text.placedSymbolArray.get(index).placedOrientation = horizontal; + } + if (symbolInstance.verticalPlacedTextSymbolIndex) { + bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).placedOrientation = vertical; + } + } + commit(now) { + this.commitTime = now; + this.zoomAtLastRecencyCheck = this.transform.zoom; + const prevPlacement = this.prevPlacement; + let placementChanged = false; + this.prevZoomAdjustment = prevPlacement ? prevPlacement.zoomAdjustment(this.transform.zoom) : 0; + const increment = prevPlacement ? prevPlacement.symbolFadeChange(now) : 1; + const prevOpacities = prevPlacement ? prevPlacement.opacities : {}; + const prevOffsets = prevPlacement ? prevPlacement.variableOffsets : {}; + const prevOrientations = prevPlacement ? prevPlacement.placedOrientations : {}; + // add the opacities from the current placement, and copy their current values from the previous placement + for (const crossTileID in this.placements) { + const jointPlacement = this.placements[crossTileID]; + const prevOpacity = prevOpacities[crossTileID]; + if (prevOpacity) { + this.opacities[crossTileID] = new JointOpacityState(prevOpacity, increment, jointPlacement.text, jointPlacement.icon); + placementChanged = placementChanged || + jointPlacement.text !== prevOpacity.text.placed || + jointPlacement.icon !== prevOpacity.icon.placed; + } + else { + this.opacities[crossTileID] = new JointOpacityState(null, increment, jointPlacement.text, jointPlacement.icon, jointPlacement.skipFade); + placementChanged = placementChanged || jointPlacement.text || jointPlacement.icon; + } + } + // copy and update values from the previous placement that aren't in the current placement but haven't finished fading + for (const crossTileID in prevOpacities) { + const prevOpacity = prevOpacities[crossTileID]; + if (!this.opacities[crossTileID]) { + const jointOpacity = new JointOpacityState(prevOpacity, increment, false, false); + if (!jointOpacity.isHidden()) { + this.opacities[crossTileID] = jointOpacity; + placementChanged = placementChanged || prevOpacity.text.placed || prevOpacity.icon.placed; + } + } + } + for (const crossTileID in prevOffsets) { + if (!this.variableOffsets[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) { + this.variableOffsets[crossTileID] = prevOffsets[crossTileID]; + } + } + for (const crossTileID in prevOrientations) { + if (!this.placedOrientations[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) { + this.placedOrientations[crossTileID] = prevOrientations[crossTileID]; + } + } + // this.lastPlacementChangeTime is the time of the last commit() that + // resulted in a placement change -- in other words, the start time of + // the last symbol fade animation + if (prevPlacement && prevPlacement.lastPlacementChangeTime === undefined) { + throw new Error('Last placement time for previous placement is not defined'); + } + if (placementChanged) { + this.lastPlacementChangeTime = now; + } + else if (typeof this.lastPlacementChangeTime !== 'number') { + this.lastPlacementChangeTime = prevPlacement ? prevPlacement.lastPlacementChangeTime : now; + } + } + updateLayerOpacities(styleLayer, tiles) { + const seenCrossTileIDs = {}; + for (const tile of tiles) { + const symbolBucket = tile.getBucket(styleLayer); + if (symbolBucket && tile.latestFeatureIndex && styleLayer.id === symbolBucket.layerIds[0]) { + this.updateBucketOpacities(symbolBucket, tile.tileID, seenCrossTileIDs, tile.collisionBoxArray); + } + } + } + updateBucketOpacities(bucket, tileID, seenCrossTileIDs, collisionBoxArray) { + if (bucket.hasTextData()) { + bucket.text.opacityVertexArray.clear(); + bucket.text.hasVisibleVertices = false; + } + if (bucket.hasIconData()) { + bucket.icon.opacityVertexArray.clear(); + bucket.icon.hasVisibleVertices = false; + } + if (bucket.hasIconCollisionBoxData()) + bucket.iconCollisionBox.collisionVertexArray.clear(); + if (bucket.hasTextCollisionBoxData()) + bucket.textCollisionBox.collisionVertexArray.clear(); + const layer = bucket.layers[0]; + const layout = layer.layout; + const duplicateOpacityState = new JointOpacityState(null, 0, false, false, true); + const textAllowOverlap = layout.get('text-allow-overlap'); + const iconAllowOverlap = layout.get('icon-allow-overlap'); + const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset'); + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const hasIconTextFit = layout.get('icon-text-fit') !== 'none'; + // If allow-overlap is true, we can show symbols before placement runs on them + // But we have to wait for placement if we potentially depend on a paired icon/text + // with allow-overlap: false. + // See https://github.com/mapbox/mapbox-gl-js/issues/7032 + const defaultOpacityState = new JointOpacityState(null, 0, textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || layout.get('icon-optional')), iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || layout.get('text-optional')), true); + if (!bucket.collisionArrays && collisionBoxArray && ((bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()))) { + bucket.deserializeCollisionBoxes(collisionBoxArray); + } + const addOpacities = (iconOrText, numVertices, opacity) => { + for (let i = 0; i < numVertices / 4; i++) { + iconOrText.opacityVertexArray.emplaceBack(opacity); + } + iconOrText.hasVisibleVertices = iconOrText.hasVisibleVertices || (opacity !== PACKED_HIDDEN_OPACITY); + }; + const boxArrays = this.collisionBoxArrays.get(bucket.bucketInstanceId); + for (let s = 0; s < bucket.symbolInstances.length; s++) { + const symbolInstance = bucket.symbolInstances.get(s); + const { numHorizontalGlyphVertices, numVerticalGlyphVertices, crossTileID } = symbolInstance; + const isDuplicate = seenCrossTileIDs[crossTileID]; + let opacityState = this.opacities[crossTileID]; + if (isDuplicate) { + opacityState = duplicateOpacityState; + } + else if (!opacityState) { + opacityState = defaultOpacityState; + // store the state so that future placements use it as a starting point + this.opacities[crossTileID] = opacityState; + } + seenCrossTileIDs[crossTileID] = true; + const hasText = numHorizontalGlyphVertices > 0 || numVerticalGlyphVertices > 0; + const hasIcon = symbolInstance.numIconVertices > 0; + const placedOrientation = this.placedOrientations[symbolInstance.crossTileID]; + const horizontalHidden = placedOrientation === performance$1.WritingMode.vertical; + const verticalHidden = placedOrientation === performance$1.WritingMode.horizontal || placedOrientation === performance$1.WritingMode.horizontalOnly; + if (hasText) { + const packedOpacity = packOpacity(opacityState.text); + // Vertical text fades in/out on collision the same way as corresponding + // horizontal text. Switch between vertical/horizontal should be instantaneous + const horizontalOpacity = horizontalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity; + addOpacities(bucket.text, numHorizontalGlyphVertices, horizontalOpacity); + const verticalOpacity = verticalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity; + addOpacities(bucket.text, numVerticalGlyphVertices, verticalOpacity); + // If this label is completely faded, mark it so that we don't have to calculate + // its position at render time. If this layer has variable placement, shift the various + // symbol instances appropriately so that symbols from buckets that have yet to be placed + // offset appropriately. + const symbolHidden = opacityState.text.isHidden(); + [ + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.leftJustifiedTextSymbolIndex + ].forEach(index => { + if (index >= 0) { + bucket.text.placedSymbolArray.get(index).hidden = symbolHidden || horizontalHidden ? 1 : 0; + } + }); + if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) { + bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).hidden = symbolHidden || verticalHidden ? 1 : 0; + } + const prevOffset = this.variableOffsets[symbolInstance.crossTileID]; + if (prevOffset) { + this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, placedOrientation); + } + const prevOrientation = this.placedOrientations[symbolInstance.crossTileID]; + if (prevOrientation) { + this.markUsedJustification(bucket, 'left', symbolInstance, prevOrientation); + this.markUsedOrientation(bucket, prevOrientation, symbolInstance); + } + } + if (hasIcon) { + const packedOpacity = packOpacity(opacityState.icon); + const useHorizontal = !(hasIconTextFit && symbolInstance.verticalPlacedIconSymbolIndex && horizontalHidden); + if (symbolInstance.placedIconSymbolIndex >= 0) { + const horizontalOpacity = useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY; + addOpacities(bucket.icon, symbolInstance.numIconVertices, horizontalOpacity); + bucket.icon.placedSymbolArray.get(symbolInstance.placedIconSymbolIndex).hidden = + opacityState.icon.isHidden(); + } + if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) { + const verticalOpacity = !useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY; + addOpacities(bucket.icon, symbolInstance.numVerticalIconVertices, verticalOpacity); + bucket.icon.placedSymbolArray.get(symbolInstance.verticalPlacedIconSymbolIndex).hidden = + opacityState.icon.isHidden(); + } + } + const realBoxes = (boxArrays && boxArrays.has(s)) ? boxArrays.get(s) : { + text: null, + icon: null + }; + if (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()) { + const collisionArrays = bucket.collisionArrays[s]; + if (collisionArrays) { + let shift = new performance$1.Point(0, 0); + if (collisionArrays.textBox || collisionArrays.verticalTextBox) { + let used = true; + if (hasVariablePlacement) { + const variableOffset = this.variableOffsets[crossTileID]; + if (variableOffset) { + // This will show either the currently placed position or the last + // successfully placed position (so you can visualize what collision + // just made the symbol disappear, and the most likely place for the + // symbol to come back) + shift = calculateVariableLayoutShift(variableOffset.anchor, variableOffset.width, variableOffset.height, variableOffset.textOffset, variableOffset.textBoxScale); + if (rotateWithMap) { + shift._rotate(pitchWithMap ? this.transform.angle : -this.transform.angle); + } + } + else { + // No offset -> this symbol hasn't been placed since coming on-screen + // No single box is particularly meaningful and all of them would be too noisy + // Use the center box just to show something's there, but mark it "not used" + used = false; + } + } + if (collisionArrays.textBox || collisionArrays.verticalTextBox) { + let hidden; + if (collisionArrays.textBox) { + hidden = horizontalHidden; + } + if (collisionArrays.verticalTextBox) { + hidden = verticalHidden; + } + updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || hidden, realBoxes.text, shift.x, shift.y); + } + } + if (collisionArrays.iconBox || collisionArrays.verticalIconBox) { + const verticalIconUsed = Boolean(!verticalHidden && collisionArrays.verticalIconBox); + let hidden; + if (collisionArrays.iconBox) { + hidden = verticalIconUsed; + } + if (collisionArrays.verticalIconBox) { + hidden = !verticalIconUsed; + } + updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, hidden, realBoxes.icon, hasIconTextFit ? shift.x : 0, hasIconTextFit ? shift.y : 0); + } + } + } + } + bucket.sortFeatures(this.transform.angle); + if (this.retainedQueryData[bucket.bucketInstanceId]) { + this.retainedQueryData[bucket.bucketInstanceId].featureSortOrder = bucket.featureSortOrder; + } + if (bucket.hasTextData() && bucket.text.opacityVertexBuffer) { + bucket.text.opacityVertexBuffer.updateData(bucket.text.opacityVertexArray); + } + if (bucket.hasIconData() && bucket.icon.opacityVertexBuffer) { + bucket.icon.opacityVertexBuffer.updateData(bucket.icon.opacityVertexArray); + } + if (bucket.hasIconCollisionBoxData() && bucket.iconCollisionBox.collisionVertexBuffer) { + bucket.iconCollisionBox.collisionVertexBuffer.updateData(bucket.iconCollisionBox.collisionVertexArray); + } + if (bucket.hasTextCollisionBoxData() && bucket.textCollisionBox.collisionVertexBuffer) { + bucket.textCollisionBox.collisionVertexBuffer.updateData(bucket.textCollisionBox.collisionVertexArray); + } + if (bucket.text.opacityVertexArray.length !== bucket.text.layoutVertexArray.length / 4) + throw new Error(`bucket.text.opacityVertexArray.length (= ${bucket.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${bucket.text.layoutVertexArray.length}) / 4`); + if (bucket.icon.opacityVertexArray.length !== bucket.icon.layoutVertexArray.length / 4) + throw new Error(`bucket.icon.opacityVertexArray.length (= ${bucket.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${bucket.icon.layoutVertexArray.length}) / 4`); + // Push generated collision circles to the bucket for debug rendering + if (bucket.bucketInstanceId in this.collisionCircleArrays) { + const instance = this.collisionCircleArrays[bucket.bucketInstanceId]; + bucket.placementInvProjMatrix = instance.invProjMatrix; + bucket.placementViewportMatrix = instance.viewportMatrix; + bucket.collisionCircleArray = instance.circles; + delete this.collisionCircleArrays[bucket.bucketInstanceId]; + } + } + symbolFadeChange(now) { + return this.fadeDuration === 0 ? + 1 : + ((now - this.commitTime) / this.fadeDuration + this.prevZoomAdjustment); + } + zoomAdjustment(zoom) { + // When zooming out quickly, labels can overlap each other. This + // adjustment is used to reduce the interval between placement calculations + // and to reduce the fade duration when zooming out quickly. Discovering the + // collisions more quickly and fading them more quickly reduces the unwanted effect. + return Math.max(0, (this.transform.zoom - zoom) / 1.5); + } + hasTransitions(now) { + return this.stale || + now - this.lastPlacementChangeTime < this.fadeDuration; + } + stillRecent(now, zoom) { + // The adjustment makes placement more frequent when zooming. + // This condition applies the adjustment only after the map has + // stopped zooming. This avoids adding extra jank while zooming. + const durationAdjustment = this.zoomAtLastRecencyCheck === zoom ? + (1 - this.zoomAdjustment(zoom)) : + 1; + this.zoomAtLastRecencyCheck = zoom; + return this.commitTime + this.fadeDuration * durationAdjustment > now; + } + setStale() { + this.stale = true; + } +} +function updateCollisionVertices(collisionVertexArray, placed, notUsed, realBox, shiftX, shiftY) { + if (!realBox || realBox.length === 0) { + realBox = [0, 0, 0, 0]; + } + const tlX = realBox[0] - viewportPadding; + const tlY = realBox[1] - viewportPadding; + const brX = realBox[2] - viewportPadding; + const brY = realBox[3] - viewportPadding; + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, tlX, tlY); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, brX, tlY); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, brX, brY); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, tlX, brY); +} +// All four vertices for a glyph will have the same opacity state +// So we pack the opacity into a uint8, and then repeat it four times +// to make a single uint32 that we can upload for each glyph in the +// label. +const shift25 = Math.pow(2, 25); +const shift24 = Math.pow(2, 24); +const shift17 = Math.pow(2, 17); +const shift16 = Math.pow(2, 16); +const shift9 = Math.pow(2, 9); +const shift8 = Math.pow(2, 8); +const shift1 = Math.pow(2, 1); +function packOpacity(opacityState) { + if (opacityState.opacity === 0 && !opacityState.placed) { + return 0; + } + else if (opacityState.opacity === 1 && opacityState.placed) { + return 4294967295; + } + const targetBit = opacityState.placed ? 1 : 0; + const opacityBits = Math.floor(opacityState.opacity * 127); + return opacityBits * shift25 + targetBit * shift24 + + opacityBits * shift17 + targetBit * shift16 + + opacityBits * shift9 + targetBit * shift8 + + opacityBits * shift1 + targetBit; +} +const PACKED_HIDDEN_OPACITY = 0; + +function createProjection() { + return { + isOccluded(_x, _y, _t) { + return false; + }, + getPitchedTextCorrection(_transform, _anchor, _tile) { + return 1.0; + }, + get useSpecialProjectionForSymbols() { return false; }, + projectTileCoordinates(_x, _y, _t, _ele) { + // This function should only be used when useSpecialProjectionForSymbols is set to true. + throw new Error('Not implemented.'); + }, + translatePosition(transform, tile, translate, translateAnchor) { + return translatePosition(transform, tile, translate, translateAnchor); + }, + getCircleRadiusCorrection(_) { + return 1.0; + } + }; +} +/** + * Returns a translation in tile units that correctly incorporates the view angle and the *-translate and *-translate-anchor properties. + * @param inViewportPixelUnitsUnits - True when the units accepted by the matrix are in viewport pixels instead of tile units. + * + * Temporarily imported from globe branch. + */ +function translatePosition(transform, tile, translate, translateAnchor, inViewportPixelUnitsUnits = false) { + if (!translate[0] && !translate[1]) + return [0, 0]; + const angle = inViewportPixelUnitsUnits ? + (translateAnchor === 'map' ? transform.angle : 0) : + (translateAnchor === 'viewport' ? -transform.angle : 0); + if (angle) { + const sinA = Math.sin(angle); + const cosA = Math.cos(angle); + translate = [ + translate[0] * cosA - translate[1] * sinA, + translate[0] * sinA + translate[1] * cosA + ]; + } + return [ + inViewportPixelUnitsUnits ? translate[0] : pixelsToTileUnits(tile, translate[0], transform.zoom), + inViewportPixelUnitsUnits ? translate[1] : pixelsToTileUnits(tile, translate[1], transform.zoom) + ]; +} + +class LayerPlacement { + constructor(styleLayer) { + this._sortAcrossTiles = styleLayer.layout.get('symbol-z-order') !== 'viewport-y' && + !styleLayer.layout.get('symbol-sort-key').isConstant(); + this._currentTileIndex = 0; + this._currentPartIndex = 0; + this._seenCrossTileIDs = {}; + this._bucketParts = []; + } + continuePlacement(tiles, placement, showCollisionBoxes, styleLayer, shouldPausePlacement) { + const bucketParts = this._bucketParts; + while (this._currentTileIndex < tiles.length) { + const tile = tiles[this._currentTileIndex]; + placement.getBucketParts(bucketParts, styleLayer, tile, this._sortAcrossTiles); + this._currentTileIndex++; + if (shouldPausePlacement()) { + return true; + } + } + if (this._sortAcrossTiles) { + this._sortAcrossTiles = false; + bucketParts.sort((a, b) => a.sortKey - b.sortKey); + } + while (this._currentPartIndex < bucketParts.length) { + const bucketPart = bucketParts[this._currentPartIndex]; + placement.placeLayerBucketPart(bucketPart, this._seenCrossTileIDs, showCollisionBoxes); + this._currentPartIndex++; + if (shouldPausePlacement()) { + return true; + } + } + return false; + } +} +class PauseablePlacement { + constructor(transform, terrain, order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, prevPlacement) { + this.placement = new Placement(transform, createProjection(), terrain, fadeDuration, crossSourceCollisions, prevPlacement); + this._currentPlacementIndex = order.length - 1; + this._forceFullPlacement = forceFullPlacement; + this._showCollisionBoxes = showCollisionBoxes; + this._done = false; + } + isDone() { + return this._done; + } + continuePlacement(order, layers, layerTiles) { + const startTime = browser.now(); + const shouldPausePlacement = () => { + return this._forceFullPlacement ? false : (browser.now() - startTime) > 2; + }; + while (this._currentPlacementIndex >= 0) { + const layerId = order[this._currentPlacementIndex]; + const layer = layers[layerId]; + const placementZoom = this.placement.collisionIndex.transform.zoom; + if (layer.type === 'symbol' && + (!layer.minzoom || layer.minzoom <= placementZoom) && + (!layer.maxzoom || layer.maxzoom > placementZoom)) { + if (!this._inProgressLayer) { + this._inProgressLayer = new LayerPlacement(layer); + } + const pausePlacement = this._inProgressLayer.continuePlacement(layerTiles[layer.source], this.placement, this._showCollisionBoxes, layer, shouldPausePlacement); + if (pausePlacement) { + // We didn't finish placing all layers within 2ms, + // but we can keep rendering with a partial placement + // We'll resume here on the next frame + return; + } + delete this._inProgressLayer; + } + this._currentPlacementIndex--; + } + this._done = true; + } + commit(now) { + this.placement.commit(now); + return this.placement; + } +} + +/* + The CrossTileSymbolIndex generally works on the assumption that + a conceptual "unique symbol" can be identified by the text of + the label combined with the anchor point. The goal is to assign + these conceptual "unique symbols" a shared crossTileID that can be + used by Placement to keep fading opacity states consistent and to + deduplicate labels. + + The CrossTileSymbolIndex indexes all the current symbol instances and + their crossTileIDs. When a symbol bucket gets added or updated, the + index assigns a crossTileID to each of it's symbol instances by either + matching it with an existing id or assigning a new one. +*/ +// Round anchor positions to roughly 4 pixel grid +const roundingFactor = 512 / performance$1.EXTENT / 2; +const KDBUSH_THRESHHOLD = 128; +class TileLayerIndex { + constructor(tileID, symbolInstances, bucketInstanceId) { + this.tileID = tileID; + this.bucketInstanceId = bucketInstanceId; + this._symbolsByKey = {}; + // group the symbolInstances by key + const symbolInstancesByKey = new Map(); + for (let i = 0; i < symbolInstances.length; i++) { + const symbolInstance = symbolInstances.get(i); + const key = symbolInstance.key; + const instances = symbolInstancesByKey.get(key); + if (instances) { + // This tile may have multiple symbol instances with the same key + // Store each one along with its coordinates + instances.push(symbolInstance); + } + else { + symbolInstancesByKey.set(key, [symbolInstance]); + } + } + // index the SymbolInstances in this each bucket + for (const [key, symbols] of symbolInstancesByKey) { + const positions = symbols.map(symbolInstance => ({ x: Math.floor(symbolInstance.anchorX * roundingFactor), y: Math.floor(symbolInstance.anchorY * roundingFactor) })); + const crossTileIDs = symbols.map(v => v.crossTileID); + const entry = { positions, crossTileIDs }; + // once we get too many symbols for a given key, it becomes much faster to index it before queries + if (entry.positions.length > KDBUSH_THRESHHOLD) { + const index = new performance$1.KDBush(entry.positions.length, 16, Uint16Array); + for (const { x, y } of entry.positions) + index.add(x, y); + index.finish(); + // clear all references to the original positions data + delete entry.positions; + entry.index = index; + } + this._symbolsByKey[key] = entry; + } + } + // Converts the coordinates of the input symbol instance into coordinates that be can compared + // against other symbols in this index. Coordinates are: + // (1) local-tile-based (so after correction we get x,y values relative to our local anchorX/Y) + // (2) converted to the z-scale of this TileLayerIndex + // (3) down-sampled by "roundingFactor" from tile coordinate precision in order to be + // more tolerant of small differences between tiles. + getScaledCoordinates(symbolInstance, childTileID) { + const { x: localX, y: localY, z: localZ } = this.tileID.canonical; + const { x, y, z } = childTileID.canonical; + const zDifference = z - localZ; + const scale = roundingFactor / Math.pow(2, zDifference); + const xWorld = (x * performance$1.EXTENT + symbolInstance.anchorX) * scale; + const yWorld = (y * performance$1.EXTENT + symbolInstance.anchorY) * scale; + const xOffset = localX * performance$1.EXTENT * roundingFactor; + const yOffset = localY * performance$1.EXTENT * roundingFactor; + const result = { + x: Math.floor(xWorld - xOffset), + y: Math.floor(yWorld - yOffset) + }; + return result; + } + findMatches(symbolInstances, newTileID, zoomCrossTileIDs) { + const tolerance = this.tileID.canonical.z < newTileID.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - newTileID.canonical.z); + for (let i = 0; i < symbolInstances.length; i++) { + const symbolInstance = symbolInstances.get(i); + if (symbolInstance.crossTileID) { + // already has a match, skip + continue; + } + const entry = this._symbolsByKey[symbolInstance.key]; + if (!entry) { + // No symbol with this key in this bucket + continue; + } + const scaledSymbolCoord = this.getScaledCoordinates(symbolInstance, newTileID); + if (entry.index) { + // Return any symbol with the same keys whose coordinates are within 1 + // grid unit. (with a 4px grid, this covers a 12px by 12px area) + const indexes = entry.index.range(scaledSymbolCoord.x - tolerance, scaledSymbolCoord.y - tolerance, scaledSymbolCoord.x + tolerance, scaledSymbolCoord.y + tolerance).sort(); + for (const i of indexes) { + const crossTileID = entry.crossTileIDs[i]; + if (!zoomCrossTileIDs[crossTileID]) { + // Once we've marked ourselves duplicate against this parent symbol, + // don't let any other symbols at the same zoom level duplicate against + // the same parent (see issue #5993) + zoomCrossTileIDs[crossTileID] = true; + symbolInstance.crossTileID = crossTileID; + break; + } + } + } + else if (entry.positions) { + for (let i = 0; i < entry.positions.length; i++) { + const thisTileSymbol = entry.positions[i]; + const crossTileID = entry.crossTileIDs[i]; + // Return any symbol with the same keys whose coordinates are within 1 + // grid unit. (with a 4px grid, this covers a 12px by 12px area) + if (Math.abs(thisTileSymbol.x - scaledSymbolCoord.x) <= tolerance && + Math.abs(thisTileSymbol.y - scaledSymbolCoord.y) <= tolerance && + !zoomCrossTileIDs[crossTileID]) { + // Once we've marked ourselves duplicate against this parent symbol, + // don't let any other symbols at the same zoom level duplicate against + // the same parent (see issue #5993) + zoomCrossTileIDs[crossTileID] = true; + symbolInstance.crossTileID = crossTileID; + break; + } + } + } + } + } + getCrossTileIDsLists() { + return Object.values(this._symbolsByKey).map(({ crossTileIDs }) => crossTileIDs); + } +} +class CrossTileIDs { + constructor() { + this.maxCrossTileID = 0; + } + generate() { + return ++this.maxCrossTileID; + } +} +class CrossTileSymbolLayerIndex { + constructor() { + this.indexes = {}; + this.usedCrossTileIDs = {}; + this.lng = 0; + } + /* + * Sometimes when a user pans across the antimeridian the longitude value gets wrapped. + * To prevent labels from flashing out and in we adjust the tileID values in the indexes + * so that they match the new wrapped version of the map. + */ + handleWrapJump(lng) { + const wrapDelta = Math.round((lng - this.lng) / 360); + if (wrapDelta !== 0) { + for (const zoom in this.indexes) { + const zoomIndexes = this.indexes[zoom]; + const newZoomIndex = {}; + for (const key in zoomIndexes) { + // change the tileID's wrap and add it to a new index + const index = zoomIndexes[key]; + index.tileID = index.tileID.unwrapTo(index.tileID.wrap + wrapDelta); + newZoomIndex[index.tileID.key] = index; + } + this.indexes[zoom] = newZoomIndex; + } + } + this.lng = lng; + } + addBucket(tileID, bucket, crossTileIDs) { + if (this.indexes[tileID.overscaledZ] && + this.indexes[tileID.overscaledZ][tileID.key]) { + if (this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId === + bucket.bucketInstanceId) { + return false; + } + else { + // We're replacing this bucket with an updated version + // Remove the old bucket's "used crossTileIDs" now so that + // the new bucket can claim them. + // The old index entries themselves stick around until + // 'removeStaleBuckets' is called. + this.removeBucketCrossTileIDs(tileID.overscaledZ, this.indexes[tileID.overscaledZ][tileID.key]); + } + } + for (let i = 0; i < bucket.symbolInstances.length; i++) { + const symbolInstance = bucket.symbolInstances.get(i); + symbolInstance.crossTileID = 0; + } + if (!this.usedCrossTileIDs[tileID.overscaledZ]) { + this.usedCrossTileIDs[tileID.overscaledZ] = {}; + } + const zoomCrossTileIDs = this.usedCrossTileIDs[tileID.overscaledZ]; + for (const zoom in this.indexes) { + const zoomIndexes = this.indexes[zoom]; + if (Number(zoom) > tileID.overscaledZ) { + for (const id in zoomIndexes) { + const childIndex = zoomIndexes[id]; + if (childIndex.tileID.isChildOf(tileID)) { + childIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs); + } + } + } + else { + const parentCoord = tileID.scaledTo(Number(zoom)); + const parentIndex = zoomIndexes[parentCoord.key]; + if (parentIndex) { + parentIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs); + } + } + } + for (let i = 0; i < bucket.symbolInstances.length; i++) { + const symbolInstance = bucket.symbolInstances.get(i); + if (!symbolInstance.crossTileID) { + // symbol did not match any known symbol, assign a new id + symbolInstance.crossTileID = crossTileIDs.generate(); + zoomCrossTileIDs[symbolInstance.crossTileID] = true; + } + } + if (this.indexes[tileID.overscaledZ] === undefined) { + this.indexes[tileID.overscaledZ] = {}; + } + this.indexes[tileID.overscaledZ][tileID.key] = new TileLayerIndex(tileID, bucket.symbolInstances, bucket.bucketInstanceId); + return true; + } + removeBucketCrossTileIDs(zoom, removedBucket) { + for (const crossTileIDs of removedBucket.getCrossTileIDsLists()) { + for (const crossTileID of crossTileIDs) { + delete this.usedCrossTileIDs[zoom][crossTileID]; + } + } + } + removeStaleBuckets(currentIDs) { + let tilesChanged = false; + for (const z in this.indexes) { + const zoomIndexes = this.indexes[z]; + for (const tileKey in zoomIndexes) { + if (!currentIDs[zoomIndexes[tileKey].bucketInstanceId]) { + this.removeBucketCrossTileIDs(z, zoomIndexes[tileKey]); + delete zoomIndexes[tileKey]; + tilesChanged = true; + } + } + } + return tilesChanged; + } +} +class CrossTileSymbolIndex { + constructor() { + this.layerIndexes = {}; + this.crossTileIDs = new CrossTileIDs(); + this.maxBucketInstanceId = 0; + this.bucketsInCurrentPlacement = {}; + } + addLayer(styleLayer, tiles, lng) { + let layerIndex = this.layerIndexes[styleLayer.id]; + if (layerIndex === undefined) { + layerIndex = this.layerIndexes[styleLayer.id] = new CrossTileSymbolLayerIndex(); + } + let symbolBucketsChanged = false; + const currentBucketIDs = {}; + layerIndex.handleWrapJump(lng); + for (const tile of tiles) { + const symbolBucket = tile.getBucket(styleLayer); + if (!symbolBucket || styleLayer.id !== symbolBucket.layerIds[0]) + continue; + if (!symbolBucket.bucketInstanceId) { + symbolBucket.bucketInstanceId = ++this.maxBucketInstanceId; + } + if (layerIndex.addBucket(tile.tileID, symbolBucket, this.crossTileIDs)) { + symbolBucketsChanged = true; + } + currentBucketIDs[symbolBucket.bucketInstanceId] = true; + } + if (layerIndex.removeStaleBuckets(currentBucketIDs)) { + symbolBucketsChanged = true; + } + return symbolBucketsChanged; + } + pruneUnusedLayers(usedLayers) { + const usedLayerMap = {}; + usedLayers.forEach((usedLayer) => { + usedLayerMap[usedLayer] = true; + }); + for (const layerId in this.layerIndexes) { + if (!usedLayerMap[layerId]) { + delete this.layerIndexes[layerId]; + } + } + } +} + +// We're skipping validation errors with the `source.canvas` identifier in order +// to continue to allow canvas sources to be added at runtime/updated in +// smart setStyle (see https://github.com/mapbox/mapbox-gl-js/pull/6424): +const emitValidationErrors = (evented, errors) => performance$1.emitValidationErrors(evented, errors && errors.filter(error => error.identifier !== 'source.canvas')); +const empty = performance$1.emptyStyle(); +/** + * The Style base class + */ +class Style extends performance$1.Evented { + constructor(map, options = {}) { + super(); + this._rtlPluginLoaded = () => { + for (const id in this.sourceCaches) { + const sourceType = this.sourceCaches[id].getSource().type; + if (sourceType === 'vector' || sourceType === 'geojson') { + // Non-vector sources don't have any symbols buckets to reload when the RTL text plugin loads + // They also load more quickly, so they're more likely to have already displaying tiles + // that would be unnecessarily booted by the plugin load event + this.sourceCaches[id].reload(); // Should be a no-op if the plugin loads before any tiles load + } + } + }; + this.map = map; + this.dispatcher = new Dispatcher(getGlobalWorkerPool(), map._getMapId()); + this.dispatcher.registerMessageHandler("GG" /* MessageType.getGlyphs */, (mapId, params) => { + return this.getGlyphs(mapId, params); + }); + this.dispatcher.registerMessageHandler("GI" /* MessageType.getImages */, (mapId, params) => { + return this.getImages(mapId, params); + }); + this.imageManager = new ImageManager(); + this.imageManager.setEventedParent(this); + this.glyphManager = new GlyphManager(map._requestManager, options.localIdeographFontFamily); + this.lineAtlas = new LineAtlas(256, 512); + this.crossTileSymbolIndex = new CrossTileSymbolIndex(); + this._spritesImagesIds = {}; + this._layers = {}; + this._order = []; + this.sourceCaches = {}; + this.zoomHistory = new performance$1.ZoomHistory(); + this._loaded = false; + this._availableImages = []; + this._resetUpdates(); + this.dispatcher.broadcast("SR" /* MessageType.setReferrer */, performance$1.getReferrer()); + rtlMainThreadPluginFactory().on(RTLPluginLoadedEventName, this._rtlPluginLoaded); + this.on('data', (event) => { + if (event.dataType !== 'source' || event.sourceDataType !== 'metadata') { + return; + } + const sourceCache = this.sourceCaches[event.sourceId]; + if (!sourceCache) { + return; + } + const source = sourceCache.getSource(); + if (!source || !source.vectorLayerIds) { + return; + } + for (const layerId in this._layers) { + const layer = this._layers[layerId]; + if (layer.source === source.id) { + this._validateLayer(layer); + } + } + }); + } + loadURL(url, options = {}, previousStyle) { + this.fire(new performance$1.Event('dataloading', { dataType: 'style' })); + options.validate = typeof options.validate === 'boolean' ? + options.validate : true; + const request = this.map._requestManager.transformRequest(url, "Style" /* ResourceType.Style */); + this._loadStyleRequest = new AbortController(); + const abortController = this._loadStyleRequest; + performance$1.getJSON(request, this._loadStyleRequest).then((response) => { + this._loadStyleRequest = null; + this._load(response.data, options, previousStyle); + }).catch((error) => { + this._loadStyleRequest = null; + if (error && !abortController.signal.aborted) { // ignore abort + this.fire(new performance$1.ErrorEvent(error)); + } + }); + } + loadJSON(json, options = {}, previousStyle) { + this.fire(new performance$1.Event('dataloading', { dataType: 'style' })); + this._frameRequest = new AbortController(); + browser.frameAsync(this._frameRequest).then(() => { + this._frameRequest = null; + options.validate = options.validate !== false; + this._load(json, options, previousStyle); + }).catch(() => { }); // ignore abort + } + loadEmpty() { + this.fire(new performance$1.Event('dataloading', { dataType: 'style' })); + this._load(empty, { validate: false }); + } + _load(json, options, previousStyle) { + var _a; + const nextState = options.transformStyle ? options.transformStyle(previousStyle, json) : json; + if (options.validate && emitValidationErrors(this, performance$1.validateStyle(nextState))) { + return; + } + this._loaded = true; + this.stylesheet = nextState; + for (const id in nextState.sources) { + this.addSource(id, nextState.sources[id], { validate: false }); + } + if (nextState.sprite) { + this._loadSprite(nextState.sprite); + } + else { + this.imageManager.setLoaded(true); + } + this.glyphManager.setURL(nextState.glyphs); + this._createLayers(); + this.light = new Light(this.stylesheet.light); + this.sky = new Sky(this.stylesheet.sky); + this.map.setTerrain((_a = this.stylesheet.terrain) !== null && _a !== void 0 ? _a : null); + this.fire(new performance$1.Event('data', { dataType: 'style' })); + this.fire(new performance$1.Event('style.load')); + } + _createLayers() { + const dereferencedLayers = performance$1.derefLayers(this.stylesheet.layers); + // Broadcast layers to workers first, so that expensive style processing (createStyleLayer) + // can happen in parallel on both main and worker threads. + this.dispatcher.broadcast("SL" /* MessageType.setLayers */, dereferencedLayers); + this._order = dereferencedLayers.map((layer) => layer.id); + this._layers = {}; + // reset serialization field, to be populated only when needed + this._serializedLayers = null; + for (const layer of dereferencedLayers) { + const styledLayer = performance$1.createStyleLayer(layer); + styledLayer.setEventedParent(this, { layer: { id: layer.id } }); + this._layers[layer.id] = styledLayer; + } + } + _loadSprite(sprite, isUpdate = false, completion = undefined) { + this.imageManager.setLoaded(false); + this._spriteRequest = new AbortController(); + let err; + loadSprite(sprite, this.map._requestManager, this.map.getPixelRatio(), this._spriteRequest).then((images) => { + this._spriteRequest = null; + if (images) { + for (const spriteId in images) { + this._spritesImagesIds[spriteId] = []; + // remove old sprite's loaded images (for the same sprite id) that are not in new sprite + const imagesToRemove = this._spritesImagesIds[spriteId] ? this._spritesImagesIds[spriteId].filter(id => !(id in images)) : []; + for (const id of imagesToRemove) { + this.imageManager.removeImage(id); + this._changedImages[id] = true; + } + for (const id in images[spriteId]) { + // don't prefix images of the "default" sprite + const imageId = spriteId === 'default' ? id : `${spriteId}:${id}`; + // save all the sprite's images' ids to be able to delete them in `removeSprite` + this._spritesImagesIds[spriteId].push(imageId); + if (imageId in this.imageManager.images) { + this.imageManager.updateImage(imageId, images[spriteId][id], false); + } + else { + this.imageManager.addImage(imageId, images[spriteId][id]); + } + if (isUpdate) { + this._changedImages[imageId] = true; + } + } + } + } + }).catch((error) => { + this._spriteRequest = null; + err = error; + this.fire(new performance$1.ErrorEvent(err)); + }).finally(() => { + this.imageManager.setLoaded(true); + this._availableImages = this.imageManager.listImages(); + if (isUpdate) { + this._changed = true; + } + this.dispatcher.broadcast("SI" /* MessageType.setImages */, this._availableImages); + this.fire(new performance$1.Event('data', { dataType: 'style' })); + if (completion) { + completion(err); + } + }); + } + _unloadSprite() { + for (const id of Object.values(this._spritesImagesIds).flat()) { + this.imageManager.removeImage(id); + this._changedImages[id] = true; + } + this._spritesImagesIds = {}; + this._availableImages = this.imageManager.listImages(); + this._changed = true; + this.dispatcher.broadcast("SI" /* MessageType.setImages */, this._availableImages); + this.fire(new performance$1.Event('data', { dataType: 'style' })); + } + _validateLayer(layer) { + const sourceCache = this.sourceCaches[layer.source]; + if (!sourceCache) { + return; + } + const sourceLayer = layer.sourceLayer; + if (!sourceLayer) { + return; + } + const source = sourceCache.getSource(); + if (source.type === 'geojson' || (source.vectorLayerIds && source.vectorLayerIds.indexOf(sourceLayer) === -1)) { + this.fire(new performance$1.ErrorEvent(new Error(`Source layer "${sourceLayer}" ` + + `does not exist on source "${source.id}" ` + + `as specified by style layer "${layer.id}".`))); + } + } + loaded() { + if (!this._loaded) + return false; + if (Object.keys(this._updatedSources).length) + return false; + for (const id in this.sourceCaches) + if (!this.sourceCaches[id].loaded()) + return false; + if (!this.imageManager.isLoaded()) + return false; + return true; + } + /** + * @hidden + * take an array of string IDs, and based on this._layers, generate an array of LayerSpecification + * @param ids - an array of string IDs, for which serialized layers will be generated. If omitted, all serialized layers will be returned + * @param returnClose - if true, return a clone of the layer object + * @returns generated result + */ + _serializeByIds(ids, returnClone = false) { + const serializedLayersDictionary = this._serializedAllLayers(); + if (!ids || ids.length === 0) { + return returnClone ? Object.values(performance$1.clone$1(serializedLayersDictionary)) : Object.values(serializedLayersDictionary); + } + const serializedLayers = []; + for (const id of ids) { + // this check will skip all custom layers + if (serializedLayersDictionary[id]) { + const toPush = returnClone ? performance$1.clone$1(serializedLayersDictionary[id]) : serializedLayersDictionary[id]; + serializedLayers.push(toPush); + } + } + return serializedLayers; + } + /** + * @hidden + * Lazy initialization of this._serializedLayers dictionary and return it + * @returns this._serializedLayers dictionary + */ + _serializedAllLayers() { + let serializedLayers = this._serializedLayers; + if (serializedLayers) { + return serializedLayers; + } + serializedLayers = this._serializedLayers = {}; + const allLayerIds = Object.keys(this._layers); + for (const layerId of allLayerIds) { + const layer = this._layers[layerId]; + if (layer.type !== 'custom') { + serializedLayers[layerId] = layer.serialize(); + } + } + return serializedLayers; + } + hasTransitions() { + if (this.light && this.light.hasTransition()) { + return true; + } + if (this.sky && this.sky.hasTransition()) { + return true; + } + for (const id in this.sourceCaches) { + if (this.sourceCaches[id].hasTransition()) { + return true; + } + } + for (const id in this._layers) { + if (this._layers[id].hasTransition()) { + return true; + } + } + return false; + } + _checkLoaded() { + if (!this._loaded) { + throw new Error('Style is not done loading.'); + } + } + /** + * @internal + * Apply queued style updates in a batch and recalculate zoom-dependent paint properties. + */ + update(parameters) { + if (!this._loaded) { + return; + } + const changed = this._changed; + if (changed) { + const updatedIds = Object.keys(this._updatedLayers); + const removedIds = Object.keys(this._removedLayers); + if (updatedIds.length || removedIds.length) { + this._updateWorkerLayers(updatedIds, removedIds); + } + for (const id in this._updatedSources) { + const action = this._updatedSources[id]; + if (action === 'reload') { + this._reloadSource(id); + } + else if (action === 'clear') { + this._clearSource(id); + } + else { + throw new Error(`Invalid action ${action}`); + } + } + this._updateTilesForChangedImages(); + this._updateTilesForChangedGlyphs(); + for (const id in this._updatedPaintProps) { + this._layers[id].updateTransitions(parameters); + } + this.light.updateTransitions(parameters); + this.sky.updateTransitions(parameters); + this._resetUpdates(); + } + const sourcesUsedBefore = {}; + // save 'used' status to sourcesUsedBefore object and reset all sourceCaches 'used' field to false + for (const sourceCacheId in this.sourceCaches) { + const sourceCache = this.sourceCaches[sourceCacheId]; + // sourceCache.used could be undefined, and sourcesUsedBefore[sourceCacheId] is also 'undefined' + sourcesUsedBefore[sourceCacheId] = sourceCache.used; + sourceCache.used = false; + } + // loop all layers and find layers that are not hidden at parameters.zoom + // and set used to true in sourceCaches dictionary for the sources of these layers + for (const layerId of this._order) { + const layer = this._layers[layerId]; + layer.recalculate(parameters, this._availableImages); + if (!layer.isHidden(parameters.zoom) && layer.source) { + this.sourceCaches[layer.source].used = true; + } + } + // cross check sourcesUsedBefore against updated this.sourceCaches dictionary + // if "used" field is different fire visibility event + for (const sourcesUsedBeforeId in sourcesUsedBefore) { + const sourceCache = this.sourceCaches[sourcesUsedBeforeId]; + // (undefine !== false) will evaluate to true and fire an useless visibility event + // need force "falsy" values to boolean to avoid the case above + if (!!sourcesUsedBefore[sourcesUsedBeforeId] !== !!sourceCache.used) { + sourceCache.fire(new performance$1.Event('data', { + sourceDataType: 'visibility', + dataType: 'source', + sourceId: sourcesUsedBeforeId + })); + } + } + this.light.recalculate(parameters); + this.sky.recalculate(parameters); + this.z = parameters.zoom; + if (changed) { + this.fire(new performance$1.Event('data', { dataType: 'style' })); + } + } + /* + * Apply any queued image changes. + */ + _updateTilesForChangedImages() { + const changedImages = Object.keys(this._changedImages); + if (changedImages.length) { + for (const name in this.sourceCaches) { + this.sourceCaches[name].reloadTilesForDependencies(['icons', 'patterns'], changedImages); + } + this._changedImages = {}; + } + } + _updateTilesForChangedGlyphs() { + if (this._glyphsDidChange) { + for (const name in this.sourceCaches) { + this.sourceCaches[name].reloadTilesForDependencies(['glyphs'], ['']); + } + this._glyphsDidChange = false; + } + } + _updateWorkerLayers(updatedIds, removedIds) { + this.dispatcher.broadcast("UL" /* MessageType.updateLayers */, { + layers: this._serializeByIds(updatedIds, false), + removedIds + }); + } + _resetUpdates() { + this._changed = false; + this._updatedLayers = {}; + this._removedLayers = {}; + this._updatedSources = {}; + this._updatedPaintProps = {}; + this._changedImages = {}; + this._glyphsDidChange = false; + } + /** + * Update this style's state to match the given style JSON, performing only + * the necessary mutations. + * + * May throw an Error ('Unimplemented: METHOD') if the mapbox-gl-style-spec + * diff algorithm produces an operation that is not supported. + * + * @returns true if any changes were made; false otherwise + */ + setState(nextState, options = {}) { + var _a; + this._checkLoaded(); + const serializedStyle = this.serialize(); + nextState = options.transformStyle ? options.transformStyle(serializedStyle, nextState) : nextState; + const validate = (_a = options.validate) !== null && _a !== void 0 ? _a : true; + if (validate && emitValidationErrors(this, performance$1.validateStyle(nextState))) + return false; + nextState = performance$1.clone$1(nextState); + nextState.layers = performance$1.derefLayers(nextState.layers); + const changes = performance$1.diffStyles(serializedStyle, nextState); + const operations = this._getOperationsToPerform(changes); + if (operations.unimplemented.length > 0) { + throw new Error(`Unimplemented: ${operations.unimplemented.join(', ')}.`); + } + if (operations.operations.length === 0) { + return false; + } + for (const styleChangeOperation of operations.operations) { + styleChangeOperation(); + } + this.stylesheet = nextState; + // reset serialization field, to be populated only when needed + this._serializedLayers = null; + return true; + } + _getOperationsToPerform(diff) { + const operations = []; + const unimplemented = []; + for (const op of diff) { + switch (op.command) { + case 'setCenter': + case 'setZoom': + case 'setBearing': + case 'setPitch': + continue; + case 'addLayer': + operations.push(() => this.addLayer.apply(this, op.args)); + break; + case 'removeLayer': + operations.push(() => this.removeLayer.apply(this, op.args)); + break; + case 'setPaintProperty': + operations.push(() => this.setPaintProperty.apply(this, op.args)); + break; + case 'setLayoutProperty': + operations.push(() => this.setLayoutProperty.apply(this, op.args)); + break; + case 'setFilter': + operations.push(() => this.setFilter.apply(this, op.args)); + break; + case 'addSource': + operations.push(() => this.addSource.apply(this, op.args)); + break; + case 'removeSource': + operations.push(() => this.removeSource.apply(this, op.args)); + break; + case 'setLayerZoomRange': + operations.push(() => this.setLayerZoomRange.apply(this, op.args)); + break; + case 'setLight': + operations.push(() => this.setLight.apply(this, op.args)); + break; + case 'setGeoJSONSourceData': + operations.push(() => this.setGeoJSONSourceData.apply(this, op.args)); + break; + case 'setGlyphs': + operations.push(() => this.setGlyphs.apply(this, op.args)); + break; + case 'setSprite': + operations.push(() => this.setSprite.apply(this, op.args)); + break; + case 'setSky': + operations.push(() => this.setSky.apply(this, op.args)); + break; + case 'setTerrain': + operations.push(() => this.map.setTerrain.apply(this, op.args)); + break; + case 'setTransition': + operations.push(() => { }); + break; + default: + unimplemented.push(op.command); + break; + } + } + return { + operations, + unimplemented + }; + } + addImage(id, image) { + if (this.getImage(id)) { + return this.fire(new performance$1.ErrorEvent(new Error(`An image named "${id}" already exists.`))); + } + this.imageManager.addImage(id, image); + this._afterImageUpdated(id); + } + updateImage(id, image) { + this.imageManager.updateImage(id, image); + } + getImage(id) { + return this.imageManager.getImage(id); + } + removeImage(id) { + if (!this.getImage(id)) { + return this.fire(new performance$1.ErrorEvent(new Error(`An image named "${id}" does not exist.`))); + } + this.imageManager.removeImage(id); + this._afterImageUpdated(id); + } + _afterImageUpdated(id) { + this._availableImages = this.imageManager.listImages(); + this._changedImages[id] = true; + this._changed = true; + this.dispatcher.broadcast("SI" /* MessageType.setImages */, this._availableImages); + this.fire(new performance$1.Event('data', { dataType: 'style' })); + } + listImages() { + this._checkLoaded(); + return this.imageManager.listImages(); + } + addSource(id, source, options = {}) { + this._checkLoaded(); + if (this.sourceCaches[id] !== undefined) { + throw new Error(`Source "${id}" already exists.`); + } + if (!source.type) { + throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(source).join(', ')}.`); + } + const builtIns = ['vector', 'raster', 'geojson', 'video', 'image']; + const shouldValidate = builtIns.indexOf(source.type) >= 0; + if (shouldValidate && this._validate(performance$1.validateStyle.source, `sources.${id}`, source, null, options)) + return; + if (this.map && this.map._collectResourceTiming) + source.collectResourceTiming = true; + const sourceCache = this.sourceCaches[id] = new SourceCache(id, source, this.dispatcher); + sourceCache.style = this; + sourceCache.setEventedParent(this, () => ({ + isSourceLoaded: sourceCache.loaded(), + source: sourceCache.serialize(), + sourceId: id + })); + sourceCache.onAdd(this.map); + this._changed = true; + } + /** + * Remove a source from this stylesheet, given its id. + * @param id - id of the source to remove + * @throws if no source is found with the given ID + */ + removeSource(id) { + this._checkLoaded(); + if (this.sourceCaches[id] === undefined) { + throw new Error('There is no source with this ID'); + } + for (const layerId in this._layers) { + if (this._layers[layerId].source === id) { + return this.fire(new performance$1.ErrorEvent(new Error(`Source "${id}" cannot be removed while layer "${layerId}" is using it.`))); + } + } + const sourceCache = this.sourceCaches[id]; + delete this.sourceCaches[id]; + delete this._updatedSources[id]; + sourceCache.fire(new performance$1.Event('data', { sourceDataType: 'metadata', dataType: 'source', sourceId: id })); + sourceCache.setEventedParent(null); + sourceCache.onRemove(this.map); + this._changed = true; + } + /** + * Set the data of a GeoJSON source, given its id. + * @param id - id of the source + * @param data - GeoJSON source + */ + setGeoJSONSourceData(id, data) { + this._checkLoaded(); + if (this.sourceCaches[id] === undefined) + throw new Error(`There is no source with this ID=${id}`); + const geojsonSource = this.sourceCaches[id].getSource(); + if (geojsonSource.type !== 'geojson') + throw new Error(`geojsonSource.type is ${geojsonSource.type}, which is !== 'geojson`); + geojsonSource.setData(data); + this._changed = true; + } + /** + * Get a source by ID. + * @param id - ID of the desired source + * @returns source + */ + getSource(id) { + return this.sourceCaches[id] && this.sourceCaches[id].getSource(); + } + /** + * Add a layer to the map style. The layer will be inserted before the layer with + * ID `before`, or appended if `before` is omitted. + * @param layerObject - The style layer to add. + * @param before - ID of an existing layer to insert before + * @param options - Style setter options. + */ + addLayer(layerObject, before, options = {}) { + this._checkLoaded(); + const id = layerObject.id; + if (this.getLayer(id)) { + this.fire(new performance$1.ErrorEvent(new Error(`Layer "${id}" already exists on this map.`))); + return; + } + let layer; + if (layerObject.type === 'custom') { + if (emitValidationErrors(this, performance$1.validateCustomStyleLayer(layerObject))) + return; + layer = performance$1.createStyleLayer(layerObject); + } + else { + if ('source' in layerObject && typeof layerObject.source === 'object') { + this.addSource(id, layerObject.source); + layerObject = performance$1.clone$1(layerObject); + layerObject = performance$1.extend(layerObject, { source: id }); + } + // this layer is not in the style.layers array, so we pass an impossible array index + if (this._validate(performance$1.validateStyle.layer, `layers.${id}`, layerObject, { arrayIndex: -1 }, options)) + return; + layer = performance$1.createStyleLayer(layerObject); + this._validateLayer(layer); + layer.setEventedParent(this, { layer: { id } }); + } + const index = before ? this._order.indexOf(before) : this._order.length; + if (before && index === -1) { + this.fire(new performance$1.ErrorEvent(new Error(`Cannot add layer "${id}" before non-existing layer "${before}".`))); + return; + } + this._order.splice(index, 0, id); + this._layerOrderChanged = true; + this._layers[id] = layer; + if (this._removedLayers[id] && layer.source && layer.type !== 'custom') { + // If, in the current batch, we have already removed this layer + // and we are now re-adding it with a different `type`, then we + // need to clear (rather than just reload) the underlying source's + // tiles. Otherwise, tiles marked 'reloading' will have buckets / + // buffers that are set up for the _previous_ version of this + // layer, causing, e.g.: + // https://github.com/mapbox/mapbox-gl-js/issues/3633 + const removed = this._removedLayers[id]; + delete this._removedLayers[id]; + if (removed.type !== layer.type) { + this._updatedSources[layer.source] = 'clear'; + } + else { + this._updatedSources[layer.source] = 'reload'; + this.sourceCaches[layer.source].pause(); + } + } + this._updateLayer(layer); + if (layer.onAdd) { + layer.onAdd(this.map); + } + } + /** + * Moves a layer to a different z-position. The layer will be inserted before the layer with + * ID `before`, or appended if `before` is omitted. + * @param id - ID of the layer to move + * @param before - ID of an existing layer to insert before + */ + moveLayer(id, before) { + this._checkLoaded(); + this._changed = true; + const layer = this._layers[id]; + if (!layer) { + this.fire(new performance$1.ErrorEvent(new Error(`The layer '${id}' does not exist in the map's style and cannot be moved.`))); + return; + } + if (id === before) { + return; + } + const index = this._order.indexOf(id); + this._order.splice(index, 1); + const newIndex = before ? this._order.indexOf(before) : this._order.length; + if (before && newIndex === -1) { + this.fire(new performance$1.ErrorEvent(new Error(`Cannot move layer "${id}" before non-existing layer "${before}".`))); + return; + } + this._order.splice(newIndex, 0, id); + this._layerOrderChanged = true; + } + /** + * Remove the layer with the given id from the style. + * A {@link ErrorEvent} event will be fired if no such layer exists. + * + * @param id - id of the layer to remove + */ + removeLayer(id) { + this._checkLoaded(); + const layer = this._layers[id]; + if (!layer) { + this.fire(new performance$1.ErrorEvent(new Error(`Cannot remove non-existing layer "${id}".`))); + return; + } + layer.setEventedParent(null); + const index = this._order.indexOf(id); + this._order.splice(index, 1); + this._layerOrderChanged = true; + this._changed = true; + this._removedLayers[id] = layer; + delete this._layers[id]; + if (this._serializedLayers) { + delete this._serializedLayers[id]; + } + delete this._updatedLayers[id]; + delete this._updatedPaintProps[id]; + if (layer.onRemove) { + layer.onRemove(this.map); + } + } + /** + * Return the style layer object with the given `id`. + * + * @param id - id of the desired layer + * @returns a layer, if one with the given `id` exists + */ + getLayer(id) { + return this._layers[id]; + } + /** + * Return the ids of all layers currently in the style, including custom layers, in order. + * + * @returns ids of layers, in order + */ + getLayersOrder() { + return [...this._order]; + } + /** + * Checks if a specific layer is present within the style. + * + * @param id - the id of the desired layer + * @returns a boolean specifying if the given layer is present + */ + hasLayer(id) { + return id in this._layers; + } + setLayerZoomRange(layerId, minzoom, maxzoom) { + this._checkLoaded(); + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new performance$1.ErrorEvent(new Error(`Cannot set the zoom range of non-existing layer "${layerId}".`))); + return; + } + if (layer.minzoom === minzoom && layer.maxzoom === maxzoom) + return; + if (minzoom != null) { + layer.minzoom = minzoom; + } + if (maxzoom != null) { + layer.maxzoom = maxzoom; + } + this._updateLayer(layer); + } + setFilter(layerId, filter, options = {}) { + this._checkLoaded(); + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new performance$1.ErrorEvent(new Error(`Cannot filter non-existing layer "${layerId}".`))); + return; + } + if (performance$1.deepEqual(layer.filter, filter)) { + return; + } + if (filter === null || filter === undefined) { + layer.filter = undefined; + this._updateLayer(layer); + return; + } + if (this._validate(performance$1.validateStyle.filter, `layers.${layer.id}.filter`, filter, null, options)) { + return; + } + layer.filter = performance$1.clone$1(filter); + this._updateLayer(layer); + } + /** + * Get a layer's filter object + * @param layer - the layer to inspect + * @returns the layer's filter, if any + */ + getFilter(layer) { + return performance$1.clone$1(this.getLayer(layer).filter); + } + setLayoutProperty(layerId, name, value, options = {}) { + this._checkLoaded(); + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new performance$1.ErrorEvent(new Error(`Cannot style non-existing layer "${layerId}".`))); + return; + } + if (performance$1.deepEqual(layer.getLayoutProperty(name), value)) + return; + layer.setLayoutProperty(name, value, options); + this._updateLayer(layer); + } + /** + * Get a layout property's value from a given layer + * @param layerId - the layer to inspect + * @param name - the name of the layout property + * @returns the property value + */ + getLayoutProperty(layerId, name) { + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new performance$1.ErrorEvent(new Error(`Cannot get style of non-existing layer "${layerId}".`))); + return; + } + return layer.getLayoutProperty(name); + } + setPaintProperty(layerId, name, value, options = {}) { + this._checkLoaded(); + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new performance$1.ErrorEvent(new Error(`Cannot style non-existing layer "${layerId}".`))); + return; + } + if (performance$1.deepEqual(layer.getPaintProperty(name), value)) + return; + const requiresRelayout = layer.setPaintProperty(name, value, options); + if (requiresRelayout) { + this._updateLayer(layer); + } + this._changed = true; + this._updatedPaintProps[layerId] = true; + // reset serialization field, to be populated only when needed + this._serializedLayers = null; + } + getPaintProperty(layer, name) { + return this.getLayer(layer).getPaintProperty(name); + } + setFeatureState(target, state) { + this._checkLoaded(); + const sourceId = target.source; + const sourceLayer = target.sourceLayer; + const sourceCache = this.sourceCaches[sourceId]; + if (sourceCache === undefined) { + this.fire(new performance$1.ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`))); + return; + } + const sourceType = sourceCache.getSource().type; + if (sourceType === 'geojson' && sourceLayer) { + this.fire(new performance$1.ErrorEvent(new Error('GeoJSON sources cannot have a sourceLayer parameter.'))); + return; + } + if (sourceType === 'vector' && !sourceLayer) { + this.fire(new performance$1.ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.'))); + return; + } + if (target.id === undefined) { + this.fire(new performance$1.ErrorEvent(new Error('The feature id parameter must be provided.'))); + } + sourceCache.setFeatureState(sourceLayer, target.id, state); + } + removeFeatureState(target, key) { + this._checkLoaded(); + const sourceId = target.source; + const sourceCache = this.sourceCaches[sourceId]; + if (sourceCache === undefined) { + this.fire(new performance$1.ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`))); + return; + } + const sourceType = sourceCache.getSource().type; + const sourceLayer = sourceType === 'vector' ? target.sourceLayer : undefined; + if (sourceType === 'vector' && !sourceLayer) { + this.fire(new performance$1.ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.'))); + return; + } + if (key && (typeof target.id !== 'string' && typeof target.id !== 'number')) { + this.fire(new performance$1.ErrorEvent(new Error('A feature id is required to remove its specific state property.'))); + return; + } + sourceCache.removeFeatureState(sourceLayer, target.id, key); + } + getFeatureState(target) { + this._checkLoaded(); + const sourceId = target.source; + const sourceLayer = target.sourceLayer; + const sourceCache = this.sourceCaches[sourceId]; + if (sourceCache === undefined) { + this.fire(new performance$1.ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`))); + return; + } + const sourceType = sourceCache.getSource().type; + if (sourceType === 'vector' && !sourceLayer) { + this.fire(new performance$1.ErrorEvent(new Error('The sourceLayer parameter must be provided for vector source types.'))); + return; + } + if (target.id === undefined) { + this.fire(new performance$1.ErrorEvent(new Error('The feature id parameter must be provided.'))); + } + return sourceCache.getFeatureState(sourceLayer, target.id); + } + getTransition() { + return performance$1.extend({ duration: 300, delay: 0 }, this.stylesheet && this.stylesheet.transition); + } + serialize() { + // We return undefined before we're loaded, following the pattern of Map.getStyle() before + // the Style object is initialized. + // Internally, Style._validate() calls Style.serialize() but callers are responsible for + // calling Style._checkLoaded() first if their validation requires the style to be loaded. + if (!this._loaded) + return; + const sources = performance$1.mapObject(this.sourceCaches, (source) => source.serialize()); + const layers = this._serializeByIds(this._order, true); + const terrain = this.map.getTerrain() || undefined; + const myStyleSheet = this.stylesheet; + return performance$1.filterObject({ + version: myStyleSheet.version, + name: myStyleSheet.name, + metadata: myStyleSheet.metadata, + light: myStyleSheet.light, + sky: myStyleSheet.sky, + center: myStyleSheet.center, + zoom: myStyleSheet.zoom, + bearing: myStyleSheet.bearing, + pitch: myStyleSheet.pitch, + sprite: myStyleSheet.sprite, + glyphs: myStyleSheet.glyphs, + transition: myStyleSheet.transition, + sources, + layers, + terrain + }, (value) => { return value !== undefined; }); + } + _updateLayer(layer) { + this._updatedLayers[layer.id] = true; + if (layer.source && !this._updatedSources[layer.source] && + //Skip for raster layers (https://github.com/mapbox/mapbox-gl-js/issues/7865) + this.sourceCaches[layer.source].getSource().type !== 'raster') { + this._updatedSources[layer.source] = 'reload'; + this.sourceCaches[layer.source].pause(); + } + // upon updating, serialized layer dictionary should be reset. + // When needed, it will be populated with the correct copy again. + this._serializedLayers = null; + this._changed = true; + } + _flattenAndSortRenderedFeatures(sourceResults) { + // Feature order is complicated. + // The order between features in two 2D layers is always determined by layer order. + // The order between features in two 3D layers is always determined by depth. + // The order between a feature in a 2D layer and a 3D layer is tricky: + // Most often layer order determines the feature order in this case. If + // a line layer is above a extrusion layer the line feature will be rendered + // above the extrusion. If the line layer is below the extrusion layer, + // it will be rendered below it. + // + // There is a weird case though. + // You have layers in this order: extrusion_layer_a, line_layer, extrusion_layer_b + // Each layer has a feature that overlaps the other features. + // The feature in extrusion_layer_a is closer than the feature in extrusion_layer_b so it is rendered above. + // The feature in line_layer is rendered above extrusion_layer_a. + // This means that that the line_layer feature is above the extrusion_layer_b feature despite + // it being in an earlier layer. + const isLayer3D = layerId => this._layers[layerId].type === 'fill-extrusion'; + const layerIndex = {}; + const features3D = []; + for (let l = this._order.length - 1; l >= 0; l--) { + const layerId = this._order[l]; + if (isLayer3D(layerId)) { + layerIndex[layerId] = l; + for (const sourceResult of sourceResults) { + const layerFeatures = sourceResult[layerId]; + if (layerFeatures) { + for (const featureWrapper of layerFeatures) { + features3D.push(featureWrapper); + } + } + } + } + } + features3D.sort((a, b) => { + return b.intersectionZ - a.intersectionZ; + }); + const features = []; + for (let l = this._order.length - 1; l >= 0; l--) { + const layerId = this._order[l]; + if (isLayer3D(layerId)) { + // add all 3D features that are in or above the current layer + for (let i = features3D.length - 1; i >= 0; i--) { + const topmost3D = features3D[i].feature; + if (layerIndex[topmost3D.layer.id] < l) + break; + features.push(topmost3D); + features3D.pop(); + } + } + else { + for (const sourceResult of sourceResults) { + const layerFeatures = sourceResult[layerId]; + if (layerFeatures) { + for (const featureWrapper of layerFeatures) { + features.push(featureWrapper.feature); + } + } + } + } + } + return features; + } + queryRenderedFeatures(queryGeometry, params, transform) { + if (params && params.filter) { + this._validate(performance$1.validateStyle.filter, 'queryRenderedFeatures.filter', params.filter, null, params); + } + const includedSources = {}; + if (params && params.layers) { + if (!Array.isArray(params.layers)) { + this.fire(new performance$1.ErrorEvent(new Error('parameters.layers must be an Array.'))); + return []; + } + for (const layerId of params.layers) { + const layer = this._layers[layerId]; + if (!layer) { + // this layer is not in the style.layers array + this.fire(new performance$1.ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be queried for features.`))); + return []; + } + includedSources[layer.source] = true; + } + } + const sourceResults = []; + params.availableImages = this._availableImages; + // LayerSpecification is serialized StyleLayer, and this casting is safe. + const serializedLayers = this._serializedAllLayers(); + for (const id in this.sourceCaches) { + if (params.layers && !includedSources[id]) + continue; + sourceResults.push(queryRenderedFeatures(this.sourceCaches[id], this._layers, serializedLayers, queryGeometry, params, transform)); + } + if (this.placement) { + // If a placement has run, query against its CollisionIndex + // for symbol results, and treat it as an extra source to merge + sourceResults.push(queryRenderedSymbols(this._layers, serializedLayers, this.sourceCaches, queryGeometry, params, this.placement.collisionIndex, this.placement.retainedQueryData)); + } + return this._flattenAndSortRenderedFeatures(sourceResults); + } + querySourceFeatures(sourceID, params) { + if (params && params.filter) { + this._validate(performance$1.validateStyle.filter, 'querySourceFeatures.filter', params.filter, null, params); + } + const sourceCache = this.sourceCaches[sourceID]; + return sourceCache ? querySourceFeatures(sourceCache, params) : []; + } + getLight() { + return this.light.getLight(); + } + setLight(lightOptions, options = {}) { + this._checkLoaded(); + const light = this.light.getLight(); + let _update = false; + for (const key in lightOptions) { + if (!performance$1.deepEqual(lightOptions[key], light[key])) { + _update = true; + break; + } + } + if (!_update) + return; + const parameters = { + now: browser.now(), + transition: performance$1.extend({ + duration: 300, + delay: 0 + }, this.stylesheet.transition) + }; + this.light.setLight(lightOptions, options); + this.light.updateTransitions(parameters); + } + getSky() { + var _a; + return (_a = this.stylesheet) === null || _a === void 0 ? void 0 : _a.sky; + } + setSky(skyOptions, options = {}) { + const sky = this.getSky(); + let update = false; + if (!skyOptions && !sky) + return; + if (skyOptions && !sky) { + update = true; + } + else if (!skyOptions && sky) { + update = true; + } + else { + for (const key in skyOptions) { + if (!performance$1.deepEqual(skyOptions[key], sky[key])) { + update = true; + break; + } + } + } + if (!update) + return; + const parameters = { + now: browser.now(), + transition: performance$1.extend({ + duration: 300, + delay: 0 + }, this.stylesheet.transition) + }; + this.stylesheet.sky = skyOptions; + this.sky.setSky(skyOptions, options); + this.sky.updateTransitions(parameters); + } + _validate(validate, key, value, props, options = {}) { + if (options && options.validate === false) { + return false; + } + return emitValidationErrors(this, validate.call(performance$1.validateStyle, performance$1.extend({ + key, + style: this.serialize(), + value, + styleSpec: performance$1.v8Spec + }, props))); + } + _remove(mapRemoved = true) { + if (this._frameRequest) { + this._frameRequest.abort(); + this._frameRequest = null; + } + if (this._loadStyleRequest) { + this._loadStyleRequest.abort(); + this._loadStyleRequest = null; + } + if (this._spriteRequest) { + this._spriteRequest.abort(); + this._spriteRequest = null; + } + rtlMainThreadPluginFactory().off(RTLPluginLoadedEventName, this._rtlPluginLoaded); + for (const layerId in this._layers) { + const layer = this._layers[layerId]; + layer.setEventedParent(null); + } + for (const id in this.sourceCaches) { + const sourceCache = this.sourceCaches[id]; + sourceCache.setEventedParent(null); + sourceCache.onRemove(this.map); + } + this.imageManager.setEventedParent(null); + this.setEventedParent(null); + if (mapRemoved) { + this.dispatcher.broadcast("RM" /* MessageType.removeMap */, undefined); + } + this.dispatcher.remove(mapRemoved); + } + _clearSource(id) { + this.sourceCaches[id].clearTiles(); + } + _reloadSource(id) { + this.sourceCaches[id].resume(); + this.sourceCaches[id].reload(); + } + _updateSources(transform) { + for (const id in this.sourceCaches) { + this.sourceCaches[id].update(transform, this.map.terrain); + } + } + _generateCollisionBoxes() { + for (const id in this.sourceCaches) { + this._reloadSource(id); + } + } + _updatePlacement(transform, showCollisionBoxes, fadeDuration, crossSourceCollisions, forceFullPlacement = false) { + let symbolBucketsChanged = false; + let placementCommitted = false; + const layerTiles = {}; + for (const layerID of this._order) { + const styleLayer = this._layers[layerID]; + if (styleLayer.type !== 'symbol') + continue; + if (!layerTiles[styleLayer.source]) { + const sourceCache = this.sourceCaches[styleLayer.source]; + layerTiles[styleLayer.source] = sourceCache.getRenderableIds(true) + .map((id) => sourceCache.getTileByID(id)) + .sort((a, b) => (b.tileID.overscaledZ - a.tileID.overscaledZ) || (a.tileID.isLessThan(b.tileID) ? -1 : 1)); + } + const layerBucketsChanged = this.crossTileSymbolIndex.addLayer(styleLayer, layerTiles[styleLayer.source], transform.center.lng); + symbolBucketsChanged = symbolBucketsChanged || layerBucketsChanged; + } + this.crossTileSymbolIndex.pruneUnusedLayers(this._order); + // Anything that changes our "in progress" layer and tile indices requires us + // to start over. When we start over, we do a full placement instead of incremental + // to prevent starvation. + // We need to restart placement to keep layer indices in sync. + // Also force full placement when fadeDuration === 0 to ensure that newly loaded + // tiles will fully display symbols in their first frame + forceFullPlacement = forceFullPlacement || this._layerOrderChanged || fadeDuration === 0; + if (forceFullPlacement || !this.pauseablePlacement || (this.pauseablePlacement.isDone() && !this.placement.stillRecent(browser.now(), transform.zoom))) { + this.pauseablePlacement = new PauseablePlacement(transform, this.map.terrain, this._order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, this.placement); + this._layerOrderChanged = false; + } + if (this.pauseablePlacement.isDone()) { + // the last placement finished running, but the next one hasn’t + // started yet because of the `stillRecent` check immediately + // above, so mark it stale to ensure that we request another + // render frame + this.placement.setStale(); + } + else { + this.pauseablePlacement.continuePlacement(this._order, this._layers, layerTiles); + if (this.pauseablePlacement.isDone()) { + this.placement = this.pauseablePlacement.commit(browser.now()); + placementCommitted = true; + } + if (symbolBucketsChanged) { + // since the placement gets split over multiple frames it is possible + // these buckets were processed before they were changed and so the + // placement is already stale while it is in progress + this.pauseablePlacement.placement.setStale(); + } + } + if (placementCommitted || symbolBucketsChanged) { + for (const layerID of this._order) { + const styleLayer = this._layers[layerID]; + if (styleLayer.type !== 'symbol') + continue; + this.placement.updateLayerOpacities(styleLayer, layerTiles[styleLayer.source]); + } + } + // needsRender is false when we have just finished a placement that didn't change the visibility of any symbols + const needsRerender = !this.pauseablePlacement.isDone() || this.placement.hasTransitions(browser.now()); + return needsRerender; + } + _releaseSymbolFadeTiles() { + for (const id in this.sourceCaches) { + this.sourceCaches[id].releaseSymbolFadeTiles(); + } + } + // Callbacks from web workers + getImages(mapId, params) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + const images = yield this.imageManager.getImages(params.icons); + // Apply queued image changes before setting the tile's dependencies so that the tile + // is not reloaded unnecessarily. Without this forced update the reload could happen in cases + // like this one: + // - icons contains "my-image" + // - imageManager.getImages(...) triggers `onstyleimagemissing` + // - the user adds "my-image" within the callback + // - addImage adds "my-image" to this._changedImages + // - the next frame triggers a reload of this tile even though it already has the latest version + this._updateTilesForChangedImages(); + const sourceCache = this.sourceCaches[params.source]; + if (sourceCache) { + sourceCache.setDependencies(params.tileID.key, params.type, params.icons); + } + return images; + }); + } + getGlyphs(mapId, params) { + return performance$1.__awaiter(this, void 0, void 0, function* () { + const glypgs = yield this.glyphManager.getGlyphs(params.stacks); + const sourceCache = this.sourceCaches[params.source]; + if (sourceCache) { + // we are not setting stacks as dependencies since for now + // we just need to know which tiles have glyph dependencies + sourceCache.setDependencies(params.tileID.key, params.type, ['']); + } + return glypgs; + }); + } + getGlyphsUrl() { + return this.stylesheet.glyphs || null; + } + setGlyphs(glyphsUrl, options = {}) { + this._checkLoaded(); + if (glyphsUrl && this._validate(performance$1.validateStyle.glyphs, 'glyphs', glyphsUrl, null, options)) { + return; + } + this._glyphsDidChange = true; + this.stylesheet.glyphs = glyphsUrl; + this.glyphManager.entries = {}; + this.glyphManager.setURL(glyphsUrl); + } + /** + * Add a sprite. + * + * @param id - The id of the desired sprite + * @param url - The url to load the desired sprite from + * @param options - The style setter options + * @param completion - The completion handler + */ + addSprite(id, url, options = {}, completion) { + this._checkLoaded(); + const spriteToAdd = [{ id, url }]; + const updatedSprite = [ + ...coerceSpriteToArray(this.stylesheet.sprite), + ...spriteToAdd + ]; + if (this._validate(performance$1.validateStyle.sprite, 'sprite', updatedSprite, null, options)) + return; + this.stylesheet.sprite = updatedSprite; + this._loadSprite(spriteToAdd, true, completion); + } + /** + * Remove a sprite by its id. When the last sprite is removed, the whole `this.stylesheet.sprite` object becomes + * `undefined`. This falsy `undefined` value later prevents attempts to load the sprite when it's absent. + * + * @param id - the id of the sprite to remove + */ + removeSprite(id) { + this._checkLoaded(); + const internalSpriteRepresentation = coerceSpriteToArray(this.stylesheet.sprite); + if (!internalSpriteRepresentation.find(sprite => sprite.id === id)) { + this.fire(new performance$1.ErrorEvent(new Error(`Sprite "${id}" doesn't exists on this map.`))); + return; + } + if (this._spritesImagesIds[id]) { + for (const imageId of this._spritesImagesIds[id]) { + this.imageManager.removeImage(imageId); + this._changedImages[imageId] = true; + } + } + internalSpriteRepresentation.splice(internalSpriteRepresentation.findIndex(sprite => sprite.id === id), 1); + this.stylesheet.sprite = internalSpriteRepresentation.length > 0 ? internalSpriteRepresentation : undefined; + delete this._spritesImagesIds[id]; + this._availableImages = this.imageManager.listImages(); + this._changed = true; + this.dispatcher.broadcast("SI" /* MessageType.setImages */, this._availableImages); + this.fire(new performance$1.Event('data', { dataType: 'style' })); + } + /** + * Get the current sprite value. + * + * @returns empty array when no sprite is set; id-url pairs otherwise + */ + getSprite() { + return coerceSpriteToArray(this.stylesheet.sprite); + } + /** + * Set a new value for the style's sprite. + * + * @param sprite - new sprite value + * @param options - style setter options + * @param completion - the completion handler + */ + setSprite(sprite, options = {}, completion) { + this._checkLoaded(); + if (sprite && this._validate(performance$1.validateStyle.sprite, 'sprite', sprite, null, options)) { + return; + } + this.stylesheet.sprite = sprite; + if (sprite) { + this._loadSprite(sprite, true, completion); + } + else { + this._unloadSprite(); + if (completion) { + completion(null); + } + } + } +} + +var posAttributes = performance$1.createLayout([ + { name: 'a_pos', type: 'Int16', components: 2 } +]); + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var preludeFrag = '#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\n'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var preludeVert = '#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture2D(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture2D(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var backgroundFrag = 'uniform vec4 u_color;uniform float u_opacity;void main() {gl_FragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var backgroundVert = 'attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var backgroundPatternFrag = 'uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var backgroundPatternVert = 'uniform mat4 u_matrix;uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var circleFrag = 'varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);lowp float antialiasblur=v_data.z;float antialiased_blur=-max(blur,antialiasblur);float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));gl_FragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var circleVert = 'uniform mat4 u_matrix;uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);float ele=get_elevation(circle_center);v_visibility=calculate_visibility(u_matrix*vec4(circle_center,ele,1.0));if (u_pitch_with_map) {vec2 corner_position=circle_center;if (u_scale_with_map) {corner_position+=extrude*(radius+stroke_width)*u_extrude_scale;} else {vec4 projected_center=u_matrix*vec4(circle_center,0,1);corner_position+=extrude*(radius+stroke_width)*u_extrude_scale*(projected_center.w/u_camera_to_center_distance);}gl_Position=u_matrix*vec4(corner_position,ele,1);} else {gl_Position=u_matrix*vec4(circle_center,ele,1);if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var clippingMaskFrag = 'void main() {gl_FragColor=vec4(1.0);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var clippingMaskVert = 'attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var heatmapFrag = 'uniform highp float u_intensity;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);gl_FragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var heatmapVert = 'uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec4 pos=vec4(floor(a_pos*0.5)+extrude,get_elevation(floor(a_pos*0.5)),1);gl_Position=u_matrix*pos;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var heatmapTextureFrag = 'uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(0.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var heatmapTextureVert = 'uniform mat4 u_matrix;uniform vec2 u_world;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var collisionBoxFrag = 'varying float v_placed;varying float v_notUsed;void main() {float alpha=0.5;gl_FragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var collisionBoxVert = 'attribute vec2 a_anchor_pos;attribute vec2 a_placed;attribute vec2 a_box_real;uniform mat4 u_matrix;uniform vec2 u_pixel_extrude_scale;varying float v_placed;varying float v_notUsed;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var collisionCircleFrag = 'varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var collisionCircleVert = 'attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var debugFrag = 'uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var debugVert = 'attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,get_elevation(a_pos),1);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillFrag = '#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillVert = 'attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillOutlineFrag = 'varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillOutlineVert = 'attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillOutlinePatternFrag = 'uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillOutlinePatternVert = 'uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillPatternFrag = '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillPatternVert = 'uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillExtrusionFrag = 'varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillExtrusionVert = 'uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillExtrusionPatternFrag = 'uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillExtrusionPatternVert = 'uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var hillshadePrepareFrag = '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var hillshadePrepareVert = 'uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var hillshadeFrag = 'uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var hillshadeVert = 'uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineFrag = 'uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineVert = '\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineGradientFrag = 'uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,v_uv);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineGradientVert = '\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;attribute float a_uv_x;attribute float a_split_index;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var linePatternFrag = '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var linePatternVert = '\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineSDFFrag = 'uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineSDFVert = '\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var rasterFrag = 'uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var rasterVert = 'uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolIconFrag = 'uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolIconVert = 'attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_tex;varying float v_fade_opacity;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolSDFFrag = '#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_2;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nfloat median(vec3 values) {return max(min(values.r,values.g),min(max(values.r,values.g),values.b));}float screenPxRange(float fontScale) {return fontScale*SDF_PX;}vec4 renderText(vec4 fill_color,vec4 halo_color,float opacity,float halo_width,float halo_blur,float EDGE_GAMMA,vec2 tex,float gamma_scale,float size,float fade_opacity) {float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}return color*(alpha*opacity*fade_opacity);}vec4 renderMSDFIcon(vec4 fill_color,vec4 halo_color,float opacity,float EDGE_GAMMA,vec2 tex,float gamma_scale,float size,float fade_opacity) {float fontScale=size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;vec3 s=texture2D(u_texture,tex).rgb;float sd=median(s);float dist=sd-0.5;if (u_is_halo) {color=halo_color;s=texture2D(u_texture_2,tex).rgb;sd=median(s);dist=sd-0.5;}float clampedDistance=clamp(dist*screenPxRange(fontScale)+0.5,0.0,1.0);highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,clampedDistance);return color*(alpha*opacity*fade_opacity);}void main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];gl_FragColor=u_is_text ? renderText(fill_color,halo_color,opacity,halo_width,halo_blur,EDGE_GAMMA,tex,gamma_scale,size,fade_opacity) : renderMSDFIcon(fill_color,halo_color,opacity,EDGE_GAMMA,tex,gamma_scale,size,fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolSDFVert = 'attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_data0;varying vec3 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolTextAndIconFrag = '#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolTextAndIconVert = 'attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec4 v_data0;varying vec4 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainDepthFrag = 'varying float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {gl_FragColor=pack(v_depth);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainCoordsFrag = 'precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;varying vec2 v_texture_pos;void main() {vec4 rgba=texture2D(u_texture,v_texture_pos);gl_FragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainFrag = 'uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;varying vec2 v_texture_pos;varying float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture2D(u_texture,v_texture_pos);if (v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);gl_FragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {gl_FragColor=surface_color;}}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainDepthVert = 'attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);v_depth=gl_Position.z/gl_Position.w;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainCoordsVert = 'attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainVert = 'attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform mat4 u_fog_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;varying float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var skyFrag = 'uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform float u_horizon;uniform float u_sky_horizon_blend;void main() {float y=gl_FragCoord.y;if (y > u_horizon) {float blend=y-u_horizon;if (blend < u_sky_horizon_blend) {gl_FragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {gl_FragColor=u_sky_color;}}}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var skyVert = 'attribute vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}'; + +// Disable Flow annotations here because Flow doesn't support importing GLSL files +const shaders = { + prelude: compile(preludeFrag, preludeVert), + background: compile(backgroundFrag, backgroundVert), + backgroundPattern: compile(backgroundPatternFrag, backgroundPatternVert), + circle: compile(circleFrag, circleVert), + clippingMask: compile(clippingMaskFrag, clippingMaskVert), + heatmap: compile(heatmapFrag, heatmapVert), + heatmapTexture: compile(heatmapTextureFrag, heatmapTextureVert), + collisionBox: compile(collisionBoxFrag, collisionBoxVert), + collisionCircle: compile(collisionCircleFrag, collisionCircleVert), + debug: compile(debugFrag, debugVert), + fill: compile(fillFrag, fillVert), + fillOutline: compile(fillOutlineFrag, fillOutlineVert), + fillOutlinePattern: compile(fillOutlinePatternFrag, fillOutlinePatternVert), + fillPattern: compile(fillPatternFrag, fillPatternVert), + fillExtrusion: compile(fillExtrusionFrag, fillExtrusionVert), + fillExtrusionPattern: compile(fillExtrusionPatternFrag, fillExtrusionPatternVert), + hillshadePrepare: compile(hillshadePrepareFrag, hillshadePrepareVert), + hillshade: compile(hillshadeFrag, hillshadeVert), + line: compile(lineFrag, lineVert), + lineGradient: compile(lineGradientFrag, lineGradientVert), + linePattern: compile(linePatternFrag, linePatternVert), + lineSDF: compile(lineSDFFrag, lineSDFVert), + raster: compile(rasterFrag, rasterVert), + symbolIcon: compile(symbolIconFrag, symbolIconVert), + symbolSDF: compile(symbolSDFFrag, symbolSDFVert), + symbolTextAndIcon: compile(symbolTextAndIconFrag, symbolTextAndIconVert), + terrain: compile(terrainFrag, terrainVert), + terrainDepth: compile(terrainDepthFrag, terrainDepthVert), + terrainCoords: compile(terrainCoordsFrag, terrainCoordsVert), + sky: compile(skyFrag, skyVert) +}; +// Expand #pragmas to #ifdefs. +function compile(fragmentSource, vertexSource) { + const re = /#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g; + const staticAttributes = vertexSource.match(/attribute ([\w]+) ([\w]+)/g); + const fragmentUniforms = fragmentSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g); + const vertexUniforms = vertexSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g); + const staticUniforms = vertexUniforms ? vertexUniforms.concat(fragmentUniforms) : fragmentUniforms; + const fragmentPragmas = {}; + fragmentSource = fragmentSource.replace(re, (match, operation, precision, type, name) => { + fragmentPragmas[name] = true; + if (operation === 'define') { + return ` +#ifndef HAS_UNIFORM_u_${name} +varying ${precision} ${type} ${name}; +#else +uniform ${precision} ${type} u_${name}; +#endif +`; + } + else /* if (operation === 'initialize') */ { + return ` +#ifdef HAS_UNIFORM_u_${name} + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + }); + vertexSource = vertexSource.replace(re, (match, operation, precision, type, name) => { + const attrType = type === 'float' ? 'vec2' : 'vec4'; + const unpackType = name.match(/color/) ? 'color' : attrType; + if (fragmentPragmas[name]) { + if (operation === 'define') { + return ` +#ifndef HAS_UNIFORM_u_${name} +uniform lowp float u_${name}_t; +attribute ${precision} ${attrType} a_${name}; +varying ${precision} ${type} ${name}; +#else +uniform ${precision} ${type} u_${name}; +#endif +`; + } + else /* if (operation === 'initialize') */ { + if (unpackType === 'vec4') { + // vec4 attributes are only used for cross-faded properties, and are not packed + return ` +#ifndef HAS_UNIFORM_u_${name} + ${name} = a_${name}; +#else + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + else { + return ` +#ifndef HAS_UNIFORM_u_${name} + ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t); +#else + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + } + } + else { + if (operation === 'define') { + return ` +#ifndef HAS_UNIFORM_u_${name} +uniform lowp float u_${name}_t; +attribute ${precision} ${attrType} a_${name}; +#else +uniform ${precision} ${type} u_${name}; +#endif +`; + } + else /* if (operation === 'initialize') */ { + if (unpackType === 'vec4') { + // vec4 attributes are only used for cross-faded properties, and are not packed + return ` +#ifndef HAS_UNIFORM_u_${name} + ${precision} ${type} ${name} = a_${name}; +#else + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + else /* */ { + return ` +#ifndef HAS_UNIFORM_u_${name} + ${precision} ${type} ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t); +#else + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + } + } + }); + return { fragmentSource, vertexSource, staticAttributes, staticUniforms }; +} + +/** + * @internal + * A vertex array object used to pass data to the webgl code + */ +class VertexArrayObject { + constructor() { + this.boundProgram = null; + this.boundLayoutVertexBuffer = null; + this.boundPaintVertexBuffers = []; + this.boundIndexBuffer = null; + this.boundVertexOffset = null; + this.boundDynamicVertexBuffer = null; + this.vao = null; + } + bind(context, program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3) { + this.context = context; + let paintBuffersDiffer = this.boundPaintVertexBuffers.length !== paintVertexBuffers.length; + for (let i = 0; !paintBuffersDiffer && i < paintVertexBuffers.length; i++) { + if (this.boundPaintVertexBuffers[i] !== paintVertexBuffers[i]) { + paintBuffersDiffer = true; + } + } + const isFreshBindRequired = (!this.vao || + this.boundProgram !== program || + this.boundLayoutVertexBuffer !== layoutVertexBuffer || + paintBuffersDiffer || + this.boundIndexBuffer !== indexBuffer || + this.boundVertexOffset !== vertexOffset || + this.boundDynamicVertexBuffer !== dynamicVertexBuffer || + this.boundDynamicVertexBuffer2 !== dynamicVertexBuffer2 || + this.boundDynamicVertexBuffer3 !== dynamicVertexBuffer3); + if (isFreshBindRequired) { + this.freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3); + } + else { + context.bindVertexArray.set(this.vao); + if (dynamicVertexBuffer) { + // The buffer may have been updated. Rebind to upload data. + dynamicVertexBuffer.bind(); + } + if (indexBuffer && indexBuffer.dynamicDraw) { + indexBuffer.bind(); + } + if (dynamicVertexBuffer2) { + dynamicVertexBuffer2.bind(); + } + if (dynamicVertexBuffer3) { + dynamicVertexBuffer3.bind(); + } + } + } + freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3) { + const numNextAttributes = program.numAttributes; + const context = this.context; + const gl = context.gl; + if (this.vao) + this.destroy(); + this.vao = context.createVertexArray(); + context.bindVertexArray.set(this.vao); + // store the arguments so that we can verify them when the vao is bound again + this.boundProgram = program; + this.boundLayoutVertexBuffer = layoutVertexBuffer; + this.boundPaintVertexBuffers = paintVertexBuffers; + this.boundIndexBuffer = indexBuffer; + this.boundVertexOffset = vertexOffset; + this.boundDynamicVertexBuffer = dynamicVertexBuffer; + this.boundDynamicVertexBuffer2 = dynamicVertexBuffer2; + this.boundDynamicVertexBuffer3 = dynamicVertexBuffer3; + layoutVertexBuffer.enableAttributes(gl, program); + for (const vertexBuffer of paintVertexBuffers) { + vertexBuffer.enableAttributes(gl, program); + } + if (dynamicVertexBuffer) { + dynamicVertexBuffer.enableAttributes(gl, program); + } + if (dynamicVertexBuffer2) { + dynamicVertexBuffer2.enableAttributes(gl, program); + } + if (dynamicVertexBuffer3) { + dynamicVertexBuffer3.enableAttributes(gl, program); + } + layoutVertexBuffer.bind(); + layoutVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset); + for (const vertexBuffer of paintVertexBuffers) { + vertexBuffer.bind(); + vertexBuffer.setVertexAttribPointers(gl, program, vertexOffset); + } + if (dynamicVertexBuffer) { + dynamicVertexBuffer.bind(); + dynamicVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset); + } + if (indexBuffer) { + indexBuffer.bind(); + } + if (dynamicVertexBuffer2) { + dynamicVertexBuffer2.bind(); + dynamicVertexBuffer2.setVertexAttribPointers(gl, program, vertexOffset); + } + if (dynamicVertexBuffer3) { + dynamicVertexBuffer3.bind(); + dynamicVertexBuffer3.setVertexAttribPointers(gl, program, vertexOffset); + } + context.currentNumAttributes = numNextAttributes; + } + destroy() { + if (this.vao) { + this.context.deleteVertexArray(this.vao); + this.vao = null; + } + } +} + +const terrainPreludeUniforms = (context, locations) => ({ + 'u_depth': new performance$1.Uniform1i(context, locations.u_depth), + 'u_terrain': new performance$1.Uniform1i(context, locations.u_terrain), + 'u_terrain_dim': new performance$1.Uniform1f(context, locations.u_terrain_dim), + 'u_terrain_matrix': new performance$1.UniformMatrix4f(context, locations.u_terrain_matrix), + 'u_terrain_unpack': new performance$1.Uniform4f(context, locations.u_terrain_unpack), + 'u_terrain_exaggeration': new performance$1.Uniform1f(context, locations.u_terrain_exaggeration) +}); +const terrainUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_texture': new performance$1.Uniform1i(context, locations.u_texture), + 'u_ele_delta': new performance$1.Uniform1f(context, locations.u_ele_delta), + 'u_fog_matrix': new performance$1.UniformMatrix4f(context, locations.u_fog_matrix), + 'u_fog_color': new performance$1.UniformColor(context, locations.u_fog_color), + 'u_fog_ground_blend': new performance$1.Uniform1f(context, locations.u_fog_ground_blend), + 'u_fog_ground_blend_opacity': new performance$1.Uniform1f(context, locations.u_fog_ground_blend_opacity), + 'u_horizon_color': new performance$1.UniformColor(context, locations.u_horizon_color), + 'u_horizon_fog_blend': new performance$1.Uniform1f(context, locations.u_horizon_fog_blend) +}); +const terrainDepthUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_ele_delta': new performance$1.Uniform1f(context, locations.u_ele_delta) +}); +const terrainCoordsUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_texture': new performance$1.Uniform1i(context, locations.u_texture), + 'u_terrain_coords_id': new performance$1.Uniform1f(context, locations.u_terrain_coords_id), + 'u_ele_delta': new performance$1.Uniform1f(context, locations.u_ele_delta) +}); +const terrainUniformValues = (matrix, eleDelta, fogMatrix, sky, pitch) => ({ + 'u_matrix': matrix, + 'u_texture': 0, + 'u_ele_delta': eleDelta, + 'u_fog_matrix': fogMatrix, + 'u_fog_color': sky ? sky.properties.get('fog-color') : performance$1.Color.white, + 'u_fog_ground_blend': sky ? sky.properties.get('fog-ground-blend') : 1, + 'u_fog_ground_blend_opacity': sky ? sky.calculateFogBlendOpacity(pitch) : 0, + 'u_horizon_color': sky ? sky.properties.get('horizon-color') : performance$1.Color.white, + 'u_horizon_fog_blend': sky ? sky.properties.get('horizon-fog-blend') : 1 +}); +const terrainDepthUniformValues = (matrix, eleDelta) => ({ + 'u_matrix': matrix, + 'u_ele_delta': eleDelta +}); +const terrainCoordsUniformValues = (matrix, coordsId, eleDelta) => ({ + 'u_matrix': matrix, + 'u_terrain_coords_id': coordsId / 255, + 'u_texture': 0, + 'u_ele_delta': eleDelta +}); + +function getTokenizedAttributesAndUniforms(array) { + const result = []; + for (let i = 0; i < array.length; i++) { + if (array[i] === null) + continue; + const token = array[i].split(' '); + result.push(token.pop()); + } + return result; +} +/** + * @internal + * A webgl program to execute in the GPU space + */ +class Program { + constructor(context, source, configuration, fixedUniforms, showOverdrawInspector, terrain) { + const gl = context.gl; + this.program = gl.createProgram(); + const staticAttrInfo = getTokenizedAttributesAndUniforms(source.staticAttributes); + const dynamicAttrInfo = configuration ? configuration.getBinderAttributes() : []; + const allAttrInfo = staticAttrInfo.concat(dynamicAttrInfo); + const preludeUniformsInfo = shaders.prelude.staticUniforms ? getTokenizedAttributesAndUniforms(shaders.prelude.staticUniforms) : []; + const staticUniformsInfo = source.staticUniforms ? getTokenizedAttributesAndUniforms(source.staticUniforms) : []; + const dynamicUniformsInfo = configuration ? configuration.getBinderUniforms() : []; + // remove duplicate uniforms + const uniformList = preludeUniformsInfo.concat(staticUniformsInfo).concat(dynamicUniformsInfo); + const allUniformsInfo = []; + for (const uniform of uniformList) { + if (allUniformsInfo.indexOf(uniform) < 0) + allUniformsInfo.push(uniform); + } + const defines = configuration ? configuration.defines() : []; + if (showOverdrawInspector) { + defines.push('#define OVERDRAW_INSPECTOR;'); + } + if (terrain) { + defines.push('#define TERRAIN3D;'); + } + const fragmentSource = defines.concat(shaders.prelude.fragmentSource, source.fragmentSource).join('\n'); + const vertexSource = defines.concat(shaders.prelude.vertexSource, source.vertexSource).join('\n'); + const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); + if (gl.isContextLost()) { + this.failedToCreate = true; + return; + } + gl.shaderSource(fragmentShader, fragmentSource); + gl.compileShader(fragmentShader); + if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) { + console.log(gl.getShaderInfoLog(fragmentShader)); + throw new Error(`Could not compile fragment shader:`); + } + gl.attachShader(this.program, fragmentShader); + const vertexShader = gl.createShader(gl.VERTEX_SHADER); + if (gl.isContextLost()) { + this.failedToCreate = true; + return; + } + gl.shaderSource(vertexShader, vertexSource); + gl.compileShader(vertexShader); + if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) { + throw new Error(`Could not compile vertex shader: ${gl.getShaderInfoLog(vertexShader)}`); + } + gl.attachShader(this.program, vertexShader); + this.attributes = {}; + const uniformLocations = {}; + this.numAttributes = allAttrInfo.length; + for (let i = 0; i < this.numAttributes; i++) { + if (allAttrInfo[i]) { + gl.bindAttribLocation(this.program, i, allAttrInfo[i]); + this.attributes[allAttrInfo[i]] = i; + } + } + gl.linkProgram(this.program); + if (!gl.getProgramParameter(this.program, gl.LINK_STATUS)) { + console.log(gl.getProgramInfoLog(this.program)); + throw new Error(`Program failed to link:`); + } + gl.deleteShader(vertexShader); + gl.deleteShader(fragmentShader); + for (let it = 0; it < allUniformsInfo.length; it++) { + const uniform = allUniformsInfo[it]; + if (uniform && !uniformLocations[uniform]) { + const uniformLocation = gl.getUniformLocation(this.program, uniform); + if (uniformLocation) { + uniformLocations[uniform] = uniformLocation; + } + } + } + this.fixedUniforms = fixedUniforms(context, uniformLocations); + this.terrainUniforms = terrainPreludeUniforms(context, uniformLocations); + this.binderUniforms = configuration ? configuration.getUniforms(context, uniformLocations) : []; + } + draw(context, drawMode, depthMode, stencilMode, colorMode, cullFaceMode, uniformValues, terrain, layerID, layoutVertexBuffer, indexBuffer, segments, currentProperties, zoom, configuration, dynamicLayoutBuffer, dynamicLayoutBuffer2, dynamicLayoutBuffer3) { + const gl = context.gl; + if (this.failedToCreate) + return; + context.program.set(this.program); + context.setDepthMode(depthMode); + context.setStencilMode(stencilMode); + context.setColorMode(colorMode); + context.setCullFace(cullFaceMode); + // set variables used by the 3d functions defined in _prelude.vertex.glsl + if (terrain) { + context.activeTexture.set(gl.TEXTURE2); + gl.bindTexture(gl.TEXTURE_2D, terrain.depthTexture); + context.activeTexture.set(gl.TEXTURE3); + gl.bindTexture(gl.TEXTURE_2D, terrain.texture); + for (const name in this.terrainUniforms) { + this.terrainUniforms[name].set(terrain[name]); + } + } + for (const name in this.fixedUniforms) { + this.fixedUniforms[name].set(uniformValues[name]); + } + if (configuration) { + configuration.setUniforms(context, this.binderUniforms, currentProperties, { zoom: zoom }); + } + let primitiveSize = 0; + switch (drawMode) { + case gl.LINES: + primitiveSize = 2; + break; + case gl.TRIANGLES: + primitiveSize = 3; + break; + case gl.LINE_STRIP: + primitiveSize = 1; + break; + } + for (const segment of segments.get()) { + const vaos = segment.vaos || (segment.vaos = {}); + const vao = vaos[layerID] || (vaos[layerID] = new VertexArrayObject()); + vao.bind(context, this, layoutVertexBuffer, configuration ? configuration.getPaintVertexBuffers() : [], indexBuffer, segment.vertexOffset, dynamicLayoutBuffer, dynamicLayoutBuffer2, dynamicLayoutBuffer3); + gl.drawElements(drawMode, segment.primitiveLength * primitiveSize, gl.UNSIGNED_SHORT, segment.primitiveOffset * primitiveSize * 2); + } + } +} + +function patternUniformValues(crossfade, painter, tile) { + const tileRatio = 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom); + const numTiles = Math.pow(2, tile.tileID.overscaledZ); + const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles; + const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles); + const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y; + return { + 'u_image': 0, + 'u_texsize': tile.imageAtlasTexture.size, + 'u_scale': [tileRatio, crossfade.fromScale, crossfade.toScale], + 'u_fade': crossfade.t, + // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision. + 'u_pixel_coord_upper': [pixelX >> 16, pixelY >> 16], + 'u_pixel_coord_lower': [pixelX & 0xFFFF, pixelY & 0xFFFF] + }; +} +function bgPatternUniformValues(image, crossfade, painter, tile) { + const imagePosA = painter.imageManager.getPattern(image.from.toString()); + const imagePosB = painter.imageManager.getPattern(image.to.toString()); + const { width, height } = painter.imageManager.getPixelSize(); + const numTiles = Math.pow(2, tile.tileID.overscaledZ); + const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles; + const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles); + const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y; + return { + 'u_image': 0, + 'u_pattern_tl_a': imagePosA.tl, + 'u_pattern_br_a': imagePosA.br, + 'u_pattern_tl_b': imagePosB.tl, + 'u_pattern_br_b': imagePosB.br, + 'u_texsize': [width, height], + 'u_mix': crossfade.t, + 'u_pattern_size_a': imagePosA.displaySize, + 'u_pattern_size_b': imagePosB.displaySize, + 'u_scale_a': crossfade.fromScale, + 'u_scale_b': crossfade.toScale, + 'u_tile_units_to_pixels': 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom), + // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision. + 'u_pixel_coord_upper': [pixelX >> 16, pixelY >> 16], + 'u_pixel_coord_lower': [pixelX & 0xFFFF, pixelY & 0xFFFF] + }; +} + +const fillExtrusionUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_lightpos': new performance$1.Uniform3f(context, locations.u_lightpos), + 'u_lightintensity': new performance$1.Uniform1f(context, locations.u_lightintensity), + 'u_lightcolor': new performance$1.Uniform3f(context, locations.u_lightcolor), + 'u_vertical_gradient': new performance$1.Uniform1f(context, locations.u_vertical_gradient), + 'u_opacity': new performance$1.Uniform1f(context, locations.u_opacity) +}); +const fillExtrusionPatternUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_lightpos': new performance$1.Uniform3f(context, locations.u_lightpos), + 'u_lightintensity': new performance$1.Uniform1f(context, locations.u_lightintensity), + 'u_lightcolor': new performance$1.Uniform3f(context, locations.u_lightcolor), + 'u_vertical_gradient': new performance$1.Uniform1f(context, locations.u_vertical_gradient), + 'u_height_factor': new performance$1.Uniform1f(context, locations.u_height_factor), + // pattern uniforms + 'u_image': new performance$1.Uniform1i(context, locations.u_image), + 'u_texsize': new performance$1.Uniform2f(context, locations.u_texsize), + 'u_pixel_coord_upper': new performance$1.Uniform2f(context, locations.u_pixel_coord_upper), + 'u_pixel_coord_lower': new performance$1.Uniform2f(context, locations.u_pixel_coord_lower), + 'u_scale': new performance$1.Uniform3f(context, locations.u_scale), + 'u_fade': new performance$1.Uniform1f(context, locations.u_fade), + 'u_opacity': new performance$1.Uniform1f(context, locations.u_opacity) +}); +const fillExtrusionUniformValues = (matrix, painter, shouldUseVerticalGradient, opacity) => { + const light = painter.style.light; + const _lp = light.properties.get('position'); + const lightPos = [_lp.x, _lp.y, _lp.z]; + const lightMat = performance$1.create$1(); + if (light.properties.get('anchor') === 'viewport') { + performance$1.fromRotation(lightMat, -painter.transform.angle); + } + performance$1.transformMat3(lightPos, lightPos, lightMat); + const lightColor = light.properties.get('color'); + return { + 'u_matrix': matrix, + 'u_lightpos': lightPos, + 'u_lightintensity': light.properties.get('intensity'), + 'u_lightcolor': [lightColor.r, lightColor.g, lightColor.b], + 'u_vertical_gradient': +shouldUseVerticalGradient, + 'u_opacity': opacity + }; +}; +const fillExtrusionPatternUniformValues = (matrix, painter, shouldUseVerticalGradient, opacity, coord, crossfade, tile) => { + return performance$1.extend(fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity), patternUniformValues(crossfade, painter, tile), { + 'u_height_factor': -Math.pow(2, coord.overscaledZ) / tile.tileSize / 8 + }); +}; + +const fillUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix) +}); +const fillPatternUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_image': new performance$1.Uniform1i(context, locations.u_image), + 'u_texsize': new performance$1.Uniform2f(context, locations.u_texsize), + 'u_pixel_coord_upper': new performance$1.Uniform2f(context, locations.u_pixel_coord_upper), + 'u_pixel_coord_lower': new performance$1.Uniform2f(context, locations.u_pixel_coord_lower), + 'u_scale': new performance$1.Uniform3f(context, locations.u_scale), + 'u_fade': new performance$1.Uniform1f(context, locations.u_fade) +}); +const fillOutlineUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_world': new performance$1.Uniform2f(context, locations.u_world) +}); +const fillOutlinePatternUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_world': new performance$1.Uniform2f(context, locations.u_world), + 'u_image': new performance$1.Uniform1i(context, locations.u_image), + 'u_texsize': new performance$1.Uniform2f(context, locations.u_texsize), + 'u_pixel_coord_upper': new performance$1.Uniform2f(context, locations.u_pixel_coord_upper), + 'u_pixel_coord_lower': new performance$1.Uniform2f(context, locations.u_pixel_coord_lower), + 'u_scale': new performance$1.Uniform3f(context, locations.u_scale), + 'u_fade': new performance$1.Uniform1f(context, locations.u_fade) +}); +const fillUniformValues = (matrix) => ({ + 'u_matrix': matrix +}); +const fillPatternUniformValues = (matrix, painter, crossfade, tile) => performance$1.extend(fillUniformValues(matrix), patternUniformValues(crossfade, painter, tile)); +const fillOutlineUniformValues = (matrix, drawingBufferSize) => ({ + 'u_matrix': matrix, + 'u_world': drawingBufferSize +}); +const fillOutlinePatternUniformValues = (matrix, painter, crossfade, tile, drawingBufferSize) => performance$1.extend(fillPatternUniformValues(matrix, painter, crossfade, tile), { + 'u_world': drawingBufferSize +}); + +const circleUniforms = (context, locations) => ({ + 'u_camera_to_center_distance': new performance$1.Uniform1f(context, locations.u_camera_to_center_distance), + 'u_scale_with_map': new performance$1.Uniform1i(context, locations.u_scale_with_map), + 'u_pitch_with_map': new performance$1.Uniform1i(context, locations.u_pitch_with_map), + 'u_extrude_scale': new performance$1.Uniform2f(context, locations.u_extrude_scale), + 'u_device_pixel_ratio': new performance$1.Uniform1f(context, locations.u_device_pixel_ratio), + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix) +}); +const circleUniformValues = (painter, coord, tile, layer) => { + const transform = painter.transform; + let pitchWithMap, extrudeScale; + if (layer.paint.get('circle-pitch-alignment') === 'map') { + const pixelRatio = pixelsToTileUnits(tile, 1, transform.zoom); + pitchWithMap = true; + extrudeScale = [pixelRatio, pixelRatio]; + } + else { + pitchWithMap = false; + extrudeScale = transform.pixelsToGLUnits; + } + return { + 'u_camera_to_center_distance': transform.cameraToCenterDistance, + 'u_scale_with_map': +(layer.paint.get('circle-pitch-scale') === 'map'), + 'u_matrix': painter.translatePosMatrix(coord.posMatrix, tile, layer.paint.get('circle-translate'), layer.paint.get('circle-translate-anchor')), + 'u_pitch_with_map': +(pitchWithMap), + 'u_device_pixel_ratio': painter.pixelRatio, + 'u_extrude_scale': extrudeScale + }; +}; + +const collisionUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_pixel_extrude_scale': new performance$1.Uniform2f(context, locations.u_pixel_extrude_scale) +}); +const collisionCircleUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_inv_matrix': new performance$1.UniformMatrix4f(context, locations.u_inv_matrix), + 'u_camera_to_center_distance': new performance$1.Uniform1f(context, locations.u_camera_to_center_distance), + 'u_viewport_size': new performance$1.Uniform2f(context, locations.u_viewport_size) +}); +const collisionUniformValues = (transform, matrix) => { + return { + 'u_matrix': matrix, + 'u_pixel_extrude_scale': [1.0 / transform.width, 1.0 / transform.height], + }; +}; +const collisionCircleUniformValues = (matrix, invMatrix, transform) => { + return { + 'u_matrix': matrix, + 'u_inv_matrix': invMatrix, + 'u_camera_to_center_distance': transform.cameraToCenterDistance, + 'u_viewport_size': [transform.width, transform.height] + }; +}; + +const debugUniforms = (context, locations) => ({ + 'u_color': new performance$1.UniformColor(context, locations.u_color), + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_overlay': new performance$1.Uniform1i(context, locations.u_overlay), + 'u_overlay_scale': new performance$1.Uniform1f(context, locations.u_overlay_scale) +}); +const debugUniformValues = (matrix, color, scaleRatio = 1) => ({ + 'u_matrix': matrix, + 'u_color': color, + 'u_overlay': 0, + 'u_overlay_scale': scaleRatio +}); + +const clippingMaskUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix) +}); +const clippingMaskUniformValues = (matrix) => ({ + 'u_matrix': matrix +}); + +const heatmapUniforms = (context, locations) => ({ + 'u_extrude_scale': new performance$1.Uniform1f(context, locations.u_extrude_scale), + 'u_intensity': new performance$1.Uniform1f(context, locations.u_intensity), + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix) +}); +const heatmapTextureUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_world': new performance$1.Uniform2f(context, locations.u_world), + 'u_image': new performance$1.Uniform1i(context, locations.u_image), + 'u_color_ramp': new performance$1.Uniform1i(context, locations.u_color_ramp), + 'u_opacity': new performance$1.Uniform1f(context, locations.u_opacity) +}); +const heatmapUniformValues = (matrix, tile, zoom, intensity) => ({ + 'u_matrix': matrix, + 'u_extrude_scale': pixelsToTileUnits(tile, 1, zoom), + 'u_intensity': intensity +}); +const heatmapTextureUniformValues = (painter, layer, textureUnit, colorRampUnit) => { + const matrix = performance$1.create(); + performance$1.ortho(matrix, 0, painter.width, painter.height, 0, 0, 1); + const gl = painter.context.gl; + return { + 'u_matrix': matrix, + 'u_world': [gl.drawingBufferWidth, gl.drawingBufferHeight], + 'u_image': textureUnit, + 'u_color_ramp': colorRampUnit, + 'u_opacity': layer.paint.get('heatmap-opacity') + }; +}; + +const hillshadeUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_image': new performance$1.Uniform1i(context, locations.u_image), + 'u_latrange': new performance$1.Uniform2f(context, locations.u_latrange), + 'u_light': new performance$1.Uniform2f(context, locations.u_light), + 'u_shadow': new performance$1.UniformColor(context, locations.u_shadow), + 'u_highlight': new performance$1.UniformColor(context, locations.u_highlight), + 'u_accent': new performance$1.UniformColor(context, locations.u_accent) +}); +const hillshadePrepareUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_image': new performance$1.Uniform1i(context, locations.u_image), + 'u_dimension': new performance$1.Uniform2f(context, locations.u_dimension), + 'u_zoom': new performance$1.Uniform1f(context, locations.u_zoom), + 'u_unpack': new performance$1.Uniform4f(context, locations.u_unpack) +}); +const hillshadeUniformValues = (painter, tile, layer, coord) => { + const shadow = layer.paint.get('hillshade-shadow-color'); + const highlight = layer.paint.get('hillshade-highlight-color'); + const accent = layer.paint.get('hillshade-accent-color'); + let azimuthal = layer.paint.get('hillshade-illumination-direction') * (Math.PI / 180); + // modify azimuthal angle by map rotation if light is anchored at the viewport + if (layer.paint.get('hillshade-illumination-anchor') === 'viewport') { + azimuthal -= painter.transform.angle; + } + const align = !painter.options.moving; + return { + 'u_matrix': coord ? coord.posMatrix : painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped(), align), + 'u_image': 0, + 'u_latrange': getTileLatRange(painter, tile.tileID), + 'u_light': [layer.paint.get('hillshade-exaggeration'), azimuthal], + 'u_shadow': shadow, + 'u_highlight': highlight, + 'u_accent': accent + }; +}; +const hillshadeUniformPrepareValues = (tileID, dem) => { + const stride = dem.stride; + const matrix = performance$1.create(); + // Flip rendering at y axis. + performance$1.ortho(matrix, 0, performance$1.EXTENT, -performance$1.EXTENT, 0, 0, 1); + performance$1.translate(matrix, matrix, [0, -performance$1.EXTENT, 0]); + return { + 'u_matrix': matrix, + 'u_image': 1, + 'u_dimension': [stride, stride], + 'u_zoom': tileID.overscaledZ, + 'u_unpack': dem.getUnpackVector() + }; +}; +function getTileLatRange(painter, tileID) { + // for scaling the magnitude of a points slope by its latitude + const tilesAtZoom = Math.pow(2, tileID.canonical.z); + const y = tileID.canonical.y; + return [ + new performance$1.MercatorCoordinate(0, y / tilesAtZoom).toLngLat().lat, + new performance$1.MercatorCoordinate(0, (y + 1) / tilesAtZoom).toLngLat().lat + ]; +} + +const lineUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_ratio': new performance$1.Uniform1f(context, locations.u_ratio), + 'u_device_pixel_ratio': new performance$1.Uniform1f(context, locations.u_device_pixel_ratio), + 'u_units_to_pixels': new performance$1.Uniform2f(context, locations.u_units_to_pixels) +}); +const lineGradientUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_ratio': new performance$1.Uniform1f(context, locations.u_ratio), + 'u_device_pixel_ratio': new performance$1.Uniform1f(context, locations.u_device_pixel_ratio), + 'u_units_to_pixels': new performance$1.Uniform2f(context, locations.u_units_to_pixels), + 'u_image': new performance$1.Uniform1i(context, locations.u_image), + 'u_image_height': new performance$1.Uniform1f(context, locations.u_image_height) +}); +const linePatternUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_texsize': new performance$1.Uniform2f(context, locations.u_texsize), + 'u_ratio': new performance$1.Uniform1f(context, locations.u_ratio), + 'u_device_pixel_ratio': new performance$1.Uniform1f(context, locations.u_device_pixel_ratio), + 'u_image': new performance$1.Uniform1i(context, locations.u_image), + 'u_units_to_pixels': new performance$1.Uniform2f(context, locations.u_units_to_pixels), + 'u_scale': new performance$1.Uniform3f(context, locations.u_scale), + 'u_fade': new performance$1.Uniform1f(context, locations.u_fade) +}); +const lineSDFUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_ratio': new performance$1.Uniform1f(context, locations.u_ratio), + 'u_device_pixel_ratio': new performance$1.Uniform1f(context, locations.u_device_pixel_ratio), + 'u_units_to_pixels': new performance$1.Uniform2f(context, locations.u_units_to_pixels), + 'u_patternscale_a': new performance$1.Uniform2f(context, locations.u_patternscale_a), + 'u_patternscale_b': new performance$1.Uniform2f(context, locations.u_patternscale_b), + 'u_sdfgamma': new performance$1.Uniform1f(context, locations.u_sdfgamma), + 'u_image': new performance$1.Uniform1i(context, locations.u_image), + 'u_tex_y_a': new performance$1.Uniform1f(context, locations.u_tex_y_a), + 'u_tex_y_b': new performance$1.Uniform1f(context, locations.u_tex_y_b), + 'u_mix': new performance$1.Uniform1f(context, locations.u_mix) +}); +const lineUniformValues = (painter, tile, layer, coord) => { + const transform = painter.transform; + return { + 'u_matrix': calculateMatrix(painter, tile, layer, coord), + 'u_ratio': 1 / pixelsToTileUnits(tile, 1, transform.zoom), + 'u_device_pixel_ratio': painter.pixelRatio, + 'u_units_to_pixels': [ + 1 / transform.pixelsToGLUnits[0], + 1 / transform.pixelsToGLUnits[1] + ] + }; +}; +const lineGradientUniformValues = (painter, tile, layer, imageHeight, coord) => { + return performance$1.extend(lineUniformValues(painter, tile, layer, coord), { + 'u_image': 0, + 'u_image_height': imageHeight, + }); +}; +const linePatternUniformValues = (painter, tile, layer, crossfade, coord) => { + const transform = painter.transform; + const tileZoomRatio = calculateTileRatio(tile, transform); + return { + 'u_matrix': calculateMatrix(painter, tile, layer, coord), + 'u_texsize': tile.imageAtlasTexture.size, + // camera zoom ratio + 'u_ratio': 1 / pixelsToTileUnits(tile, 1, transform.zoom), + 'u_device_pixel_ratio': painter.pixelRatio, + 'u_image': 0, + 'u_scale': [tileZoomRatio, crossfade.fromScale, crossfade.toScale], + 'u_fade': crossfade.t, + 'u_units_to_pixels': [ + 1 / transform.pixelsToGLUnits[0], + 1 / transform.pixelsToGLUnits[1] + ] + }; +}; +const lineSDFUniformValues = (painter, tile, layer, dasharray, crossfade, coord) => { + const transform = painter.transform; + const lineAtlas = painter.lineAtlas; + const tileRatio = calculateTileRatio(tile, transform); + const round = layer.layout.get('line-cap') === 'round'; + const posA = lineAtlas.getDash(dasharray.from, round); + const posB = lineAtlas.getDash(dasharray.to, round); + const widthA = posA.width * crossfade.fromScale; + const widthB = posB.width * crossfade.toScale; + return performance$1.extend(lineUniformValues(painter, tile, layer, coord), { + 'u_patternscale_a': [tileRatio / widthA, -posA.height / 2], + 'u_patternscale_b': [tileRatio / widthB, -posB.height / 2], + 'u_sdfgamma': lineAtlas.width / (Math.min(widthA, widthB) * 256 * painter.pixelRatio) / 2, + 'u_image': 0, + 'u_tex_y_a': posA.y, + 'u_tex_y_b': posB.y, + 'u_mix': crossfade.t + }); +}; +function calculateTileRatio(tile, transform) { + return 1 / pixelsToTileUnits(tile, 1, transform.tileZoom); +} +function calculateMatrix(painter, tile, layer, coord) { + return painter.translatePosMatrix(coord ? coord.posMatrix : tile.tileID.posMatrix, tile, layer.paint.get('line-translate'), layer.paint.get('line-translate-anchor')); +} + +const rasterUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_tl_parent': new performance$1.Uniform2f(context, locations.u_tl_parent), + 'u_scale_parent': new performance$1.Uniform1f(context, locations.u_scale_parent), + 'u_buffer_scale': new performance$1.Uniform1f(context, locations.u_buffer_scale), + 'u_fade_t': new performance$1.Uniform1f(context, locations.u_fade_t), + 'u_opacity': new performance$1.Uniform1f(context, locations.u_opacity), + 'u_image0': new performance$1.Uniform1i(context, locations.u_image0), + 'u_image1': new performance$1.Uniform1i(context, locations.u_image1), + 'u_brightness_low': new performance$1.Uniform1f(context, locations.u_brightness_low), + 'u_brightness_high': new performance$1.Uniform1f(context, locations.u_brightness_high), + 'u_saturation_factor': new performance$1.Uniform1f(context, locations.u_saturation_factor), + 'u_contrast_factor': new performance$1.Uniform1f(context, locations.u_contrast_factor), + 'u_spin_weights': new performance$1.Uniform3f(context, locations.u_spin_weights) +}); +const rasterUniformValues = (matrix, parentTL, parentScaleBy, fade, layer) => ({ + 'u_matrix': matrix, + 'u_tl_parent': parentTL, + 'u_scale_parent': parentScaleBy, + 'u_buffer_scale': 1, + 'u_fade_t': fade.mix, + 'u_opacity': fade.opacity * layer.paint.get('raster-opacity'), + 'u_image0': 0, + 'u_image1': 1, + 'u_brightness_low': layer.paint.get('raster-brightness-min'), + 'u_brightness_high': layer.paint.get('raster-brightness-max'), + 'u_saturation_factor': saturationFactor(layer.paint.get('raster-saturation')), + 'u_contrast_factor': contrastFactor(layer.paint.get('raster-contrast')), + 'u_spin_weights': spinWeights(layer.paint.get('raster-hue-rotate')) +}); +function spinWeights(angle) { + angle *= Math.PI / 180; + const s = Math.sin(angle); + const c = Math.cos(angle); + return [ + (2 * c + 1) / 3, + (-Math.sqrt(3) * s - c + 1) / 3, + (Math.sqrt(3) * s - c + 1) / 3 + ]; +} +function contrastFactor(contrast) { + return contrast > 0 ? + 1 / (1 - contrast) : + 1 + contrast; +} +function saturationFactor(saturation) { + return saturation > 0 ? + 1 - 1 / (1.001 - saturation) : + -saturation; +} + +const symbolIconUniforms = (context, locations) => ({ + 'u_is_size_zoom_constant': new performance$1.Uniform1i(context, locations.u_is_size_zoom_constant), + 'u_is_size_feature_constant': new performance$1.Uniform1i(context, locations.u_is_size_feature_constant), + 'u_size_t': new performance$1.Uniform1f(context, locations.u_size_t), + 'u_size': new performance$1.Uniform1f(context, locations.u_size), + 'u_camera_to_center_distance': new performance$1.Uniform1f(context, locations.u_camera_to_center_distance), + 'u_pitch': new performance$1.Uniform1f(context, locations.u_pitch), + 'u_rotate_symbol': new performance$1.Uniform1i(context, locations.u_rotate_symbol), + 'u_aspect_ratio': new performance$1.Uniform1f(context, locations.u_aspect_ratio), + 'u_fade_change': new performance$1.Uniform1f(context, locations.u_fade_change), + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_label_plane_matrix': new performance$1.UniformMatrix4f(context, locations.u_label_plane_matrix), + 'u_coord_matrix': new performance$1.UniformMatrix4f(context, locations.u_coord_matrix), + 'u_is_text': new performance$1.Uniform1i(context, locations.u_is_text), + 'u_pitch_with_map': new performance$1.Uniform1i(context, locations.u_pitch_with_map), + 'u_is_along_line': new performance$1.Uniform1i(context, locations.u_is_along_line), + 'u_is_variable_anchor': new performance$1.Uniform1i(context, locations.u_is_variable_anchor), + 'u_texsize': new performance$1.Uniform2f(context, locations.u_texsize), + 'u_texture': new performance$1.Uniform1i(context, locations.u_texture), + 'u_translation': new performance$1.Uniform2f(context, locations.u_translation), + 'u_pitched_scale': new performance$1.Uniform1f(context, locations.u_pitched_scale), +}); +const symbolSDFUniforms = (context, locations) => ({ + 'u_is_size_zoom_constant': new performance$1.Uniform1i(context, locations.u_is_size_zoom_constant), + 'u_is_size_feature_constant': new performance$1.Uniform1i(context, locations.u_is_size_feature_constant), + 'u_size_t': new performance$1.Uniform1f(context, locations.u_size_t), + 'u_size': new performance$1.Uniform1f(context, locations.u_size), + 'u_camera_to_center_distance': new performance$1.Uniform1f(context, locations.u_camera_to_center_distance), + 'u_pitch': new performance$1.Uniform1f(context, locations.u_pitch), + 'u_rotate_symbol': new performance$1.Uniform1i(context, locations.u_rotate_symbol), + 'u_aspect_ratio': new performance$1.Uniform1f(context, locations.u_aspect_ratio), + 'u_fade_change': new performance$1.Uniform1f(context, locations.u_fade_change), + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_label_plane_matrix': new performance$1.UniformMatrix4f(context, locations.u_label_plane_matrix), + 'u_coord_matrix': new performance$1.UniformMatrix4f(context, locations.u_coord_matrix), + 'u_is_text': new performance$1.Uniform1i(context, locations.u_is_text), + 'u_pitch_with_map': new performance$1.Uniform1i(context, locations.u_pitch_with_map), + 'u_is_along_line': new performance$1.Uniform1i(context, locations.u_is_along_line), + 'u_is_variable_anchor': new performance$1.Uniform1i(context, locations.u_is_variable_anchor), + 'u_texsize': new performance$1.Uniform2f(context, locations.u_texsize), + 'u_texture': new performance$1.Uniform1i(context, locations.u_texture), + 'u_texture_2': new performance$1.Uniform1i(context, locations.u_texture_2), + 'u_gamma_scale': new performance$1.Uniform1f(context, locations.u_gamma_scale), + 'u_device_pixel_ratio': new performance$1.Uniform1f(context, locations.u_device_pixel_ratio), + 'u_is_halo': new performance$1.Uniform1i(context, locations.u_is_halo), + 'u_translation': new performance$1.Uniform2f(context, locations.u_translation), + 'u_pitched_scale': new performance$1.Uniform1f(context, locations.u_pitched_scale), +}); +const symbolTextAndIconUniforms = (context, locations) => ({ + 'u_is_size_zoom_constant': new performance$1.Uniform1i(context, locations.u_is_size_zoom_constant), + 'u_is_size_feature_constant': new performance$1.Uniform1i(context, locations.u_is_size_feature_constant), + 'u_size_t': new performance$1.Uniform1f(context, locations.u_size_t), + 'u_size': new performance$1.Uniform1f(context, locations.u_size), + 'u_camera_to_center_distance': new performance$1.Uniform1f(context, locations.u_camera_to_center_distance), + 'u_pitch': new performance$1.Uniform1f(context, locations.u_pitch), + 'u_rotate_symbol': new performance$1.Uniform1i(context, locations.u_rotate_symbol), + 'u_aspect_ratio': new performance$1.Uniform1f(context, locations.u_aspect_ratio), + 'u_fade_change': new performance$1.Uniform1f(context, locations.u_fade_change), + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_label_plane_matrix': new performance$1.UniformMatrix4f(context, locations.u_label_plane_matrix), + 'u_coord_matrix': new performance$1.UniformMatrix4f(context, locations.u_coord_matrix), + 'u_is_text': new performance$1.Uniform1i(context, locations.u_is_text), + 'u_pitch_with_map': new performance$1.Uniform1i(context, locations.u_pitch_with_map), + 'u_is_along_line': new performance$1.Uniform1i(context, locations.u_is_along_line), + 'u_is_variable_anchor': new performance$1.Uniform1i(context, locations.u_is_variable_anchor), + 'u_texsize': new performance$1.Uniform2f(context, locations.u_texsize), + 'u_texsize_icon': new performance$1.Uniform2f(context, locations.u_texsize_icon), + 'u_texture': new performance$1.Uniform1i(context, locations.u_texture), + 'u_texture_icon': new performance$1.Uniform1i(context, locations.u_texture_icon), + 'u_gamma_scale': new performance$1.Uniform1f(context, locations.u_gamma_scale), + 'u_device_pixel_ratio': new performance$1.Uniform1f(context, locations.u_device_pixel_ratio), + 'u_is_halo': new performance$1.Uniform1i(context, locations.u_is_halo), + 'u_translation': new performance$1.Uniform2f(context, locations.u_translation), + 'u_pitched_scale': new performance$1.Uniform1f(context, locations.u_pitched_scale), +}); +const symbolIconUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, pitchedScale) => { + const transform = painter.transform; + return { + 'u_is_size_zoom_constant': +(functionType === 'constant' || functionType === 'source'), + 'u_is_size_feature_constant': +(functionType === 'constant' || functionType === 'camera'), + 'u_size_t': size ? size.uSizeT : 0, + 'u_size': size ? size.uSize : 0, + 'u_camera_to_center_distance': transform.cameraToCenterDistance, + 'u_pitch': transform.pitch / 360 * 2 * Math.PI, + 'u_rotate_symbol': +rotateInShader, + 'u_aspect_ratio': transform.width / transform.height, + 'u_fade_change': painter.options.fadeDuration ? painter.symbolFadeChange : 1, + 'u_matrix': matrix, + 'u_label_plane_matrix': labelPlaneMatrix, + 'u_coord_matrix': glCoordMatrix, + 'u_is_text': +isText, + 'u_pitch_with_map': +pitchWithMap, + 'u_is_along_line': isAlongLine, + 'u_is_variable_anchor': isVariableAnchor, + 'u_texsize': texSize, + 'u_texture': 0, + 'u_translation': translation, + 'u_pitched_scale': pitchedScale + }; +}; +const symbolSDFUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, isHalo, pitchedScale) => { + const transform = painter.transform; + return performance$1.extend(symbolIconUniformValues(functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, pitchedScale), { + 'u_gamma_scale': (pitchWithMap ? Math.cos(transform._pitch) * transform.cameraToCenterDistance : 1), + 'u_device_pixel_ratio': painter.pixelRatio, + 'u_is_halo': +isHalo, + 'u_texture_2': 1 + }); +}; +const symbolTextAndIconUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, texSizeSDF, texSizeIcon, pitchedScale) => { + return performance$1.extend(symbolSDFUniformValues(functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, true, texSizeSDF, true, pitchedScale), { + 'u_texsize_icon': texSizeIcon, + 'u_texture_icon': 1 + }); +}; + +const backgroundUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_opacity': new performance$1.Uniform1f(context, locations.u_opacity), + 'u_color': new performance$1.UniformColor(context, locations.u_color) +}); +const backgroundPatternUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.UniformMatrix4f(context, locations.u_matrix), + 'u_opacity': new performance$1.Uniform1f(context, locations.u_opacity), + 'u_image': new performance$1.Uniform1i(context, locations.u_image), + 'u_pattern_tl_a': new performance$1.Uniform2f(context, locations.u_pattern_tl_a), + 'u_pattern_br_a': new performance$1.Uniform2f(context, locations.u_pattern_br_a), + 'u_pattern_tl_b': new performance$1.Uniform2f(context, locations.u_pattern_tl_b), + 'u_pattern_br_b': new performance$1.Uniform2f(context, locations.u_pattern_br_b), + 'u_texsize': new performance$1.Uniform2f(context, locations.u_texsize), + 'u_mix': new performance$1.Uniform1f(context, locations.u_mix), + 'u_pattern_size_a': new performance$1.Uniform2f(context, locations.u_pattern_size_a), + 'u_pattern_size_b': new performance$1.Uniform2f(context, locations.u_pattern_size_b), + 'u_scale_a': new performance$1.Uniform1f(context, locations.u_scale_a), + 'u_scale_b': new performance$1.Uniform1f(context, locations.u_scale_b), + 'u_pixel_coord_upper': new performance$1.Uniform2f(context, locations.u_pixel_coord_upper), + 'u_pixel_coord_lower': new performance$1.Uniform2f(context, locations.u_pixel_coord_lower), + 'u_tile_units_to_pixels': new performance$1.Uniform1f(context, locations.u_tile_units_to_pixels) +}); +const backgroundUniformValues = (matrix, opacity, color) => ({ + 'u_matrix': matrix, + 'u_opacity': opacity, + 'u_color': color +}); +const backgroundPatternUniformValues = (matrix, opacity, painter, image, tile, crossfade) => performance$1.extend(bgPatternUniformValues(image, crossfade, painter, tile), { + 'u_matrix': matrix, + 'u_opacity': opacity +}); + +const skyUniforms = (context, locations) => ({ + 'u_sky_color': new performance$1.UniformColor(context, locations.u_sky_color), + 'u_horizon_color': new performance$1.UniformColor(context, locations.u_horizon_color), + 'u_horizon': new performance$1.Uniform1f(context, locations.u_horizon), + 'u_sky_horizon_blend': new performance$1.Uniform1f(context, locations.u_sky_horizon_blend), +}); +const skyUniformValues = (sky, transform, pixelRatio) => ({ + 'u_sky_color': sky.properties.get('sky-color'), + 'u_horizon_color': sky.properties.get('horizon-color'), + 'u_horizon': (transform.height / 2 + transform.getHorizon()) * pixelRatio, + 'u_sky_horizon_blend': (sky.properties.get('sky-horizon-blend') * transform.height / 2) * pixelRatio, +}); + +const programUniforms = { + fillExtrusion: fillExtrusionUniforms, + fillExtrusionPattern: fillExtrusionPatternUniforms, + fill: fillUniforms, + fillPattern: fillPatternUniforms, + fillOutline: fillOutlineUniforms, + fillOutlinePattern: fillOutlinePatternUniforms, + circle: circleUniforms, + collisionBox: collisionUniforms, + collisionCircle: collisionCircleUniforms, + debug: debugUniforms, + clippingMask: clippingMaskUniforms, + heatmap: heatmapUniforms, + heatmapTexture: heatmapTextureUniforms, + hillshade: hillshadeUniforms, + hillshadePrepare: hillshadePrepareUniforms, + line: lineUniforms, + lineGradient: lineGradientUniforms, + linePattern: linePatternUniforms, + lineSDF: lineSDFUniforms, + raster: rasterUniforms, + symbolIcon: symbolIconUniforms, + symbolSDF: symbolSDFUniforms, + symbolTextAndIcon: symbolTextAndIconUniforms, + background: backgroundUniforms, + backgroundPattern: backgroundPatternUniforms, + terrain: terrainUniforms, + terrainDepth: terrainDepthUniforms, + terrainCoords: terrainCoordsUniforms, + sky: skyUniforms +}; + +/** + * @internal + * an index buffer class + */ +class IndexBuffer { + constructor(context, array, dynamicDraw) { + this.context = context; + const gl = context.gl; + this.buffer = gl.createBuffer(); + this.dynamicDraw = Boolean(dynamicDraw); + // The bound index buffer is part of vertex array object state. We don't want to + // modify whatever VAO happens to be currently bound, so make sure the default + // vertex array provided by the context is bound instead. + this.context.unbindVAO(); + context.bindElementBuffer.set(this.buffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW); + if (!this.dynamicDraw) { + delete array.arrayBuffer; + } + } + bind() { + this.context.bindElementBuffer.set(this.buffer); + } + updateData(array) { + const gl = this.context.gl; + if (!this.dynamicDraw) + throw new Error('Attempted to update data while not in dynamic mode.'); + // The right VAO will get this buffer re-bound later in VertexArrayObject#bind + // See https://github.com/mapbox/mapbox-gl-js/issues/5620 + this.context.unbindVAO(); + this.bind(); + gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, array.arrayBuffer); + } + destroy() { + const gl = this.context.gl; + if (this.buffer) { + gl.deleteBuffer(this.buffer); + delete this.buffer; + } + } +} + +/** + * An Enum for AttributeType + */ +const AttributeType = { + Int8: 'BYTE', + Uint8: 'UNSIGNED_BYTE', + Int16: 'SHORT', + Uint16: 'UNSIGNED_SHORT', + Int32: 'INT', + Uint32: 'UNSIGNED_INT', + Float32: 'FLOAT' +}; +/** + * @internal + * The `VertexBuffer` class turns a `StructArray` into a WebGL buffer. Each member of the StructArray's + * Struct type is converted to a WebGL attribute. + */ +class VertexBuffer { + /** + * @param dynamicDraw - Whether this buffer will be repeatedly updated. + */ + constructor(context, array, attributes, dynamicDraw) { + this.length = array.length; + this.attributes = attributes; + this.itemSize = array.bytesPerElement; + this.dynamicDraw = dynamicDraw; + this.context = context; + const gl = context.gl; + this.buffer = gl.createBuffer(); + context.bindVertexBuffer.set(this.buffer); + gl.bufferData(gl.ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW); + if (!this.dynamicDraw) { + delete array.arrayBuffer; + } + } + bind() { + this.context.bindVertexBuffer.set(this.buffer); + } + updateData(array) { + if (array.length !== this.length) + throw new Error(`Length of new data is ${array.length}, which doesn't match current length of ${this.length}`); + const gl = this.context.gl; + this.bind(); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, array.arrayBuffer); + } + enableAttributes(gl, program) { + for (let j = 0; j < this.attributes.length; j++) { + const member = this.attributes[j]; + const attribIndex = program.attributes[member.name]; + if (attribIndex !== undefined) { + gl.enableVertexAttribArray(attribIndex); + } + } + } + /** + * Set the attribute pointers in a WebGL context + * @param gl - The WebGL context + * @param program - The active WebGL program + * @param vertexOffset - Index of the starting vertex of the segment + */ + setVertexAttribPointers(gl, program, vertexOffset) { + for (let j = 0; j < this.attributes.length; j++) { + const member = this.attributes[j]; + const attribIndex = program.attributes[member.name]; + if (attribIndex !== undefined) { + gl.vertexAttribPointer(attribIndex, member.components, gl[AttributeType[member.type]], false, this.itemSize, member.offset + (this.itemSize * (vertexOffset || 0))); + } + } + } + /** + * Destroy the GL buffer bound to the given WebGL context + */ + destroy() { + const gl = this.context.gl; + if (this.buffer) { + gl.deleteBuffer(this.buffer); + delete this.buffer; + } + } +} + +const cache = new WeakMap(); +function isWebGL2(gl) { + var _a; + if (cache.has(gl)) { + return cache.get(gl); + } + else { + const value = (_a = gl.getParameter(gl.VERSION)) === null || _a === void 0 ? void 0 : _a.startsWith('WebGL 2.0'); + cache.set(gl, value); + return value; + } +} + +class BaseValue { + constructor(context) { + this.gl = context.gl; + this.default = this.getDefault(); + this.current = this.default; + this.dirty = false; + } + get() { + return this.current; + } + set(value) { + // overridden in child classes; + } + getDefault() { + return this.default; // overridden in child classes + } + setDefault() { + this.set(this.default); + } +} +class ClearColor extends BaseValue { + getDefault() { + return performance$1.Color.transparent; + } + set(v) { + const c = this.current; + if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) + return; + this.gl.clearColor(v.r, v.g, v.b, v.a); + this.current = v; + this.dirty = false; + } +} +class ClearDepth extends BaseValue { + getDefault() { + return 1; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.clearDepth(v); + this.current = v; + this.dirty = false; + } +} +class ClearStencil extends BaseValue { + getDefault() { + return 0; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.clearStencil(v); + this.current = v; + this.dirty = false; + } +} +class ColorMask extends BaseValue { + getDefault() { + return [true, true, true, true]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) + return; + this.gl.colorMask(v[0], v[1], v[2], v[3]); + this.current = v; + this.dirty = false; + } +} +class DepthMask extends BaseValue { + getDefault() { + return true; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.depthMask(v); + this.current = v; + this.dirty = false; + } +} +class StencilMask extends BaseValue { + getDefault() { + return 0xFF; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.stencilMask(v); + this.current = v; + this.dirty = false; + } +} +class StencilFunc extends BaseValue { + getDefault() { + return { + func: this.gl.ALWAYS, + ref: 0, + mask: 0xFF + }; + } + set(v) { + const c = this.current; + if (v.func === c.func && v.ref === c.ref && v.mask === c.mask && !this.dirty) + return; + this.gl.stencilFunc(v.func, v.ref, v.mask); + this.current = v; + this.dirty = false; + } +} +class StencilOp extends BaseValue { + getDefault() { + const gl = this.gl; + return [gl.KEEP, gl.KEEP, gl.KEEP]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && !this.dirty) + return; + this.gl.stencilOp(v[0], v[1], v[2]); + this.current = v; + this.dirty = false; + } +} +class StencilTest extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (v) { + gl.enable(gl.STENCIL_TEST); + } + else { + gl.disable(gl.STENCIL_TEST); + } + this.current = v; + this.dirty = false; + } +} +class DepthRange extends BaseValue { + getDefault() { + return [0, 1]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && !this.dirty) + return; + this.gl.depthRange(v[0], v[1]); + this.current = v; + this.dirty = false; + } +} +class DepthTest extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (v) { + gl.enable(gl.DEPTH_TEST); + } + else { + gl.disable(gl.DEPTH_TEST); + } + this.current = v; + this.dirty = false; + } +} +class DepthFunc extends BaseValue { + getDefault() { + return this.gl.LESS; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.depthFunc(v); + this.current = v; + this.dirty = false; + } +} +class Blend extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (v) { + gl.enable(gl.BLEND); + } + else { + gl.disable(gl.BLEND); + } + this.current = v; + this.dirty = false; + } +} +class BlendFunc extends BaseValue { + getDefault() { + const gl = this.gl; + return [gl.ONE, gl.ZERO]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && !this.dirty) + return; + this.gl.blendFunc(v[0], v[1]); + this.current = v; + this.dirty = false; + } +} +class BlendColor extends BaseValue { + getDefault() { + return performance$1.Color.transparent; + } + set(v) { + const c = this.current; + if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) + return; + this.gl.blendColor(v.r, v.g, v.b, v.a); + this.current = v; + this.dirty = false; + } +} +class BlendEquation extends BaseValue { + getDefault() { + return this.gl.FUNC_ADD; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.blendEquation(v); + this.current = v; + this.dirty = false; + } +} +class CullFace extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (v) { + gl.enable(gl.CULL_FACE); + } + else { + gl.disable(gl.CULL_FACE); + } + this.current = v; + this.dirty = false; + } +} +class CullFaceSide extends BaseValue { + getDefault() { + return this.gl.BACK; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.cullFace(v); + this.current = v; + this.dirty = false; + } +} +class FrontFace extends BaseValue { + getDefault() { + return this.gl.CCW; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.frontFace(v); + this.current = v; + this.dirty = false; + } +} +class ProgramValue extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.useProgram(v); + this.current = v; + this.dirty = false; + } +} +class ActiveTextureUnit extends BaseValue { + getDefault() { + return this.gl.TEXTURE0; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.activeTexture(v); + this.current = v; + this.dirty = false; + } +} +class Viewport extends BaseValue { + getDefault() { + const gl = this.gl; + return [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) + return; + this.gl.viewport(v[0], v[1], v[2], v[3]); + this.current = v; + this.dirty = false; + } +} +class BindFramebuffer extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, v); + this.current = v; + this.dirty = false; + } +} +class BindRenderbuffer extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.bindRenderbuffer(gl.RENDERBUFFER, v); + this.current = v; + this.dirty = false; + } +} +class BindTexture extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, v); + this.current = v; + this.dirty = false; + } +} +class BindVertexBuffer extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.bindBuffer(gl.ARRAY_BUFFER, v); + this.current = v; + this.dirty = false; + } +} +class BindElementBuffer extends BaseValue { + getDefault() { + return null; + } + set(v) { + // Always rebind + const gl = this.gl; + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, v); + this.current = v; + this.dirty = false; + } +} +class BindVertexArray extends BaseValue { + getDefault() { + return null; + } + set(v) { + var _a; + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (isWebGL2(gl)) { + gl.bindVertexArray(v); + } + else { + (_a = gl.getExtension('OES_vertex_array_object')) === null || _a === void 0 ? void 0 : _a.bindVertexArrayOES(v); + } + this.current = v; + this.dirty = false; + } +} +class PixelStoreUnpack extends BaseValue { + getDefault() { + return 4; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_ALIGNMENT, v); + this.current = v; + this.dirty = false; + } +} +class PixelStoreUnpackPremultiplyAlpha extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, v); + this.current = v; + this.dirty = false; + } +} +class PixelStoreUnpackFlipY extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, v); + this.current = v; + this.dirty = false; + } +} +class FramebufferAttachment extends BaseValue { + constructor(context, parent) { + super(context); + this.context = context; + this.parent = parent; + } + getDefault() { + return null; + } +} +class ColorAttachment extends FramebufferAttachment { + setDirty() { + this.dirty = true; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.context.bindFramebuffer.set(this.parent); + // note: it's possible to attach a renderbuffer to the color + // attachment point, but thus far MBGL only uses textures for color + const gl = this.gl; + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, v, 0); + this.current = v; + this.dirty = false; + } +} +class DepthAttachment extends FramebufferAttachment { + set(v) { + if (v === this.current && !this.dirty) + return; + this.context.bindFramebuffer.set(this.parent); + // note: it's possible to attach a texture to the depth attachment + // point, but thus far MBGL only uses renderbuffers for depth + const gl = this.gl; + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, v); + this.current = v; + this.dirty = false; + } +} +class DepthStencilAttachment extends FramebufferAttachment { + set(v) { + if (v === this.current && !this.dirty) + return; + this.context.bindFramebuffer.set(this.parent); + // note: it's possible to attach a texture to the depth attachment + // point, but thus far MBGL only uses renderbuffers for depth + const gl = this.gl; + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, v); + this.current = v; + this.dirty = false; + } +} + +/** + * @internal + * A framebuffer holder object + */ +class Framebuffer { + constructor(context, width, height, hasDepth, hasStencil) { + this.context = context; + this.width = width; + this.height = height; + const gl = context.gl; + const fbo = this.framebuffer = gl.createFramebuffer(); + this.colorAttachment = new ColorAttachment(context, fbo); + if (hasDepth) { + this.depthAttachment = hasStencil ? new DepthStencilAttachment(context, fbo) : new DepthAttachment(context, fbo); + } + else if (hasStencil) { + throw new Error('Stencil cannot be set without depth'); + } + if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) { + throw new Error('Framebuffer is not complete'); + } + } + destroy() { + const gl = this.context.gl; + const texture = this.colorAttachment.get(); + if (texture) + gl.deleteTexture(texture); + if (this.depthAttachment) { + const renderbuffer = this.depthAttachment.get(); + if (renderbuffer) + gl.deleteRenderbuffer(renderbuffer); + } + gl.deleteFramebuffer(this.framebuffer); + } +} + +const ZERO = 0x0000; +const ONE = 0x0001; +const ONE_MINUS_SRC_ALPHA = 0x0303; +class ColorMode { + constructor(blendFunction, blendColor, mask) { + this.blendFunction = blendFunction; + this.blendColor = blendColor; + this.mask = mask; + } +} +ColorMode.Replace = [ONE, ZERO]; +ColorMode.disabled = new ColorMode(ColorMode.Replace, performance$1.Color.transparent, [false, false, false, false]); +ColorMode.unblended = new ColorMode(ColorMode.Replace, performance$1.Color.transparent, [true, true, true, true]); +ColorMode.alphaBlended = new ColorMode([ONE, ONE_MINUS_SRC_ALPHA], performance$1.Color.transparent, [true, true, true, true]); + +/** + * @internal + * A webgl wrapper class to allow injection, mocking and abstaction + */ +class Context { + constructor(gl) { + var _a, _b; + this.gl = gl; + this.clearColor = new ClearColor(this); + this.clearDepth = new ClearDepth(this); + this.clearStencil = new ClearStencil(this); + this.colorMask = new ColorMask(this); + this.depthMask = new DepthMask(this); + this.stencilMask = new StencilMask(this); + this.stencilFunc = new StencilFunc(this); + this.stencilOp = new StencilOp(this); + this.stencilTest = new StencilTest(this); + this.depthRange = new DepthRange(this); + this.depthTest = new DepthTest(this); + this.depthFunc = new DepthFunc(this); + this.blend = new Blend(this); + this.blendFunc = new BlendFunc(this); + this.blendColor = new BlendColor(this); + this.blendEquation = new BlendEquation(this); + this.cullFace = new CullFace(this); + this.cullFaceSide = new CullFaceSide(this); + this.frontFace = new FrontFace(this); + this.program = new ProgramValue(this); + this.activeTexture = new ActiveTextureUnit(this); + this.viewport = new Viewport(this); + this.bindFramebuffer = new BindFramebuffer(this); + this.bindRenderbuffer = new BindRenderbuffer(this); + this.bindTexture = new BindTexture(this); + this.bindVertexBuffer = new BindVertexBuffer(this); + this.bindElementBuffer = new BindElementBuffer(this); + this.bindVertexArray = new BindVertexArray(this); + this.pixelStoreUnpack = new PixelStoreUnpack(this); + this.pixelStoreUnpackPremultiplyAlpha = new PixelStoreUnpackPremultiplyAlpha(this); + this.pixelStoreUnpackFlipY = new PixelStoreUnpackFlipY(this); + this.extTextureFilterAnisotropic = (gl.getExtension('EXT_texture_filter_anisotropic') || + gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || + gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic')); + if (this.extTextureFilterAnisotropic) { + this.extTextureFilterAnisotropicMax = gl.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } + this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + if (isWebGL2(gl)) { + this.HALF_FLOAT = gl.HALF_FLOAT; + const extColorBufferHalfFloat = gl.getExtension('EXT_color_buffer_half_float'); + this.RGBA16F = (_a = gl.RGBA16F) !== null && _a !== void 0 ? _a : extColorBufferHalfFloat === null || extColorBufferHalfFloat === void 0 ? void 0 : extColorBufferHalfFloat.RGBA16F_EXT; + this.RGB16F = (_b = gl.RGB16F) !== null && _b !== void 0 ? _b : extColorBufferHalfFloat === null || extColorBufferHalfFloat === void 0 ? void 0 : extColorBufferHalfFloat.RGB16F_EXT; + gl.getExtension('EXT_color_buffer_float'); + } + else { + gl.getExtension('EXT_color_buffer_half_float'); + gl.getExtension('OES_texture_half_float_linear'); + const extTextureHalfFloat = gl.getExtension('OES_texture_half_float'); + this.HALF_FLOAT = extTextureHalfFloat === null || extTextureHalfFloat === void 0 ? void 0 : extTextureHalfFloat.HALF_FLOAT_OES; + } + } + setDefault() { + this.unbindVAO(); + this.clearColor.setDefault(); + this.clearDepth.setDefault(); + this.clearStencil.setDefault(); + this.colorMask.setDefault(); + this.depthMask.setDefault(); + this.stencilMask.setDefault(); + this.stencilFunc.setDefault(); + this.stencilOp.setDefault(); + this.stencilTest.setDefault(); + this.depthRange.setDefault(); + this.depthTest.setDefault(); + this.depthFunc.setDefault(); + this.blend.setDefault(); + this.blendFunc.setDefault(); + this.blendColor.setDefault(); + this.blendEquation.setDefault(); + this.cullFace.setDefault(); + this.cullFaceSide.setDefault(); + this.frontFace.setDefault(); + this.program.setDefault(); + this.activeTexture.setDefault(); + this.bindFramebuffer.setDefault(); + this.pixelStoreUnpack.setDefault(); + this.pixelStoreUnpackPremultiplyAlpha.setDefault(); + this.pixelStoreUnpackFlipY.setDefault(); + } + setDirty() { + this.clearColor.dirty = true; + this.clearDepth.dirty = true; + this.clearStencil.dirty = true; + this.colorMask.dirty = true; + this.depthMask.dirty = true; + this.stencilMask.dirty = true; + this.stencilFunc.dirty = true; + this.stencilOp.dirty = true; + this.stencilTest.dirty = true; + this.depthRange.dirty = true; + this.depthTest.dirty = true; + this.depthFunc.dirty = true; + this.blend.dirty = true; + this.blendFunc.dirty = true; + this.blendColor.dirty = true; + this.blendEquation.dirty = true; + this.cullFace.dirty = true; + this.cullFaceSide.dirty = true; + this.frontFace.dirty = true; + this.program.dirty = true; + this.activeTexture.dirty = true; + this.viewport.dirty = true; + this.bindFramebuffer.dirty = true; + this.bindRenderbuffer.dirty = true; + this.bindTexture.dirty = true; + this.bindVertexBuffer.dirty = true; + this.bindElementBuffer.dirty = true; + this.bindVertexArray.dirty = true; + this.pixelStoreUnpack.dirty = true; + this.pixelStoreUnpackPremultiplyAlpha.dirty = true; + this.pixelStoreUnpackFlipY.dirty = true; + } + createIndexBuffer(array, dynamicDraw) { + return new IndexBuffer(this, array, dynamicDraw); + } + createVertexBuffer(array, attributes, dynamicDraw) { + return new VertexBuffer(this, array, attributes, dynamicDraw); + } + createRenderbuffer(storageFormat, width, height) { + const gl = this.gl; + const rbo = gl.createRenderbuffer(); + this.bindRenderbuffer.set(rbo); + gl.renderbufferStorage(gl.RENDERBUFFER, storageFormat, width, height); + this.bindRenderbuffer.set(null); + return rbo; + } + createFramebuffer(width, height, hasDepth, hasStencil) { + return new Framebuffer(this, width, height, hasDepth, hasStencil); + } + clear({ color, depth, stencil }) { + const gl = this.gl; + let mask = 0; + if (color) { + mask |= gl.COLOR_BUFFER_BIT; + this.clearColor.set(color); + this.colorMask.set([true, true, true, true]); + } + if (typeof depth !== 'undefined') { + mask |= gl.DEPTH_BUFFER_BIT; + // Workaround for platforms where clearDepth doesn't seem to work + // without resetting the depthRange. See https://github.com/mapbox/mapbox-gl-js/issues/3437 + this.depthRange.set([0, 1]); + this.clearDepth.set(depth); + this.depthMask.set(true); + } + if (typeof stencil !== 'undefined') { + mask |= gl.STENCIL_BUFFER_BIT; + this.clearStencil.set(stencil); + this.stencilMask.set(0xFF); + } + gl.clear(mask); + } + setCullFace(cullFaceMode) { + if (cullFaceMode.enable === false) { + this.cullFace.set(false); + } + else { + this.cullFace.set(true); + this.cullFaceSide.set(cullFaceMode.mode); + this.frontFace.set(cullFaceMode.frontFace); + } + } + setDepthMode(depthMode) { + if (depthMode.func === this.gl.ALWAYS && !depthMode.mask) { + this.depthTest.set(false); + } + else { + this.depthTest.set(true); + this.depthFunc.set(depthMode.func); + this.depthMask.set(depthMode.mask); + this.depthRange.set(depthMode.range); + } + } + setStencilMode(stencilMode) { + if (stencilMode.test.func === this.gl.ALWAYS && !stencilMode.mask) { + this.stencilTest.set(false); + } + else { + this.stencilTest.set(true); + this.stencilMask.set(stencilMode.mask); + this.stencilOp.set([stencilMode.fail, stencilMode.depthFail, stencilMode.pass]); + this.stencilFunc.set({ + func: stencilMode.test.func, + ref: stencilMode.ref, + mask: stencilMode.test.mask + }); + } + } + setColorMode(colorMode) { + if (performance$1.deepEqual(colorMode.blendFunction, ColorMode.Replace)) { + this.blend.set(false); + } + else { + this.blend.set(true); + this.blendFunc.set(colorMode.blendFunction); + this.blendColor.set(colorMode.blendColor); + } + this.colorMask.set(colorMode.mask); + } + createVertexArray() { + var _a; + if (isWebGL2(this.gl)) + return this.gl.createVertexArray(); + return (_a = this.gl.getExtension('OES_vertex_array_object')) === null || _a === void 0 ? void 0 : _a.createVertexArrayOES(); + } + deleteVertexArray(x) { + var _a; + if (isWebGL2(this.gl)) + return this.gl.deleteVertexArray(x); + return (_a = this.gl.getExtension('OES_vertex_array_object')) === null || _a === void 0 ? void 0 : _a.deleteVertexArrayOES(x); + } + unbindVAO() { + // Unbinding the VAO prevents other things (custom layers, new buffer creation) from + // unintentionally changing the state of the last VAO used. + this.bindVertexArray.set(null); + } +} + +const ALWAYS$1 = 0x0207; +class DepthMode { + constructor(depthFunc, depthMask, depthRange) { + this.func = depthFunc; + this.mask = depthMask; + this.range = depthRange; + } +} +DepthMode.ReadOnly = false; +DepthMode.ReadWrite = true; +DepthMode.disabled = new DepthMode(ALWAYS$1, DepthMode.ReadOnly, [0, 1]); + +const ALWAYS = 0x0207; +const KEEP = 0x1E00; +class StencilMode { + constructor(test, ref, mask, fail, depthFail, pass) { + this.test = test; + this.ref = ref; + this.mask = mask; + this.fail = fail; + this.depthFail = depthFail; + this.pass = pass; + } +} +StencilMode.disabled = new StencilMode({ func: ALWAYS, mask: 0 }, 0, 0, KEEP, KEEP, KEEP); + +const BACK = 0x0405; +const CCW = 0x0901; +class CullFaceMode { + constructor(enable, mode, frontFace) { + this.enable = enable; + this.mode = mode; + this.frontFace = frontFace; + } +} +CullFaceMode.disabled = new CullFaceMode(false, BACK, CCW); +CullFaceMode.backCCW = new CullFaceMode(true, BACK, CCW); + +let quadTriangles; +function drawCollisionDebug(painter, sourceCache, layer, coords, isText) { + const context = painter.context; + const gl = context.gl; + const program = painter.useProgram('collisionBox'); + const tileBatches = []; + let circleCount = 0; + let circleOffset = 0; + for (let i = 0; i < coords.length; i++) { + const coord = coords[i]; + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const buffers = isText ? bucket.textCollisionBox : bucket.iconCollisionBox; + // Get collision circle data of this bucket + const circleArray = bucket.collisionCircleArray; + if (circleArray.length > 0) { + // We need to know the projection matrix that was used for projecting collision circles to the screen. + // This might vary between buckets as the symbol placement is a continuous process. This matrix is + // required for transforming points from previous screen space to the current one + const invTransform = performance$1.create(); + performance$1.mul(invTransform, bucket.placementInvProjMatrix, painter.transform.glCoordMatrix); + performance$1.mul(invTransform, invTransform, bucket.placementViewportMatrix); + tileBatches.push({ + circleArray, + circleOffset, + transform: coord.posMatrix, // Ignore translation + invTransform, + coord + }); + circleCount += circleArray.length / 4; // 4 values per circle + circleOffset = circleCount; + } + // Draw collision boxes + if (!buffers) { + continue; + } + program.draw(context, gl.LINES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, collisionUniformValues(painter.transform, coord.posMatrix), painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord), layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer, buffers.segments, null, painter.transform.zoom, null, null, buffers.collisionVertexBuffer); + } + if (!isText || !tileBatches.length) { + return; + } + // Render collision circles + const circleProgram = painter.useProgram('collisionCircle'); + // Construct vertex data + const vertexData = new performance$1.CollisionCircleLayoutArray(); + vertexData.resize(circleCount * 4); + vertexData._trim(); + let vertexOffset = 0; + for (const batch of tileBatches) { + for (let i = 0; i < batch.circleArray.length / 4; i++) { + const circleIdx = i * 4; + const x = batch.circleArray[circleIdx + 0]; + const y = batch.circleArray[circleIdx + 1]; + const radius = batch.circleArray[circleIdx + 2]; + const collision = batch.circleArray[circleIdx + 3]; + // 4 floats per vertex, 4 vertices per quad + vertexData.emplace(vertexOffset++, x, y, radius, collision, 0); + vertexData.emplace(vertexOffset++, x, y, radius, collision, 1); + vertexData.emplace(vertexOffset++, x, y, radius, collision, 2); + vertexData.emplace(vertexOffset++, x, y, radius, collision, 3); + } + } + if (!quadTriangles || quadTriangles.length < circleCount * 2) { + quadTriangles = createQuadTriangles(circleCount); + } + const indexBuffer = context.createIndexBuffer(quadTriangles, true); + const vertexBuffer = context.createVertexBuffer(vertexData, performance$1.collisionCircleLayout.members, true); + // Render batches + for (const batch of tileBatches) { + const uniforms = collisionCircleUniformValues(batch.transform, batch.invTransform, painter.transform); + circleProgram.draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, uniforms, painter.style.map.terrain && painter.style.map.terrain.getTerrainData(batch.coord), layer.id, vertexBuffer, indexBuffer, performance$1.SegmentVector.simpleSegment(0, batch.circleOffset * 2, batch.circleArray.length, batch.circleArray.length / 2), null, painter.transform.zoom, null, null, null); + } + vertexBuffer.destroy(); + indexBuffer.destroy(); +} +function createQuadTriangles(quadCount) { + const triCount = quadCount * 2; + const array = new performance$1.QuadTriangleArray(); + array.resize(triCount); + array._trim(); + // Two triangles and 4 vertices per quad. + for (let i = 0; i < triCount; i++) { + const idx = i * 6; + array.uint16[idx + 0] = i * 4 + 0; + array.uint16[idx + 1] = i * 4 + 1; + array.uint16[idx + 2] = i * 4 + 2; + array.uint16[idx + 3] = i * 4 + 2; + array.uint16[idx + 4] = i * 4 + 3; + array.uint16[idx + 5] = i * 4 + 0; + } + return array; +} + +const identityMat4 = performance$1.identity(new Float32Array(16)); +function drawSymbols(painter, sourceCache, layer, coords, variableOffsets) { + if (painter.renderPass !== 'translucent') + return; + // Disable the stencil test so that labels aren't clipped to tile boundaries. + const stencilMode = StencilMode.disabled; + const colorMode = painter.colorModeForRenderPass(); + const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset'); + //Compute variable-offsets before painting since icons and text data positioning + //depend on each other in this case. + if (hasVariablePlacement) { + updateVariableAnchors(coords, painter, layer, sourceCache, layer.layout.get('text-rotation-alignment'), layer.layout.get('text-pitch-alignment'), layer.paint.get('text-translate'), layer.paint.get('text-translate-anchor'), variableOffsets); + } + if (layer.paint.get('icon-opacity').constantOr(1) !== 0) { + drawLayerSymbols(painter, sourceCache, layer, coords, false, layer.paint.get('icon-translate'), layer.paint.get('icon-translate-anchor'), layer.layout.get('icon-rotation-alignment'), layer.layout.get('icon-pitch-alignment'), layer.layout.get('icon-keep-upright'), stencilMode, colorMode); + } + if (layer.paint.get('text-opacity').constantOr(1) !== 0) { + drawLayerSymbols(painter, sourceCache, layer, coords, true, layer.paint.get('text-translate'), layer.paint.get('text-translate-anchor'), layer.layout.get('text-rotation-alignment'), layer.layout.get('text-pitch-alignment'), layer.layout.get('text-keep-upright'), stencilMode, colorMode); + } + if (sourceCache.map.showCollisionBoxes) { + drawCollisionDebug(painter, sourceCache, layer, coords, true); + drawCollisionDebug(painter, sourceCache, layer, coords, false); + } +} +function calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize) { + const { horizontalAlign, verticalAlign } = performance$1.getAnchorAlignment(anchor); + const shiftX = -(horizontalAlign - 0.5) * width; + const shiftY = -(verticalAlign - 0.5) * height; + return new performance$1.Point((shiftX / textBoxScale + textOffset[0]) * renderTextSize, (shiftY / textBoxScale + textOffset[1]) * renderTextSize); +} +function updateVariableAnchors(coords, painter, layer, sourceCache, rotationAlignment, pitchAlignment, translate, translateAnchor, variableOffsets) { + const transform = painter.transform; + const projection = createProjection(); + const rotateWithMap = rotationAlignment === 'map'; + const pitchWithMap = pitchAlignment === 'map'; + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket || !bucket.text || !bucket.text.segments.get().length) + continue; + const sizeData = bucket.textSizeData; + const size = performance$1.evaluateSizeForZoom(sizeData, transform.zoom); + const pixelToTileScale = pixelsToTileUnits(tile, 1, painter.transform.zoom); + const labelPlaneMatrix = getLabelPlaneMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, pixelToTileScale); + const updateTextFitIcon = layer.layout.get('icon-text-fit') !== 'none' && bucket.hasIconData(); + if (size) { + const tileScale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ); + const getElevation = painter.style.map.terrain ? (x, y) => painter.style.map.terrain.getElevation(coord, x, y) : null; + const translation = projection.translatePosition(transform, tile, translate, translateAnchor); + updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, transform, labelPlaneMatrix, coord.posMatrix, tileScale, size, updateTextFitIcon, projection, translation, coord.toUnwrapped(), getElevation); + } + } +} +function getShiftedAnchor(projectedAnchorPoint, projectionContext, rotateWithMap, shift, transformAngle, pitchedTextShiftCorrection) { + // Usual case is that we take the projected anchor and add the pixel-based shift + // calculated earlier. In the (somewhat weird) case of pitch-aligned text, we add an equivalent + // tile-unit based shift to the anchor before projecting to the label plane. + const translatedAnchor = projectionContext.tileAnchorPoint.add(new performance$1.Point(projectionContext.translation[0], projectionContext.translation[1])); + if (projectionContext.pitchWithMap) { + let adjustedShift = shift.mult(pitchedTextShiftCorrection); + if (!rotateWithMap) { + adjustedShift = adjustedShift.rotate(-transformAngle); + } + const tileAnchorShifted = translatedAnchor.add(adjustedShift); + return project(tileAnchorShifted.x, tileAnchorShifted.y, projectionContext.labelPlaneMatrix, projectionContext.getElevation).point; + } + else { + if (rotateWithMap) { + // Compute the angle with which to rotate the anchor, so that it is aligned with + // the map's actual east-west axis. Very similar to what is done in the shader. + const projectedAnchorRight = projectTileCoordinatesToViewport(projectionContext.tileAnchorPoint.x + 1, projectionContext.tileAnchorPoint.y, projectionContext); + const east = projectedAnchorRight.point.sub(projectedAnchorPoint); + const angle = Math.atan(east.y / east.x) + (east.x < 0 ? Math.PI : 0); + return projectedAnchorPoint.add(shift.rotate(angle)); + } + else { + return projectedAnchorPoint.add(shift); + } + } +} +function updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, transform, labelPlaneMatrix, posMatrix, tileScale, size, updateTextFitIcon, projection, translation, unwrappedTileID, getElevation) { + const placedSymbols = bucket.text.placedSymbolArray; + const dynamicTextLayoutVertexArray = bucket.text.dynamicLayoutVertexArray; + const dynamicIconLayoutVertexArray = bucket.icon.dynamicLayoutVertexArray; + const placedTextShifts = {}; + dynamicTextLayoutVertexArray.clear(); + for (let s = 0; s < placedSymbols.length; s++) { + const symbol = placedSymbols.get(s); + const skipOrientation = bucket.allowVerticalPlacement && !symbol.placedOrientation; + const variableOffset = (!symbol.hidden && symbol.crossTileID && !skipOrientation) ? variableOffsets[symbol.crossTileID] : null; + if (!variableOffset) { + // These symbols are from a justification that is not being used, or a label that wasn't placed + // so we don't need to do the extra math to figure out what incremental shift to apply. + hideGlyphs(symbol.numGlyphs, dynamicTextLayoutVertexArray); + } + else { + const tileAnchor = new performance$1.Point(symbol.anchorX, symbol.anchorY); + const projectionContext = { + getElevation, + width: transform.width, + height: transform.height, + labelPlaneMatrix, + lineVertexArray: null, + pitchWithMap, + projection, + projectionCache: null, + tileAnchorPoint: tileAnchor, + translation, + unwrappedTileID + }; + const projectedAnchor = pitchWithMap ? + project(tileAnchor.x, tileAnchor.y, posMatrix, getElevation) : + projectTileCoordinatesToViewport(tileAnchor.x, tileAnchor.y, projectionContext); + const perspectiveRatio = getPerspectiveRatio(transform.cameraToCenterDistance, projectedAnchor.signedDistanceFromCamera); + let renderTextSize = performance$1.evaluateSizeForFeature(bucket.textSizeData, size, symbol) * perspectiveRatio / performance$1.ONE_EM; + if (pitchWithMap) { + // Go from size in pixels to equivalent size in tile units + renderTextSize *= bucket.tilePixelRatio / tileScale; + } + const { width, height, anchor, textOffset, textBoxScale } = variableOffset; + const shift = calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize); + const pitchedTextCorrection = projection.getPitchedTextCorrection(transform, tileAnchor.add(new performance$1.Point(translation[0], translation[1])), unwrappedTileID); + const shiftedAnchor = getShiftedAnchor(projectedAnchor.point, projectionContext, rotateWithMap, shift, transform.angle, pitchedTextCorrection); + const angle = (bucket.allowVerticalPlacement && symbol.placedOrientation === performance$1.WritingMode.vertical) ? Math.PI / 2 : 0; + for (let g = 0; g < symbol.numGlyphs; g++) { + performance$1.addDynamicAttributes(dynamicTextLayoutVertexArray, shiftedAnchor, angle); + } + //Only offset horizontal text icons + if (updateTextFitIcon && symbol.associatedIconIndex >= 0) { + placedTextShifts[symbol.associatedIconIndex] = { shiftedAnchor, angle }; + } + } + } + if (updateTextFitIcon) { + dynamicIconLayoutVertexArray.clear(); + const placedIcons = bucket.icon.placedSymbolArray; + for (let i = 0; i < placedIcons.length; i++) { + const placedIcon = placedIcons.get(i); + if (placedIcon.hidden) { + hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray); + } + else { + const shift = placedTextShifts[i]; + if (!shift) { + hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray); + } + else { + for (let g = 0; g < placedIcon.numGlyphs; g++) { + performance$1.addDynamicAttributes(dynamicIconLayoutVertexArray, shift.shiftedAnchor, shift.angle); + } + } + } + } + bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicIconLayoutVertexArray); + } + bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicTextLayoutVertexArray); +} +function getSymbolProgramName(isSDF, isText, bucket) { + if (bucket.iconsInText && isText) { + return 'symbolTextAndIcon'; + } + else if (isSDF) { + return 'symbolSDF'; + } + else { + return 'symbolIcon'; + } +} +function drawLayerSymbols(painter, sourceCache, layer, coords, isText, translate, translateAnchor, rotationAlignment, pitchAlignment, keepUpright, stencilMode, colorMode) { + const context = painter.context; + const gl = context.gl; + const tr = painter.transform; + const projection = createProjection(); + const rotateWithMap = rotationAlignment === 'map'; + const pitchWithMap = pitchAlignment === 'map'; + const alongLine = rotationAlignment !== 'viewport' && layer.layout.get('symbol-placement') !== 'point'; + // Line label rotation happens in `updateLineLabels` + // Pitched point labels are automatically rotated by the labelPlaneMatrix projection + // Unpitched point labels need to have their rotation applied after projection + const rotateInShader = rotateWithMap && !pitchWithMap && !alongLine; + const isViewportLine = !pitchWithMap && alongLine; + const hasSortKey = !layer.layout.get('symbol-sort-key').isConstant(); + let sortFeaturesByKey = false; + const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly); + const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset'); + const tileRenderState = []; + const pitchedTextRescaling = projection.getCircleRadiusCorrection(tr); + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const buffers = isText ? bucket.text : bucket.icon; + if (!buffers || !buffers.segments.get().length || !buffers.hasVisibleVertices) + continue; + const programConfiguration = buffers.programConfigurations.get(layer.id); + const isSDF = isText || bucket.sdfIcons; + const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData; + const transformed = pitchWithMap || tr.pitch !== 0; + const program = painter.useProgram(getSymbolProgramName(isSDF, isText, bucket), programConfiguration); + const size = performance$1.evaluateSizeForZoom(sizeData, tr.zoom); + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + let texSize; + let texSizeIcon = [0, 0]; + let atlasTexture; + let atlasInterpolation; + let atlasTextureIcon = null; + let atlasInterpolationIcon; + let atlasBackgroundTexture; + if (isText) { + atlasTexture = tile.glyphAtlasTexture; + atlasInterpolation = gl.LINEAR; + texSize = tile.glyphAtlasTexture.size; + if (bucket.iconsInText) { + texSizeIcon = tile.imageAtlasTexture.size; + atlasTextureIcon = tile.imageAtlasTexture; + const zoomDependentSize = sizeData.kind === 'composite' || sizeData.kind === 'camera'; + atlasInterpolationIcon = transformed || painter.options.rotating || painter.options.zooming || zoomDependentSize ? gl.LINEAR : gl.NEAREST; + } + } + else { + const iconScaled = layer.layout.get('icon-size').constantOr(0) !== 1 || bucket.iconsNeedLinear; + atlasTexture = tile.imageAtlasTexture; + atlasBackgroundTexture = tile.imageBackgroundsAtlasTexture; + atlasInterpolation = isSDF || painter.options.rotating || painter.options.zooming || iconScaled || transformed ? + gl.LINEAR : + gl.NEAREST; + texSize = tile.imageAtlasTexture.size; + } + const s = pixelsToTileUnits(tile, 1, painter.transform.zoom); + const baseMatrix = isViewportLine ? coord.posMatrix : identityMat4; + const labelPlaneMatrix = getLabelPlaneMatrix(baseMatrix, pitchWithMap, rotateWithMap, painter.transform, s); + const glCoordMatrixForShader = getGlCoordMatrix(baseMatrix, pitchWithMap, rotateWithMap, painter.transform, s); + const glCoordMatrixForSymbolPlacement = getGlCoordMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, s); + const translation = projection.translatePosition(painter.transform, tile, translate, translateAnchor); + const hasVariableAnchors = hasVariablePlacement && bucket.hasTextData(); + const updateTextFitIcon = layer.layout.get('icon-text-fit') !== 'none' && + hasVariableAnchors && + bucket.hasIconData(); + if (alongLine) { + const getElevation = painter.style.map.terrain ? (x, y) => painter.style.map.terrain.getElevation(coord, x, y) : null; + const rotateToLine = layer.layout.get('text-rotation-alignment') === 'map'; + updateLineLabels(bucket, coord.posMatrix, painter, isText, labelPlaneMatrix, glCoordMatrixForSymbolPlacement, pitchWithMap, keepUpright, rotateToLine, projection, coord.toUnwrapped(), tr.width, tr.height, translation, getElevation); + } + const matrix = coord.posMatrix; // formerly also incorporated translate and translate-anchor + const shaderVariableAnchor = (isText && hasVariablePlacement) || updateTextFitIcon; + const noLabelPlane = (alongLine || shaderVariableAnchor); + const uLabelPlaneMatrix = noLabelPlane ? identityMat4 : labelPlaneMatrix; + const uglCoordMatrix = glCoordMatrixForShader; // formerly also incorporated translate and translate-anchor + const hasHalo = isSDF && layer.paint.get(isText ? 'text-halo-width' : 'icon-halo-width').constantOr(1) !== 0; + let uniformValues; + if (isSDF) { + if (!bucket.iconsInText) { + uniformValues = symbolSDFUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, translation, isText, texSize, true, pitchedTextRescaling); + } + else { + uniformValues = symbolTextAndIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, translation, texSize, texSizeIcon, pitchedTextRescaling); + } + } + else { + uniformValues = symbolIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, translation, isText, texSize, pitchedTextRescaling); + } + const state = { + program, + buffers, + uniformValues, + atlasTexture, + atlasBackgroundTexture, + atlasTextureIcon, + atlasInterpolation, + atlasInterpolationIcon, + isSDF, + hasHalo + }; + if (hasSortKey && bucket.canOverlap) { + sortFeaturesByKey = true; + const oldSegments = buffers.segments.get(); + for (const segment of oldSegments) { + tileRenderState.push({ + segments: new performance$1.SegmentVector([segment]), + sortKey: segment.sortKey, + state, + terrainData + }); + } + } + else { + tileRenderState.push({ + segments: buffers.segments, + sortKey: 0, + state, + terrainData + }); + } + } + if (sortFeaturesByKey) { + tileRenderState.sort((a, b) => a.sortKey - b.sortKey); + } + for (const segmentState of tileRenderState) { + const state = segmentState.state; + context.activeTexture.set(gl.TEXTURE0); + state.atlasTexture.bind(state.atlasInterpolation, gl.CLAMP_TO_EDGE); + if (state.atlasTextureIcon || state.atlasBackgroundTexture) { + context.activeTexture.set(gl.TEXTURE1); + if (state.atlasTextureIcon) { + state.atlasTextureIcon.bind(state.atlasInterpolationIcon, gl.CLAMP_TO_EDGE); + } + if (state.atlasBackgroundTexture) { + state.atlasBackgroundTexture.bind(state.atlasInterpolation, gl.CLAMP_TO_EDGE); + } + } + if (state.isSDF) { + const uniformValues = state.uniformValues; + if (state.hasHalo) { + uniformValues['u_is_halo'] = 1; + drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, uniformValues, segmentState.terrainData); + } + uniformValues['u_is_halo'] = 0; + } + drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, state.uniformValues, segmentState.terrainData); + } +} +function drawSymbolElements(buffers, segments, layer, painter, program, depthMode, stencilMode, colorMode, uniformValues, terrainData) { + const context = painter.context; + const gl = context.gl; + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer, segments, layer.paint, painter.transform.zoom, buffers.programConfigurations.get(layer.id), buffers.dynamicLayoutVertexBuffer, buffers.opacityVertexBuffer); +} + +function drawCircles(painter, sourceCache, layer, coords) { + if (painter.renderPass !== 'translucent') + return; + const opacity = layer.paint.get('circle-opacity'); + const strokeWidth = layer.paint.get('circle-stroke-width'); + const strokeOpacity = layer.paint.get('circle-stroke-opacity'); + const sortFeaturesByKey = !layer.layout.get('circle-sort-key').isConstant(); + if (opacity.constantOr(1) === 0 && (strokeWidth.constantOr(1) === 0 || strokeOpacity.constantOr(1) === 0)) { + return; + } + const context = painter.context; + const gl = context.gl; + const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly); + // Turn off stencil testing to allow circles to be drawn across boundaries, + // so that large circles are not clipped to tiles + const stencilMode = StencilMode.disabled; + const colorMode = painter.colorModeForRenderPass(); + const segmentsRenderStates = []; + for (let i = 0; i < coords.length; i++) { + const coord = coords[i]; + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram('circle', programConfiguration); + const layoutVertexBuffer = bucket.layoutVertexBuffer; + const indexBuffer = bucket.indexBuffer; + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + const uniformValues = circleUniformValues(painter, coord, tile, layer); + const state = { + programConfiguration, + program, + layoutVertexBuffer, + indexBuffer, + uniformValues, + terrainData + }; + if (sortFeaturesByKey) { + const oldSegments = bucket.segments.get(); + for (const segment of oldSegments) { + segmentsRenderStates.push({ + segments: new performance$1.SegmentVector([segment]), + sortKey: segment.sortKey, + state + }); + } + } + else { + segmentsRenderStates.push({ + segments: bucket.segments, + sortKey: 0, + state + }); + } + } + if (sortFeaturesByKey) { + segmentsRenderStates.sort((a, b) => a.sortKey - b.sortKey); + } + for (const segmentsState of segmentsRenderStates) { + const { programConfiguration, program, layoutVertexBuffer, indexBuffer, uniformValues, terrainData } = segmentsState.state; + const segments = segmentsState.segments; + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, layoutVertexBuffer, indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration); + } +} + +function drawHeatmap(painter, sourceCache, layer, tileIDs) { + if (layer.paint.get('heatmap-opacity') === 0) { + return; + } + const context = painter.context; + if (painter.style.map.terrain) { + for (const coord of tileIDs) { + const tile = sourceCache.getTile(coord); + // Skip tiles that have uncovered parents to avoid flickering; we don't need + // to use complex tile masking here because the change between zoom levels is subtle, + // so it's fine to simply render the parent until all its 4 children are loaded + if (sourceCache.hasRenderableParent(coord)) + continue; + if (painter.renderPass === 'offscreen') { + prepareHeatmapTerrain(painter, tile, layer, coord); + } + else if (painter.renderPass === 'translucent') { + renderHeatmapTerrain(painter, layer, coord); + } + } + context.viewport.set([0, 0, painter.width, painter.height]); + } + else { + if (painter.renderPass === 'offscreen') { + prepareHeatmapFlat(painter, sourceCache, layer, tileIDs); + } + else if (painter.renderPass === 'translucent') { + renderHeatmapFlat(painter, layer); + } + } +} +function prepareHeatmapFlat(painter, sourceCache, layer, coords) { + const context = painter.context; + const gl = context.gl; + // Allow kernels to be drawn across boundaries, so that + // large kernels are not clipped to tiles + const stencilMode = StencilMode.disabled; + // Turn on additive blending for kernels, which is a key aspect of kernel density estimation formula + const colorMode = new ColorMode([gl.ONE, gl.ONE], performance$1.Color.transparent, [true, true, true, true]); + bindFramebuffer(context, painter, layer); + context.clear({ color: performance$1.Color.transparent }); + for (let i = 0; i < coords.length; i++) { + const coord = coords[i]; + // Skip tiles that have uncovered parents to avoid flickering; we don't need + // to use complex tile masking here because the change between zoom levels is subtle, + // so it's fine to simply render the parent until all its 4 children are loaded + if (sourceCache.hasRenderableParent(coord)) + continue; + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram('heatmap', programConfiguration); + const { zoom } = painter.transform; + program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.disabled, heatmapUniformValues(coord.posMatrix, tile, zoom, layer.paint.get('heatmap-intensity')), null, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration); + } + context.viewport.set([0, 0, painter.width, painter.height]); +} +function renderHeatmapFlat(painter, layer) { + const context = painter.context; + const gl = context.gl; + context.setColorMode(painter.colorModeForRenderPass()); + // Here we bind two different textures from which we'll sample in drawing + // heatmaps: the kernel texture, prepared in the offscreen pass, and a + // color ramp texture. + const fbo = layer.heatmapFbos.get(performance$1.HEATMAP_FULL_RENDER_FBO_KEY); + if (!fbo) + return; + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get()); + context.activeTexture.set(gl.TEXTURE1); + const colorRampTexture = getColorRampTexture(context, layer); + colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + painter.useProgram('heatmapTexture').draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, heatmapTextureUniformValues(painter, layer, 0, 1), null, layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer, painter.viewportSegments, layer.paint, painter.transform.zoom); +} +function prepareHeatmapTerrain(painter, tile, layer, coord) { + const context = painter.context; + const gl = context.gl; + const stencilMode = StencilMode.disabled; + // Turn on additive blending for kernels, which is a key aspect of kernel density estimation formula + const colorMode = new ColorMode([gl.ONE, gl.ONE], performance$1.Color.transparent, [true, true, true, true]); + const bucket = tile.getBucket(layer); + if (!bucket) + return; + const tileKey = coord.key; + let fbo = layer.heatmapFbos.get(tileKey); + if (!fbo) { + fbo = createHeatmapFbo(context, tile.tileSize, tile.tileSize); + layer.heatmapFbos.set(tileKey, fbo); + } + context.bindFramebuffer.set(fbo.framebuffer); + context.viewport.set([0, 0, tile.tileSize, tile.tileSize]); + context.clear({ color: performance$1.Color.transparent }); + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram('heatmap', programConfiguration); + const terrainData = painter.style.map.terrain.getTerrainData(coord); + program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.disabled, heatmapUniformValues(coord.posMatrix, tile, painter.transform.zoom, layer.paint.get('heatmap-intensity')), terrainData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration); +} +function renderHeatmapTerrain(painter, layer, coord) { + const context = painter.context; + const gl = context.gl; + context.setColorMode(painter.colorModeForRenderPass()); + const colorRampTexture = getColorRampTexture(context, layer); + // Here we bind two different textures from which we'll sample in drawing + // heatmaps: the kernel texture, prepared in the offscreen pass, and a + // color ramp texture. + const tileKey = coord.key; + const fbo = layer.heatmapFbos.get(tileKey); + if (!fbo) + return; + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get()); + context.activeTexture.set(gl.TEXTURE1); + colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + painter.useProgram('heatmapTexture').draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, heatmapTextureUniformValues(painter, layer, 0, 1), null, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments, layer.paint, painter.transform.zoom); + // destroy the FBO after rendering + fbo.destroy(); + layer.heatmapFbos.delete(tileKey); +} +function bindFramebuffer(context, painter, layer) { + const gl = context.gl; + context.activeTexture.set(gl.TEXTURE1); + // Use a 4x downscaled screen texture for better performance + context.viewport.set([0, 0, painter.width / 4, painter.height / 4]); + let fbo = layer.heatmapFbos.get(performance$1.HEATMAP_FULL_RENDER_FBO_KEY); + if (!fbo) { + fbo = createHeatmapFbo(context, painter.width / 4, painter.height / 4); + layer.heatmapFbos.set(performance$1.HEATMAP_FULL_RENDER_FBO_KEY, fbo); + } + else { + gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get()); + context.bindFramebuffer.set(fbo.framebuffer); + } +} +function createHeatmapFbo(context, width, height) { + var _a, _b; + const gl = context.gl; + const texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + // Use the higher precision half-float texture where available (producing much smoother looking heatmaps); + // Otherwise, fall back to a low precision texture + const numType = (_a = context.HALF_FLOAT) !== null && _a !== void 0 ? _a : gl.UNSIGNED_BYTE; + const internalFormat = (_b = context.RGBA16F) !== null && _b !== void 0 ? _b : gl.RGBA; + gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, width, height, 0, gl.RGBA, numType, null); + const fbo = context.createFramebuffer(width, height, false, false); + fbo.colorAttachment.set(texture); + return fbo; +} +function getColorRampTexture(context, layer) { + if (!layer.colorRampTexture) { + layer.colorRampTexture = new Texture(context, layer.colorRamp, context.gl.RGBA); + } + return layer.colorRampTexture; +} + +function drawLine(painter, sourceCache, layer, coords) { + if (painter.renderPass !== 'translucent') + return; + const opacity = layer.paint.get('line-opacity'); + const width = layer.paint.get('line-width'); + if (opacity.constantOr(1) === 0 || width.constantOr(1) === 0) + return; + const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly); + const colorMode = painter.colorModeForRenderPass(); + const dasharray = layer.paint.get('line-dasharray'); + const patternProperty = layer.paint.get('line-pattern'); + const image = patternProperty.constantOr(1); + const gradient = layer.paint.get('line-gradient'); + const crossfade = layer.getCrossfadeParameters(); + const programId = image ? 'linePattern' : + dasharray ? 'lineSDF' : + gradient ? 'lineGradient' : 'line'; + const context = painter.context; + const gl = context.gl; + let firstTile = true; + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + if (image && !tile.patternsLoaded()) + continue; + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const programConfiguration = bucket.programConfigurations.get(layer.id); + const prevProgram = painter.context.program.get(); + const program = painter.useProgram(programId, programConfiguration); + const programChanged = firstTile || program.program !== prevProgram; + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + const constantPattern = patternProperty.constantOr(null); + if (constantPattern && tile.imageAtlas) { + const atlas = tile.imageAtlas; + const posTo = atlas.patternPositions[constantPattern.to.toString()]; + const posFrom = atlas.patternPositions[constantPattern.from.toString()]; + if (posTo && posFrom) + programConfiguration.setConstantPatternPositions(posTo, posFrom); + } + const terrainCoord = terrainData ? coord : null; + const uniformValues = image ? linePatternUniformValues(painter, tile, layer, crossfade, terrainCoord) : + dasharray ? lineSDFUniformValues(painter, tile, layer, dasharray, crossfade, terrainCoord) : + gradient ? lineGradientUniformValues(painter, tile, layer, bucket.lineClipsArray.length, terrainCoord) : + lineUniformValues(painter, tile, layer, terrainCoord); + if (image) { + context.activeTexture.set(gl.TEXTURE0); + tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + programConfiguration.updatePaintBuffers(crossfade); + } + else if (dasharray && (programChanged || painter.lineAtlas.dirty)) { + context.activeTexture.set(gl.TEXTURE0); + painter.lineAtlas.bind(context); + } + else if (gradient) { + const layerGradient = bucket.gradients[layer.id]; + let gradientTexture = layerGradient.texture; + if (layer.gradientVersion !== layerGradient.version) { + let textureResolution = 256; + if (layer.stepInterpolant) { + const sourceMaxZoom = sourceCache.getSource().maxzoom; + const potentialOverzoom = coord.canonical.z === sourceMaxZoom ? + Math.ceil(1 << (painter.transform.maxZoom - coord.canonical.z)) : 1; + const lineLength = bucket.maxLineLength / performance$1.EXTENT; + // Logical pixel tile size is 512px, and 1024px right before current zoom + 1 + const maxTilePixelSize = 1024; + // Maximum possible texture coverage heuristic, bound by hardware max texture size + const maxTextureCoverage = lineLength * maxTilePixelSize * potentialOverzoom; + textureResolution = performance$1.clamp(performance$1.nextPowerOfTwo(maxTextureCoverage), 256, context.maxTextureSize); + } + layerGradient.gradient = performance$1.renderColorRamp({ + expression: layer.gradientExpression(), + evaluationKey: 'lineProgress', + resolution: textureResolution, + image: layerGradient.gradient || undefined, + clips: bucket.lineClipsArray + }); + if (layerGradient.texture) { + layerGradient.texture.update(layerGradient.gradient); + } + else { + layerGradient.texture = new Texture(context, layerGradient.gradient, gl.RGBA); + } + layerGradient.version = layer.gradientVersion; + gradientTexture = layerGradient.texture; + } + context.activeTexture.set(gl.TEXTURE0); + gradientTexture.bind(layer.stepInterpolant ? gl.NEAREST : gl.LINEAR, gl.CLAMP_TO_EDGE); + } + program.draw(context, gl.TRIANGLES, depthMode, painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration, bucket.layoutVertexBuffer2); + firstTile = false; + // once refactored so that bound texture state is managed, we'll also be able to remove this firstTile/programChanged logic + } +} + +/** + * A simple helper shared by draw_fill and draw_fill_extrusions to find the correct pattern positions AND update program. + * For transitionable properties, especially 'fill-pattern' and 'fill-extrusion-pattern', while rendering certain frames + * tile.imageAtlas has been updated by worker to hold the new pattern only, but rendering code is still looking for the previous image. + * The mismatch was causing setConstantPatternPositions method not being called and pixelRatio was always the + * default of 1, instead of actual values set by original map.addImage. + * + * @param programConfiguration - to be used to set pattern position and device pixel ratio. + * @param propertyName - 'fill-pattern' or 'fill-extrusion-pattern' property key + * @param constantPattern - either 'fill-pattern' or 'fill-extrusion-pattern' property value + * @param tile - current tile being drawn + * @param layer - current layer being rendered + */ +function updatePatternPositionsInProgram(programConfiguration, propertyName, constantPattern, tile, layer) { + if (!constantPattern || !tile || !tile.imageAtlas) { + return; + } + const patternPositions = tile.imageAtlas.patternPositions; + let posTo = patternPositions[constantPattern.to.toString()]; + let posFrom = patternPositions[constantPattern.from.toString()]; + // https://github.com/maplibre/maplibre-gl-js/issues/3377 + if (!posTo && posFrom) + posTo = posFrom; + if (!posFrom && posTo) + posFrom = posTo; + // try again in case patternPositions has been updated by worker + if (!posTo || !posFrom) { + const transitioned = layer.getPaintProperty(propertyName); + posTo = patternPositions[transitioned]; + posFrom = patternPositions[transitioned]; + } + if (posTo && posFrom) { + programConfiguration.setConstantPatternPositions(posTo, posFrom); + } +} + +function drawFill(painter, sourceCache, layer, coords) { + const color = layer.paint.get('fill-color'); + const opacity = layer.paint.get('fill-opacity'); + if (opacity.constantOr(1) === 0) { + return; + } + const colorMode = painter.colorModeForRenderPass(); + const pattern = layer.paint.get('fill-pattern'); + const pass = painter.opaquePassEnabledForLayer() && + (!pattern.constantOr(1) && + color.constantOr(performance$1.Color.transparent).a === 1 && + opacity.constantOr(0) === 1) ? 'opaque' : 'translucent'; + // Draw fill + if (painter.renderPass === pass) { + const depthMode = painter.depthModeForSublayer(1, painter.renderPass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly); + drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, false); + } + // Draw stroke + if (painter.renderPass === 'translucent' && layer.paint.get('fill-antialias')) { + // If we defined a different color for the fill outline, we are + // going to ignore the bits in 0x07 and just care about the global + // clipping mask. + // Otherwise, we only want to drawFill the antialiased parts that are + // *outside* the current shape. This is important in case the fill + // or stroke color is translucent. If we wouldn't clip to outside + // the current shape, some pixels from the outline stroke overlapped + // the (non-antialiased) fill. + const depthMode = painter.depthModeForSublayer(layer.getPaintProperty('fill-outline-color') ? 2 : 0, DepthMode.ReadOnly); + drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, true); + } +} +function drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, isOutline) { + const gl = painter.context.gl; + const fillPropertyName = 'fill-pattern'; + const patternProperty = layer.paint.get(fillPropertyName); + const image = patternProperty && patternProperty.constantOr(1); + const crossfade = layer.getCrossfadeParameters(); + let drawMode, programName, uniformValues, indexBuffer, segments; + if (!isOutline) { + programName = image ? 'fillPattern' : 'fill'; + drawMode = gl.TRIANGLES; + } + else { + programName = image && !layer.getPaintProperty('fill-outline-color') ? 'fillOutlinePattern' : 'fillOutline'; + drawMode = gl.LINES; + } + const constantPattern = patternProperty.constantOr(null); + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + if (image && !tile.patternsLoaded()) + continue; + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram(programName, programConfiguration); + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + if (image) { + painter.context.activeTexture.set(gl.TEXTURE0); + tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + programConfiguration.updatePaintBuffers(crossfade); + } + updatePatternPositionsInProgram(programConfiguration, fillPropertyName, constantPattern, tile, layer); + const terrainCoord = terrainData ? coord : null; + const posMatrix = terrainCoord ? terrainCoord.posMatrix : coord.posMatrix; + const tileMatrix = painter.translatePosMatrix(posMatrix, tile, layer.paint.get('fill-translate'), layer.paint.get('fill-translate-anchor')); + if (!isOutline) { + indexBuffer = bucket.indexBuffer; + segments = bucket.segments; + uniformValues = image ? + fillPatternUniformValues(tileMatrix, painter, crossfade, tile) : + fillUniformValues(tileMatrix); + } + else { + indexBuffer = bucket.indexBuffer2; + segments = bucket.segments2; + const drawingBufferSize = [gl.drawingBufferWidth, gl.drawingBufferHeight]; + uniformValues = (programName === 'fillOutlinePattern' && image) ? + fillOutlinePatternUniformValues(tileMatrix, painter, crossfade, tile, drawingBufferSize) : + fillOutlineUniformValues(tileMatrix, drawingBufferSize); + } + program.draw(painter.context, drawMode, depthMode, painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, bucket.layoutVertexBuffer, indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration); + } +} + +function drawFillExtrusion(painter, source, layer, coords) { + const opacity = layer.paint.get('fill-extrusion-opacity'); + if (opacity === 0) { + return; + } + if (painter.renderPass === 'translucent') { + const depthMode = new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D); + if (opacity === 1 && !layer.paint.get('fill-extrusion-pattern').constantOr(1)) { + const colorMode = painter.colorModeForRenderPass(); + drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, colorMode); + } + else { + // Draw transparent buildings in two passes so that only the closest surface is drawn. + // First draw all the extrusions into only the depth buffer. No colors are drawn. + drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, ColorMode.disabled); + // Then draw all the extrusions a second type, only coloring fragments if they have the + // same depth value as the closest fragment in the previous pass. Use the stencil buffer + // to prevent the second draw in cases where we have coincident polygons. + drawExtrusionTiles(painter, source, layer, coords, depthMode, painter.stencilModeFor3D(), painter.colorModeForRenderPass()); + } + } +} +function drawExtrusionTiles(painter, source, layer, coords, depthMode, stencilMode, colorMode) { + const context = painter.context; + const gl = context.gl; + const fillPropertyName = 'fill-extrusion-pattern'; + const patternProperty = layer.paint.get(fillPropertyName); + const image = patternProperty.constantOr(1); + const crossfade = layer.getCrossfadeParameters(); + const opacity = layer.paint.get('fill-extrusion-opacity'); + const constantPattern = patternProperty.constantOr(null); + for (const coord of coords) { + const tile = source.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram(image ? 'fillExtrusionPattern' : 'fillExtrusion', programConfiguration); + if (image) { + painter.context.activeTexture.set(gl.TEXTURE0); + tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + programConfiguration.updatePaintBuffers(crossfade); + } + updatePatternPositionsInProgram(programConfiguration, fillPropertyName, constantPattern, tile, layer); + const matrix = painter.translatePosMatrix(coord.posMatrix, tile, layer.paint.get('fill-extrusion-translate'), layer.paint.get('fill-extrusion-translate-anchor')); + const shouldUseVerticalGradient = layer.paint.get('fill-extrusion-vertical-gradient'); + const uniformValues = image ? + fillExtrusionPatternUniformValues(matrix, painter, shouldUseVerticalGradient, opacity, coord, crossfade, tile) : + fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity); + program.draw(context, context.gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration, painter.style.map.terrain && bucket.centroidVertexBuffer); + } +} + +function drawHillshade(painter, sourceCache, layer, tileIDs) { + if (painter.renderPass !== 'offscreen' && painter.renderPass !== 'translucent') + return; + const context = painter.context; + const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly); + const colorMode = painter.colorModeForRenderPass(); + const [stencilModes, coords] = painter.renderPass === 'translucent' ? + painter.stencilConfigForOverlap(tileIDs) : [{}, tileIDs]; + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + if (typeof tile.needsHillshadePrepare !== 'undefined' && tile.needsHillshadePrepare && painter.renderPass === 'offscreen') { + prepareHillshade(painter, tile, layer, depthMode, StencilMode.disabled, colorMode); + } + else if (painter.renderPass === 'translucent') { + renderHillshade(painter, coord, tile, layer, depthMode, stencilModes[coord.overscaledZ], colorMode); + } + } + context.viewport.set([0, 0, painter.width, painter.height]); +} +function renderHillshade(painter, coord, tile, layer, depthMode, stencilMode, colorMode) { + const context = painter.context; + const gl = context.gl; + const fbo = tile.fbo; + if (!fbo) + return; + const program = painter.useProgram('hillshade'); + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get()); + const terrainCoord = terrainData ? coord : null; + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, hillshadeUniformValues(painter, tile, layer, terrainCoord), terrainData, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments); +} +// hillshade rendering is done in two steps. the prepare step first calculates the slope of the terrain in the x and y +// directions for each pixel, and saves those values to a framebuffer texture in the r and g channels. +function prepareHillshade(painter, tile, layer, depthMode, stencilMode, colorMode) { + const context = painter.context; + const gl = context.gl; + const dem = tile.dem; + if (dem && dem.data) { + const tileSize = dem.dim; + const textureStride = dem.stride; + const pixelData = dem.getPixels(); + context.activeTexture.set(gl.TEXTURE1); + context.pixelStoreUnpackPremultiplyAlpha.set(false); + tile.demTexture = tile.demTexture || painter.getTileTexture(textureStride); + if (tile.demTexture) { + const demTexture = tile.demTexture; + demTexture.update(pixelData, { premultiply: false }); + demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE); + } + else { + tile.demTexture = new Texture(context, pixelData, gl.RGBA, { premultiply: false }); + tile.demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE); + } + context.activeTexture.set(gl.TEXTURE0); + let fbo = tile.fbo; + if (!fbo) { + const renderTexture = new Texture(context, { width: tileSize, height: tileSize, data: null }, gl.RGBA); + renderTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + fbo = tile.fbo = context.createFramebuffer(tileSize, tileSize, true, false); + fbo.colorAttachment.set(renderTexture.texture); + } + context.bindFramebuffer.set(fbo.framebuffer); + context.viewport.set([0, 0, tileSize, tileSize]); + painter.useProgram('hillshadePrepare').draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, hillshadeUniformPrepareValues(tile.tileID, dem), null, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments); + tile.needsHillshadePrepare = false; + } +} + +function drawRaster(painter, sourceCache, layer, tileIDs) { + if (painter.renderPass !== 'translucent') + return; + if (layer.paint.get('raster-opacity') === 0) + return; + if (!tileIDs.length) + return; + const context = painter.context; + const gl = context.gl; + const source = sourceCache.getSource(); + const program = painter.useProgram('raster'); + const colorMode = painter.colorModeForRenderPass(); + const [stencilModes, coords] = source instanceof ImageSource ? [{}, tileIDs] : + painter.stencilConfigForOverlap(tileIDs); + const minTileZ = coords[coords.length - 1].overscaledZ; + const align = !painter.options.moving; + for (const coord of coords) { + // Set the lower zoom level to sublayer 0, and higher zoom levels to higher sublayers + // Use gl.LESS to prevent double drawing in areas where tiles overlap. + const depthMode = painter.depthModeForSublayer(coord.overscaledZ - minTileZ, layer.paint.get('raster-opacity') === 1 ? DepthMode.ReadWrite : DepthMode.ReadOnly, gl.LESS); + const tile = sourceCache.getTile(coord); + tile.registerFadeDuration(layer.paint.get('raster-fade-duration')); + const parentTile = sourceCache.findLoadedParent(coord, 0); + const siblingTile = sourceCache.findLoadedSibling(coord); + // Prefer parent tile if present + const fadeTileReference = parentTile || siblingTile || null; + const fade = getFadeValues(tile, fadeTileReference, sourceCache, layer, painter.transform, painter.style.map.terrain); + let parentScaleBy, parentTL; + const textureFilter = layer.paint.get('raster-resampling') === 'nearest' ? gl.NEAREST : gl.LINEAR; + context.activeTexture.set(gl.TEXTURE0); + tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST); + context.activeTexture.set(gl.TEXTURE1); + if (parentTile) { + parentTile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST); + parentScaleBy = Math.pow(2, parentTile.tileID.overscaledZ - tile.tileID.overscaledZ); + parentTL = [tile.tileID.canonical.x * parentScaleBy % 1, tile.tileID.canonical.y * parentScaleBy % 1]; + } + else { + tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST); + } + // Enable anisotropic filtering only when the pitch is greater than 20 degrees + // to preserve image sharpness on flat or slightly tilted maps. + if (tile.texture.useMipmap && context.extTextureFilterAnisotropic && painter.transform.pitch > 20) { + gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax); + } + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + const terrainCoord = terrainData ? coord : null; + const posMatrix = terrainCoord ? terrainCoord.posMatrix : painter.transform.calculatePosMatrix(coord.toUnwrapped(), align); + const uniformValues = rasterUniformValues(posMatrix, parentTL || [0, 0], parentScaleBy || 1, fade, layer); + if (source instanceof ImageSource) { + program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, source.boundsBuffer, painter.quadTriangleIndexBuffer, source.boundsSegments); + } + else { + program.draw(context, gl.TRIANGLES, depthMode, stencilModes[coord.overscaledZ], colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments); + } + } +} +function getFadeValues(tile, parentTile, sourceCache, layer, transform, terrain) { + const fadeDuration = layer.paint.get('raster-fade-duration'); + if (!terrain && fadeDuration > 0) { + const now = browser.now(); + const sinceTile = (now - tile.timeAdded) / fadeDuration; + const sinceParent = parentTile ? (now - parentTile.timeAdded) / fadeDuration : -1; + const source = sourceCache.getSource(); + const idealZ = transform.coveringZoomLevel({ + tileSize: source.tileSize, + roundZoom: source.roundZoom + }); + // if no parent or parent is older, fade in; if parent is younger, fade out + const fadeIn = !parentTile || Math.abs(parentTile.tileID.overscaledZ - idealZ) > Math.abs(tile.tileID.overscaledZ - idealZ); + const childOpacity = (fadeIn && tile.refreshedUponExpiration) ? 1 : performance$1.clamp(fadeIn ? sinceTile : 1 - sinceParent, 0, 1); + // we don't crossfade tiles that were just refreshed upon expiring: + // once they're old enough to pass the crossfading threshold + // (fadeDuration), unset the `refreshedUponExpiration` flag so we don't + // incorrectly fail to crossfade them when zooming + if (tile.refreshedUponExpiration && sinceTile >= 1) + tile.refreshedUponExpiration = false; + if (parentTile) { + return { + opacity: 1, + mix: 1 - childOpacity + }; + } + else { + return { + opacity: childOpacity, + mix: 0 + }; + } + } + else { + return { + opacity: 1, + mix: 0 + }; + } +} + +function drawBackground(painter, sourceCache, layer, coords) { + const color = layer.paint.get('background-color'); + const opacity = layer.paint.get('background-opacity'); + if (opacity === 0) + return; + const context = painter.context; + const gl = context.gl; + const transform = painter.transform; + const tileSize = transform.tileSize; + const image = layer.paint.get('background-pattern'); + if (painter.isPatternMissing(image)) + return; + const pass = (!image && color.a === 1 && opacity === 1 && painter.opaquePassEnabledForLayer()) ? 'opaque' : 'translucent'; + if (painter.renderPass !== pass) + return; + const stencilMode = StencilMode.disabled; + const depthMode = painter.depthModeForSublayer(0, pass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly); + const colorMode = painter.colorModeForRenderPass(); + const program = painter.useProgram(image ? 'backgroundPattern' : 'background'); + const tileIDs = coords ? coords : transform.coveringTiles({ tileSize, terrain: painter.style.map.terrain }); + if (image) { + context.activeTexture.set(gl.TEXTURE0); + painter.imageManager.bind(painter.context); + } + const crossfade = layer.getCrossfadeParameters(); + for (const tileID of tileIDs) { + const matrix = coords ? tileID.posMatrix : painter.transform.calculatePosMatrix(tileID.toUnwrapped()); + const uniformValues = image ? + backgroundPatternUniformValues(matrix, opacity, painter, image, { tileID, tileSize }, crossfade) : + backgroundUniformValues(matrix, opacity, color); + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(tileID); + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, painter.tileExtentBuffer, painter.quadTriangleIndexBuffer, painter.tileExtentSegments); + } +} + +const topColor = new performance$1.Color(1, 0, 0, 1); +const btmColor = new performance$1.Color(0, 1, 0, 1); +const leftColor = new performance$1.Color(0, 0, 1, 1); +const rightColor = new performance$1.Color(1, 0, 1, 1); +const centerColor = new performance$1.Color(0, 1, 1, 1); +function drawDebugPadding(painter) { + const padding = painter.transform.padding; + const lineWidth = 3; + // Top + drawHorizontalLine(painter, painter.transform.height - (padding.top || 0), lineWidth, topColor); + // Bottom + drawHorizontalLine(painter, padding.bottom || 0, lineWidth, btmColor); + // Left + drawVerticalLine(painter, padding.left || 0, lineWidth, leftColor); + // Right + drawVerticalLine(painter, painter.transform.width - (padding.right || 0), lineWidth, rightColor); + // Center + const center = painter.transform.centerPoint; + drawCrosshair(painter, center.x, painter.transform.height - center.y, centerColor); +} +function drawCrosshair(painter, x, y, color) { + const size = 20; + const lineWidth = 2; + //Vertical line + drawDebugSSRect(painter, x - lineWidth / 2, y - size / 2, lineWidth, size, color); + //Horizontal line + drawDebugSSRect(painter, x - size / 2, y - lineWidth / 2, size, lineWidth, color); +} +function drawHorizontalLine(painter, y, lineWidth, color) { + drawDebugSSRect(painter, 0, y + lineWidth / 2, painter.transform.width, lineWidth, color); +} +function drawVerticalLine(painter, x, lineWidth, color) { + drawDebugSSRect(painter, x - lineWidth / 2, 0, lineWidth, painter.transform.height, color); +} +function drawDebugSSRect(painter, x, y, width, height, color) { + const context = painter.context; + const gl = context.gl; + gl.enable(gl.SCISSOR_TEST); + gl.scissor(x * painter.pixelRatio, y * painter.pixelRatio, width * painter.pixelRatio, height * painter.pixelRatio); + context.clear({ color }); + gl.disable(gl.SCISSOR_TEST); +} +function drawDebug(painter, sourceCache, coords) { + for (let i = 0; i < coords.length; i++) { + drawDebugTile(painter, sourceCache, coords[i]); + } +} +function drawDebugTile(painter, sourceCache, coord) { + const context = painter.context; + const gl = context.gl; + const posMatrix = coord.posMatrix; + const program = painter.useProgram('debug'); + const depthMode = DepthMode.disabled; + const stencilMode = StencilMode.disabled; + const colorMode = painter.colorModeForRenderPass(); + const id = '$debug'; + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + context.activeTexture.set(gl.TEXTURE0); + const tileRawData = sourceCache.getTileByID(coord.key).latestRawTileData; + const tileByteLength = (tileRawData && tileRawData.byteLength) || 0; + const tileSizeKb = Math.floor(tileByteLength / 1024); + const tileSize = sourceCache.getTile(coord).tileSize; + const scaleRatio = (512 / Math.min(tileSize, 512) * (coord.overscaledZ / painter.transform.zoom)) * 0.5; + let tileIdText = coord.canonical.toString(); + if (coord.overscaledZ !== coord.canonical.z) { + tileIdText += ` => ${coord.overscaledZ}`; + } + const tileLabel = `${tileIdText} ${tileSizeKb}kB`; + drawTextToOverlay(painter, tileLabel); + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, ColorMode.alphaBlended, CullFaceMode.disabled, debugUniformValues(posMatrix, performance$1.Color.transparent, scaleRatio), null, id, painter.debugBuffer, painter.quadTriangleIndexBuffer, painter.debugSegments); + program.draw(context, gl.LINE_STRIP, depthMode, stencilMode, colorMode, CullFaceMode.disabled, debugUniformValues(posMatrix, performance$1.Color.red), terrainData, id, painter.debugBuffer, painter.tileBorderIndexBuffer, painter.debugSegments); +} +function drawTextToOverlay(painter, text) { + painter.initDebugOverlayCanvas(); + const canvas = painter.debugOverlayCanvas; + const gl = painter.context.gl; + const ctx2d = painter.debugOverlayCanvas.getContext('2d'); + ctx2d.clearRect(0, 0, canvas.width, canvas.height); + ctx2d.shadowColor = 'white'; + ctx2d.shadowBlur = 2; + ctx2d.lineWidth = 1.5; + ctx2d.strokeStyle = 'white'; + ctx2d.textBaseline = 'top'; + ctx2d.font = `bold ${36}px Open Sans, sans-serif`; + ctx2d.fillText(text, 5, 5); + ctx2d.strokeText(text, 5, 5); + painter.debugOverlayTexture.update(canvas); + painter.debugOverlayTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); +} +function selectDebugSource(style, zoom) { + // Use vector source with highest maxzoom + // Else use source with highest maxzoom of any type + let selectedSource = null; + const layers = Object.values(style._layers); + const sources = layers.flatMap((layer) => { + if (layer.source && !layer.isHidden(zoom)) { + const sourceCache = style.sourceCaches[layer.source]; + return [sourceCache]; + } + else { + return []; + } + }); + const vectorSources = sources.filter((source) => source.getSource().type === 'vector'); + const otherSources = sources.filter((source) => source.getSource().type !== 'vector'); + const considerSource = (source) => { + if (!selectedSource || (selectedSource.getSource().maxzoom < source.getSource().maxzoom)) { + selectedSource = source; + } + }; + vectorSources.forEach((source) => considerSource(source)); + if (!selectedSource) { + otherSources.forEach((source) => considerSource(source)); + } + return selectedSource; +} + +function drawCustom(painter, sourceCache, layer) { + const context = painter.context; + const implementation = layer.implementation; + if (painter.renderPass === 'offscreen') { + const prerender = implementation.prerender; + if (prerender) { + painter.setCustomLayerDefaults(); + context.setColorMode(painter.colorModeForRenderPass()); + prerender.call(implementation, context.gl, painter.transform.customLayerMatrix()); + context.setDirty(); + painter.setBaseState(); + } + } + else if (painter.renderPass === 'translucent') { + painter.setCustomLayerDefaults(); + context.setColorMode(painter.colorModeForRenderPass()); + context.setStencilMode(StencilMode.disabled); + const depthMode = implementation.renderingMode === '3d' ? + new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D) : + painter.depthModeForSublayer(0, DepthMode.ReadOnly); + context.setDepthMode(depthMode); + implementation.render(context.gl, painter.transform.customLayerMatrix(), { farZ: painter.transform.farZ, nearZ: painter.transform.nearZ, fov: painter.transform._fov, modelViewProjectionMatrix: painter.transform.modelViewProjectionMatrix, projectionMatrix: painter.transform.projectionMatrix }); + context.setDirty(); + painter.setBaseState(); + context.bindFramebuffer.set(null); + } +} + +/** + * Redraw the Depth Framebuffer + * @param painter - the painter + * @param terrain - the terrain + */ +function drawDepth(painter, terrain) { + const context = painter.context; + const gl = context.gl; + const colorMode = ColorMode.unblended; + const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]); + const mesh = terrain.getTerrainMesh(); + const tiles = terrain.sourceCache.getRenderableTiles(); + const program = painter.useProgram('terrainDepth'); + context.bindFramebuffer.set(terrain.getFramebuffer('depth').framebuffer); + context.viewport.set([0, 0, painter.width / devicePixelRatio, painter.height / devicePixelRatio]); + context.clear({ color: performance$1.Color.transparent, depth: 1 }); + for (const tile of tiles) { + const terrainData = terrain.getTerrainData(tile.tileID); + const posMatrix = painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped()); + const uniformValues = terrainDepthUniformValues(posMatrix, terrain.getMeshFrameDelta(painter.transform.zoom)); + program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments); + } + context.bindFramebuffer.set(null); + context.viewport.set([0, 0, painter.width, painter.height]); +} +/** + * Redraw the Coords Framebuffers + * @param painter - the painter + * @param terrain - the terrain + */ +function drawCoords(painter, terrain) { + const context = painter.context; + const gl = context.gl; + const colorMode = ColorMode.unblended; + const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]); + const mesh = terrain.getTerrainMesh(); + const coords = terrain.getCoordsTexture(); + const tiles = terrain.sourceCache.getRenderableTiles(); + // draw tile-coords into framebuffer + const program = painter.useProgram('terrainCoords'); + context.bindFramebuffer.set(terrain.getFramebuffer('coords').framebuffer); + context.viewport.set([0, 0, painter.width / devicePixelRatio, painter.height / devicePixelRatio]); + context.clear({ color: performance$1.Color.transparent, depth: 1 }); + terrain.coordsIndex = []; + for (const tile of tiles) { + const terrainData = terrain.getTerrainData(tile.tileID); + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, coords.texture); + const posMatrix = painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped()); + const uniformValues = terrainCoordsUniformValues(posMatrix, 255 - terrain.coordsIndex.length, terrain.getMeshFrameDelta(painter.transform.zoom)); + program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments); + terrain.coordsIndex.push(tile.tileID.key); + } + context.bindFramebuffer.set(null); + context.viewport.set([0, 0, painter.width, painter.height]); +} +function drawTerrain(painter, terrain, tiles) { + const context = painter.context; + const gl = context.gl; + const colorMode = painter.colorModeForRenderPass(); + const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D); + const program = painter.useProgram('terrain'); + const mesh = terrain.getTerrainMesh(); + context.bindFramebuffer.set(null); + context.viewport.set([0, 0, painter.width, painter.height]); + for (const tile of tiles) { + const texture = painter.renderToTexture.getTexture(tile); + const terrainData = terrain.getTerrainData(tile.tileID); + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + const posMatrix = painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped()); + const eleDelta = terrain.getMeshFrameDelta(painter.transform.zoom); + const fogMatrix = painter.transform.calculateFogMatrix(tile.tileID.toUnwrapped()); + const uniformValues = terrainUniformValues(posMatrix, eleDelta, fogMatrix, painter.style.sky, painter.transform.pitch); + program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments); + } +} + +class Mesh { + constructor(vertexBuffer, indexBuffer, segments) { + this.vertexBuffer = vertexBuffer; + this.indexBuffer = indexBuffer; + this.segments = segments; + } + destroy() { + this.vertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.segments.destroy(); + this.vertexBuffer = null; + this.indexBuffer = null; + this.segments = null; + } +} + +function drawSky(painter, sky) { + const context = painter.context; + const gl = context.gl; + const skyUniforms = skyUniformValues(sky, painter.style.map.transform, painter.pixelRatio); + const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]); + const stencilMode = StencilMode.disabled; + const colorMode = painter.colorModeForRenderPass(); + const program = painter.useProgram('sky'); + if (!sky.mesh) { + const vertexArray = new performance$1.PosArray(); + vertexArray.emplaceBack(-1, -1); + vertexArray.emplaceBack(1, -1); + vertexArray.emplaceBack(1, 1); + vertexArray.emplaceBack(-1, 1); + const indexArray = new performance$1.TriangleIndexArray(); + indexArray.emplaceBack(0, 1, 2); + indexArray.emplaceBack(0, 2, 3); + sky.mesh = new Mesh(context.createVertexBuffer(vertexArray, posAttributes.members), context.createIndexBuffer(indexArray), performance$1.SegmentVector.simpleSegment(0, 0, vertexArray.length, indexArray.length)); + } + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, skyUniforms, undefined, 'sky', sky.mesh.vertexBuffer, sky.mesh.indexBuffer, sky.mesh.segments); +} + +/** + * @internal + * Initialize a new painter object. + */ +class Painter { + constructor(gl, transform) { + this.context = new Context(gl); + this.transform = transform; + this._tileTextures = {}; + this.terrainFacilitator = { dirty: true, matrix: performance$1.identity(new Float64Array(16)), renderTime: 0 }; + this.setup(); + // Within each layer there are multiple distinct z-planes that can be drawn to. + // This is implemented using the WebGL depth buffer. + this.numSublayers = SourceCache.maxUnderzooming + SourceCache.maxOverzooming + 1; + this.depthEpsilon = 1 / Math.pow(2, 16); + this.crossTileSymbolIndex = new CrossTileSymbolIndex(); + } + /* + * Update the GL viewport, projection matrix, and transforms to compensate + * for a new width and height value. + */ + resize(width, height, pixelRatio) { + this.width = Math.floor(width * pixelRatio); + this.height = Math.floor(height * pixelRatio); + this.pixelRatio = pixelRatio; + this.context.viewport.set([0, 0, this.width, this.height]); + if (this.style) { + for (const layerId of this.style._order) { + this.style._layers[layerId].resize(); + } + } + } + setup() { + const context = this.context; + const tileExtentArray = new performance$1.PosArray(); + tileExtentArray.emplaceBack(0, 0); + tileExtentArray.emplaceBack(performance$1.EXTENT, 0); + tileExtentArray.emplaceBack(0, performance$1.EXTENT); + tileExtentArray.emplaceBack(performance$1.EXTENT, performance$1.EXTENT); + this.tileExtentBuffer = context.createVertexBuffer(tileExtentArray, posAttributes.members); + this.tileExtentSegments = performance$1.SegmentVector.simpleSegment(0, 0, 4, 2); + const debugArray = new performance$1.PosArray(); + debugArray.emplaceBack(0, 0); + debugArray.emplaceBack(performance$1.EXTENT, 0); + debugArray.emplaceBack(0, performance$1.EXTENT); + debugArray.emplaceBack(performance$1.EXTENT, performance$1.EXTENT); + this.debugBuffer = context.createVertexBuffer(debugArray, posAttributes.members); + this.debugSegments = performance$1.SegmentVector.simpleSegment(0, 0, 4, 5); + const rasterBoundsArray = new performance$1.RasterBoundsArray(); + rasterBoundsArray.emplaceBack(0, 0, 0, 0); + rasterBoundsArray.emplaceBack(performance$1.EXTENT, 0, performance$1.EXTENT, 0); + rasterBoundsArray.emplaceBack(0, performance$1.EXTENT, 0, performance$1.EXTENT); + rasterBoundsArray.emplaceBack(performance$1.EXTENT, performance$1.EXTENT, performance$1.EXTENT, performance$1.EXTENT); + this.rasterBoundsBuffer = context.createVertexBuffer(rasterBoundsArray, rasterBoundsAttributes.members); + this.rasterBoundsSegments = performance$1.SegmentVector.simpleSegment(0, 0, 4, 2); + const viewportArray = new performance$1.PosArray(); + viewportArray.emplaceBack(0, 0); + viewportArray.emplaceBack(1, 0); + viewportArray.emplaceBack(0, 1); + viewportArray.emplaceBack(1, 1); + this.viewportBuffer = context.createVertexBuffer(viewportArray, posAttributes.members); + this.viewportSegments = performance$1.SegmentVector.simpleSegment(0, 0, 4, 2); + const tileLineStripIndices = new performance$1.LineStripIndexArray(); + tileLineStripIndices.emplaceBack(0); + tileLineStripIndices.emplaceBack(1); + tileLineStripIndices.emplaceBack(3); + tileLineStripIndices.emplaceBack(2); + tileLineStripIndices.emplaceBack(0); + this.tileBorderIndexBuffer = context.createIndexBuffer(tileLineStripIndices); + const quadTriangleIndices = new performance$1.TriangleIndexArray(); + quadTriangleIndices.emplaceBack(0, 1, 2); + quadTriangleIndices.emplaceBack(2, 1, 3); + this.quadTriangleIndexBuffer = context.createIndexBuffer(quadTriangleIndices); + const gl = this.context.gl; + this.stencilClearMode = new StencilMode({ func: gl.ALWAYS, mask: 0 }, 0x0, 0xFF, gl.ZERO, gl.ZERO, gl.ZERO); + } + /* + * Reset the drawing canvas by clearing the stencil buffer so that we can draw + * new tiles at the same location, while retaining previously drawn pixels. + */ + clearStencil() { + const context = this.context; + const gl = context.gl; + this.nextStencilID = 1; + this.currentStencilSource = undefined; + // As a temporary workaround for https://github.com/mapbox/mapbox-gl-js/issues/5490, + // pending an upstream fix, we draw a fullscreen stencil=0 clipping mask here, + // effectively clearing the stencil buffer: once an upstream patch lands, remove + // this function in favor of context.clear({ stencil: 0x0 }) + const matrix = performance$1.create(); + performance$1.ortho(matrix, 0, this.width, this.height, 0, 0, 1); + performance$1.scale(matrix, matrix, [gl.drawingBufferWidth, gl.drawingBufferHeight, 0]); + this.useProgram('clippingMask').draw(context, gl.TRIANGLES, DepthMode.disabled, this.stencilClearMode, ColorMode.disabled, CullFaceMode.disabled, clippingMaskUniformValues(matrix), null, '$clipping', this.viewportBuffer, this.quadTriangleIndexBuffer, this.viewportSegments); + } + _renderTileClippingMasks(layer, tileIDs) { + if (this.currentStencilSource === layer.source || !layer.isTileClipped() || !tileIDs || !tileIDs.length) + return; + this.currentStencilSource = layer.source; + const context = this.context; + const gl = context.gl; + if (this.nextStencilID + tileIDs.length > 256) { + // we'll run out of fresh IDs so we need to clear and start from scratch + this.clearStencil(); + } + context.setColorMode(ColorMode.disabled); + context.setDepthMode(DepthMode.disabled); + const program = this.useProgram('clippingMask'); + this._tileClippingMaskIDs = {}; + for (const tileID of tileIDs) { + const id = this._tileClippingMaskIDs[tileID.key] = this.nextStencilID++; + const terrainData = this.style.map.terrain && this.style.map.terrain.getTerrainData(tileID); + program.draw(context, gl.TRIANGLES, DepthMode.disabled, + // Tests will always pass, and ref value will be written to stencil buffer. + new StencilMode({ func: gl.ALWAYS, mask: 0 }, id, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE), ColorMode.disabled, CullFaceMode.disabled, clippingMaskUniformValues(tileID.posMatrix), terrainData, '$clipping', this.tileExtentBuffer, this.quadTriangleIndexBuffer, this.tileExtentSegments); + } + } + stencilModeFor3D() { + this.currentStencilSource = undefined; + if (this.nextStencilID + 1 > 256) { + this.clearStencil(); + } + const id = this.nextStencilID++; + const gl = this.context.gl; + return new StencilMode({ func: gl.NOTEQUAL, mask: 0xFF }, id, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE); + } + stencilModeForClipping(tileID) { + const gl = this.context.gl; + return new StencilMode({ func: gl.EQUAL, mask: 0xFF }, this._tileClippingMaskIDs[tileID.key], 0x00, gl.KEEP, gl.KEEP, gl.REPLACE); + } + /* + * Sort coordinates by Z as drawing tiles is done in Z-descending order. + * All children with the same Z write the same stencil value. Children + * stencil values are greater than parent's. This is used only for raster + * and raster-dem tiles, which are already clipped to tile boundaries, to + * mask area of tile overlapped by children tiles. + * Stencil ref values continue range used in _tileClippingMaskIDs. + * + * Returns [StencilMode for tile overscaleZ map, sortedCoords]. + */ + stencilConfigForOverlap(tileIDs) { + const gl = this.context.gl; + const coords = tileIDs.sort((a, b) => b.overscaledZ - a.overscaledZ); + const minTileZ = coords[coords.length - 1].overscaledZ; + const stencilValues = coords[0].overscaledZ - minTileZ + 1; + if (stencilValues > 1) { + this.currentStencilSource = undefined; + if (this.nextStencilID + stencilValues > 256) { + this.clearStencil(); + } + const zToStencilMode = {}; + for (let i = 0; i < stencilValues; i++) { + zToStencilMode[i + minTileZ] = new StencilMode({ func: gl.GEQUAL, mask: 0xFF }, i + this.nextStencilID, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE); + } + this.nextStencilID += stencilValues; + return [zToStencilMode, coords]; + } + return [{ [minTileZ]: StencilMode.disabled }, coords]; + } + colorModeForRenderPass() { + const gl = this.context.gl; + if (this._showOverdrawInspector) { + const numOverdrawSteps = 8; + const a = 1 / numOverdrawSteps; + return new ColorMode([gl.CONSTANT_COLOR, gl.ONE], new performance$1.Color(a, a, a, 0), [true, true, true, true]); + } + else if (this.renderPass === 'opaque') { + return ColorMode.unblended; + } + else { + return ColorMode.alphaBlended; + } + } + depthModeForSublayer(n, mask, func) { + if (!this.opaquePassEnabledForLayer()) + return DepthMode.disabled; + const depth = 1 - ((1 + this.currentLayer) * this.numSublayers + n) * this.depthEpsilon; + return new DepthMode(func || this.context.gl.LEQUAL, mask, [depth, depth]); + } + /* + * The opaque pass and 3D layers both use the depth buffer. + * Layers drawn above 3D layers need to be drawn using the + * painter's algorithm so that they appear above 3D features. + * This returns true for layers that can be drawn using the + * opaque pass. + */ + opaquePassEnabledForLayer() { + return this.currentLayer < this.opaquePassCutoff; + } + render(style, options) { + this.style = style; + this.options = options; + this.lineAtlas = style.lineAtlas; + this.imageManager = style.imageManager; + this.glyphManager = style.glyphManager; + this.symbolFadeChange = style.placement.symbolFadeChange(browser.now()); + this.imageManager.beginFrame(); + const layerIds = this.style._order; + const sourceCaches = this.style.sourceCaches; + const coordsAscending = {}; + const coordsDescending = {}; + const coordsDescendingSymbol = {}; + for (const id in sourceCaches) { + const sourceCache = sourceCaches[id]; + if (sourceCache.used) { + sourceCache.prepare(this.context); + } + coordsAscending[id] = sourceCache.getVisibleCoordinates(); + coordsDescending[id] = coordsAscending[id].slice().reverse(); + coordsDescendingSymbol[id] = sourceCache.getVisibleCoordinates(true).reverse(); + } + this.opaquePassCutoff = Infinity; + for (let i = 0; i < layerIds.length; i++) { + const layerId = layerIds[i]; + if (this.style._layers[layerId].is3D()) { + this.opaquePassCutoff = i; + break; + } + } + this.maybeDrawDepthAndCoords(false); + if (this.renderToTexture) { + this.renderToTexture.prepareForRender(this.style, this.transform.zoom); + // this is disabled, because render-to-texture is rendering all layers from bottom to top. + this.opaquePassCutoff = 0; + } + // Offscreen pass =============================================== + // We first do all rendering that requires rendering to a separate + // framebuffer, and then save those for rendering back to the map + // later: in doing this we avoid doing expensive framebuffer restores. + this.renderPass = 'offscreen'; + for (const layerId of layerIds) { + const layer = this.style._layers[layerId]; + if (!layer.hasOffscreenPass() || layer.isHidden(this.transform.zoom)) + continue; + const coords = coordsDescending[layer.source]; + if (layer.type !== 'custom' && !coords.length) + continue; + this.renderLayer(this, sourceCaches[layer.source], layer, coords); + } + // Rebind the main framebuffer now that all offscreen layers have been rendered: + this.context.bindFramebuffer.set(null); + // Clear buffers in preparation for drawing to the main framebuffer + this.context.clear({ color: options.showOverdrawInspector ? performance$1.Color.black : performance$1.Color.transparent, depth: 1 }); + this.clearStencil(); + // draw sky first to not overwrite symbols + if (this.style.sky) + drawSky(this, this.style.sky); + this._showOverdrawInspector = options.showOverdrawInspector; + this.depthRangeFor3D = [0, 1 - ((style._order.length + 2) * this.numSublayers * this.depthEpsilon)]; + // Opaque pass =============================================== + // Draw opaque layers top-to-bottom first. + if (!this.renderToTexture) { + this.renderPass = 'opaque'; + for (this.currentLayer = layerIds.length - 1; this.currentLayer >= 0; this.currentLayer--) { + const layer = this.style._layers[layerIds[this.currentLayer]]; + const sourceCache = sourceCaches[layer.source]; + const coords = coordsAscending[layer.source]; + this._renderTileClippingMasks(layer, coords); + this.renderLayer(this, sourceCache, layer, coords); + } + } + // Translucent pass =============================================== + // Draw all other layers bottom-to-top. + this.renderPass = 'translucent'; + for (this.currentLayer = 0; this.currentLayer < layerIds.length; this.currentLayer++) { + const layer = this.style._layers[layerIds[this.currentLayer]]; + const sourceCache = sourceCaches[layer.source]; + if (this.renderToTexture && this.renderToTexture.renderLayer(layer)) + continue; + // For symbol layers in the translucent pass, we add extra tiles to the renderable set + // for cross-tile symbol fading. Symbol layers don't use tile clipping, so no need to render + // separate clipping masks + const coords = (layer.type === 'symbol' ? coordsDescendingSymbol : coordsDescending)[layer.source]; + this._renderTileClippingMasks(layer, coordsAscending[layer.source]); + this.renderLayer(this, sourceCache, layer, coords); + } + if (this.options.showTileBoundaries) { + const selectedSource = selectDebugSource(this.style, this.transform.zoom); + if (selectedSource) { + drawDebug(this, selectedSource, selectedSource.getVisibleCoordinates()); + } + } + if (this.options.showPadding) { + drawDebugPadding(this); + } + // Set defaults for most GL values so that anyone using the state after the render + // encounters more expected values. + this.context.setDefault(); + } + /** + * Update the depth and coords framebuffers, if the contents of those frame buffers is out of date. + * If requireExact is false, then the contents of those frame buffers is not updated if it is close + * to accurate (that is, the camera has not moved much since it was updated last). + */ + maybeDrawDepthAndCoords(requireExact) { + if (!this.style || !this.style.map || !this.style.map.terrain) { + return; + } + const prevMatrix = this.terrainFacilitator.matrix; + const currMatrix = this.transform.modelViewProjectionMatrix; + // Update coords/depth-framebuffer on camera movement, or tile reloading + let doUpdate = this.terrainFacilitator.dirty; + doUpdate || (doUpdate = requireExact ? !performance$1.exactEquals(prevMatrix, currMatrix) : !performance$1.equals(prevMatrix, currMatrix)); + doUpdate || (doUpdate = this.style.map.terrain.sourceCache.tilesAfterTime(this.terrainFacilitator.renderTime).length > 0); + if (!doUpdate) { + return; + } + performance$1.copy(prevMatrix, currMatrix); + this.terrainFacilitator.renderTime = Date.now(); + this.terrainFacilitator.dirty = false; + drawDepth(this, this.style.map.terrain); + drawCoords(this, this.style.map.terrain); + } + renderLayer(painter, sourceCache, layer, coords) { + if (layer.isHidden(this.transform.zoom)) + return; + if (layer.type !== 'background' && layer.type !== 'custom' && !(coords || []).length) + return; + this.id = layer.id; + switch (layer.type) { + case 'symbol': + drawSymbols(painter, sourceCache, layer, coords, this.style.placement.variableOffsets); + break; + case 'circle': + drawCircles(painter, sourceCache, layer, coords); + break; + case 'heatmap': + drawHeatmap(painter, sourceCache, layer, coords); + break; + case 'line': + drawLine(painter, sourceCache, layer, coords); + break; + case 'fill': + drawFill(painter, sourceCache, layer, coords); + break; + case 'fill-extrusion': + drawFillExtrusion(painter, sourceCache, layer, coords); + break; + case 'hillshade': + drawHillshade(painter, sourceCache, layer, coords); + break; + case 'raster': + drawRaster(painter, sourceCache, layer, coords); + break; + case 'background': + drawBackground(painter, sourceCache, layer, coords); + break; + case 'custom': + drawCustom(painter, sourceCache, layer); + break; + } + } + /** + * Transform a matrix to incorporate the *-translate and *-translate-anchor properties into it. + * @param inViewportPixelUnitsUnits - True when the units accepted by the matrix are in viewport pixels instead of tile units. + * @returns matrix + */ + translatePosMatrix(matrix, tile, translate, translateAnchor, inViewportPixelUnitsUnits) { + if (!translate[0] && !translate[1]) + return matrix; + const angle = inViewportPixelUnitsUnits ? + (translateAnchor === 'map' ? this.transform.angle : 0) : + (translateAnchor === 'viewport' ? -this.transform.angle : 0); + if (angle) { + const sinA = Math.sin(angle); + const cosA = Math.cos(angle); + translate = [ + translate[0] * cosA - translate[1] * sinA, + translate[0] * sinA + translate[1] * cosA + ]; + } + const translation = [ + inViewportPixelUnitsUnits ? translate[0] : pixelsToTileUnits(tile, translate[0], this.transform.zoom), + inViewportPixelUnitsUnits ? translate[1] : pixelsToTileUnits(tile, translate[1], this.transform.zoom), + 0 + ]; + const translatedMatrix = new Float32Array(16); + performance$1.translate(translatedMatrix, matrix, translation); + return translatedMatrix; + } + saveTileTexture(texture) { + const textures = this._tileTextures[texture.size[0]]; + if (!textures) { + this._tileTextures[texture.size[0]] = [texture]; + } + else { + textures.push(texture); + } + } + getTileTexture(size) { + const textures = this._tileTextures[size]; + return textures && textures.length > 0 ? textures.pop() : null; + } + /** + * Checks whether a pattern image is needed, and if it is, whether it is not loaded. + * + * @returns true if a needed image is missing and rendering needs to be skipped. + */ + isPatternMissing(image) { + if (!image) + return false; + if (!image.from || !image.to) + return true; + const imagePosA = this.imageManager.getPattern(image.from.toString()); + const imagePosB = this.imageManager.getPattern(image.to.toString()); + return !imagePosA || !imagePosB; + } + useProgram(name, programConfiguration) { + this.cache = this.cache || {}; + const key = name + + (programConfiguration ? programConfiguration.cacheKey : '') + + (this._showOverdrawInspector ? '/overdraw' : '') + + (this.style.map.terrain ? '/terrain' : ''); + if (!this.cache[key]) { + this.cache[key] = new Program(this.context, shaders[name], programConfiguration, programUniforms[name], this._showOverdrawInspector, this.style.map.terrain); + } + return this.cache[key]; + } + /* + * Reset some GL state to default values to avoid hard-to-debug bugs + * in custom layers. + */ + setCustomLayerDefaults() { + // Prevent custom layers from unintentionally modify the last VAO used. + // All other state is state is restored on it's own, but for VAOs it's + // simpler to unbind so that we don't have to track the state of VAOs. + this.context.unbindVAO(); + // The default values for this state is meaningful and often expected. + // Leaving this state dirty could cause a lot of confusion for users. + this.context.cullFace.setDefault(); + this.context.activeTexture.setDefault(); + this.context.pixelStoreUnpack.setDefault(); + this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(); + this.context.pixelStoreUnpackFlipY.setDefault(); + } + /* + * Set GL state that is shared by all layers. + */ + setBaseState() { + const gl = this.context.gl; + this.context.cullFace.set(false); + this.context.viewport.set([0, 0, this.width, this.height]); + this.context.blendEquation.set(gl.FUNC_ADD); + } + initDebugOverlayCanvas() { + if (this.debugOverlayCanvas == null) { + this.debugOverlayCanvas = document.createElement('canvas'); + this.debugOverlayCanvas.width = 512; + this.debugOverlayCanvas.height = 512; + const gl = this.context.gl; + this.debugOverlayTexture = new Texture(this.context, this.debugOverlayCanvas, gl.RGBA); + } + } + destroy() { + if (this.debugOverlayTexture) { + this.debugOverlayTexture.destroy(); + } + } + /* + * Return true if drawing buffer size is != from requested size. + * That means that we've reached GL limits somehow. + * Note: drawing buffer size changes only when canvas size changes + */ + overLimit() { + const { drawingBufferWidth, drawingBufferHeight } = this.context.gl; + return this.width !== drawingBufferWidth || this.height !== drawingBufferHeight; + } +} + +class Frustum { + constructor(points, planes) { + this.points = points; + this.planes = planes; + } + static fromInvProjectionMatrix(invProj, worldSize, zoom) { + const clipSpaceCorners = [ + [-1, 1, -1, 1], + [1, 1, -1, 1], + [1, -1, -1, 1], + [-1, -1, -1, 1], + [-1, 1, 1, 1], + [1, 1, 1, 1], + [1, -1, 1, 1], + [-1, -1, 1, 1] + ]; + const scale = Math.pow(2, zoom); + // Transform frustum corner points from clip space to tile space, Z to meters + const frustumCoords = clipSpaceCorners.map(v => { + v = performance$1.transformMat4([], v, invProj); + const s = 1.0 / v[3] / worldSize * scale; + return performance$1.mul$1(v, v, [s, s, 1.0 / v[3], s]); + }); + const frustumPlanePointIndices = [ + [0, 1, 2], // near + [6, 5, 4], // far + [0, 3, 7], // left + [2, 1, 5], // right + [3, 2, 6], // bottom + [0, 4, 5] // top + ]; + const frustumPlanes = frustumPlanePointIndices.map((p) => { + const a = performance$1.sub([], frustumCoords[p[0]], frustumCoords[p[1]]); + const b = performance$1.sub([], frustumCoords[p[2]], frustumCoords[p[1]]); + const n = performance$1.normalize([], performance$1.cross([], a, b)); + const d = -performance$1.dot(n, frustumCoords[p[1]]); + return n.concat(d); + }); + return new Frustum(frustumCoords, frustumPlanes); + } +} +class Aabb { + constructor(min_, max_) { + this.min = min_; + this.max = max_; + this.center = performance$1.scale$1([], performance$1.add([], this.min, this.max), 0.5); + } + quadrant(index) { + const split = [(index % 2) === 0, index < 2]; + const qMin = performance$1.clone$2(this.min); + const qMax = performance$1.clone$2(this.max); + for (let axis = 0; axis < split.length; axis++) { + qMin[axis] = split[axis] ? this.min[axis] : this.center[axis]; + qMax[axis] = split[axis] ? this.center[axis] : this.max[axis]; + } + // Elevation is always constant, hence quadrant.max.z = this.max.z + qMax[2] = this.max[2]; + return new Aabb(qMin, qMax); + } + distanceX(point) { + const pointOnAabb = Math.max(Math.min(this.max[0], point[0]), this.min[0]); + return pointOnAabb - point[0]; + } + distanceY(point) { + const pointOnAabb = Math.max(Math.min(this.max[1], point[1]), this.min[1]); + return pointOnAabb - point[1]; + } + // Performs a frustum-aabb intersection test. Returns 0 if there's no intersection, + // 1 if shapes are intersecting and 2 if the aabb if fully inside the frustum. + intersects(frustum) { + // Execute separating axis test between two convex objects to find intersections + // Each frustum plane together with 3 major axes define the separating axes + const aabbPoints = [ + [this.min[0], this.min[1], this.min[2], 1], + [this.max[0], this.min[1], this.min[2], 1], + [this.max[0], this.max[1], this.min[2], 1], + [this.min[0], this.max[1], this.min[2], 1], + [this.min[0], this.min[1], this.max[2], 1], + [this.max[0], this.min[1], this.max[2], 1], + [this.max[0], this.max[1], this.max[2], 1], + [this.min[0], this.max[1], this.max[2], 1] + ]; + let fullyInside = true; + for (let p = 0; p < frustum.planes.length; p++) { + const plane = frustum.planes[p]; + let pointsInside = 0; + for (let i = 0; i < aabbPoints.length; i++) { + if (performance$1.dot$1(plane, aabbPoints[i]) >= 0) { + pointsInside++; + } + } + if (pointsInside === 0) + return 0; + if (pointsInside !== aabbPoints.length) + fullyInside = false; + } + if (fullyInside) + return 2; + for (let axis = 0; axis < 3; axis++) { + let projMin = Number.MAX_VALUE; + let projMax = -Number.MAX_VALUE; + for (let p = 0; p < frustum.points.length; p++) { + const projectedPoint = frustum.points[p][axis] - this.min[axis]; + projMin = Math.min(projMin, projectedPoint); + projMax = Math.max(projMax, projectedPoint); + } + if (projMax < 0 || projMin > this.max[axis] - this.min[axis]) + return 0; + } + return 1; + } +} + +/** + * An `EdgeInset` object represents screen space padding applied to the edges of the viewport. + * This shifts the apprent center or the vanishing point of the map. This is useful for adding floating UI elements + * on top of the map and having the vanishing point shift as UI elements resize. + * + * @group Geography and Geometry + */ +class EdgeInsets { + constructor(top = 0, bottom = 0, left = 0, right = 0) { + if (isNaN(top) || top < 0 || + isNaN(bottom) || bottom < 0 || + isNaN(left) || left < 0 || + isNaN(right) || right < 0) { + throw new Error('Invalid value for edge-insets, top, bottom, left and right must all be numbers'); + } + this.top = top; + this.bottom = bottom; + this.left = left; + this.right = right; + } + /** + * Interpolates the inset in-place. + * This maintains the current inset value for any inset not present in `target`. + * @param start - interpolation start + * @param target - interpolation target + * @param t - interpolation step/weight + * @returns the insets + */ + interpolate(start, target, t) { + if (target.top != null && start.top != null) + this.top = performance$1.interpolate.number(start.top, target.top, t); + if (target.bottom != null && start.bottom != null) + this.bottom = performance$1.interpolate.number(start.bottom, target.bottom, t); + if (target.left != null && start.left != null) + this.left = performance$1.interpolate.number(start.left, target.left, t); + if (target.right != null && start.right != null) + this.right = performance$1.interpolate.number(start.right, target.right, t); + return this; + } + /** + * Utility method that computes the new apprent center or vanishing point after applying insets. + * This is in pixels and with the top left being (0.0) and +y being downwards. + * + * @param width - the width + * @param height - the height + * @returns the point + */ + getCenter(width, height) { + // Clamp insets so they never overflow width/height and always calculate a valid center + const x = performance$1.clamp((this.left + width - this.right) / 2, 0, width); + const y = performance$1.clamp((this.top + height - this.bottom) / 2, 0, height); + return new performance$1.Point(x, y); + } + equals(other) { + return this.top === other.top && + this.bottom === other.bottom && + this.left === other.left && + this.right === other.right; + } + clone() { + return new EdgeInsets(this.top, this.bottom, this.left, this.right); + } + /** + * Returns the current state as json, useful when you want to have a + * read-only representation of the inset. + * + * @returns state as json + */ + toJSON() { + return { + top: this.top, + bottom: this.bottom, + left: this.left, + right: this.right + }; + } +} + +const MAX_VALID_LATITUDE = 85.051129; +/** + * @internal + * A single transform, generally used for a single tile to be + * scaled, rotated, and zoomed. + */ +class Transform { + constructor(minZoom, maxZoom, minPitch, maxPitch, renderWorldCopies) { + this.tileSize = 512; // constant + this._renderWorldCopies = renderWorldCopies === undefined ? true : !!renderWorldCopies; + this._minZoom = minZoom || 0; + this._maxZoom = maxZoom || 22; + this._minPitch = (minPitch === undefined || minPitch === null) ? 0 : minPitch; + this._maxPitch = (maxPitch === undefined || maxPitch === null) ? 60 : maxPitch; + this.setMaxBounds(); + this.width = 0; + this.height = 0; + this._center = new performance$1.LngLat(0, 0); + this._elevation = 0; + this.zoom = 0; + this.angle = 0; + this._fov = 0.6435011087932844; + this._pitch = 0; + this._unmodified = true; + this._edgeInsets = new EdgeInsets(); + this._posMatrixCache = {}; + this._alignedPosMatrixCache = {}; + this._fogMatrixCache = {}; + this.minElevationForCurrentTile = 0; + } + clone() { + const clone = new Transform(this._minZoom, this._maxZoom, this._minPitch, this.maxPitch, this._renderWorldCopies); + clone.apply(this); + return clone; + } + apply(that) { + this.tileSize = that.tileSize; + this.latRange = that.latRange; + this.lngRange = that.lngRange; + this.width = that.width; + this.height = that.height; + this._center = that._center; + this._elevation = that._elevation; + this.minElevationForCurrentTile = that.minElevationForCurrentTile; + this.zoom = that.zoom; + this.angle = that.angle; + this._fov = that._fov; + this._pitch = that._pitch; + this._unmodified = that._unmodified; + this._edgeInsets = that._edgeInsets.clone(); + this._calcMatrices(); + } + get minZoom() { return this._minZoom; } + set minZoom(zoom) { + if (this._minZoom === zoom) + return; + this._minZoom = zoom; + this.zoom = Math.max(this.zoom, zoom); + } + get maxZoom() { return this._maxZoom; } + set maxZoom(zoom) { + if (this._maxZoom === zoom) + return; + this._maxZoom = zoom; + this.zoom = Math.min(this.zoom, zoom); + } + get minPitch() { return this._minPitch; } + set minPitch(pitch) { + if (this._minPitch === pitch) + return; + this._minPitch = pitch; + this.pitch = Math.max(this.pitch, pitch); + } + get maxPitch() { return this._maxPitch; } + set maxPitch(pitch) { + if (this._maxPitch === pitch) + return; + this._maxPitch = pitch; + this.pitch = Math.min(this.pitch, pitch); + } + get renderWorldCopies() { return this._renderWorldCopies; } + set renderWorldCopies(renderWorldCopies) { + if (renderWorldCopies === undefined) { + renderWorldCopies = true; + } + else if (renderWorldCopies === null) { + renderWorldCopies = false; + } + this._renderWorldCopies = renderWorldCopies; + } + get worldSize() { + return this.tileSize * this.scale; + } + get centerOffset() { + return this.centerPoint._sub(this.size._div(2)); + } + get size() { + return new performance$1.Point(this.width, this.height); + } + get bearing() { + return -this.angle / Math.PI * 180; + } + set bearing(bearing) { + const b = -performance$1.wrap(bearing, -180, 180) * Math.PI / 180; + if (this.angle === b) + return; + this._unmodified = false; + this.angle = b; + this._calcMatrices(); + // 2x2 matrix for rotating points + this.rotationMatrix = performance$1.create$2(); + performance$1.rotate(this.rotationMatrix, this.rotationMatrix, this.angle); + } + get pitch() { + return this._pitch / Math.PI * 180; + } + set pitch(pitch) { + const p = performance$1.clamp(pitch, this.minPitch, this.maxPitch) / 180 * Math.PI; + if (this._pitch === p) + return; + this._unmodified = false; + this._pitch = p; + this._calcMatrices(); + } + get fov() { + return this._fov / Math.PI * 180; + } + set fov(fov) { + fov = Math.max(0.01, Math.min(60, fov)); + if (this._fov === fov) + return; + this._unmodified = false; + this._fov = fov / 180 * Math.PI; + this._calcMatrices(); + } + get zoom() { return this._zoom; } + set zoom(zoom) { + const constrainedZoom = Math.min(Math.max(zoom, this.minZoom), this.maxZoom); + if (this._zoom === constrainedZoom) + return; + this._unmodified = false; + this._zoom = constrainedZoom; + this.tileZoom = Math.max(0, Math.floor(constrainedZoom)); + this.scale = this.zoomScale(constrainedZoom); + this._constrain(); + this._calcMatrices(); + } + get center() { return this._center; } + set center(center) { + if (center.lat === this._center.lat && center.lng === this._center.lng) + return; + this._unmodified = false; + this._center = center; + this._constrain(); + this._calcMatrices(); + } + /** + * Elevation at current center point, meters above sea level + */ + get elevation() { return this._elevation; } + set elevation(elevation) { + if (elevation === this._elevation) + return; + this._elevation = elevation; + this._constrain(); + this._calcMatrices(); + } + get padding() { return this._edgeInsets.toJSON(); } + set padding(padding) { + if (this._edgeInsets.equals(padding)) + return; + this._unmodified = false; + //Update edge-insets in place + this._edgeInsets.interpolate(this._edgeInsets, padding, 1); + this._calcMatrices(); + } + /** + * The center of the screen in pixels with the top-left corner being (0,0) + * and +y axis pointing downwards. This accounts for padding. + */ + get centerPoint() { + return this._edgeInsets.getCenter(this.width, this.height); + } + /** + * Returns if the padding params match + * + * @param padding - the padding to check against + * @returns true if they are equal, false otherwise + */ + isPaddingEqual(padding) { + return this._edgeInsets.equals(padding); + } + /** + * Helper method to update edge-insets in place + * + * @param start - the starting padding + * @param target - the target padding + * @param t - the step/weight + */ + interpolatePadding(start, target, t) { + this._unmodified = false; + this._edgeInsets.interpolate(start, target, t); + this._constrain(); + this._calcMatrices(); + } + /** + * Return a zoom level that will cover all tiles the transform + * @param options - the options + * @returns zoom level An integer zoom level at which all tiles will be visible. + */ + coveringZoomLevel(options) { + const z = (options.roundZoom ? Math.round : Math.floor)(this.zoom + this.scaleZoom(this.tileSize / options.tileSize)); + // At negative zoom levels load tiles from z0 because negative tile zoom levels don't exist. + return Math.max(0, z); + } + /** + * Return any "wrapped" copies of a given tile coordinate that are visible + * in the current view. + */ + getVisibleUnwrappedCoordinates(tileID) { + const result = [new performance$1.UnwrappedTileID(0, tileID)]; + if (this._renderWorldCopies) { + const utl = this.pointCoordinate(new performance$1.Point(0, 0)); + const utr = this.pointCoordinate(new performance$1.Point(this.width, 0)); + const ubl = this.pointCoordinate(new performance$1.Point(this.width, this.height)); + const ubr = this.pointCoordinate(new performance$1.Point(0, this.height)); + const w0 = Math.floor(Math.min(utl.x, utr.x, ubl.x, ubr.x)); + const w1 = Math.floor(Math.max(utl.x, utr.x, ubl.x, ubr.x)); + // Add an extra copy of the world on each side to properly render ImageSources and CanvasSources. + // Both sources draw outside the tile boundaries of the tile that "contains them" so we need + // to add extra copies on both sides in case offscreen tiles need to draw into on-screen ones. + const extraWorldCopy = 1; + for (let w = w0 - extraWorldCopy; w <= w1 + extraWorldCopy; w++) { + if (w === 0) + continue; + result.push(new performance$1.UnwrappedTileID(w, tileID)); + } + } + return result; + } + /** + * Return all coordinates that could cover this transform for a covering + * zoom level. + * @param options - the options + * @returns OverscaledTileIDs + */ + coveringTiles(options) { + var _a, _b; + let z = this.coveringZoomLevel(options); + const actualZ = z; + if (options.minzoom !== undefined && z < options.minzoom) + return []; + if (options.maxzoom !== undefined && z > options.maxzoom) + z = options.maxzoom; + const cameraCoord = this.pointCoordinate(this.getCameraPoint()); + const centerCoord = performance$1.MercatorCoordinate.fromLngLat(this.center); + const numTiles = Math.pow(2, z); + const cameraPoint = [numTiles * cameraCoord.x, numTiles * cameraCoord.y, 0]; + const centerPoint = [numTiles * centerCoord.x, numTiles * centerCoord.y, 0]; + const cameraFrustum = Frustum.fromInvProjectionMatrix(this.invModelViewProjectionMatrix, this.worldSize, z); + // 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 + let minZoom = options.minzoom || 0; + // Use 0.1 as an epsilon to avoid for explicit == 0.0 floating point checks + if (!options.terrain && this.pitch <= 60.0 && this._edgeInsets.top < 0.1) + minZoom = z; + // There should always be a certain number of maximum zoom level tiles surrounding the center location in 2D or in front of the camera in 3D + const radiusOfMaxLvlLodInTiles = options.terrain ? 2 / Math.min(this.tileSize, options.tileSize) * this.tileSize : 3; + const newRootTile = (wrap) => { + return { + aabb: new Aabb([wrap * numTiles, 0, 0], [(wrap + 1) * numTiles, numTiles, 0]), + zoom: 0, + x: 0, + y: 0, + wrap, + fullyVisible: false + }; + }; + // Do a depth-first traversal to find visible tiles and proper levels of detail + const stack = []; + const result = []; + const maxZoom = z; + const overscaledZ = options.reparseOverscaled ? actualZ : z; + if (this._renderWorldCopies) { + // Render copy of the globe thrice on both sides + for (let i = 1; i <= 3; i++) { + stack.push(newRootTile(-i)); + stack.push(newRootTile(i)); + } + } + stack.push(newRootTile(0)); + while (stack.length > 0) { + const it = stack.pop(); + const x = it.x; + const y = it.y; + let fullyVisible = it.fullyVisible; + // Visibility of a tile is not required if any of its ancestor if fully inside the frustum + if (!fullyVisible) { + const intersectResult = it.aabb.intersects(cameraFrustum); + if (intersectResult === 0) + continue; + fullyVisible = intersectResult === 2; + } + const refPoint = options.terrain ? cameraPoint : centerPoint; + const distanceX = it.aabb.distanceX(refPoint); + const distanceY = it.aabb.distanceY(refPoint); + const longestDim = Math.max(Math.abs(distanceX), Math.abs(distanceY)); + // We're using distance based heuristics to determine if a tile should be split into quadrants or not. + // radiusOfMaxLvlLodInTiles defines that there's always a certain number of maxLevel tiles next to the map center. + // Using the fact that a parent node in quadtree is twice the size of its children (per dimension) + // we can define distance thresholds for each relative level: + // f(k) = offset + 2 + 4 + 8 + 16 + ... + 2^k. This is the same as "offset+2^(k+1)-2" + const distToSplit = radiusOfMaxLvlLodInTiles + (1 << (maxZoom - it.zoom)) - 2; + // Have we reached the target depth or is the tile too far away to be any split further? + if (it.zoom === maxZoom || (longestDim > distToSplit && it.zoom >= minZoom)) { + const dz = maxZoom - it.zoom, dx = cameraPoint[0] - 0.5 - (x << dz), dy = cameraPoint[1] - 0.5 - (y << dz); + result.push({ + tileID: new performance$1.OverscaledTileID(it.zoom === maxZoom ? overscaledZ : it.zoom, it.wrap, it.zoom, x, y), + distanceSq: performance$1.sqrLen([centerPoint[0] - 0.5 - x, centerPoint[1] - 0.5 - y]), + // this variable is currently not used, but may be important to reduce the amount of loaded tiles + tileDistanceToCamera: Math.sqrt(dx * dx + dy * dy) + }); + continue; + } + for (let i = 0; i < 4; i++) { + const childX = (x << 1) + (i % 2); + const childY = (y << 1) + (i >> 1); + const childZ = it.zoom + 1; + let quadrant = it.aabb.quadrant(i); + if (options.terrain) { + const tileID = new performance$1.OverscaledTileID(childZ, it.wrap, childZ, childX, childY); + const minMax = options.terrain.getMinMaxElevation(tileID); + const minElevation = (_a = minMax.minElevation) !== null && _a !== void 0 ? _a : this.elevation; + const maxElevation = (_b = minMax.maxElevation) !== null && _b !== void 0 ? _b : this.elevation; + quadrant = new Aabb([quadrant.min[0], quadrant.min[1], minElevation], [quadrant.max[0], quadrant.max[1], maxElevation]); + } + stack.push({ aabb: quadrant, zoom: childZ, x: childX, y: childY, wrap: it.wrap, fullyVisible }); + } + } + return result.sort((a, b) => a.distanceSq - b.distanceSq).map(a => a.tileID); + } + resize(width, height) { + this.width = width; + this.height = height; + this.pixelsToGLUnits = [2 / width, -2 / height]; + this._constrain(); + this._calcMatrices(); + } + get unmodified() { return this._unmodified; } + zoomScale(zoom) { return Math.pow(2, zoom); } + scaleZoom(scale) { return Math.log(scale) / Math.LN2; } + /** + * Convert from LngLat to world coordinates (Mercator coordinates scaled by 512) + * @param lnglat - the lngLat + * @returns Point + */ + project(lnglat) { + const lat = performance$1.clamp(lnglat.lat, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE); + return new performance$1.Point(performance$1.mercatorXfromLng(lnglat.lng) * this.worldSize, performance$1.mercatorYfromLat(lat) * this.worldSize); + } + /** + * Convert from world coordinates ([0, 512],[0, 512]) to LngLat ([-180, 180], [-90, 90]) + * @param point - world coordinate + * @returns LngLat + */ + unproject(point) { + return new performance$1.MercatorCoordinate(point.x / this.worldSize, point.y / this.worldSize).toLngLat(); + } + get point() { return this.project(this.center); } + /** + * get the camera position in LngLat and altitudes in meter + * @returns An object with lngLat & altitude. + */ + getCameraPosition() { + const lngLat = this.pointLocation(this.getCameraPoint()); + const altitude = Math.cos(this._pitch) * this.cameraToCenterDistance / this._pixelPerMeter; + return { lngLat, altitude: altitude + this.elevation }; + } + /** + * This method works in combination with freezeElevation activated. + * freezeElevation is enabled during map-panning because during this the camera should sit in constant height. + * After panning finished, call this method to recalculate the zoomlevel for the current camera-height in current terrain. + * @param terrain - the terrain + */ + recalculateZoom(terrain) { + const origElevation = this.elevation; + const origAltitude = Math.cos(this._pitch) * this.cameraToCenterDistance / this._pixelPerMeter; + // find position the camera is looking on + const center = this.pointLocation(this.centerPoint, terrain); + const elevation = terrain.getElevationForLngLatZoom(center, this.tileZoom); + const deltaElevation = this.elevation - elevation; + if (!deltaElevation) + return; + // The camera's altitude off the ground + the ground's elevation = a constant: + // this means the camera stays at the same total height. + const requiredAltitude = origAltitude + origElevation - elevation; + // Since altitude = Math.cos(this._pitch) * this.cameraToCenterDistance / pixelPerMeter: + const requiredPixelPerMeter = Math.cos(this._pitch) * this.cameraToCenterDistance / requiredAltitude; + // Since pixelPerMeter = mercatorZfromAltitude(1, center.lat) * worldSize: + const requiredWorldSize = requiredPixelPerMeter / performance$1.mercatorZfromAltitude(1, center.lat); + // Since worldSize = this.tileSize * scale: + const requiredScale = requiredWorldSize / this.tileSize; + const zoom = this.scaleZoom(requiredScale); + // update matrices + this._elevation = elevation; + this._center = center; + this.zoom = zoom; + } + setLocationAtPoint(lnglat, point) { + const a = this.pointCoordinate(point); + const b = this.pointCoordinate(this.centerPoint); + const loc = this.locationCoordinate(lnglat); + const newCenter = new performance$1.MercatorCoordinate(loc.x - (a.x - b.x), loc.y - (a.y - b.y)); + this.center = this.coordinateLocation(newCenter); + if (this._renderWorldCopies) { + this.center = this.center.wrap(); + } + } + /** + * Given a LngLat location, return the screen point that corresponds to it + * @param lnglat - location + * @param terrain - optional terrain + * @returns screen point + */ + locationPoint(lnglat, terrain) { + return terrain ? + this.coordinatePoint(this.locationCoordinate(lnglat), terrain.getElevationForLngLatZoom(lnglat, this.tileZoom), this.pixelMatrix3D) : + this.coordinatePoint(this.locationCoordinate(lnglat)); + } + /** + * Given a point on screen, return its lnglat + * @param p - screen point + * @param terrain - optional terrain + * @returns lnglat location + */ + pointLocation(p, terrain) { + return this.coordinateLocation(this.pointCoordinate(p, terrain)); + } + /** + * Given a geographical lnglat, return an unrounded + * coordinate that represents it at low zoom level. + * @param lnglat - the location + * @returns The mercator coordinate + */ + locationCoordinate(lnglat) { + return performance$1.MercatorCoordinate.fromLngLat(lnglat); + } + /** + * Given a Coordinate, return its geographical position. + * @param coord - mercator coordinates + * @returns lng and lat + */ + coordinateLocation(coord) { + return coord && coord.toLngLat(); + } + /** + * Given a Point, return its mercator coordinate. + * @param p - the point + * @param terrain - optional terrain + * @returns lnglat + */ + pointCoordinate(p, terrain) { + // get point-coordinate from terrain coordinates framebuffer + if (terrain) { + const coordinate = terrain.pointCoordinate(p); + if (coordinate != null) { + return coordinate; + } + } + // calculate point-coordinate on flat earth + const targetZ = 0; + // since we don't know the correct projected z value for the point, + // unproject two points to get a line and then find the point on that + // line with z=0 + const coord0 = [p.x, p.y, 0, 1]; + const coord1 = [p.x, p.y, 1, 1]; + performance$1.transformMat4(coord0, coord0, this.pixelMatrixInverse); + performance$1.transformMat4(coord1, coord1, this.pixelMatrixInverse); + const w0 = coord0[3]; + const w1 = coord1[3]; + const x0 = coord0[0] / w0; + const x1 = coord1[0] / w1; + const y0 = coord0[1] / w0; + const y1 = coord1[1] / w1; + const z0 = coord0[2] / w0; + const z1 = coord1[2] / w1; + const t = z0 === z1 ? 0 : (targetZ - z0) / (z1 - z0); + return new performance$1.MercatorCoordinate(performance$1.interpolate.number(x0, x1, t) / this.worldSize, performance$1.interpolate.number(y0, y1, t) / this.worldSize); + } + /** + * Given a coordinate, return the screen point that corresponds to it + * @param coord - the coordinates + * @param elevation - the elevation + * @param pixelMatrix - the pixel matrix + * @returns screen point + */ + coordinatePoint(coord, elevation = 0, pixelMatrix = this.pixelMatrix) { + const p = [coord.x * this.worldSize, coord.y * this.worldSize, elevation, 1]; + performance$1.transformMat4(p, p, pixelMatrix); + return new performance$1.Point(p[0] / p[3], p[1] / p[3]); + } + /** + * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not + * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region. + * @returns Returns a {@link LngLatBounds} object describing the map's geographical bounds. + */ + getBounds() { + const top = Math.max(0, this.height / 2 - this.getHorizon()); + return new LngLatBounds() + .extend(this.pointLocation(new performance$1.Point(0, top))) + .extend(this.pointLocation(new performance$1.Point(this.width, top))) + .extend(this.pointLocation(new performance$1.Point(this.width, this.height))) + .extend(this.pointLocation(new performance$1.Point(0, this.height))); + } + /** + * Returns the maximum geographical bounds the map is constrained to, or `null` if none set. + * @returns max bounds + */ + getMaxBounds() { + if (!this.latRange || this.latRange.length !== 2 || + !this.lngRange || this.lngRange.length !== 2) + return null; + return new LngLatBounds([this.lngRange[0], this.latRange[0]], [this.lngRange[1], this.latRange[1]]); + } + /** + * Calculate pixel height of the visible horizon in relation to map-center (e.g. height/2), + * multiplied by a static factor to simulate the earth-radius. + * The calculated value is the horizontal line from the camera-height to sea-level. + * @returns Horizon above center in pixels. + */ + getHorizon() { + return Math.tan(Math.PI / 2 - this._pitch) * this.cameraToCenterDistance * 0.85; + } + /** + * Sets or clears the map's geographical constraints. + * @param bounds - A {@link LngLatBounds} object describing the new geographic boundaries of the map. + */ + setMaxBounds(bounds) { + if (bounds) { + this.lngRange = [bounds.getWest(), bounds.getEast()]; + this.latRange = [bounds.getSouth(), bounds.getNorth()]; + this._constrain(); + } + else { + this.lngRange = null; + this.latRange = [-MAX_VALID_LATITUDE, MAX_VALID_LATITUDE]; + } + } + calculateTileMatrix(unwrappedTileID) { + const canonical = unwrappedTileID.canonical; + const scale = this.worldSize / this.zoomScale(canonical.z); + const unwrappedX = canonical.x + Math.pow(2, canonical.z) * unwrappedTileID.wrap; + const worldMatrix = performance$1.identity(new Float64Array(16)); + performance$1.translate(worldMatrix, worldMatrix, [unwrappedX * scale, canonical.y * scale, 0]); + performance$1.scale(worldMatrix, worldMatrix, [scale / performance$1.EXTENT, scale / performance$1.EXTENT, 1]); + return worldMatrix; + } + /** + * Calculate the posMatrix that, given a tile coordinate, would be used to display the tile on a map. + * @param unwrappedTileID - the tile ID + */ + calculatePosMatrix(unwrappedTileID, aligned = false) { + const posMatrixKey = unwrappedTileID.key; + const cache = aligned ? this._alignedPosMatrixCache : this._posMatrixCache; + if (cache[posMatrixKey]) { + return cache[posMatrixKey]; + } + const posMatrix = this.calculateTileMatrix(unwrappedTileID); + performance$1.multiply(posMatrix, aligned ? this.alignedModelViewProjectionMatrix : this.modelViewProjectionMatrix, posMatrix); + cache[posMatrixKey] = new Float32Array(posMatrix); + return cache[posMatrixKey]; + } + /** + * Calculate the fogMatrix that, given a tile coordinate, would be used to calculate fog on the map. + * @param unwrappedTileID - the tile ID + * @private + */ + calculateFogMatrix(unwrappedTileID) { + const posMatrixKey = unwrappedTileID.key; + const cache = this._fogMatrixCache; + if (cache[posMatrixKey]) { + return cache[posMatrixKey]; + } + const fogMatrix = this.calculateTileMatrix(unwrappedTileID); + performance$1.multiply(fogMatrix, this.fogMatrix, fogMatrix); + cache[posMatrixKey] = new Float32Array(fogMatrix); + return cache[posMatrixKey]; + } + customLayerMatrix() { + return this.mercatorMatrix.slice(); + } + /** + * Get center lngLat and zoom to ensure that + * 1) everything beyond the bounds is excluded + * 2) a given lngLat is as near the center as possible + * Bounds are those set by maxBounds or North & South "Poles" and, if only 1 globe is displayed, antimeridian. + */ + getConstrained(lngLat, zoom) { + zoom = performance$1.clamp(+zoom, this.minZoom, this.maxZoom); + const result = { + center: new performance$1.LngLat(lngLat.lng, lngLat.lat), + zoom + }; + let lngRange = this.lngRange; + if (!this._renderWorldCopies && lngRange === null) { + const almost180 = 180 - 1e-10; + lngRange = [-almost180, almost180]; + } + const worldSize = this.tileSize * this.zoomScale(result.zoom); // A world size for the requested zoom level, not the current world size + let minY = 0; + let maxY = worldSize; + let minX = 0; + let maxX = worldSize; + let scaleY = 0; + let scaleX = 0; + const { x: screenWidth, y: screenHeight } = this.size; + if (this.latRange) { + const latRange = this.latRange; + minY = performance$1.mercatorYfromLat(latRange[1]) * worldSize; + maxY = performance$1.mercatorYfromLat(latRange[0]) * worldSize; + const shouldZoomIn = maxY - minY < screenHeight; + if (shouldZoomIn) + scaleY = screenHeight / (maxY - minY); + } + if (lngRange) { + minX = performance$1.wrap(performance$1.mercatorXfromLng(lngRange[0]) * worldSize, 0, worldSize); + maxX = performance$1.wrap(performance$1.mercatorXfromLng(lngRange[1]) * worldSize, 0, worldSize); + if (maxX < minX) + maxX += worldSize; + const shouldZoomIn = maxX - minX < screenWidth; + if (shouldZoomIn) + scaleX = screenWidth / (maxX - minX); + } + const { x: originalX, y: originalY } = this.project.call({ worldSize }, lngLat); + let modifiedX, modifiedY; + const scale = Math.max(scaleX || 0, scaleY || 0); + if (scale) { + // zoom in to exclude all beyond the given lng/lat ranges + const newPoint = new performance$1.Point(scaleX ? (maxX + minX) / 2 : originalX, scaleY ? (maxY + minY) / 2 : originalY); + result.center = this.unproject.call({ worldSize }, newPoint).wrap(); + result.zoom += this.scaleZoom(scale); + return result; + } + if (this.latRange) { + const h2 = screenHeight / 2; + if (originalY - h2 < minY) + modifiedY = minY + h2; + if (originalY + h2 > maxY) + modifiedY = maxY - h2; + } + if (lngRange) { + const centerX = (minX + maxX) / 2; + let wrappedX = originalX; + if (this._renderWorldCopies) { + wrappedX = performance$1.wrap(originalX, centerX - worldSize / 2, centerX + worldSize / 2); + } + const w2 = screenWidth / 2; + if (wrappedX - w2 < minX) + modifiedX = minX + w2; + if (wrappedX + w2 > maxX) + modifiedX = maxX - w2; + } + // pan the map if the screen goes off the range + if (modifiedX !== undefined || modifiedY !== undefined) { + const newPoint = new performance$1.Point(modifiedX !== null && modifiedX !== void 0 ? modifiedX : originalX, modifiedY !== null && modifiedY !== void 0 ? modifiedY : originalY); + result.center = this.unproject.call({ worldSize }, newPoint).wrap(); + } + return result; + } + _constrain() { + if (!this.center || !this.width || !this.height || this._constraining) + return; + this._constraining = true; + const unmodified = this._unmodified; + const { center, zoom } = this.getConstrained(this.center, this.zoom); + this.center = center; + this.zoom = zoom; + this._unmodified = unmodified; + this._constraining = false; + } + _calcMatrices() { + if (!this.height) + return; + const halfFov = this._fov / 2; + const offset = this.centerOffset; + const x = this.point.x, y = this.point.y; + this.cameraToCenterDistance = 0.5 / Math.tan(halfFov) * this.height; + this._pixelPerMeter = performance$1.mercatorZfromAltitude(1, this.center.lat) * this.worldSize; + let m = performance$1.identity(new Float64Array(16)); + performance$1.scale(m, m, [this.width / 2, -this.height / 2, 1]); + performance$1.translate(m, m, [1, -1, 0]); + this.labelPlaneMatrix = m; + m = performance$1.identity(new Float64Array(16)); + performance$1.scale(m, m, [1, -1, 1]); + performance$1.translate(m, m, [-1, -1, 0]); + performance$1.scale(m, m, [2 / this.width, 2 / this.height, 1]); + this.glCoordMatrix = m; + // Calculate the camera to sea-level distance in pixel in respect of terrain + const cameraToSeaLevelDistance = this.cameraToCenterDistance + this._elevation * this._pixelPerMeter / Math.cos(this._pitch); + // In case of negative minimum elevation (e.g. the dead see, under the sea maps) use a lower plane for calculation + const minElevation = Math.min(this.elevation, this.minElevationForCurrentTile); + const cameraToLowestPointDistance = cameraToSeaLevelDistance - minElevation * this._pixelPerMeter / Math.cos(this._pitch); + const lowestPlane = minElevation < 0 ? cameraToLowestPointDistance : cameraToSeaLevelDistance; + // Find the distance from the center point [width/2 + offset.x, height/2 + offset.y] to the + // center top point [width/2 + offset.x, 0] in Z units, using the law of sines. + // 1 Z unit is equivalent to 1 horizontal px at the center of the map + // (the distance between[width/2, height/2] and [width/2 + 1, height/2]) + const groundAngle = Math.PI / 2 + this._pitch; + const fovAboveCenter = this._fov * (0.5 + offset.y / this.height); + const topHalfSurfaceDistance = Math.sin(fovAboveCenter) * lowestPlane / Math.sin(performance$1.clamp(Math.PI - groundAngle - fovAboveCenter, 0.01, Math.PI - 0.01)); + // Find the distance from the center point to the horizon + const horizon = this.getHorizon(); + const horizonAngle = Math.atan(horizon / this.cameraToCenterDistance); + const fovCenterToHorizon = 2 * horizonAngle * (0.5 + offset.y / (horizon * 2)); + const topHalfSurfaceDistanceHorizon = Math.sin(fovCenterToHorizon) * lowestPlane / Math.sin(performance$1.clamp(Math.PI - groundAngle - fovCenterToHorizon, 0.01, Math.PI - 0.01)); + // Calculate z distance of the farthest fragment that should be rendered. + // Add a bit extra to avoid precision problems when a fragment's distance is exactly `furthestDistance` + const topHalfMinDistance = Math.min(topHalfSurfaceDistance, topHalfSurfaceDistanceHorizon); + this.farZ = (Math.cos(Math.PI / 2 - this._pitch) * topHalfMinDistance + lowestPlane) * 1.01; + // The larger the value of nearZ is + // - the more depth precision is available for features (good) + // - clipping starts appearing sooner when the camera is close to 3d features (bad) + // + // Other values work for mapbox-gl-js but deck.gl was encountering precision issues + // when rendering custom layers. This value was experimentally chosen and + // seems to solve z-fighting issues in deck.gl while not clipping buildings too close to the camera. + this.nearZ = this.height / 50; + // matrix for conversion from location to clip space(-1 .. 1) + m = new Float64Array(16); + performance$1.perspective(m, this._fov, this.width / this.height, this.nearZ, this.farZ); + // Apply center of perspective offset + m[8] = -offset.x * 2 / this.width; + m[9] = offset.y * 2 / this.height; + this.projectionMatrix = performance$1.clone(m); + performance$1.scale(m, m, [1, -1, 1]); + performance$1.translate(m, m, [0, 0, -this.cameraToCenterDistance]); + performance$1.rotateX(m, m, this._pitch); + performance$1.rotateZ(m, m, this.angle); + performance$1.translate(m, m, [-x, -y, 0]); + // The mercatorMatrix can be used to transform points from mercator coordinates + // ([0, 0] nw, [1, 1] se) to clip space. + this.mercatorMatrix = performance$1.scale([], m, [this.worldSize, this.worldSize, this.worldSize]); + // scale vertically to meters per pixel (inverse of ground resolution): + performance$1.scale(m, m, [1, 1, this._pixelPerMeter]); + // matrix for conversion from world space to screen coordinates in 2D + this.pixelMatrix = performance$1.multiply(new Float64Array(16), this.labelPlaneMatrix, m); + // matrix for conversion from world space to clip space (-1 .. 1) + performance$1.translate(m, m, [0, 0, -this.elevation]); // elevate camera over terrain + this.modelViewProjectionMatrix = m; + this.invModelViewProjectionMatrix = performance$1.invert([], m); + // create a fog matrix, same es proj-matrix but with near clipping-plane in mapcenter + // needed to calculate a correct z-value for fog calculation, because projMatrix z value is not + this.fogMatrix = new Float64Array(16); + performance$1.perspective(this.fogMatrix, this._fov, this.width / this.height, cameraToSeaLevelDistance, this.farZ); + this.fogMatrix[8] = -offset.x * 2 / this.width; + this.fogMatrix[9] = offset.y * 2 / this.height; + performance$1.scale(this.fogMatrix, this.fogMatrix, [1, -1, 1]); + performance$1.translate(this.fogMatrix, this.fogMatrix, [0, 0, -this.cameraToCenterDistance]); + performance$1.rotateX(this.fogMatrix, this.fogMatrix, this._pitch); + performance$1.rotateZ(this.fogMatrix, this.fogMatrix, this.angle); + performance$1.translate(this.fogMatrix, this.fogMatrix, [-x, -y, 0]); + performance$1.scale(this.fogMatrix, this.fogMatrix, [1, 1, this._pixelPerMeter]); + performance$1.translate(this.fogMatrix, this.fogMatrix, [0, 0, -this.elevation]); // elevate camera over terrain + // matrix for conversion from world space to screen coordinates in 3D + this.pixelMatrix3D = performance$1.multiply(new Float64Array(16), this.labelPlaneMatrix, m); + // Make a second projection matrix that is aligned to a pixel grid for rendering raster tiles. + // We're rounding the (floating point) x/y values to achieve to avoid rendering raster images to fractional + // coordinates. Additionally, we adjust by half a pixel in either direction in case that viewport dimension + // is an odd integer to preserve rendering to the pixel grid. We're rotating this shift based on the angle + // of the transformation so that 0°, 90°, 180°, and 270° rasters are crisp, and adjust the shift so that + // it is always <= 0.5 pixels. + const xShift = (this.width % 2) / 2, yShift = (this.height % 2) / 2, angleCos = Math.cos(this.angle), angleSin = Math.sin(this.angle), dx = x - Math.round(x) + angleCos * xShift + angleSin * yShift, dy = y - Math.round(y) + angleCos * yShift + angleSin * xShift; + const alignedM = new Float64Array(m); + performance$1.translate(alignedM, alignedM, [dx > 0.5 ? dx - 1 : dx, dy > 0.5 ? dy - 1 : dy, 0]); + this.alignedModelViewProjectionMatrix = alignedM; + // inverse matrix for conversion from screen coordinates to location + m = performance$1.invert(new Float64Array(16), this.pixelMatrix); + if (!m) + throw new Error('failed to invert matrix'); + this.pixelMatrixInverse = m; + this._posMatrixCache = {}; + this._alignedPosMatrixCache = {}; + this._fogMatrixCache = {}; + } + maxPitchScaleFactor() { + // calcMatrices hasn't run yet + if (!this.pixelMatrixInverse) + return 1; + const coord = this.pointCoordinate(new performance$1.Point(0, 0)); + const p = [coord.x * this.worldSize, coord.y * this.worldSize, 0, 1]; + const topPoint = performance$1.transformMat4(p, p, this.pixelMatrix); + return topPoint[3] / this.cameraToCenterDistance; + } + /** + * The camera looks at the map from a 3D (lng, lat, altitude) location. Let's use `cameraLocation` + * as the name for the location under the camera and on the surface of the earth (lng, lat, 0). + * `cameraPoint` is the projected position of the `cameraLocation`. + * + * This point is useful to us because only fill-extrusions that are between `cameraPoint` and + * the query point on the surface of the earth can extend and intersect the query. + * + * When the map is not pitched the `cameraPoint` is equivalent to the center of the map because + * the camera is right above the center of the map. + */ + getCameraPoint() { + const pitch = this._pitch; + const yOffset = Math.tan(pitch) * (this.cameraToCenterDistance || 1); + return this.centerPoint.add(new performance$1.Point(0, yOffset)); + } + /** + * When the map is pitched, some of the 3D features that intersect a query will not intersect + * the query at the surface of the earth. Instead the feature may be closer and only intersect + * the query because it extrudes into the air. + * @param queryGeometry - For point queries, the line from the query point to the "camera point", + * for other geometries, the envelope of the query geometry and the "camera point" + * @returns a geometry that includes all of the original query as well as all possible ares of the + * screen where the *base* of a visible extrusion could be. + * + */ + getCameraQueryGeometry(queryGeometry) { + const c = this.getCameraPoint(); + if (queryGeometry.length === 1) { + return [queryGeometry[0], c]; + } + else { + let minX = c.x; + let minY = c.y; + let maxX = c.x; + let maxY = c.y; + for (const p of queryGeometry) { + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + return [ + new performance$1.Point(minX, minY), + new performance$1.Point(maxX, minY), + new performance$1.Point(maxX, maxY), + new performance$1.Point(minX, maxY), + new performance$1.Point(minX, minY) + ]; + } + } + /** + * Return the distance to the camera in clip space from a LngLat. + * This can be compared to the value from the depth buffer (terrain.depthAtPoint) + * to determine whether a point is occluded. + * @param lngLat - the point + * @param elevation - the point's elevation + * @returns depth value in clip space (between 0 and 1) + */ + lngLatToCameraDepth(lngLat, elevation) { + const coord = this.locationCoordinate(lngLat); + const p = [coord.x * this.worldSize, coord.y * this.worldSize, elevation, 1]; + performance$1.transformMat4(p, p, this.modelViewProjectionMatrix); + return (p[2] / p[3]); + } +} + +/** + * Throttle the given function to run at most every `period` milliseconds. + */ +function throttle(fn, time) { + let pending = false; + let timerId = null; + let lastCallContext = null; + let lastCallArgs; + const later = () => { + timerId = null; + if (pending) { + fn.apply(lastCallContext, lastCallArgs); + timerId = setTimeout(later, time); + pending = false; + } + }; + return (...args) => { + pending = true; + lastCallContext = this; + lastCallArgs = args; + if (!timerId) { + later(); + } + return timerId; + }; +} + +/** + * Adds the map's position to its page's location hash. + * Passed as an option to the map object. + * + * @group Markers and Controls + */ +class Hash { + constructor(hashName) { + this._getCurrentHash = () => { + // Get the current hash from location, stripped from its number sign + const hash = window.location.hash.replace('#', ''); + if (this._hashName) { + // Split the parameter-styled hash into parts and find the value we need + let keyval; + hash.split('&').map(part => part.split('=')).forEach(part => { + if (part[0] === this._hashName) { + keyval = part; + } + }); + return (keyval ? keyval[1] || '' : '').split('/'); + } + return hash.split('/'); + }; + this._onHashChange = () => { + const loc = this._getCurrentHash(); + if (loc.length >= 3 && !loc.some(v => isNaN(v))) { + const bearing = this._map.dragRotate.isEnabled() && this._map.touchZoomRotate.isEnabled() ? +(loc[3] || 0) : this._map.getBearing(); + this._map.jumpTo({ + center: [+loc[2], +loc[1]], + zoom: +loc[0], + bearing, + pitch: +(loc[4] || 0) + }); + return true; + } + return false; + }; + this._updateHashUnthrottled = () => { + // Replace if already present, else append the updated hash string + const location = window.location.href.replace(/(#.+)?$/, this.getHashString()); + window.history.replaceState(window.history.state, null, location); + }; + this._removeHash = () => { + const currentHash = this._getCurrentHash(); + if (currentHash.length === 0) { + return; + } + const baseHash = currentHash.join('/'); + let targetHash = baseHash; + if (targetHash.split('&').length > 0) { + targetHash = targetHash.split('&')[0]; // #3/1/2&foo=bar -> #3/1/2 + } + if (this._hashName) { + targetHash = `${this._hashName}=${baseHash}`; + } + let replaceString = window.location.hash.replace(targetHash, ''); + if (replaceString.startsWith('#&')) { + replaceString = replaceString.slice(0, 1) + replaceString.slice(2); + } + else if (replaceString === '#') { + replaceString = ''; + } + let location = window.location.href.replace(/(#.+)?$/, replaceString); + location = location.replace('&&', '&'); + window.history.replaceState(window.history.state, null, location); + }; + /** + * Mobile Safari doesn't allow updating the hash more than 100 times per 30 seconds. + */ + this._updateHash = throttle(this._updateHashUnthrottled, 30 * 1000 / 100); + this._hashName = hashName && encodeURIComponent(hashName); + } + /** + * Map element to listen for coordinate changes + * + * @param map - The map object + */ + addTo(map) { + this._map = map; + addEventListener('hashchange', this._onHashChange, false); + this._map.on('moveend', this._updateHash); + return this; + } + /** + * Removes hash + */ + remove() { + removeEventListener('hashchange', this._onHashChange, false); + this._map.off('moveend', this._updateHash); + clearTimeout(this._updateHash()); + this._removeHash(); + delete this._map; + return this; + } + getHashString(mapFeedback) { + const center = this._map.getCenter(), zoom = Math.round(this._map.getZoom() * 100) / 100, + // derived from equation: 512px * 2^z / 360 / 10^d < 0.5px + precision = Math.ceil((zoom * Math.LN2 + Math.log(512 / 360 / 0.5)) / Math.LN10), m = Math.pow(10, precision), lng = Math.round(center.lng * m) / m, lat = Math.round(center.lat * m) / m, bearing = this._map.getBearing(), pitch = this._map.getPitch(); + let hash = ''; + if (mapFeedback) { + // new map feedback site has some constraints that don't allow + // us to use the same hash format as we do for the Map hash option. + hash += `/${lng}/${lat}/${zoom}`; + } + else { + hash += `${zoom}/${lat}/${lng}`; + } + if (bearing || pitch) + hash += (`/${Math.round(bearing * 10) / 10}`); + if (pitch) + hash += (`/${Math.round(pitch)}`); + if (this._hashName) { + const hashName = this._hashName; + let found = false; + const parts = window.location.hash.slice(1).split('&').map(part => { + const key = part.split('=')[0]; + if (key === hashName) { + found = true; + return `${key}=${hash}`; + } + return part; + }).filter(a => a); + if (!found) { + parts.push(`${hashName}=${hash}`); + } + return `#${parts.join('&')}`; + } + return `#${hash}`; + } +} + +const defaultInertiaOptions = { + linearity: 0.3, + easing: performance$1.bezier(0, 0, 0.3, 1), +}; +const defaultPanInertiaOptions = performance$1.extend({ + deceleration: 2500, + maxSpeed: 1400 +}, defaultInertiaOptions); +const defaultZoomInertiaOptions = performance$1.extend({ + deceleration: 20, + maxSpeed: 1400 +}, defaultInertiaOptions); +const defaultBearingInertiaOptions = performance$1.extend({ + deceleration: 1000, + maxSpeed: 360 +}, defaultInertiaOptions); +const defaultPitchInertiaOptions = performance$1.extend({ + deceleration: 1000, + maxSpeed: 90 +}, defaultInertiaOptions); +class HandlerInertia { + constructor(map) { + this._map = map; + this.clear(); + } + clear() { + this._inertiaBuffer = []; + } + record(settings) { + this._drainInertiaBuffer(); + this._inertiaBuffer.push({ time: browser.now(), settings }); + } + _drainInertiaBuffer() { + const inertia = this._inertiaBuffer, now = browser.now(), cutoff = 160; //msec + while (inertia.length > 0 && now - inertia[0].time > cutoff) + inertia.shift(); + } + _onMoveEnd(panInertiaOptions) { + this._drainInertiaBuffer(); + if (this._inertiaBuffer.length < 2) { + return; + } + const deltas = { + zoom: 0, + bearing: 0, + pitch: 0, + pan: new performance$1.Point(0, 0), + pinchAround: undefined, + around: undefined + }; + for (const { settings } of this._inertiaBuffer) { + deltas.zoom += settings.zoomDelta || 0; + deltas.bearing += settings.bearingDelta || 0; + deltas.pitch += settings.pitchDelta || 0; + if (settings.panDelta) + deltas.pan._add(settings.panDelta); + if (settings.around) + deltas.around = settings.around; + if (settings.pinchAround) + deltas.pinchAround = settings.pinchAround; + } + const lastEntry = this._inertiaBuffer[this._inertiaBuffer.length - 1]; + const duration = (lastEntry.time - this._inertiaBuffer[0].time); + const easeOptions = {}; + if (deltas.pan.mag()) { + const result = calculateEasing(deltas.pan.mag(), duration, performance$1.extend({}, defaultPanInertiaOptions, panInertiaOptions || {})); + easeOptions.offset = deltas.pan.mult(result.amount / deltas.pan.mag()); + easeOptions.center = this._map.transform.center; + extendDuration(easeOptions, result); + } + if (deltas.zoom) { + const result = calculateEasing(deltas.zoom, duration, defaultZoomInertiaOptions); + easeOptions.zoom = this._map.transform.zoom + result.amount; + extendDuration(easeOptions, result); + } + if (deltas.bearing) { + const result = calculateEasing(deltas.bearing, duration, defaultBearingInertiaOptions); + easeOptions.bearing = this._map.transform.bearing + performance$1.clamp(result.amount, -179, 179); + extendDuration(easeOptions, result); + } + if (deltas.pitch) { + const result = calculateEasing(deltas.pitch, duration, defaultPitchInertiaOptions); + easeOptions.pitch = this._map.transform.pitch + result.amount; + extendDuration(easeOptions, result); + } + if (easeOptions.zoom || easeOptions.bearing) { + const last = deltas.pinchAround === undefined ? deltas.around : deltas.pinchAround; + easeOptions.around = last ? this._map.unproject(last) : this._map.getCenter(); + } + this.clear(); + return performance$1.extend(easeOptions, { + noMoveStart: true + }); + } +} +// Unfortunately zoom, bearing, etc can't have different durations and easings so +// we need to choose one. We use the longest duration and it's corresponding easing. +function extendDuration(easeOptions, result) { + if (!easeOptions.duration || easeOptions.duration < result.duration) { + easeOptions.duration = result.duration; + easeOptions.easing = result.easing; + } +} +function calculateEasing(amount, inertiaDuration, inertiaOptions) { + const { maxSpeed, linearity, deceleration } = inertiaOptions; + const speed = performance$1.clamp(amount * linearity / (inertiaDuration / 1000), -maxSpeed, maxSpeed); + const duration = Math.abs(speed) / (deceleration * linearity); + return { + easing: inertiaOptions.easing, + duration: duration * 1000, + amount: speed * (duration / 2) + }; +} + +/** + * `MapMouseEvent` is the event type for mouse-related map events. + * + * @group Event Related + * + * @example + * ```ts + * // The `click` event is an example of a `MapMouseEvent`. + * // Set up an event listener on the map. + * map.on('click', (e) => { + * // The event object (e) contains information like the + * // coordinates of the point on the map that was clicked. + * console.log('A click event has occurred at ' + e.lngLat); + * }); + * ``` + */ +class MapMouseEvent extends performance$1.Event { + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the following default map behaviors: + * + * * On `mousedown` events, the behavior of {@link DragPanHandler} + * * On `mousedown` events, the behavior of {@link DragRotateHandler} + * * On `mousedown` events, the behavior of {@link BoxZoomHandler} + * * On `dblclick` events, the behavior of {@link DoubleClickZoomHandler} + * + */ + preventDefault() { + this._defaultPrevented = true; + } + /** + * `true` if `preventDefault` has been called. + */ + get defaultPrevented() { + return this._defaultPrevented; + } + constructor(type, map, originalEvent, data = {}) { + const point = DOM.mousePos(map.getCanvas(), originalEvent); + const lngLat = map.unproject(point); + super(type, performance$1.extend({ point, lngLat, originalEvent }, data)); + this._defaultPrevented = false; + this.target = map; + } +} +/** + * `MapTouchEvent` is the event type for touch-related map events. + * + * @group Event Related + */ +class MapTouchEvent extends performance$1.Event { + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the following default map behaviors: + * + * * On `touchstart` events, the behavior of {@link DragPanHandler} + * * On `touchstart` events, the behavior of {@link TwoFingersTouchZoomRotateHandler} + * + */ + preventDefault() { + this._defaultPrevented = true; + } + /** + * `true` if `preventDefault` has been called. + */ + get defaultPrevented() { + return this._defaultPrevented; + } + constructor(type, map, originalEvent) { + const touches = type === 'touchend' ? originalEvent.changedTouches : originalEvent.touches; + const points = DOM.touchPos(map.getCanvasContainer(), touches); + const lngLats = points.map((t) => map.unproject(t)); + const point = points.reduce((prev, curr, i, arr) => { + return prev.add(curr.div(arr.length)); + }, new performance$1.Point(0, 0)); + const lngLat = map.unproject(point); + super(type, { points, point, lngLats, lngLat, originalEvent }); + this._defaultPrevented = false; + } +} +/** + * `MapWheelEvent` is the event type for the `wheel` map event. + * + * @group Event Related + */ +class MapWheelEvent extends performance$1.Event { + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the behavior of {@link ScrollZoomHandler}. + */ + preventDefault() { + this._defaultPrevented = true; + } + /** + * `true` if `preventDefault` has been called. + */ + get defaultPrevented() { + return this._defaultPrevented; + } + /** */ + constructor(type, map, originalEvent) { + super(type, { originalEvent }); + this._defaultPrevented = false; + } +} + +class MapEventHandler { + constructor(map, options) { + this._map = map; + this._clickTolerance = options.clickTolerance; + } + reset() { + delete this._mousedownPos; + } + wheel(e) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - ScrollZoom + return this._firePreventable(new MapWheelEvent(e.type, this._map, e)); + } + mousedown(e, point) { + this._mousedownPos = point; + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - MousePan + // - MouseRotate + // - MousePitch + // - DblclickHandler + return this._firePreventable(new MapMouseEvent(e.type, this._map, e)); + } + mouseup(e) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + click(e, point) { + if (this._mousedownPos && this._mousedownPos.dist(point) >= this._clickTolerance) + return; + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + dblclick(e) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - DblClickZoom + return this._firePreventable(new MapMouseEvent(e.type, this._map, e)); + } + mouseover(e) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + mouseout(e) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + touchstart(e) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - TouchPan + // - TouchZoom + // - TouchRotate + // - TouchPitch + // - TapZoom + // - SwipeZoom + return this._firePreventable(new MapTouchEvent(e.type, this._map, e)); + } + touchmove(e) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + touchend(e) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + touchcancel(e) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + _firePreventable(mapEvent) { + this._map.fire(mapEvent); + if (mapEvent.defaultPrevented) { + // returning an object marks the handler as active and resets other handlers + return {}; + } + } + isEnabled() { + return true; + } + isActive() { + return false; + } + enable() { } + disable() { } +} +class BlockableMapEventHandler { + constructor(map) { + this._map = map; + } + reset() { + this._delayContextMenu = false; + this._ignoreContextMenu = true; + delete this._contextMenuEvent; + } + mousemove(e) { + // mousemove map events should not be fired when interaction handlers (pan, rotate, etc) are active + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + mousedown() { + this._delayContextMenu = true; + this._ignoreContextMenu = false; + } + mouseup() { + this._delayContextMenu = false; + if (this._contextMenuEvent) { + this._map.fire(new MapMouseEvent('contextmenu', this._map, this._contextMenuEvent)); + delete this._contextMenuEvent; + } + } + contextmenu(e) { + if (this._delayContextMenu) { + // Mac: contextmenu fired on mousedown; we save it until mouseup for consistency's sake + this._contextMenuEvent = e; + } + else if (!this._ignoreContextMenu) { + // Windows: contextmenu fired on mouseup, so fire event now + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + // prevent browser context menu when necessary + if (this._map.listens('contextmenu')) { + e.preventDefault(); + } + } + isEnabled() { + return true; + } + isActive() { + return false; + } + enable() { } + disable() { } +} + +/** + * @internal + * Shared utilities for the Handler classes to access the correct camera state. + * If Camera.transformCameraUpdate is specified or terrain is enabled, the + * "desired state" of camera may differ from the state used for rendering. The + * handlers need the "desired state" to track accumulated changes. + */ +class TransformProvider { + constructor(map) { + this._map = map; + } + get transform() { + return this._map._requestedCameraState || this._map.transform; + } + get center() { + return { lng: this.transform.center.lng, lat: this.transform.center.lat }; + } + get zoom() { + return this.transform.zoom; + } + get pitch() { + return this.transform.pitch; + } + get bearing() { + return this.transform.bearing; + } + unproject(point) { + return this.transform.pointLocation(performance$1.Point.convert(point), this._map.terrain); + } +} + +/** + * The `BoxZoomHandler` allows the user to zoom the map to fit within a bounding box. + * The bounding box is defined by clicking and holding `shift` while dragging the cursor. + * + * @group Handlers + */ +class BoxZoomHandler { + /** @internal */ + constructor(map, options) { + this._map = map; + this._tr = new TransformProvider(map); + this._el = map.getCanvasContainer(); + this._container = map.getContainer(); + this._clickTolerance = options.clickTolerance || 1; + } + /** + * Returns a Boolean indicating whether the "box zoom" interaction is enabled. + * + * @returns `true` if the "box zoom" interaction is enabled. + */ + isEnabled() { + return !!this._enabled; + } + /** + * Returns a Boolean indicating whether the "box zoom" interaction is active, i.e. currently being used. + * + * @returns `true` if the "box zoom" interaction is active. + */ + isActive() { + return !!this._active; + } + /** + * Enables the "box zoom" interaction. + * + * @example + * ```ts + * map.boxZoom.enable(); + * ``` + */ + enable() { + if (this.isEnabled()) + return; + this._enabled = true; + } + /** + * Disables the "box zoom" interaction. + * + * @example + * ```ts + * map.boxZoom.disable(); + * ``` + */ + disable() { + if (!this.isEnabled()) + return; + this._enabled = false; + } + mousedown(e, point) { + if (!this.isEnabled()) + return; + if (!(e.shiftKey && e.button === 0)) + return; + DOM.disableDrag(); + this._startPos = this._lastPos = point; + this._active = true; + } + mousemoveWindow(e, point) { + if (!this._active) + return; + const pos = point; + if (this._lastPos.equals(pos) || (!this._box && pos.dist(this._startPos) < this._clickTolerance)) { + return; + } + const p0 = this._startPos; + this._lastPos = pos; + if (!this._box) { + this._box = DOM.create('div', 'maplibregl-boxzoom', this._container); + this._container.classList.add('maplibregl-crosshair'); + this._fireEvent('boxzoomstart', e); + } + const minX = Math.min(p0.x, pos.x), maxX = Math.max(p0.x, pos.x), minY = Math.min(p0.y, pos.y), maxY = Math.max(p0.y, pos.y); + DOM.setTransform(this._box, `translate(${minX}px,${minY}px)`); + this._box.style.width = `${maxX - minX}px`; + this._box.style.height = `${maxY - minY}px`; + } + mouseupWindow(e, point) { + if (!this._active) + return; + if (e.button !== 0) + return; + const p0 = this._startPos, p1 = point; + this.reset(); + DOM.suppressClick(); + if (p0.x === p1.x && p0.y === p1.y) { + this._fireEvent('boxzoomcancel', e); + } + else { + this._map.fire(new performance$1.Event('boxzoomend', { originalEvent: e })); + return { + cameraAnimation: map => map.fitScreenCoordinates(p0, p1, this._tr.bearing, { linear: true }) + }; + } + } + keydown(e) { + if (!this._active) + return; + if (e.keyCode === 27) { + this.reset(); + this._fireEvent('boxzoomcancel', e); + } + } + reset() { + this._active = false; + this._container.classList.remove('maplibregl-crosshair'); + if (this._box) { + DOM.remove(this._box); + this._box = null; + } + DOM.enableDrag(); + delete this._startPos; + delete this._lastPos; + } + _fireEvent(type, e) { + return this._map.fire(new performance$1.Event(type, { originalEvent: e })); + } +} + +function indexTouches(touches, points) { + if (touches.length !== points.length) + throw new Error(`The number of touches and points are not equal - touches ${touches.length}, points ${points.length}`); + const obj = {}; + for (let i = 0; i < touches.length; i++) { + obj[touches[i].identifier] = points[i]; + } + return obj; +} + +function getCentroid(points) { + const sum = new performance$1.Point(0, 0); + for (const point of points) { + sum._add(point); + } + return sum.div(points.length); +} +const MAX_TAP_INTERVAL = 500; +const MAX_TOUCH_TIME = 500; +const MAX_DIST = 30; +class SingleTapRecognizer { + constructor(options) { + this.reset(); + this.numTouches = options.numTouches; + } + reset() { + delete this.centroid; + delete this.startTime; + delete this.touches; + this.aborted = false; + } + touchstart(e, points, mapTouches) { + if (this.centroid || mapTouches.length > this.numTouches) { + this.aborted = true; + } + if (this.aborted) { + return; + } + if (this.startTime === undefined) { + this.startTime = e.timeStamp; + } + if (mapTouches.length === this.numTouches) { + this.centroid = getCentroid(points); + this.touches = indexTouches(mapTouches, points); + } + } + touchmove(e, points, mapTouches) { + if (this.aborted || !this.centroid) + return; + const newTouches = indexTouches(mapTouches, points); + for (const id in this.touches) { + const prevPos = this.touches[id]; + const pos = newTouches[id]; + if (!pos || pos.dist(prevPos) > MAX_DIST) { + this.aborted = true; + } + } + } + touchend(e, points, mapTouches) { + if (!this.centroid || e.timeStamp - this.startTime > MAX_TOUCH_TIME) { + this.aborted = true; + } + if (mapTouches.length === 0) { + const centroid = !this.aborted && this.centroid; + this.reset(); + if (centroid) + return centroid; + } + } +} +class TapRecognizer { + constructor(options) { + this.singleTap = new SingleTapRecognizer(options); + this.numTaps = options.numTaps; + this.reset(); + } + reset() { + this.lastTime = Infinity; + delete this.lastTap; + this.count = 0; + this.singleTap.reset(); + } + touchstart(e, points, mapTouches) { + this.singleTap.touchstart(e, points, mapTouches); + } + touchmove(e, points, mapTouches) { + this.singleTap.touchmove(e, points, mapTouches); + } + touchend(e, points, mapTouches) { + const tap = this.singleTap.touchend(e, points, mapTouches); + if (tap) { + const soonEnough = e.timeStamp - this.lastTime < MAX_TAP_INTERVAL; + const closeEnough = !this.lastTap || this.lastTap.dist(tap) < MAX_DIST; + if (!soonEnough || !closeEnough) { + this.reset(); + } + this.count++; + this.lastTime = e.timeStamp; + this.lastTap = tap; + if (this.count === this.numTaps) { + this.reset(); + return tap; + } + } + } +} + +/** + * A `TapZoomHandler` allows the user to zoom the map at a point by double tapping + */ +class TapZoomHandler { + constructor(map) { + this._tr = new TransformProvider(map); + this._zoomIn = new TapRecognizer({ + numTouches: 1, + numTaps: 2 + }); + this._zoomOut = new TapRecognizer({ + numTouches: 2, + numTaps: 1 + }); + this.reset(); + } + reset() { + this._active = false; + this._zoomIn.reset(); + this._zoomOut.reset(); + } + touchstart(e, points, mapTouches) { + this._zoomIn.touchstart(e, points, mapTouches); + this._zoomOut.touchstart(e, points, mapTouches); + } + touchmove(e, points, mapTouches) { + this._zoomIn.touchmove(e, points, mapTouches); + this._zoomOut.touchmove(e, points, mapTouches); + } + touchend(e, points, mapTouches) { + const zoomInPoint = this._zoomIn.touchend(e, points, mapTouches); + const zoomOutPoint = this._zoomOut.touchend(e, points, mapTouches); + const tr = this._tr; + if (zoomInPoint) { + this._active = true; + e.preventDefault(); + setTimeout(() => this.reset(), 0); + return { + cameraAnimation: (map) => map.easeTo({ + duration: 300, + zoom: tr.zoom + 1, + around: tr.unproject(zoomInPoint) + }, { originalEvent: e }) + }; + } + else if (zoomOutPoint) { + this._active = true; + e.preventDefault(); + setTimeout(() => this.reset(), 0); + return { + cameraAnimation: (map) => map.easeTo({ + duration: 300, + zoom: tr.zoom - 1, + around: tr.unproject(zoomOutPoint) + }, { originalEvent: e }) + }; + } + } + touchcancel() { + this.reset(); + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } +} + +/** + * A generic class to create handlers for drag events, from both mouse and touch events. + */ +class DragHandler { + constructor(options) { + this._enabled = !!options.enable; + this._moveStateManager = options.moveStateManager; + this._clickTolerance = options.clickTolerance || 1; + this._moveFunction = options.move; + this._activateOnStart = !!options.activateOnStart; + options.assignEvents(this); + this.reset(); + } + reset(e) { + this._active = false; + this._moved = false; + delete this._lastPoint; + this._moveStateManager.endMove(e); + } + _move(...params) { + const move = this._moveFunction(...params); + if (move.bearingDelta || move.pitchDelta || move.around || move.panDelta) { + this._active = true; + return move; + } + } + dragStart(e, point) { + if (!this.isEnabled() || this._lastPoint) + return; + if (!this._moveStateManager.isValidStartEvent(e)) + return; + this._moveStateManager.startMove(e); + this._lastPoint = point['length'] ? point[0] : point; + if (this._activateOnStart && this._lastPoint) + this._active = true; + } + dragMove(e, point) { + if (!this.isEnabled()) + return; + const lastPoint = this._lastPoint; + if (!lastPoint) + return; + e.preventDefault(); + if (!this._moveStateManager.isValidMoveEvent(e)) { + this.reset(e); + return; + } + const movePoint = point['length'] ? point[0] : point; + if (!this._moved && movePoint.dist(lastPoint) < this._clickTolerance) + return; + this._moved = true; + this._lastPoint = movePoint; + return this._move(lastPoint, movePoint); + } + dragEnd(e) { + if (!this.isEnabled() || !this._lastPoint) + return; + if (!this._moveStateManager.isValidEndEvent(e)) + return; + if (this._moved) + DOM.suppressClick(); + this.reset(e); + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } + getClickTolerance() { + return this._clickTolerance; + } +} + +const LEFT_BUTTON$1 = 0; +const RIGHT_BUTTON$1 = 2; +// the values for each button in MouseEvent.buttons +const BUTTONS_FLAGS = { + [LEFT_BUTTON$1]: 1, + [RIGHT_BUTTON$1]: 2 +}; +function buttonNoLongerPressed(e, button) { + const flag = BUTTONS_FLAGS[button]; + return e.buttons === undefined || (e.buttons & flag) !== flag; +} +class MouseMoveStateManager { + constructor(options) { + this._correctEvent = options.checkCorrectEvent; + } + startMove(e) { + const eventButton = DOM.mouseButton(e); + this._eventButton = eventButton; + } + endMove(_e) { + delete this._eventButton; + } + isValidStartEvent(e) { + return this._correctEvent(e); + } + isValidMoveEvent(e) { + // Some browsers don't fire a `mouseup` when the mouseup occurs outside + // the window or iframe: + // https://github.com/mapbox/mapbox-gl-js/issues/4622 + // + // If the button is no longer pressed during this `mousemove` it may have + // been released outside of the window or iframe. + return !buttonNoLongerPressed(e, this._eventButton); + } + isValidEndEvent(e) { + const eventButton = DOM.mouseButton(e); + return eventButton === this._eventButton; + } +} +class OneFingerTouchMoveStateManager { + constructor() { + this._firstTouch = undefined; + } + _isOneFingerTouch(e) { + return e.targetTouches.length === 1; + } + _isSameTouchEvent(e) { + return e.targetTouches[0].identifier === this._firstTouch; + } + startMove(e) { + const firstTouch = e.targetTouches[0].identifier; + this._firstTouch = firstTouch; + } + endMove(_e) { + delete this._firstTouch; + } + isValidStartEvent(e) { + return this._isOneFingerTouch(e); + } + isValidMoveEvent(e) { + return this._isOneFingerTouch(e) && this._isSameTouchEvent(e); + } + isValidEndEvent(e) { + return this._isOneFingerTouch(e) && this._isSameTouchEvent(e); + } +} + +const LEFT_BUTTON = 0; +const RIGHT_BUTTON = 2; +const assignEvents$1 = (handler) => { + handler.mousedown = handler.dragStart; + handler.mousemoveWindow = handler.dragMove; + handler.mouseup = handler.dragEnd; + handler.contextmenu = (e) => { + e.preventDefault(); + }; +}; +const generateMousePanHandler = ({ enable, clickTolerance, }) => { + const mouseMoveStateManager = new MouseMoveStateManager({ + checkCorrectEvent: (e) => DOM.mouseButton(e) === LEFT_BUTTON && !e.ctrlKey, + }); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ around: point, panDelta: point.sub(lastPoint) }), + activateOnStart: true, + moveStateManager: mouseMoveStateManager, + enable, + assignEvents: assignEvents$1, + }); +}; +const generateMouseRotationHandler = ({ enable, clickTolerance, bearingDegreesPerPixelMoved = 0.8 }) => { + const mouseMoveStateManager = new MouseMoveStateManager({ + checkCorrectEvent: (e) => (DOM.mouseButton(e) === LEFT_BUTTON && e.ctrlKey) || + (DOM.mouseButton(e) === RIGHT_BUTTON), + }); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ bearingDelta: (point.x - lastPoint.x) * bearingDegreesPerPixelMoved }), + // prevent browser context menu when necessary; we don't allow it with rotation + // because we can't discern rotation gesture start from contextmenu on Mac + moveStateManager: mouseMoveStateManager, + enable, + assignEvents: assignEvents$1, + }); +}; +const generateMousePitchHandler = ({ enable, clickTolerance, pitchDegreesPerPixelMoved = -0.5 }) => { + const mouseMoveStateManager = new MouseMoveStateManager({ + checkCorrectEvent: (e) => (DOM.mouseButton(e) === LEFT_BUTTON && e.ctrlKey) || + (DOM.mouseButton(e) === RIGHT_BUTTON), + }); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ pitchDelta: (point.y - lastPoint.y) * pitchDegreesPerPixelMoved }), + // prevent browser context menu when necessary; we don't allow it with rotation + // because we can't discern rotation gesture start from contextmenu on Mac + moveStateManager: mouseMoveStateManager, + enable, + assignEvents: assignEvents$1, + }); +}; + +/** + * A `TouchPanHandler` allows the user to pan the map using touch gestures. + */ +class TouchPanHandler { + constructor(options, map) { + this._clickTolerance = options.clickTolerance || 1; + this._map = map; + this.reset(); + } + reset() { + this._active = false; + this._touches = {}; + this._sum = new performance$1.Point(0, 0); + } + _shouldBePrevented(touchesCount) { + const minTouches = this._map.cooperativeGestures.isEnabled() ? 2 : 1; + return touchesCount < minTouches; + } + touchstart(e, points, mapTouches) { + return this._calculateTransform(e, points, mapTouches); + } + touchmove(e, points, mapTouches) { + if (!this._active) + return; + if (this._shouldBePrevented(mapTouches.length)) { + this._map.cooperativeGestures.notifyGestureBlocked('touch_pan', e); + return; + } + e.preventDefault(); + return this._calculateTransform(e, points, mapTouches); + } + touchend(e, points, mapTouches) { + this._calculateTransform(e, points, mapTouches); + if (this._active && this._shouldBePrevented(mapTouches.length)) { + this.reset(); + } + } + touchcancel() { + this.reset(); + } + _calculateTransform(e, points, mapTouches) { + if (mapTouches.length > 0) + this._active = true; + const touches = indexTouches(mapTouches, points); + const touchPointSum = new performance$1.Point(0, 0); + const touchDeltaSum = new performance$1.Point(0, 0); + let touchDeltaCount = 0; + for (const identifier in touches) { + const point = touches[identifier]; + const prevPoint = this._touches[identifier]; + if (prevPoint) { + touchPointSum._add(point); + touchDeltaSum._add(point.sub(prevPoint)); + touchDeltaCount++; + touches[identifier] = point; + } + } + this._touches = touches; + if (this._shouldBePrevented(touchDeltaCount) || !touchDeltaSum.mag()) + return; + const panDelta = touchDeltaSum.div(touchDeltaCount); + this._sum._add(panDelta); + if (this._sum.mag() < this._clickTolerance) + return; + const around = touchPointSum.div(touchDeltaCount); + return { + around, + panDelta + }; + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } +} + +/** + * The `TwoFingersTouchHandler`s allows the user to zoom, pitch and rotate the map using two fingers + * + */ +class TwoFingersTouchHandler { + /** @internal */ + constructor() { + this.reset(); + } + reset() { + this._active = false; + delete this._firstTwoTouches; + } + touchstart(e, points, mapTouches) { + //log('touchstart', points, e.target.innerHTML, e.targetTouches.length ? e.targetTouches[0].target.innerHTML: undefined); + if (this._firstTwoTouches || mapTouches.length < 2) + return; + this._firstTwoTouches = [ + mapTouches[0].identifier, + mapTouches[1].identifier + ]; + // implemented by child classes + this._start([points[0], points[1]]); + } + touchmove(e, points, mapTouches) { + if (!this._firstTwoTouches) + return; + e.preventDefault(); + const [idA, idB] = this._firstTwoTouches; + const a = getTouchById(mapTouches, points, idA); + const b = getTouchById(mapTouches, points, idB); + if (!a || !b) + return; + const pinchAround = this._aroundCenter ? null : a.add(b).div(2); + // implemented by child classes + return this._move([a, b], pinchAround, e); + } + touchend(e, points, mapTouches) { + if (!this._firstTwoTouches) + return; + const [idA, idB] = this._firstTwoTouches; + const a = getTouchById(mapTouches, points, idA); + const b = getTouchById(mapTouches, points, idB); + if (a && b) + return; + if (this._active) + DOM.suppressClick(); + this.reset(); + } + touchcancel() { + this.reset(); + } + /** + * Enables the "drag to pitch" interaction. + * + * @example + * ```ts + * map.touchPitch.enable(); + * ``` + */ + enable(options) { + this._enabled = true; + this._aroundCenter = !!options && options.around === 'center'; + } + /** + * Disables the "drag to pitch" interaction. + * + * @example + * ```ts + * map.touchPitch.disable(); + * ``` + */ + disable() { + this._enabled = false; + this.reset(); + } + /** + * Returns a Boolean indicating whether the "drag to pitch" interaction is enabled. + * + * @returns `true` if the "drag to pitch" interaction is enabled. + */ + isEnabled() { + return !!this._enabled; + } + /** + * Returns a Boolean indicating whether the "drag to pitch" interaction is active, i.e. currently being used. + * + * @returns `true` if the "drag to pitch" interaction is active. + */ + isActive() { + return !!this._active; + } +} +function getTouchById(mapTouches, points, identifier) { + for (let i = 0; i < mapTouches.length; i++) { + if (mapTouches[i].identifier === identifier) + return points[i]; + } + return undefined; +} +/* ZOOM */ +const ZOOM_THRESHOLD = 0.1; +function getZoomDelta(distance, lastDistance) { + return Math.log(distance / lastDistance) / Math.LN2; +} +/** + * The `TwoFingersTouchHandler`s allows the user to zoom the map two fingers + * + * @group Handlers + */ +class TwoFingersTouchZoomHandler extends TwoFingersTouchHandler { + reset() { + super.reset(); + delete this._distance; + delete this._startDistance; + } + _start(points) { + this._startDistance = this._distance = points[0].dist(points[1]); + } + _move(points, pinchAround) { + const lastDistance = this._distance; + this._distance = points[0].dist(points[1]); + if (!this._active && Math.abs(getZoomDelta(this._distance, this._startDistance)) < ZOOM_THRESHOLD) + return; + this._active = true; + return { + zoomDelta: getZoomDelta(this._distance, lastDistance), + pinchAround + }; + } +} +/* ROTATE */ +const ROTATION_THRESHOLD = 25; // pixels along circumference of touch circle +function getBearingDelta(a, b) { + return a.angleWith(b) * 180 / Math.PI; +} +/** + * The `TwoFingersTouchHandler`s allows the user to rotate the map two fingers + * + * @group Handlers + */ +class TwoFingersTouchRotateHandler extends TwoFingersTouchHandler { + reset() { + super.reset(); + delete this._minDiameter; + delete this._startVector; + delete this._vector; + } + _start(points) { + this._startVector = this._vector = points[0].sub(points[1]); + this._minDiameter = points[0].dist(points[1]); + } + _move(points, pinchAround, _e) { + const lastVector = this._vector; + this._vector = points[0].sub(points[1]); + if (!this._active && this._isBelowThreshold(this._vector)) + return; + this._active = true; + return { + bearingDelta: getBearingDelta(this._vector, lastVector), + pinchAround + }; + } + _isBelowThreshold(vector) { + /* + * The threshold before a rotation actually happens is configured in + * pixels along the circumference of the circle formed by the two fingers. + * This makes the threshold in degrees larger when the fingers are close + * together and smaller when the fingers are far apart. + * + * Use the smallest diameter from the whole gesture to reduce sensitivity + * when pinching in and out. + */ + this._minDiameter = Math.min(this._minDiameter, vector.mag()); + const circumference = Math.PI * this._minDiameter; + const threshold = ROTATION_THRESHOLD / circumference * 360; + const bearingDeltaSinceStart = getBearingDelta(vector, this._startVector); + return Math.abs(bearingDeltaSinceStart) < threshold; + } +} +/* PITCH */ +function isVertical(vector) { + return Math.abs(vector.y) > Math.abs(vector.x); +} +const ALLOWED_SINGLE_TOUCH_TIME = 100; +/** + * The `TwoFingersTouchPitchHandler` allows the user to pitch the map by dragging up and down with two fingers. + * + * @group Handlers + */ +class TwoFingersTouchPitchHandler extends TwoFingersTouchHandler { + constructor(map) { + super(); + this._currentTouchCount = 0; + this._map = map; + } + reset() { + super.reset(); + this._valid = undefined; + delete this._firstMove; + delete this._lastPoints; + } + touchstart(e, points, mapTouches) { + super.touchstart(e, points, mapTouches); + this._currentTouchCount = mapTouches.length; + } + _start(points) { + this._lastPoints = points; + if (isVertical(points[0].sub(points[1]))) { + // fingers are more horizontal than vertical + this._valid = false; + } + } + _move(points, center, e) { + // If cooperative gestures is enabled, we need a 3-finger minimum for this gesture to register + if (this._map.cooperativeGestures.isEnabled() && this._currentTouchCount < 3) { + return; + } + const vectorA = points[0].sub(this._lastPoints[0]); + const vectorB = points[1].sub(this._lastPoints[1]); + this._valid = this.gestureBeginsVertically(vectorA, vectorB, e.timeStamp); + if (!this._valid) + return; + this._lastPoints = points; + this._active = true; + const yDeltaAverage = (vectorA.y + vectorB.y) / 2; + const degreesPerPixelMoved = -0.5; + return { + pitchDelta: yDeltaAverage * degreesPerPixelMoved + }; + } + gestureBeginsVertically(vectorA, vectorB, timeStamp) { + if (this._valid !== undefined) + return this._valid; + const threshold = 2; + const movedA = vectorA.mag() >= threshold; + const movedB = vectorB.mag() >= threshold; + // neither finger has moved a meaningful amount, wait + if (!movedA && !movedB) + return; + // One finger has moved and the other has not. + // If enough time has passed, decide it is not a pitch. + if (!movedA || !movedB) { + if (this._firstMove === undefined) { + this._firstMove = timeStamp; + } + if (timeStamp - this._firstMove < ALLOWED_SINGLE_TOUCH_TIME) { + // still waiting for a movement from the second finger + return undefined; + } + else { + return false; + } + } + const isSameDirection = vectorA.y > 0 === vectorB.y > 0; + return isVertical(vectorA) && isVertical(vectorB) && isSameDirection; + } +} + +const defaultOptions$5 = { + panStep: 100, + bearingStep: 15, + pitchStep: 10 +}; +/** + * The `KeyboardHandler` allows the user to zoom, rotate, and pan the map using + * the following keyboard shortcuts: + * + * - `=` / `+`: Increase the zoom level by 1. + * - `Shift-=` / `Shift-+`: Increase the zoom level by 2. + * - `-`: Decrease the zoom level by 1. + * - `Shift--`: Decrease the zoom level by 2. + * - Arrow keys: Pan by 100 pixels. + * - `Shift+⇢`: Increase the rotation by 15 degrees. + * - `Shift+⇠`: Decrease the rotation by 15 degrees. + * - `Shift+⇡`: Increase the pitch by 10 degrees. + * - `Shift+⇣`: Decrease the pitch by 10 degrees. + * + * @group Handlers + */ +class KeyboardHandler { + /** @internal */ + constructor(map) { + this._tr = new TransformProvider(map); + const stepOptions = defaultOptions$5; + this._panStep = stepOptions.panStep; + this._bearingStep = stepOptions.bearingStep; + this._pitchStep = stepOptions.pitchStep; + this._rotationDisabled = false; + } + reset() { + this._active = false; + } + keydown(e) { + if (e.altKey || e.ctrlKey || e.metaKey) + return; + let zoomDir = 0; + let bearingDir = 0; + let pitchDir = 0; + let xDir = 0; + let yDir = 0; + switch (e.keyCode) { + case 61: + case 107: + case 171: + case 187: + zoomDir = 1; + break; + case 189: + case 109: + case 173: + zoomDir = -1; + break; + case 37: + if (e.shiftKey) { + bearingDir = -1; + } + else { + e.preventDefault(); + xDir = -1; + } + break; + case 39: + if (e.shiftKey) { + bearingDir = 1; + } + else { + e.preventDefault(); + xDir = 1; + } + break; + case 38: + if (e.shiftKey) { + pitchDir = 1; + } + else { + e.preventDefault(); + yDir = -1; + } + break; + case 40: + if (e.shiftKey) { + pitchDir = -1; + } + else { + e.preventDefault(); + yDir = 1; + } + break; + default: + return; + } + if (this._rotationDisabled) { + bearingDir = 0; + pitchDir = 0; + } + return { + cameraAnimation: (map) => { + const tr = this._tr; + map.easeTo({ + duration: 300, + easeId: 'keyboardHandler', + easing: easeOut, + zoom: zoomDir ? Math.round(tr.zoom) + zoomDir * (e.shiftKey ? 2 : 1) : tr.zoom, + bearing: tr.bearing + bearingDir * this._bearingStep, + pitch: tr.pitch + pitchDir * this._pitchStep, + offset: [-xDir * this._panStep, -yDir * this._panStep], + center: tr.center + }, { originalEvent: e }); + } + }; + } + /** + * Enables the "keyboard rotate and zoom" interaction. + * + * @example + * ```ts + * map.keyboard.enable(); + * ``` + */ + enable() { + this._enabled = true; + } + /** + * Disables the "keyboard rotate and zoom" interaction. + * + * @example + * ```ts + * map.keyboard.disable(); + * ``` + */ + disable() { + this._enabled = false; + this.reset(); + } + /** + * Returns a Boolean indicating whether the "keyboard rotate and zoom" + * interaction is enabled. + * + * @returns `true` if the "keyboard rotate and zoom" + * interaction is enabled. + */ + isEnabled() { + return this._enabled; + } + /** + * Returns true if the handler is enabled and has detected the start of a + * zoom/rotate gesture. + * + * @returns `true` if the handler is enabled and has detected the + * start of a zoom/rotate gesture. + */ + isActive() { + return this._active; + } + /** + * Disables the "keyboard pan/rotate" interaction, leaving the + * "keyboard zoom" interaction enabled. + * + * @example + * ```ts + * map.keyboard.disableRotation(); + * ``` + */ + disableRotation() { + this._rotationDisabled = true; + } + /** + * Enables the "keyboard pan/rotate" interaction. + * + * @example + * ```ts + * map.keyboard.enable(); + * map.keyboard.enableRotation(); + * ``` + */ + enableRotation() { + this._rotationDisabled = false; + } +} +function easeOut(t) { + return t * (2 - t); +} + +// deltaY value for mouse scroll wheel identification +const wheelZoomDelta = 4.000244140625; +// These magic numbers control the rate of zoom. Trackpad events fire at a greater +// frequency than mouse scroll wheel, so reduce the zoom rate per wheel tick +const defaultZoomRate = 1 / 100; +const wheelZoomRate = 1 / 450; +// upper bound on how much we scale the map in any single render frame; this +// is used to limit zoom rate in the case of very fast scrolling +const maxScalePerFrame = 2; +/** + * The `ScrollZoomHandler` allows the user to zoom the map by scrolling. + * + * @group Handlers + */ +class ScrollZoomHandler { + /** @internal */ + constructor(map, triggerRenderFrame) { + this._onTimeout = (initialEvent) => { + this._type = 'wheel'; + this._delta -= this._lastValue; + if (!this._active) { + this._start(initialEvent); + } + }; + this._map = map; + this._tr = new TransformProvider(map); + this._triggerRenderFrame = triggerRenderFrame; + this._delta = 0; + this._defaultZoomRate = defaultZoomRate; + this._wheelZoomRate = wheelZoomRate; + } + /** + * Set the zoom rate of a trackpad + * @param zoomRate - 1/100 The rate used to scale trackpad movement to a zoom value. + * @example + * Speed up trackpad zoom + * ```ts + * map.scrollZoom.setZoomRate(1/25); + * ``` + */ + setZoomRate(zoomRate) { + this._defaultZoomRate = zoomRate; + } + /** + * Set the zoom rate of a mouse wheel + * @param wheelZoomRate - 1/450 The rate used to scale mouse wheel movement to a zoom value. + * @example + * Slow down zoom of mouse wheel + * ```ts + * map.scrollZoom.setWheelZoomRate(1/600); + * ``` + */ + setWheelZoomRate(wheelZoomRate) { + this._wheelZoomRate = wheelZoomRate; + } + /** + * Returns a Boolean indicating whether the "scroll to zoom" interaction is enabled. + * @returns `true` if the "scroll to zoom" interaction is enabled. + */ + isEnabled() { + return !!this._enabled; + } + /* + * Active state is turned on and off with every scroll wheel event and is set back to false before the map + * render is called, so _active is not a good candidate for determining if a scroll zoom animation is in + * progress. + */ + isActive() { + return !!this._active || this._finishTimeout !== undefined; + } + isZooming() { + return !!this._zooming; + } + /** + * Enables the "scroll to zoom" interaction. + * + * @param options - Options object. + * @example + * ```ts + * map.scrollZoom.enable(); + * map.scrollZoom.enable({ around: 'center' }) + * ``` + */ + enable(options) { + if (this.isEnabled()) + return; + this._enabled = true; + this._aroundCenter = !!options && options.around === 'center'; + } + /** + * Disables the "scroll to zoom" interaction. + * + * @example + * ```ts + * map.scrollZoom.disable(); + * ``` + */ + disable() { + if (!this.isEnabled()) + return; + this._enabled = false; + } + /** + * Determines whether or not the gesture is blocked due to cooperativeGestures. + */ + _shouldBePrevented(e) { + if (!this._map.cooperativeGestures.isEnabled()) { + return false; + } + const isTrackpadPinch = e.ctrlKey; + const isBypassed = isTrackpadPinch || this._map.cooperativeGestures.isBypassed(e); + return !isBypassed; + } + wheel(e) { + if (!this.isEnabled()) + return; + if (this._shouldBePrevented(e)) { + this._map.cooperativeGestures.notifyGestureBlocked('wheel_zoom', e); + return; + } + let value = e.deltaMode === WheelEvent.DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY; + const now = browser.now(), timeDelta = now - (this._lastWheelEventTime || 0); + this._lastWheelEventTime = now; + if (value !== 0 && (value % wheelZoomDelta) === 0) { + // This one is definitely a mouse wheel event. + this._type = 'wheel'; + } + else if (value !== 0 && Math.abs(value) < 4) { + // This one is definitely a trackpad event because it is so small. + this._type = 'trackpad'; + } + else if (timeDelta > 400) { + // This is likely a new scroll action. + this._type = null; + this._lastValue = value; + // Start a timeout in case this was a singular event, and delay it by up to 40ms. + this._timeout = setTimeout(this._onTimeout, 40, e); + } + else if (!this._type) { + // This is a repeating event, but we don't know the type of event just yet. + // If the delta per time is small, we assume it's a fast trackpad; otherwise we switch into wheel mode. + this._type = (Math.abs(timeDelta * value) < 200) ? 'trackpad' : 'wheel'; + // Make sure our delayed event isn't fired again, because we accumulate + // the previous event (which was less than 40ms ago) into this event. + if (this._timeout) { + clearTimeout(this._timeout); + this._timeout = null; + value += this._lastValue; + } + } + // Slow down zoom if shift key is held for more precise zooming + if (e.shiftKey && value) + value = value / 4; + // Only fire the callback if we actually know what type of scrolling device the user uses. + if (this._type) { + this._lastWheelEvent = e; + this._delta -= value; + if (!this._active) { + this._start(e); + } + } + e.preventDefault(); + } + _start(e) { + if (!this._delta) + return; + if (this._frameId) { + this._frameId = null; + } + this._active = true; + if (!this.isZooming()) { + this._zooming = true; + } + if (this._finishTimeout) { + clearTimeout(this._finishTimeout); + delete this._finishTimeout; + } + const pos = DOM.mousePos(this._map.getCanvas(), e); + const tr = this._tr; + if (pos.y > tr.transform.height / 2 - tr.transform.getHorizon()) { + this._around = performance$1.LngLat.convert(this._aroundCenter ? tr.center : tr.unproject(pos)); + } + else { + // Do not use current cursor position if above the horizon to avoid 'unproject' this point + // as it is not mapped into 'coords' framebuffer or inversible with 'pixelMatrixInverse'. + this._around = performance$1.LngLat.convert(tr.center); + } + this._aroundPoint = tr.transform.locationPoint(this._around); + if (!this._frameId) { + this._frameId = true; + this._triggerRenderFrame(); + } + } + renderFrame() { + if (!this._frameId) + return; + this._frameId = null; + if (!this.isActive()) + return; + const tr = this._tr.transform; + // if we've had scroll events since the last render frame, consume the + // accumulated delta, and update the target zoom level accordingly + if (this._delta !== 0) { + // For trackpad events and single mouse wheel ticks, use the default zoom rate + const zoomRate = (this._type === 'wheel' && Math.abs(this._delta) > wheelZoomDelta) ? this._wheelZoomRate : this._defaultZoomRate; + // Scale by sigmoid of scroll wheel delta. + let scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * zoomRate))); + if (this._delta < 0 && scale !== 0) { + scale = 1 / scale; + } + const fromScale = typeof this._targetZoom === 'number' ? tr.zoomScale(this._targetZoom) : tr.scale; + this._targetZoom = Math.min(tr.maxZoom, Math.max(tr.minZoom, tr.scaleZoom(fromScale * scale))); + // if this is a mouse wheel, refresh the starting zoom and easing + // function we're using to smooth out the zooming between wheel + // events + if (this._type === 'wheel') { + this._startZoom = tr.zoom; + this._easing = this._smoothOutEasing(200); + } + this._delta = 0; + } + const targetZoom = typeof this._targetZoom === 'number' ? + this._targetZoom : tr.zoom; + const startZoom = this._startZoom; + const easing = this._easing; + let finished = false; + let zoom; + const lastWheelEventTimeDiff = browser.now() - this._lastWheelEventTime; + if (this._type === 'wheel' && startZoom && easing && lastWheelEventTimeDiff) { + const t = Math.min(lastWheelEventTimeDiff / 200, 1); + const k = easing(t); + zoom = performance$1.interpolate.number(startZoom, targetZoom, k); + if (t < 1) { + if (!this._frameId) { + this._frameId = true; + } + } + else { + finished = true; + } + } + else { + zoom = targetZoom; + finished = true; + } + this._active = true; + if (finished) { + this._active = false; + this._finishTimeout = setTimeout(() => { + this._zooming = false; + this._triggerRenderFrame(); + delete this._targetZoom; + delete this._finishTimeout; + }, 200); + } + return { + noInertia: true, + needsRenderFrame: !finished, + zoomDelta: zoom - tr.zoom, + around: this._aroundPoint, + originalEvent: this._lastWheelEvent + }; + } + _smoothOutEasing(duration) { + let easing = performance$1.defaultEasing; + if (this._prevEase) { + const currentEase = this._prevEase; + const t = (browser.now() - currentEase.start) / currentEase.duration; + const speed = currentEase.easing(t + 0.01) - currentEase.easing(t); + // Quick hack to make new bezier that is continuous with last + const x = 0.27 / Math.sqrt(speed * speed + 0.0001) * 0.01; + const y = Math.sqrt(0.27 * 0.27 - x * x); + easing = performance$1.bezier(x, y, 0.25, 1); + } + this._prevEase = { + start: browser.now(), + duration, + easing + }; + return easing; + } + reset() { + this._active = false; + this._zooming = false; + delete this._targetZoom; + if (this._finishTimeout) { + clearTimeout(this._finishTimeout); + delete this._finishTimeout; + } + } +} + +/** + * The `DoubleClickZoomHandler` allows the user to zoom the map at a point by + * double clicking or double tapping. + * + * @group Handlers + */ +class DoubleClickZoomHandler { + /** @internal */ + constructor(clickZoom, TapZoom) { + this._clickZoom = clickZoom; + this._tapZoom = TapZoom; + } + /** + * Enables the "double click to zoom" interaction. + * + * @example + * ```ts + * map.doubleClickZoom.enable(); + * ``` + */ + enable() { + this._clickZoom.enable(); + this._tapZoom.enable(); + } + /** + * Disables the "double click to zoom" interaction. + * + * @example + * ```ts + * map.doubleClickZoom.disable(); + * ``` + */ + disable() { + this._clickZoom.disable(); + this._tapZoom.disable(); + } + /** + * Returns a Boolean indicating whether the "double click to zoom" interaction is enabled. + * + * @returns `true` if the "double click to zoom" interaction is enabled. + */ + isEnabled() { + return this._clickZoom.isEnabled() && this._tapZoom.isEnabled(); + } + /** + * Returns a Boolean indicating whether the "double click to zoom" interaction is active, i.e. currently being used. + * + * @returns `true` if the "double click to zoom" interaction is active. + */ + isActive() { + return this._clickZoom.isActive() || this._tapZoom.isActive(); + } +} + +/** + * The `ClickZoomHandler` allows the user to zoom the map at a point by double clicking + * It is used by other handlers + */ +class ClickZoomHandler { + /** @internal */ + constructor(map) { + this._tr = new TransformProvider(map); + this.reset(); + } + reset() { + this._active = false; + } + dblclick(e, point) { + e.preventDefault(); + return { + cameraAnimation: (map) => { + map.easeTo({ + duration: 300, + zoom: this._tr.zoom + (e.shiftKey ? -1 : 1), + around: this._tr.unproject(point) + }, { originalEvent: e }); + } + }; + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } +} + +/** + * A `TapDragZoomHandler` allows the user to zoom the map at a point by double tapping. It also allows the user pan the map by dragging. + */ +class TapDragZoomHandler { + constructor() { + this._tap = new TapRecognizer({ + numTouches: 1, + numTaps: 1 + }); + this.reset(); + } + reset() { + this._active = false; + delete this._swipePoint; + delete this._swipeTouch; + delete this._tapTime; + delete this._tapPoint; + this._tap.reset(); + } + touchstart(e, points, mapTouches) { + if (this._swipePoint) + return; + if (!this._tapTime) { + this._tap.touchstart(e, points, mapTouches); + } + else { + const swipePoint = points[0]; + const soonEnough = e.timeStamp - this._tapTime < MAX_TAP_INTERVAL; + const closeEnough = this._tapPoint.dist(swipePoint) < MAX_DIST; + if (!soonEnough || !closeEnough) { + this.reset(); + } + else if (mapTouches.length > 0) { + this._swipePoint = swipePoint; + this._swipeTouch = mapTouches[0].identifier; + } + } + } + touchmove(e, points, mapTouches) { + if (!this._tapTime) { + this._tap.touchmove(e, points, mapTouches); + } + else if (this._swipePoint) { + if (mapTouches[0].identifier !== this._swipeTouch) { + return; + } + const newSwipePoint = points[0]; + const dist = newSwipePoint.y - this._swipePoint.y; + this._swipePoint = newSwipePoint; + e.preventDefault(); + this._active = true; + return { + zoomDelta: dist / 128 + }; + } + } + touchend(e, points, mapTouches) { + if (!this._tapTime) { + const point = this._tap.touchend(e, points, mapTouches); + if (point) { + this._tapTime = e.timeStamp; + this._tapPoint = point; + } + } + else if (this._swipePoint) { + if (mapTouches.length === 0) { + this.reset(); + } + } + } + touchcancel() { + this.reset(); + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } +} + +/** + * The `DragPanHandler` allows the user to pan the map by clicking and dragging + * the cursor. + * + * @group Handlers + */ +class DragPanHandler { + /** @internal */ + constructor(el, mousePan, touchPan) { + this._el = el; + this._mousePan = mousePan; + this._touchPan = touchPan; + } + /** + * Enables the "drag to pan" interaction. + * + * @param options - Options object + * @example + * ```ts + * map.dragPan.enable(); + * map.dragPan.enable({ + * linearity: 0.3, + * easing: bezier(0, 0, 0.3, 1), + * maxSpeed: 1400, + * deceleration: 2500, + * }); + * ``` + */ + enable(options) { + this._inertiaOptions = options || {}; + this._mousePan.enable(); + this._touchPan.enable(); + this._el.classList.add('maplibregl-touch-drag-pan'); + } + /** + * Disables the "drag to pan" interaction. + * + * @example + * ```ts + * map.dragPan.disable(); + * ``` + */ + disable() { + this._mousePan.disable(); + this._touchPan.disable(); + this._el.classList.remove('maplibregl-touch-drag-pan'); + } + /** + * Returns a Boolean indicating whether the "drag to pan" interaction is enabled. + * + * @returns `true` if the "drag to pan" interaction is enabled. + */ + isEnabled() { + return this._mousePan.isEnabled() && this._touchPan.isEnabled(); + } + /** + * Returns a Boolean indicating whether the "drag to pan" interaction is active, i.e. currently being used. + * + * @returns `true` if the "drag to pan" interaction is active. + */ + isActive() { + return this._mousePan.isActive() || this._touchPan.isActive(); + } +} + +/** + * The `DragRotateHandler` allows the user to rotate the map by clicking and + * dragging the cursor while holding the right mouse button or `ctrl` key. + * + * @group Handlers + */ +class DragRotateHandler { + /** @internal */ + constructor(options, mouseRotate, mousePitch) { + this._pitchWithRotate = options.pitchWithRotate; + this._mouseRotate = mouseRotate; + this._mousePitch = mousePitch; + } + /** + * Enables the "drag to rotate" interaction. + * + * @example + * ```ts + * map.dragRotate.enable(); + * ``` + */ + enable() { + this._mouseRotate.enable(); + if (this._pitchWithRotate) + this._mousePitch.enable(); + } + /** + * Disables the "drag to rotate" interaction. + * + * @example + * ```ts + * map.dragRotate.disable(); + * ``` + */ + disable() { + this._mouseRotate.disable(); + this._mousePitch.disable(); + } + /** + * Returns a Boolean indicating whether the "drag to rotate" interaction is enabled. + * + * @returns `true` if the "drag to rotate" interaction is enabled. + */ + isEnabled() { + return this._mouseRotate.isEnabled() && (!this._pitchWithRotate || this._mousePitch.isEnabled()); + } + /** + * Returns a Boolean indicating whether the "drag to rotate" interaction is active, i.e. currently being used. + * + * @returns `true` if the "drag to rotate" interaction is active. + */ + isActive() { + return this._mouseRotate.isActive() || this._mousePitch.isActive(); + } +} + +/** + * The `TwoFingersTouchZoomRotateHandler` allows the user to zoom and rotate the map by + * pinching on a touchscreen. + * + * They can zoom with one finger by double tapping and dragging. On the second tap, + * hold the finger down and drag up or down to zoom in or out. + * + * @group Handlers + */ +class TwoFingersTouchZoomRotateHandler { + /** @internal */ + constructor(el, touchZoom, touchRotate, tapDragZoom) { + this._el = el; + this._touchZoom = touchZoom; + this._touchRotate = touchRotate; + this._tapDragZoom = tapDragZoom; + this._rotationDisabled = false; + this._enabled = true; + } + /** + * Enables the "pinch to rotate and zoom" interaction. + * + * @param options - Options object. + * + * @example + * ```ts + * map.touchZoomRotate.enable(); + * map.touchZoomRotate.enable({ around: 'center' }); + * ``` + */ + enable(options) { + this._touchZoom.enable(options); + if (!this._rotationDisabled) + this._touchRotate.enable(options); + this._tapDragZoom.enable(); + this._el.classList.add('maplibregl-touch-zoom-rotate'); + } + /** + * Disables the "pinch to rotate and zoom" interaction. + * + * @example + * ```ts + * map.touchZoomRotate.disable(); + * ``` + */ + disable() { + this._touchZoom.disable(); + this._touchRotate.disable(); + this._tapDragZoom.disable(); + this._el.classList.remove('maplibregl-touch-zoom-rotate'); + } + /** + * Returns a Boolean indicating whether the "pinch to rotate and zoom" interaction is enabled. + * + * @returns `true` if the "pinch to rotate and zoom" interaction is enabled. + */ + isEnabled() { + return this._touchZoom.isEnabled() && + (this._rotationDisabled || this._touchRotate.isEnabled()) && + this._tapDragZoom.isEnabled(); + } + /** + * Returns true if the handler is enabled and has detected the start of a zoom/rotate gesture. + * + * @returns `true` if the handler is active, `false` otherwise + */ + isActive() { + return this._touchZoom.isActive() || this._touchRotate.isActive() || this._tapDragZoom.isActive(); + } + /** + * Disables the "pinch to rotate" interaction, leaving the "pinch to zoom" + * interaction enabled. + * + * @example + * ```ts + * map.touchZoomRotate.disableRotation(); + * ``` + */ + disableRotation() { + this._rotationDisabled = true; + this._touchRotate.disable(); + } + /** + * Enables the "pinch to rotate" interaction. + * + * @example + * ```ts + * map.touchZoomRotate.enable(); + * map.touchZoomRotate.enableRotation(); + * ``` + */ + enableRotation() { + this._rotationDisabled = false; + if (this._touchZoom.isEnabled()) + this._touchRotate.enable(); + } +} + +/** + * A `CooperativeGestureHandler` is a control that adds cooperative gesture info when user tries to zoom in/out. + * + * When the CooperativeGestureHandler blocks a gesture, it will emit a `cooperativegestureprevented` event. + * + * @group Handlers + * + * @example + * ```ts + * const map = new Map({ + * cooperativeGestures: true + * }); + * ``` + * @see [Example: cooperative gestures](https://maplibre.org/maplibre-gl-js/docs/examples/cooperative-gestures/) + **/ +class CooperativeGesturesHandler { + constructor(map, options) { + /** + * This is the key that will allow to bypass the cooperative gesture protection + */ + this._bypassKey = navigator.userAgent.indexOf('Mac') !== -1 ? 'metaKey' : 'ctrlKey'; + this._map = map; + this._options = options; + this._enabled = false; + } + isActive() { + return false; + } + reset() { } + _setupUI() { + if (this._container) + return; + const mapCanvasContainer = this._map.getCanvasContainer(); + // Add a cooperative gestures class (enable touch-action: pan-x pan-y;) + mapCanvasContainer.classList.add('maplibregl-cooperative-gestures'); + this._container = DOM.create('div', 'maplibregl-cooperative-gesture-screen', mapCanvasContainer); + let desktopMessage = this._map._getUIString('CooperativeGesturesHandler.WindowsHelpText'); + if (this._bypassKey === 'metaKey') { + desktopMessage = this._map._getUIString('CooperativeGesturesHandler.MacHelpText'); + } + const mobileMessage = this._map._getUIString('CooperativeGesturesHandler.MobileHelpText'); + // Create and append the desktop message div + const desktopDiv = document.createElement('div'); + desktopDiv.className = 'maplibregl-desktop-message'; + desktopDiv.textContent = desktopMessage; + this._container.appendChild(desktopDiv); + // Create and append the mobile message div + const mobileDiv = document.createElement('div'); + mobileDiv.className = 'maplibregl-mobile-message'; + mobileDiv.textContent = mobileMessage; + this._container.appendChild(mobileDiv); + // Remove cooperative gesture screen from the accessibility tree since screenreaders cannot interact with the map using gestures + this._container.setAttribute('aria-hidden', 'true'); + } + _destroyUI() { + if (this._container) { + DOM.remove(this._container); + const mapCanvasContainer = this._map.getCanvasContainer(); + mapCanvasContainer.classList.remove('maplibregl-cooperative-gestures'); + } + delete this._container; + } + enable() { + this._setupUI(); + this._enabled = true; + } + disable() { + this._enabled = false; + this._destroyUI(); + } + isEnabled() { + return this._enabled; + } + isBypassed(event) { + return event[this._bypassKey]; + } + notifyGestureBlocked(gestureType, originalEvent) { + if (!this._enabled) + return; + // notify subscribers that a cooperative gesture was prevented + this._map.fire(new performance$1.Event('cooperativegestureprevented', { gestureType, originalEvent })); + // Alert user how to scroll/pan + this._container.classList.add('maplibregl-show'); + setTimeout(() => { + this._container.classList.remove('maplibregl-show'); + }, 100); + } +} + +const isMoving = (p) => p.zoom || p.drag || p.pitch || p.rotate; +class RenderFrameEvent extends performance$1.Event { +} +function hasChange(result) { + return (result.panDelta && result.panDelta.mag()) || result.zoomDelta || result.bearingDelta || result.pitchDelta; +} +class HandlerManager { + constructor(map, options) { + this.handleWindowEvent = (e) => { + this.handleEvent(e, `${e.type}Window`); + }; + this.handleEvent = (e, eventName) => { + if (e.type === 'blur') { + this.stop(true); + return; + } + this._updatingCamera = true; + const inputEvent = e.type === 'renderFrame' ? undefined : e; + /* + * We don't call e.preventDefault() for any events by default. + * Handlers are responsible for calling it where necessary. + */ + const mergedHandlerResult = { needsRenderFrame: false }; + const eventsInProgress = {}; + const activeHandlers = {}; + const eventTouches = e.touches; + const mapTouches = eventTouches ? this._getMapTouches(eventTouches) : undefined; + const points = mapTouches ? + DOM.touchPos(this._map.getCanvas(), mapTouches) : + DOM.mousePos(this._map.getCanvas(), e); + for (const { handlerName, handler, allowed } of this._handlers) { + if (!handler.isEnabled()) + continue; + let data; + if (this._blockedByActive(activeHandlers, allowed, handlerName)) { + handler.reset(); + } + else { + if (handler[eventName || e.type]) { + data = handler[eventName || e.type](e, points, mapTouches); + this.mergeHandlerResult(mergedHandlerResult, eventsInProgress, data, handlerName, inputEvent); + if (data && data.needsRenderFrame) { + this._triggerRenderFrame(); + } + } + } + if (data || handler.isActive()) { + activeHandlers[handlerName] = handler; + } + } + const deactivatedHandlers = {}; + for (const name in this._previousActiveHandlers) { + if (!activeHandlers[name]) { + deactivatedHandlers[name] = inputEvent; + } + } + this._previousActiveHandlers = activeHandlers; + if (Object.keys(deactivatedHandlers).length || hasChange(mergedHandlerResult)) { + this._changes.push([mergedHandlerResult, eventsInProgress, deactivatedHandlers]); + this._triggerRenderFrame(); + } + if (Object.keys(activeHandlers).length || hasChange(mergedHandlerResult)) { + this._map._stop(true); + } + this._updatingCamera = false; + const { cameraAnimation } = mergedHandlerResult; + if (cameraAnimation) { + this._inertia.clear(); + this._fireEvents({}, {}, true); + this._changes = []; + cameraAnimation(this._map); + } + }; + this._map = map; + this._el = this._map.getCanvasContainer(); + this._handlers = []; + this._handlersById = {}; + this._changes = []; + this._inertia = new HandlerInertia(map); + this._bearingSnap = options.bearingSnap; + this._previousActiveHandlers = {}; + // Track whether map is currently moving, to compute start/move/end events + this._eventsInProgress = {}; + this._addDefaultHandlers(options); + const el = this._el; + this._listeners = [ + // This needs to be `passive: true` so that a double tap fires two + // pairs of touchstart/end events in iOS Safari 13. If this is set to + // `passive: false` then the second pair of events is only fired if + // preventDefault() is called on the first touchstart. Calling preventDefault() + // undesirably prevents click events. + [el, 'touchstart', { passive: true }], + // This needs to be `passive: false` so that scrolls and pinches can be + // prevented in browsers that don't support `touch-actions: none`, for example iOS Safari 12. + [el, 'touchmove', { passive: false }], + [el, 'touchend', undefined], + [el, 'touchcancel', undefined], + [el, 'mousedown', undefined], + [el, 'mousemove', undefined], + [el, 'mouseup', undefined], + // Bind window-level event listeners for move and up/end events. In the absence of + // the pointer capture API, which is not supported by all necessary platforms, + // window-level event listeners give us the best shot at capturing events that + // fall outside the map canvas element. Use `{capture: true}` for the move event + // to prevent map move events from being fired during a drag. + [document, 'mousemove', { capture: true }], + [document, 'mouseup', undefined], + [el, 'mouseover', undefined], + [el, 'mouseout', undefined], + [el, 'dblclick', undefined], + [el, 'click', undefined], + [el, 'keydown', { capture: false }], + [el, 'keyup', undefined], + [el, 'wheel', { passive: false }], + [el, 'contextmenu', undefined], + [window, 'blur', undefined] + ]; + for (const [target, type, listenerOptions] of this._listeners) { + DOM.addEventListener(target, type, target === document ? this.handleWindowEvent : this.handleEvent, listenerOptions); + } + } + destroy() { + for (const [target, type, listenerOptions] of this._listeners) { + DOM.removeEventListener(target, type, target === document ? this.handleWindowEvent : this.handleEvent, listenerOptions); + } + } + _addDefaultHandlers(options) { + const map = this._map; + const el = map.getCanvasContainer(); + this._add('mapEvent', new MapEventHandler(map, options)); + const boxZoom = map.boxZoom = new BoxZoomHandler(map, options); + this._add('boxZoom', boxZoom); + if (options.interactive && options.boxZoom) { + boxZoom.enable(); + } + const cooperativeGestures = map.cooperativeGestures = new CooperativeGesturesHandler(map, options.cooperativeGestures); + this._add('cooperativeGestures', cooperativeGestures); + if (options.cooperativeGestures) { + cooperativeGestures.enable(); + } + const tapZoom = new TapZoomHandler(map); + const clickZoom = new ClickZoomHandler(map); + map.doubleClickZoom = new DoubleClickZoomHandler(clickZoom, tapZoom); + this._add('tapZoom', tapZoom); + this._add('clickZoom', clickZoom); + if (options.interactive && options.doubleClickZoom) { + map.doubleClickZoom.enable(); + } + const tapDragZoom = new TapDragZoomHandler(); + this._add('tapDragZoom', tapDragZoom); + const touchPitch = map.touchPitch = new TwoFingersTouchPitchHandler(map); + this._add('touchPitch', touchPitch); + if (options.interactive && options.touchPitch) { + map.touchPitch.enable(options.touchPitch); + } + const mouseRotate = generateMouseRotationHandler(options); + const mousePitch = generateMousePitchHandler(options); + map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch); + this._add('mouseRotate', mouseRotate, ['mousePitch']); + this._add('mousePitch', mousePitch, ['mouseRotate']); + if (options.interactive && options.dragRotate) { + map.dragRotate.enable(); + } + const mousePan = generateMousePanHandler(options); + const touchPan = new TouchPanHandler(options, map); + map.dragPan = new DragPanHandler(el, mousePan, touchPan); + this._add('mousePan', mousePan); + this._add('touchPan', touchPan, ['touchZoom', 'touchRotate']); + if (options.interactive && options.dragPan) { + map.dragPan.enable(options.dragPan); + } + const touchRotate = new TwoFingersTouchRotateHandler(); + const touchZoom = new TwoFingersTouchZoomHandler(); + map.touchZoomRotate = new TwoFingersTouchZoomRotateHandler(el, touchZoom, touchRotate, tapDragZoom); + this._add('touchRotate', touchRotate, ['touchPan', 'touchZoom']); + this._add('touchZoom', touchZoom, ['touchPan', 'touchRotate']); + if (options.interactive && options.touchZoomRotate) { + map.touchZoomRotate.enable(options.touchZoomRotate); + } + const scrollZoom = map.scrollZoom = new ScrollZoomHandler(map, () => this._triggerRenderFrame()); + this._add('scrollZoom', scrollZoom, ['mousePan']); + if (options.interactive && options.scrollZoom) { + map.scrollZoom.enable(options.scrollZoom); + } + const keyboard = map.keyboard = new KeyboardHandler(map); + this._add('keyboard', keyboard); + if (options.interactive && options.keyboard) { + map.keyboard.enable(); + } + this._add('blockableMapEvent', new BlockableMapEventHandler(map)); + } + _add(handlerName, handler, allowed) { + this._handlers.push({ handlerName, handler, allowed }); + this._handlersById[handlerName] = handler; + } + stop(allowEndAnimation) { + // do nothing if this method was triggered by a gesture update + if (this._updatingCamera) + return; + for (const { handler } of this._handlers) { + handler.reset(); + } + this._inertia.clear(); + this._fireEvents({}, {}, allowEndAnimation); + this._changes = []; + } + isActive() { + for (const { handler } of this._handlers) { + if (handler.isActive()) + return true; + } + return false; + } + isZooming() { + return !!this._eventsInProgress.zoom || this._map.scrollZoom.isZooming(); + } + isRotating() { + return !!this._eventsInProgress.rotate; + } + isMoving() { + return Boolean(isMoving(this._eventsInProgress)) || this.isZooming(); + } + _blockedByActive(activeHandlers, allowed, myName) { + for (const name in activeHandlers) { + if (name === myName) + continue; + if (!allowed || allowed.indexOf(name) < 0) { + return true; + } + } + return false; + } + _getMapTouches(touches) { + const mapTouches = []; + for (const t of touches) { + const target = t.target; + if (this._el.contains(target)) { + mapTouches.push(t); + } + } + return mapTouches; + } + mergeHandlerResult(mergedHandlerResult, eventsInProgress, handlerResult, name, e) { + if (!handlerResult) + return; + performance$1.extend(mergedHandlerResult, handlerResult); + const eventData = { handlerName: name, originalEvent: handlerResult.originalEvent || e }; + // track which handler changed which camera property + if (handlerResult.zoomDelta !== undefined) { + eventsInProgress.zoom = eventData; + } + if (handlerResult.panDelta !== undefined) { + eventsInProgress.drag = eventData; + } + if (handlerResult.pitchDelta !== undefined) { + eventsInProgress.pitch = eventData; + } + if (handlerResult.bearingDelta !== undefined) { + eventsInProgress.rotate = eventData; + } + } + _applyChanges() { + const combined = {}; + const combinedEventsInProgress = {}; + const combinedDeactivatedHandlers = {}; + for (const [change, eventsInProgress, deactivatedHandlers] of this._changes) { + if (change.panDelta) + combined.panDelta = (combined.panDelta || new performance$1.Point(0, 0))._add(change.panDelta); + if (change.zoomDelta) + combined.zoomDelta = (combined.zoomDelta || 0) + change.zoomDelta; + if (change.bearingDelta) + combined.bearingDelta = (combined.bearingDelta || 0) + change.bearingDelta; + if (change.pitchDelta) + combined.pitchDelta = (combined.pitchDelta || 0) + change.pitchDelta; + if (change.around !== undefined) + combined.around = change.around; + if (change.pinchAround !== undefined) + combined.pinchAround = change.pinchAround; + if (change.noInertia) + combined.noInertia = change.noInertia; + performance$1.extend(combinedEventsInProgress, eventsInProgress); + performance$1.extend(combinedDeactivatedHandlers, deactivatedHandlers); + } + this._updateMapTransform(combined, combinedEventsInProgress, combinedDeactivatedHandlers); + this._changes = []; + } + _updateMapTransform(combinedResult, combinedEventsInProgress, deactivatedHandlers) { + const map = this._map; + const tr = map._getTransformForUpdate(); + const terrain = map.terrain; + if (!hasChange(combinedResult) && !(terrain && this._terrainMovement)) { + return this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true); + } + let { panDelta, zoomDelta, bearingDelta, pitchDelta, around, pinchAround } = combinedResult; + if (pinchAround !== undefined) { + around = pinchAround; + } + // stop any ongoing camera animations (easeTo, flyTo) + map._stop(true); + around = around || map.transform.centerPoint; + const loc = tr.pointLocation(panDelta ? around.sub(panDelta) : around); + if (bearingDelta) + tr.bearing += bearingDelta; + if (pitchDelta) + tr.pitch += pitchDelta; + if (zoomDelta) + tr.zoom += zoomDelta; + if (!terrain) { + tr.setLocationAtPoint(loc, around); + } + else { + // when 3d-terrain is enabled act a little different: + // - dragging do not drag the picked point itself, instead it drags the map by pixel-delta. + // With this approach it is no longer possible to pick a point from somewhere near + // the horizon to the center in one move. + // So this logic avoids the problem, that in such cases you easily loose orientation. + if (!this._terrainMovement && + (combinedEventsInProgress.drag || combinedEventsInProgress.zoom)) { + // When starting to drag or move, flag it and register moveend to clear flagging + this._terrainMovement = true; + this._map._elevationFreeze = true; + tr.setLocationAtPoint(loc, around); + } + else if (combinedEventsInProgress.drag && this._terrainMovement) { + // drag map + tr.center = tr.pointLocation(tr.centerPoint.sub(panDelta)); + } + else { + tr.setLocationAtPoint(loc, around); + } + } + map._applyUpdatedTransform(tr); + this._map._update(); + if (!combinedResult.noInertia) + this._inertia.record(combinedResult); + this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true); + } + _fireEvents(newEventsInProgress, deactivatedHandlers, allowEndAnimation) { + const wasMoving = isMoving(this._eventsInProgress); + const nowMoving = isMoving(newEventsInProgress); + const startEvents = {}; + for (const eventName in newEventsInProgress) { + const { originalEvent } = newEventsInProgress[eventName]; + if (!this._eventsInProgress[eventName]) { + startEvents[`${eventName}start`] = originalEvent; + } + this._eventsInProgress[eventName] = newEventsInProgress[eventName]; + } + // fire start events only after this._eventsInProgress has been updated + if (!wasMoving && nowMoving) { + this._fireEvent('movestart', nowMoving.originalEvent); + } + for (const name in startEvents) { + this._fireEvent(name, startEvents[name]); + } + if (nowMoving) { + this._fireEvent('move', nowMoving.originalEvent); + } + for (const eventName in newEventsInProgress) { + const { originalEvent } = newEventsInProgress[eventName]; + this._fireEvent(eventName, originalEvent); + } + const endEvents = {}; + let originalEndEvent; + for (const eventName in this._eventsInProgress) { + const { handlerName, originalEvent } = this._eventsInProgress[eventName]; + if (!this._handlersById[handlerName].isActive()) { + delete this._eventsInProgress[eventName]; + originalEndEvent = deactivatedHandlers[handlerName] || originalEvent; + endEvents[`${eventName}end`] = originalEndEvent; + } + } + for (const name in endEvents) { + this._fireEvent(name, endEvents[name]); + } + const stillMoving = isMoving(this._eventsInProgress); + const finishedMoving = (wasMoving || nowMoving) && !stillMoving; + if (finishedMoving && this._terrainMovement) { + this._map._elevationFreeze = false; + this._terrainMovement = false; + const tr = this._map._getTransformForUpdate(); + tr.recalculateZoom(this._map.terrain); + this._map._applyUpdatedTransform(tr); + } + if (allowEndAnimation && finishedMoving) { + this._updatingCamera = true; + const inertialEase = this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions); + const shouldSnapToNorth = bearing => bearing !== 0 && -this._bearingSnap < bearing && bearing < this._bearingSnap; + if (inertialEase && (inertialEase.essential || !browser.prefersReducedMotion)) { + if (shouldSnapToNorth(inertialEase.bearing || this._map.getBearing())) { + inertialEase.bearing = 0; + } + inertialEase.freezeElevation = true; + this._map.easeTo(inertialEase, { originalEvent: originalEndEvent }); + } + else { + this._map.fire(new performance$1.Event('moveend', { originalEvent: originalEndEvent })); + if (shouldSnapToNorth(this._map.getBearing())) { + this._map.resetNorth(); + } + } + this._updatingCamera = false; + } + } + _fireEvent(type, e) { + this._map.fire(new performance$1.Event(type, e ? { originalEvent: e } : {})); + } + _requestFrame() { + this._map.triggerRepaint(); + return this._map._renderTaskQueue.add(timeStamp => { + delete this._frameId; + this.handleEvent(new RenderFrameEvent('renderFrame', { timeStamp })); + this._applyChanges(); + }); + } + _triggerRenderFrame() { + if (this._frameId === undefined) { + this._frameId = this._requestFrame(); + } + } +} + +class Camera extends performance$1.Evented { + constructor(transform, options) { + super(); + // Callback for map._requestRenderFrame + this._renderFrameCallback = () => { + const t = Math.min((browser.now() - this._easeStart) / this._easeOptions.duration, 1); + this._onEaseFrame(this._easeOptions.easing(t)); + // if _stop is called during _onEaseFrame from _fireMoveEvents we should avoid a new _requestRenderFrame, checking it by ensuring _easeFrameId was not deleted + if (t < 1 && this._easeFrameId) { + this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback); + } + else { + this.stop(); + } + }; + this._moving = false; + this._zooming = false; + this.transform = transform; + this._bearingSnap = options.bearingSnap; + this.on('moveend', () => { + delete this._requestedCameraState; + }); + } + /** + * Returns the map's geographical centerpoint. + * + * @returns The map's geographical centerpoint. + * @example + * Return a LngLat object such as `{lng: 0, lat: 0}` + * ```ts + * let center = map.getCenter(); + * // access longitude and latitude values directly + * let {lng, lat} = map.getCenter(); + * ``` + */ + getCenter() { return new performance$1.LngLat(this.transform.center.lng, this.transform.center.lat); } + /** + * Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param center - The centerpoint to set. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * map.setCenter([-74, 38]); + * ``` + */ + setCenter(center, eventData) { + return this.jumpTo({ center }, eventData); + } + /** + * Pans the map by the specified offset. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param offset - `x` and `y` coordinates by which to pan the map. + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/) + */ + panBy(offset, options, eventData) { + offset = performance$1.Point.convert(offset).mult(-1); + return this.panTo(this.transform.center, performance$1.extend({ offset }, options), eventData); + } + /** + * Pans the map to the specified location with an animated transition. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param lnglat - The location to pan the map to. + * @param options - Options describing the destination and animation of the transition. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * map.panTo([-74, 38]); + * // Specify that the panTo animation should last 5000 milliseconds. + * map.panTo([-74, 38], {duration: 5000}); + * ``` + * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/live-update-feature/) + */ + panTo(lnglat, options, eventData) { + return this.easeTo(performance$1.extend({ + center: lnglat + }, options), eventData); + } + /** + * Returns the map's current zoom level. + * + * @returns The map's current zoom level. + * @example + * ```ts + * map.getZoom(); + * ``` + */ + getZoom() { return this.transform.zoom; } + /** + * Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param zoom - The zoom level to set (0-20). + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Zoom to the zoom level 5 without an animated transition + * ```ts + * map.setZoom(5); + * ``` + */ + setZoom(zoom, eventData) { + this.jumpTo({ zoom }, eventData); + return this; + } + /** + * Zooms the map to the specified zoom level, with an animated transition. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param zoom - The zoom level to transition to. + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * // Zoom to the zoom level 5 without an animated transition + * map.zoomTo(5); + * // Zoom to the zoom level 8 with an animated transition + * map.zoomTo(8, { + * duration: 2000, + * offset: [100, 50] + * }); + * ``` + */ + zoomTo(zoom, options, eventData) { + return this.easeTo(performance$1.extend({ + zoom + }, options), eventData); + } + /** + * Increases the map's zoom level by 1. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Zoom the map in one level with a custom animation duration + * ```ts + * map.zoomIn({duration: 1000}); + * ``` + */ + zoomIn(options, eventData) { + this.zoomTo(this.getZoom() + 1, options, eventData); + return this; + } + /** + * Decreases the map's zoom level by 1. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Zoom the map out one level with a custom animation offset + * ```ts + * map.zoomOut({offset: [80, 60]}); + * ``` + */ + zoomOut(options, eventData) { + this.zoomTo(this.getZoom() - 1, options, eventData); + return this; + } + /** + * Returns the map's current bearing. The bearing is the compass direction that is "up"; for example, a bearing + * of 90° orients the map so that east is up. + * + * @returns The map's current bearing. + * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/) + */ + getBearing() { return this.transform.bearing; } + /** + * Sets the map's bearing (rotation). The bearing is the compass direction that is "up"; for example, a bearing + * of 90° orients the map so that east is up. + * + * Equivalent to `jumpTo({bearing: bearing})`. + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param bearing - The desired bearing. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Rotate the map to 90 degrees + * ```ts + * map.setBearing(90); + * ``` + */ + setBearing(bearing, eventData) { + this.jumpTo({ bearing }, eventData); + return this; + } + /** + * Returns the current padding applied around the map viewport. + * + * @returns The current padding around the map viewport. + */ + getPadding() { return this.transform.padding; } + /** + * Sets the padding in pixels around the viewport. + * + * Equivalent to `jumpTo({padding: padding})`. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param padding - The desired padding. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Sets a left padding of 300px, and a top padding of 50px + * ```ts + * map.setPadding({ left: 300, top: 50 }); + * ``` + */ + setPadding(padding, eventData) { + this.jumpTo({ padding }, eventData); + return this; + } + /** + * Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction + * that is "up"; for example, a bearing of 90° orients the map so that east is up. + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param bearing - The desired bearing. + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + rotateTo(bearing, options, eventData) { + return this.easeTo(performance$1.extend({ + bearing + }, options), eventData); + } + /** + * Rotates the map so that north is up (0° bearing), with an animated transition. + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + resetNorth(options, eventData) { + this.rotateTo(0, performance$1.extend({ duration: 1000 }, options), eventData); + return this; + } + /** + * Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + resetNorthPitch(options, eventData) { + this.easeTo(performance$1.extend({ + bearing: 0, + pitch: 0, + duration: 1000 + }, options), eventData); + return this; + } + /** + * Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the + * `bearingSnap` threshold). + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + snapToNorth(options, eventData) { + if (Math.abs(this.getBearing()) < this._bearingSnap) { + return this.resetNorth(options, eventData); + } + return this; + } + /** + * Returns the map's current pitch (tilt). + * + * @returns The map's current pitch, measured in degrees away from the plane of the screen. + */ + getPitch() { return this.transform.pitch; } + /** + * Sets the map's pitch (tilt). Equivalent to `jumpTo({pitch: pitch})`. + * + * Triggers the following events: `movestart`, `moveend`, `pitchstart`, and `pitchend`. + * + * @param pitch - The pitch to set, measured in degrees away from the plane of the screen (0-60). + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + setPitch(pitch, eventData) { + this.jumpTo({ pitch }, eventData); + return this; + } + /** + * @param bounds - Calculate the center for these bounds in the viewport and use + * the highest zoom level up to and including `Map#getMaxZoom()` that fits + * in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0. + * Bounds will be taken in [sw, ne] order. Southwest point will always be to the left of the northeast point. + * @param options - Options object + * @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`. + * If map is unable to fit, method will warn and return undefined. + * @example + * ```ts + * let bbox = [[-79, 43], [-73, 45]]; + * let newCameraTransform = map.cameraForBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + */ + cameraForBounds(bounds, options) { + bounds = LngLatBounds.convert(bounds).adjustAntiMeridian(); + const bearing = options && options.bearing || 0; + return this._cameraForBoxAndBearing(bounds.getNorthWest(), bounds.getSouthEast(), bearing, options); + } + /** + * @internal + * Calculate the center of these two points in the viewport and use + * the highest zoom level up to and including `Map#getMaxZoom()` that fits + * the points in the viewport at the specified bearing. + * @param p0 - First point + * @param p1 - Second point + * @param bearing - Desired map bearing at end of animation, in degrees + * @param options - the camera options + * @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`. + * If map is unable to fit, method will warn and return undefined. + * @example + * ```ts + * let p0 = [-79, 43]; + * let p1 = [-73, 45]; + * let bearing = 90; + * let newCameraTransform = map._cameraForBoxAndBearing(p0, p1, bearing, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + */ + _cameraForBoxAndBearing(p0, p1, bearing, options) { + const defaultPadding = { + top: 0, + bottom: 0, + right: 0, + left: 0 + }; + options = performance$1.extend({ + padding: defaultPadding, + offset: [0, 0], + maxZoom: this.transform.maxZoom + }, options); + if (typeof options.padding === 'number') { + const p = options.padding; + options.padding = { + top: p, + bottom: p, + right: p, + left: p + }; + } + options.padding = performance$1.extend(defaultPadding, options.padding); + const tr = this.transform; + const edgePadding = tr.padding; + // Consider all corners of the rotated bounding box derived from the given points + // when find the camera position that fits the given points. + const bounds = new LngLatBounds(p0, p1); + const nwWorld = tr.project(bounds.getNorthWest()); + const neWorld = tr.project(bounds.getNorthEast()); + const seWorld = tr.project(bounds.getSouthEast()); + const swWorld = tr.project(bounds.getSouthWest()); + const bearingRadians = performance$1.degreesToRadians(-bearing); + const nwRotatedWorld = nwWorld.rotate(bearingRadians); + const neRotatedWorld = neWorld.rotate(bearingRadians); + const seRotatedWorld = seWorld.rotate(bearingRadians); + const swRotatedWorld = swWorld.rotate(bearingRadians); + const upperRight = new performance$1.Point(Math.max(nwRotatedWorld.x, neRotatedWorld.x, swRotatedWorld.x, seRotatedWorld.x), Math.max(nwRotatedWorld.y, neRotatedWorld.y, swRotatedWorld.y, seRotatedWorld.y)); + const lowerLeft = new performance$1.Point(Math.min(nwRotatedWorld.x, neRotatedWorld.x, swRotatedWorld.x, seRotatedWorld.x), Math.min(nwRotatedWorld.y, neRotatedWorld.y, swRotatedWorld.y, seRotatedWorld.y)); + // Calculate zoom: consider the original bbox and padding. + const size = upperRight.sub(lowerLeft); + const scaleX = (tr.width - (edgePadding.left + edgePadding.right + options.padding.left + options.padding.right)) / size.x; + const scaleY = (tr.height - (edgePadding.top + edgePadding.bottom + options.padding.top + options.padding.bottom)) / size.y; + if (scaleY < 0 || scaleX < 0) { + performance$1.warnOnce('Map cannot fit within canvas with the given bounds, padding, and/or offset.'); + return undefined; + } + const zoom = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom); + // Calculate center: apply the zoom, the configured offset, as well as offset that exists as a result of padding. + const offset = performance$1.Point.convert(options.offset); + const paddingOffsetX = (options.padding.left - options.padding.right) / 2; + const paddingOffsetY = (options.padding.top - options.padding.bottom) / 2; + const paddingOffset = new performance$1.Point(paddingOffsetX, paddingOffsetY); + const rotatedPaddingOffset = paddingOffset.rotate(performance$1.degreesToRadians(bearing)); + const offsetAtInitialZoom = offset.add(rotatedPaddingOffset); + const offsetAtFinalZoom = offsetAtInitialZoom.mult(tr.scale / tr.zoomScale(zoom)); + const center = tr.unproject( + // either world diagonal can be used (NW-SE or NE-SW) + nwWorld.add(seWorld).div(2).sub(offsetAtFinalZoom)); + return { + center, + zoom, + bearing + }; + } + /** + * Pans and zooms the map to contain its visible area within the specified geographical bounds. + * This function will also reset the map's bearing to 0 if bearing is nonzero. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param bounds - Center these bounds in the viewport and use the highest + * zoom level up to and including `Map#getMaxZoom()` that fits them in the viewport. + * Bounds will be taken in [sw, ne] order. Southwest point will always be to the left of the northeast point. + * @param options - Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * let bbox = [[-79, 43], [-73, 45]]; + * map.fitBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + * @see [Fit a map to a bounding box](https://maplibre.org/maplibre-gl-js/docs/examples/fitbounds/) + */ + fitBounds(bounds, options, eventData) { + return this._fitInternal(this.cameraForBounds(bounds, options), options, eventData); + } + /** + * Pans, rotates and zooms the map to to fit the box made by points p0 and p1 + * once the map is rotated to the specified bearing. To zoom without rotating, + * pass in the current map bearing. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend` and `rotate`. + * + * @param p0 - First point on screen, in pixel coordinates + * @param p1 - Second point on screen, in pixel coordinates + * @param bearing - Desired map bearing at end of animation, in degrees + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * let p0 = [220, 400]; + * let p1 = [500, 900]; + * map.fitScreenCoordinates(p0, p1, map.getBearing(), { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + * @see Used by {@link BoxZoomHandler} + */ + fitScreenCoordinates(p0, p1, bearing, options, eventData) { + return this._fitInternal(this._cameraForBoxAndBearing(this.transform.pointLocation(performance$1.Point.convert(p0)), this.transform.pointLocation(performance$1.Point.convert(p1)), bearing, options), options, eventData); + } + _fitInternal(calculatedOptions, options, eventData) { + // cameraForBounds warns + returns undefined if unable to fit: + if (!calculatedOptions) + return this; + options = performance$1.extend(calculatedOptions, options); + // Explicitly remove the padding field because, calculatedOptions already accounts for padding by setting zoom and center accordingly. + delete options.padding; + return options.linear ? + this.easeTo(options, eventData) : + this.flyTo(options, eventData); + } + /** + * Changes any combination of center, zoom, bearing, and pitch, without + * an animated transition. The map will retain its current values for any + * details not specified in `options`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`, + * `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * // jump to coordinates at current zoom + * map.jumpTo({center: [0, 0]}); + * // jump with zoom, pitch, and bearing options + * map.jumpTo({ + * center: [0, 0], + * zoom: 8, + * pitch: 45, + * bearing: 90 + * }); + * ``` + * @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js/docs/examples/jump-to/) + * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/live-update-feature/) + */ + jumpTo(options, eventData) { + this.stop(); + const tr = this._getTransformForUpdate(); + let zoomChanged = false, bearingChanged = false, pitchChanged = false; + if ('zoom' in options && tr.zoom !== +options.zoom) { + zoomChanged = true; + tr.zoom = +options.zoom; + } + if (options.center !== undefined) { + tr.center = performance$1.LngLat.convert(options.center); + } + if ('bearing' in options && tr.bearing !== +options.bearing) { + bearingChanged = true; + tr.bearing = +options.bearing; + } + if ('pitch' in options && tr.pitch !== +options.pitch) { + pitchChanged = true; + tr.pitch = +options.pitch; + } + if (options.padding != null && !tr.isPaddingEqual(options.padding)) { + tr.padding = options.padding; + } + this._applyUpdatedTransform(tr); + this.fire(new performance$1.Event('movestart', eventData)) + .fire(new performance$1.Event('move', eventData)); + if (zoomChanged) { + this.fire(new performance$1.Event('zoomstart', eventData)) + .fire(new performance$1.Event('zoom', eventData)) + .fire(new performance$1.Event('zoomend', eventData)); + } + if (bearingChanged) { + this.fire(new performance$1.Event('rotatestart', eventData)) + .fire(new performance$1.Event('rotate', eventData)) + .fire(new performance$1.Event('rotateend', eventData)); + } + if (pitchChanged) { + this.fire(new performance$1.Event('pitchstart', eventData)) + .fire(new performance$1.Event('pitch', eventData)) + .fire(new performance$1.Event('pitchend', eventData)); + } + return this.fire(new performance$1.Event('moveend', eventData)); + } + /** + * Calculates pitch, zoom and bearing for looking at `newCenter` with the camera position being `newCenter` + * and returns them as {@link CameraOptions}. + * @param from - The camera to look from + * @param altitudeFrom - The altitude of the camera to look from + * @param to - The center to look at + * @param altitudeTo - Optional altitude of the center to look at. If none given the ground height will be used. + * @returns the calculated camera options + */ + calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo = 0) { + const fromMerc = performance$1.MercatorCoordinate.fromLngLat(from, altitudeFrom); + const toMerc = performance$1.MercatorCoordinate.fromLngLat(to, altitudeTo); + const dx = toMerc.x - fromMerc.x; + const dy = toMerc.y - fromMerc.y; + const dz = toMerc.z - fromMerc.z; + const distance3D = Math.hypot(dx, dy, dz); + if (distance3D === 0) + throw new Error('Can\'t calculate camera options with same From and To'); + const groundDistance = Math.hypot(dx, dy); + const zoom = this.transform.scaleZoom(this.transform.cameraToCenterDistance / distance3D / this.transform.tileSize); + const bearing = (Math.atan2(dx, -dy) * 180) / Math.PI; + let pitch = (Math.acos(groundDistance / distance3D) * 180) / Math.PI; + pitch = dz < 0 ? 90 - pitch : 90 + pitch; + return { + center: toMerc.toLngLat(), + zoom, + pitch, + bearing + }; + } + /** + * Changes any combination of `center`, `zoom`, `bearing`, `pitch`, and `padding` with an animated transition + * between old and new values. The map will retain its current values for any + * details not specified in `options`. + * + * Note: The transition will happen instantly if the user has enabled + * the `reduced motion` accessibility feature enabled in their operating system, + * unless `options` includes `essential: true`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`, + * `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options describing the destination and animation of the transition. + * Accepts {@link CameraOptions} and {@link AnimationOptions}. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/) + */ + easeTo(options, eventData) { + var _a; + this._stop(false, options.easeId); + options = performance$1.extend({ + offset: [0, 0], + duration: 500, + easing: performance$1.defaultEasing + }, options); + if (options.animate === false || (!options.essential && browser.prefersReducedMotion)) + options.duration = 0; + const tr = this._getTransformForUpdate(), startZoom = tr.zoom, startBearing = tr.bearing, startPitch = tr.pitch, startPadding = tr.padding, bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing, pitch = 'pitch' in options ? +options.pitch : startPitch, padding = 'padding' in options ? options.padding : tr.padding; + const offsetAsPoint = performance$1.Point.convert(options.offset); + let pointAtOffset = tr.centerPoint.add(offsetAsPoint); + const locationAtOffset = tr.pointLocation(pointAtOffset); + const { center, zoom } = tr.getConstrained(performance$1.LngLat.convert(options.center || locationAtOffset), (_a = options.zoom) !== null && _a !== void 0 ? _a : startZoom); + this._normalizeCenter(center, tr); + const from = tr.project(locationAtOffset); + const delta = tr.project(center).sub(from); + const finalScale = tr.zoomScale(zoom - startZoom); + let around, aroundPoint; + if (options.around) { + around = performance$1.LngLat.convert(options.around); + aroundPoint = tr.locationPoint(around); + } + const currently = { + moving: this._moving, + zooming: this._zooming, + rotating: this._rotating, + pitching: this._pitching + }; + this._zooming = this._zooming || (zoom !== startZoom); + this._rotating = this._rotating || (startBearing !== bearing); + this._pitching = this._pitching || (pitch !== startPitch); + this._padding = !tr.isPaddingEqual(padding); + this._easeId = options.easeId; + this._prepareEase(eventData, options.noMoveStart, currently); + if (this.terrain) + this._prepareElevation(center); + this._ease((k) => { + if (this._zooming) { + tr.zoom = performance$1.interpolate.number(startZoom, zoom, k); + } + if (this._rotating) { + tr.bearing = performance$1.interpolate.number(startBearing, bearing, k); + } + if (this._pitching) { + tr.pitch = performance$1.interpolate.number(startPitch, pitch, k); + } + if (this._padding) { + tr.interpolatePadding(startPadding, padding, k); + // When padding is being applied, Transform#centerPoint is changing continuously, + // thus we need to recalculate offsetPoint every frame + pointAtOffset = tr.centerPoint.add(offsetAsPoint); + } + if (this.terrain && !options.freezeElevation) + this._updateElevation(k); + if (around) { + tr.setLocationAtPoint(around, aroundPoint); + } + else { + const scale = tr.zoomScale(tr.zoom - startZoom); + const base = zoom > startZoom ? + Math.min(2, finalScale) : + Math.max(0.5, finalScale); + const speedup = Math.pow(base, 1 - k); + const newCenter = tr.unproject(from.add(delta.mult(k * speedup)).mult(scale)); + tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset); + } + this._applyUpdatedTransform(tr); + this._fireMoveEvents(eventData); + }, (interruptingEaseId) => { + if (this.terrain && options.freezeElevation) + this._finalizeElevation(); + this._afterEase(eventData, interruptingEaseId); + }, options); + return this; + } + _prepareEase(eventData, noMoveStart, currently = {}) { + this._moving = true; + if (!noMoveStart && !currently.moving) { + this.fire(new performance$1.Event('movestart', eventData)); + } + if (this._zooming && !currently.zooming) { + this.fire(new performance$1.Event('zoomstart', eventData)); + } + if (this._rotating && !currently.rotating) { + this.fire(new performance$1.Event('rotatestart', eventData)); + } + if (this._pitching && !currently.pitching) { + this.fire(new performance$1.Event('pitchstart', eventData)); + } + } + _prepareElevation(center) { + this._elevationCenter = center; + this._elevationStart = this.transform.elevation; + this._elevationTarget = this.terrain.getElevationForLngLatZoom(center, this.transform.tileZoom); + this._elevationFreeze = true; + } + _updateElevation(k) { + this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter, this.transform.tileZoom); + const elevation = this.terrain.getElevationForLngLatZoom(this._elevationCenter, this.transform.tileZoom); + // target terrain updated during flight, slowly move camera to new height + if (k < 1 && elevation !== this._elevationTarget) { + const pitch1 = this._elevationTarget - this._elevationStart; + const pitch2 = (elevation - (pitch1 * k + this._elevationStart)) / (1 - k); + this._elevationStart += k * (pitch1 - pitch2); + this._elevationTarget = elevation; + } + this.transform.elevation = performance$1.interpolate.number(this._elevationStart, this._elevationTarget, k); + } + _finalizeElevation() { + this._elevationFreeze = false; + this.transform.recalculateZoom(this.terrain); + } + /** + * @internal + * Called when the camera is about to be manipulated. + * If `transformCameraUpdate` is specified or terrain is enabled, a copy of + * the current transform is created to track the accumulated changes. + * This underlying transform represents the "desired state" proposed by input handlers / animations / UI controls. + * It may differ from the state used for rendering (`this.transform`). + * @returns Transform to apply changes to + */ + _getTransformForUpdate() { + if (!this.transformCameraUpdate && !this.terrain) + return this.transform; + if (!this._requestedCameraState) { + this._requestedCameraState = this.transform.clone(); + } + return this._requestedCameraState; + } + /** + * @internal + * Checks the given transform for the camera being below terrain surface and + * returns new pitch and zoom to fix that. + * + * With the new pitch and zoom, the camera will be at the same ground + * position but at higher altitude. It will still point to the same spot on + * the map. + * + * @param tr - The transform to check. + */ + _elevateCameraIfInsideTerrain(tr) { + const camera = tr.getCameraPosition(); + const minAltitude = this.terrain.getElevationForLngLatZoom(camera.lngLat, tr.zoom); + if (camera.altitude < minAltitude) { + const newCamera = this.calculateCameraOptionsFromTo(camera.lngLat, minAltitude, tr.center, tr.elevation); + return { + pitch: newCamera.pitch, + zoom: newCamera.zoom, + }; + } + return {}; + } + /** + * @internal + * Called after the camera is done being manipulated. + * @param tr - the requested camera end state + * If the camera is inside terrain, it gets elevated. + * Call `transformCameraUpdate` if present, and then apply the "approved" changes. + */ + _applyUpdatedTransform(tr) { + const modifiers = []; + if (this.terrain) { + modifiers.push(tr => this._elevateCameraIfInsideTerrain(tr)); + } + if (this.transformCameraUpdate) { + modifiers.push(tr => this.transformCameraUpdate(tr)); + } + if (!modifiers.length) { + return; + } + const finalTransform = tr.clone(); + for (const modifier of modifiers) { + const nextTransform = finalTransform.clone(); + const { center, zoom, pitch, bearing, elevation } = modifier(nextTransform); + if (center) + nextTransform.center = center; + if (zoom !== undefined) + nextTransform.zoom = zoom; + if (pitch !== undefined) + nextTransform.pitch = pitch; + if (bearing !== undefined) + nextTransform.bearing = bearing; + if (elevation !== undefined) + nextTransform.elevation = elevation; + finalTransform.apply(nextTransform); + } + this.transform.apply(finalTransform); + } + _fireMoveEvents(eventData) { + this.fire(new performance$1.Event('move', eventData)); + if (this._zooming) { + this.fire(new performance$1.Event('zoom', eventData)); + } + if (this._rotating) { + this.fire(new performance$1.Event('rotate', eventData)); + } + if (this._pitching) { + this.fire(new performance$1.Event('pitch', eventData)); + } + } + _afterEase(eventData, easeId) { + // if this easing is being stopped to start another easing with + // the same id then don't fire any events to avoid extra start/stop events + if (this._easeId && easeId && this._easeId === easeId) { + return; + } + delete this._easeId; + const wasZooming = this._zooming; + const wasRotating = this._rotating; + const wasPitching = this._pitching; + this._moving = false; + this._zooming = false; + this._rotating = false; + this._pitching = false; + this._padding = false; + if (wasZooming) { + this.fire(new performance$1.Event('zoomend', eventData)); + } + if (wasRotating) { + this.fire(new performance$1.Event('rotateend', eventData)); + } + if (wasPitching) { + this.fire(new performance$1.Event('pitchend', eventData)); + } + this.fire(new performance$1.Event('moveend', eventData)); + } + /** + * Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that + * evokes flight. The animation seamlessly incorporates zooming and panning to help + * the user maintain her bearings even after traversing a great distance. + * + * Note: The animation will be skipped, and this will behave equivalently to `jumpTo` + * if the user has the `reduced motion` accessibility feature enabled in their operating system, + * unless 'options' includes `essential: true`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`, + * `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options describing the destination and animation of the transition. + * Accepts {@link CameraOptions}, {@link AnimationOptions}, + * and the following additional options. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * // fly with default options to null island + * map.flyTo({center: [0, 0], zoom: 9}); + * // using flyTo options + * map.flyTo({ + * center: [0, 0], + * zoom: 9, + * speed: 0.2, + * curve: 1, + * easing(t) { + * return t; + * } + * }); + * ``` + * @see [Fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/flyto/) + * @see [Slowly fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/flyto-options/) + * @see [Fly to a location based on scroll position](https://maplibre.org/maplibre-gl-js/docs/examples/scroll-fly-to/) + */ + flyTo(options, eventData) { + var _a; + // Fall through to jumpTo if user has set prefers-reduced-motion + if (!options.essential && browser.prefersReducedMotion) { + const coercedOptions = performance$1.pick(options, ['center', 'zoom', 'bearing', 'pitch', 'around']); + return this.jumpTo(coercedOptions, eventData); + } + // This method implements an “optimal path” animation, as detailed in: + // + // Van Wijk, Jarke J.; Nuij, Wim A. A. “Smooth and efficient zooming and panning.” INFOVIS + // ’03. pp. 15–22. . + // + // Where applicable, local variable documentation begins with the associated variable or + // function in van Wijk (2003). + this.stop(); + options = performance$1.extend({ + offset: [0, 0], + speed: 1.2, + curve: 1.42, + easing: performance$1.defaultEasing + }, options); + const tr = this._getTransformForUpdate(), startZoom = tr.zoom, startBearing = tr.bearing, startPitch = tr.pitch, startPadding = tr.padding; + const bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing; + const pitch = 'pitch' in options ? +options.pitch : startPitch; + const padding = 'padding' in options ? options.padding : tr.padding; + const offsetAsPoint = performance$1.Point.convert(options.offset); + let pointAtOffset = tr.centerPoint.add(offsetAsPoint); + const locationAtOffset = tr.pointLocation(pointAtOffset); + const { center, zoom } = tr.getConstrained(performance$1.LngLat.convert(options.center || locationAtOffset), (_a = options.zoom) !== null && _a !== void 0 ? _a : startZoom); + this._normalizeCenter(center, tr); + const scale = tr.zoomScale(zoom - startZoom); + const from = tr.project(locationAtOffset); + const delta = tr.project(center).sub(from); + let rho = options.curve; + // w₀: Initial visible span, measured in pixels at the initial scale. + const w0 = Math.max(tr.width, tr.height), + // w₁: Final visible span, measured in pixels with respect to the initial scale. + w1 = w0 / scale, + // Length of the flight path as projected onto the ground plane, measured in pixels from + // the world image origin at the initial scale. + u1 = delta.mag(); + if ('minZoom' in options) { + const minZoom = performance$1.clamp(Math.min(options.minZoom, startZoom, zoom), tr.minZoom, tr.maxZoom); + // wm: Maximum visible span, measured in pixels with respect to the initial + // scale. + const wMax = w0 / tr.zoomScale(minZoom - startZoom); + rho = Math.sqrt(wMax / u1 * 2); + } + // ρ² + const rho2 = rho * rho; + /** + * rᵢ: Returns the zoom-out factor at one end of the animation. + * + * @param descent - `true` for the descent, `false` for the ascent + */ + function zoomOutFactor(descent) { + const b = (w1 * w1 - w0 * w0 + (descent ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (descent ? w1 : w0) * rho2 * u1); + return Math.log(Math.sqrt(b * b + 1) - b); + } + function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; } + function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; } + function tanh(n) { return sinh(n) / cosh(n); } + // r₀: Zoom-out factor during ascent. + const r0 = zoomOutFactor(false); + // w(s): Returns the visible span on the ground, measured in pixels with respect to the + // initial scale. Assumes an angular field of view of 2 arctan ½ ≈ 53°. + let w = function (s) { + return (cosh(r0) / cosh(r0 + rho * s)); + }; + // u(s): Returns the distance along the flight path as projected onto the ground plane, + // measured in pixels from the world image origin at the initial scale. + let u = function (s) { + return w0 * ((cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2) / u1; + }; + // S: Total length of the flight path, measured in ρ-screenfuls. + let S = (zoomOutFactor(true) - r0) / rho; + // When u₀ = u₁, the optimal path doesn’t require both ascent and descent. + if (Math.abs(u1) < 0.000001 || !isFinite(S)) { + // Perform a more or less instantaneous transition if the path is too short. + if (Math.abs(w0 - w1) < 0.000001) + return this.easeTo(options, eventData); + const k = w1 < w0 ? -1 : 1; + S = Math.abs(Math.log(w1 / w0)) / rho; + u = () => 0; + w = (s) => Math.exp(k * rho * s); + } + if ('duration' in options) { + options.duration = +options.duration; + } + else { + const V = 'screenSpeed' in options ? +options.screenSpeed / rho : +options.speed; + options.duration = 1000 * S / V; + } + if (options.maxDuration && options.duration > options.maxDuration) { + options.duration = 0; + } + this._zooming = true; + this._rotating = (startBearing !== bearing); + this._pitching = (pitch !== startPitch); + this._padding = !tr.isPaddingEqual(padding); + this._prepareEase(eventData, false); + if (this.terrain) + this._prepareElevation(center); + this._ease((k) => { + // s: The distance traveled along the flight path, measured in ρ-screenfuls. + const s = k * S; + const scale = 1 / w(s); + tr.zoom = k === 1 ? zoom : startZoom + tr.scaleZoom(scale); + if (this._rotating) { + tr.bearing = performance$1.interpolate.number(startBearing, bearing, k); + } + if (this._pitching) { + tr.pitch = performance$1.interpolate.number(startPitch, pitch, k); + } + if (this._padding) { + tr.interpolatePadding(startPadding, padding, k); + // When padding is being applied, Transform#centerPoint is changing continuously, + // thus we need to recalculate offsetPoint every frame + pointAtOffset = tr.centerPoint.add(offsetAsPoint); + } + if (this.terrain && !options.freezeElevation) + this._updateElevation(k); + const newCenter = k === 1 ? center : tr.unproject(from.add(delta.mult(u(s))).mult(scale)); + tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset); + this._applyUpdatedTransform(tr); + this._fireMoveEvents(eventData); + }, () => { + if (this.terrain && options.freezeElevation) + this._finalizeElevation(); + this._afterEase(eventData); + }, options); + return this; + } + isEasing() { + return !!this._easeFrameId; + } + /** + * Stops any animated transition underway. + */ + stop() { + return this._stop(); + } + _stop(allowGestures, easeId) { + var _a; + if (this._easeFrameId) { + this._cancelRenderFrame(this._easeFrameId); + delete this._easeFrameId; + delete this._onEaseFrame; + } + if (this._onEaseEnd) { + // The _onEaseEnd function might emit events which trigger new + // animation, which sets a new _onEaseEnd. Ensure we don't delete + // it unintentionally. + const onEaseEnd = this._onEaseEnd; + delete this._onEaseEnd; + onEaseEnd.call(this, easeId); + } + if (!allowGestures) { + (_a = this.handlers) === null || _a === void 0 ? void 0 : _a.stop(false); + } + return this; + } + _ease(frame, finish, options) { + if (options.animate === false || options.duration === 0) { + frame(1); + finish(); + } + else { + this._easeStart = browser.now(); + this._easeOptions = options; + this._onEaseFrame = frame; + this._onEaseEnd = finish; + this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback); + } + } + // convert bearing so that it's numerically close to the current one so that it interpolates properly + _normalizeBearing(bearing, currentBearing) { + bearing = performance$1.wrap(bearing, -180, 180); + const diff = Math.abs(bearing - currentBearing); + if (Math.abs(bearing - 360 - currentBearing) < diff) + bearing -= 360; + if (Math.abs(bearing + 360 - currentBearing) < diff) + bearing += 360; + return bearing; + } + // If a path crossing the antimeridian would be shorter, extend the final coordinate so that + // interpolating between the two endpoints will cross it. + _normalizeCenter(center, tr) { + if (!tr.renderWorldCopies || tr.lngRange) + return; + const delta = center.lng - tr.center.lng; + center.lng += + delta > 180 ? -360 : + delta < -180 ? 360 : 0; + } + /** + * Get the elevation difference between a given point + * and a point that is currently in the middle of the screen. + * This method should be used for proper positioning of custom 3d objects, as explained [here](https://maplibre.org/maplibre-gl-js/docs/examples/add-3d-model-with-terrain/) + * Returns null if terrain is not enabled. + * This method is subject to change in Maplibre GL JS v5. + * @param lngLatLike - [x,y] or LngLat coordinates of the location + * @returns elevation offset in meters + */ + queryTerrainElevation(lngLatLike) { + if (!this.terrain) { + return null; + } + const elevation = this.terrain.getElevationForLngLatZoom(performance$1.LngLat.convert(lngLatLike), this.transform.tileZoom); + return elevation - this.transform.elevation; + } +} + +const defaultAttributionControlOptions = { + compact: true, + customAttribution: 'MapLibre' +}; +/** + * An `AttributionControl` control presents the map's attribution information. By default, the attribution control is expanded (regardless of map width). + * @group Markers and Controls + * @example + * ```ts + * let map = new Map({attributionControl: false}) + * .addControl(new AttributionControl({ + * compact: true + * })); + * ``` + */ +class AttributionControl { + /** + * @param options - the attribution options + */ + constructor(options = defaultAttributionControlOptions) { + this._toggleAttribution = () => { + if (this._container.classList.contains('maplibregl-compact')) { + if (this._container.classList.contains('maplibregl-compact-show')) { + this._container.setAttribute('open', ''); + this._container.classList.remove('maplibregl-compact-show'); + } + else { + this._container.classList.add('maplibregl-compact-show'); + this._container.removeAttribute('open'); + } + } + }; + this._updateData = (e) => { + if (e && (e.sourceDataType === 'metadata' || e.sourceDataType === 'visibility' || e.dataType === 'style' || e.type === 'terrain')) { + this._updateAttributions(); + } + }; + this._updateCompact = () => { + if (this._map.getCanvasContainer().offsetWidth <= 640 || this._compact) { + if (this._compact === false) { + this._container.setAttribute('open', ''); + } + else if (!this._container.classList.contains('maplibregl-compact') && !this._container.classList.contains('maplibregl-attrib-empty')) { + this._container.setAttribute('open', ''); + this._container.classList.add('maplibregl-compact', 'maplibregl-compact-show'); + } + } + else { + this._container.setAttribute('open', ''); + if (this._container.classList.contains('maplibregl-compact')) { + this._container.classList.remove('maplibregl-compact', 'maplibregl-compact-show'); + } + } + }; + this._updateCompactMinimize = () => { + if (this._container.classList.contains('maplibregl-compact')) { + if (this._container.classList.contains('maplibregl-compact-show')) { + this._container.classList.remove('maplibregl-compact-show'); + } + } + }; + this.options = options; + } + getDefaultPosition() { + return 'bottom-right'; + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._compact = this.options.compact; + this._container = DOM.create('details', 'maplibregl-ctrl maplibregl-ctrl-attrib'); + this._compactButton = DOM.create('summary', 'maplibregl-ctrl-attrib-button', this._container); + this._compactButton.addEventListener('click', this._toggleAttribution); + this._setElementTitle(this._compactButton, 'ToggleAttribution'); + this._innerContainer = DOM.create('div', 'maplibregl-ctrl-attrib-inner', this._container); + this._updateAttributions(); + this._updateCompact(); + this._map.on('styledata', this._updateData); + this._map.on('sourcedata', this._updateData); + this._map.on('terrain', this._updateData); + this._map.on('resize', this._updateCompact); + this._map.on('drag', this._updateCompactMinimize); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + this._map.off('styledata', this._updateData); + this._map.off('sourcedata', this._updateData); + this._map.off('terrain', this._updateData); + this._map.off('resize', this._updateCompact); + this._map.off('drag', this._updateCompactMinimize); + this._map = undefined; + this._compact = undefined; + this._attribHTML = undefined; + } + _setElementTitle(element, title) { + const str = this._map._getUIString(`AttributionControl.${title}`); + element.title = str; + element.setAttribute('aria-label', str); + } + _updateAttributions() { + if (!this._map.style) + return; + let attributions = []; + if (this.options.customAttribution) { + if (Array.isArray(this.options.customAttribution)) { + attributions = attributions.concat(this.options.customAttribution.map(attribution => { + if (typeof attribution !== 'string') + return ''; + return attribution; + })); + } + else if (typeof this.options.customAttribution === 'string') { + attributions.push(this.options.customAttribution); + } + } + if (this._map.style.stylesheet) { + const stylesheet = this._map.style.stylesheet; + this.styleOwner = stylesheet.owner; + this.styleId = stylesheet.id; + } + const sourceCaches = this._map.style.sourceCaches; + for (const id in sourceCaches) { + const sourceCache = sourceCaches[id]; + if (sourceCache.used || sourceCache.usedForTerrain) { + const source = sourceCache.getSource(); + if (source.attribution && attributions.indexOf(source.attribution) < 0) { + attributions.push(source.attribution); + } + } + } + // remove any entries that are whitespace + attributions = attributions.filter(e => String(e).trim()); + // remove any entries that are substrings of another entry. + // first sort by length so that substrings come first + attributions.sort((a, b) => a.length - b.length); + attributions = attributions.filter((attrib, i) => { + for (let j = i + 1; j < attributions.length; j++) { + if (attributions[j].indexOf(attrib) >= 0) { + return false; + } + } + return true; + }); + // check if attribution string is different to minimize DOM changes + const attribHTML = attributions.join(' | '); + if (attribHTML === this._attribHTML) + return; + this._attribHTML = attribHTML; + if (attributions.length) { + this._innerContainer.innerHTML = attribHTML; + this._container.classList.remove('maplibregl-attrib-empty'); + } + else { + this._container.classList.add('maplibregl-attrib-empty'); + } + this._updateCompact(); + // remove old DOM node from _editLink + this._editLink = null; + } +} + +/** + * A `LogoControl` is a control that adds the watermark. + * + * @group Markers and Controls + * + * @example + * ```ts + * map.addControl(new LogoControl({compact: false})); + * ``` + **/ +class LogoControl { + /** + * @param options - the control's options + */ + constructor(options = {}) { + this._updateCompact = () => { + const containerChildren = this._container.children; + if (containerChildren.length) { + const anchor = containerChildren[0]; + if (this._map.getCanvasContainer().offsetWidth <= 640 || this._compact) { + if (this._compact !== false) { + anchor.classList.add('maplibregl-compact'); + } + } + else { + anchor.classList.remove('maplibregl-compact'); + } + } + }; + this.options = options; + } + getDefaultPosition() { + return 'bottom-left'; + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._compact = this.options && this.options.compact; + this._container = DOM.create('div', 'maplibregl-ctrl'); + const anchor = DOM.create('a', 'maplibregl-ctrl-logo'); + anchor.target = '_blank'; + anchor.rel = 'noopener nofollow'; + anchor.href = 'https://maplibre.org/'; + anchor.setAttribute('aria-label', this._map._getUIString('LogoControl.Title')); + anchor.setAttribute('rel', 'noopener nofollow'); + this._container.appendChild(anchor); + this._container.style.display = 'block'; + this._map.on('resize', this._updateCompact); + this._updateCompact(); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + this._map.off('resize', this._updateCompact); + this._map = undefined; + this._compact = undefined; + } +} + +class TaskQueue { + constructor() { + this._queue = []; + this._id = 0; + this._cleared = false; + this._currentlyRunning = false; + } + add(callback) { + const id = ++this._id; + const queue = this._queue; + queue.push({ callback, id, cancelled: false }); + return id; + } + remove(id) { + const running = this._currentlyRunning; + const queue = running ? this._queue.concat(running) : this._queue; + for (const task of queue) { + if (task.id === id) { + task.cancelled = true; + return; + } + } + } + run(timeStamp = 0) { + if (this._currentlyRunning) + throw new Error('Attempting to run(), but is already running.'); + const queue = this._currentlyRunning = this._queue; + // Tasks queued by callbacks in the current queue should be executed + // on the next run, not the current run. + this._queue = []; + for (const task of queue) { + if (task.cancelled) + continue; + task.callback(timeStamp); + if (this._cleared) + break; + } + this._cleared = false; + this._currentlyRunning = false; + } + clear() { + if (this._currentlyRunning) { + this._cleared = true; + } + this._queue = []; + } +} + +var pos3dAttributes = performance$1.createLayout([ + { name: 'a_pos3d', type: 'Int16', components: 3 } +]); + +/** + * @internal + * This class is a helper for the Terrain-class, it: + * + * - loads raster-dem tiles + * - manages all renderToTexture tiles. + * - caches previous rendered tiles. + * - finds all necessary renderToTexture tiles for a OverscaledTileID area + * - finds the corresponding raster-dem tile for OverscaledTileID + */ +class TerrainSourceCache extends performance$1.Evented { + constructor(sourceCache) { + super(); + this.sourceCache = sourceCache; + this._tiles = {}; + this._renderableTilesKeys = []; + this._sourceTileCache = {}; + this.minzoom = 0; + this.maxzoom = 22; + this.tileSize = 512; + this.deltaZoom = 1; + sourceCache.usedForTerrain = true; + sourceCache.tileSize = this.tileSize * 2 ** this.deltaZoom; + } + destruct() { + this.sourceCache.usedForTerrain = false; + this.sourceCache.tileSize = null; + } + /** + * Load Terrain Tiles, create internal render-to-texture tiles, free GPU memory. + * @param transform - the operation to do + * @param terrain - the terrain + */ + update(transform, terrain) { + // load raster-dem tiles for the current scene. + this.sourceCache.update(transform, terrain); + // create internal render-to-texture tiles for the current scene. + this._renderableTilesKeys = []; + const keys = {}; + for (const tileID of transform.coveringTiles({ + tileSize: this.tileSize, + minzoom: this.minzoom, + maxzoom: this.maxzoom, + reparseOverscaled: false, + terrain + })) { + keys[tileID.key] = true; + this._renderableTilesKeys.push(tileID.key); + if (!this._tiles[tileID.key]) { + tileID.posMatrix = new Float64Array(16); + performance$1.ortho(tileID.posMatrix, 0, performance$1.EXTENT, 0, performance$1.EXTENT, 0, 1); + this._tiles[tileID.key] = new Tile(tileID, this.tileSize); + } + } + // free unused tiles + for (const key in this._tiles) { + if (!keys[key]) + delete this._tiles[key]; + } + } + /** + * Free render to texture cache + * @param tileID - optional, free only corresponding to tileID. + */ + freeRtt(tileID) { + for (const key in this._tiles) { + const tile = this._tiles[key]; + if (!tileID || tile.tileID.equals(tileID) || tile.tileID.isChildOf(tileID) || tileID.isChildOf(tile.tileID)) + tile.rtt = []; + } + } + /** + * get a list of tiles, which are loaded and should be rendered in the current scene + * @returns the renderable tiles + */ + getRenderableTiles() { + return this._renderableTilesKeys.map(key => this.getTileByID(key)); + } + /** + * get terrain tile by the TileID key + * @param id - the tile id + * @returns the tile + */ + getTileByID(id) { + return this._tiles[id]; + } + /** + * Searches for the corresponding current renderable terrain-tiles + * @param tileID - the tile to look for + * @returns the tiles that were found + */ + getTerrainCoords(tileID) { + const coords = {}; + for (const key of this._renderableTilesKeys) { + const _tileID = this._tiles[key].tileID; + if (_tileID.canonical.equals(tileID.canonical)) { + const coord = tileID.clone(); + coord.posMatrix = new Float64Array(16); + performance$1.ortho(coord.posMatrix, 0, performance$1.EXTENT, 0, performance$1.EXTENT, 0, 1); + coords[key] = coord; + } + else if (_tileID.canonical.isChildOf(tileID.canonical)) { + const coord = tileID.clone(); + coord.posMatrix = new Float64Array(16); + const dz = _tileID.canonical.z - tileID.canonical.z; + const dx = _tileID.canonical.x - (_tileID.canonical.x >> dz << dz); + const dy = _tileID.canonical.y - (_tileID.canonical.y >> dz << dz); + const size = performance$1.EXTENT >> dz; + performance$1.ortho(coord.posMatrix, 0, size, 0, size, 0, 1); + performance$1.translate(coord.posMatrix, coord.posMatrix, [-dx * size, -dy * size, 0]); + coords[key] = coord; + } + else if (tileID.canonical.isChildOf(_tileID.canonical)) { + const coord = tileID.clone(); + coord.posMatrix = new Float64Array(16); + const dz = tileID.canonical.z - _tileID.canonical.z; + const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz); + const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz); + const size = performance$1.EXTENT >> dz; + performance$1.ortho(coord.posMatrix, 0, performance$1.EXTENT, 0, performance$1.EXTENT, 0, 1); + performance$1.translate(coord.posMatrix, coord.posMatrix, [dx * size, dy * size, 0]); + performance$1.scale(coord.posMatrix, coord.posMatrix, [1 / (2 ** dz), 1 / (2 ** dz), 0]); + coords[key] = coord; + } + } + return coords; + } + /** + * find the covering raster-dem tile + * @param tileID - the tile to look for + * @param searchForDEM - Optional parameter to search for (parent) sourcetiles with loaded dem. + * @returns the tile + */ + getSourceTile(tileID, searchForDEM) { + const source = this.sourceCache._source; + let z = tileID.overscaledZ - this.deltaZoom; + if (z > source.maxzoom) + z = source.maxzoom; + if (z < source.minzoom) + return null; + // cache for tileID to terrain-tileID + if (!this._sourceTileCache[tileID.key]) + this._sourceTileCache[tileID.key] = tileID.scaledTo(z).key; + let tile = this.sourceCache.getTileByID(this._sourceTileCache[tileID.key]); + // during tile-loading phase look if parent tiles (with loaded dem) are available. + if (!(tile && tile.dem) && searchForDEM) + while (z >= source.minzoom && !(tile && tile.dem)) + tile = this.sourceCache.getTileByID(tileID.scaledTo(z--).key); + return tile; + } + /** + * get a list of tiles, loaded after a specific time. This is used to update depth & coords framebuffers. + * @param time - the time + * @returns the relevant tiles + */ + tilesAfterTime(time = Date.now()) { + return Object.values(this._tiles).filter(t => t.timeAdded >= time); + } +} + +/** + * @internal + * This is the main class which handles most of the 3D Terrain logic. It has the following topics: + * + * 1. loads raster-dem tiles via the internal sourceCache this.sourceCache + * 2. creates a depth-framebuffer, which is used to calculate the visibility of coordinates + * 3. creates a coords-framebuffer, which is used the get to tile-coordinate for a screen-pixel + * 4. stores all render-to-texture tiles in the this.sourceCache._tiles + * 5. calculates the elevation for a specific tile-coordinate + * 6. creates a terrain-mesh + * + * A note about the GPU resource-usage: + * + * Framebuffers: + * + * - one for the depth & coords framebuffer with the size of the map-div. + * - one for rendering a tile to texture with the size of tileSize (= 512x512). + * + * Textures: + * + * - one texture for an empty raster-dem tile with size 1x1 + * - one texture for an empty depth-buffer, when terrain is disabled with size 1x1 + * - one texture for an each loaded raster-dem with size of the source.tileSize + * - one texture for the coords-framebuffer with the size of the map-div. + * - one texture for the depth-framebuffer with the size of the map-div. + * - one texture for the encoded tile-coords with the size 2*tileSize (=1024x1024) + * - finally for each render-to-texture tile (= this._tiles) a set of textures + * for each render stack (The stack-concept is documented in painter.ts). + * + * Normally there exists 1-3 Textures per tile, depending on the stylesheet. + * Each Textures has the size 2*tileSize (= 1024x1024). Also there exists a + * cache of the last 150 newest rendered tiles. + * + */ +class Terrain { + constructor(painter, sourceCache, options) { + this.painter = painter; + this.sourceCache = new TerrainSourceCache(sourceCache); + this.options = options; + this.exaggeration = typeof options.exaggeration === 'number' ? options.exaggeration : 1.0; + this.qualityFactor = 2; + this.meshSize = 128; + this._demMatrixCache = {}; + this.coordsIndex = []; + this._coordsTextureSize = 1024; + } + /** + * get the elevation-value from original dem-data for a given tile-coordinate + * @param tileID - the tile to get elevation for + * @param x - between 0 .. EXTENT + * @param y - between 0 .. EXTENT + * @param extent - optional, default 8192 + * @returns the elevation + */ + getDEMElevation(tileID, x, y, extent = performance$1.EXTENT) { + var _a; + if (!(x >= 0 && x < extent && y >= 0 && y < extent)) + return 0; + const terrain = this.getTerrainData(tileID); + const dem = (_a = terrain.tile) === null || _a === void 0 ? void 0 : _a.dem; + if (!dem) + return 0; + const pos = performance$1.transformMat4$1([], [x / extent * performance$1.EXTENT, y / extent * performance$1.EXTENT], terrain.u_terrain_matrix); + const coord = [pos[0] * dem.dim, pos[1] * dem.dim]; + // bilinear interpolation + const cx = Math.floor(coord[0]), cy = Math.floor(coord[1]), tx = coord[0] - cx, ty = coord[1] - cy; + return (dem.get(cx, cy) * (1 - tx) * (1 - ty) + + dem.get(cx + 1, cy) * (tx) * (1 - ty) + + dem.get(cx, cy + 1) * (1 - tx) * (ty) + + dem.get(cx + 1, cy + 1) * (tx) * (ty)); + } + /** + * Get the elevation for given {@link LngLat} in respect of exaggeration. + * @param lnglat - the location + * @param zoom - the zoom + * @returns the elevation + */ + getElevationForLngLatZoom(lnglat, zoom) { + if (!performance$1.isInBoundsForZoomLngLat(zoom, lnglat.wrap())) + return 0; + const { tileID, mercatorX, mercatorY } = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom); + return this.getElevation(tileID, mercatorX % performance$1.EXTENT, mercatorY % performance$1.EXTENT, performance$1.EXTENT); + } + /** + * Get the elevation for given coordinate in respect of exaggeration. + * @param tileID - the tile id + * @param x - between 0 .. EXTENT + * @param y - between 0 .. EXTENT + * @param extent - optional, default 8192 + * @returns the elevation + */ + getElevation(tileID, x, y, extent = performance$1.EXTENT) { + return this.getDEMElevation(tileID, x, y, extent) * this.exaggeration; + } + /** + * returns a Terrain Object for a tile. Unless the tile corresponds to data (e.g. tile is loading), return a flat dem object + * @param tileID - the tile to get the terrain for + * @returns the terrain data to use in the program + */ + getTerrainData(tileID) { + // create empty DEM Objects, which will used while raster-dem tiles are loading. + // creates an empty depth-buffer texture which is needed, during the initialization process of the 3d mesh.. + if (!this._emptyDemTexture) { + const context = this.painter.context; + const image = new performance$1.RGBAImage({ width: 1, height: 1 }, new Uint8Array(1 * 4)); + this._emptyDepthTexture = new Texture(context, image, context.gl.RGBA, { premultiply: false }); + this._emptyDemUnpack = [0, 0, 0, 0]; + this._emptyDemTexture = new Texture(context, new performance$1.RGBAImage({ width: 1, height: 1 }), context.gl.RGBA, { premultiply: false }); + this._emptyDemTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE); + this._emptyDemMatrix = performance$1.identity([]); + } + // find covering dem tile and prepare demTexture + const sourceTile = this.sourceCache.getSourceTile(tileID, true); + if (sourceTile && sourceTile.dem && (!sourceTile.demTexture || sourceTile.needsTerrainPrepare)) { + const context = this.painter.context; + sourceTile.demTexture = this.painter.getTileTexture(sourceTile.dem.stride); + if (sourceTile.demTexture) + sourceTile.demTexture.update(sourceTile.dem.getPixels(), { premultiply: false }); + else + sourceTile.demTexture = new Texture(context, sourceTile.dem.getPixels(), context.gl.RGBA, { premultiply: false }); + sourceTile.demTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE); + sourceTile.needsTerrainPrepare = false; + } + // create matrix for lookup in dem data + const matrixKey = sourceTile && (sourceTile + sourceTile.tileID.key) + tileID.key; + if (matrixKey && !this._demMatrixCache[matrixKey]) { + const maxzoom = this.sourceCache.sourceCache._source.maxzoom; + let dz = tileID.canonical.z - sourceTile.tileID.canonical.z; + if (tileID.overscaledZ > tileID.canonical.z) { + if (tileID.canonical.z >= maxzoom) + dz = tileID.canonical.z - maxzoom; + else + performance$1.warnOnce('cannot calculate elevation if elevation maxzoom > source.maxzoom'); + } + const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz); + const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz); + const demMatrix = performance$1.fromScaling(new Float64Array(16), [1 / (performance$1.EXTENT << dz), 1 / (performance$1.EXTENT << dz), 0]); + performance$1.translate(demMatrix, demMatrix, [dx * performance$1.EXTENT, dy * performance$1.EXTENT, 0]); + this._demMatrixCache[tileID.key] = { matrix: demMatrix, coord: tileID }; + } + // return uniform values & textures + return { + 'u_depth': 2, + 'u_terrain': 3, + 'u_terrain_dim': sourceTile && sourceTile.dem && sourceTile.dem.dim || 1, + 'u_terrain_matrix': matrixKey ? this._demMatrixCache[tileID.key].matrix : this._emptyDemMatrix, + 'u_terrain_unpack': sourceTile && sourceTile.dem && sourceTile.dem.getUnpackVector() || this._emptyDemUnpack, + 'u_terrain_exaggeration': this.exaggeration, + texture: (sourceTile && sourceTile.demTexture || this._emptyDemTexture).texture, + depthTexture: (this._fboDepthTexture || this._emptyDepthTexture).texture, + tile: sourceTile + }; + } + /** + * get a framebuffer as big as the map-div, which will be used to render depth & coords into a texture + * @param texture - the texture + * @returns the frame buffer + */ + getFramebuffer(texture) { + const painter = this.painter; + const width = painter.width / devicePixelRatio; + const height = painter.height / devicePixelRatio; + if (this._fbo && (this._fbo.width !== width || this._fbo.height !== height)) { + this._fbo.destroy(); + this._fboCoordsTexture.destroy(); + this._fboDepthTexture.destroy(); + delete this._fbo; + delete this._fboDepthTexture; + delete this._fboCoordsTexture; + } + if (!this._fboCoordsTexture) { + this._fboCoordsTexture = new Texture(painter.context, { width, height, data: null }, painter.context.gl.RGBA, { premultiply: false }); + this._fboCoordsTexture.bind(painter.context.gl.NEAREST, painter.context.gl.CLAMP_TO_EDGE); + } + if (!this._fboDepthTexture) { + this._fboDepthTexture = new Texture(painter.context, { width, height, data: null }, painter.context.gl.RGBA, { premultiply: false }); + this._fboDepthTexture.bind(painter.context.gl.NEAREST, painter.context.gl.CLAMP_TO_EDGE); + } + if (!this._fbo) { + this._fbo = painter.context.createFramebuffer(width, height, true, false); + this._fbo.depthAttachment.set(painter.context.createRenderbuffer(painter.context.gl.DEPTH_COMPONENT16, width, height)); + } + this._fbo.colorAttachment.set(texture === 'coords' ? this._fboCoordsTexture.texture : this._fboDepthTexture.texture); + return this._fbo; + } + /** + * create coords texture, needed to grab coordinates from canvas + * encode coords coordinate into 4 bytes: + * - 8 lower bits for x + * - 8 lower bits for y + * - 4 higher bits for x + * - 4 higher bits for y + * - 8 bits for coordsIndex (1 .. 255) (= number of terraintile), is later setted in draw_terrain uniform value + * @returns the texture + */ + getCoordsTexture() { + const context = this.painter.context; + if (this._coordsTexture) + return this._coordsTexture; + const data = new Uint8Array(this._coordsTextureSize * this._coordsTextureSize * 4); + for (let y = 0, i = 0; y < this._coordsTextureSize; y++) + for (let x = 0; x < this._coordsTextureSize; x++, i += 4) { + data[i + 0] = x & 255; + data[i + 1] = y & 255; + data[i + 2] = ((x >> 8) << 4) | (y >> 8); + data[i + 3] = 0; + } + const image = new performance$1.RGBAImage({ width: this._coordsTextureSize, height: this._coordsTextureSize }, new Uint8Array(data.buffer)); + const texture = new Texture(context, image, context.gl.RGBA, { premultiply: false }); + texture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE); + this._coordsTexture = texture; + return texture; + } + /** + * Reads a pixel from the coords-framebuffer and translate this to mercator. + * @param p - Screen-Coordinate + * @returns mercator coordinate for a screen pixel + */ + pointCoordinate(p) { + // First, ensure the coords framebuffer is up to date. + this.painter.maybeDrawDepthAndCoords(true); + const rgba = new Uint8Array(4); + const context = this.painter.context, gl = context.gl; + const px = Math.round(p.x * this.painter.pixelRatio / devicePixelRatio); + const py = Math.round(p.y * this.painter.pixelRatio / devicePixelRatio); + const fbHeight = Math.round(this.painter.height / devicePixelRatio); + // grab coordinate pixel from coordinates framebuffer + context.bindFramebuffer.set(this.getFramebuffer('coords').framebuffer); + gl.readPixels(px, fbHeight - py - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rgba); + context.bindFramebuffer.set(null); + // decode coordinates (encoding see getCoordsTexture) + const x = rgba[0] + ((rgba[2] >> 4) << 8); + const y = rgba[1] + ((rgba[2] & 15) << 8); + const tileID = this.coordsIndex[255 - rgba[3]]; + const tile = tileID && this.sourceCache.getTileByID(tileID); + if (!tile) + return null; + const coordsSize = this._coordsTextureSize; + const worldSize = (1 << tile.tileID.canonical.z) * coordsSize; + return new performance$1.MercatorCoordinate((tile.tileID.canonical.x * coordsSize + x) / worldSize + tile.tileID.wrap, (tile.tileID.canonical.y * coordsSize + y) / worldSize, this.getElevation(tile.tileID, x, y, coordsSize)); + } + /** + * Reads the depth value from the depth-framebuffer at a given screen pixel + * @param p - Screen coordinate + * @returns depth value in clip space (between 0 and 1) + */ + depthAtPoint(p) { + const rgba = new Uint8Array(4); + const context = this.painter.context, gl = context.gl; + context.bindFramebuffer.set(this.getFramebuffer('depth').framebuffer); + gl.readPixels(p.x, this.painter.height / devicePixelRatio - p.y - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rgba); + context.bindFramebuffer.set(null); + // decode coordinates (encoding see terran_depth.fragment.glsl) + const depthValue = (rgba[0] / (256 * 256 * 256) + rgba[1] / (256 * 256) + rgba[2] / 256 + rgba[3]) / 256; + return depthValue; + } + /** + * create a regular mesh which will be used by all terrain-tiles + * @returns the created regular mesh + */ + getTerrainMesh() { + if (this._mesh) + return this._mesh; + const context = this.painter.context; + const vertexArray = new performance$1.Pos3dArray(); + const indexArray = new performance$1.TriangleIndexArray(); + const meshSize = this.meshSize; + const delta = performance$1.EXTENT / meshSize; + const meshSize2 = meshSize * meshSize; + for (let y = 0; y <= meshSize; y++) + for (let x = 0; x <= meshSize; x++) + vertexArray.emplaceBack(x * delta, y * delta, 0); + for (let y = 0; y < meshSize2; y += meshSize + 1) + for (let x = 0; x < meshSize; x++) { + indexArray.emplaceBack(x + y, meshSize + x + y + 1, meshSize + x + y + 2); + indexArray.emplaceBack(x + y, meshSize + x + y + 2, x + y + 1); + } + // add an extra frame around the mesh to avoid stiching on tile boundaries with different zoomlevels + // first code-block is for top-bottom frame and second for left-right frame + const offsetTop = vertexArray.length, offsetBottom = offsetTop + (meshSize + 1) * 2; + for (const y of [0, 1]) + for (let x = 0; x <= meshSize; x++) + for (const z of [0, 1]) + vertexArray.emplaceBack(x * delta, y * performance$1.EXTENT, z); + for (let x = 0; x < meshSize * 2; x += 2) { + indexArray.emplaceBack(offsetBottom + x, offsetBottom + x + 1, offsetBottom + x + 3); + indexArray.emplaceBack(offsetBottom + x, offsetBottom + x + 3, offsetBottom + x + 2); + indexArray.emplaceBack(offsetTop + x, offsetTop + x + 3, offsetTop + x + 1); + indexArray.emplaceBack(offsetTop + x, offsetTop + x + 2, offsetTop + x + 3); + } + const offsetLeft = vertexArray.length, offsetRight = offsetLeft + (meshSize + 1) * 2; + for (const x of [0, 1]) + for (let y = 0; y <= meshSize; y++) + for (const z of [0, 1]) + vertexArray.emplaceBack(x * performance$1.EXTENT, y * delta, z); + for (let y = 0; y < meshSize * 2; y += 2) { + indexArray.emplaceBack(offsetLeft + y, offsetLeft + y + 1, offsetLeft + y + 3); + indexArray.emplaceBack(offsetLeft + y, offsetLeft + y + 3, offsetLeft + y + 2); + indexArray.emplaceBack(offsetRight + y, offsetRight + y + 3, offsetRight + y + 1); + indexArray.emplaceBack(offsetRight + y, offsetRight + y + 2, offsetRight + y + 3); + } + this._mesh = new Mesh(context.createVertexBuffer(vertexArray, pos3dAttributes.members), context.createIndexBuffer(indexArray), performance$1.SegmentVector.simpleSegment(0, 0, vertexArray.length, indexArray.length)); + return this._mesh; + } + /** + * Calculates a height of the frame around the terrain-mesh to avoid stiching between + * tile boundaries in different zoomlevels. + * @param zoom - current zoomlevel + * @returns the elevation delta in meters + */ + getMeshFrameDelta(zoom) { + // divide by 5 is evaluated by trial & error to get a frame in the right height + return 2 * Math.PI * performance$1.earthRadius / Math.pow(2, zoom) / 5; + } + getMinTileElevationForLngLatZoom(lnglat, zoom) { + var _a; + const { tileID } = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom); + return (_a = this.getMinMaxElevation(tileID).minElevation) !== null && _a !== void 0 ? _a : 0; + } + /** + * Get the minimum and maximum elevation contained in a tile. This includes any + * exaggeration included in the terrain. + * + * @param tileID - ID of the tile to be used as a source for the min/max elevation + * @returns the minimum and maximum elevation found in the tile, including the terrain's + * exaggeration + */ + getMinMaxElevation(tileID) { + const tile = this.getTerrainData(tileID).tile; + const minMax = { minElevation: null, maxElevation: null }; + if (tile && tile.dem) { + minMax.minElevation = tile.dem.min * this.exaggeration; + minMax.maxElevation = tile.dem.max * this.exaggeration; + } + return minMax; + } + _getOverscaledTileIDFromLngLatZoom(lnglat, zoom) { + const mercatorCoordinate = performance$1.MercatorCoordinate.fromLngLat(lnglat.wrap()); + const worldSize = (1 << zoom) * performance$1.EXTENT; + const mercatorX = mercatorCoordinate.x * worldSize; + const mercatorY = mercatorCoordinate.y * worldSize; + const tileX = Math.floor(mercatorX / performance$1.EXTENT), tileY = Math.floor(mercatorY / performance$1.EXTENT); + const tileID = new performance$1.OverscaledTileID(zoom, 0, zoom, tileX, tileY); + return { + tileID, + mercatorX, + mercatorY + }; + } +} + +/** + * @internal + * `RenderPool` is a resource pool for textures and framebuffers + */ +class RenderPool { + constructor(_context, _size, _tileSize) { + this._context = _context; + this._size = _size; + this._tileSize = _tileSize; + this._objects = []; + this._recentlyUsed = []; + this._stamp = 0; + } + destruct() { + for (const obj of this._objects) { + obj.texture.destroy(); + obj.fbo.destroy(); + } + } + _createObject(id) { + const fbo = this._context.createFramebuffer(this._tileSize, this._tileSize, true, true); + const texture = new Texture(this._context, { width: this._tileSize, height: this._tileSize, data: null }, this._context.gl.RGBA); + texture.bind(this._context.gl.LINEAR, this._context.gl.CLAMP_TO_EDGE); + fbo.depthAttachment.set(this._context.createRenderbuffer(this._context.gl.DEPTH_STENCIL, this._tileSize, this._tileSize)); + fbo.colorAttachment.set(texture.texture); + return { id, fbo, texture, stamp: -1, inUse: false }; + } + getObjectForId(id) { + return this._objects[id]; + } + useObject(obj) { + obj.inUse = true; + this._recentlyUsed = this._recentlyUsed.filter(id => obj.id !== id); + this._recentlyUsed.push(obj.id); + } + stampObject(obj) { + obj.stamp = ++this._stamp; + } + getOrCreateFreeObject() { + // check for free existing object + for (const id of this._recentlyUsed) { + if (!this._objects[id].inUse) + return this._objects[id]; + } + if (this._objects.length >= this._size) + throw new Error('No free RenderPool available, call freeAllObjects() required!'); + // create new object + const obj = this._createObject(this._objects.length); + this._objects.push(obj); + return obj; + } + freeObject(obj) { + obj.inUse = false; + } + freeAllObjects() { + for (const obj of this._objects) + this.freeObject(obj); + } + isFull() { + if (this._objects.length < this._size) { + return false; + } + return this._objects.some(o => !o.inUse) === false; + } +} + +/** + * lookup table which layers should rendered to texture + */ +const LAYERS = { + background: true, + fill: true, + line: true, + raster: true, + hillshade: true +}; +/** + * @internal + * A helper class to help define what should be rendered to texture and how + */ +class RenderToTexture { + constructor(painter, terrain) { + this.painter = painter; + this.terrain = terrain; + this.pool = new RenderPool(painter.context, 30, terrain.sourceCache.tileSize * terrain.qualityFactor); + } + destruct() { + this.pool.destruct(); + } + getTexture(tile) { + return this.pool.getObjectForId(tile.rtt[this._stacks.length - 1].id).texture; + } + prepareForRender(style, zoom) { + this._stacks = []; + this._prevType = null; + this._rttTiles = []; + this._renderableTiles = this.terrain.sourceCache.getRenderableTiles(); + this._renderableLayerIds = style._order.filter(id => !style._layers[id].isHidden(zoom)); + this._coordsDescendingInv = {}; + for (const id in style.sourceCaches) { + this._coordsDescendingInv[id] = {}; + const tileIDs = style.sourceCaches[id].getVisibleCoordinates(); + for (const tileID of tileIDs) { + const keys = this.terrain.sourceCache.getTerrainCoords(tileID); + for (const key in keys) { + if (!this._coordsDescendingInv[id][key]) + this._coordsDescendingInv[id][key] = []; + this._coordsDescendingInv[id][key].push(keys[key]); + } + } + } + this._coordsDescendingInvStr = {}; + for (const id of style._order) { + const layer = style._layers[id], source = layer.source; + if (LAYERS[layer.type]) { + if (!this._coordsDescendingInvStr[source]) { + this._coordsDescendingInvStr[source] = {}; + for (const key in this._coordsDescendingInv[source]) + this._coordsDescendingInvStr[source][key] = this._coordsDescendingInv[source][key].map(c => c.key).sort().join(); + } + } + } + // check tiles to render + for (const tile of this._renderableTiles) { + for (const source in this._coordsDescendingInvStr) { + // rerender if there are more coords to render than in the last rendering + const coords = this._coordsDescendingInvStr[source][tile.tileID.key]; + if (coords && coords !== tile.rttCoords[source]) + tile.rtt = []; + } + } + } + /** + * due that switching textures is relatively slow, the render + * layer-by-layer context is not practicable. To bypass this problem + * this lines of code stack all layers and later render all at once. + * Because of the stylesheet possibility to mixing render-to-texture layers + * and 'live'-layers (f.e. symbols) it is necessary to create more stacks. For example + * a symbol-layer is in between of fill-layers. + * @param layer - the layer to render + * @returns if true layer is rendered to texture, otherwise false + */ + renderLayer(layer) { + if (layer.isHidden(this.painter.transform.zoom)) + return false; + const type = layer.type; + const painter = this.painter; + const isLastLayer = this._renderableLayerIds[this._renderableLayerIds.length - 1] === layer.id; + // remember background, fill, line & raster layer to render into a stack + if (LAYERS[type]) { + // create a new stack if previous layer was not rendered to texture (f.e. symbols) + if (!this._prevType || !LAYERS[this._prevType]) + this._stacks.push([]); + // push current render-to-texture layer to render-stack + this._prevType = type; + this._stacks[this._stacks.length - 1].push(layer.id); + // rendering is done later, all in once + if (!isLastLayer) + return true; + } + // in case a stack is finished render all collected stack-layers into a texture + if (LAYERS[this._prevType] || (LAYERS[type] && isLastLayer)) { + this._prevType = type; + const stack = this._stacks.length - 1, layers = this._stacks[stack] || []; + for (const tile of this._renderableTiles) { + // if render pool is full draw current tiles to screen and free pool + if (this.pool.isFull()) { + drawTerrain(this.painter, this.terrain, this._rttTiles); + this._rttTiles = []; + this.pool.freeAllObjects(); + } + this._rttTiles.push(tile); + // check for cached PoolObject + if (tile.rtt[stack]) { + const obj = this.pool.getObjectForId(tile.rtt[stack].id); + if (obj.stamp === tile.rtt[stack].stamp) { + this.pool.useObject(obj); + continue; + } + } + // get free PoolObject + const obj = this.pool.getOrCreateFreeObject(); + this.pool.useObject(obj); + this.pool.stampObject(obj); + tile.rtt[stack] = { id: obj.id, stamp: obj.stamp }; + // prepare PoolObject for rendering + painter.context.bindFramebuffer.set(obj.fbo.framebuffer); + painter.context.clear({ color: performance$1.Color.transparent, stencil: 0 }); + painter.currentStencilSource = undefined; + for (let l = 0; l < layers.length; l++) { + const layer = painter.style._layers[layers[l]]; + const coords = layer.source ? this._coordsDescendingInv[layer.source][tile.tileID.key] : [tile.tileID]; + painter.context.viewport.set([0, 0, obj.fbo.width, obj.fbo.height]); + painter._renderTileClippingMasks(layer, coords); + painter.renderLayer(painter, painter.style.sourceCaches[layer.source], layer, coords); + if (layer.source) + tile.rttCoords[layer.source] = this._coordsDescendingInvStr[layer.source][tile.tileID.key]; + } + } + drawTerrain(this.painter, this.terrain, this._rttTiles); + this._rttTiles = []; + this.pool.freeAllObjects(); + return LAYERS[type]; + } + return false; + } +} + +const defaultLocale = { + 'AttributionControl.ToggleAttribution': 'Toggle attribution', + 'AttributionControl.MapFeedback': 'Map feedback', + 'FullscreenControl.Enter': 'Enter fullscreen', + 'FullscreenControl.Exit': 'Exit fullscreen', + 'GeolocateControl.FindMyLocation': 'Find my location', + 'GeolocateControl.LocationNotAvailable': 'Location not available', + 'LogoControl.Title': 'MapLibre logo', + 'Map.Title': 'Map', + 'Marker.Title': 'Map marker', + 'NavigationControl.ResetBearing': 'Reset bearing to north', + 'NavigationControl.ZoomIn': 'Zoom in', + 'NavigationControl.ZoomOut': 'Zoom out', + 'Popup.Close': 'Close popup', + 'ScaleControl.Feet': 'ft', + 'ScaleControl.Meters': 'm', + 'ScaleControl.Kilometers': 'km', + 'ScaleControl.Miles': 'mi', + 'ScaleControl.NauticalMiles': 'nm', + 'TerrainControl.Enable': 'Enable terrain', + 'TerrainControl.Disable': 'Disable terrain', + 'CooperativeGesturesHandler.WindowsHelpText': 'Use Ctrl + scroll to zoom the map', + 'CooperativeGesturesHandler.MacHelpText': 'Use ⌘ + scroll to zoom the map', + 'CooperativeGesturesHandler.MobileHelpText': 'Use two fingers to move the map', +}; + +const version$1 = packageJSON.version; +const defaultMinZoom = -2; +const defaultMaxZoom = 22; +// the default values, but also the valid range +const defaultMinPitch = 0; +const defaultMaxPitch = 60; +// use this variable to check maxPitch for validity +const maxPitchThreshold = 85; +const defaultOptions$4 = { + hash: false, + interactive: true, + bearingSnap: 7, + attributionControl: defaultAttributionControlOptions, + maplibreLogo: false, + failIfMajorPerformanceCaveat: false, + preserveDrawingBuffer: false, + refreshExpiredTiles: true, + scrollZoom: true, + minZoom: defaultMinZoom, + maxZoom: defaultMaxZoom, + minPitch: defaultMinPitch, + maxPitch: defaultMaxPitch, + boxZoom: true, + dragRotate: true, + dragPan: true, + keyboard: true, + doubleClickZoom: true, + touchZoomRotate: true, + touchPitch: true, + cooperativeGestures: false, + trackResize: true, + center: [0, 0], + zoom: 0, + bearing: 0, + pitch: 0, + renderWorldCopies: true, + maxTileCacheSize: null, + maxTileCacheZoomLevels: performance$1.config.MAX_TILE_CACHE_ZOOM_LEVELS, + transformRequest: null, + transformCameraUpdate: null, + fadeDuration: 300, + crossSourceCollisions: true, + clickTolerance: 3, + localIdeographFontFamily: 'sans-serif', + pitchWithRotate: true, + validateStyle: true, + /**Because GL MAX_TEXTURE_SIZE is usually at least 4096px. */ + maxCanvasSize: [4096, 4096], + cancelPendingTileRequestsWhileZooming: true +}; +/** + * The `Map` object represents the map on your page. It exposes methods + * and properties that enable you to programmatically change the map, + * and fires events as users interact with it. + * + * You create a `Map` by specifying a `container` and other options, see {@link MapOptions} for the full list. + * Then MapLibre GL JS initializes the map on the page and returns your `Map` object. + * + * @group Main + * + * @example + * ```ts + * let map = new Map({ + * container: 'map', + * center: [-122.420679, 37.772537], + * zoom: 13, + * style: style_object, + * hash: true, + * transformRequest: (url, resourceType)=> { + * if(resourceType === 'Source' && url.startsWith('http://myHost')) { + * return { + * url: url.replace('http', 'https'), + * headers: { 'my-custom-header': true}, + * credentials: 'include' // Include cookies for cross-origin requests + * } + * } + * } + * }); + * ``` + * @see [Display a map](https://maplibre.org/maplibre-gl-js/docs/examples/simple-map/) + */ +let Map$1 = class Map extends Camera { + constructor(options) { + performance$1.PerformanceUtils.mark(performance$1.PerformanceMarkers.create); + const resolvedOptions = Object.assign(Object.assign({}, defaultOptions$4), options); + if (resolvedOptions.minZoom != null && resolvedOptions.maxZoom != null && resolvedOptions.minZoom > resolvedOptions.maxZoom) { + throw new Error('maxZoom must be greater than or equal to minZoom'); + } + if (resolvedOptions.minPitch != null && resolvedOptions.maxPitch != null && resolvedOptions.minPitch > resolvedOptions.maxPitch) { + throw new Error('maxPitch must be greater than or equal to minPitch'); + } + if (resolvedOptions.minPitch != null && resolvedOptions.minPitch < defaultMinPitch) { + throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`); + } + if (resolvedOptions.maxPitch != null && resolvedOptions.maxPitch > maxPitchThreshold) { + throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`); + } + const transform = new Transform(resolvedOptions.minZoom, resolvedOptions.maxZoom, resolvedOptions.minPitch, resolvedOptions.maxPitch, resolvedOptions.renderWorldCopies); + super(transform, { bearingSnap: resolvedOptions.bearingSnap }); + this._idleTriggered = false; + this._crossFadingFactor = 1; + this._renderTaskQueue = new TaskQueue(); + this._controls = []; + this._mapId = performance$1.uniqueId(); + this._contextLost = (event) => { + event.preventDefault(); + if (this._frameRequest) { + this._frameRequest.abort(); + this._frameRequest = null; + } + this.fire(new performance$1.Event('webglcontextlost', { originalEvent: event })); + }; + this._contextRestored = (event) => { + this._setupPainter(); + this.resize(); + this._update(); + this.fire(new performance$1.Event('webglcontextrestored', { originalEvent: event })); + }; + this._onMapScroll = (event) => { + if (event.target !== this._container) + return; + // Revert any scroll which would move the canvas outside of the view + this._container.scrollTop = 0; + this._container.scrollLeft = 0; + return false; + }; + this._onWindowOnline = () => { + this._update(); + }; + this._interactive = resolvedOptions.interactive; + this._maxTileCacheSize = resolvedOptions.maxTileCacheSize; + this._maxTileCacheZoomLevels = resolvedOptions.maxTileCacheZoomLevels; + this._failIfMajorPerformanceCaveat = resolvedOptions.failIfMajorPerformanceCaveat === true; + this._preserveDrawingBuffer = resolvedOptions.preserveDrawingBuffer === true; + this._antialias = resolvedOptions.antialias === true; + this._trackResize = resolvedOptions.trackResize === true; + this._bearingSnap = resolvedOptions.bearingSnap; + this._refreshExpiredTiles = resolvedOptions.refreshExpiredTiles === true; + this._fadeDuration = resolvedOptions.fadeDuration; + this._crossSourceCollisions = resolvedOptions.crossSourceCollisions === true; + this._collectResourceTiming = resolvedOptions.collectResourceTiming === true; + this._locale = Object.assign(Object.assign({}, defaultLocale), resolvedOptions.locale); + this._clickTolerance = resolvedOptions.clickTolerance; + this._overridePixelRatio = resolvedOptions.pixelRatio; + this._maxCanvasSize = resolvedOptions.maxCanvasSize; + this.transformCameraUpdate = resolvedOptions.transformCameraUpdate; + this.cancelPendingTileRequestsWhileZooming = resolvedOptions.cancelPendingTileRequestsWhileZooming === true; + this._imageQueueHandle = ImageRequest.addThrottleControl(() => this.isMoving()); + this._requestManager = new RequestManager(resolvedOptions.transformRequest); + if (typeof resolvedOptions.container === 'string') { + this._container = document.getElementById(resolvedOptions.container); + if (!this._container) { + throw new Error(`Container '${resolvedOptions.container}' not found.`); + } + } + else if (resolvedOptions.container instanceof HTMLElement) { + this._container = resolvedOptions.container; + } + else { + throw new Error('Invalid type: \'container\' must be a String or HTMLElement.'); + } + if (resolvedOptions.maxBounds) { + this.setMaxBounds(resolvedOptions.maxBounds); + } + this._setupContainer(); + this._setupPainter(); + this.on('move', () => this._update(false)) + .on('moveend', () => this._update(false)) + .on('zoom', () => this._update(true)) + .on('terrain', () => { + this.painter.terrainFacilitator.dirty = true; + this._update(true); + }) + .once('idle', () => { this._idleTriggered = true; }); + if (typeof window !== 'undefined') { + addEventListener('online', this._onWindowOnline, false); + let initialResizeEventCaptured = false; + const throttledResizeCallback = throttle((entries) => { + if (this._trackResize && !this._removed) { + this.resize(entries); + this.redraw(); + } + }, 50); + this._resizeObserver = new ResizeObserver((entries) => { + if (!initialResizeEventCaptured) { + initialResizeEventCaptured = true; + return; + } + throttledResizeCallback(entries); + }); + this._resizeObserver.observe(this._container); + } + this.handlers = new HandlerManager(this, resolvedOptions); + const hashName = (typeof resolvedOptions.hash === 'string' && resolvedOptions.hash) || undefined; + this._hash = resolvedOptions.hash && (new Hash(hashName)).addTo(this); + // don't set position from options if set through hash + if (!this._hash || !this._hash._onHashChange()) { + this.jumpTo({ + center: resolvedOptions.center, + zoom: resolvedOptions.zoom, + bearing: resolvedOptions.bearing, + pitch: resolvedOptions.pitch + }); + if (resolvedOptions.bounds) { + this.resize(); + this.fitBounds(resolvedOptions.bounds, performance$1.extend({}, resolvedOptions.fitBoundsOptions, { duration: 0 })); + } + } + this.resize(); + this._localIdeographFontFamily = resolvedOptions.localIdeographFontFamily; + this._validateStyle = resolvedOptions.validateStyle; + if (resolvedOptions.style) + this.setStyle(resolvedOptions.style, { localIdeographFontFamily: resolvedOptions.localIdeographFontFamily }); + if (resolvedOptions.attributionControl) + this.addControl(new AttributionControl(typeof resolvedOptions.attributionControl === 'boolean' ? undefined : resolvedOptions.attributionControl)); + if (resolvedOptions.maplibreLogo) + this.addControl(new LogoControl(), resolvedOptions.logoPosition); + this.on('style.load', () => { + if (this.transform.unmodified) { + this.jumpTo(this.style.stylesheet); + } + }); + this.on('data', (event) => { + this._update(event.dataType === 'style'); + this.fire(new performance$1.Event(`${event.dataType}data`, event)); + }); + this.on('dataloading', (event) => { + this.fire(new performance$1.Event(`${event.dataType}dataloading`, event)); + }); + this.on('dataabort', (event) => { + this.fire(new performance$1.Event('sourcedataabort', event)); + }); + } + /** + * @internal + * Returns a unique number for this map instance which is used for the MapLoadEvent + * to make sure we only fire one event per instantiated map object. + * @returns the uniq map ID + */ + _getMapId() { + return this._mapId; + } + /** + * Adds an {@link IControl} to the map, calling `control.onAdd(this)`. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param control - The {@link IControl} to add. + * @param position - position on the map to which the control will be added. + * Valid values are `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. Defaults to `'top-right'`. + * @example + * Add zoom and rotation controls to the map. + * ```ts + * map.addControl(new NavigationControl()); + * ``` + * @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigation/) + */ + addControl(control, position) { + if (position === undefined) { + if (control.getDefaultPosition) { + position = control.getDefaultPosition(); + } + else { + position = 'top-right'; + } + } + if (!control || !control.onAdd) { + return this.fire(new performance$1.ErrorEvent(new Error('Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.'))); + } + const controlElement = control.onAdd(this); + this._controls.push(control); + const positionContainer = this._controlPositions[position]; + if (position.indexOf('bottom') !== -1) { + positionContainer.insertBefore(controlElement, positionContainer.firstChild); + } + else { + positionContainer.appendChild(controlElement); + } + return this; + } + /** + * Removes the control from the map. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param control - The {@link IControl} to remove. + * @example + * ```ts + * // Define a new navigation control. + * let navigation = new NavigationControl(); + * // Add zoom and rotation controls to the map. + * map.addControl(navigation); + * // Remove zoom and rotation controls from the map. + * map.removeControl(navigation); + * ``` + */ + removeControl(control) { + if (!control || !control.onRemove) { + return this.fire(new performance$1.ErrorEvent(new Error('Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.'))); + } + const ci = this._controls.indexOf(control); + if (ci > -1) + this._controls.splice(ci, 1); + control.onRemove(this); + return this; + } + /** + * Checks if a control exists on the map. + * + * @param control - The {@link IControl} to check. + * @returns true if map contains control. + * @example + * ```ts + * // Define a new navigation control. + * let navigation = new NavigationControl(); + * // Add zoom and rotation controls to the map. + * map.addControl(navigation); + * // Check that the navigation control exists on the map. + * map.hasControl(navigation); + * ``` + */ + hasControl(control) { + return this._controls.indexOf(control) > -1; + } + calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo) { + if (altitudeTo == null && this.terrain) { + altitudeTo = this.terrain.getElevationForLngLatZoom(to, this.transform.tileZoom); + } + return super.calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo); + } + /** + * Resizes the map according to the dimensions of its + * `container` element. + * + * Checks if the map container size changed and updates the map if it has changed. + * This method must be called after the map's `container` is resized programmatically + * or when the map is shown after being initially hidden with CSS. + * + * Triggers the following events: `movestart`, `move`, `moveend`, and `resize`. + * + * @param eventData - Additional properties to be passed to `movestart`, `move`, `resize`, and `moveend` + * events that get triggered as a result of resize. This can be useful for differentiating the + * source of an event (for example, user-initiated or programmatically-triggered events). + * @example + * Resize the map when the map container is shown after being initially hidden with CSS. + * ```ts + * let mapDiv = document.getElementById('map'); + * if (mapDiv.style.visibility === true) map.resize(); + * ``` + */ + resize(eventData) { + var _a; + const dimensions = this._containerDimensions(); + const width = dimensions[0]; + const height = dimensions[1]; + const clampedPixelRatio = this._getClampedPixelRatio(width, height); + this._resizeCanvas(width, height, clampedPixelRatio); + this.painter.resize(width, height, clampedPixelRatio); + // check if we've reached GL limits, in that case further clamps pixelRatio + if (this.painter.overLimit()) { + const gl = this.painter.context.gl; + // store updated _maxCanvasSize value + this._maxCanvasSize = [gl.drawingBufferWidth, gl.drawingBufferHeight]; + const clampedPixelRatio = this._getClampedPixelRatio(width, height); + this._resizeCanvas(width, height, clampedPixelRatio); + this.painter.resize(width, height, clampedPixelRatio); + } + this.transform.resize(width, height); + (_a = this._requestedCameraState) === null || _a === void 0 ? void 0 : _a.resize(width, height); + const fireMoving = !this._moving; + if (fireMoving) { + this.stop(); + this.fire(new performance$1.Event('movestart', eventData)) + .fire(new performance$1.Event('move', eventData)); + } + this.fire(new performance$1.Event('resize', eventData)); + if (fireMoving) + this.fire(new performance$1.Event('moveend', eventData)); + return this; + } + /** + * @internal + * Return the map's pixel ratio eventually scaled down to respect maxCanvasSize. + * Internally you should use this and not getPixelRatio(). + */ + _getClampedPixelRatio(width, height) { + const { 0: maxCanvasWidth, 1: maxCanvasHeight } = this._maxCanvasSize; + const pixelRatio = this.getPixelRatio(); + const canvasWidth = width * pixelRatio; + const canvasHeight = height * pixelRatio; + const widthScaleFactor = canvasWidth > maxCanvasWidth ? (maxCanvasWidth / canvasWidth) : 1; + const heightScaleFactor = canvasHeight > maxCanvasHeight ? (maxCanvasHeight / canvasHeight) : 1; + return Math.min(widthScaleFactor, heightScaleFactor) * pixelRatio; + } + /** + * Returns the map's pixel ratio. + * Note that the pixel ratio actually applied may be lower to respect maxCanvasSize. + * @returns The pixel ratio. + */ + getPixelRatio() { + var _a; + return (_a = this._overridePixelRatio) !== null && _a !== void 0 ? _a : devicePixelRatio; + } + /** + * Sets the map's pixel ratio. This allows to override `devicePixelRatio`. + * After this call, the canvas' `width` attribute will be `container.clientWidth * pixelRatio` + * and its height attribute will be `container.clientHeight * pixelRatio`. + * Set this to null to disable `devicePixelRatio` override. + * Note that the pixel ratio actually applied may be lower to respect maxCanvasSize. + * @param pixelRatio - The pixel ratio. + */ + setPixelRatio(pixelRatio) { + this._overridePixelRatio = pixelRatio; + this.resize(); + } + /** + * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not + * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region. + * @returns The geographical bounds of the map as {@link LngLatBounds}. + * @example + * ```ts + * let bounds = map.getBounds(); + * ``` + */ + getBounds() { + return this.transform.getBounds(); + } + /** + * Returns the maximum geographical bounds the map is constrained to, or `null` if none set. + * @returns The map object. + * @example + * ```ts + * let maxBounds = map.getMaxBounds(); + * ``` + */ + getMaxBounds() { + return this.transform.getMaxBounds(); + } + /** + * Sets or clears the map's geographical bounds. + * + * Pan and zoom operations are constrained within these bounds. + * If a pan or zoom is performed that would + * display regions outside these bounds, the map will + * instead display a position and zoom level + * as close as possible to the operation's request while still + * remaining within the bounds. + * + * @param bounds - The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds. + * @example + * Define bounds that conform to the `LngLatBoundsLike` object as set the max bounds. + * ```ts + * let bounds = [ + * [-74.04728, 40.68392], // [west, south] + * [-73.91058, 40.87764] // [east, north] + * ]; + * map.setMaxBounds(bounds); + * ``` + */ + setMaxBounds(bounds) { + this.transform.setMaxBounds(LngLatBounds.convert(bounds)); + return this._update(); + } + /** + * Sets or clears the map's minimum zoom level. + * If the map's current zoom level is lower than the new minimum, + * the map will zoom to the new minimum. + * + * It is not always possible to zoom out and reach the set `minZoom`. + * Other factors such as map height may restrict zooming. For example, + * if the map is 512px tall it will not be possible to zoom below zoom 0 + * no matter what the `minZoom` is set to. + * + * A {@link ErrorEvent} event will be fired if minZoom is out of bounds. + * + * @param minZoom - The minimum zoom level to set (-2 - 24). + * If `null` or `undefined` is provided, the function removes the current minimum zoom (i.e. sets it to -2). + * @example + * ```ts + * map.setMinZoom(12.25); + * ``` + */ + setMinZoom(minZoom) { + minZoom = minZoom === null || minZoom === undefined ? defaultMinZoom : minZoom; + if (minZoom >= defaultMinZoom && minZoom <= this.transform.maxZoom) { + this.transform.minZoom = minZoom; + this._update(); + if (this.getZoom() < minZoom) + this.setZoom(minZoom); + return this; + } + else + throw new Error(`minZoom must be between ${defaultMinZoom} and the current maxZoom, inclusive`); + } + /** + * Returns the map's minimum allowable zoom level. + * + * @returns minZoom + * @example + * ```ts + * let minZoom = map.getMinZoom(); + * ``` + */ + getMinZoom() { return this.transform.minZoom; } + /** + * Sets or clears the map's maximum zoom level. + * If the map's current zoom level is higher than the new maximum, + * the map will zoom to the new maximum. + * + * A {@link ErrorEvent} event will be fired if minZoom is out of bounds. + * + * @param maxZoom - The maximum zoom level to set. + * If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22). + * @example + * ```ts + * map.setMaxZoom(18.75); + * ``` + */ + setMaxZoom(maxZoom) { + maxZoom = maxZoom === null || maxZoom === undefined ? defaultMaxZoom : maxZoom; + if (maxZoom >= this.transform.minZoom) { + this.transform.maxZoom = maxZoom; + this._update(); + if (this.getZoom() > maxZoom) + this.setZoom(maxZoom); + return this; + } + else + throw new Error('maxZoom must be greater than the current minZoom'); + } + /** + * Returns the map's maximum allowable zoom level. + * + * @returns The maxZoom + * @example + * ```ts + * let maxZoom = map.getMaxZoom(); + * ``` + */ + getMaxZoom() { return this.transform.maxZoom; } + /** + * Sets or clears the map's minimum pitch. + * If the map's current pitch is lower than the new minimum, + * the map will pitch to the new minimum. + * + * A {@link ErrorEvent} event will be fired if minPitch is out of bounds. + * + * @param minPitch - The minimum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. + * If `null` or `undefined` is provided, the function removes the current minimum pitch (i.e. sets it to 0). + */ + setMinPitch(minPitch) { + minPitch = minPitch === null || minPitch === undefined ? defaultMinPitch : minPitch; + if (minPitch < defaultMinPitch) { + throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`); + } + if (minPitch >= defaultMinPitch && minPitch <= this.transform.maxPitch) { + this.transform.minPitch = minPitch; + this._update(); + if (this.getPitch() < minPitch) + this.setPitch(minPitch); + return this; + } + else + throw new Error(`minPitch must be between ${defaultMinPitch} and the current maxPitch, inclusive`); + } + /** + * Returns the map's minimum allowable pitch. + * + * @returns The minPitch + */ + getMinPitch() { return this.transform.minPitch; } + /** + * Sets or clears the map's maximum pitch. + * If the map's current pitch is higher than the new maximum, + * the map will pitch to the new maximum. + * + * A {@link ErrorEvent} event will be fired if maxPitch is out of bounds. + * + * @param maxPitch - The maximum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. + * If `null` or `undefined` is provided, the function removes the current maximum pitch (sets it to 60). + */ + setMaxPitch(maxPitch) { + maxPitch = maxPitch === null || maxPitch === undefined ? defaultMaxPitch : maxPitch; + if (maxPitch > maxPitchThreshold) { + throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`); + } + if (maxPitch >= this.transform.minPitch) { + this.transform.maxPitch = maxPitch; + this._update(); + if (this.getPitch() > maxPitch) + this.setPitch(maxPitch); + return this; + } + else + throw new Error('maxPitch must be greater than the current minPitch'); + } + /** + * Returns the map's maximum allowable pitch. + * + * @returns The maxPitch + */ + getMaxPitch() { return this.transform.maxPitch; } + /** + * 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`: + * + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * @returns The renderWorldCopies + * @example + * ```ts + * let worldCopiesRendered = map.getRenderWorldCopies(); + * ``` + * @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/) + */ + getRenderWorldCopies() { return this.transform.renderWorldCopies; } + /** + * Sets the state of `renderWorldCopies`. + * + * @param renderWorldCopies - If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`: + * + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * + * `undefined` is treated as `true`, `null` is treated as `false`. + * @example + * ```ts + * map.setRenderWorldCopies(true); + * ``` + * @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/) + */ + setRenderWorldCopies(renderWorldCopies) { + this.transform.renderWorldCopies = renderWorldCopies; + return this._update(); + } + /** + * Returns a [Point](https://github.com/mapbox/point-geometry) representing pixel coordinates, relative to the map's `container`, + * that correspond to the specified geographical location. + * + * @param lnglat - The geographical location to project. + * @returns The [Point](https://github.com/mapbox/point-geometry) corresponding to `lnglat`, relative to the map's `container`. + * @example + * ```ts + * let coordinate = [-122.420679, 37.772537]; + * let point = map.project(coordinate); + * ``` + */ + project(lnglat) { + return this.transform.locationPoint(performance$1.LngLat.convert(lnglat), this.style && this.terrain); + } + /** + * Returns a {@link LngLat} representing geographical coordinates that correspond + * to the specified pixel coordinates. + * + * @param point - The pixel coordinates to unproject. + * @returns The {@link LngLat} corresponding to `point`. + * @example + * ```ts + * map.on('click', (e) => { + * // When the map is clicked, get the geographic coordinate. + * let coordinate = map.unproject(e.point); + * }); + * ``` + */ + unproject(point) { + return this.transform.pointLocation(performance$1.Point.convert(point), this.terrain); + } + /** + * Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture. + * @returns true if the map is moving. + * @example + * ```ts + * let isMoving = map.isMoving(); + * ``` + */ + isMoving() { + var _a; + return this._moving || ((_a = this.handlers) === null || _a === void 0 ? void 0 : _a.isMoving()); + } + /** + * Returns true if the map is zooming due to a camera animation or user gesture. + * @returns true if the map is zooming. + * @example + * ```ts + * let isZooming = map.isZooming(); + * ``` + */ + isZooming() { + var _a; + return this._zooming || ((_a = this.handlers) === null || _a === void 0 ? void 0 : _a.isZooming()); + } + /** + * Returns true if the map is rotating due to a camera animation or user gesture. + * @returns true if the map is rotating. + * @example + * ```ts + * map.isRotating(); + * ``` + */ + isRotating() { + var _a; + return this._rotating || ((_a = this.handlers) === null || _a === void 0 ? void 0 : _a.isRotating()); + } + _createDelegatedListener(type, layerIds, listener) { + if (type === 'mouseenter' || type === 'mouseover') { + let mousein = false; + const mousemove = (e) => { + const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId)); + const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, { layers: existingLayers }) : []; + if (!features.length) { + mousein = false; + } + else if (!mousein) { + mousein = true; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent, { features })); + } + }; + const mouseout = () => { + mousein = false; + }; + return { layers: layerIds, listener, delegates: { mousemove, mouseout } }; + } + else if (type === 'mouseleave' || type === 'mouseout') { + let mousein = false; + const mousemove = (e) => { + const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId)); + const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, { layers: existingLayers }) : []; + if (features.length) { + mousein = true; + } + else if (mousein) { + mousein = false; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent)); + } + }; + const mouseout = (e) => { + if (mousein) { + mousein = false; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent)); + } + }; + return { layers: layerIds, listener, delegates: { mousemove, mouseout } }; + } + else { + const delegate = (e) => { + const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId)); + const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, { layers: existingLayers }) : []; + if (features.length) { + // Here we need to mutate the original event, so that preventDefault works as expected. + e.features = features; + listener.call(this, e); + delete e.features; + } + }; + return { layers: layerIds, listener, delegates: { [type]: delegate } }; + } + } + _saveDelegatedListener(type, delegatedListener) { + this._delegatedListeners = this._delegatedListeners || {}; + this._delegatedListeners[type] = this._delegatedListeners[type] || []; + this._delegatedListeners[type].push(delegatedListener); + } + _removeDelegatedListener(type, layerIds, listener) { + if (!this._delegatedListeners || !this._delegatedListeners[type]) { + return; + } + const listeners = this._delegatedListeners[type]; + for (let i = 0; i < listeners.length; i++) { + const delegatedListener = listeners[i]; + if (delegatedListener.listener === listener && + delegatedListener.layers.length === layerIds.length && + delegatedListener.layers.every((layerId) => layerIds.includes(layerId))) { + for (const event in delegatedListener.delegates) { + this.off(event, delegatedListener.delegates[event]); + } + listeners.splice(i, 1); + return; + } + } + } + on(type, layerIdsOrListener, listener) { + if (listener === undefined) { + return super.on(type, layerIdsOrListener); + } + const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener; + const delegatedListener = this._createDelegatedListener(type, layerIds, listener); + this._saveDelegatedListener(type, delegatedListener); + for (const event in delegatedListener.delegates) { + this.on(event, delegatedListener.delegates[event]); + } + return this; + } + once(type, layerIdsOrListener, listener) { + if (listener === undefined) { + return super.once(type, layerIdsOrListener); + } + const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener; + const delegatedListener = this._createDelegatedListener(type, layerIds, listener); + for (const key in delegatedListener.delegates) { + const delegate = delegatedListener.delegates[key]; + delegatedListener.delegates[key] = (...args) => { + this._removeDelegatedListener(type, layerIds, listener); + delegate(...args); + }; + } + this._saveDelegatedListener(type, delegatedListener); + for (const event in delegatedListener.delegates) { + this.once(event, delegatedListener.delegates[event]); + } + return this; + } + off(type, layerIdsOrListener, listener) { + if (listener === undefined) { + return super.off(type, layerIdsOrListener); + } + const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener; + this._removeDelegatedListener(type, layerIds, listener); + return this; + } + /** + * Returns an array of MapGeoJSONFeature objects + * representing visible features that satisfy the query parameters. + * + * @param geometryOrOptions - (optional) The geometry of the query region: + * either a single point or southwest and northeast points describing a bounding box. + * Omitting this parameter (i.e. calling {@link Map#queryRenderedFeatures} with zero arguments, + * or with only a `options` argument) is equivalent to passing a bounding box encompassing the entire + * map viewport. + * The geometryOrOptions can receive a {@link QueryRenderedFeaturesOptions} only to support a situation where the function receives only one parameter which is the options parameter. + * @param options - (optional) Options object. + * + * @returns An array of MapGeoJSONFeature objects. + * + * The `properties` value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only + * string and numeric property values are supported (i.e. `null`, `Array`, and `Object` values are not supported). + * + * Each feature includes top-level `layer`, `source`, and `sourceLayer` properties. The `layer` property is an object + * representing the style layer to which the feature belongs. Layout and paint properties in this object contain values + * which are fully evaluated for the given zoom level and feature. + * + * Only features that are currently rendered are included. Some features will **not** be included, like: + * + * - Features from layers whose `visibility` property is `"none"`. + * - Features from layers whose zoom range excludes the current zoom level. + * - Symbol features that have been hidden due to text or icon collision. + * + * Features from all other layers are included, including features that may have no visible + * contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to + * 0. + * + * The topmost rendered feature appears first in the returned array, and subsequent features are sorted by + * descending z-order. Features that are rendered multiple times (due to wrapping across the antemeridian at low + * zoom levels) are returned only once (though subject to the following caveat). + * + * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature + * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple + * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. + * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding + * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile + * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple + * tiles due to tile buffering. + * + * @example + * Find all features at a point + * ```ts + * let features = map.queryRenderedFeatures( + * [20, 35], + * { layers: ['my-layer-name'] } + * ); + * ``` + * + * @example + * Find all features within a static bounding box + * ```ts + * let features = map.queryRenderedFeatures( + * [[10, 20], [30, 50]], + * { layers: ['my-layer-name'] } + * ); + * ``` + * + * @example + * Find all features within a bounding box around a point + * ```ts + * let width = 10; + * let height = 20; + * let features = map.queryRenderedFeatures([ + * [point.x - width / 2, point.y - height / 2], + * [point.x + width / 2, point.y + height / 2] + * ], { layers: ['my-layer-name'] }); + * ``` + * + * @example + * Query all rendered features from a single layer + * ```ts + * let features = map.queryRenderedFeatures({ layers: ['my-layer-name'] }); + * ``` + * @see [Get features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/queryrenderedfeatures/) + */ + queryRenderedFeatures(geometryOrOptions, options) { + if (!this.style) { + return []; + } + let queryGeometry; + const isGeometry = geometryOrOptions instanceof performance$1.Point || Array.isArray(geometryOrOptions); + const geometry = isGeometry ? geometryOrOptions : [[0, 0], [this.transform.width, this.transform.height]]; + options = options || (isGeometry ? {} : geometryOrOptions) || {}; + if (geometry instanceof performance$1.Point || typeof geometry[0] === 'number') { + queryGeometry = [performance$1.Point.convert(geometry)]; + } + else { + const tl = performance$1.Point.convert(geometry[0]); + const br = performance$1.Point.convert(geometry[1]); + queryGeometry = [tl, new performance$1.Point(br.x, tl.y), br, new performance$1.Point(tl.x, br.y), tl]; + } + return this.style.queryRenderedFeatures(queryGeometry, options, this.transform); + } + /** + * Returns an array of MapGeoJSONFeature objects + * representing features within the specified vector tile or GeoJSON source that satisfy the query parameters. + * + * @param sourceId - The ID of the vector tile or GeoJSON source to query. + * @param parameters - The options object. + * @returns An array of MapGeoJSONFeature objects. + * + * In contrast to {@link Map#queryRenderedFeatures}, this function returns all features matching the query parameters, + * whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded + * vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently + * visible viewport. + * + * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature + * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple + * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. + * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding + * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile + * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple + * tiles due to tile buffering. + * + * @example + * Find all features in one source layer in a vector source + * ```ts + * let features = map.querySourceFeatures('your-source-id', { + * sourceLayer: 'your-source-layer' + * }); + * ``` + * + */ + querySourceFeatures(sourceId, parameters) { + return this.style.querySourceFeatures(sourceId, parameters); + } + /** + * Updates the map's MapLibre style object with a new value. + * + * 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 + * against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites + * (images used for icons and patterns) and glyphs (fonts for label text) **cannot** be diffed. If the sprites or fonts used in the current + * style and the given style are different in any way, the map renderer will force a full update, removing the current style and building + * the given one from scratch. + * + * + * @param style - A JSON object conforming to the schema described in the + * [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/), or a URL to such JSON. + * @param options - The options object. + * + * @example + * ```ts + * map.setStyle("https://demotiles.maplibre.org/style.json"); + * + * map.setStyle('https://demotiles.maplibre.org/style.json', { + * transformStyle: (previousStyle, nextStyle) => ({ + * ...nextStyle, + * sources: { + * ...nextStyle.sources, + * // copy a source from previous style + * 'osm': previousStyle.sources.osm + * }, + * layers: [ + * // background layer + * nextStyle.layers[0], + * // copy a layer from previous style + * previousStyle.layers[0], + * // other layers from the next style + * ...nextStyle.layers.slice(1).map(layer => { + * // hide the layers we don't need from demotiles style + * if (layer.id.startsWith('geolines')) { + * layer.layout = {...layer.layout || {}, visibility: 'none'}; + * // filter out US polygons + * } else if (layer.id.startsWith('coastline') || layer.id.startsWith('countries')) { + * layer.filter = ['!=', ['get', 'ADM0_A3'], 'USA']; + * } + * return layer; + * }) + * ] + * }) + * }); + * ``` + */ + setStyle(style, options) { + options = performance$1.extend({}, { + localIdeographFontFamily: this._localIdeographFontFamily, + validate: this._validateStyle + }, options); + if ((options.diff !== false && options.localIdeographFontFamily === this._localIdeographFontFamily) && this.style && style) { + this._diffStyle(style, options); + return this; + } + else { + this._localIdeographFontFamily = options.localIdeographFontFamily; + return this._updateStyle(style, options); + } + } + /** + * Updates the requestManager's transform request with a new function + * + * @param transformRequest - 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. + * Expected to return an object with a `url` property and optionally `headers` and `credentials` properties + * + * @example + * ```ts + * map.setTransformRequest((url: string, resourceType: string) => {}); + * ``` + */ + setTransformRequest(transformRequest) { + this._requestManager.setTransformRequest(transformRequest); + return this; + } + _getUIString(key) { + const str = this._locale[key]; + if (str == null) { + throw new Error(`Missing UI string '${key}'`); + } + return str; + } + _updateStyle(style, options) { + // transformStyle relies on having previous style serialized, if it is not loaded yet, delay _updateStyle until previous style is loaded + if (options.transformStyle && this.style && !this.style._loaded) { + this.style.once('style.load', () => this._updateStyle(style, options)); + return; + } + const previousStyle = this.style && options.transformStyle ? this.style.serialize() : undefined; + if (this.style) { + this.style.setEventedParent(null); + // Only release workers when map is getting disposed + this.style._remove(!style); + } + if (!style) { + delete this.style; + return this; + } + else { + this.style = new Style(this, options || {}); + } + this.style.setEventedParent(this, { style: this.style }); + if (typeof style === 'string') { + this.style.loadURL(style, options, previousStyle); + } + else { + this.style.loadJSON(style, options, previousStyle); + } + return this; + } + _lazyInitEmptyStyle() { + if (!this.style) { + this.style = new Style(this, {}); + this.style.setEventedParent(this, { style: this.style }); + this.style.loadEmpty(); + } + } + _diffStyle(style, options) { + if (typeof style === 'string') { + const url = style; + const request = this._requestManager.transformRequest(url, "Style" /* ResourceType.Style */); + performance$1.getJSON(request, new AbortController()).then((response) => { + this._updateDiff(response.data, options); + }).catch((error) => { + if (error) { + this.fire(new performance$1.ErrorEvent(error)); + } + }); + } + else if (typeof style === 'object') { + this._updateDiff(style, options); + } + } + _updateDiff(style, options) { + try { + if (this.style.setState(style, options)) { + this._update(true); + } + } + catch (e) { + performance$1.warnOnce(`Unable to perform style diff: ${e.message || e.error || e}. Rebuilding the style from scratch.`); + this._updateStyle(style, options); + } + } + /** + * Returns the map's MapLibre style object, a JSON object which can be used to recreate the map's style. + * + * @returns The map's style JSON object. + * + * @example + * ```ts + * let styleJson = map.getStyle(); + * ``` + * + */ + getStyle() { + if (this.style) { + return this.style.serialize(); + } + } + /** + * Returns a Boolean indicating whether the map's style is fully loaded. + * + * @returns A Boolean indicating whether the style is fully loaded. + * + * @example + * ```ts + * let styleLoadStatus = map.isStyleLoaded(); + * ``` + */ + isStyleLoaded() { + if (!this.style) + return performance$1.warnOnce('There is no style added to the map.'); + return this.style.loaded(); + } + /** + * Adds a source to the map's style. + * + * Events triggered: + * + * Triggers the `source.add` event. + * + * @param id - The ID of the source to add. Must not conflict with existing sources. + * @param source - The source object, conforming to the + * MapLibre Style Specification's [source definition](https://maplibre.org/maplibre-style-spec/sources) or + * {@link CanvasSourceSpecification}. + * @example + * ```ts + * map.addSource('my-data', { + * type: 'vector', + * url: 'https://demotiles.maplibre.org/tiles/tiles.json' + * }); + * ``` + * @example + * ```ts + * map.addSource('my-data', { + * "type": "geojson", + * "data": { + * "type": "Feature", + * "geometry": { + * "type": "Point", + * "coordinates": [-77.0323, 38.9131] + * }, + * "properties": { + * "title": "Mapbox DC", + * "marker-symbol": "monument" + * } + * } + * }); + * ``` + * @see GeoJSON source: [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/live-geojson/) + */ + addSource(id, source) { + this._lazyInitEmptyStyle(); + this.style.addSource(id, source); + return this._update(true); + } + /** + * Returns a Boolean indicating whether the source is loaded. Returns `true` if the source with + * the given ID in the map's style has no outstanding network requests, otherwise `false`. + * + * A {@link ErrorEvent} event will be fired if there is no source wit the specified ID. + * + * @param id - The ID of the source to be checked. + * @returns A Boolean indicating whether the source is loaded. + * @example + * ```ts + * let sourceLoaded = map.isSourceLoaded('bathymetry-data'); + * ``` + */ + isSourceLoaded(id) { + const source = this.style && this.style.sourceCaches[id]; + if (source === undefined) { + this.fire(new performance$1.ErrorEvent(new Error(`There is no source with ID '${id}'`))); + return; + } + return source.loaded(); + } + /** + * Loads a 3D terrain mesh, based on a "raster-dem" source. + * + * Triggers the `terrain` event. + * + * @param options - Options object. + * @example + * ```ts + * map.setTerrain({ source: 'terrain' }); + * ``` + */ + setTerrain(options) { + this.style._checkLoaded(); + // clear event handlers + if (this._terrainDataCallback) + this.style.off('data', this._terrainDataCallback); + if (!options) { + // remove terrain + if (this.terrain) + this.terrain.sourceCache.destruct(); + this.terrain = null; + if (this.painter.renderToTexture) + this.painter.renderToTexture.destruct(); + this.painter.renderToTexture = null; + this.transform.minElevationForCurrentTile = 0; + this.transform.elevation = 0; + } + else { + // add terrain + const sourceCache = this.style.sourceCaches[options.source]; + if (!sourceCache) + throw new Error(`cannot load terrain, because there exists no source with ID: ${options.source}`); + // Update terrain tiles when adding new terrain + if (this.terrain === null) + sourceCache.reload(); + // Warn once if user is using the same source for hillshade and terrain + for (const index in this.style._layers) { + const thisLayer = this.style._layers[index]; + if (thisLayer.type === 'hillshade' && thisLayer.source === options.source) { + performance$1.warnOnce('You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.'); + } + } + this.terrain = new Terrain(this.painter, sourceCache, options); + this.painter.renderToTexture = new RenderToTexture(this.painter, this.terrain); + this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + this._terrainDataCallback = e => { + if (e.dataType === 'style') { + this.terrain.sourceCache.freeRtt(); + } + else if (e.dataType === 'source' && e.tile) { + if (e.sourceId === options.source && !this._elevationFreeze) { + this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + } + this.terrain.sourceCache.freeRtt(e.tile.tileID); + } + }; + this.style.on('data', this._terrainDataCallback); + } + this.fire(new performance$1.Event('terrain', { terrain: options })); + return this; + } + /** + * Get the terrain-options if terrain is loaded + * @returns the TerrainSpecification passed to setTerrain + * @example + * ```ts + * map.getTerrain(); // { source: 'terrain' }; + * ``` + */ + getTerrain() { + var _a, _b; + return (_b = (_a = this.terrain) === null || _a === void 0 ? void 0 : _a.options) !== null && _b !== void 0 ? _b : null; + } + /** + * Returns a Boolean indicating whether all tiles in the viewport from all sources on + * the style are loaded. + * + * @returns A Boolean indicating whether all tiles are loaded. + * @example + * ```ts + * let tilesLoaded = map.areTilesLoaded(); + * ``` + */ + areTilesLoaded() { + const sources = this.style && this.style.sourceCaches; + for (const id in sources) { + const source = sources[id]; + const tiles = source._tiles; + for (const t in tiles) { + const tile = tiles[t]; + if (!(tile.state === 'loaded' || tile.state === 'errored')) + return false; + } + } + return true; + } + /** + * Removes a source from the map's style. + * + * @param id - The ID of the source to remove. + * @example + * ```ts + * map.removeSource('bathymetry-data'); + * ``` + */ + removeSource(id) { + this.style.removeSource(id); + return this._update(true); + } + /** + * Returns the source with the specified ID in the map's style. + * + * This method is often used to update a source using the instance members for the relevant + * source type as defined in classes that derive from {@link Source}. + * For example, setting the `data` for a GeoJSON source or updating the `url` and `coordinates` + * of an image source. + * + * @param id - The ID of the source to get. + * @returns The style source with the specified ID or `undefined` if the ID + * corresponds to no existing sources. + * The shape of the object varies by source type. + * A list of options for each source type is available on the MapLibre Style Specification's + * [Sources](https://maplibre.org/maplibre-style-spec/sources/) page. + * @example + * ```ts + * let sourceObject = map.getSource('points'); + * ``` + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + * @see [Animate a point](https://maplibre.org/maplibre-gl-js/docs/examples/animate-point-along-line/) + * @see [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/live-geojson/) + */ + getSource(id) { + return this.style.getSource(id); + } + /** + * Add an image to the style. This image can be displayed on the map like any other icon in the style's + * sprite using the image's ID with + * [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image), + * [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern), + * [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern), + * or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern). + * + * A {@link ErrorEvent} event will be fired if the image parameter is invalid or there is not enough space in the sprite to add this image. + * + * @param id - The ID of the image. + * @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data` + * properties with the same format as `ImageData`. + * @param options - Options object. + * @example + * ```ts + * // If the style's sprite does not already contain an image with ID 'cat', + * // add the image 'cat-icon.png' to the style's sprite with the ID 'cat'. + * const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png'); + * if (!map.hasImage('cat')) map.addImage('cat', image.data); + * + * // Add a stretchable image that can be used with `icon-text-fit` + * // In this example, the image is 600px wide by 400px high. + * const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png'); + * if (map.hasImage('border-image')) return; + * map.addImage('border-image', image.data, { + * content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border + * stretchX: [[16, 584]], // stretch everything horizontally except the 16px border + * stretchY: [[16, 384]], // stretch everything vertically except the 16px border + * }); + * ``` + * @see Use `HTMLImageElement`: [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image/) + * @see Use `ImageData`: [Add a generated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-generated/) + */ + addImage(id, image, options = {}) { + const { pixelRatio = 1, sdf = false, stretchX, stretchY, content, textFitWidth, textFitHeight } = options; + this._lazyInitEmptyStyle(); + const version = 0; + if (image instanceof HTMLImageElement || performance$1.isImageBitmap(image)) { + const { width, height, data } = browser.getImageData(image); + this.style.addImage(id, { data: new performance$1.RGBAImage({ width, height }, data), pixelRatio, stretchX, stretchY, content, textFitWidth, textFitHeight, sdf, version }); + } + else if (image.width === undefined || image.height === undefined) { + return this.fire(new performance$1.ErrorEvent(new Error('Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' + + 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`'))); + } + else { + const { width, height, data } = image; + const userImage = image; + this.style.addImage(id, { + data: new performance$1.RGBAImage({ width, height }, new Uint8Array(data)), + pixelRatio, + stretchX, + stretchY, + content, + textFitWidth, + textFitHeight, + sdf, + version, + userImage + }); + if (userImage.onAdd) { + userImage.onAdd(this, id); + } + return this; + } + } + /** + * Update an existing image in a style. This image can be displayed on the map like any other icon in the style's + * sprite using the image's ID with + * [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image), + * [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern), + * [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern), + * or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern). + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param id - The ID of the image. + * @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data` + * properties with the same format as `ImageData`. + * @example + * ```ts + * // If an image with the ID 'cat' already exists in the style's sprite, + * // replace that image with a new image, 'other-cat-icon.png'. + * if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png'); + * ``` + */ + updateImage(id, image) { + const existingImage = this.style.getImage(id); + if (!existingImage) { + return this.fire(new performance$1.ErrorEvent(new Error('The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.'))); + } + const imageData = (image instanceof HTMLImageElement || performance$1.isImageBitmap(image)) ? + browser.getImageData(image) : + image; + const { width, height, data } = imageData; + if (width === undefined || height === undefined) { + return this.fire(new performance$1.ErrorEvent(new Error('Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' + + 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`'))); + } + if (width !== existingImage.data.width || height !== existingImage.data.height) { + return this.fire(new performance$1.ErrorEvent(new Error('The width and height of the updated image must be that same as the previous version of the image'))); + } + const copy = !(image instanceof HTMLImageElement || performance$1.isImageBitmap(image)); + existingImage.data.replace(data, copy); + this.style.updateImage(id, existingImage); + return this; + } + /** + * Returns an image, specified by ID, currently available in the map. + * This includes both images from the style's original sprite + * and any images that have been added at runtime using {@link Map#addImage}. + * + * @param id - The ID of the image. + * @returns An image in the map with the specified ID. + * + * @example + * ```ts + * let coffeeShopIcon = map.getImage("coffee_cup"); + * ``` + */ + getImage(id) { + return this.style.getImage(id); + } + /** + * Check whether or not an image with a specific ID exists in the style. This checks both images + * in the style's original sprite and any images + * that have been added at runtime using {@link Map#addImage}. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param id - The ID of the image. + * + * @returns A Boolean indicating whether the image exists. + * @example + * Check if an image with the ID 'cat' exists in the style's sprite. + * ```ts + * let catIconExists = map.hasImage('cat'); + * ``` + */ + hasImage(id) { + if (!id) { + this.fire(new performance$1.ErrorEvent(new Error('Missing required image id'))); + return false; + } + return !!this.style.getImage(id); + } + /** + * Remove an image from a style. This can be an image from the style's original + * sprite or any images + * that have been added at runtime using {@link Map#addImage}. + * + * @param id - The ID of the image. + * + * @example + * ```ts + * // If an image with the ID 'cat' exists in + * // the style's sprite, remove it. + * if (map.hasImage('cat')) map.removeImage('cat'); + * ``` + */ + removeImage(id) { + this.style.removeImage(id); + } + /** + * Load an image from an external URL to be used with {@link Map#addImage}. External + * domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS). + * + * @param url - The URL of the image file. Image file must be in png, webp, or jpg format. + * @returns a promise that is resolved when the image is loaded + * + * @example + * Load an image from an external URL. + * ```ts + * const response = await map.loadImage('https://picsum.photos/50/50'); + * // Add the loaded image to the style's sprite with the ID 'photo'. + * map.addImage('photo', response.data); + * ``` + * @see [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image/) + */ + loadImage(url) { + return ImageRequest.getImage(this._requestManager.transformRequest(url, "Image" /* ResourceType.Image */), new AbortController()); + } + /** + * Returns an Array of strings containing the IDs of all images currently available in the map. + * This includes both images from the style's original sprite + * and any images that have been added at runtime using {@link Map#addImage}. + * + * @returns An Array of strings containing the names of all sprites/images currently available in the map. + * + * @example + * ```ts + * let allImages = map.listImages(); + * ``` + */ + listImages() { + return this.style.listImages(); + } + /** + * Adds a [MapLibre style layer](https://maplibre.org/maplibre-style-spec/layers) + * to the map's style. + * + * A layer defines how data from a specified source will be styled. Read more about layer types + * and available paint and layout properties in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/layers). + * + * @param layer - The layer to add, + * conforming to either the MapLibre Style Specification's [layer definition](https://maplibre.org/maplibre-style-spec/layers) or, + * less commonly, the {@link CustomLayerInterface} specification. Can also be a layer definition with an embedded source definition. + * The MapLibre Style Specification's layer definition is appropriate for most layers. + * + * @param beforeId - The ID of an existing layer to insert the new layer before, + * resulting in the new layer appearing visually beneath the existing layer. + * If this argument is not specified, the layer will be appended to the end of the layers array + * and appear visually above all other layers. + * + * @example + * Add a circle layer with a vector source + * ```ts + * map.addLayer({ + * id: 'points-of-interest', + * source: { + * type: 'vector', + * url: 'https://demotiles.maplibre.org/tiles/tiles.json' + * }, + * 'source-layer': 'poi_label', + * type: 'circle', + * paint: { + * // MapLibre Style Specification paint properties + * }, + * layout: { + * // MapLibre Style Specification layout properties + * } + * }); + * ``` + * + * @example + * Define a source before using it to create a new layer + * ```ts + * map.addSource('state-data', { + * type: 'geojson', + * data: 'path/to/data.geojson' + * }); + * + * map.addLayer({ + * id: 'states', + * // References the GeoJSON source defined above + * // and does not require a `source-layer` + * source: 'state-data', + * type: 'symbol', + * layout: { + * // Set the label content to the + * // feature's `name` property + * text-field: ['get', 'name'] + * } + * }); + * ``` + * + * @example + * Add a new symbol layer before an existing layer + * ```ts + * map.addLayer({ + * id: 'states', + * // References a source that's already been defined + * source: 'state-data', + * type: 'symbol', + * layout: { + * // Set the label content to the + * // feature's `name` property + * text-field: ['get', 'name'] + * } + * // Add the layer before the existing `cities` layer + * }, 'cities'); + * ``` + * @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/cluster/) + * @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/vector-source/) + * @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/wms/) + */ + addLayer(layer, beforeId) { + this._lazyInitEmptyStyle(); + this.style.addLayer(layer, beforeId); + return this._update(true); + } + /** + * Moves a layer to a different z-position. + * + * @param id - The ID of the layer to move. + * @param 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. + * + * @example + * 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. + * ```ts + * map.moveLayer('polygon', 'country-label'); + * ``` + */ + moveLayer(id, beforeId) { + this.style.moveLayer(id, beforeId); + return this._update(true); + } + /** + * Removes the layer with the given ID from the map's style. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param id - The ID of the layer to remove + * + * @example + * If a layer with ID 'state-data' exists, remove it. + * ```ts + * if (map.getLayer('state-data')) map.removeLayer('state-data'); + * ``` + */ + removeLayer(id) { + this.style.removeLayer(id); + return this._update(true); + } + /** + * Returns the layer with the specified ID in the map's style. + * + * @param id - The ID of the layer to get. + * @returns The layer with the specified ID, or `undefined` + * if the ID corresponds to no existing layers. + * + * @example + * ```ts + * let stateDataLayer = map.getLayer('state-data'); + * ``` + * @see [Filter symbols by toggling a list](https://maplibre.org/maplibre-gl-js/docs/examples/filter-markers/) + * @see [Filter symbols by text input](https://maplibre.org/maplibre-gl-js/docs/examples/filter-markers-by-input/) + */ + getLayer(id) { + return this.style.getLayer(id); + } + /** + * Return the ids of all layers currently in the style, including custom layers, in order. + * + * @returns ids of layers, in order + * + * @example + * ```ts + * const orderedLayerIds = map.getLayersOrder(); + * ``` + */ + getLayersOrder() { + return this.style.getLayersOrder(); + } + /** + * Sets the zoom extent for the specified style layer. The zoom extent includes the + * [minimum zoom level](https://maplibre.org/maplibre-style-spec/layers/#minzoom) + * and [maximum zoom level](https://maplibre.org/maplibre-style-spec/layers/#maxzoom)) + * at which the layer will be rendered. + * + * Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the + * minimum zoom level of the _source layer_ because the data does not exist at those zoom levels. If the minimum + * zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style + * layer will not be rendered at all zoom levels in the zoom range. + * + * @param layerId - The ID of the layer to which the zoom extent will be applied. + * @param minzoom - The minimum zoom to set (0-24). + * @param maxzoom - The maximum zoom to set (0-24). + * + * @example + * ```ts + * map.setLayerZoomRange('my-layer', 2, 5); + * ``` + */ + setLayerZoomRange(layerId, minzoom, maxzoom) { + this.style.setLayerZoomRange(layerId, minzoom, maxzoom); + return this._update(true); + } + /** + * Sets the filter for the specified style layer. + * + * Filters control which features a style layer renders from its source. + * Any feature for which the filter expression evaluates to `true` will be + * rendered on the map. Those that are false will be hidden. + * + * Use `setFilter` to show a subset of your source data. + * + * To clear the filter, pass `null` or `undefined` as the second parameter. + * + * @param layerId - The ID of the layer to which the filter will be applied. + * @param filter - The filter, conforming to the MapLibre Style Specification's + * [filter definition](https://maplibre.org/maplibre-style-spec/layers/#filter). If `null` or `undefined` is provided, the function removes any existing filter from the layer. + * @param options - Options object. + * + * @example + * Display only features with the 'name' property 'USA' + * ```ts + * map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']); + * ``` + * @example + * Display only features with five or more 'available-spots' + * ```ts + * map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]); + * ``` + * @example + * Remove the filter for the 'bike-docks' style layer + * ```ts + * map.setFilter('bike-docks', null); + * ``` + * @see [Create a timeline animation](https://maplibre.org/maplibre-gl-js/docs/examples/timeline-animation/) + */ + setFilter(layerId, filter, options = {}) { + this.style.setFilter(layerId, filter, options); + return this._update(true); + } + /** + * Returns the filter applied to the specified style layer. + * + * @param layerId - The ID of the style layer whose filter to get. + * @returns The layer's filter. + */ + getFilter(layerId) { + return this.style.getFilter(layerId); + } + /** + * Sets the value of a paint property in the specified style layer. + * + * @param layerId - The ID of the layer to set the paint property in. + * @param name - The name of the paint property to set. + * @param value - The value of the paint property to set. + * Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/). + * Pass `null` to unset the existing value. + * @param options - Options object. + * @example + * ```ts + * map.setPaintProperty('my-layer', 'fill-color', '#faafee'); + * ``` + * @see [Change a layer's color with buttons](https://maplibre.org/maplibre-gl-js/docs/examples/color-switcher/) + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + setPaintProperty(layerId, name, value, options = {}) { + this.style.setPaintProperty(layerId, name, value, options); + return this._update(true); + } + /** + * Returns the value of a paint property in the specified style layer. + * + * @param layerId - The ID of the layer to get the paint property from. + * @param name - The name of a paint property to get. + * @returns The value of the specified paint property. + */ + getPaintProperty(layerId, name) { + return this.style.getPaintProperty(layerId, name); + } + /** + * Sets the value of a layout property in the specified style layer. + * + * @param layerId - The ID of the layer to set the layout property in. + * @param name - The name of the layout property to set. + * @param value - The value of the layout property. Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/). + * @param options - The options object. + * @example + * ```ts + * map.setLayoutProperty('my-layer', 'visibility', 'none'); + * ``` + */ + setLayoutProperty(layerId, name, value, options = {}) { + this.style.setLayoutProperty(layerId, name, value, options); + return this._update(true); + } + /** + * Returns the value of a layout property in the specified style layer. + * + * @param layerId - The ID of the layer to get the layout property from. + * @param name - The name of the layout property to get. + * @returns The value of the specified layout property. + */ + getLayoutProperty(layerId, name) { + return this.style.getLayoutProperty(layerId, name); + } + /** + * Sets the value of the style's glyphs property. + * + * @param glyphsUrl - Glyph URL to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/glyphs/). + * @param options - Options object. + * @example + * ```ts + * map.setGlyphs('https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf'); + * ``` + */ + setGlyphs(glyphsUrl, options = {}) { + this._lazyInitEmptyStyle(); + this.style.setGlyphs(glyphsUrl, options); + return this._update(true); + } + /** + * Returns the value of the style's glyphs URL + * + * @returns glyphs Style's glyphs url + */ + getGlyphs() { + return this.style.getGlyphsUrl(); + } + /** + * Adds a sprite to the map's style. Fires the `style` event. + * + * @param id - The ID of the sprite to add. Must not conflict with existing sprites. + * @param url - The URL to load the sprite from + * @param options - Options object. + * @example + * ```ts + * map.addSprite('sprite-two', 'http://example.com/sprite-two'); + * ``` + */ + addSprite(id, url, options = {}) { + this._lazyInitEmptyStyle(); + this.style.addSprite(id, url, options, (err) => { + if (!err) { + this._update(true); + } + }); + return this; + } + /** + * Removes the sprite from the map's style. Fires the `style` event. + * + * @param id - The ID of the sprite to remove. If the sprite is declared as a single URL, the ID must be "default". + * @example + * ```ts + * map.removeSprite('sprite-two'); + * map.removeSprite('default'); + * ``` + */ + removeSprite(id) { + this._lazyInitEmptyStyle(); + this.style.removeSprite(id); + return this._update(true); + } + /** + * Returns the as-is value of the style's sprite. + * + * @returns style's sprite list of id-url pairs + */ + getSprite() { + return this.style.getSprite(); + } + /** + * Sets the value of the style's sprite property. + * + * @param spriteUrl - Sprite URL to set. + * @param options - Options object. + * @example + * ```ts + * map.setSprite('YOUR_SPRITE_URL'); + * ``` + */ + setSprite(spriteUrl, options = {}) { + this._lazyInitEmptyStyle(); + this.style.setSprite(spriteUrl, options, (err) => { + if (!err) { + this._update(true); + } + }); + return this; + } + /** + * Sets the any combination of light values. + * + * @param light - Light properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/light). + * @param options - Options object. + * + * @example + * ```ts + * let layerVisibility = map.getLayoutProperty('my-layer', 'visibility'); + * ``` + */ + setLight(light, options = {}) { + this._lazyInitEmptyStyle(); + this.style.setLight(light, options); + return this._update(true); + } + /** + * Returns the value of the light object. + * + * @returns light Light properties of the style. + */ + getLight() { + return this.style.getLight(); + } + /** + * Loads sky and fog defined by {@link SkySpecification} onto the map. + * Note: The fog only shows when using the terrain 3D feature. + * @param sky - Sky properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/sky/). + * @returns `this` + * @example + * ```ts + * map.setSky({ 'sky-color': '#00f' }); + * ``` + */ + setSky(sky) { + this._lazyInitEmptyStyle(); + this.style.setSky(sky); + return this._update(true); + } + /** + * Returns the value of the sky object. + * + * @returns the sky properties of the style. + * @example + * ```ts + * map.getSky(); + * ``` + */ + getSky() { + return this.style.getSky(); + } + /** + * Sets the `state` of a feature. + * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime. + * When using this method, the `state` object is merged with any existing key-value pairs in the feature's state. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * This method can only be used with sources that have a `feature.id` attribute. The `feature.id` attribute can be defined in three ways: + * + * - For vector or GeoJSON sources, including an `id` attribute in the original data file. + * - For vector or GeoJSON sources, using the [`promoteId`](https://maplibre.org/maplibre-style-spec/sources/#vector-promoteId) option at the time the source is defined. + * - For GeoJSON sources, using the [`generateId`](https://maplibre.org/maplibre-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. + * + * _Note: You can use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state) to access the values in a feature's state object for the purposes of styling._ + * + * @param feature - Feature identifier. Feature objects returned from + * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param state - A set of key-value pairs. The values should be valid JSON types. + * + * @example + * ```ts + * // When the mouse moves over the `my-layer` layer, update + * // the feature state for the feature under the mouse + * map.on('mousemove', 'my-layer', (e) => { + * if (e.features.length > 0) { + * map.setFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id, + * }, { + * hover: true + * }); + * } + * }); + * ``` + * @see [Create a hover effect](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/) + */ + setFeatureState(feature, state) { + this.style.setFeatureState(feature, state); + return this._update(); + } + /** + * Removes the `state` of a feature, setting it back to the default behavior. + * If only a `target.source` is specified, it will remove the state for all features from that source. + * If `target.id` is also specified, it will remove all keys for that feature's state. + * If `key` is also specified, it removes only that key from that feature's state. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * @param target - Identifier of where to remove state. It can be a source, a feature, or a specific key of feature. + * Feature objects returned from {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param key - (optional) The key in the feature state to reset. + * @example + * Reset the entire state object for all features in the `my-source` source + * ```ts + * map.removeFeatureState({ + * source: 'my-source' + * }); + * ``` + * + * @example + * When the mouse leaves the `my-layer` layer, + * reset the entire state object for the + * feature under the mouse + * ```ts + * map.on('mouseleave', 'my-layer', (e) => { + * map.removeFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }); + * }); + * ``` + * + * @example + * When the mouse leaves the `my-layer` layer, + * reset only the `hover` key-value pair in the + * state for the feature under the mouse + * ```ts + * map.on('mouseleave', 'my-layer', (e) => { + * map.removeFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }, 'hover'); + * }); + * ``` + */ + removeFeatureState(target, key) { + this.style.removeFeatureState(target, key); + return this._update(); + } + /** + * Gets the `state` of a feature. + * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * _Note: To access the values in a feature's state object for the purposes of styling the feature, use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state)._ + * + * @param feature - Feature identifier. Feature objects returned from + * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @returns The state of the feature: a set of key-value pairs that was assigned to the feature at runtime. + * + * @example + * When the mouse moves over the `my-layer` layer, + * get the feature state for the feature under the mouse + * ```ts + * map.on('mousemove', 'my-layer', (e) => { + * if (e.features.length > 0) { + * map.getFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }); + * } + * }); + * ``` + */ + getFeatureState(feature) { + return this.style.getFeatureState(feature); + } + /** + * Returns the map's containing HTML element. + * + * @returns The map's container. + */ + getContainer() { + return this._container; + } + /** + * Returns the HTML element containing the map's `` element. + * + * If you want to add non-GL overlays to the map, you should append them to this element. + * + * This is the element to which event bindings for map interactivity (such as panning and zooming) are + * attached. It will receive bubbled events from child elements such as the ``, but not from + * map controls. + * + * @returns The container of the map's ``. + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + getCanvasContainer() { + return this._canvasContainer; + } + /** + * Returns the map's `` element. + * + * @returns The map's `` element. + * @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-on-symbol/) + */ + getCanvas() { + return this._canvas; + } + _containerDimensions() { + let width = 0; + let height = 0; + if (this._container) { + width = this._container.clientWidth || 400; + height = this._container.clientHeight || 300; + } + return [width, height]; + } + _setupContainer() { + const container = this._container; + container.classList.add('maplibregl-map'); + const canvasContainer = this._canvasContainer = DOM.create('div', 'maplibregl-canvas-container', container); + if (this._interactive) { + canvasContainer.classList.add('maplibregl-interactive'); + } + this._canvas = DOM.create('canvas', 'maplibregl-canvas', canvasContainer); + this._canvas.addEventListener('webglcontextlost', this._contextLost, false); + this._canvas.addEventListener('webglcontextrestored', this._contextRestored, false); + this._canvas.setAttribute('tabindex', this._interactive ? '0' : '-1'); + this._canvas.setAttribute('aria-label', this._getUIString('Map.Title')); + this._canvas.setAttribute('role', 'region'); + const dimensions = this._containerDimensions(); + const clampedPixelRatio = this._getClampedPixelRatio(dimensions[0], dimensions[1]); + this._resizeCanvas(dimensions[0], dimensions[1], clampedPixelRatio); + const controlContainer = this._controlContainer = DOM.create('div', 'maplibregl-control-container', container); + const positions = this._controlPositions = {}; + ['top-left', 'top-right', 'bottom-left', 'bottom-right'].forEach((positionName) => { + positions[positionName] = DOM.create('div', `maplibregl-ctrl-${positionName} `, controlContainer); + }); + this._container.addEventListener('scroll', this._onMapScroll, false); + } + _resizeCanvas(width, height, pixelRatio) { + // Request the required canvas size taking the pixelratio into account. + this._canvas.width = Math.floor(pixelRatio * width); + this._canvas.height = Math.floor(pixelRatio * height); + // Maintain the same canvas size, potentially downscaling it for HiDPI displays + this._canvas.style.width = `${width}px`; + this._canvas.style.height = `${height}px`; + } + _setupPainter() { + const attributes = { + alpha: true, + stencil: true, + depth: true, + failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat, + preserveDrawingBuffer: this._preserveDrawingBuffer, + antialias: this._antialias || false + }; + let webglcontextcreationerrorDetailObject = null; + this._canvas.addEventListener('webglcontextcreationerror', (args) => { + webglcontextcreationerrorDetailObject = { requestedAttributes: attributes }; + if (args) { + webglcontextcreationerrorDetailObject.statusMessage = args.statusMessage; + webglcontextcreationerrorDetailObject.type = args.type; + } + }, { once: true }); + const gl = this._canvas.getContext('webgl2', attributes) || + this._canvas.getContext('webgl', attributes); + if (!gl) { + const msg = 'Failed to initialize WebGL'; + if (webglcontextcreationerrorDetailObject) { + webglcontextcreationerrorDetailObject.message = msg; + throw new Error(JSON.stringify(webglcontextcreationerrorDetailObject)); + } + else { + throw new Error(msg); + } + } + this.painter = new Painter(gl, this.transform); + webpSupported.testSupport(gl); + } + /** + * Returns a Boolean indicating whether the map is fully loaded. + * + * Returns `false` if the style is not yet fully loaded, + * or if there has been a change to the sources or style that + * has not yet fully loaded. + * + * @returns A Boolean indicating whether the map is fully loaded. + */ + loaded() { + return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded(); + } + /** + * @internal + * Update this map's style and sources, and re-render the map. + * + * @param updateStyle - mark the map's style for reprocessing as + * well as its sources + */ + _update(updateStyle) { + if (!this.style || !this.style._loaded) + return this; + this._styleDirty = this._styleDirty || updateStyle; + this._sourcesDirty = true; + this.triggerRepaint(); + return this; + } + /** + * @internal + * Request that the given callback be executed during the next render + * frame. Schedule a render frame if one is not already scheduled. + * + * @returns An id that can be used to cancel the callback + */ + _requestRenderFrame(callback) { + this._update(); + return this._renderTaskQueue.add(callback); + } + _cancelRenderFrame(id) { + this._renderTaskQueue.remove(id); + } + /** + * @internal + * Call when a (re-)render of the map is required: + * + * - The style has changed (`setPaintProperty()`, etc.) + * - Source data has changed (e.g. tiles have finished loading) + * - The map has is moving (or just finished moving) + * - A transition is in progress + * + * @param paintStartTimeStamp - The time when the animation frame began executing. + */ + _render(paintStartTimeStamp) { + const fadeDuration = this._idleTriggered ? this._fadeDuration : 0; + // A custom layer may have used the context asynchronously. Mark the state as dirty. + this.painter.context.setDirty(); + this.painter.setBaseState(); + this._renderTaskQueue.run(paintStartTimeStamp); + // A task queue callback may have fired a user event which may have removed the map + if (this._removed) + return; + let crossFading = false; + // If the style has changed, the map is being zoomed, or a transition or fade is in progress: + // - Apply style changes (in a batch) + // - Recalculate paint properties. + if (this.style && this._styleDirty) { + this._styleDirty = false; + const zoom = this.transform.zoom; + const now = browser.now(); + this.style.zoomHistory.update(zoom, now); + const parameters = new performance$1.EvaluationParameters(zoom, { + now, + fadeDuration, + zoomHistory: this.style.zoomHistory, + transition: this.style.getTransition() + }); + const factor = parameters.crossFadingFactor(); + if (factor !== 1 || factor !== this._crossFadingFactor) { + crossFading = true; + this._crossFadingFactor = factor; + } + this.style.update(parameters); + } + // If we are in _render for any reason other than an in-progress paint + // transition, update source caches to check for and load any tiles we + // need for the current transform + if (this.style && this._sourcesDirty) { + this._sourcesDirty = false; + this.style._updateSources(this.transform); + } + // update terrain stuff + if (this.terrain) { + this.terrain.sourceCache.update(this.transform, this.terrain); + this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + if (!this._elevationFreeze) { + this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + } + } + else { + this.transform.minElevationForCurrentTile = 0; + this.transform.elevation = 0; + } + this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, fadeDuration, this._crossSourceCollisions); + // Actually draw + this.painter.render(this.style, { + showTileBoundaries: this.showTileBoundaries, + showOverdrawInspector: this._showOverdrawInspector, + rotating: this.isRotating(), + zooming: this.isZooming(), + moving: this.isMoving(), + fadeDuration, + showPadding: this.showPadding, + }); + this.fire(new performance$1.Event('render')); + if (this.loaded() && !this._loaded) { + this._loaded = true; + performance$1.PerformanceUtils.mark(performance$1.PerformanceMarkers.load); + this.fire(new performance$1.Event('load')); + } + if (this.style && (this.style.hasTransitions() || crossFading)) { + this._styleDirty = true; + } + if (this.style && !this._placementDirty) { + // Since no fade operations are in progress, we can release + // all tiles held for fading. If we didn't do this, the tiles + // would just sit in the SourceCaches until the next render + this.style._releaseSymbolFadeTiles(); + } + // Schedule another render frame if it's needed. + // + // Even though `_styleDirty` and `_sourcesDirty` are reset in this + // method, synchronous events fired during Style#update or + // Style#_updateSources could have caused them to be set again. + const somethingDirty = this._sourcesDirty || this._styleDirty || this._placementDirty; + if (somethingDirty || this._repaint) { + this.triggerRepaint(); + } + else if (!this.isMoving() && this.loaded()) { + this.fire(new performance$1.Event('idle')); + } + if (this._loaded && !this._fullyLoaded && !somethingDirty) { + this._fullyLoaded = true; + performance$1.PerformanceUtils.mark(performance$1.PerformanceMarkers.fullLoad); + } + return this; + } + /** + * Force a synchronous redraw of the map. + * @example + * ```ts + * map.redraw(); + * ``` + */ + redraw() { + if (this.style) { + // cancel the scheduled update + if (this._frameRequest) { + this._frameRequest.abort(); + this._frameRequest = null; + } + this._render(0); + } + return this; + } + /** + * Clean up and release all internal resources associated with this map. + * + * This includes DOM elements, event bindings, web workers, and WebGL resources. + * + * Use this method when you are done using the map and wish to ensure that it no + * longer consumes browser resources. Afterwards, you must not call any other + * methods on the map. + */ + remove() { + var _a; + if (this._hash) + this._hash.remove(); + for (const control of this._controls) + control.onRemove(this); + this._controls = []; + if (this._frameRequest) { + this._frameRequest.abort(); + this._frameRequest = null; + } + this._renderTaskQueue.clear(); + this.painter.destroy(); + this.handlers.destroy(); + delete this.handlers; + this.setStyle(null); + if (typeof window !== 'undefined') { + removeEventListener('online', this._onWindowOnline, false); + } + ImageRequest.removeThrottleControl(this._imageQueueHandle); + (_a = this._resizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect(); + const extension = this.painter.context.gl.getExtension('WEBGL_lose_context'); + if (extension === null || extension === void 0 ? void 0 : extension.loseContext) + extension.loseContext(); + this._canvas.removeEventListener('webglcontextrestored', this._contextRestored, false); + this._canvas.removeEventListener('webglcontextlost', this._contextLost, false); + DOM.remove(this._canvasContainer); + DOM.remove(this._controlContainer); + this._container.classList.remove('maplibregl-map'); + performance$1.PerformanceUtils.clearMetrics(); + this._removed = true; + this.fire(new performance$1.Event('remove')); + } + /** + * Trigger the rendering of a single frame. Use this method with custom layers to + * repaint the map when the layer changes. Calling this multiple times before the + * next frame is rendered will still result in only a single frame being rendered. + * @example + * ```ts + * map.triggerRepaint(); + * ``` + * @see [Add a 3D model](https://maplibre.org/maplibre-gl-js/docs/examples/add-3d-model/) + * @see [Add an animated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-animated/) + */ + triggerRepaint() { + if (this.style && !this._frameRequest) { + this._frameRequest = new AbortController(); + browser.frameAsync(this._frameRequest).then((paintStartTimeStamp) => { + performance$1.PerformanceUtils.frame(paintStartTimeStamp); + this._frameRequest = null; + this._render(paintStartTimeStamp); + }).catch(() => { }); // ignore abort error + } + } + /** + * Gets and sets a Boolean indicating whether the map will render an outline + * around each tile and the tile ID. These tile boundaries are useful for + * debugging. + * + * The uncompressed file size of the first vector source is drawn in the top left + * corner of each tile, next to the tile ID. + * + * @example + * ```ts + * map.showTileBoundaries = true; + * ``` + */ + get showTileBoundaries() { return !!this._showTileBoundaries; } + set showTileBoundaries(value) { + if (this._showTileBoundaries === value) + return; + this._showTileBoundaries = value; + this._update(); + } + /** + * Gets and sets a Boolean indicating whether the map will visualize + * the padding offsets. + */ + get showPadding() { return !!this._showPadding; } + set showPadding(value) { + if (this._showPadding === value) + return; + this._showPadding = value; + this._update(); + } + /** + * Gets and sets a Boolean indicating whether the map will render boxes + * around all symbols in the data source, revealing which symbols + * were rendered or which were hidden due to collisions. + * This information is useful for debugging. + */ + get showCollisionBoxes() { return !!this._showCollisionBoxes; } + set showCollisionBoxes(value) { + if (this._showCollisionBoxes === value) + return; + this._showCollisionBoxes = value; + if (value) { + // When we turn collision boxes on we have to generate them for existing tiles + // When we turn them off, there's no cost to leaving existing boxes in place + this.style._generateCollisionBoxes(); + } + else { + // Otherwise, call an update to remove collision boxes + this._update(); + } + } + /** + * Gets and sets a Boolean indicating whether the map should color-code + * each fragment to show how many times it has been shaded. + * White fragments have been shaded 8 or more times. + * Black fragments have been shaded 0 times. + * This information is useful for debugging. + */ + get showOverdrawInspector() { return !!this._showOverdrawInspector; } + set showOverdrawInspector(value) { + if (this._showOverdrawInspector === value) + return; + this._showOverdrawInspector = value; + this._update(); + } + /** + * Gets and sets a Boolean indicating whether the map will + * continuously repaint. This information is useful for analyzing performance. + */ + get repaint() { return !!this._repaint; } + set repaint(value) { + if (this._repaint !== value) { + this._repaint = value; + this.triggerRepaint(); + } + } + // show vertices + get vertices() { return !!this._vertices; } + set vertices(value) { this._vertices = value; this._update(); } + /** + * Returns the package version of the library + * @returns Package version of the library + */ + get version() { + return version$1; + } + /** + * Returns the elevation for the point where the camera is looking. + * This value corresponds to: + * "meters above sea level" * "exaggeration" + * @returns The elevation. + */ + getCameraTargetElevation() { + return this.transform.elevation; + } +}; + +const assignEvents = (handler) => { + handler.touchstart = handler.dragStart; + handler.touchmoveWindow = handler.dragMove; + handler.touchend = handler.dragEnd; +}; +const generateOneFingerTouchRotationHandler = ({ enable, clickTolerance, bearingDegreesPerPixelMoved = 0.8 }) => { + const touchMoveStateManager = new OneFingerTouchMoveStateManager(); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ bearingDelta: (point.x - lastPoint.x) * bearingDegreesPerPixelMoved }), + moveStateManager: touchMoveStateManager, + enable, + assignEvents, + }); +}; +const generateOneFingerTouchPitchHandler = ({ enable, clickTolerance, pitchDegreesPerPixelMoved = -0.5 }) => { + const touchMoveStateManager = new OneFingerTouchMoveStateManager(); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ pitchDelta: (point.y - lastPoint.y) * pitchDegreesPerPixelMoved }), + moveStateManager: touchMoveStateManager, + enable, + assignEvents, + }); +}; + +const defaultOptions$3 = { + showCompass: true, + showZoom: true, + visualizePitch: false +}; +/** + * A `NavigationControl` control contains zoom buttons and a compass. + * + * @group Markers and Controls + * + * @example + * ```ts + * let nav = new NavigationControl(); + * map.addControl(nav, 'top-left'); + * ``` + * @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigation/) + */ +class NavigationControl { + /** + * @param options - the control's options + */ + constructor(options) { + this._updateZoomButtons = () => { + const zoom = this._map.getZoom(); + const isMax = zoom === this._map.getMaxZoom(); + const isMin = zoom === this._map.getMinZoom(); + this._zoomInButton.disabled = isMax; + this._zoomOutButton.disabled = isMin; + this._zoomInButton.setAttribute('aria-disabled', isMax.toString()); + this._zoomOutButton.setAttribute('aria-disabled', isMin.toString()); + }; + this._rotateCompassArrow = () => { + const rotate = this.options.visualizePitch ? + `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)` : + `rotate(${this._map.transform.angle * (180 / Math.PI)}deg)`; + this._compassIcon.style.transform = rotate; + }; + this._setButtonTitle = (button, title) => { + const str = this._map._getUIString(`NavigationControl.${title}`); + button.title = str; + button.setAttribute('aria-label', str); + }; + this.options = performance$1.extend({}, defaultOptions$3, options); + this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group'); + this._container.addEventListener('contextmenu', (e) => e.preventDefault()); + if (this.options.showZoom) { + this._zoomInButton = this._createButton('maplibregl-ctrl-zoom-in', (e) => this._map.zoomIn({}, { originalEvent: e })); + DOM.create('span', 'maplibregl-ctrl-icon', this._zoomInButton).setAttribute('aria-hidden', 'true'); + this._zoomOutButton = this._createButton('maplibregl-ctrl-zoom-out', (e) => this._map.zoomOut({}, { originalEvent: e })); + DOM.create('span', 'maplibregl-ctrl-icon', this._zoomOutButton).setAttribute('aria-hidden', 'true'); + } + if (this.options.showCompass) { + this._compass = this._createButton('maplibregl-ctrl-compass', (e) => { + if (this.options.visualizePitch) { + this._map.resetNorthPitch({}, { originalEvent: e }); + } + else { + this._map.resetNorth({}, { originalEvent: e }); + } + }); + this._compassIcon = DOM.create('span', 'maplibregl-ctrl-icon', this._compass); + this._compassIcon.setAttribute('aria-hidden', 'true'); + } + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + if (this.options.showZoom) { + this._setButtonTitle(this._zoomInButton, 'ZoomIn'); + this._setButtonTitle(this._zoomOutButton, 'ZoomOut'); + this._map.on('zoom', this._updateZoomButtons); + this._updateZoomButtons(); + } + if (this.options.showCompass) { + this._setButtonTitle(this._compass, 'ResetBearing'); + if (this.options.visualizePitch) { + this._map.on('pitch', this._rotateCompassArrow); + } + this._map.on('rotate', this._rotateCompassArrow); + this._rotateCompassArrow(); + this._handler = new MouseRotateWrapper(this._map, this._compass, this.options.visualizePitch); + } + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + if (this.options.showZoom) { + this._map.off('zoom', this._updateZoomButtons); + } + if (this.options.showCompass) { + if (this.options.visualizePitch) { + this._map.off('pitch', this._rotateCompassArrow); + } + this._map.off('rotate', this._rotateCompassArrow); + this._handler.off(); + delete this._handler; + } + delete this._map; + } + _createButton(className, fn) { + const a = DOM.create('button', className, this._container); + a.type = 'button'; + a.addEventListener('click', fn); + return a; + } +} +class MouseRotateWrapper { + constructor(map, element, pitch = false) { + this.mousedown = (e) => { + this.startMouse(performance$1.extend({}, e, { ctrlKey: true, preventDefault: () => e.preventDefault() }), DOM.mousePos(this.element, e)); + DOM.addEventListener(window, 'mousemove', this.mousemove); + DOM.addEventListener(window, 'mouseup', this.mouseup); + }; + this.mousemove = (e) => { + this.moveMouse(e, DOM.mousePos(this.element, e)); + }; + this.mouseup = (e) => { + this.mouseRotate.dragEnd(e); + if (this.mousePitch) + this.mousePitch.dragEnd(e); + this.offTemp(); + }; + this.touchstart = (e) => { + if (e.targetTouches.length !== 1) { + this.reset(); + } + else { + this._startPos = this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0]; + this.startTouch(e, this._startPos); + DOM.addEventListener(window, 'touchmove', this.touchmove, { passive: false }); + DOM.addEventListener(window, 'touchend', this.touchend); + } + }; + this.touchmove = (e) => { + if (e.targetTouches.length !== 1) { + this.reset(); + } + else { + this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0]; + this.moveTouch(e, this._lastPos); + } + }; + this.touchend = (e) => { + if (e.targetTouches.length === 0 && + this._startPos && + this._lastPos && + this._startPos.dist(this._lastPos) < this._clickTolerance) { + this.element.click(); + } + delete this._startPos; + delete this._lastPos; + this.offTemp(); + }; + this.reset = () => { + this.mouseRotate.reset(); + if (this.mousePitch) + this.mousePitch.reset(); + this.touchRotate.reset(); + if (this.touchPitch) + this.touchPitch.reset(); + delete this._startPos; + delete this._lastPos; + this.offTemp(); + }; + this._clickTolerance = 10; + const mapRotateTolerance = map.dragRotate._mouseRotate.getClickTolerance(); + const mapPitchTolerance = map.dragRotate._mousePitch.getClickTolerance(); + this.element = element; + this.mouseRotate = generateMouseRotationHandler({ clickTolerance: mapRotateTolerance, enable: true }); + this.touchRotate = generateOneFingerTouchRotationHandler({ clickTolerance: mapRotateTolerance, enable: true }); + this.map = map; + if (pitch) { + this.mousePitch = generateMousePitchHandler({ clickTolerance: mapPitchTolerance, enable: true }); + this.touchPitch = generateOneFingerTouchPitchHandler({ clickTolerance: mapPitchTolerance, enable: true }); + } + DOM.addEventListener(element, 'mousedown', this.mousedown); + DOM.addEventListener(element, 'touchstart', this.touchstart, { passive: false }); + DOM.addEventListener(element, 'touchcancel', this.reset); + } + startMouse(e, point) { + this.mouseRotate.dragStart(e, point); + if (this.mousePitch) + this.mousePitch.dragStart(e, point); + DOM.disableDrag(); + } + startTouch(e, point) { + this.touchRotate.dragStart(e, point); + if (this.touchPitch) + this.touchPitch.dragStart(e, point); + DOM.disableDrag(); + } + moveMouse(e, point) { + const map = this.map; + const { bearingDelta } = this.mouseRotate.dragMove(e, point) || {}; + if (bearingDelta) + map.setBearing(map.getBearing() + bearingDelta); + if (this.mousePitch) { + const { pitchDelta } = this.mousePitch.dragMove(e, point) || {}; + if (pitchDelta) + map.setPitch(map.getPitch() + pitchDelta); + } + } + moveTouch(e, point) { + const map = this.map; + const { bearingDelta } = this.touchRotate.dragMove(e, point) || {}; + if (bearingDelta) + map.setBearing(map.getBearing() + bearingDelta); + if (this.touchPitch) { + const { pitchDelta } = this.touchPitch.dragMove(e, point) || {}; + if (pitchDelta) + map.setPitch(map.getPitch() + pitchDelta); + } + } + off() { + const element = this.element; + DOM.removeEventListener(element, 'mousedown', this.mousedown); + DOM.removeEventListener(element, 'touchstart', this.touchstart, { passive: false }); + DOM.removeEventListener(window, 'touchmove', this.touchmove, { passive: false }); + DOM.removeEventListener(window, 'touchend', this.touchend); + DOM.removeEventListener(element, 'touchcancel', this.reset); + this.offTemp(); + } + offTemp() { + DOM.enableDrag(); + DOM.removeEventListener(window, 'mousemove', this.mousemove); + DOM.removeEventListener(window, 'mouseup', this.mouseup); + DOM.removeEventListener(window, 'touchmove', this.touchmove, { passive: false }); + DOM.removeEventListener(window, 'touchend', this.touchend); + } +} + +let supportsGeolocation; +function checkGeolocationSupport() { + return performance$1.__awaiter(this, arguments, void 0, function* (forceRecalculation = false) { + if (supportsGeolocation !== undefined && !forceRecalculation) { + return supportsGeolocation; + } + if (window.navigator.permissions === undefined) { + supportsGeolocation = !!window.navigator.geolocation; + return supportsGeolocation; + } + // navigator.permissions has incomplete browser support + // https://caniuse.com/#feat=permissions-api + // Test for the case where a browser disables Geolocation because of an + // insecure origin + try { + const permissions = yield window.navigator.permissions.query({ name: 'geolocation' }); + supportsGeolocation = permissions.state !== 'denied'; // eslint-disable-line require-atomic-updates + } + catch (_a) { + // Fix for iOS16 which rejects query but still supports geolocation + supportsGeolocation = !!window.navigator.geolocation; // eslint-disable-line require-atomic-updates + } + return supportsGeolocation; + }); +} + +/** + * Given a LngLat, prior projected position, and a transform, return a new LngLat shifted + * n × 360° east or west for some n ≥ 0 such that: + * + * * the projected location of the result is on screen, if possible, and secondarily: + * * the difference between the projected location of the result and the prior position + * is minimized. + * + * The object is to preserve perceived object constancy for Popups and Markers as much as + * possible; they should avoid shifting large distances across the screen, even when the + * map center changes by ±360° due to automatic wrapping, and when about to go off screen, + * should wrap just enough to avoid doing so. + */ +function smartWrap(lngLat, priorPos, transform) { + const originalLngLat = new performance$1.LngLat(lngLat.lng, lngLat.lat); + lngLat = new performance$1.LngLat(lngLat.lng, lngLat.lat); + // First, try shifting one world in either direction, and see if either is closer to the + // prior position. This preserves object constancy when the map center is auto-wrapped + // during animations. + if (priorPos) { + const left = new performance$1.LngLat(lngLat.lng - 360, lngLat.lat); + const right = new performance$1.LngLat(lngLat.lng + 360, lngLat.lat); + const delta = transform.locationPoint(lngLat).distSqr(priorPos); + if (transform.locationPoint(left).distSqr(priorPos) < delta) { + lngLat = left; + } + else if (transform.locationPoint(right).distSqr(priorPos) < delta) { + lngLat = right; + } + } + // Second, wrap toward the center until the new position is on screen, or we can't get + // any closer. + while (Math.abs(lngLat.lng - transform.center.lng) > 180) { + const pos = transform.locationPoint(lngLat); + if (pos.x >= 0 && pos.y >= 0 && pos.x <= transform.width && pos.y <= transform.height) { + break; + } + if (lngLat.lng > transform.center.lng) { + lngLat.lng -= 360; + } + else { + lngLat.lng += 360; + } + } + // Apply the change only if new coord is below horizon + if (lngLat.lng !== originalLngLat.lng && + transform.locationPoint(lngLat).y > (transform.height / 2 - transform.getHorizon())) { + return lngLat; + } + return originalLngLat; +} + +const anchorTranslate = { + 'center': 'translate(-50%,-50%)', + 'top': 'translate(-50%,0)', + 'top-left': 'translate(0,0)', + 'top-right': 'translate(-100%,0)', + 'bottom': 'translate(-50%,-100%)', + 'bottom-left': 'translate(0,-100%)', + 'bottom-right': 'translate(-100%,-100%)', + 'left': 'translate(0,-50%)', + 'right': 'translate(-100%,-50%)' +}; +function applyAnchorClass(element, anchor, prefix) { + const classList = element.classList; + for (const key in anchorTranslate) { + classList.remove(`maplibregl-${prefix}-anchor-${key}`); + } + classList.add(`maplibregl-${prefix}-anchor-${anchor}`); +} + +/** + * Creates a marker component + * + * @group Markers and Controls + * + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([30.5, 50.5]) + * .addTo(map); + * ``` + * + * @example + * Set options + * ```ts + * let marker = new Marker({ + * color: "#FFFFFF", + * draggable: true + * }).setLngLat([30.5, 50.5]) + * .addTo(map); + * ``` + * @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/custom-marker-icons/) + * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/) + * + * ## Events + * + * **Event** `dragstart` of type {@link Event} will be fired when dragging starts. + * + * **Event** `drag` of type {@link Event} will be fired while dragging. + * + * **Event** `dragend` of type {@link Event} will be fired when the marker is finished being dragged. + */ +class Marker extends performance$1.Evented { + /** + * @param options - the options + */ + constructor(options) { + super(); + this._onKeyPress = (e) => { + const code = e.code; + const legacyCode = e.charCode || e.keyCode; + if ((code === 'Space') || (code === 'Enter') || + (legacyCode === 32) || (legacyCode === 13) // space or enter + ) { + this.togglePopup(); + } + }; + this._onMapClick = (e) => { + const targetElement = e.originalEvent.target; + const element = this._element; + if (this._popup && (targetElement === element || element.contains(targetElement))) { + this.togglePopup(); + } + }; + this._update = (e) => { + var _a; + if (!this._map) + return; + const isFullyLoaded = this._map.loaded() && !this._map.isMoving(); + if ((e === null || e === void 0 ? void 0 : e.type) === 'terrain' || ((e === null || e === void 0 ? void 0 : e.type) === 'render' && !isFullyLoaded)) { + this._map.once('render', this._update); + } + if (this._map.transform.renderWorldCopies) { + this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map.transform); + } + else { + this._lngLat = (_a = this._lngLat) === null || _a === void 0 ? void 0 : _a.wrap(); + } + this._flatPos = this._pos = this._map.project(this._lngLat)._add(this._offset); + if (this._map.terrain) { + // flat position is saved because smartWrap needs non-elevated points + this._flatPos = this._map.transform.locationPoint(this._lngLat)._add(this._offset); + } + let rotation = ''; + if (this._rotationAlignment === 'viewport' || this._rotationAlignment === 'auto') { + rotation = `rotateZ(${this._rotation}deg)`; + } + else if (this._rotationAlignment === 'map') { + rotation = `rotateZ(${this._rotation - this._map.getBearing()}deg)`; + } + let pitch = ''; + if (this._pitchAlignment === 'viewport' || this._pitchAlignment === 'auto') { + pitch = 'rotateX(0deg)'; + } + else if (this._pitchAlignment === 'map') { + pitch = `rotateX(${this._map.getPitch()}deg)`; + } + // because rounding the coordinates at every `move` event causes stuttered zooming + // we only round them when _update is called with `moveend` or when its called with + // no arguments (when the Marker is initialized or Marker#setLngLat is invoked). + if (!this._subpixelPositioning && (!e || e.type === 'moveend')) { + this._pos = this._pos.round(); + } + DOM.setTransform(this._element, `${anchorTranslate[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${pitch} ${rotation}`); + browser.frameAsync(new AbortController()).then(() => { + this._updateOpacity(e && e.type === 'moveend'); + }).catch(() => { }); + }; + this._onMove = (e) => { + if (!this._isDragging) { + const clickTolerance = this._clickTolerance || this._map._clickTolerance; + this._isDragging = e.point.dist(this._pointerdownPos) >= clickTolerance; + } + if (!this._isDragging) + return; + this._pos = e.point.sub(this._positionDelta); + this._lngLat = this._map.unproject(this._pos); + this.setLngLat(this._lngLat); + // suppress click event so that popups don't toggle on drag + this._element.style.pointerEvents = 'none'; + // make sure dragstart only fires on the first move event after mousedown. + // this can't be on mousedown because that event doesn't necessarily + // imply that a drag is about to happen. + if (this._state === 'pending') { + this._state = 'active'; + this.fire(new performance$1.Event('dragstart')); + } + this.fire(new performance$1.Event('drag')); + }; + this._onUp = () => { + // revert to normal pointer event handling + this._element.style.pointerEvents = 'auto'; + this._positionDelta = null; + this._pointerdownPos = null; + this._isDragging = false; + this._map.off('mousemove', this._onMove); + this._map.off('touchmove', this._onMove); + // only fire dragend if it was preceded by at least one drag event + if (this._state === 'active') { + this.fire(new performance$1.Event('dragend')); + } + this._state = 'inactive'; + }; + this._addDragHandler = (e) => { + if (this._element.contains(e.originalEvent.target)) { + e.preventDefault(); + // We need to calculate the pixel distance between the click point + // and the marker position, with the offset accounted for. Then we + // can subtract this distance from the mousemove event's position + // to calculate the new marker position. + // If we don't do this, the marker 'jumps' to the click position + // creating a jarring UX effect. + this._positionDelta = e.point.sub(this._pos).add(this._offset); + this._pointerdownPos = e.point; + this._state = 'pending'; + this._map.on('mousemove', this._onMove); + this._map.on('touchmove', this._onMove); + this._map.once('mouseup', this._onUp); + this._map.once('touchend', this._onUp); + } + }; + this._anchor = options && options.anchor || 'center'; + this._color = options && options.color || '#3FB1CE'; + this._scale = options && options.scale || 1; + this._draggable = options && options.draggable || false; + this._clickTolerance = options && options.clickTolerance || 0; + this._subpixelPositioning = options && options.subpixelPositioning || false; + this._isDragging = false; + this._state = 'inactive'; + this._rotation = options && options.rotation || 0; + this._rotationAlignment = options && options.rotationAlignment || 'auto'; + this._pitchAlignment = options && options.pitchAlignment && options.pitchAlignment !== 'auto' ? options.pitchAlignment : this._rotationAlignment; + this.setOpacity(); // set default opacity + this.setOpacity(options === null || options === void 0 ? void 0 : options.opacity, options === null || options === void 0 ? void 0 : options.opacityWhenCovered); + if (!options || !options.element) { + this._defaultMarker = true; + this._element = DOM.create('div'); + // create default map marker SVG + const svg = DOM.createNS('http://www.w3.org/2000/svg', 'svg'); + const defaultHeight = 41; + const defaultWidth = 27; + svg.setAttributeNS(null, 'display', 'block'); + svg.setAttributeNS(null, 'height', `${defaultHeight}px`); + svg.setAttributeNS(null, 'width', `${defaultWidth}px`); + svg.setAttributeNS(null, 'viewBox', `0 0 ${defaultWidth} ${defaultHeight}`); + const markerLarge = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + markerLarge.setAttributeNS(null, 'stroke', 'none'); + markerLarge.setAttributeNS(null, 'stroke-width', '1'); + markerLarge.setAttributeNS(null, 'fill', 'none'); + markerLarge.setAttributeNS(null, 'fill-rule', 'evenodd'); + const page1 = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + page1.setAttributeNS(null, 'fill-rule', 'nonzero'); + const shadow = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + shadow.setAttributeNS(null, 'transform', 'translate(3.0, 29.0)'); + shadow.setAttributeNS(null, 'fill', '#000000'); + const ellipses = [ + { 'rx': '10.5', 'ry': '5.25002273' }, + { 'rx': '10.5', 'ry': '5.25002273' }, + { 'rx': '9.5', 'ry': '4.77275007' }, + { 'rx': '8.5', 'ry': '4.29549936' }, + { 'rx': '7.5', 'ry': '3.81822308' }, + { 'rx': '6.5', 'ry': '3.34094679' }, + { 'rx': '5.5', 'ry': '2.86367051' }, + { 'rx': '4.5', 'ry': '2.38636864' } + ]; + for (const data of ellipses) { + const ellipse = DOM.createNS('http://www.w3.org/2000/svg', 'ellipse'); + ellipse.setAttributeNS(null, 'opacity', '0.04'); + ellipse.setAttributeNS(null, 'cx', '10.5'); + ellipse.setAttributeNS(null, 'cy', '5.80029008'); + ellipse.setAttributeNS(null, 'rx', data['rx']); + ellipse.setAttributeNS(null, 'ry', data['ry']); + shadow.appendChild(ellipse); + } + const background = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + background.setAttributeNS(null, 'fill', this._color); + const bgPath = DOM.createNS('http://www.w3.org/2000/svg', 'path'); + 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'); + background.appendChild(bgPath); + const border = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + border.setAttributeNS(null, 'opacity', '0.25'); + border.setAttributeNS(null, 'fill', '#000000'); + const borderPath = DOM.createNS('http://www.w3.org/2000/svg', 'path'); + 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'); + border.appendChild(borderPath); + const maki = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + maki.setAttributeNS(null, 'transform', 'translate(6.0, 7.0)'); + maki.setAttributeNS(null, 'fill', '#FFFFFF'); + const circleContainer = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + circleContainer.setAttributeNS(null, 'transform', 'translate(8.0, 8.0)'); + const circle1 = DOM.createNS('http://www.w3.org/2000/svg', 'circle'); + circle1.setAttributeNS(null, 'fill', '#000000'); + circle1.setAttributeNS(null, 'opacity', '0.25'); + circle1.setAttributeNS(null, 'cx', '5.5'); + circle1.setAttributeNS(null, 'cy', '5.5'); + circle1.setAttributeNS(null, 'r', '5.4999962'); + const circle2 = DOM.createNS('http://www.w3.org/2000/svg', 'circle'); + circle2.setAttributeNS(null, 'fill', '#FFFFFF'); + circle2.setAttributeNS(null, 'cx', '5.5'); + circle2.setAttributeNS(null, 'cy', '5.5'); + circle2.setAttributeNS(null, 'r', '5.4999962'); + circleContainer.appendChild(circle1); + circleContainer.appendChild(circle2); + page1.appendChild(shadow); + page1.appendChild(background); + page1.appendChild(border); + page1.appendChild(maki); + page1.appendChild(circleContainer); + svg.appendChild(page1); + svg.setAttributeNS(null, 'height', `${defaultHeight * this._scale}px`); + svg.setAttributeNS(null, 'width', `${defaultWidth * this._scale}px`); + this._element.appendChild(svg); + // if no element and no offset option given apply an offset for the default marker + // the -14 as the y value of the default marker offset was determined as follows + // + // the marker tip is at the center of the shadow ellipse from the default svg + // 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)" + // offset to the svg center "height (41 / 2)" gives (29.0 + 5.80029008) - (41 / 2) and rounded for an integer pixel offset gives 14 + // negative is used to move the marker up from the center so the tip is at the Marker lngLat + this._offset = performance$1.Point.convert(options && options.offset || [0, -14]); + } + else { + this._element = options.element; + this._offset = performance$1.Point.convert(options && options.offset || [0, 0]); + } + this._element.classList.add('maplibregl-marker'); + this._element.addEventListener('dragstart', (e) => { + e.preventDefault(); + }); + this._element.addEventListener('mousedown', (e) => { + // prevent focusing on click + e.preventDefault(); + }); + applyAnchorClass(this._element, this._anchor, 'marker'); + if (options && options.className) { + for (const name of options.className.split(' ')) { + this._element.classList.add(name); + } + } + this._popup = null; + } + /** + * Attaches the `Marker` to a `Map` object. + * @param map - The MapLibre GL JS map to add the marker to. + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([30.5, 50.5]) + * .addTo(map); // add the marker to the map + * ``` + */ + addTo(map) { + this.remove(); + this._map = map; + this._element.setAttribute('aria-label', map._getUIString('Marker.Title')); + map.getCanvasContainer().appendChild(this._element); + map.on('move', this._update); + map.on('moveend', this._update); + map.on('terrain', this._update); + this.setDraggable(this._draggable); + this._update(); + // If we attached the `click` listener to the marker element, the popup + // would close once the event propagated to `map` due to the + // `Popup#_onClickClose` listener. + this._map.on('click', this._onMapClick); + return this; + } + /** + * Removes the marker from a map + * @example + * ```ts + * let marker = new Marker().addTo(map); + * marker.remove(); + * ``` + */ + remove() { + if (this._opacityTimeout) { + clearTimeout(this._opacityTimeout); + delete this._opacityTimeout; + } + if (this._map) { + this._map.off('click', this._onMapClick); + this._map.off('move', this._update); + this._map.off('moveend', this._update); + this._map.off('terrain', this._update); + this._map.off('mousedown', this._addDragHandler); + this._map.off('touchstart', this._addDragHandler); + this._map.off('mouseup', this._onUp); + this._map.off('touchend', this._onUp); + this._map.off('mousemove', this._onMove); + this._map.off('touchmove', this._onMove); + delete this._map; + } + DOM.remove(this._element); + if (this._popup) + this._popup.remove(); + return this; + } + /** + * Get the marker's geographical location. + * + * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously + * set by `setLngLat` because `Marker` wraps the anchor longitude across copies of the world to keep + * the marker on screen. + * + * @returns A {@link LngLat} describing the marker's location. + * @example + * ```ts + * // Store the marker's longitude and latitude coordinates in a variable + * let lngLat = marker.getLngLat(); + * // Print the marker's longitude and latitude values in the console + * console.log('Longitude: ' + lngLat.lng + ', Latitude: ' + lngLat.lat ) + * ``` + * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/) + */ + getLngLat() { + return this._lngLat; + } + /** + * Set the marker's geographical position and move it. + * @param lnglat - A {@link LngLat} describing where the marker should be located. + * @example + * Create a new marker, set the longitude and latitude, and add it to the map + * ```ts + * new Marker() + * .setLngLat([-65.017, -16.457]) + * .addTo(map); + * ``` + * @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/custom-marker-icons/) + * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/) + */ + setLngLat(lnglat) { + this._lngLat = performance$1.LngLat.convert(lnglat); + this._pos = null; + if (this._popup) + this._popup.setLngLat(this._lngLat); + this._update(); + return this; + } + /** + * Returns the `Marker`'s HTML element. + * @returns element + */ + getElement() { + return this._element; + } + /** + * Binds a {@link Popup} to the {@link Marker}. + * @param popup - An instance of the {@link Popup} class. If undefined or null, any popup + * set on this {@link Marker} instance is unset. + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([0, 0]) + * .setPopup(new Popup().setHTML("

Hello World!

")) // add popup + * .addTo(map); + * ``` + * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/) + */ + setPopup(popup) { + if (this._popup) { + this._popup.remove(); + this._popup = null; + this._element.removeEventListener('keypress', this._onKeyPress); + if (!this._originalTabIndex) { + this._element.removeAttribute('tabindex'); + } + } + if (popup) { + if (!('offset' in popup.options)) { + const markerHeight = 41 - (5.8 / 2); + const markerRadius = 13.5; + const linearOffset = Math.abs(markerRadius) / Math.SQRT2; + popup.options.offset = this._defaultMarker ? { + 'top': [0, 0], + 'top-left': [0, 0], + 'top-right': [0, 0], + 'bottom': [0, -markerHeight], + 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + 'left': [markerRadius, (markerHeight - markerRadius) * -1], + 'right': [-markerRadius, (markerHeight - markerRadius) * -1] + } : this._offset; + } + this._popup = popup; + this._originalTabIndex = this._element.getAttribute('tabindex'); + if (!this._originalTabIndex) { + this._element.setAttribute('tabindex', '0'); + } + this._element.addEventListener('keypress', this._onKeyPress); + } + return this; + } + /** + * Set the option to allow subpixel positioning of the marker by passing a boolean + * + * @param value - when set to `true`, subpixel positioning is enabled for the marker. + * + * @example + * ```ts + * let marker = new Marker() + * marker.setSubpixelPositioning(true); + * ``` + */ + setSubpixelPositioning(value) { + this._subpixelPositioning = value; + return this; + } + /** + * Returns the {@link Popup} instance that is bound to the {@link Marker}. + * @returns popup + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([0, 0]) + * .setPopup(new Popup().setHTML("

Hello World!

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

Hello World!

")) + * .addTo(map); + * + * marker.togglePopup(); // toggle popup open or closed + * ``` + */ + togglePopup() { + const popup = this._popup; + if (this._element.style.opacity === this._opacityWhenCovered) + return this; + if (!popup) + return this; + else if (popup.isOpen()) + popup.remove(); + else { + popup.setLngLat(this._lngLat); + popup.addTo(this._map); + } + return this; + } + _updateOpacity(force = false) { + var _a, _b; + const terrain = (_a = this._map) === null || _a === void 0 ? void 0 : _a.terrain; + if (!terrain) { + if (this._element.style.opacity !== this._opacity) { + this._element.style.opacity = this._opacity; + } + return; + } + if (force) { + this._opacityTimeout = null; + } + else { + if (this._opacityTimeout) { + return; + } + this._opacityTimeout = setTimeout(() => { + this._opacityTimeout = null; + }, 100); + } + const map = this._map; + // Read depth framebuffer, getting position of terrain in line of sight to marker + const terrainDistance = map.terrain.depthAtPoint(this._pos); + // Transform marker position to clip space + const elevation = map.terrain.getElevationForLngLatZoom(this._lngLat, map.transform.tileZoom); + const markerDistance = map.transform.lngLatToCameraDepth(this._lngLat, elevation); + const forgiveness = .006; + if (markerDistance - terrainDistance < forgiveness) { + this._element.style.opacity = this._opacity; + return; + } + // If the base is obscured, use the offset to check if the marker's center is obscured. + const metersToCenter = -this._offset.y / map.transform._pixelPerMeter; + const elevationToCenter = Math.sin(map.getPitch() * Math.PI / 180) * metersToCenter; + const terrainDistanceCenter = map.terrain.depthAtPoint(new performance$1.Point(this._pos.x, this._pos.y - this._offset.y)); + const markerDistanceCenter = map.transform.lngLatToCameraDepth(this._lngLat, elevation + elevationToCenter); + // Display at full opacity if center is visible. + const centerIsInvisible = markerDistanceCenter - terrainDistanceCenter > forgiveness; + if (((_b = this._popup) === null || _b === void 0 ? void 0 : _b.isOpen()) && centerIsInvisible) + this._popup.remove(); + this._element.style.opacity = centerIsInvisible ? this._opacityWhenCovered : this._opacity; + } + /** + * Get the marker's offset. + * @returns The marker's screen coordinates in pixels. + */ + getOffset() { + return this._offset; + } + /** + * Sets the offset of the marker + * @param offset - The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up. + */ + setOffset(offset) { + this._offset = performance$1.Point.convert(offset); + this._update(); + return this; + } + /** + * Adds a CSS class to the marker element. + * + * @param className - on-empty string with CSS class name to add to marker element + * + * @example + * ``` + * let marker = new Marker() + * marker.addClassName('some-class') + * ``` + */ + addClassName(className) { + this._element.classList.add(className); + } + /** + * Removes a CSS class from the marker element. + * + * @param className - Non-empty string with CSS class name to remove from marker element + * + * @example + * ```ts + * let marker = new Marker() + * marker.removeClassName('some-class') + * ``` + */ + removeClassName(className) { + this._element.classList.remove(className); + } + /** + * Add or remove the given CSS class on the marker element, depending on whether the element currently has that class. + * + * @param className - Non-empty string with CSS class name to add/remove + * + * @returns if the class was removed return false, if class was added, then return true + * + * @example + * ```ts + * let marker = new Marker() + * marker.toggleClassName('toggleClass') + * ``` + */ + toggleClassName(className) { + return this._element.classList.toggle(className); + } + /** + * Sets the `draggable` property and functionality of the marker + * @param shouldBeDraggable - Turns drag functionality on/off + */ + setDraggable(shouldBeDraggable) { + this._draggable = !!shouldBeDraggable; // convert possible undefined value to false + // handle case where map may not exist yet + // e.g. when setDraggable is called before addTo + if (this._map) { + if (shouldBeDraggable) { + this._map.on('mousedown', this._addDragHandler); + this._map.on('touchstart', this._addDragHandler); + } + else { + this._map.off('mousedown', this._addDragHandler); + this._map.off('touchstart', this._addDragHandler); + } + } + return this; + } + /** + * Returns true if the marker can be dragged + * @returns True if the marker is draggable. + */ + isDraggable() { + return this._draggable; + } + /** + * Sets the `rotation` property of the marker. + * @param rotation - The rotation angle of the marker (clockwise, in degrees), relative to its respective {@link Marker#setRotationAlignment} setting. + */ + setRotation(rotation) { + this._rotation = rotation || 0; + this._update(); + return this; + } + /** + * Returns the current rotation angle of the marker (in degrees). + * @returns The current rotation angle of the marker. + */ + getRotation() { + return this._rotation; + } + /** + * Sets the `rotationAlignment` property of the marker. + * @param alignment - Sets the `rotationAlignment` property of the marker. defaults to 'auto' + */ + setRotationAlignment(alignment) { + this._rotationAlignment = alignment || 'auto'; + this._update(); + return this; + } + /** + * Returns the current `rotationAlignment` property of the marker. + * @returns The current rotational alignment of the marker. + */ + getRotationAlignment() { + return this._rotationAlignment; + } + /** + * Sets the `pitchAlignment` property of the marker. + * @param alignment - Sets the `pitchAlignment` property of the marker. If alignment is 'auto', it will automatically match `rotationAlignment`. + */ + setPitchAlignment(alignment) { + this._pitchAlignment = alignment && alignment !== 'auto' ? alignment : this._rotationAlignment; + this._update(); + return this; + } + /** + * Returns the current `pitchAlignment` property of the marker. + * @returns The current pitch alignment of the marker in degrees. + */ + getPitchAlignment() { + return this._pitchAlignment; + } + /** + * Sets the `opacity` and `opacityWhenCovered` properties of the marker. + * When called without arguments, resets opacity and opacityWhenCovered to defaults + * @param opacity - Sets the `opacity` property of the marker. + * @param opacityWhenCovered - Sets the `opacityWhenCovered` property of the marker. + */ + setOpacity(opacity, opacityWhenCovered) { + if (opacity === undefined && opacityWhenCovered === undefined) { + this._opacity = '1'; + this._opacityWhenCovered = '0.2'; + } + if (opacity !== undefined) { + this._opacity = opacity; + } + if (opacityWhenCovered !== undefined) { + this._opacityWhenCovered = opacityWhenCovered; + } + if (this._map) { + this._updateOpacity(true); + } + return this; + } +} + +const defaultOptions$2 = { + positionOptions: { + enableHighAccuracy: false, + maximumAge: 0, + timeout: 6000 /* 6 sec */ + }, + fitBoundsOptions: { + maxZoom: 15 + }, + trackUserLocation: false, + showAccuracyCircle: true, + showUserLocation: true +}; +let numberOfWatches = 0; +let noTimeout = false; +/** + * A `GeolocateControl` control provides a button that uses the browser's geolocation + * API to locate the user on the map. + * + * Not all browsers support geolocation, + * and some users may disable the feature. Geolocation support for modern + * browsers including Chrome requires sites to be served over HTTPS. If + * geolocation support is not available, the `GeolocateControl` will show + * as disabled. + * + * The zoom level applied will depend on the accuracy of the geolocation provided by the device. + * + * 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: + * * 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. + * * passive - the user's location dot automatically updates, but the map's camera does not. Occurs upon the user initiating a map movement. + * * disabled - occurs if Geolocation is not available, disabled or denied. + * + * These interaction states can't be controlled programmatically, rather they are set based on user interactions. + * + * ## State Diagram + * ![GeolocateControl state diagram](https://github.com/maplibre/maplibre-gl-js/assets/3269297/78e720e5-d781-4da8-9803-a7a0e6aaaa9f) + * + * @group Markers and Controls + * + * @example + * ```ts + * map.addControl(new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * })); + * ``` + * @see [Locate the user](https://maplibre.org/maplibre-gl-js/docs/examples/locate-user/) + * + * ## Events + * + * **Event** `trackuserlocationend` of type {@link Event} will be fired when the `GeolocateControl` 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. + * + * **Event** `trackuserlocationstart` of type {@link Event} will be fired when the `GeolocateControl` 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). + * + * **Event** `userlocationlostfocus` of type {@link Event} will be fired when the `GeolocateControl` 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. + * + * **Event** `userlocationfocus` of type {@link Event} will be fired when the `GeolocateControl` changes to the active lock state, which happens upon 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. + * + * **Event** `geolocate` of type {@link Event} will be fired on each Geolocation API position update which returned as success. + * `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). + * + * **Event** `error` of type {@link Event} will be fired on each Geolocation API position update which returned as an error. + * `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). + * + * **Event** `outofmaxbounds` of type {@link Event} will be fired on each Geolocation API position update which returned as success but user position is out of map `maxBounds`. + * `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). + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a trackuserlocationend event occurs. + * geolocate.on('trackuserlocationend', () => { + * console.log('A trackuserlocationend event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a trackuserlocationstart event occurs. + * geolocate.on('trackuserlocationstart', () => { + * console.log('A trackuserlocationstart event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an userlocationlostfocus event occurs. + * geolocate.on('userlocationlostfocus', function() { + * console.log('An userlocationlostfocus event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an userlocationfocus event occurs. + * geolocate.on('userlocationfocus', function() { + * console.log('An userlocationfocus event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a geolocate event occurs. + * geolocate.on('geolocate', () => { + * console.log('A geolocate event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an error event occurs. + * geolocate.on('error', () => { + * console.log('An error event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an outofmaxbounds event occurs. + * geolocate.on('outofmaxbounds', () => { + * console.log('An outofmaxbounds event has occurred.') + * }); + * ``` + */ +class GeolocateControl extends performance$1.Evented { + /** + * @param options - the control's options + */ + constructor(options) { + super(); + /** + * When the Geolocation API returns a new location, update the `GeolocateControl`. + * + * @param position - the Geolocation API Position + */ + this._onSuccess = (position) => { + if (!this._map) { + // control has since been removed + return; + } + if (this._isOutOfMapMaxBounds(position)) { + this._setErrorState(); + this.fire(new performance$1.Event('outofmaxbounds', position)); + this._updateMarker(); + this._finish(); + return; + } + if (this.options.trackUserLocation) { + // keep a record of the position so that if the state is BACKGROUND and the user + // clicks the button, we can move to ACTIVE_LOCK immediately without waiting for + // watchPosition to trigger _onSuccess + this._lastKnownPosition = position; + switch (this._watchState) { + case 'WAITING_ACTIVE': + case 'ACTIVE_LOCK': + case 'ACTIVE_ERROR': + this._watchState = 'ACTIVE_LOCK'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active'); + break; + case 'BACKGROUND': + case 'BACKGROUND_ERROR': + this._watchState = 'BACKGROUND'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background'); + break; + default: + throw new Error(`Unexpected watchState ${this._watchState}`); + } + } + // if showUserLocation and the watch state isn't off then update the marker location + if (this.options.showUserLocation && this._watchState !== 'OFF') { + this._updateMarker(position); + } + // if in normal mode (not watch mode), or if in watch mode and the state is active watch + // then update the camera + if (!this.options.trackUserLocation || this._watchState === 'ACTIVE_LOCK') { + this._updateCamera(position); + } + if (this.options.showUserLocation) { + this._dotElement.classList.remove('maplibregl-user-location-dot-stale'); + } + this.fire(new performance$1.Event('geolocate', position)); + this._finish(); + }; + /** + * Update the camera location to center on the current position + * + * @param position - the Geolocation API Position + */ + this._updateCamera = (position) => { + const center = new performance$1.LngLat(position.coords.longitude, position.coords.latitude); + const radius = position.coords.accuracy; + const bearing = this._map.getBearing(); + const options = performance$1.extend({ bearing }, this.options.fitBoundsOptions); + const newBounds = LngLatBounds.fromLngLat(center, radius); + this._map.fitBounds(newBounds, options, { + geolocateSource: true // tag this camera change so it won't cause the control to change to background state + }); + }; + /** + * Update the user location dot Marker to the current position + * + * @param position - the Geolocation API Position + */ + this._updateMarker = (position) => { + if (position) { + const center = new performance$1.LngLat(position.coords.longitude, position.coords.latitude); + this._accuracyCircleMarker.setLngLat(center).addTo(this._map); + this._userLocationDotMarker.setLngLat(center).addTo(this._map); + this._accuracy = position.coords.accuracy; + if (this.options.showUserLocation && this.options.showAccuracyCircle) { + this._updateCircleRadius(); + } + } + else { + this._userLocationDotMarker.remove(); + this._accuracyCircleMarker.remove(); + } + }; + this._onZoom = () => { + if (this.options.showUserLocation && this.options.showAccuracyCircle) { + this._updateCircleRadius(); + } + }; + this._onError = (error) => { + if (!this._map) { + // control has since been removed + return; + } + if (this.options.trackUserLocation) { + if (error.code === 1) { + // PERMISSION_DENIED + this._watchState = 'OFF'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error'); + this._geolocateButton.disabled = true; + const title = this._map._getUIString('GeolocateControl.LocationNotAvailable'); + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + if (this._geolocationWatchID !== undefined) { + this._clearWatch(); + } + } + else if (error.code === 3 && noTimeout) { + // this represents a forced error state + // this was triggered to force immediate geolocation when a watch is already present + // see https://github.com/mapbox/mapbox-gl-js/issues/8214 + // and https://w3c.github.io/geolocation-api/#example-5-forcing-the-user-agent-to-return-a-fresh-cached-position + return; + } + else { + this._setErrorState(); + } + } + if (this._watchState !== 'OFF' && this.options.showUserLocation) { + this._dotElement.classList.add('maplibregl-user-location-dot-stale'); + } + this.fire(new performance$1.Event('error', error)); + this._finish(); + }; + this._finish = () => { + if (this._timeoutId) { + clearTimeout(this._timeoutId); + } + this._timeoutId = undefined; + }; + this._setupUI = () => { + // the control could have been removed before reaching here + if (!this._map) { + return; + } + this._container.addEventListener('contextmenu', (e) => e.preventDefault()); + this._geolocateButton = DOM.create('button', 'maplibregl-ctrl-geolocate', this._container); + DOM.create('span', 'maplibregl-ctrl-icon', this._geolocateButton).setAttribute('aria-hidden', 'true'); + this._geolocateButton.type = 'button'; + this._geolocateButton.disabled = true; + }; + this._finishSetupUI = (supported) => { + // this method is called asynchronously during onAdd + if (!this._map) { + // control has since been removed + return; + } + if (supported === false) { + performance$1.warnOnce('Geolocation support is not available so the GeolocateControl will be disabled.'); + const title = this._map._getUIString('GeolocateControl.LocationNotAvailable'); + this._geolocateButton.disabled = true; + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + } + else { + const title = this._map._getUIString('GeolocateControl.FindMyLocation'); + this._geolocateButton.disabled = false; + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + } + if (this.options.trackUserLocation) { + this._geolocateButton.setAttribute('aria-pressed', 'false'); + this._watchState = 'OFF'; + } + // when showUserLocation is enabled, keep the Geolocate button disabled until the device location marker is setup on the map + if (this.options.showUserLocation) { + this._dotElement = DOM.create('div', 'maplibregl-user-location-dot'); + this._userLocationDotMarker = new Marker({ element: this._dotElement }); + this._circleElement = DOM.create('div', 'maplibregl-user-location-accuracy-circle'); + this._accuracyCircleMarker = new Marker({ element: this._circleElement, pitchAlignment: 'map' }); + if (this.options.trackUserLocation) + this._watchState = 'OFF'; + this._map.on('zoom', this._onZoom); + } + this._geolocateButton.addEventListener('click', () => this.trigger()); + this._setup = true; + // when the camera is changed (and it's not as a result of the Geolocation Control) change + // the watch mode to background watch, so that the marker is updated but not the camera. + if (this.options.trackUserLocation) { + this._map.on('movestart', (event) => { + const fromResize = event.originalEvent && event.originalEvent.type === 'resize'; + if (!event.geolocateSource && this._watchState === 'ACTIVE_LOCK' && !fromResize) { + this._watchState = 'BACKGROUND'; + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this.fire(new performance$1.Event('trackuserlocationend')); + this.fire(new performance$1.Event('userlocationlostfocus')); + } + }); + } + }; + this.options = performance$1.extend({}, defaultOptions$2, options); + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group'); + this._setupUI(); + checkGeolocationSupport().then((supported) => this._finishSetupUI(supported)); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + // clear the geolocation watch if exists + if (this._geolocationWatchID !== undefined) { + window.navigator.geolocation.clearWatch(this._geolocationWatchID); + this._geolocationWatchID = undefined; + } + // clear the markers from the map + if (this.options.showUserLocation && this._userLocationDotMarker) { + this._userLocationDotMarker.remove(); + } + if (this.options.showAccuracyCircle && this._accuracyCircleMarker) { + this._accuracyCircleMarker.remove(); + } + DOM.remove(this._container); + this._map.off('zoom', this._onZoom); + this._map = undefined; + numberOfWatches = 0; + noTimeout = false; + } + /** + * Check if the Geolocation API Position is outside the map's `maxBounds`. + * + * @param position - the Geolocation API Position + * @returns `true` if position is outside the map's `maxBounds`, otherwise returns `false`. + */ + _isOutOfMapMaxBounds(position) { + const bounds = this._map.getMaxBounds(); + const coordinates = position.coords; + return bounds && (coordinates.longitude < bounds.getWest() || + coordinates.longitude > bounds.getEast() || + coordinates.latitude < bounds.getSouth() || + coordinates.latitude > bounds.getNorth()); + } + _setErrorState() { + switch (this._watchState) { + case 'WAITING_ACTIVE': + this._watchState = 'ACTIVE_ERROR'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active-error'); + break; + case 'ACTIVE_LOCK': + this._watchState = 'ACTIVE_ERROR'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting'); + // turn marker grey + break; + case 'BACKGROUND': + this._watchState = 'BACKGROUND_ERROR'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background-error'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting'); + // turn marker grey + break; + case 'ACTIVE_ERROR': + break; + default: + throw new Error(`Unexpected watchState ${this._watchState}`); + } + } + _updateCircleRadius() { + const bounds = this._map.getBounds(); + const southEastPoint = bounds.getSouthEast(); + const northEastPoint = bounds.getNorthEast(); + const mapHeightInMeters = southEastPoint.distanceTo(northEastPoint); + const mapHeightInPixels = this._map._container.clientHeight; + const circleDiameter = Math.ceil(2 * (this._accuracy / (mapHeightInMeters / mapHeightInPixels))); + this._circleElement.style.width = `${circleDiameter}px`; + this._circleElement.style.height = `${circleDiameter}px`; + } + /** + * Programmatically request and move the map to the user's location. + * + * @returns `false` if called before control was added to a map, otherwise returns `true`. + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * map.on('load', () => { + * geolocate.trigger(); + * }); + * ``` + */ + trigger() { + if (!this._setup) { + performance$1.warnOnce('Geolocate control triggered before added to a map'); + return false; + } + if (this.options.trackUserLocation) { + // update watchState and do any outgoing state cleanup + switch (this._watchState) { + case 'OFF': + // turn on the Geolocate Control + this._watchState = 'WAITING_ACTIVE'; + this.fire(new performance$1.Event('trackuserlocationstart')); + break; + case 'WAITING_ACTIVE': + case 'ACTIVE_LOCK': + case 'ACTIVE_ERROR': + case 'BACKGROUND_ERROR': + // turn off the Geolocate Control + numberOfWatches--; + noTimeout = false; + this._watchState = 'OFF'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error'); + this.fire(new performance$1.Event('trackuserlocationend')); + break; + case 'BACKGROUND': + this._watchState = 'ACTIVE_LOCK'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background'); + // set camera to last known location + if (this._lastKnownPosition) + this._updateCamera(this._lastKnownPosition); + this.fire(new performance$1.Event('trackuserlocationstart')); + this.fire(new performance$1.Event('userlocationfocus')); + break; + default: + throw new Error(`Unexpected watchState ${this._watchState}`); + } + // incoming state setup + switch (this._watchState) { + case 'WAITING_ACTIVE': + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active'); + break; + case 'ACTIVE_LOCK': + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active'); + break; + case 'OFF': + break; + default: + throw new Error(`Unexpected watchState ${this._watchState}`); + } + // manage geolocation.watchPosition / geolocation.clearWatch + if (this._watchState === 'OFF' && this._geolocationWatchID !== undefined) { + // clear watchPosition as we've changed to an OFF state + this._clearWatch(); + } + else if (this._geolocationWatchID === undefined) { + // enable watchPosition since watchState is not OFF and there is no watchPosition already running + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.setAttribute('aria-pressed', 'true'); + numberOfWatches++; + let positionOptions; + if (numberOfWatches > 1) { + positionOptions = { maximumAge: 600000, timeout: 0 }; + noTimeout = true; + } + else { + positionOptions = this.options.positionOptions; + noTimeout = false; + } + this._geolocationWatchID = window.navigator.geolocation.watchPosition(this._onSuccess, this._onError, positionOptions); + } + } + else { + window.navigator.geolocation.getCurrentPosition(this._onSuccess, this._onError, this.options.positionOptions); + // This timeout ensures that we still call finish() even if + // the user declines to share their location in Firefox + this._timeoutId = setTimeout(this._finish, 10000 /* 10sec */); + } + return true; + } + _clearWatch() { + window.navigator.geolocation.clearWatch(this._geolocationWatchID); + this._geolocationWatchID = undefined; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.setAttribute('aria-pressed', 'false'); + if (this.options.showUserLocation) { + this._updateMarker(null); + } + } +} + +const defaultOptions$1 = { + maxWidth: 100, + unit: 'metric' +}; +/** + * A `ScaleControl` control displays the ratio of a distance on the map to the corresponding distance on the ground. + * + * @group Markers and Controls + * + * @example + * ```ts + * let scale = new ScaleControl({ + * maxWidth: 80, + * unit: 'imperial' + * }); + * map.addControl(scale); + * + * scale.setUnit('metric'); + * ``` + */ +class ScaleControl { + /** + * @param options - the control's options + */ + constructor(options) { + this._onMove = () => { + updateScale(this._map, this._container, this.options); + }; + /** + * Set the scale's unit of the distance + * + * @param unit - Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`). + */ + this.setUnit = (unit) => { + this.options.unit = unit; + updateScale(this._map, this._container, this.options); + }; + this.options = Object.assign(Object.assign({}, defaultOptions$1), options); + } + getDefaultPosition() { + return 'bottom-left'; + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-scale', map.getContainer()); + this._map.on('move', this._onMove); + this._onMove(); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + this._map.off('move', this._onMove); + this._map = undefined; + } +} +function updateScale(map, container, options) { + // A horizontal scale is imagined to be present at center of the map + // container with maximum length (Default) as 100px. + // Using spherical law of cosines approximation, the real distance is + // found between the two coordinates. + const maxWidth = options && options.maxWidth || 100; + const y = map._container.clientHeight / 2; + const left = map.unproject([0, y]); + const right = map.unproject([maxWidth, y]); + const maxMeters = left.distanceTo(right); + // The real distance corresponding to 100px scale length is rounded off to + // near pretty number and the scale length for the same is found out. + // Default unit of the scale is based on User's locale. + if (options && options.unit === 'imperial') { + const maxFeet = 3.2808 * maxMeters; + if (maxFeet > 5280) { + const maxMiles = maxFeet / 5280; + setScale(container, maxWidth, maxMiles, map._getUIString('ScaleControl.Miles')); + } + else { + setScale(container, maxWidth, maxFeet, map._getUIString('ScaleControl.Feet')); + } + } + else if (options && options.unit === 'nautical') { + const maxNauticals = maxMeters / 1852; + setScale(container, maxWidth, maxNauticals, map._getUIString('ScaleControl.NauticalMiles')); + } + else if (maxMeters >= 1000) { + setScale(container, maxWidth, maxMeters / 1000, map._getUIString('ScaleControl.Kilometers')); + } + else { + setScale(container, maxWidth, maxMeters, map._getUIString('ScaleControl.Meters')); + } +} +function setScale(container, maxWidth, maxDistance, unit) { + const distance = getRoundNum(maxDistance); + const ratio = distance / maxDistance; + container.style.width = `${maxWidth * ratio}px`; + container.innerHTML = `${distance} ${unit}`; +} +function getDecimalRoundNum(d) { + const multiplier = Math.pow(10, Math.ceil(-Math.log(d) / Math.LN10)); + return Math.round(d * multiplier) / multiplier; +} +function getRoundNum(num) { + const pow10 = Math.pow(10, (`${Math.floor(num)}`).length - 1); + let d = num / pow10; + d = d >= 10 ? 10 : + d >= 5 ? 5 : + d >= 3 ? 3 : + d >= 2 ? 2 : + d >= 1 ? 1 : getDecimalRoundNum(d); + return pow10 * d; +} + +/** + * A `FullscreenControl` control contains a button for toggling the map in and out of fullscreen mode. + * When [requestFullscreen](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen) is not supported, fullscreen is handled via CSS properties. + * The map's `cooperativeGestures` option is temporarily disabled while the map + * is in fullscreen mode, and is restored when the map exist fullscreen mode. + * + * @group Markers and Controls + * @param options - the full screen control options + * + * @example + * ```ts + * map.addControl(new FullscreenControl({container: document.querySelector('body')})); + * ``` + * @see [View a fullscreen map](https://maplibre.org/maplibre-gl-js/docs/examples/fullscreen/) + * + * ## Events + * + * **Event** `fullscreenstart` of type {@link Event} will be fired when fullscreen mode has started. + * + * **Event** `fullscreenend` of type {@link Event} will be fired when fullscreen mode has ended. + */ +class FullscreenControl extends performance$1.Evented { + /** + * @param options - the control's options + */ + constructor(options = {}) { + super(); + this._onFullscreenChange = () => { + var _a; + let fullscreenElement = window.document.fullscreenElement || + window.document.mozFullScreenElement || + window.document.webkitFullscreenElement || + window.document.msFullscreenElement; + while ((_a = fullscreenElement === null || fullscreenElement === void 0 ? void 0 : fullscreenElement.shadowRoot) === null || _a === void 0 ? void 0 : _a.fullscreenElement) { + fullscreenElement = fullscreenElement.shadowRoot.fullscreenElement; + } + if ((fullscreenElement === this._container) !== this._fullscreen) { + this._handleFullscreenChange(); + } + }; + this._onClickFullscreen = () => { + if (this._isFullscreen()) { + this._exitFullscreen(); + } + else { + this._requestFullscreen(); + } + }; + this._fullscreen = false; + if (options && options.container) { + if (options.container instanceof HTMLElement) { + this._container = options.container; + } + else { + performance$1.warnOnce('Full screen control \'container\' must be a DOM element.'); + } + } + if ('onfullscreenchange' in document) { + this._fullscreenchange = 'fullscreenchange'; + } + else if ('onmozfullscreenchange' in document) { + this._fullscreenchange = 'mozfullscreenchange'; + } + else if ('onwebkitfullscreenchange' in document) { + this._fullscreenchange = 'webkitfullscreenchange'; + } + else if ('onmsfullscreenchange' in document) { + this._fullscreenchange = 'MSFullscreenChange'; + } + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + if (!this._container) + this._container = this._map.getContainer(); + this._controlContainer = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group'); + this._setupUI(); + return this._controlContainer; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._controlContainer); + this._map = null; + window.document.removeEventListener(this._fullscreenchange, this._onFullscreenChange); + } + _setupUI() { + const button = this._fullscreenButton = DOM.create('button', (('maplibregl-ctrl-fullscreen')), this._controlContainer); + DOM.create('span', 'maplibregl-ctrl-icon', button).setAttribute('aria-hidden', 'true'); + button.type = 'button'; + this._updateTitle(); + this._fullscreenButton.addEventListener('click', this._onClickFullscreen); + window.document.addEventListener(this._fullscreenchange, this._onFullscreenChange); + } + _updateTitle() { + const title = this._getTitle(); + this._fullscreenButton.setAttribute('aria-label', title); + this._fullscreenButton.title = title; + } + _getTitle() { + return this._map._getUIString(this._isFullscreen() ? 'FullscreenControl.Exit' : 'FullscreenControl.Enter'); + } + _isFullscreen() { + return this._fullscreen; + } + _handleFullscreenChange() { + this._fullscreen = !this._fullscreen; + this._fullscreenButton.classList.toggle('maplibregl-ctrl-shrink'); + this._fullscreenButton.classList.toggle('maplibregl-ctrl-fullscreen'); + this._updateTitle(); + if (this._fullscreen) { + this.fire(new performance$1.Event('fullscreenstart')); + this._prevCooperativeGesturesEnabled = this._map.cooperativeGestures.isEnabled(); + this._map.cooperativeGestures.disable(); + } + else { + this.fire(new performance$1.Event('fullscreenend')); + if (this._prevCooperativeGesturesEnabled) { + this._map.cooperativeGestures.enable(); + } + } + } + _exitFullscreen() { + if (window.document.exitFullscreen) { + window.document.exitFullscreen(); + } + else if (window.document.mozCancelFullScreen) { + window.document.mozCancelFullScreen(); + } + else if (window.document.msExitFullscreen) { + window.document.msExitFullscreen(); + } + else if (window.document.webkitCancelFullScreen) { + window.document.webkitCancelFullScreen(); + } + else { + this._togglePseudoFullScreen(); + } + } + _requestFullscreen() { + if (this._container.requestFullscreen) { + this._container.requestFullscreen(); + } + else if (this._container.mozRequestFullScreen) { + this._container.mozRequestFullScreen(); + } + else if (this._container.msRequestFullscreen) { + this._container.msRequestFullscreen(); + } + else if (this._container.webkitRequestFullscreen) { + this._container.webkitRequestFullscreen(); + } + else { + this._togglePseudoFullScreen(); + } + } + _togglePseudoFullScreen() { + this._container.classList.toggle('maplibregl-pseudo-fullscreen'); + this._handleFullscreenChange(); + this._map.resize(); + } +} + +/** + * A `TerrainControl` control contains a button for turning the terrain on and off. + * + * @group Markers and Controls + * + * @example + * ```ts + * let map = new Map({TerrainControl: false}) + * .addControl(new TerrainControl({ + * source: "terrain" + * })); + * ``` + */ +class TerrainControl { + /** + * @param options - the control's options + */ + constructor(options) { + this._toggleTerrain = () => { + if (this._map.getTerrain()) { + this._map.setTerrain(null); + } + else { + this._map.setTerrain(this.options); + } + this._updateTerrainIcon(); + }; + this._updateTerrainIcon = () => { + this._terrainButton.classList.remove('maplibregl-ctrl-terrain'); + this._terrainButton.classList.remove('maplibregl-ctrl-terrain-enabled'); + if (this._map.terrain) { + this._terrainButton.classList.add('maplibregl-ctrl-terrain-enabled'); + this._terrainButton.title = this._map._getUIString('TerrainControl.Disable'); + } + else { + this._terrainButton.classList.add('maplibregl-ctrl-terrain'); + this._terrainButton.title = this._map._getUIString('TerrainControl.Enable'); + } + }; + this.options = options; + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group'); + this._terrainButton = DOM.create('button', 'maplibregl-ctrl-terrain', this._container); + DOM.create('span', 'maplibregl-ctrl-icon', this._terrainButton).setAttribute('aria-hidden', 'true'); + this._terrainButton.type = 'button'; + this._terrainButton.addEventListener('click', this._toggleTerrain); + this._updateTerrainIcon(); + this._map.on('terrain', this._updateTerrainIcon); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + this._map.off('terrain', this._updateTerrainIcon); + this._map = undefined; + } +} + +const defaultOptions = { + closeButton: true, + closeOnClick: true, + focusAfterOpen: true, + className: '', + maxWidth: '240px', + subpixelPositioning: false +}; +const focusQuerySelector = [ + 'a[href]', + '[tabindex]:not([tabindex=\'-1\'])', + '[contenteditable]:not([contenteditable=\'false\'])', + 'button:not([disabled])', + 'input:not([disabled])', + 'select:not([disabled])', + 'textarea:not([disabled])', +].join(', '); +/** + * A popup component. + * + * @group Markers and Controls + * + * + * @example + * Create a popup + * ```ts + * let popup = new Popup(); + * // Set an event listener that will fire + * // any time the popup is opened + * popup.on('open', () => { + * console.log('popup was opened'); + * }); + * ``` + * + * @example + * Create a popup + * ```ts + * let popup = new Popup(); + * // Set an event listener that will fire + * // any time the popup is closed + * popup.on('close', () => { + * console.log('popup was closed'); + * }); + * ``` + * + * @example + * ```ts + * let markerHeight = 50, markerRadius = 10, linearOffset = 25; + * let popupOffsets = { + * 'top': [0, 0], + * 'top-left': [0,0], + * 'top-right': [0,0], + * 'bottom': [0, -markerHeight], + * 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + * 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + * 'left': [markerRadius, (markerHeight - markerRadius) * -1], + * 'right': [-markerRadius, (markerHeight - markerRadius) * -1] + * }; + * let popup = new Popup({offset: popupOffsets, className: 'my-class'}) + * .setLngLat(e.lngLat) + * .setHTML("

Hello World!

") + * .setMaxWidth("300px") + * .addTo(map); + * ``` + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/) + * + * ## Events + * + * **Event** `open` of type {@link Event} will be fired when the popup is opened manually or programmatically. + * + * **Event** `close` of type {@link Event} will be fired when the popup is closed manually or programmatically. + */ +class Popup extends performance$1.Evented { + /** + * @param options - the options + */ + constructor(options) { + super(); + /** + * Removes the popup from the map it has been added to. + * + * @example + * ```ts + * let popup = new Popup().addTo(map); + * popup.remove(); + * ``` + */ + this.remove = () => { + if (this._content) { + DOM.remove(this._content); + } + if (this._container) { + DOM.remove(this._container); + delete this._container; + } + if (this._map) { + this._map.off('move', this._update); + this._map.off('move', this._onClose); + this._map.off('click', this._onClose); + this._map.off('remove', this.remove); + this._map.off('mousemove', this._onMouseMove); + this._map.off('mouseup', this._onMouseUp); + this._map.off('drag', this._onDrag); + this._map._canvasContainer.classList.remove('maplibregl-track-pointer'); + delete this._map; + this.fire(new performance$1.Event('close')); + } + return this; + }; + this._onMouseUp = (event) => { + this._update(event.point); + }; + this._onMouseMove = (event) => { + this._update(event.point); + }; + this._onDrag = (event) => { + this._update(event.point); + }; + this._update = (cursor) => { + var _a; + const hasPosition = this._lngLat || this._trackPointer; + if (!this._map || !hasPosition || !this._content) { + return; + } + if (!this._container) { + this._container = DOM.create('div', 'maplibregl-popup', this._map.getContainer()); + this._tip = DOM.create('div', 'maplibregl-popup-tip', this._container); + this._container.appendChild(this._content); + if (this.options.className) { + for (const name of this.options.className.split(' ')) { + this._container.classList.add(name); + } + } + if (this._closeButton) { + this._closeButton.setAttribute('aria-label', this._map._getUIString('Popup.Close')); + } + if (this._trackPointer) { + this._container.classList.add('maplibregl-popup-track-pointer'); + } + } + if (this.options.maxWidth && this._container.style.maxWidth !== this.options.maxWidth) { + this._container.style.maxWidth = this.options.maxWidth; + } + if (this._map.transform.renderWorldCopies && !this._trackPointer) { + this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map.transform); + } + else { + this._lngLat = (_a = this._lngLat) === null || _a === void 0 ? void 0 : _a.wrap(); + } + if (this._trackPointer && !cursor) + return; + const pos = this._flatPos = this._pos = this._trackPointer && cursor ? cursor : this._map.project(this._lngLat); + if (this._map.terrain) { + // flat position is saved because smartWrap needs non-elevated points + this._flatPos = this._trackPointer && cursor ? cursor : this._map.transform.locationPoint(this._lngLat); + } + let anchor = this.options.anchor; + const offset = normalizeOffset(this.options.offset); + if (!anchor) { + const width = this._container.offsetWidth; + const height = this._container.offsetHeight; + let anchorComponents; + if (pos.y + offset.bottom.y < height) { + anchorComponents = ['top']; + } + else if (pos.y > this._map.transform.height - height) { + anchorComponents = ['bottom']; + } + else { + anchorComponents = []; + } + if (pos.x < width / 2) { + anchorComponents.push('left'); + } + else if (pos.x > this._map.transform.width - width / 2) { + anchorComponents.push('right'); + } + if (anchorComponents.length === 0) { + anchor = 'bottom'; + } + else { + anchor = anchorComponents.join('-'); + } + } + let offsetedPos = pos.add(offset[anchor]); + if (!this.options.subpixelPositioning) { + offsetedPos = offsetedPos.round(); + } + DOM.setTransform(this._container, `${anchorTranslate[anchor]} translate(${offsetedPos.x}px,${offsetedPos.y}px)`); + applyAnchorClass(this._container, anchor, 'popup'); + }; + this._onClose = () => { + this.remove(); + }; + this.options = performance$1.extend(Object.create(defaultOptions), options); + } + /** + * Adds the popup to a map. + * + * @param map - The MapLibre GL JS map to add the popup to. + * @example + * ```ts + * new Popup() + * .setLngLat([0, 0]) + * .setHTML("

Null Island

") + * .addTo(map); + * ``` + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + * @see [Show polygon information on click](https://maplibre.org/maplibre-gl-js/docs/examples/polygon-popup-on-click/) + */ + addTo(map) { + if (this._map) + this.remove(); + this._map = map; + if (this.options.closeOnClick) { + this._map.on('click', this._onClose); + } + if (this.options.closeOnMove) { + this._map.on('move', this._onClose); + } + this._map.on('remove', this.remove); + this._update(); + this._focusFirstElement(); + if (this._trackPointer) { + this._map.on('mousemove', this._onMouseMove); + this._map.on('mouseup', this._onMouseUp); + if (this._container) { + this._container.classList.add('maplibregl-popup-track-pointer'); + } + this._map._canvasContainer.classList.add('maplibregl-track-pointer'); + } + else { + this._map.on('move', this._update); + } + this.fire(new performance$1.Event('open')); + return this; + } + /** + * @returns `true` if the popup is open, `false` if it is closed. + */ + isOpen() { + return !!this._map; + } + /** + * Returns the geographical location of the popup's anchor. + * + * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously + * set by `setLngLat` because `Popup` wraps the anchor longitude across copies of the world to keep + * the popup on screen. + * + * @returns The geographical location of the popup's anchor. + */ + getLngLat() { + return this._lngLat; + } + /** + * Sets the geographical location of the popup's anchor, and moves the popup to it. Replaces trackPointer() behavior. + * + * @param lnglat - The geographical location to set as the popup's anchor. + */ + setLngLat(lnglat) { + this._lngLat = performance$1.LngLat.convert(lnglat); + this._pos = null; + this._flatPos = null; + this._trackPointer = false; + this._update(); + if (this._map) { + this._map.on('move', this._update); + this._map.off('mousemove', this._onMouseMove); + if (this._container) { + this._container.classList.remove('maplibregl-popup-track-pointer'); + } + this._map._canvasContainer.classList.remove('maplibregl-track-pointer'); + } + return this; + } + /** + * Tracks the popup anchor to the cursor position on screens with a pointer device (it will be hidden on touchscreens). Replaces the `setLngLat` behavior. + * For most use cases, set `closeOnClick` and `closeButton` to `false`. + * @example + * ```ts + * let popup = new Popup({ closeOnClick: false, closeButton: false }) + * .setHTML("

Hello World!

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

Hello World!

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

Hello World!

") + * .addTo(map); + * ``` + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/) + */ + setHTML(html) { + const frag = document.createDocumentFragment(); + const temp = document.createElement('body'); + let child; + temp.innerHTML = html; + while (true) { + child = temp.firstChild; + if (!child) + break; + frag.appendChild(child); + } + return this.setDOMContent(frag); + } + /** + * Returns the popup's maximum width. + * + * @returns The maximum width of the popup. + */ + getMaxWidth() { + var _a; + return (_a = this._container) === null || _a === void 0 ? void 0 : _a.style.maxWidth; + } + /** + * Sets the popup's maximum width. This is setting the CSS property `max-width`. + * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width + * + * @param maxWidth - A string representing the value for the maximum width. + */ + setMaxWidth(maxWidth) { + this.options.maxWidth = maxWidth; + this._update(); + return this; + } + /** + * Sets the popup's content to the element provided as a DOM node. + * + * @param htmlNode - A DOM node to be used as content for the popup. + * @example + * Create an element with the popup content + * ```ts + * let div = document.createElement('div'); + * div.innerHTML = 'Hello, world!'; + * let popup = new Popup() + * .setLngLat(e.lngLat) + * .setDOMContent(div) + * .addTo(map); + * ``` + */ + setDOMContent(htmlNode) { + if (this._content) { + // Clear out children first. + while (this._content.hasChildNodes()) { + if (this._content.firstChild) { + this._content.removeChild(this._content.firstChild); + } + } + } + else { + this._content = DOM.create('div', 'maplibregl-popup-content', this._container); + } + // The close button should be the last tabbable element inside the popup for a good keyboard UX. + this._content.appendChild(htmlNode); + this._createCloseButton(); + this._update(); + this._focusFirstElement(); + return this; + } + /** + * Adds a CSS class to the popup container element. + * + * @param className - Non-empty string with CSS class name to add to popup container + * + * @example + * ```ts + * let popup = new Popup() + * popup.addClassName('some-class') + * ``` + */ + addClassName(className) { + if (this._container) { + this._container.classList.add(className); + } + return this; + } + /** + * Removes a CSS class from the popup container element. + * + * @param className - Non-empty string with CSS class name to remove from popup container + * + * @example + * ```ts + * let popup = new Popup() + * popup.removeClassName('some-class') + * ``` + */ + removeClassName(className) { + if (this._container) { + this._container.classList.remove(className); + } + return this; + } + /** + * Sets the popup's offset. + * + * @param offset - Sets the popup's offset. + */ + setOffset(offset) { + this.options.offset = offset; + this._update(); + return this; + } + /** + * Add or remove the given CSS class on the popup container, depending on whether the container currently has that class. + * + * @param className - Non-empty string with CSS class name to add/remove + * + * @returns if the class was removed return false, if class was added, then return true, undefined if there is no container + * + * @example + * ```ts + * let popup = new Popup() + * popup.toggleClassName('toggleClass') + * ``` + */ + toggleClassName(className) { + if (this._container) { + return this._container.classList.toggle(className); + } + } + /** + * Set the option to allow subpixel positioning of the popup by passing a boolean + * + * @param value - When boolean is true, subpixel positioning is enabled for the popup. + * + * @example + * ```ts + * let popup = new Popup() + * popup.setSubpixelPositioning(true); + * ``` + */ + setSubpixelPositioning(value) { + this.options.subpixelPositioning = value; + } + _createCloseButton() { + if (this.options.closeButton) { + this._closeButton = DOM.create('button', 'maplibregl-popup-close-button', this._content); + this._closeButton.type = 'button'; + this._closeButton.innerHTML = '×'; + this._closeButton.addEventListener('click', this._onClose); + } + } + _focusFirstElement() { + if (!this.options.focusAfterOpen || !this._container) + return; + const firstFocusable = this._container.querySelector(focusQuerySelector); + if (firstFocusable) + firstFocusable.focus(); + } +} +function normalizeOffset(offset) { + if (!offset) { + return normalizeOffset(new performance$1.Point(0, 0)); + } + else if (typeof offset === 'number') { + // input specifies a radius from which to calculate offsets at all positions + const cornerOffset = Math.round(Math.abs(offset) / Math.SQRT2); + return { + 'center': new performance$1.Point(0, 0), + 'top': new performance$1.Point(0, offset), + 'top-left': new performance$1.Point(cornerOffset, cornerOffset), + 'top-right': new performance$1.Point(-cornerOffset, cornerOffset), + 'bottom': new performance$1.Point(0, -offset), + 'bottom-left': new performance$1.Point(cornerOffset, -cornerOffset), + 'bottom-right': new performance$1.Point(-cornerOffset, -cornerOffset), + 'left': new performance$1.Point(offset, 0), + 'right': new performance$1.Point(-offset, 0) + }; + } + else if (offset instanceof performance$1.Point || Array.isArray(offset)) { + // input specifies a single offset to be applied to all positions + const convertedOffset = performance$1.Point.convert(offset); + return { + 'center': convertedOffset, + 'top': convertedOffset, + 'top-left': convertedOffset, + 'top-right': convertedOffset, + 'bottom': convertedOffset, + 'bottom-left': convertedOffset, + 'bottom-right': convertedOffset, + 'left': convertedOffset, + 'right': convertedOffset + }; + } + else { + // input specifies an offset per position + return { + 'center': performance$1.Point.convert(offset['center'] || [0, 0]), + 'top': performance$1.Point.convert(offset['top'] || [0, 0]), + 'top-left': performance$1.Point.convert(offset['top-left'] || [0, 0]), + 'top-right': performance$1.Point.convert(offset['top-right'] || [0, 0]), + 'bottom': performance$1.Point.convert(offset['bottom'] || [0, 0]), + 'bottom-left': performance$1.Point.convert(offset['bottom-left'] || [0, 0]), + 'bottom-right': performance$1.Point.convert(offset['bottom-right'] || [0, 0]), + 'left': performance$1.Point.convert(offset['left'] || [0, 0]), + 'right': performance$1.Point.convert(offset['right'] || [0, 0]) + }; + } +} + +const version = packageJSON.version; +/** + * Sets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text). + * Necessary for supporting the Arabic and Hebrew languages, which are written right-to-left. + * + * @param pluginURL - URL pointing to the Mapbox RTL text plugin source. + * @param lazy - If set to `true`, maplibre will defer loading the plugin until rtl text is encountered, + * rtl text will then be rendered only after the plugin finishes loading. + * @example + * ```ts + * setRTLTextPlugin('https://unpkg.com/@mapbox/mapbox-gl-rtl-text@0.2.3/mapbox-gl-rtl-text.js', false); + * ``` + * @see [Add support for right-to-left scripts](https://maplibre.org/maplibre-gl-js/docs/examples/mapbox-gl-rtl-text/) + */ +function setRTLTextPlugin(pluginURL, lazy) { + return rtlMainThreadPluginFactory().setRTLTextPlugin(pluginURL, lazy); +} +/** + * Gets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text) status. + * The status can be `unavailable` (i.e. not requested or removed), `loading`, `loaded` or `error`. + * If the status is `loaded` and the plugin is requested again, an error will be thrown. + * + * @example + * ```ts + * const pluginStatus = getRTLTextPluginStatus(); + * ``` + */ +function getRTLTextPluginStatus() { + return rtlMainThreadPluginFactory().getRTLTextPluginStatus(); +} +/** + * Returns the package version of the library + * @returns Package version of the library + */ +function getVersion() { return version; } +/** + * Gets the number of web workers instantiated on a page with GL JS maps. + * By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3). + * Make sure to set this property before creating any map instances for it to have effect. + * + * @returns Number of workers currently configured. + * @example + * ```ts + * const workerCount = getWorkerCount() + * ``` + */ +function getWorkerCount() { return WorkerPool.workerCount; } +/** + * Sets the number of web workers instantiated on a page with GL JS maps. + * By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3). + * Make sure to set this property before creating any map instances for it to have effect. + * + * @example + * ```ts + * setWorkerCount(2); + * ``` + */ +function setWorkerCount(count) { WorkerPool.workerCount = count; } +/** + * Gets and sets the maximum number of images (raster tiles, sprites, icons) to load in parallel, + * which affects performance in raster-heavy maps. 16 by default. + * + * @returns Number of parallel requests currently configured. + * @example + * ```ts + * getMaxParallelImageRequests(); + * ``` + */ +function getMaxParallelImageRequests() { return performance$1.config.MAX_PARALLEL_IMAGE_REQUESTS; } +/** + * Sets the maximum number of images (raster tiles, sprites, icons) to load in parallel, + * which affects performance in raster-heavy maps. 16 by default. + * + * @example + * ```ts + * setMaxParallelImageRequests(10); + * ``` + */ +function setMaxParallelImageRequests(numRequests) { performance$1.config.MAX_PARALLEL_IMAGE_REQUESTS = numRequests; } +/** + * Gets the worker url + * @returns The worker url + */ +function getWorkerUrl() { return performance$1.config.WORKER_URL; } +/** + * Sets the worker url + */ +function setWorkerUrl(value) { performance$1.config.WORKER_URL = value; } +/** + * Allows loading javascript code in the worker thread. + * *Note* that since this is using some very internal classes and flows it is considered experimental and can break at any point. + * + * It can be useful for the following examples: + * 1. Using `self.addProtocol` in the worker thread - note that you might need to also register the protocol on the main thread. + * 2. Using `self.registerWorkerSource(workerSource: WorkerSource)` to register a worker source, which should come with `addSourceType` usually. + * 3. using `self.actor.registerMessageHandler` to override some internal worker operations + * @param workerUrl - the worker url e.g. a url of a javascript file to load in the worker + * @returns + * + * @example + * ```ts + * // below is an example of sending a js file to the worker to load the method there + * // Note that you'll need to call the global function `addProtocol` in the worker to register the protocol there. + * // add-protocol-worker.js + * async function loadFn(params, abortController) { + * const t = await fetch(`https://${params.url.split("://")[1]}`); + * if (t.status == 200) { + * const buffer = await t.arrayBuffer(); + * return {data: buffer} + * } else { + * throw new Error(`Tile fetch error: ${t.statusText}`); + * } + * } + * self.addProtocol('custom', loadFn); + * + * // main.js + * importScriptInWorkers('add-protocol-worker.js'); + * ``` + */ +function importScriptInWorkers(workerUrl) { return getGlobalDispatcher().broadcast("IS" /* MessageType.importScript */, workerUrl); } + +exports.AJAXError = performance$1.AJAXError; +exports.Evented = performance$1.Evented; +exports.LngLat = performance$1.LngLat; +exports.MercatorCoordinate = performance$1.MercatorCoordinate; +exports.Point = performance$1.Point; +exports.addProtocol = performance$1.addProtocol; +exports.config = performance$1.config; +exports.removeProtocol = performance$1.removeProtocol; +exports.AttributionControl = AttributionControl; +exports.BoxZoomHandler = BoxZoomHandler; +exports.CanvasSource = CanvasSource; +exports.CooperativeGesturesHandler = CooperativeGesturesHandler; +exports.DoubleClickZoomHandler = DoubleClickZoomHandler; +exports.DragPanHandler = DragPanHandler; +exports.DragRotateHandler = DragRotateHandler; +exports.EdgeInsets = EdgeInsets; +exports.FullscreenControl = FullscreenControl; +exports.GeoJSONSource = GeoJSONSource; +exports.GeolocateControl = GeolocateControl; +exports.Hash = Hash; +exports.ImageSource = ImageSource; +exports.KeyboardHandler = KeyboardHandler; +exports.LngLatBounds = LngLatBounds; +exports.LogoControl = LogoControl; +exports.Map = Map$1; +exports.MapMouseEvent = MapMouseEvent; +exports.MapTouchEvent = MapTouchEvent; +exports.MapWheelEvent = MapWheelEvent; +exports.Marker = Marker; +exports.NavigationControl = NavigationControl; +exports.Popup = Popup; +exports.RasterDEMTileSource = RasterDEMTileSource; +exports.RasterTileSource = RasterTileSource; +exports.ScaleControl = ScaleControl; +exports.ScrollZoomHandler = ScrollZoomHandler; +exports.Style = Style; +exports.TerrainControl = TerrainControl; +exports.TwoFingersTouchPitchHandler = TwoFingersTouchPitchHandler; +exports.TwoFingersTouchRotateHandler = TwoFingersTouchRotateHandler; +exports.TwoFingersTouchZoomHandler = TwoFingersTouchZoomHandler; +exports.TwoFingersTouchZoomRotateHandler = TwoFingersTouchZoomRotateHandler; +exports.VectorTileSource = VectorTileSource; +exports.VideoSource = VideoSource; +exports.addSourceType = addSourceType; +exports.clearPrewarmedResources = clearPrewarmedResources; +exports.getMaxParallelImageRequests = getMaxParallelImageRequests; +exports.getRTLTextPluginStatus = getRTLTextPluginStatus; +exports.getVersion = getVersion; +exports.getWorkerCount = getWorkerCount; +exports.getWorkerUrl = getWorkerUrl; +exports.importScriptInWorkers = importScriptInWorkers; +exports.prewarm = prewarm; +exports.setMaxParallelImageRequests = setMaxParallelImageRequests; +exports.setRTLTextPlugin = setRTLTextPlugin; +exports.setWorkerCount = setWorkerCount; +exports.setWorkerUrl = setWorkerUrl; + +})); + +// +// Our custom intro provides a specialized "define()" function, called by the +// AMD modules below, that sets up the worker blob URL and then executes the +// main module, storing its exported value as 'maplibregl' + + +var maplibregl$1 = maplibregl; + +return maplibregl$1; + +})); +//# sourceMappingURL=maplibre-gl-dev.js.map diff --git a/dist/maplibre-gl-unminified.js b/dist/maplibre-gl-unminified.js new file mode 100644 index 0000000000..eb9d74bd79 --- /dev/null +++ b/dist/maplibre-gl-unminified.js @@ -0,0 +1,52814 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v4.7.0/LICENSE.txt + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.maplibregl = factory()); +})(this, (function () { 'use strict'; + +/* eslint-disable */ + +var maplibregl = {}; +var modules = {}; +function define(moduleName, _dependencies, moduleFactory) { + modules[moduleName] = moduleFactory; + + // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) + if (moduleName !== 'index') { + return; + } + + // we assume that when an index module is initializing then other modules are loaded already + var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);' + + var sharedModule = {}; + // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) + // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) + // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following + modules.shared(sharedModule); + modules.index(maplibregl, sharedModule); + + if (typeof window !== 'undefined') { + maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); + } + + return maplibregl; +}; + + + +define('shared', ['exports'], (function (exports) { 'use strict'; + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +function getDefaultExportFromCjs$1 (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var pointGeometry = Point$1; + +/** + * A standalone point geometry with useful accessor, comparison, and + * modification methods. + * + * @class Point + * @param {Number} x the x-coordinate. this could be longitude or screen + * pixels, or any other sort of unit. + * @param {Number} y the y-coordinate. this could be latitude or screen + * pixels, or any other sort of unit. + * @example + * var point = new Point(-77, 38); + */ +function Point$1(x, y) { + this.x = x; + this.y = y; +} + +Point$1.prototype = { + + /** + * Clone this point, returning a new point that can be modified + * without affecting the old one. + * @return {Point} the clone + */ + clone: function() { return new Point$1(this.x, this.y); }, + + /** + * Add this point's x & y coordinates to another point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + add: function(p) { return this.clone()._add(p); }, + + /** + * Subtract this point's x & y coordinates to from point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + sub: function(p) { return this.clone()._sub(p); }, + + /** + * Multiply this point's x & y coordinates by point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + multByPoint: function(p) { return this.clone()._multByPoint(p); }, + + /** + * Divide this point's x & y coordinates by point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + divByPoint: function(p) { return this.clone()._divByPoint(p); }, + + /** + * Multiply this point's x & y coordinates by a factor, + * yielding a new point. + * @param {Point} k factor + * @return {Point} output point + */ + mult: function(k) { return this.clone()._mult(k); }, + + /** + * Divide this point's x & y coordinates by a factor, + * yielding a new point. + * @param {Point} k factor + * @return {Point} output point + */ + div: function(k) { return this.clone()._div(k); }, + + /** + * Rotate this point around the 0, 0 origin by an angle a, + * given in radians + * @param {Number} a angle to rotate around, in radians + * @return {Point} output point + */ + rotate: function(a) { return this.clone()._rotate(a); }, + + /** + * Rotate this point around p point by an angle a, + * given in radians + * @param {Number} a angle to rotate around, in radians + * @param {Point} p Point to rotate around + * @return {Point} output point + */ + rotateAround: function(a,p) { return this.clone()._rotateAround(a,p); }, + + /** + * Multiply this point by a 4x1 transformation matrix + * @param {Array} m transformation matrix + * @return {Point} output point + */ + matMult: function(m) { return this.clone()._matMult(m); }, + + /** + * Calculate this point but as a unit vector from 0, 0, meaning + * that the distance from the resulting point to the 0, 0 + * coordinate will be equal to 1 and the angle from the resulting + * point to the 0, 0 coordinate will be the same as before. + * @return {Point} unit vector point + */ + unit: function() { return this.clone()._unit(); }, + + /** + * Compute a perpendicular point, where the new y coordinate + * is the old x coordinate and the new x coordinate is the old y + * coordinate multiplied by -1 + * @return {Point} perpendicular point + */ + perp: function() { return this.clone()._perp(); }, + + /** + * Return a version of this point with the x & y coordinates + * rounded to integers. + * @return {Point} rounded point + */ + round: function() { return this.clone()._round(); }, + + /** + * Return the magitude of this point: this is the Euclidean + * distance from the 0, 0 coordinate to this point's x and y + * coordinates. + * @return {Number} magnitude + */ + mag: function() { + return Math.sqrt(this.x * this.x + this.y * this.y); + }, + + /** + * Judge whether this point is equal to another point, returning + * true or false. + * @param {Point} other the other point + * @return {boolean} whether the points are equal + */ + equals: function(other) { + return this.x === other.x && + this.y === other.y; + }, + + /** + * Calculate the distance from this point to another point + * @param {Point} p the other point + * @return {Number} distance + */ + dist: function(p) { + return Math.sqrt(this.distSqr(p)); + }, + + /** + * Calculate the distance from this point to another point, + * without the square root step. Useful if you're comparing + * relative distances. + * @param {Point} p the other point + * @return {Number} distance + */ + distSqr: function(p) { + var dx = p.x - this.x, + dy = p.y - this.y; + return dx * dx + dy * dy; + }, + + /** + * Get the angle from the 0, 0 coordinate to this point, in radians + * coordinates. + * @return {Number} angle + */ + angle: function() { + return Math.atan2(this.y, this.x); + }, + + /** + * Get the angle from this point to another point, in radians + * @param {Point} b the other point + * @return {Number} angle + */ + angleTo: function(b) { + return Math.atan2(this.y - b.y, this.x - b.x); + }, + + /** + * Get the angle between this point and another point, in radians + * @param {Point} b the other point + * @return {Number} angle + */ + angleWith: function(b) { + return this.angleWithSep(b.x, b.y); + }, + + /* + * Find the angle of the two vectors, solving the formula for + * the cross product a x b = |a||b|sin(θ) for θ. + * @param {Number} x the x-coordinate + * @param {Number} y the y-coordinate + * @return {Number} the angle in radians + */ + angleWithSep: function(x, y) { + return Math.atan2( + this.x * y - this.y * x, + this.x * x + this.y * y); + }, + + _matMult: function(m) { + var x = m[0] * this.x + m[1] * this.y, + y = m[2] * this.x + m[3] * this.y; + this.x = x; + this.y = y; + return this; + }, + + _add: function(p) { + this.x += p.x; + this.y += p.y; + return this; + }, + + _sub: function(p) { + this.x -= p.x; + this.y -= p.y; + return this; + }, + + _mult: function(k) { + this.x *= k; + this.y *= k; + return this; + }, + + _div: function(k) { + this.x /= k; + this.y /= k; + return this; + }, + + _multByPoint: function(p) { + this.x *= p.x; + this.y *= p.y; + return this; + }, + + _divByPoint: function(p) { + this.x /= p.x; + this.y /= p.y; + return this; + }, + + _unit: function() { + this._div(this.mag()); + return this; + }, + + _perp: function() { + var y = this.y; + this.y = this.x; + this.x = -y; + return this; + }, + + _rotate: function(angle) { + var cos = Math.cos(angle), + sin = Math.sin(angle), + x = cos * this.x - sin * this.y, + y = sin * this.x + cos * this.y; + this.x = x; + this.y = y; + return this; + }, + + _rotateAround: function(angle, p) { + var cos = Math.cos(angle), + sin = Math.sin(angle), + x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y), + y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y); + this.x = x; + this.y = y; + return this; + }, + + _round: function() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } +}; + +/** + * Construct a point from an array if necessary, otherwise if the input + * is already a Point, or an unknown type, return it unchanged + * @param {Array|Point|*} a any kind of input value + * @return {Point} constructed point, or passed-through value. + * @example + * // this + * var point = Point.convert([0, 1]); + * // is equivalent to + * var point = new Point(0, 1); + */ +Point$1.convert = function (a) { + if (a instanceof Point$1) { + return a; + } + if (Array.isArray(a)) { + return new Point$1(a[0], a[1]); + } + return a; +}; + +var Point$2 = /*@__PURE__*/getDefaultExportFromCjs$1(pointGeometry); + +var unitbezier$1 = UnitBezier$2; + +function UnitBezier$2(p1x, p1y, p2x, p2y) { + // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). + this.cx = 3.0 * p1x; + this.bx = 3.0 * (p2x - p1x) - this.cx; + this.ax = 1.0 - this.cx - this.bx; + + this.cy = 3.0 * p1y; + this.by = 3.0 * (p2y - p1y) - this.cy; + this.ay = 1.0 - this.cy - this.by; + + this.p1x = p1x; + this.p1y = p1y; + this.p2x = p2x; + this.p2y = p2y; +} + +UnitBezier$2.prototype = { + sampleCurveX: function (t) { + // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. + return ((this.ax * t + this.bx) * t + this.cx) * t; + }, + + sampleCurveY: function (t) { + return ((this.ay * t + this.by) * t + this.cy) * t; + }, + + sampleCurveDerivativeX: function (t) { + return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; + }, + + solveCurveX: function (x, epsilon) { + if (epsilon === undefined) epsilon = 1e-6; + + if (x < 0.0) return 0.0; + if (x > 1.0) return 1.0; + + var t = x; + + // First try a few iterations of Newton's method - normally very fast. + for (var i = 0; i < 8; i++) { + var x2 = this.sampleCurveX(t) - x; + if (Math.abs(x2) < epsilon) return t; + + var d2 = this.sampleCurveDerivativeX(t); + if (Math.abs(d2) < 1e-6) break; + + t = t - x2 / d2; + } + + // Fall back to the bisection method for reliability. + var t0 = 0.0; + var t1 = 1.0; + t = x; + + for (i = 0; i < 20; i++) { + x2 = this.sampleCurveX(t); + if (Math.abs(x2 - x) < epsilon) break; + + if (x > x2) { + t0 = t; + } else { + t1 = t; + } + + t = (t1 - t0) * 0.5 + t0; + } + + return t; + }, + + solve: function (x, epsilon) { + return this.sampleCurveY(this.solveCurveX(x, epsilon)); + } +}; + +var UnitBezier$3 = /*@__PURE__*/getDefaultExportFromCjs$1(unitbezier$1); + +let supportsOffscreenCanvas; +function offscreenCanvasSupported() { + if (supportsOffscreenCanvas == null) { + supportsOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && + new OffscreenCanvas(1, 1).getContext('2d') && + typeof createImageBitmap === 'function'; + } + return supportsOffscreenCanvas; +} + +let offscreenCanvasDistorted; +/** + * Some browsers don't return the exact pixels from a canvas to prevent user fingerprinting (see #3185). + * This function writes pixels to an OffscreenCanvas and reads them back using getImageData, returning false + * if they don't match. + * + * @returns true if the browser supports OffscreenCanvas but it distorts getImageData results, false otherwise. + */ +function isOffscreenCanvasDistorted() { + if (offscreenCanvasDistorted == null) { + offscreenCanvasDistorted = false; + if (offscreenCanvasSupported()) { + const size = 5; + const canvas = new OffscreenCanvas(size, size); + const context = canvas.getContext('2d', { willReadFrequently: true }); + if (context) { + // fill each pixel with an RGB value that should make the byte at index i equal to i (except alpha channel): + // [0, 1, 2, 255, 4, 5, 6, 255, 8, 9, 10, 255, ...] + for (let i = 0; i < size * size; i++) { + const base = i * 4; + context.fillStyle = `rgb(${base},${base + 1},${base + 2})`; + context.fillRect(i % size, Math.floor(i / size), 1, 1); + } + const data = context.getImageData(0, 0, size, size).data; + for (let i = 0; i < size * size * 4; i++) { + if (i % 4 !== 3 && data[i] !== i) { + offscreenCanvasDistorted = true; + break; + } + } + } + } + } + return offscreenCanvasDistorted || false; +} + +/** + * For a given collection of 2D points, returns their axis-aligned bounding box, + * in the format [minX, minY, maxX, maxY]. + */ +function getAABB(points) { + let tlX = Infinity; + let tlY = Infinity; + let brX = -Infinity; + let brY = -Infinity; + for (const p of points) { + tlX = Math.min(tlX, p.x); + tlY = Math.min(tlY, p.y); + brX = Math.max(brX, p.x); + brY = Math.max(brY, p.y); + } + return [tlX, tlY, brX, brY]; +} +/** + * Given a value `t` that varies between 0 and 1, return + * an interpolation function that eases between 0 and 1 in a pleasing + * cubic in-out fashion. + */ +function easeCubicInOut(t) { + if (t <= 0) + return 0; + if (t >= 1) + return 1; + const t2 = t * t, t3 = t2 * t; + return 4 * (t < 0.5 ? t3 : 3 * (t - t2) + t3 - 0.75); +} +/** + * Given given (x, y), (x1, y1) control points for a bezier curve, + * return a function that interpolates along that curve. + * + * @param p1x - control point 1 x coordinate + * @param p1y - control point 1 y coordinate + * @param p2x - control point 2 x coordinate + * @param p2y - control point 2 y coordinate + */ +function bezier(p1x, p1y, p2x, p2y) { + const bezier = new UnitBezier$3(p1x, p1y, p2x, p2y); + return (t) => { + return bezier.solve(t); + }; +} +/** + * A default bezier-curve powered easing function with + * control points (0.25, 0.1) and (0.25, 1) + */ +const defaultEasing = bezier(0.25, 0.1, 0.25, 1); +/** + * constrain n to the given range via min + max + * + * @param n - value + * @param min - the minimum value to be returned + * @param max - the maximum value to be returned + * @returns the clamped value + */ +function clamp$1(n, min, max) { + return Math.min(max, Math.max(min, n)); +} +/** + * constrain n to the given range, excluding the minimum, via modular arithmetic + * + * @param n - value + * @param min - the minimum value to be returned, exclusive + * @param max - the maximum value to be returned, inclusive + * @returns constrained number + */ +function wrap(n, min, max) { + const d = max - min; + const w = ((n - min) % d + d) % d + min; + return (w === min) ? max : w; +} +/** + * Compute the difference between the keys in one object and the keys + * in another object. + * + * @returns keys difference + */ +function keysDifference(obj, other) { + const difference = []; + for (const i in obj) { + if (!(i in other)) { + difference.push(i); + } + } + return difference; +} +function extend(dest, ...sources) { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; +} +/** + * Given an object and a number of properties as strings, return version + * of that object with only those properties. + * + * @param src - the object + * @param properties - an array of property names chosen + * to appear on the resulting object. + * @returns object with limited properties. + * @example + * ```ts + * let foo = { name: 'Charlie', age: 10 }; + * let justName = pick(foo, ['name']); // justName = { name: 'Charlie' } + * ``` + */ +function pick(src, properties) { + const result = {}; + for (let i = 0; i < properties.length; i++) { + const k = properties[i]; + if (k in src) { + result[k] = src[k]; + } + } + return result; +} +let id = 1; +/** + * Return a unique numeric id, starting at 1 and incrementing with + * each call. + * + * @returns unique numeric id. + */ +function uniqueId() { + return id++; +} +/** + * Return whether a given value is a power of two + */ +function isPowerOfTwo(value) { + return (Math.log(value) / Math.LN2) % 1 === 0; +} +/** + * Return the next power of two, or the input value if already a power of two + */ +function nextPowerOfTwo(value) { + if (value <= 1) + return 1; + return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2)); +} +/** + * Create an object by mapping all the values of an existing object while + * preserving their keys. + */ +function mapObject(input, iterator, context) { + const output = {}; + for (const key in input) { + output[key] = iterator.call(this, input[key], key, input); + } + return output; +} +/** + * Create an object by filtering out values of an existing object. + */ +function filterObject(input, iterator, context) { + const output = {}; + for (const key in input) { + if (iterator.call(this, input[key], key, input)) { + output[key] = input[key]; + } + } + return output; +} +/** + * Deeply compares two object literals. + * @param a - first object literal to be compared + * @param b - second object literal to be compared + * @returns true if the two object literals are deeply equal, false otherwise + */ +function deepEqual$1(a, b) { + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) { + if (!deepEqual$1(a[i], b[i])) + return false; + } + return true; + } + if (typeof a === 'object' && a !== null && b !== null) { + if (!(typeof b === 'object')) + return false; + const keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) + return false; + for (const key in a) { + if (!deepEqual$1(a[key], b[key])) + return false; + } + return true; + } + return a === b; +} +/** + * Deeply clones two objects. + */ +function clone$1(input) { + if (Array.isArray(input)) { + return input.map(clone$1); + } + else if (typeof input === 'object' && input) { + return mapObject(input, clone$1); + } + else { + return input; + } +} +/** + * Check if two arrays have at least one common element. + */ +function arraysIntersect(a, b) { + for (let l = 0; l < a.length; l++) { + if (b.indexOf(a[l]) >= 0) + return true; + } + return false; +} +/** + * Print a warning message to the console and ensure duplicate warning messages + * are not printed. + */ +const warnOnceHistory = {}; +function warnOnce(message) { + if (!warnOnceHistory[message]) { + // console isn't defined in some WebWorkers, see #2558 + if (typeof console !== 'undefined') + console.warn(message); + warnOnceHistory[message] = true; + } +} +/** + * Indicates if the provided Points are in a counter clockwise (true) or clockwise (false) order + * + * @returns true for a counter clockwise set of points + */ +// https://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/ +function isCounterClockwise(a, b, c) { + return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x); +} +/** + * For two lines a and b in 2d space, defined by any two points along the lines, + * find the intersection point, or return null if the lines are parallel + * + * @param a1 - First point on line a + * @param a2 - Second point on line a + * @param b1 - First point on line b + * @param b2 - Second point on line b + * + * @returns the intersection point of the two lines or null if they are parallel + */ +function findLineIntersection(a1, a2, b1, b2) { + const aDeltaY = a2.y - a1.y; + const aDeltaX = a2.x - a1.x; + const bDeltaY = b2.y - b1.y; + const bDeltaX = b2.x - b1.x; + const denominator = (bDeltaY * aDeltaX) - (bDeltaX * aDeltaY); + if (denominator === 0) { + // Lines are parallel + return null; + } + const originDeltaY = a1.y - b1.y; + const originDeltaX = a1.x - b1.x; + const aInterpolation = (bDeltaX * originDeltaY - bDeltaY * originDeltaX) / denominator; + // Find intersection by projecting out from origin of first segment + return new Point$2(a1.x + (aInterpolation * aDeltaX), a1.y + (aInterpolation * aDeltaY)); +} +/** + * Converts spherical coordinates to cartesian coordinates. + * + * @param spherical - Spherical coordinates, in [radial, azimuthal, polar] + * @returns cartesian coordinates in [x, y, z] + */ +function sphericalToCartesian([r, azimuthal, polar]) { + // We abstract "north"/"up" (compass-wise) to be 0° when really this is 90° (π/2): + // correct for that here + azimuthal += 90; + // Convert azimuthal and polar angles to radians + azimuthal *= Math.PI / 180; + polar *= Math.PI / 180; + return { + x: r * Math.cos(azimuthal) * Math.sin(polar), + y: r * Math.sin(azimuthal) * Math.sin(polar), + z: r * Math.cos(polar) + }; +} +/** + * Returns true if the when run in the web-worker context. + * + * @returns `true` if the when run in the web-worker context. + */ +function isWorker(self) { + // @ts-ignore + return typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof WorkerGlobalScope; +} +/** + * Parses data from 'Cache-Control' headers. + * + * @param cacheControl - Value of 'Cache-Control' header + * @returns object containing parsed header info. + */ +function parseCacheControl(cacheControl) { + // Taken from [Wreck](https://github.com/hapijs/wreck) + const re = /(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g; + const header = {}; + cacheControl.replace(re, ($0, $1, $2, $3) => { + const value = $2 || $3; + header[$1] = value ? value.toLowerCase() : true; + return ''; + }); + if (header['max-age']) { + const maxAge = parseInt(header['max-age'], 10); + if (isNaN(maxAge)) + delete header['max-age']; + else + header['max-age'] = maxAge; + } + return header; +} +let _isSafari = null; +/** + * Returns true when run in WebKit derived browsers. + * This is used as a workaround for a memory leak in Safari caused by using Transferable objects to + * transfer data between WebWorkers and the main thread. + * https://github.com/mapbox/mapbox-gl-js/issues/8771 + * + * This should be removed once the underlying Safari issue is fixed. + * + * @param scope - Since this function is used both on the main thread and WebWorker context, + * let the calling scope pass in the global scope object. + * @returns `true` when run in WebKit derived browsers. + */ +function isSafari(scope) { + if (_isSafari == null) { + const userAgent = scope.navigator ? scope.navigator.userAgent : null; + _isSafari = !!scope.safari || + !!(userAgent && (/\b(iPad|iPhone|iPod)\b/.test(userAgent) || (!!userAgent.match('Safari') && !userAgent.match('Chrome')))); + } + return _isSafari; +} +function isImageBitmap(image) { + return typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap; +} +/** + * Converts an ArrayBuffer to an ImageBitmap. + * + * Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work + * perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting + * ArrayBuffers. + * + * @param data - Data to convert + * @returns - A promise resolved when the conversion is finished + */ +const arrayBufferToImageBitmap = (data) => __awaiter(void 0, void 0, void 0, function* () { + if (data.byteLength === 0) { + return createImageBitmap(new ImageData(1, 1)); + } + const blob = new Blob([new Uint8Array(data)], { type: 'image/png' }); + try { + return createImageBitmap(blob); + } + catch (e) { + throw 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.`); + } +}); +const transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII='; +/** + * Converts an ArrayBuffer to an HTMLImageElement. + * + * Used mostly for testing purposes only, because mocking libs don't know how to work with ArrayBuffers, but work + * perfectly fine with ImageBitmaps. Might also be used for environments (other than testing) not supporting + * ArrayBuffers. + * + * @param data - Data to convert + * @returns - A promise resolved when the conversion is finished + */ +const arrayBufferToImage = (data) => { + return new Promise((resolve, reject) => { + const img = new Image(); + img.onload = () => { + resolve(img); + URL.revokeObjectURL(img.src); + // prevent image dataURI memory leak in Safari; + // but don't free the image immediately because it might be uploaded in the next frame + // https://github.com/mapbox/mapbox-gl-js/issues/10226 + img.onload = null; + window.requestAnimationFrame(() => { img.src = transparentPngUrl; }); + }; + img.onerror = () => reject(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.')); + const blob = new Blob([new Uint8Array(data)], { type: 'image/png' }); + img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl; + }); +}; +/** + * Computes the webcodecs VideoFrame API options to select a rectangle out of + * an image and write it into the destination rectangle. + * + * Rect (x/y/width/height) select the overlapping rectangle from the source image + * and layout (offset/stride) write that overlapping rectangle to the correct place + * in the destination image. + * + * Offset is the byte offset in the dest image that the first pixel appears at + * and stride is the number of bytes to the start of the next row: + * ┌───────────┐ + * │ dest │ + * │ ┌───┼───────┐ + * │offset→│▓▓▓│ source│ + * │ │▓▓▓│ │ + * │ └───┼───────┘ + * │stride ⇠╌╌╌│ + * │╌╌╌╌╌╌→ │ + * └───────────┘ + * + * @param image - source image containing a width and height attribute + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns the layout and rect options to pass into VideoFrame API + */ +function computeVideoFrameParameters(image, x, y, width, height) { + const destRowOffset = Math.max(-x, 0) * 4; + const firstSourceRow = Math.max(0, y); + const firstDestRow = firstSourceRow - y; + const offset = firstDestRow * width * 4 + destRowOffset; + const stride = width * 4; + const sourceLeft = Math.max(0, x); + const sourceTop = Math.max(0, y); + const sourceRight = Math.min(image.width, x + width); + const sourceBottom = Math.min(image.height, y + height); + return { + rect: { + x: sourceLeft, + y: sourceTop, + width: sourceRight - sourceLeft, + height: sourceBottom - sourceTop + }, + layout: [{ offset, stride }] + }; +} +/** + * Reads pixels from an ImageBitmap/Image/canvas using webcodec VideoFrame API. + * + * @param data - image, imagebitmap, or canvas to parse + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred + */ +function readImageUsingVideoFrame(image, x, y, width, height) { + return __awaiter(this, void 0, void 0, function* () { + if (typeof VideoFrame === 'undefined') { + throw new Error('VideoFrame not supported'); + } + const frame = new VideoFrame(image, { timestamp: 0 }); + try { + const format = frame === null || frame === void 0 ? void 0 : frame.format; + if (!format || !(format.startsWith('BGR') || format.startsWith('RGB'))) { + throw new Error(`Unrecognized format ${format}`); + } + const swapBR = format.startsWith('BGR'); + const result = new Uint8ClampedArray(width * height * 4); + yield frame.copyTo(result, computeVideoFrameParameters(image, x, y, width, height)); + if (swapBR) { + for (let i = 0; i < result.length; i += 4) { + const tmp = result[i]; + result[i] = result[i + 2]; + result[i + 2] = tmp; + } + } + return result; + } + finally { + frame.close(); + } + }); +} +let offscreenCanvas; +let offscreenCanvasContext; +/** + * Reads pixels from an ImageBitmap/Image/canvas using OffscreenCanvas + * + * @param data - image, imagebitmap, or canvas to parse + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns a promise containing the parsed RGBA pixel values of the image, or the error if an error occurred + */ +function readImageDataUsingOffscreenCanvas(imgBitmap, x, y, width, height) { + const origWidth = imgBitmap.width; + const origHeight = imgBitmap.height; + // Lazily initialize OffscreenCanvas + if (!offscreenCanvas || !offscreenCanvasContext) { + // Dem tiles are typically 256x256 + offscreenCanvas = new OffscreenCanvas(origWidth, origHeight); + offscreenCanvasContext = offscreenCanvas.getContext('2d', { willReadFrequently: true }); + } + offscreenCanvas.width = origWidth; + offscreenCanvas.height = origHeight; + offscreenCanvasContext.drawImage(imgBitmap, 0, 0, origWidth, origHeight); + const imgData = offscreenCanvasContext.getImageData(x, y, width, height); + offscreenCanvasContext.clearRect(0, 0, origWidth, origHeight); + return imgData.data; +} +/** + * Reads RGBA pixels from an preferring OffscreenCanvas, but falling back to VideoFrame if supported and + * the browser is mangling OffscreenCanvas getImageData results. + * + * @param data - image, imagebitmap, or canvas to parse + * @param x - top-left x coordinate to read from the image + * @param y - top-left y coordinate to read from the image + * @param width - width of the rectangle to read from the image + * @param height - height of the rectangle to read from the image + * @returns a promise containing the parsed RGBA pixel values of the image + */ +function getImageData(image, x, y, width, height) { + return __awaiter(this, void 0, void 0, function* () { + if (isOffscreenCanvasDistorted()) { + try { + return yield readImageUsingVideoFrame(image, x, y, width, height); + } + catch (e) { + // fall back to OffscreenCanvas + } + } + return readImageDataUsingOffscreenCanvas(image, x, y, width, height); + }); +} +/** + * This method is used in order to register an event listener using a lambda function. + * The return value will allow unsubscribing from the event, without the need to store the method reference. + * @param target - The target + * @param message - The message + * @param listener - The listener + * @param options - The options + * @returns a subscription object that can be used to unsubscribe from the event + */ +function subscribe(target, message, listener, options) { + target.addEventListener(message, listener, options); + return { + unsubscribe: () => { + target.removeEventListener(message, listener, options); + } + }; +} +/** + * This method converts degrees to radians. + * The return value is the radian value. + * @param degrees - The number of degrees + * @returns radians + */ +function degreesToRadians(degrees) { + return degrees * Math.PI / 180; +} +/** + * The maximum world tile zoom (Z). + * In other words, the upper bound supported for tile zoom. + */ +const MAX_TILE_ZOOM = 25; +/** + * The minimum world tile zoom (Z). + * In other words, the lower bound supported for tile zoom. + */ +const MIN_TILE_ZOOM = 0; + +/** + * An error message to use when an operation is aborted + */ +const ABORT_ERROR = 'AbortError'; +/** + * Check if an error is an abort error + * @param error - An error object + * @returns - true if the error is an abort error + */ +function isAbortError(error) { + return error.message === ABORT_ERROR; +} +/** + * Use this when you need to create an abort error. + * @returns An error object with the message "AbortError" + */ +function createAbortError() { + return new Error(ABORT_ERROR); +} + +const config = { + MAX_PARALLEL_IMAGE_REQUESTS: 16, + MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME: 8, + MAX_TILE_CACHE_ZOOM_LEVELS: 5, + REGISTERED_PROTOCOLS: {}, + WORKER_URL: '' +}; + +function getProtocol(url) { + return config.REGISTERED_PROTOCOLS[url.substring(0, url.indexOf('://'))]; +} +/** + * Adds a custom load resource function that will be called when using a URL that starts with a custom url schema. + * This will happen in the main thread, and workers might call it if they don't know how to handle the protocol. + * The example below will be triggered for custom:// urls defined in the sources list in the style definitions. + * The function passed will receive the request parameters and should return with the resulting resource, + * for example a pbf vector tile, non-compressed, represented as ArrayBuffer. + * + * @param customProtocol - the protocol to hook, for example 'custom' + * @param loadFn - the function to use when trying to fetch a tile specified by the customProtocol + * @example + * ```ts + * // This will fetch a file using the fetch API (this is obviously a non interesting example...) + * addProtocol('custom', async (params, abortController) => { + * const t = await fetch(`https://${params.url.split("://")[1]}`); + * if (t.status == 200) { + * const buffer = await t.arrayBuffer(); + * return {data: buffer} + * } else { + * throw new Error(`Tile fetch error: ${t.statusText}`); + * } + * }); + * // the following is an example of a way to return an error when trying to load a tile + * addProtocol('custom2', async (params, abortController) => { + * throw new Error('someErrorMessage')); + * }); + * ``` + */ +function addProtocol(customProtocol, loadFn) { + config.REGISTERED_PROTOCOLS[customProtocol] = loadFn; +} +/** + * Removes a previously added protocol in the main thread. + * + * @param customProtocol - the custom protocol to remove registration for + * @example + * ```ts + * removeProtocol('custom'); + * ``` + */ +function removeProtocol(customProtocol) { + delete config.REGISTERED_PROTOCOLS[customProtocol]; +} + +/** + * This is used to identify the global dispatcher id when sending a message from the worker without a target map id. + */ +const GLOBAL_DISPATCHER_ID = 'global-dispatcher'; +/** + * An error thrown when a HTTP request results in an error response. + */ +class AJAXError extends Error { + /** + * @param status - The response's HTTP status code. + * @param statusText - The response's HTTP status text. + * @param url - The request's URL. + * @param body - The response's body. + */ + constructor(status, statusText, url, body) { + super(`AJAXError: ${statusText} (${status}): ${url}`); + this.status = status; + this.statusText = statusText; + this.url = url; + this.body = body; + } +} +/** + * Ensure that we're sending the correct referrer from blob URL worker bundles. + * For files loaded from the local file system, `location.origin` will be set + * to the string(!) "null" (Firefox), or "file://" (Chrome, Safari, Edge), + * and we will set an empty referrer. Otherwise, we're using the document's URL. + */ +const getReferrer = () => isWorker(self) ? + self.worker && self.worker.referrer : + (window.location.protocol === 'blob:' ? window.parent : window).location.href; +/** + * Determines whether a URL is a file:// URL. This is obviously the case if it begins + * with file://. Relative URLs are also file:// URLs iff the original document was loaded + * via a file:// URL. + * @param url - The URL to check + * @returns `true` if the URL is a file:// URL, `false` otherwise + */ +const isFileURL = url => /^file:/.test(url) || (/^file:/.test(getReferrer()) && !/^\w+:/.test(url)); +function makeFetchRequest(requestParameters, abortController) { + return __awaiter(this, void 0, void 0, function* () { + const request = new Request(requestParameters.url, { + method: requestParameters.method || 'GET', + body: requestParameters.body, + credentials: requestParameters.credentials, + headers: requestParameters.headers, + cache: requestParameters.cache, + referrer: getReferrer(), + signal: abortController.signal + }); + // If the user has already set an Accept header, do not overwrite it here + if (requestParameters.type === 'json' && !request.headers.has('Accept')) { + request.headers.set('Accept', 'application/json'); + } + const response = yield fetch(request); + if (!response.ok) { + const body = yield response.blob(); + throw new AJAXError(response.status, response.statusText, requestParameters.url, body); + } + let parsePromise; + if ((requestParameters.type === 'arrayBuffer' || requestParameters.type === 'image')) { + parsePromise = response.arrayBuffer(); + } + else if (requestParameters.type === 'json') { + parsePromise = response.json(); + } + else { + parsePromise = response.text(); + } + const result = yield parsePromise; + if (abortController.signal.aborted) { + throw createAbortError(); + } + return { data: result, cacheControl: response.headers.get('Cache-Control'), expires: response.headers.get('Expires') }; + }); +} +function makeXMLHttpRequest(requestParameters, abortController) { + return new Promise((resolve, reject) => { + var _a; + const xhr = new XMLHttpRequest(); + xhr.open(requestParameters.method || 'GET', requestParameters.url, true); + if (requestParameters.type === 'arrayBuffer' || requestParameters.type === 'image') { + xhr.responseType = 'arraybuffer'; + } + for (const k in requestParameters.headers) { + xhr.setRequestHeader(k, requestParameters.headers[k]); + } + if (requestParameters.type === 'json') { + xhr.responseType = 'text'; + // Do not overwrite the user-provided Accept header + if (!((_a = requestParameters.headers) === null || _a === void 0 ? void 0 : _a.Accept)) { + xhr.setRequestHeader('Accept', 'application/json'); + } + } + xhr.withCredentials = requestParameters.credentials === 'include'; + xhr.onerror = () => { + reject(new Error(xhr.statusText)); + }; + xhr.onload = () => { + if (abortController.signal.aborted) { + return; + } + if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response !== null) { + let data = xhr.response; + if (requestParameters.type === 'json') { + // We're manually parsing JSON here to get better error messages. + try { + data = JSON.parse(xhr.response); + } + catch (err) { + reject(err); + return; + } + } + resolve({ data, cacheControl: xhr.getResponseHeader('Cache-Control'), expires: xhr.getResponseHeader('Expires') }); + } + else { + const body = new Blob([xhr.response], { type: xhr.getResponseHeader('Content-Type') }); + reject(new AJAXError(xhr.status, xhr.statusText, requestParameters.url, body)); + } + }; + abortController.signal.addEventListener('abort', () => { + xhr.abort(); + reject(createAbortError()); + }); + xhr.send(requestParameters.body); + }); +} +/** + * We're trying to use the Fetch API if possible. However, requests for resources with the file:// URI scheme don't work with the Fetch API. + * In this case we unconditionally use XHR on the current thread since referrers don't matter. + * This method can also use the registered method if `addProtocol` was called. + * @param requestParameters - The request parameters + * @param abortController - The abort controller allowing to cancel the request + * @returns a promise resolving to the response, including cache control and expiry data + */ +const makeRequest = function (requestParameters, abortController) { + if (/:\/\//.test(requestParameters.url) && !(/^https?:|^file:/.test(requestParameters.url))) { + const protocolLoadFn = getProtocol(requestParameters.url); + if (protocolLoadFn) { + return protocolLoadFn(requestParameters, abortController); + } + if (isWorker(self) && self.worker && self.worker.actor) { + return self.worker.actor.sendAsync({ type: "GR" /* MessageType.getResource */, data: requestParameters, targetMapId: GLOBAL_DISPATCHER_ID }, abortController); + } + } + if (!isFileURL(requestParameters.url)) { + if (fetch && Request && AbortController && Object.prototype.hasOwnProperty.call(Request.prototype, 'signal')) { + return makeFetchRequest(requestParameters, abortController); + } + if (isWorker(self) && self.worker && self.worker.actor) { + return self.worker.actor.sendAsync({ type: "GR" /* MessageType.getResource */, data: requestParameters, mustQueue: true, targetMapId: GLOBAL_DISPATCHER_ID }, abortController); + } + } + return makeXMLHttpRequest(requestParameters, abortController); +}; +const getJSON = (requestParameters, abortController) => { + return makeRequest(extend(requestParameters, { type: 'json' }), abortController); +}; +const getArrayBuffer = (requestParameters, abortController) => { + return makeRequest(extend(requestParameters, { type: 'arrayBuffer' }), abortController); +}; +function sameOrigin(inComingUrl) { + // A relative URL "/foo" or "./foo" will throw exception in URL's ctor, + // try-catch is expansive so just use a heuristic check to avoid it + // also check data URL + if (!inComingUrl || + inComingUrl.indexOf('://') <= 0 || // relative URL + inComingUrl.indexOf('data:image/') === 0 || // data image URL + inComingUrl.indexOf('blob:') === 0) { // blob + return true; + } + const urlObj = new URL(inComingUrl); + const locationObj = window.location; + return urlObj.protocol === locationObj.protocol && urlObj.host === locationObj.host; +} +const getVideo = (urls) => { + const video = window.document.createElement('video'); + video.muted = true; + return new Promise((resolve) => { + video.onloadstart = () => { + resolve(video); + }; + for (const url of urls) { + const s = window.document.createElement('source'); + if (!sameOrigin(url)) { + video.crossOrigin = 'Anonymous'; + } + s.src = url; + video.appendChild(s); + } + }); +}; + +function _addEventListener(type, listener, listenerList) { + const listenerExists = listenerList[type] && listenerList[type].indexOf(listener) !== -1; + if (!listenerExists) { + listenerList[type] = listenerList[type] || []; + listenerList[type].push(listener); + } +} +function _removeEventListener(type, listener, listenerList) { + if (listenerList && listenerList[type]) { + const index = listenerList[type].indexOf(listener); + if (index !== -1) { + listenerList[type].splice(index, 1); + } + } +} +/** + * The event class + */ +class Event { + constructor(type, data = {}) { + extend(this, data); + this.type = type; + } +} +/** + * An error event + */ +class ErrorEvent extends Event { + constructor(error, data = {}) { + super('error', extend({ error }, data)); + } +} +/** + * Methods mixed in to other classes for event capabilities. + * + * @group Event Related + */ +class Evented { + /** + * Adds a listener to a specified event type. + * + * @param type - The event type to add a listen for. + * @param listener - The function to be called when the event is fired. + * The listener function is called with the data object passed to `fire`, + * extended with `target` and `type` properties. + */ + on(type, listener) { + this._listeners = this._listeners || {}; + _addEventListener(type, listener, this._listeners); + return this; + } + /** + * Removes a previously registered event listener. + * + * @param type - The event type to remove listeners for. + * @param listener - The listener function to remove. + */ + off(type, listener) { + _removeEventListener(type, listener, this._listeners); + _removeEventListener(type, listener, this._oneTimeListeners); + return this; + } + /** + * Adds a listener that will be called only once to a specified event type. + * + * The listener will be called first time the event fires after the listener is registered. + * + * @param type - The event type to listen for. + * @param listener - The function to be called when the event is fired the first time. + * @returns `this` or a promise if a listener is not provided + */ + once(type, listener) { + if (!listener) { + return new Promise((resolve) => this.once(type, resolve)); + } + this._oneTimeListeners = this._oneTimeListeners || {}; + _addEventListener(type, listener, this._oneTimeListeners); + return this; + } + fire(event, properties) { + // Compatibility with (type: string, properties: Object) signature from previous versions. + // See https://github.com/mapbox/mapbox-gl-js/issues/6522, + // https://github.com/mapbox/mapbox-gl-draw/issues/766 + if (typeof event === 'string') { + event = new Event(event, properties || {}); + } + const type = event.type; + if (this.listens(type)) { + event.target = this; + // make sure adding or removing listeners inside other listeners won't cause an infinite loop + const listeners = this._listeners && this._listeners[type] ? this._listeners[type].slice() : []; + for (const listener of listeners) { + listener.call(this, event); + } + const oneTimeListeners = this._oneTimeListeners && this._oneTimeListeners[type] ? this._oneTimeListeners[type].slice() : []; + for (const listener of oneTimeListeners) { + _removeEventListener(type, listener, this._oneTimeListeners); + listener.call(this, event); + } + const parent = this._eventedParent; + if (parent) { + extend(event, typeof this._eventedParentData === 'function' ? this._eventedParentData() : this._eventedParentData); + parent.fire(event); + } + // To ensure that no error events are dropped, print them to the + // console if they have no listeners. + } + else if (event instanceof ErrorEvent) { + console.error(event.error); + } + return this; + } + /** + * Returns a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type. + * + * @param type - The event type + * @returns `true` if there is at least one registered listener for specified event type, `false` otherwise + */ + listens(type) { + return ((this._listeners && this._listeners[type] && this._listeners[type].length > 0) || + (this._oneTimeListeners && this._oneTimeListeners[type] && this._oneTimeListeners[type].length > 0) || + (this._eventedParent && this._eventedParent.listens(type))); + } + /** + * Bubble all events fired by this instance of Evented to this parent instance of Evented. + */ + setEventedParent(parent, data) { + this._eventedParent = parent; + this._eventedParentData = data; + return this; + } +} + +var $version = 8; +var $root = { + version: { + required: true, + type: "enum", + values: [ + 8 + ] + }, + name: { + type: "string" + }, + metadata: { + type: "*" + }, + center: { + type: "array", + value: "number" + }, + zoom: { + type: "number" + }, + bearing: { + type: "number", + "default": 0, + period: 360, + units: "degrees" + }, + pitch: { + type: "number", + "default": 0, + units: "degrees" + }, + light: { + type: "light" + }, + sky: { + type: "sky" + }, + projection: { + type: "projection" + }, + terrain: { + type: "terrain" + }, + sources: { + required: true, + type: "sources" + }, + sprite: { + type: "sprite" + }, + glyphs: { + type: "string" + }, + transition: { + type: "transition" + }, + layers: { + required: true, + type: "array", + value: "layer" + } +}; +var sources = { + "*": { + type: "source" + } +}; +var source = [ + "source_vector", + "source_raster", + "source_raster_dem", + "source_geojson", + "source_video", + "source_image" +]; +var source_vector = { + type: { + required: true, + type: "enum", + values: { + vector: { + } + } + }, + url: { + type: "string" + }, + tiles: { + type: "array", + value: "string" + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ] + }, + scheme: { + type: "enum", + values: { + xyz: { + }, + tms: { + } + }, + "default": "xyz" + }, + minzoom: { + type: "number", + "default": 0 + }, + maxzoom: { + type: "number", + "default": 22 + }, + attribution: { + type: "string" + }, + promoteId: { + type: "promoteId" + }, + volatile: { + type: "boolean", + "default": false + }, + "*": { + type: "*" + } +}; +var source_raster = { + type: { + required: true, + type: "enum", + values: { + raster: { + } + } + }, + url: { + type: "string" + }, + tiles: { + type: "array", + value: "string" + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ] + }, + minzoom: { + type: "number", + "default": 0 + }, + maxzoom: { + type: "number", + "default": 22 + }, + tileSize: { + type: "number", + "default": 512, + units: "pixels" + }, + scheme: { + type: "enum", + values: { + xyz: { + }, + tms: { + } + }, + "default": "xyz" + }, + attribution: { + type: "string" + }, + volatile: { + type: "boolean", + "default": false + }, + "*": { + type: "*" + } +}; +var source_raster_dem = { + type: { + required: true, + type: "enum", + values: { + "raster-dem": { + } + } + }, + url: { + type: "string" + }, + tiles: { + type: "array", + value: "string" + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ] + }, + minzoom: { + type: "number", + "default": 0 + }, + maxzoom: { + type: "number", + "default": 22 + }, + tileSize: { + type: "number", + "default": 512, + units: "pixels" + }, + attribution: { + type: "string" + }, + encoding: { + type: "enum", + values: { + terrarium: { + }, + mapbox: { + }, + custom: { + } + }, + "default": "mapbox" + }, + redFactor: { + type: "number", + "default": 1 + }, + blueFactor: { + type: "number", + "default": 1 + }, + greenFactor: { + type: "number", + "default": 1 + }, + baseShift: { + type: "number", + "default": 0 + }, + volatile: { + type: "boolean", + "default": false + }, + "*": { + type: "*" + } +}; +var source_geojson = { + type: { + required: true, + type: "enum", + values: { + geojson: { + } + } + }, + data: { + required: true, + type: "*" + }, + maxzoom: { + type: "number", + "default": 18 + }, + attribution: { + type: "string" + }, + buffer: { + type: "number", + "default": 128, + maximum: 512, + minimum: 0 + }, + filter: { + type: "*" + }, + tolerance: { + type: "number", + "default": 0.375 + }, + cluster: { + type: "boolean", + "default": false + }, + clusterRadius: { + type: "number", + "default": 50, + minimum: 0 + }, + clusterMaxZoom: { + type: "number" + }, + clusterMinPoints: { + type: "number" + }, + clusterProperties: { + type: "*" + }, + lineMetrics: { + type: "boolean", + "default": false + }, + generateId: { + type: "boolean", + "default": false + }, + promoteId: { + type: "promoteId" + } +}; +var source_video = { + type: { + required: true, + type: "enum", + values: { + video: { + } + } + }, + urls: { + required: true, + type: "array", + value: "string" + }, + coordinates: { + required: true, + type: "array", + length: 4, + value: { + type: "array", + length: 2, + value: "number" + } + } +}; +var source_image = { + type: { + required: true, + type: "enum", + values: { + image: { + } + } + }, + url: { + required: true, + type: "string" + }, + coordinates: { + required: true, + type: "array", + length: 4, + value: { + type: "array", + length: 2, + value: "number" + } + } +}; +var layer = { + id: { + type: "string", + required: true + }, + type: { + type: "enum", + values: { + fill: { + }, + line: { + }, + symbol: { + }, + circle: { + }, + heatmap: { + }, + "fill-extrusion": { + }, + raster: { + }, + hillshade: { + }, + background: { + } + }, + required: true + }, + metadata: { + type: "*" + }, + source: { + type: "string" + }, + "source-layer": { + type: "string" + }, + minzoom: { + type: "number", + minimum: 0, + maximum: 24 + }, + maxzoom: { + type: "number", + minimum: 0, + maximum: 24 + }, + filter: { + type: "filter" + }, + layout: { + type: "layout" + }, + paint: { + type: "paint" + } +}; +var layout$7 = [ + "layout_fill", + "layout_line", + "layout_circle", + "layout_heatmap", + "layout_fill-extrusion", + "layout_symbol", + "layout_raster", + "layout_hillshade", + "layout_background" +]; +var layout_background = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_fill = { + "fill-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_circle = { + "circle-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_heatmap = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_line = { + "line-cap": { + type: "enum", + values: { + butt: { + }, + round: { + }, + square: { + } + }, + "default": "butt", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-join": { + type: "enum", + values: { + bevel: { + }, + round: { + }, + miter: { + } + }, + "default": "miter", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "line-miter-limit": { + type: "number", + "default": 2, + requires: [ + { + "line-join": "miter" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-round-limit": { + type: "number", + "default": 1.05, + requires: [ + { + "line-join": "round" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_symbol = { + "symbol-placement": { + type: "enum", + values: { + point: { + }, + line: { + }, + "line-center": { + } + }, + "default": "point", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-spacing": { + type: "number", + "default": 250, + minimum: 1, + units: "pixels", + requires: [ + { + "symbol-placement": "line" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-avoid-edges": { + type: "boolean", + "default": false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-sort-key": { + type: "number", + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "symbol-z-order": { + type: "enum", + values: { + auto: { + }, + "viewport-y": { + }, + source: { + } + }, + "default": "auto", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-allow-overlap": { + type: "boolean", + "default": false, + requires: [ + "icon-image", + { + "!": "icon-overlap" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-overlap": { + type: "enum", + values: { + never: { + }, + always: { + }, + cooperative: { + } + }, + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-ignore-placement": { + type: "boolean", + "default": false, + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-optional": { + type: "boolean", + "default": false, + requires: [ + "icon-image", + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-rotation-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-size": { + type: "number", + "default": 1, + minimum: 0, + units: "factor of the original icon size", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-text-fit": { + type: "enum", + values: { + none: { + }, + width: { + }, + height: { + }, + both: { + } + }, + "default": "none", + requires: [ + "icon-image", + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-text-fit-padding": { + type: "array", + value: "number", + length: 4, + "default": [ + 0, + 0, + 0, + 0 + ], + units: "pixels", + requires: [ + "icon-image", + "text-field", + { + "icon-text-fit": [ + "both", + "width", + "height" + ] + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-image": { + type: "resolvedImage", + tokens: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-rotate": { + type: "number", + "default": 0, + period: 360, + units: "degrees", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-padding": { + type: "padding", + "default": [ + 2 + ], + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-keep-upright": { + type: "boolean", + "default": false, + requires: [ + "icon-image", + { + "icon-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-offset": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-anchor": { + type: "enum", + values: { + center: { + }, + left: { + }, + right: { + }, + top: { + }, + bottom: { + }, + "top-left": { + }, + "top-right": { + }, + "bottom-left": { + }, + "bottom-right": { + } + }, + "default": "center", + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-pitch-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-pitch-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotation-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + }, + "viewport-glyph": { + }, + auto: { + } + }, + "default": "auto", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-field": { + type: "formatted", + "default": "", + tokens: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-font": { + type: "array", + value: "string", + "default": [ + "Open Sans Regular", + "Arial Unicode MS Regular" + ], + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-size": { + type: "number", + "default": 16, + minimum: 0, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-width": { + type: "number", + "default": 10, + minimum: 0, + units: "ems", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-line-height": { + type: "number", + "default": 1.2, + units: "ems", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-letter-spacing": { + type: "number", + "default": 0, + units: "ems", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-justify": { + type: "enum", + values: { + auto: { + }, + left: { + }, + center: { + }, + right: { + } + }, + "default": "center", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-radial-offset": { + type: "number", + units: "ems", + "default": 0, + requires: [ + "text-field" + ], + "property-type": "data-driven", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + } + }, + "text-variable-anchor": { + type: "array", + value: "enum", + values: { + center: { + }, + left: { + }, + right: { + }, + top: { + }, + bottom: { + }, + "top-left": { + }, + "top-right": { + }, + "bottom-left": { + }, + "bottom-right": { + } + }, + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-variable-anchor-offset": { + type: "variableAnchorOffsetCollection", + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-anchor": { + type: "enum", + values: { + center: { + }, + left: { + }, + right: { + }, + top: { + }, + bottom: { + }, + "top-left": { + }, + "top-right": { + }, + "bottom-left": { + }, + "bottom-right": { + } + }, + "default": "center", + requires: [ + "text-field", + { + "!": "text-variable-anchor" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-angle": { + type: "number", + "default": 45, + units: "degrees", + requires: [ + "text-field", + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-writing-mode": { + type: "array", + value: "enum", + values: { + horizontal: { + }, + vertical: { + } + }, + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotate": { + type: "number", + "default": 0, + period: 360, + units: "degrees", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-padding": { + type: "number", + "default": 2, + minimum: 0, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-keep-upright": { + type: "boolean", + "default": true, + requires: [ + "text-field", + { + "text-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-transform": { + type: "enum", + values: { + none: { + }, + uppercase: { + }, + lowercase: { + } + }, + "default": "none", + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-offset": { + type: "array", + value: "number", + units: "ems", + length: 2, + "default": [ + 0, + 0 + ], + requires: [ + "text-field", + { + "!": "text-radial-offset" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-allow-overlap": { + type: "boolean", + "default": false, + requires: [ + "text-field", + { + "!": "text-overlap" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-overlap": { + type: "enum", + values: { + never: { + }, + always: { + }, + cooperative: { + } + }, + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-ignore-placement": { + type: "boolean", + "default": false, + requires: [ + "text-field" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-optional": { + type: "boolean", + "default": false, + requires: [ + "text-field", + "icon-image" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_raster = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var layout_hillshade = { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}; +var filter = { + type: "array", + value: "*" +}; +var filter_operator = { + type: "enum", + values: { + "==": { + }, + "!=": { + }, + ">": { + }, + ">=": { + }, + "<": { + }, + "<=": { + }, + "in": { + }, + "!in": { + }, + all: { + }, + any: { + }, + none: { + }, + has: { + }, + "!has": { + } + } +}; +var geometry_type = { + type: "enum", + values: { + Point: { + }, + LineString: { + }, + Polygon: { + } + } +}; +var function_stop = { + type: "array", + minimum: 0, + maximum: 24, + value: [ + "number", + "color" + ], + length: 2 +}; +var expression$1 = { + type: "array", + value: "*", + minimum: 1 +}; +var light = { + anchor: { + type: "enum", + "default": "viewport", + values: { + map: { + }, + viewport: { + } + }, + "property-type": "data-constant", + transition: false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + } + }, + position: { + type: "array", + "default": [ + 1.15, + 210, + 30 + ], + length: 3, + value: "number", + "property-type": "data-constant", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + } + }, + color: { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + intensity: { + type: "number", + "property-type": "data-constant", + "default": 0.5, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + } +}; +var sky = { + "sky-color": { + type: "color", + "property-type": "data-constant", + "default": "#88C6FC", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "horizon-color": { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "fog-color": { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "fog-ground-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.5, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "horizon-fog-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.8, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "sky-horizon-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.8, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + }, + "atmosphere-blend": { + type: "number", + "property-type": "data-constant", + "default": 0.8, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true + } +}; +var terrain = { + source: { + type: "string", + required: true + }, + exaggeration: { + type: "number", + minimum: 0, + "default": 1 + } +}; +var projection = { + type: { + type: "enum", + "default": "mercator", + values: { + mercator: { + }, + globe: { + } + } + } +}; +var paint$9 = [ + "paint_fill", + "paint_line", + "paint_circle", + "paint_heatmap", + "paint_fill-extrusion", + "paint_symbol", + "paint_raster", + "paint_hillshade", + "paint_background" +]; +var paint_fill = { + "fill-antialias": { + type: "boolean", + "default": true, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "fill-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-outline-color": { + type: "color", + transition: true, + requires: [ + { + "!": "fill-pattern" + }, + { + "fill-antialias": true + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "fill-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + } +}; +var paint_line = { + "line-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "line-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "line-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-width": { + type: "number", + "default": 1, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-gap-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-offset": { + type: "number", + "default": 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-dasharray": { + type: "array", + value: "number", + minimum: 0, + transition: true, + units: "line widths", + requires: [ + { + "!": "line-pattern" + } + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "line-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "line-gradient": { + type: "color", + transition: false, + requires: [ + { + "!": "line-dasharray" + }, + { + "!": "line-pattern" + }, + { + source: "geojson", + has: { + lineMetrics: true + } + } + ], + expression: { + interpolated: true, + parameters: [ + "line-progress" + ] + }, + "property-type": "color-ramp" + } +}; +var paint_circle = { + "circle-radius": { + type: "number", + "default": 5, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-blur": { + type: "number", + "default": 0, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "circle-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-scale": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-alignment": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "viewport", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-stroke-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + } +}; +var paint_heatmap = { + "heatmap-radius": { + type: "number", + "default": 30, + minimum: 1, + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-weight": { + type: "number", + "default": 1, + minimum: 0, + transition: false, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-intensity": { + type: "number", + "default": 1, + minimum: 0, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "heatmap-color": { + type: "color", + "default": [ + "interpolate", + [ + "linear" + ], + [ + "heatmap-density" + ], + 0, + "rgba(0, 0, 255, 0)", + 0.1, + "royalblue", + 0.3, + "cyan", + 0.5, + "lime", + 0.7, + "yellow", + 1, + "red" + ], + transition: false, + expression: { + interpolated: true, + parameters: [ + "heatmap-density" + ] + }, + "property-type": "color-ramp" + }, + "heatmap-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_symbol = { + "icon-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-color": { + type: "color", + "default": "rgba(0, 0, 0, 0)", + transition: true, + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + requires: [ + "icon-image" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "icon-image", + "icon-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-color": { + type: "color", + "default": "#000000", + transition: true, + overridable: true, + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-color": { + type: "color", + "default": "rgba(0, 0, 0, 0)", + transition: true, + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + requires: [ + "text-field" + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "text-field", + "text-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_raster = { + "raster-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-hue-rotate": { + type: "number", + "default": 0, + period: 360, + transition: true, + units: "degrees", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-min": { + type: "number", + "default": 0, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-max": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-saturation": { + type: "number", + "default": 0, + minimum: -1, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-contrast": { + type: "number", + "default": 0, + minimum: -1, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-resampling": { + type: "enum", + values: { + linear: { + }, + nearest: { + } + }, + "default": "linear", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-fade-duration": { + type: "number", + "default": 300, + minimum: 0, + transition: false, + units: "milliseconds", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_hillshade = { + "hillshade-illumination-direction": { + type: "number", + "default": 335, + minimum: 0, + maximum: 359, + transition: false, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-illumination-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "viewport", + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-exaggeration": { + type: "number", + "default": 0.5, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-shadow-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-highlight-color": { + type: "color", + "default": "#FFFFFF", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-accent-color": { + type: "color", + "default": "#000000", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_background = { + "background-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "background-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "background-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "background-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var transition = { + duration: { + type: "number", + "default": 300, + minimum: 0, + units: "milliseconds" + }, + delay: { + type: "number", + "default": 0, + minimum: 0, + units: "milliseconds" + } +}; +var promoteId = { + "*": { + type: "string" + } +}; +var v8Spec = { + $version: $version, + $root: $root, + sources: sources, + source: source, + source_vector: source_vector, + source_raster: source_raster, + source_raster_dem: source_raster_dem, + source_geojson: source_geojson, + source_video: source_video, + source_image: source_image, + layer: layer, + layout: layout$7, + layout_background: layout_background, + layout_fill: layout_fill, + layout_circle: layout_circle, + layout_heatmap: layout_heatmap, + "layout_fill-extrusion": { + visibility: { + type: "enum", + values: { + visible: { + }, + none: { + } + }, + "default": "visible", + "property-type": "constant" + } +}, + layout_line: layout_line, + layout_symbol: layout_symbol, + layout_raster: layout_raster, + layout_hillshade: layout_hillshade, + filter: filter, + filter_operator: filter_operator, + geometry_type: geometry_type, + "function": { + expression: { + type: "expression" + }, + stops: { + type: "array", + value: "function_stop" + }, + base: { + type: "number", + "default": 1, + minimum: 0 + }, + property: { + type: "string", + "default": "$zoom" + }, + type: { + type: "enum", + values: { + identity: { + }, + exponential: { + }, + interval: { + }, + categorical: { + } + }, + "default": "exponential" + }, + colorSpace: { + type: "enum", + values: { + rgb: { + }, + lab: { + }, + hcl: { + } + }, + "default": "rgb" + }, + "default": { + type: "*", + required: false + } +}, + function_stop: function_stop, + expression: expression$1, + light: light, + sky: sky, + terrain: terrain, + projection: projection, + paint: paint$9, + paint_fill: paint_fill, + "paint_fill-extrusion": { + "fill-extrusion-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-color": { + type: "color", + "default": "#000000", + transition: true, + requires: [ + { + "!": "fill-extrusion-pattern" + } + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-translate-anchor": { + type: "enum", + values: { + map: { + }, + viewport: { + } + }, + "default": "map", + requires: [ + "fill-extrusion-translate" + ], + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-pattern": { + type: "resolvedImage", + transition: true, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "fill-extrusion-height": { + type: "number", + "default": 0, + minimum: 0, + units: "meters", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-base": { + type: "number", + "default": 0, + minimum: 0, + units: "meters", + transition: true, + requires: [ + "fill-extrusion-height" + ], + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-vertical-gradient": { + type: "boolean", + "default": true, + transition: false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}, + paint_line: paint_line, + paint_circle: paint_circle, + paint_heatmap: paint_heatmap, + paint_symbol: paint_symbol, + paint_raster: paint_raster, + paint_hillshade: paint_hillshade, + paint_background: paint_background, + transition: transition, + "property-type": { + "data-driven": { + type: "property-type" + }, + "cross-faded": { + type: "property-type" + }, + "cross-faded-data-driven": { + type: "property-type" + }, + "color-ramp": { + type: "property-type" + }, + "data-constant": { + type: "property-type" + }, + constant: { + type: "property-type" + } +}, + promoteId: promoteId +}; + +const refProperties = ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout']; + +function deref(layer, parent) { + const result = {}; + for (const k in layer) { + if (k !== 'ref') { + result[k] = layer[k]; + } + } + refProperties.forEach((k) => { + if (k in parent) { + result[k] = parent[k]; + } + }); + return result; +} +/** + * Given an array of layers, some of which may contain `ref` properties + * whose value is the `id` of another property, return a new array where + * such layers have been augmented with the 'type', 'source', etc. properties + * from the parent layer, and the `ref` property has been removed. + * + * The input is not modified. The output may contain references to portions + * of the input. + * + * @private + * @param {Array} layers + * @returns {Array} + */ +function derefLayers(layers) { + layers = layers.slice(); + const map = Object.create(null); + for (let i = 0; i < layers.length; i++) { + map[layers[i].id] = layers[i]; + } + for (let i = 0; i < layers.length; i++) { + if ('ref' in layers[i]) { + layers[i] = deref(layers[i], map[layers[i].ref]); + } + } + return layers; +} + +/** + * Deeply compares two object literals. + * + * @private + */ +function deepEqual(a, b) { + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) { + if (!deepEqual(a[i], b[i])) + return false; + } + return true; + } + if (typeof a === 'object' && a !== null && b !== null) { + if (!(typeof b === 'object')) + return false; + const keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) + return false; + for (const key in a) { + if (!deepEqual(a[key], b[key])) + return false; + } + return true; + } + return a === b; +} + +/** + * The main reason for this method is to allow type check when adding a command to the array. + * @param commands - The commands array to add to + * @param command - The command to add + */ +function addCommand(commands, command) { + commands.push(command); +} +function addSource(sourceId, after, commands) { + addCommand(commands, { command: 'addSource', args: [sourceId, after[sourceId]] }); +} +function removeSource(sourceId, commands, sourcesRemoved) { + addCommand(commands, { command: 'removeSource', args: [sourceId] }); + sourcesRemoved[sourceId] = true; +} +function updateSource(sourceId, after, commands, sourcesRemoved) { + removeSource(sourceId, commands, sourcesRemoved); + addSource(sourceId, after, commands); +} +function canUpdateGeoJSON(before, after, sourceId) { + let prop; + for (prop in before[sourceId]) { + if (!Object.prototype.hasOwnProperty.call(before[sourceId], prop)) + continue; + if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + for (prop in after[sourceId]) { + if (!Object.prototype.hasOwnProperty.call(after[sourceId], prop)) + continue; + if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + return true; +} +function diffSources(before, after, commands, sourcesRemoved) { + before = before || {}; + after = after || {}; + let sourceId; + // look for sources to remove + for (sourceId in before) { + if (!Object.prototype.hasOwnProperty.call(before, sourceId)) + continue; + if (!Object.prototype.hasOwnProperty.call(after, sourceId)) { + removeSource(sourceId, commands, sourcesRemoved); + } + } + // look for sources to add/update + for (sourceId in after) { + if (!Object.prototype.hasOwnProperty.call(after, sourceId)) + continue; + if (!Object.prototype.hasOwnProperty.call(before, sourceId)) { + addSource(sourceId, after, commands); + } + else if (!deepEqual(before[sourceId], after[sourceId])) { + if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) { + addCommand(commands, { command: 'setGeoJSONSourceData', args: [sourceId, after[sourceId].data] }); + } + else { + // no update command, must remove then add + updateSource(sourceId, after, commands, sourcesRemoved); + } + } + } +} +function diffLayerPropertyChanges(before, after, commands, layerId, klass, command) { + before = before || {}; + after = after || {}; + for (const prop in before) { + if (!Object.prototype.hasOwnProperty.call(before, prop)) + continue; + if (!deepEqual(before[prop], after[prop])) { + commands.push({ command, args: [layerId, prop, after[prop], klass] }); + } + } + for (const prop in after) { + if (!Object.prototype.hasOwnProperty.call(after, prop) || Object.prototype.hasOwnProperty.call(before, prop)) + continue; + if (!deepEqual(before[prop], after[prop])) { + commands.push({ command, args: [layerId, prop, after[prop], klass] }); + } + } +} +function pluckId(layer) { + return layer.id; +} +function indexById(group, layer) { + group[layer.id] = layer; + return group; +} +function diffLayers(before, after, commands) { + before = before || []; + after = after || []; + // order of layers by id + const beforeOrder = before.map(pluckId); + const afterOrder = after.map(pluckId); + // index of layer by id + const beforeIndex = before.reduce(indexById, {}); + const afterIndex = after.reduce(indexById, {}); + // track order of layers as if they have been mutated + const tracker = beforeOrder.slice(); + // layers that have been added do not need to be diffed + const clean = Object.create(null); + let layerId; + let beforeLayer; + let afterLayer; + let insertBeforeLayerId; + let prop; + // remove layers + for (let i = 0, d = 0; i < beforeOrder.length; i++) { + layerId = beforeOrder[i]; + if (!Object.prototype.hasOwnProperty.call(afterIndex, layerId)) { + addCommand(commands, { command: 'removeLayer', args: [layerId] }); + tracker.splice(tracker.indexOf(layerId, d), 1); + } + else { + // limit where in tracker we need to look for a match + d++; + } + } + // add/reorder layers + for (let i = 0, d = 0; i < afterOrder.length; i++) { + // work backwards as insert is before an existing layer + layerId = afterOrder[afterOrder.length - 1 - i]; + if (tracker[tracker.length - 1 - i] === layerId) + continue; + if (Object.prototype.hasOwnProperty.call(beforeIndex, layerId)) { + // remove the layer before we insert at the correct position + addCommand(commands, { command: 'removeLayer', args: [layerId] }); + tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1); + } + else { + // limit where in tracker we need to look for a match + d++; + } + // add layer at correct position + insertBeforeLayerId = tracker[tracker.length - i]; + addCommand(commands, { command: 'addLayer', args: [afterIndex[layerId], insertBeforeLayerId] }); + tracker.splice(tracker.length - i, 0, layerId); + clean[layerId] = true; + } + // update layers + for (let i = 0; i < afterOrder.length; i++) { + layerId = afterOrder[i]; + beforeLayer = beforeIndex[layerId]; + afterLayer = afterIndex[layerId]; + // no need to update if previously added (new or moved) + if (clean[layerId] || deepEqual(beforeLayer, afterLayer)) + continue; + // If source, source-layer, or type have changes, then remove the layer + // and add it back 'from scratch'. + if (!deepEqual(beforeLayer.source, afterLayer.source) || !deepEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !deepEqual(beforeLayer.type, afterLayer.type)) { + addCommand(commands, { command: 'removeLayer', args: [layerId] }); + // we add the layer back at the same position it was already in, so + // there's no need to update the `tracker` + insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1]; + addCommand(commands, { command: 'addLayer', args: [afterLayer, insertBeforeLayerId] }); + continue; + } + // layout, paint, filter, minzoom, maxzoom + diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, 'setLayoutProperty'); + diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, 'setPaintProperty'); + if (!deepEqual(beforeLayer.filter, afterLayer.filter)) { + addCommand(commands, { command: 'setFilter', args: [layerId, afterLayer.filter] }); + } + if (!deepEqual(beforeLayer.minzoom, afterLayer.minzoom) || !deepEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) { + addCommand(commands, { command: 'setLayerZoomRange', args: [layerId, afterLayer.minzoom, afterLayer.maxzoom] }); + } + // handle all other layer props, including paint.* + for (prop in beforeLayer) { + if (!Object.prototype.hasOwnProperty.call(beforeLayer, prop)) + continue; + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || + prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') + continue; + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), 'setPaintProperty'); + } + else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) { + addCommand(commands, { command: 'setLayerProperty', args: [layerId, prop, afterLayer[prop]] }); + } + } + for (prop in afterLayer) { + if (!Object.prototype.hasOwnProperty.call(afterLayer, prop) || Object.prototype.hasOwnProperty.call(beforeLayer, prop)) + continue; + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || + prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') + continue; + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), 'setPaintProperty'); + } + else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) { + addCommand(commands, { command: 'setLayerProperty', args: [layerId, prop, afterLayer[prop]] }); + } + } + } +} +/** + * Diff two stylesheet + * + * Creates semanticly aware diffs that can easily be applied at runtime. + * Operations produced by the diff closely resemble the maplibre-gl-js API. Any + * error creating the diff will fall back to the 'setStyle' operation. + * + * Example diff: + * [ + * { command: 'setConstant', args: ['@water', '#0000FF'] }, + * { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] } + * ] + * + * @private + * @param {*} [before] stylesheet to compare from + * @param {*} after stylesheet to compare to + * @returns Array list of changes + */ +function diffStyles(before, after) { + if (!before) + return [{ command: 'setStyle', args: [after] }]; + let commands = []; + try { + // Handle changes to top-level properties + if (!deepEqual(before.version, after.version)) { + return [{ command: 'setStyle', args: [after] }]; + } + if (!deepEqual(before.center, after.center)) { + commands.push({ command: 'setCenter', args: [after.center] }); + } + if (!deepEqual(before.zoom, after.zoom)) { + commands.push({ command: 'setZoom', args: [after.zoom] }); + } + if (!deepEqual(before.bearing, after.bearing)) { + commands.push({ command: 'setBearing', args: [after.bearing] }); + } + if (!deepEqual(before.pitch, after.pitch)) { + commands.push({ command: 'setPitch', args: [after.pitch] }); + } + if (!deepEqual(before.sprite, after.sprite)) { + commands.push({ command: 'setSprite', args: [after.sprite] }); + } + if (!deepEqual(before.glyphs, after.glyphs)) { + commands.push({ command: 'setGlyphs', args: [after.glyphs] }); + } + if (!deepEqual(before.transition, after.transition)) { + commands.push({ command: 'setTransition', args: [after.transition] }); + } + if (!deepEqual(before.light, after.light)) { + commands.push({ command: 'setLight', args: [after.light] }); + } + if (!deepEqual(before.terrain, after.terrain)) { + commands.push({ command: 'setTerrain', args: [after.terrain] }); + } + if (!deepEqual(before.sky, after.sky)) { + commands.push({ command: 'setSky', args: [after.sky] }); + } + if (!deepEqual(before.projection, after.projection)) { + commands.push({ command: 'setProjection', args: [after.projection] }); + } + // Handle changes to `sources` + // If a source is to be removed, we also--before the removeSource + // command--need to remove all the style layers that depend on it. + const sourcesRemoved = {}; + // First collect the {add,remove}Source commands + const removeOrAddSourceCommands = []; + diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved); + // Push a removeLayer command for each style layer that depends on a + // source that's being removed. + // Also, exclude any such layers them from the input to `diffLayers` + // below, so that diffLayers produces the appropriate `addLayers` + // command + const beforeLayers = []; + if (before.layers) { + before.layers.forEach((layer) => { + if ('source' in layer && sourcesRemoved[layer.source]) { + commands.push({ command: 'removeLayer', args: [layer.id] }); + } + else { + beforeLayers.push(layer); + } + }); + } + commands = commands.concat(removeOrAddSourceCommands); + // Handle changes to `layers` + diffLayers(beforeLayers, after.layers, commands); + } + catch (e) { + // fall back to setStyle + console.warn('Unable to compute style diff:', e); + commands = [{ command: 'setStyle', args: [after] }]; + } + return commands; +} + +// Note: Do not inherit from Error. It breaks when transpiling to ES5. +class ValidationError { + constructor(key, value, message, identifier) { + this.message = (key ? `${key}: ` : '') + message; + if (identifier) + this.identifier = identifier; + if (value !== null && value !== undefined && value.__line__) { + this.line = value.__line__; + } + } +} + +function extendBy(output, ...inputs) { + for (const input of inputs) { + for (const k in input) { + output[k] = input[k]; + } + } + return output; +} + +class ExpressionParsingError extends Error { + constructor(key, message) { + super(message); + this.message = message; + this.key = key; + } +} + +/** + * Tracks `let` bindings during expression parsing. + * @private + */ +class Scope { + constructor(parent, bindings = []) { + this.parent = parent; + this.bindings = {}; + for (const [name, expression] of bindings) { + this.bindings[name] = expression; + } + } + concat(bindings) { + return new Scope(this, bindings); + } + get(name) { + if (this.bindings[name]) { + return this.bindings[name]; + } + if (this.parent) { + return this.parent.get(name); + } + throw new Error(`${name} not found in scope.`); + } + has(name) { + if (this.bindings[name]) + return true; + return this.parent ? this.parent.has(name) : false; + } +} + +const NullType = { kind: 'null' }; +const NumberType = { kind: 'number' }; +const StringType = { kind: 'string' }; +const BooleanType = { kind: 'boolean' }; +const ColorType = { kind: 'color' }; +const ObjectType = { kind: 'object' }; +const ValueType = { kind: 'value' }; +const ErrorType = { kind: 'error' }; +const CollatorType = { kind: 'collator' }; +const FormattedType = { kind: 'formatted' }; +const PaddingType = { kind: 'padding' }; +const ResolvedImageType = { kind: 'resolvedImage' }; +const VariableAnchorOffsetCollectionType = { kind: 'variableAnchorOffsetCollection' }; +function array$1(itemType, N) { + return { + kind: 'array', + itemType, + N + }; +} +function toString$1(type) { + if (type.kind === 'array') { + const itemType = toString$1(type.itemType); + return typeof type.N === 'number' ? + `array<${itemType}, ${type.N}>` : + type.itemType.kind === 'value' ? 'array' : `array<${itemType}>`; + } + else { + return type.kind; + } +} +const valueMemberTypes = [ + NullType, + NumberType, + StringType, + BooleanType, + ColorType, + FormattedType, + ObjectType, + array$1(ValueType), + PaddingType, + ResolvedImageType, + VariableAnchorOffsetCollectionType +]; +/** + * Returns null if `t` is a subtype of `expected`; otherwise returns an + * error message. + * @private + */ +function checkSubtype(expected, t) { + if (t.kind === 'error') { + // Error is a subtype of every type + return null; + } + else if (expected.kind === 'array') { + if (t.kind === 'array' && + ((t.N === 0 && t.itemType.kind === 'value') || !checkSubtype(expected.itemType, t.itemType)) && + (typeof expected.N !== 'number' || expected.N === t.N)) { + return null; + } + } + else if (expected.kind === t.kind) { + return null; + } + else if (expected.kind === 'value') { + for (const memberType of valueMemberTypes) { + if (!checkSubtype(memberType, t)) { + return null; + } + } + } + return `Expected ${toString$1(expected)} but found ${toString$1(t)} instead.`; +} +function isValidType(provided, allowedTypes) { + return allowedTypes.some(t => t.kind === provided.kind); +} +function isValidNativeType(provided, allowedTypes) { + return allowedTypes.some(t => { + if (t === 'null') { + return provided === null; + } + else if (t === 'array') { + return Array.isArray(provided); + } + else if (t === 'object') { + return provided && !Array.isArray(provided) && typeof provided === 'object'; + } + else { + return t === typeof provided; + } + }); +} +/** + * Verify whether the specified type is of the same type as the specified sample. + * + * @param provided Type to verify + * @param sample Sample type to reference + * @returns `true` if both objects are of the same type, `false` otherwise + * @example basic types + * if (verifyType(outputType, ValueType)) { + * // type narrowed to: + * outputType.kind; // 'value' + * } + * @example array types + * if (verifyType(outputType, array(NumberType))) { + * // type narrowed to: + * outputType.kind; // 'array' + * outputType.itemType; // NumberTypeT + * outputType.itemType.kind; // 'number' + * } + */ +function verifyType(provided, sample) { + if (provided.kind === 'array' && sample.kind === 'array') { + return provided.itemType.kind === sample.itemType.kind && typeof provided.N === 'number'; + } + return provided.kind === sample.kind; +} + +// See https://observablehq.com/@mbostock/lab-and-rgb +const Xn = 0.96422, Yn = 1, Zn = 0.82521, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1, deg2rad = Math.PI / 180, rad2deg = 180 / Math.PI; +function constrainAngle(angle) { + angle = angle % 360; + if (angle < 0) { + angle += 360; + } + return angle; +} +function rgbToLab([r, g, b, alpha]) { + r = rgb2xyz(r); + g = rgb2xyz(g); + b = rgb2xyz(b); + let x, z; + const y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn); + if (r === g && g === b) { + x = z = y; + } + else { + x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn); + z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn); + } + const l = 116 * y - 16; + return [(l < 0) ? 0 : l, 500 * (x - y), 200 * (y - z), alpha]; +} +function rgb2xyz(x) { + return (x <= 0.04045) ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); +} +function xyz2lab(t) { + return (t > t3) ? Math.pow(t, 1 / 3) : t / t2 + t0; +} +function labToRgb([l, a, b, alpha]) { + let y = (l + 16) / 116, x = isNaN(a) ? y : y + a / 500, z = isNaN(b) ? y : y - b / 200; + y = Yn * lab2xyz(y); + x = Xn * lab2xyz(x); + z = Zn * lab2xyz(z); + return [ + xyz2rgb(3.1338561 * x - 1.6168667 * y - 0.4906146 * z), // D50 -> sRGB + xyz2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z), + xyz2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z), + alpha, + ]; +} +function xyz2rgb(x) { + x = (x <= 0.00304) ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055; + return (x < 0) ? 0 : (x > 1) ? 1 : x; // clip to 0..1 range +} +function lab2xyz(t) { + return (t > t1) ? t * t * t : t2 * (t - t0); +} +function rgbToHcl(rgbColor) { + const [l, a, b, alpha] = rgbToLab(rgbColor); + const c = Math.sqrt(a * a + b * b); + const h = Math.round(c * 10000) ? constrainAngle(Math.atan2(b, a) * rad2deg) : NaN; + return [h, c, l, alpha]; +} +function hclToRgb([h, c, l, alpha]) { + h = isNaN(h) ? 0 : h * deg2rad; + return labToRgb([l, Math.cos(h) * c, Math.sin(h) * c, alpha]); +} +// https://drafts.csswg.org/css-color-4/#hsl-to-rgb +function hslToRgb([h, s, l, alpha]) { + h = constrainAngle(h); + s /= 100; + l /= 100; + function f(n) { + const k = (n + h / 30) % 12; + const a = s * Math.min(l, 1 - l); + return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); + } + return [f(0), f(8), f(4), alpha]; +} + +/** + * CSS color parser compliant with CSS Color 4 Specification. + * Supports: named colors, `transparent` keyword, all rgb hex notations, + * rgb(), rgba(), hsl() and hsla() functions. + * Does not round the parsed values to integers from the range 0..255. + * + * Syntax: + * + * = | + * = | + * + * rgb() = rgb( {3} [ / ]? ) | rgb( {3} [ / ]? ) + * rgb() = rgb( #{3} , ? ) | rgb( #{3} , ? ) + * + * hsl() = hsl( [ / ]? ) + * hsl() = hsl( , , , ? ) + * + * Caveats: + * - - with optional `deg` suffix; `grad`, `rad`, `turn` are not supported + * - `none` keyword is not supported + * - comments inside rgb()/hsl() are not supported + * - legacy color syntax rgba() is supported with an identical grammar and behavior to rgb() + * - legacy color syntax hsla() is supported with an identical grammar and behavior to hsl() + * + * @param input CSS color string to parse. + * @returns Color in sRGB color space, with `red`, `green`, `blue` + * and `alpha` channels normalized to the range 0..1, + * or `undefined` if the input is not a valid color string. + */ +function parseCssColor(input) { + input = input.toLowerCase().trim(); + if (input === 'transparent') { + return [0, 0, 0, 0]; + } + // 'white', 'black', 'blue' + const namedColorsMatch = namedColors[input]; + if (namedColorsMatch) { + const [r, g, b] = namedColorsMatch; + return [r / 255, g / 255, b / 255, 1]; + } + // #f0c, #f0cf, #ff00cc, #ff00ccff + if (input.startsWith('#')) { + const hexRegexp = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/; + if (hexRegexp.test(input)) { + const step = input.length < 6 ? 1 : 2; + let i = 1; + return [ + parseHex(input.slice(i, i += step)), + parseHex(input.slice(i, i += step)), + parseHex(input.slice(i, i += step)), + parseHex(input.slice(i, i + step) || 'ff'), + ]; + } + } + // rgb(128 0 0), rgb(50% 0% 0%), rgba(255,0,255,0.6), rgb(255 0 255 / 60%), rgb(100% 0% 100% /.6) + if (input.startsWith('rgb')) { + const rgbRegExp = /^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/; + const rgbMatch = input.match(rgbRegExp); + if (rgbMatch) { + const [_, // eslint-disable-line @typescript-eslint/no-unused-vars + r, // + rp, // % (optional) + f1, // , (optional) + g, // + gp, // % (optional) + f2, // , (optional) + b, // + bp, // % (optional) + f3, // ,|/ (optional) + a, // (optional) + ap, // % (optional) + ] = rgbMatch; + const argFormat = [f1 || ' ', f2 || ' ', f3].join(''); + if (argFormat === ' ' || + argFormat === ' /' || + argFormat === ',,' || + argFormat === ',,,') { + const valFormat = [rp, gp, bp].join(''); + const maxValue = (valFormat === '%%%') ? 100 : + (valFormat === '') ? 255 : 0; + if (maxValue) { + const rgba = [ + clamp(+r / maxValue, 0, 1), + clamp(+g / maxValue, 0, 1), + clamp(+b / maxValue, 0, 1), + a ? parseAlpha(+a, ap) : 1, + ]; + if (validateNumbers(rgba)) { + return rgba; + } + // invalid numbers + } + // values must be all numbers or all percentages + } + return; // comma optional syntax requires no commas at all + } + } + // hsl(120 50% 80%), hsla(120deg,50%,80%,.9), hsl(12e1 50% 80% / 90%) + const hslRegExp = /^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/; + const hslMatch = input.match(hslRegExp); + if (hslMatch) { + const [_, // eslint-disable-line @typescript-eslint/no-unused-vars + h, // + f1, // , (optional) + s, // + f2, // , (optional) + l, // + f3, // ,|/ (optional) + a, // (optional) + ap, // % (optional) + ] = hslMatch; + const argFormat = [f1 || ' ', f2 || ' ', f3].join(''); + if (argFormat === ' ' || + argFormat === ' /' || + argFormat === ',,' || + argFormat === ',,,') { + const hsla = [ + +h, + clamp(+s, 0, 100), + clamp(+l, 0, 100), + a ? parseAlpha(+a, ap) : 1, + ]; + if (validateNumbers(hsla)) { + return hslToRgb(hsla); + } + // invalid numbers + } + // comma optional syntax requires no commas at all + } +} +function parseHex(hex) { + return parseInt(hex.padEnd(2, hex), 16) / 255; +} +function parseAlpha(a, asPercentage) { + return clamp(asPercentage ? (a / 100) : a, 0, 1); +} +function clamp(n, min, max) { + return Math.min(Math.max(min, n), max); +} +/** + * The regular expression for numeric values is not super specific, and it may + * happen that it will accept a value that is not a valid number. In order to + * detect and eliminate such values this function exists. + * + * @param array Array of uncertain numbers. + * @returns `true` if the specified array contains only valid numbers, `false` otherwise. + */ +function validateNumbers(array) { + return !array.some(Number.isNaN); +} +/** + * To generate: + * - visit {@link https://www.w3.org/TR/css-color-4/#named-colors} + * - run in the console: + * @example + * copy(`{\n${[...document.querySelector('.named-color-table tbody').children].map((tr) => `${tr.cells[2].textContent.trim()}: [${tr.cells[4].textContent.trim().split(/\s+/).join(', ')}],`).join('\n')}\n}`); + */ +const namedColors = { + aliceblue: [240, 248, 255], + antiquewhite: [250, 235, 215], + aqua: [0, 255, 255], + aquamarine: [127, 255, 212], + azure: [240, 255, 255], + beige: [245, 245, 220], + bisque: [255, 228, 196], + black: [0, 0, 0], + blanchedalmond: [255, 235, 205], + blue: [0, 0, 255], + blueviolet: [138, 43, 226], + brown: [165, 42, 42], + burlywood: [222, 184, 135], + cadetblue: [95, 158, 160], + chartreuse: [127, 255, 0], + chocolate: [210, 105, 30], + coral: [255, 127, 80], + cornflowerblue: [100, 149, 237], + cornsilk: [255, 248, 220], + crimson: [220, 20, 60], + cyan: [0, 255, 255], + darkblue: [0, 0, 139], + darkcyan: [0, 139, 139], + darkgoldenrod: [184, 134, 11], + darkgray: [169, 169, 169], + darkgreen: [0, 100, 0], + darkgrey: [169, 169, 169], + darkkhaki: [189, 183, 107], + darkmagenta: [139, 0, 139], + darkolivegreen: [85, 107, 47], + darkorange: [255, 140, 0], + darkorchid: [153, 50, 204], + darkred: [139, 0, 0], + darksalmon: [233, 150, 122], + darkseagreen: [143, 188, 143], + darkslateblue: [72, 61, 139], + darkslategray: [47, 79, 79], + darkslategrey: [47, 79, 79], + darkturquoise: [0, 206, 209], + darkviolet: [148, 0, 211], + deeppink: [255, 20, 147], + deepskyblue: [0, 191, 255], + dimgray: [105, 105, 105], + dimgrey: [105, 105, 105], + dodgerblue: [30, 144, 255], + firebrick: [178, 34, 34], + floralwhite: [255, 250, 240], + forestgreen: [34, 139, 34], + fuchsia: [255, 0, 255], + gainsboro: [220, 220, 220], + ghostwhite: [248, 248, 255], + gold: [255, 215, 0], + goldenrod: [218, 165, 32], + gray: [128, 128, 128], + green: [0, 128, 0], + greenyellow: [173, 255, 47], + grey: [128, 128, 128], + honeydew: [240, 255, 240], + hotpink: [255, 105, 180], + indianred: [205, 92, 92], + indigo: [75, 0, 130], + ivory: [255, 255, 240], + khaki: [240, 230, 140], + lavender: [230, 230, 250], + lavenderblush: [255, 240, 245], + lawngreen: [124, 252, 0], + lemonchiffon: [255, 250, 205], + lightblue: [173, 216, 230], + lightcoral: [240, 128, 128], + lightcyan: [224, 255, 255], + lightgoldenrodyellow: [250, 250, 210], + lightgray: [211, 211, 211], + lightgreen: [144, 238, 144], + lightgrey: [211, 211, 211], + lightpink: [255, 182, 193], + lightsalmon: [255, 160, 122], + lightseagreen: [32, 178, 170], + lightskyblue: [135, 206, 250], + lightslategray: [119, 136, 153], + lightslategrey: [119, 136, 153], + lightsteelblue: [176, 196, 222], + lightyellow: [255, 255, 224], + lime: [0, 255, 0], + limegreen: [50, 205, 50], + linen: [250, 240, 230], + magenta: [255, 0, 255], + maroon: [128, 0, 0], + mediumaquamarine: [102, 205, 170], + mediumblue: [0, 0, 205], + mediumorchid: [186, 85, 211], + mediumpurple: [147, 112, 219], + mediumseagreen: [60, 179, 113], + mediumslateblue: [123, 104, 238], + mediumspringgreen: [0, 250, 154], + mediumturquoise: [72, 209, 204], + mediumvioletred: [199, 21, 133], + midnightblue: [25, 25, 112], + mintcream: [245, 255, 250], + mistyrose: [255, 228, 225], + moccasin: [255, 228, 181], + navajowhite: [255, 222, 173], + navy: [0, 0, 128], + oldlace: [253, 245, 230], + olive: [128, 128, 0], + olivedrab: [107, 142, 35], + orange: [255, 165, 0], + orangered: [255, 69, 0], + orchid: [218, 112, 214], + palegoldenrod: [238, 232, 170], + palegreen: [152, 251, 152], + paleturquoise: [175, 238, 238], + palevioletred: [219, 112, 147], + papayawhip: [255, 239, 213], + peachpuff: [255, 218, 185], + peru: [205, 133, 63], + pink: [255, 192, 203], + plum: [221, 160, 221], + powderblue: [176, 224, 230], + purple: [128, 0, 128], + rebeccapurple: [102, 51, 153], + red: [255, 0, 0], + rosybrown: [188, 143, 143], + royalblue: [65, 105, 225], + saddlebrown: [139, 69, 19], + salmon: [250, 128, 114], + sandybrown: [244, 164, 96], + seagreen: [46, 139, 87], + seashell: [255, 245, 238], + sienna: [160, 82, 45], + silver: [192, 192, 192], + skyblue: [135, 206, 235], + slateblue: [106, 90, 205], + slategray: [112, 128, 144], + slategrey: [112, 128, 144], + snow: [255, 250, 250], + springgreen: [0, 255, 127], + steelblue: [70, 130, 180], + tan: [210, 180, 140], + teal: [0, 128, 128], + thistle: [216, 191, 216], + tomato: [255, 99, 71], + turquoise: [64, 224, 208], + violet: [238, 130, 238], + wheat: [245, 222, 179], + white: [255, 255, 255], + whitesmoke: [245, 245, 245], + yellow: [255, 255, 0], + yellowgreen: [154, 205, 50], +}; + +/** + * Color representation used by WebGL. + * Defined in sRGB color space and pre-blended with alpha. + * @private + */ +class Color { + /** + * @param r Red component premultiplied by `alpha` 0..1 + * @param g Green component premultiplied by `alpha` 0..1 + * @param b Blue component premultiplied by `alpha` 0..1 + * @param [alpha=1] Alpha component 0..1 + * @param [premultiplied=true] Whether the `r`, `g` and `b` values have already + * been multiplied by alpha. If `true` nothing happens if `false` then they will + * be multiplied automatically. + */ + constructor(r, g, b, alpha = 1, premultiplied = true) { + this.r = r; + this.g = g; + this.b = b; + this.a = alpha; + if (!premultiplied) { + this.r *= alpha; + this.g *= alpha; + this.b *= alpha; + if (!alpha) { + // alpha = 0 erases completely rgb channels. This behavior is not desirable + // if this particular color is later used in color interpolation. + // Because of that, a reference to original color is saved. + this.overwriteGetter('rgb', [r, g, b, alpha]); + } + } + } + /** + * Parses CSS color strings and converts colors to sRGB color space if needed. + * Officially supported color formats: + * - keyword, e.g. 'aquamarine' or 'steelblue' + * - hex (with 3, 4, 6 or 8 digits), e.g. '#f0f' or '#e9bebea9' + * - rgb and rgba, e.g. 'rgb(0,240,120)' or 'rgba(0%,94%,47%,0.1)' or 'rgb(0 240 120 / .3)' + * - hsl and hsla, e.g. 'hsl(0,0%,83%)' or 'hsla(0,0%,83%,.5)' or 'hsl(0 0% 83% / 20%)' + * + * @param input CSS color string to parse. + * @returns A `Color` instance, or `undefined` if the input is not a valid color string. + */ + static parse(input) { + // in zoom-and-property function input could be an instance of Color class + if (input instanceof Color) { + return input; + } + if (typeof input !== 'string') { + return; + } + const rgba = parseCssColor(input); + if (rgba) { + return new Color(...rgba, false); + } + } + /** + * Used in color interpolation and by 'to-rgba' expression. + * + * @returns Gien color, with reversed alpha blending, in sRGB color space. + */ + get rgb() { + const { r, g, b, a } = this; + const f = a || Infinity; // reverse alpha blending factor + return this.overwriteGetter('rgb', [r / f, g / f, b / f, a]); + } + /** + * Used in color interpolation. + * + * @returns Gien color, with reversed alpha blending, in HCL color space. + */ + get hcl() { + return this.overwriteGetter('hcl', rgbToHcl(this.rgb)); + } + /** + * Used in color interpolation. + * + * @returns Gien color, with reversed alpha blending, in LAB color space. + */ + get lab() { + return this.overwriteGetter('lab', rgbToLab(this.rgb)); + } + /** + * Lazy getter pattern. When getter is called for the first time lazy value + * is calculated and then overwrites getter function in given object instance. + * + * @example: + * const redColor = Color.parse('red'); + * let x = redColor.hcl; // this will invoke `get hcl()`, which will calculate + * // the value of red in HCL space and invoke this `overwriteGetter` function + * // which in turn will set a field with a key 'hcl' in the `redColor` object. + * // In other words it will override `get hcl()` from its `Color` prototype + * // with its own property: hcl = [calculated red value in hcl]. + * let y = redColor.hcl; // next call will no longer invoke getter but simply + * // return the previously calculated value + * x === y; // true - `x` is exactly the same object as `y` + * + * @param getterKey Getter key + * @param lazyValue Lazily calculated value to be memoized by current instance + * @private + */ + overwriteGetter(getterKey, lazyValue) { + Object.defineProperty(this, getterKey, { value: lazyValue }); + return lazyValue; + } + /** + * Used by 'to-string' expression. + * + * @returns Serialized color in format `rgba(r,g,b,a)` + * where r,g,b are numbers within 0..255 and alpha is number within 1..0 + * + * @example + * var purple = new Color.parse('purple'); + * purple.toString; // = "rgba(128,0,128,1)" + * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)'); + * translucentGreen.toString(); // = "rgba(26,207,26,0.73)" + */ + toString() { + const [r, g, b, a] = this.rgb; + return `rgba(${[r, g, b].map(n => Math.round(n * 255)).join(',')},${a})`; + } +} +Color.black = new Color(0, 0, 0, 1); +Color.white = new Color(1, 1, 1, 1); +Color.transparent = new Color(0, 0, 0, 0); +Color.red = new Color(1, 0, 0, 1); + +// Flow type declarations for Intl cribbed from +// https://github.com/facebook/flow/issues/1270 +class Collator { + constructor(caseSensitive, diacriticSensitive, locale) { + if (caseSensitive) + this.sensitivity = diacriticSensitive ? 'variant' : 'case'; + else + this.sensitivity = diacriticSensitive ? 'accent' : 'base'; + this.locale = locale; + this.collator = new Intl.Collator(this.locale ? this.locale : [], { sensitivity: this.sensitivity, usage: 'search' }); + } + compare(lhs, rhs) { + return this.collator.compare(lhs, rhs); + } + resolvedLocale() { + // We create a Collator without "usage: search" because we don't want + // the search options encoded in our result (e.g. "en-u-co-search") + return new Intl.Collator(this.locale ? this.locale : []) + .resolvedOptions().locale; + } +} + +class FormattedSection { + constructor(text, image, scale, fontStack, textColor) { + this.text = text; + this.image = image; + this.scale = scale; + this.fontStack = fontStack; + this.textColor = textColor; + } +} +class Formatted { + constructor(sections) { + this.sections = sections; + } + static fromString(unformatted) { + return new Formatted([new FormattedSection(unformatted, null, null, null, null)]); + } + isEmpty() { + if (this.sections.length === 0) + return true; + return !this.sections.some(section => section.text.length !== 0 || + (section.image && section.image.name.length !== 0)); + } + static factory(text) { + if (text instanceof Formatted) { + return text; + } + else { + return Formatted.fromString(text); + } + } + toString() { + if (this.sections.length === 0) + return ''; + return this.sections.map(section => section.text).join(''); + } +} + +/** + * A set of four numbers representing padding around a box. Create instances from + * bare arrays or numeric values using the static method `Padding.parse`. + * @private + */ +class Padding { + constructor(values) { + this.values = values.slice(); + } + /** + * Numeric padding values + * @param input A padding value + * @returns A `Padding` instance, or `undefined` if the input is not a valid padding value. + */ + static parse(input) { + if (input instanceof Padding) { + return input; + } + // Backwards compatibility: bare number is treated the same as array with single value. + // Padding applies to all four sides. + if (typeof input === 'number') { + return new Padding([input, input, input, input]); + } + if (!Array.isArray(input)) { + return undefined; + } + if (input.length < 1 || input.length > 4) { + return undefined; + } + for (const val of input) { + if (typeof val !== 'number') { + return undefined; + } + } + // Expand shortcut properties into explicit 4-sided values + switch (input.length) { + case 1: + input = [input[0], input[0], input[0], input[0]]; + break; + case 2: + input = [input[0], input[1], input[0], input[1]]; + break; + case 3: + input = [input[0], input[1], input[2], input[1]]; + break; + } + return new Padding(input); + } + toString() { + return JSON.stringify(this.values); + } +} + +/** Set of valid anchor positions, as a set for validation */ +const anchors = new Set(['center', 'left', 'right', 'top', 'bottom', 'top-left', 'top-right', 'bottom-left', 'bottom-right']); +/** + * Utility class to assist managing values for text-variable-anchor-offset property. Create instances from + * bare arrays using the static method `VariableAnchorOffsetCollection.parse`. + * @private + */ +class VariableAnchorOffsetCollection { + constructor(values) { + this.values = values.slice(); + } + static parse(input) { + if (input instanceof VariableAnchorOffsetCollection) { + return input; + } + if (!Array.isArray(input) || + input.length < 1 || + input.length % 2 !== 0) { + return undefined; + } + for (let i = 0; i < input.length; i += 2) { + // Elements in even positions should be anchor positions; Elements in odd positions should be offset values + const anchorValue = input[i]; + const offsetValue = input[i + 1]; + if (typeof anchorValue !== 'string' || !anchors.has(anchorValue)) { + return undefined; + } + if (!Array.isArray(offsetValue) || offsetValue.length !== 2 || typeof offsetValue[0] !== 'number' || typeof offsetValue[1] !== 'number') { + return undefined; + } + } + return new VariableAnchorOffsetCollection(input); + } + toString() { + return JSON.stringify(this.values); + } +} + +class ResolvedImage { + constructor(options) { + this.name = options.name; + this.available = options.available; + } + toString() { + return this.name; + } + static fromString(name) { + if (!name) + return null; // treat empty values as no image + return new ResolvedImage({ name, available: false }); + } +} + +function validateRGBA(r, g, b, a) { + if (!(typeof r === 'number' && r >= 0 && r <= 255 && + typeof g === 'number' && g >= 0 && g <= 255 && + typeof b === 'number' && b >= 0 && b <= 255)) { + const value = typeof a === 'number' ? [r, g, b, a] : [r, g, b]; + return `Invalid rgba value [${value.join(', ')}]: 'r', 'g', and 'b' must be between 0 and 255.`; + } + if (!(typeof a === 'undefined' || (typeof a === 'number' && a >= 0 && a <= 1))) { + return `Invalid rgba value [${[r, g, b, a].join(', ')}]: 'a' must be between 0 and 1.`; + } + return null; +} +function isValue(mixed) { + if (mixed === null || + typeof mixed === 'string' || + typeof mixed === 'boolean' || + typeof mixed === 'number' || + mixed instanceof Color || + mixed instanceof Collator || + mixed instanceof Formatted || + mixed instanceof Padding || + mixed instanceof VariableAnchorOffsetCollection || + mixed instanceof ResolvedImage) { + return true; + } + else if (Array.isArray(mixed)) { + for (const item of mixed) { + if (!isValue(item)) { + return false; + } + } + return true; + } + else if (typeof mixed === 'object') { + for (const key in mixed) { + if (!isValue(mixed[key])) { + return false; + } + } + return true; + } + else { + return false; + } +} +function typeOf(value) { + if (value === null) { + return NullType; + } + else if (typeof value === 'string') { + return StringType; + } + else if (typeof value === 'boolean') { + return BooleanType; + } + else if (typeof value === 'number') { + return NumberType; + } + else if (value instanceof Color) { + return ColorType; + } + else if (value instanceof Collator) { + return CollatorType; + } + else if (value instanceof Formatted) { + return FormattedType; + } + else if (value instanceof Padding) { + return PaddingType; + } + else if (value instanceof VariableAnchorOffsetCollection) { + return VariableAnchorOffsetCollectionType; + } + else if (value instanceof ResolvedImage) { + return ResolvedImageType; + } + else if (Array.isArray(value)) { + const length = value.length; + let itemType; + for (const item of value) { + const t = typeOf(item); + if (!itemType) { + itemType = t; + } + else if (itemType === t) { + continue; + } + else { + itemType = ValueType; + break; + } + } + return array$1(itemType || ValueType, length); + } + else { + return ObjectType; + } +} +function toString(value) { + const type = typeof value; + if (value === null) { + return ''; + } + else if (type === 'string' || type === 'number' || type === 'boolean') { + return String(value); + } + else if (value instanceof Color || value instanceof Formatted || value instanceof Padding || value instanceof VariableAnchorOffsetCollection || value instanceof ResolvedImage) { + return value.toString(); + } + else { + return JSON.stringify(value); + } +} + +class Literal { + constructor(type, value) { + this.type = type; + this.value = value; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (!isValue(args[1])) + return context.error('invalid value'); + const value = args[1]; + let type = typeOf(value); + // special case: infer the item type if possible for zero-length arrays + const expected = context.expectedType; + if (type.kind === 'array' && + type.N === 0 && + expected && + expected.kind === 'array' && + (typeof expected.N !== 'number' || expected.N === 0)) { + type = expected; + } + return new Literal(type, value); + } + evaluate() { + return this.value; + } + eachChild() { } + outputDefined() { + return true; + } +} + +class RuntimeError { + constructor(message) { + this.name = 'ExpressionEvaluationError'; + this.message = message; + } + toJSON() { + return this.message; + } +} + +const types$1 = { + string: StringType, + number: NumberType, + boolean: BooleanType, + object: ObjectType +}; +class Assertion { + constructor(type, args) { + this.type = type; + this.args = args; + } + static parse(args, context) { + if (args.length < 2) + return context.error('Expected at least one argument.'); + let i = 1; + let type; + const name = args[0]; + if (name === 'array') { + let itemType; + if (args.length > 2) { + const type = args[1]; + if (typeof type !== 'string' || !(type in types$1) || type === 'object') + return context.error('The item type argument of "array" must be one of string, number, boolean', 1); + itemType = types$1[type]; + i++; + } + else { + itemType = ValueType; + } + let N; + if (args.length > 3) { + if (args[2] !== null && + (typeof args[2] !== 'number' || + args[2] < 0 || + args[2] !== Math.floor(args[2]))) { + return context.error('The length argument to "array" must be a positive integer literal', 2); + } + N = args[2]; + i++; + } + type = array$1(itemType, N); + } + else { + if (!types$1[name]) + throw new Error(`Types doesn't contain name = ${name}`); + type = types$1[name]; + } + const parsed = []; + for (; i < args.length; i++) { + const input = context.parse(args[i], i, ValueType); + if (!input) + return null; + parsed.push(input); + } + return new Assertion(type, parsed); + } + evaluate(ctx) { + for (let i = 0; i < this.args.length; i++) { + const value = this.args[i].evaluate(ctx); + const error = checkSubtype(this.type, typeOf(value)); + if (!error) { + return value; + } + else if (i === this.args.length - 1) { + throw new RuntimeError(`Expected value to be of type ${toString$1(this.type)}, but found ${toString$1(typeOf(value))} instead.`); + } + } + throw new Error(); + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return this.args.every(arg => arg.outputDefined()); + } +} + +const types = { + 'to-boolean': BooleanType, + 'to-color': ColorType, + 'to-number': NumberType, + 'to-string': StringType +}; +/** + * Special form for error-coalescing coercion expressions "to-number", + * "to-color". Since these coercions can fail at runtime, they accept multiple + * arguments, only evaluating one at a time until one succeeds. + * + * @private + */ +class Coercion { + constructor(type, args) { + this.type = type; + this.args = args; + } + static parse(args, context) { + if (args.length < 2) + return context.error('Expected at least one argument.'); + const name = args[0]; + if (!types[name]) + throw new Error(`Can't parse ${name} as it is not part of the known types`); + if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2) + return context.error('Expected one argument.'); + const type = types[name]; + const parsed = []; + for (let i = 1; i < args.length; i++) { + const input = context.parse(args[i], i, ValueType); + if (!input) + return null; + parsed.push(input); + } + return new Coercion(type, parsed); + } + evaluate(ctx) { + switch (this.type.kind) { + case 'boolean': + return Boolean(this.args[0].evaluate(ctx)); + case 'color': { + let input; + let error; + for (const arg of this.args) { + input = arg.evaluate(ctx); + error = null; + if (input instanceof Color) { + return input; + } + else if (typeof input === 'string') { + const c = ctx.parseColor(input); + if (c) + return c; + } + else if (Array.isArray(input)) { + if (input.length < 3 || input.length > 4) { + error = `Invalid rbga value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`; + } + else { + error = validateRGBA(input[0], input[1], input[2], input[3]); + } + if (!error) { + return new Color(input[0] / 255, input[1] / 255, input[2] / 255, input[3]); + } + } + } + throw new RuntimeError(error || `Could not parse color from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`); + } + case 'padding': { + let input; + for (const arg of this.args) { + input = arg.evaluate(ctx); + const pad = Padding.parse(input); + if (pad) { + return pad; + } + } + throw new RuntimeError(`Could not parse padding from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`); + } + case 'variableAnchorOffsetCollection': { + let input; + for (const arg of this.args) { + input = arg.evaluate(ctx); + const coll = VariableAnchorOffsetCollection.parse(input); + if (coll) { + return coll; + } + } + throw new RuntimeError(`Could not parse variableAnchorOffsetCollection from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`); + } + case 'number': { + let value = null; + for (const arg of this.args) { + value = arg.evaluate(ctx); + if (value === null) + return 0; + const num = Number(value); + if (isNaN(num)) + continue; + return num; + } + throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`); + } + case 'formatted': + // There is no explicit 'to-formatted' but this coercion can be implicitly + // created by properties that expect the 'formatted' type. + return Formatted.fromString(toString(this.args[0].evaluate(ctx))); + case 'resolvedImage': + return ResolvedImage.fromString(toString(this.args[0].evaluate(ctx))); + default: + return toString(this.args[0].evaluate(ctx)); + } + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return this.args.every(arg => arg.outputDefined()); + } +} + +const geometryTypes = ['Unknown', 'Point', 'LineString', 'Polygon']; +class EvaluationContext { + constructor() { + this.globals = null; + this.feature = null; + this.featureState = null; + this.formattedSection = null; + this._parseColorCache = {}; + this.availableImages = null; + this.canonical = null; + } + id() { + return this.feature && 'id' in this.feature ? this.feature.id : null; + } + geometryType() { + return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null; + } + geometry() { + return this.feature && 'geometry' in this.feature ? this.feature.geometry : null; + } + canonicalID() { + return this.canonical; + } + properties() { + return this.feature && this.feature.properties || {}; + } + parseColor(input) { + let cached = this._parseColorCache[input]; + if (!cached) { + cached = this._parseColorCache[input] = Color.parse(input); + } + return cached; + } +} + +/** + * State associated parsing at a given point in an expression tree. + * @private + */ +class ParsingContext { + constructor(registry, isConstantFunc, path = [], expectedType, scope = new Scope(), errors = []) { + this.registry = registry; + this.path = path; + this.key = path.map(part => `[${part}]`).join(''); + this.scope = scope; + this.errors = errors; + this.expectedType = expectedType; + this._isConstant = isConstantFunc; + } + /** + * @param expr the JSON expression to parse + * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed + * @param options + * @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. + * @private + */ + parse(expr, index, expectedType, bindings, options = {}) { + if (index) { + return this.concat(index, expectedType, bindings)._parse(expr, options); + } + return this._parse(expr, options); + } + _parse(expr, options) { + if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') { + expr = ['literal', expr]; + } + function annotate(parsed, type, typeAnnotation) { + if (typeAnnotation === 'assert') { + return new Assertion(type, [parsed]); + } + else if (typeAnnotation === 'coerce') { + return new Coercion(type, [parsed]); + } + else { + return parsed; + } + } + if (Array.isArray(expr)) { + if (expr.length === 0) { + return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].'); + } + const op = expr[0]; + if (typeof op !== 'string') { + this.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use ["literal", [...]].`, 0); + return null; + } + const Expr = this.registry[op]; + if (Expr) { + let parsed = Expr.parse(expr, this); + if (!parsed) + return null; + if (this.expectedType) { + const expected = this.expectedType; + const actual = parsed.type; + // When we expect a number, string, boolean, or array but have a value, wrap it in an assertion. + // When we expect a color or formatted string, but have a string or value, wrap it in a coercion. + // Otherwise, we do static type-checking. + // + // These behaviors are overridable for: + // * The "coalesce" operator, which needs to omit type annotations. + // * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion. + // + if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') { + parsed = annotate(parsed, expected, options.typeAnnotation || 'assert'); + } + else if ((expected.kind === 'color' || expected.kind === 'formatted' || expected.kind === 'resolvedImage') && (actual.kind === 'value' || actual.kind === 'string')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } + else if (expected.kind === 'padding' && (actual.kind === 'value' || actual.kind === 'number' || actual.kind === 'array')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } + else if (expected.kind === 'variableAnchorOffsetCollection' && (actual.kind === 'value' || actual.kind === 'array')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } + else if (this.checkSubtype(expected, actual)) { + return null; + } + } + // If an expression's arguments are all literals, we can evaluate + // it immediately and replace it with a literal value in the + // parsed/compiled result. Expressions that expect an image should + // not be resolved here so we can later get the available images. + if (!(parsed instanceof Literal) && (parsed.type.kind !== 'resolvedImage') && this._isConstant(parsed)) { + const ec = new EvaluationContext(); + try { + parsed = new Literal(parsed.type, parsed.evaluate(ec)); + } + catch (e) { + this.error(e.message); + return null; + } + } + return parsed; + } + return this.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); + } + else if (typeof expr === 'undefined') { + return this.error('\'undefined\' value invalid. Use null instead.'); + } + else if (typeof expr === 'object') { + return this.error('Bare objects invalid. Use ["literal", {...}] instead.'); + } + else { + return this.error(`Expected an array, but found ${typeof expr} instead.`); + } + } + /** + * Returns a copy of this context suitable for parsing the subexpression at + * index `index`, optionally appending to 'let' binding map. + * + * Note that `errors` property, intended for collecting errors while + * parsing, is copied by reference rather than cloned. + * @private + */ + concat(index, expectedType, bindings) { + const path = typeof index === 'number' ? this.path.concat(index) : this.path; + const scope = bindings ? this.scope.concat(bindings) : this.scope; + return new ParsingContext(this.registry, this._isConstant, path, expectedType || null, scope, this.errors); + } + /** + * Push a parsing (or type checking) error into the `this.errors` + * @param error The message + * @param keys Optionally specify the source of the error at a child + * of the current expression at `this.key`. + * @private + */ + error(error, ...keys) { + const key = `${this.key}${keys.map(k => `[${k}]`).join('')}`; + this.errors.push(new ExpressionParsingError(key, error)); + } + /** + * Returns null if `t` is a subtype of `expected`; otherwise returns an + * error message and also pushes it to `this.errors`. + * @param expected The expected type + * @param t The actual type + * @returns null if `t` is a subtype of `expected`; otherwise returns an error message + */ + checkSubtype(expected, t) { + const error = checkSubtype(expected, t); + if (error) + this.error(error); + return error; + } +} + +class Let { + constructor(bindings, result) { + this.type = result.type; + this.bindings = [].concat(bindings); + this.result = result; + } + evaluate(ctx) { + return this.result.evaluate(ctx); + } + eachChild(fn) { + for (const binding of this.bindings) { + fn(binding[1]); + } + fn(this.result); + } + static parse(args, context) { + if (args.length < 4) + return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`); + const bindings = []; + for (let i = 1; i < args.length - 1; i += 2) { + const name = args[i]; + if (typeof name !== 'string') { + return context.error(`Expected string, but found ${typeof name} instead.`, i); + } + if (/[^a-zA-Z0-9_]/.test(name)) { + return context.error('Variable names must contain only alphanumeric characters or \'_\'.', i); + } + const value = context.parse(args[i + 1], i + 1); + if (!value) + return null; + bindings.push([name, value]); + } + const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings); + if (!result) + return null; + return new Let(bindings, result); + } + outputDefined() { + return this.result.outputDefined(); + } +} + +class Var { + constructor(name, boundExpression) { + this.type = boundExpression.type; + this.name = name; + this.boundExpression = boundExpression; + } + static parse(args, context) { + if (args.length !== 2 || typeof args[1] !== 'string') + return context.error('\'var\' expression requires exactly one string literal argument.'); + const name = args[1]; + if (!context.scope.has(name)) { + return context.error(`Unknown variable "${name}". Make sure "${name}" has been bound in an enclosing "let" expression before using it.`, 1); + } + return new Var(name, context.scope.get(name)); + } + evaluate(ctx) { + return this.boundExpression.evaluate(ctx); + } + eachChild() { } + outputDefined() { + return false; + } +} + +class At { + constructor(type, index, input) { + this.type = type; + this.index = index; + this.input = input; + } + static parse(args, context) { + if (args.length !== 3) + return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); + const index = context.parse(args[1], 1, NumberType); + const input = context.parse(args[2], 2, array$1(context.expectedType || ValueType)); + if (!index || !input) + return null; + const t = input.type; + return new At(t.itemType, index, input); + } + evaluate(ctx) { + const index = this.index.evaluate(ctx); + const array = this.input.evaluate(ctx); + if (index < 0) { + throw new RuntimeError(`Array index out of bounds: ${index} < 0.`); + } + if (index >= array.length) { + throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`); + } + if (index !== Math.floor(index)) { + throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`); + } + return array[index]; + } + eachChild(fn) { + fn(this.index); + fn(this.input); + } + outputDefined() { + return false; + } +} + +class In { + constructor(needle, haystack) { + this.type = BooleanType; + this.needle = needle; + this.haystack = haystack; + } + static parse(args, context) { + if (args.length !== 3) { + return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); + } + const needle = context.parse(args[1], 1, ValueType); + const haystack = context.parse(args[2], 2, ValueType); + if (!needle || !haystack) + return null; + if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) { + return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(needle.type)} instead`); + } + return new In(needle, haystack); + } + evaluate(ctx) { + const needle = this.needle.evaluate(ctx); + const haystack = this.haystack.evaluate(ctx); + if (!haystack) + return false; + if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) { + throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(typeOf(needle))} instead.`); + } + if (!isValidNativeType(haystack, ['string', 'array'])) { + throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString$1(typeOf(haystack))} instead.`); + } + return haystack.indexOf(needle) >= 0; + } + eachChild(fn) { + fn(this.needle); + fn(this.haystack); + } + outputDefined() { + return true; + } +} + +class IndexOf { + constructor(needle, haystack, fromIndex) { + this.type = NumberType; + this.needle = needle; + this.haystack = haystack; + this.fromIndex = fromIndex; + } + static parse(args, context) { + if (args.length <= 2 || args.length >= 5) { + return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`); + } + const needle = context.parse(args[1], 1, ValueType); + const haystack = context.parse(args[2], 2, ValueType); + if (!needle || !haystack) + return null; + if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) { + return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(needle.type)} instead`); + } + if (args.length === 4) { + const fromIndex = context.parse(args[3], 3, NumberType); + if (!fromIndex) + return null; + return new IndexOf(needle, haystack, fromIndex); + } + else { + return new IndexOf(needle, haystack); + } + } + evaluate(ctx) { + const needle = this.needle.evaluate(ctx); + const haystack = this.haystack.evaluate(ctx); + if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) { + throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString$1(typeOf(needle))} instead.`); + } + let fromIndex; + if (this.fromIndex) { + fromIndex = this.fromIndex.evaluate(ctx); + } + if (isValidNativeType(haystack, ['string'])) { + const rawIndex = haystack.indexOf(needle, fromIndex); + if (rawIndex === -1) { + return -1; + } + else { + // The index may be affected by surrogate pairs, so get the length of the preceding substring. + return [...haystack.slice(0, rawIndex)].length; + } + } + else if (isValidNativeType(haystack, ['array'])) { + return haystack.indexOf(needle, fromIndex); + } + else { + throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString$1(typeOf(haystack))} instead.`); + } + } + eachChild(fn) { + fn(this.needle); + fn(this.haystack); + if (this.fromIndex) { + fn(this.fromIndex); + } + } + outputDefined() { + return false; + } +} + +class Match { + constructor(inputType, outputType, input, cases, outputs, otherwise) { + this.inputType = inputType; + this.type = outputType; + this.input = input; + this.cases = cases; + this.outputs = outputs; + this.otherwise = otherwise; + } + static parse(args, context) { + if (args.length < 5) + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + if (args.length % 2 !== 1) + return context.error('Expected an even number of arguments.'); + let inputType; + let outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + const cases = {}; + const outputs = []; + for (let i = 2; i < args.length - 1; i += 2) { + let labels = args[i]; + const value = args[i + 1]; + if (!Array.isArray(labels)) { + labels = [labels]; + } + const labelContext = context.concat(i); + if (labels.length === 0) { + return labelContext.error('Expected at least one branch label.'); + } + for (const label of labels) { + if (typeof label !== 'number' && typeof label !== 'string') { + return labelContext.error('Branch labels must be numbers or strings.'); + } + else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) { + return labelContext.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`); + } + else if (typeof label === 'number' && Math.floor(label) !== label) { + return labelContext.error('Numeric branch labels must be integer values.'); + } + else if (!inputType) { + inputType = typeOf(label); + } + else if (labelContext.checkSubtype(inputType, typeOf(label))) { + return null; + } + if (typeof cases[String(label)] !== 'undefined') { + return labelContext.error('Branch labels must be unique.'); + } + cases[String(label)] = outputs.length; + } + const result = context.parse(value, i, outputType); + if (!result) + return null; + outputType = outputType || result.type; + outputs.push(result); + } + const input = context.parse(args[1], 1, ValueType); + if (!input) + return null; + const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) + return null; + if (input.type.kind !== 'value' && context.concat(1).checkSubtype(inputType, input.type)) { + return null; + } + return new Match(inputType, outputType, input, cases, outputs, otherwise); + } + evaluate(ctx) { + const input = this.input.evaluate(ctx); + const output = (typeOf(input) === this.inputType && this.outputs[this.cases[input]]) || this.otherwise; + return output.evaluate(ctx); + } + eachChild(fn) { + fn(this.input); + this.outputs.forEach(fn); + fn(this.otherwise); + } + outputDefined() { + return this.outputs.every(out => out.outputDefined()) && this.otherwise.outputDefined(); + } +} + +class Case { + constructor(type, branches, otherwise) { + this.type = type; + this.branches = branches; + this.otherwise = otherwise; + } + static parse(args, context) { + if (args.length < 4) + return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`); + if (args.length % 2 !== 0) + return context.error('Expected an odd number of arguments.'); + let outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + const branches = []; + for (let i = 1; i < args.length - 1; i += 2) { + const test = context.parse(args[i], i, BooleanType); + if (!test) + return null; + const result = context.parse(args[i + 1], i + 1, outputType); + if (!result) + return null; + branches.push([test, result]); + outputType = outputType || result.type; + } + const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) + return null; + if (!outputType) + throw new Error('Can\'t infer output type'); + return new Case(outputType, branches, otherwise); + } + evaluate(ctx) { + for (const [test, expression] of this.branches) { + if (test.evaluate(ctx)) { + return expression.evaluate(ctx); + } + } + return this.otherwise.evaluate(ctx); + } + eachChild(fn) { + for (const [test, expression] of this.branches) { + fn(test); + fn(expression); + } + fn(this.otherwise); + } + outputDefined() { + return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined(); + } +} + +class Slice { + constructor(type, input, beginIndex, endIndex) { + this.type = type; + this.input = input; + this.beginIndex = beginIndex; + this.endIndex = endIndex; + } + static parse(args, context) { + if (args.length <= 2 || args.length >= 5) { + return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`); + } + const input = context.parse(args[1], 1, ValueType); + const beginIndex = context.parse(args[2], 2, NumberType); + if (!input || !beginIndex) + return null; + if (!isValidType(input.type, [array$1(ValueType), StringType, ValueType])) { + return context.error(`Expected first argument to be of type array or string, but found ${toString$1(input.type)} instead`); + } + if (args.length === 4) { + const endIndex = context.parse(args[3], 3, NumberType); + if (!endIndex) + return null; + return new Slice(input.type, input, beginIndex, endIndex); + } + else { + return new Slice(input.type, input, beginIndex); + } + } + evaluate(ctx) { + const input = this.input.evaluate(ctx); + const beginIndex = this.beginIndex.evaluate(ctx); + let endIndex; + if (this.endIndex) { + endIndex = this.endIndex.evaluate(ctx); + } + if (isValidNativeType(input, ['string'])) { + // Indices may be affected by surrogate pairs. + return [...input].slice(beginIndex, endIndex).join(''); + } + else if (isValidNativeType(input, ['array'])) { + return input.slice(beginIndex, endIndex); + } + else { + throw new RuntimeError(`Expected first argument to be of type array or string, but found ${toString$1(typeOf(input))} instead.`); + } + } + eachChild(fn) { + fn(this.input); + fn(this.beginIndex); + if (this.endIndex) { + fn(this.endIndex); + } + } + outputDefined() { + return false; + } +} + +/** + * Returns the index of the last stop <= input, or 0 if it doesn't exist. + * @private + */ +function findStopLessThanOrEqualTo(stops, input) { + const lastIndex = stops.length - 1; + let lowerIndex = 0; + let upperIndex = lastIndex; + let currentIndex = 0; + let currentValue, nextValue; + while (lowerIndex <= upperIndex) { + currentIndex = Math.floor((lowerIndex + upperIndex) / 2); + currentValue = stops[currentIndex]; + nextValue = stops[currentIndex + 1]; + if (currentValue <= input) { + if (currentIndex === lastIndex || input < nextValue) { // Search complete + return currentIndex; + } + lowerIndex = currentIndex + 1; + } + else if (currentValue > input) { + upperIndex = currentIndex - 1; + } + else { + throw new RuntimeError('Input is not a number.'); + } + } + return 0; +} + +class Step { + constructor(type, input, stops) { + this.type = type; + this.input = input; + this.labels = []; + this.outputs = []; + for (const [label, expression] of stops) { + this.labels.push(label); + this.outputs.push(expression); + } + } + static parse(args, context) { + if (args.length - 1 < 4) { + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + } + if ((args.length - 1) % 2 !== 0) { + return context.error('Expected an even number of arguments.'); + } + const input = context.parse(args[1], 1, NumberType); + if (!input) + return null; + const stops = []; + let outputType = null; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + for (let i = 1; i < args.length; i += 2) { + const label = i === 1 ? -Infinity : args[i]; + const value = args[i + 1]; + const labelKey = i; + const valueKey = i + 1; + if (typeof label !== 'number') { + return context.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + const parsed = context.parse(value, valueKey, outputType); + if (!parsed) + return null; + outputType = outputType || parsed.type; + stops.push([label, parsed]); + } + return new Step(outputType, input, stops); + } + evaluate(ctx) { + const labels = this.labels; + const outputs = this.outputs; + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + const value = this.input.evaluate(ctx); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + const stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + const index = findStopLessThanOrEqualTo(labels, value); + return outputs[index].evaluate(ctx); + } + eachChild(fn) { + fn(this.input); + for (const expression of this.outputs) { + fn(expression); + } + } + outputDefined() { + return this.outputs.every(out => out.outputDefined()); + } +} + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var unitbezier = UnitBezier; + +function UnitBezier(p1x, p1y, p2x, p2y) { + // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). + this.cx = 3.0 * p1x; + this.bx = 3.0 * (p2x - p1x) - this.cx; + this.ax = 1.0 - this.cx - this.bx; + + this.cy = 3.0 * p1y; + this.by = 3.0 * (p2y - p1y) - this.cy; + this.ay = 1.0 - this.cy - this.by; + + this.p1x = p1x; + this.p1y = p1y; + this.p2x = p2x; + this.p2y = p2y; +} + +UnitBezier.prototype = { + sampleCurveX: function (t) { + // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. + return ((this.ax * t + this.bx) * t + this.cx) * t; + }, + + sampleCurveY: function (t) { + return ((this.ay * t + this.by) * t + this.cy) * t; + }, + + sampleCurveDerivativeX: function (t) { + return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; + }, + + solveCurveX: function (x, epsilon) { + if (epsilon === undefined) epsilon = 1e-6; + + if (x < 0.0) return 0.0; + if (x > 1.0) return 1.0; + + var t = x; + + // First try a few iterations of Newton's method - normally very fast. + for (var i = 0; i < 8; i++) { + var x2 = this.sampleCurveX(t) - x; + if (Math.abs(x2) < epsilon) return t; + + var d2 = this.sampleCurveDerivativeX(t); + if (Math.abs(d2) < 1e-6) break; + + t = t - x2 / d2; + } + + // Fall back to the bisection method for reliability. + var t0 = 0.0; + var t1 = 1.0; + t = x; + + for (i = 0; i < 20; i++) { + x2 = this.sampleCurveX(t); + if (Math.abs(x2 - x) < epsilon) break; + + if (x > x2) { + t0 = t; + } else { + t1 = t; + } + + t = (t1 - t0) * 0.5 + t0; + } + + return t; + }, + + solve: function (x, epsilon) { + return this.sampleCurveY(this.solveCurveX(x, epsilon)); + } +}; + +var UnitBezier$1 = /*@__PURE__*/getDefaultExportFromCjs(unitbezier); + +/** + * Checks whether the specified color space is one of the supported interpolation color spaces. + * + * @param colorSpace Color space key to verify. + * @returns `true` if the specified color space is one of the supported + * interpolation color spaces, `false` otherwise + */ +function isSupportedInterpolationColorSpace(colorSpace) { + return colorSpace === 'rgb' || colorSpace === 'hcl' || colorSpace === 'lab'; +} +function number(from, to, t) { + return from + t * (to - from); +} +function color(from, to, t, spaceKey = 'rgb') { + switch (spaceKey) { + case 'rgb': { + const [r, g, b, alpha] = array(from.rgb, to.rgb, t); + return new Color(r, g, b, alpha, false); + } + case 'hcl': { + const [hue0, chroma0, light0, alphaF] = from.hcl; + const [hue1, chroma1, light1, alphaT] = to.hcl; + // https://github.com/gka/chroma.js/blob/cd1b3c0926c7a85cbdc3b1453b3a94006de91a92/src/interpolator/_hsx.js + let hue, chroma; + if (!isNaN(hue0) && !isNaN(hue1)) { + let dh = hue1 - hue0; + if (hue1 > hue0 && dh > 180) { + dh -= 360; + } + else if (hue1 < hue0 && hue0 - hue1 > 180) { + dh += 360; + } + hue = hue0 + t * dh; + } + else if (!isNaN(hue0)) { + hue = hue0; + if (light1 === 1 || light1 === 0) + chroma = chroma0; + } + else if (!isNaN(hue1)) { + hue = hue1; + if (light0 === 1 || light0 === 0) + chroma = chroma1; + } + else { + hue = NaN; + } + const [r, g, b, alpha] = hclToRgb([ + hue, + chroma !== null && chroma !== void 0 ? chroma : number(chroma0, chroma1, t), + number(light0, light1, t), + number(alphaF, alphaT, t), + ]); + return new Color(r, g, b, alpha, false); + } + case 'lab': { + const [r, g, b, alpha] = labToRgb(array(from.lab, to.lab, t)); + return new Color(r, g, b, alpha, false); + } + } +} +function array(from, to, t) { + return from.map((d, i) => { + return number(d, to[i], t); + }); +} +function padding(from, to, t) { + return new Padding(array(from.values, to.values, t)); +} +function variableAnchorOffsetCollection(from, to, t) { + const fromValues = from.values; + const toValues = to.values; + if (fromValues.length !== toValues.length) { + throw new RuntimeError(`Cannot interpolate values of different length. from: ${from.toString()}, to: ${to.toString()}`); + } + const output = []; + for (let i = 0; i < fromValues.length; i += 2) { + // Anchor entries must match + if (fromValues[i] !== toValues[i]) { + throw new RuntimeError(`Cannot interpolate values containing mismatched anchors. from[${i}]: ${fromValues[i]}, to[${i}]: ${toValues[i]}`); + } + output.push(fromValues[i]); + // Interpolate the offset values for each anchor + const [fx, fy] = fromValues[i + 1]; + const [tx, ty] = toValues[i + 1]; + output.push([number(fx, tx, t), number(fy, ty, t)]); + } + return new VariableAnchorOffsetCollection(output); +} +const interpolate = { + number, + color, + array, + padding, + variableAnchorOffsetCollection +}; + +class Interpolate { + constructor(type, operator, interpolation, input, stops) { + this.type = type; + this.operator = operator; + this.interpolation = interpolation; + this.input = input; + this.labels = []; + this.outputs = []; + for (const [label, expression] of stops) { + this.labels.push(label); + this.outputs.push(expression); + } + } + static interpolationFactor(interpolation, input, lower, upper) { + let t = 0; + if (interpolation.name === 'exponential') { + t = exponentialInterpolation(input, interpolation.base, lower, upper); + } + else if (interpolation.name === 'linear') { + t = exponentialInterpolation(input, 1, lower, upper); + } + else if (interpolation.name === 'cubic-bezier') { + const c = interpolation.controlPoints; + const ub = new UnitBezier$1(c[0], c[1], c[2], c[3]); + t = ub.solve(exponentialInterpolation(input, 1, lower, upper)); + } + return t; + } + static parse(args, context) { + let [operator, interpolation, input, ...rest] = args; + if (!Array.isArray(interpolation) || interpolation.length === 0) { + return context.error('Expected an interpolation type expression.', 1); + } + if (interpolation[0] === 'linear') { + interpolation = { name: 'linear' }; + } + else if (interpolation[0] === 'exponential') { + const base = interpolation[1]; + if (typeof base !== 'number') + return context.error('Exponential interpolation requires a numeric base.', 1, 1); + interpolation = { + name: 'exponential', + base + }; + } + else if (interpolation[0] === 'cubic-bezier') { + const controlPoints = interpolation.slice(1); + if (controlPoints.length !== 4 || + controlPoints.some(t => typeof t !== 'number' || t < 0 || t > 1)) { + return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1); + } + interpolation = { + name: 'cubic-bezier', + controlPoints: controlPoints + }; + } + else { + return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0); + } + if (args.length - 1 < 4) { + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + } + if ((args.length - 1) % 2 !== 0) { + return context.error('Expected an even number of arguments.'); + } + input = context.parse(input, 2, NumberType); + if (!input) + return null; + const stops = []; + let outputType = null; + if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') { + outputType = ColorType; + } + else if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + for (let i = 0; i < rest.length; i += 2) { + const label = rest[i]; + const value = rest[i + 1]; + const labelKey = i + 3; + const valueKey = i + 4; + if (typeof label !== 'number') { + return context.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + const parsed = context.parse(value, valueKey, outputType); + if (!parsed) + return null; + outputType = outputType || parsed.type; + stops.push([label, parsed]); + } + if (!verifyType(outputType, NumberType) && + !verifyType(outputType, ColorType) && + !verifyType(outputType, PaddingType) && + !verifyType(outputType, VariableAnchorOffsetCollectionType) && + !verifyType(outputType, array$1(NumberType))) { + return context.error(`Type ${toString$1(outputType)} is not interpolatable.`); + } + return new Interpolate(outputType, operator, interpolation, input, stops); + } + evaluate(ctx) { + const labels = this.labels; + const outputs = this.outputs; + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + const value = this.input.evaluate(ctx); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + const stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + const index = findStopLessThanOrEqualTo(labels, value); + const lower = labels[index]; + const upper = labels[index + 1]; + const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper); + const outputLower = outputs[index].evaluate(ctx); + const outputUpper = outputs[index + 1].evaluate(ctx); + switch (this.operator) { + case 'interpolate': + return interpolate[this.type.kind](outputLower, outputUpper, t); + case 'interpolate-hcl': + return interpolate.color(outputLower, outputUpper, t, 'hcl'); + case 'interpolate-lab': + return interpolate.color(outputLower, outputUpper, t, 'lab'); + } + } + eachChild(fn) { + fn(this.input); + for (const expression of this.outputs) { + fn(expression); + } + } + outputDefined() { + return this.outputs.every(out => out.outputDefined()); + } +} +/** + * Returns a ratio that can be used to interpolate between exponential function + * stops. + * 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, + * and `a` and `b` are constants affording sufficient degrees of freedom to fit + * the function to the given stops. + * + * Here's a bit of algebra that lets us compute `f(x)` directly from the stop + * values without explicitly solving for `a` and `b`: + * + * First stop value: `f(x0) = y0 = a * base^x0 + b` + * Second stop value: `f(x1) = y1 = a * base^x1 + b` + * => `y1 - y0 = a(base^x1 - base^x0)` + * => `a = (y1 - y0)/(base^x1 - base^x0)` + * + * Desired value: `f(x) = y = a * base^x + b` + * => `f(x) = y0 + a * (base^x - base^x0)` + * + * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a + * little algebra: + * ``` + * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) + * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) + * ``` + * + * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have + * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as + * an interpolation factor between the two stops' output values. + * + * (Note: a slightly different form for `ratio`, + * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer + * expensive `Math.pow()` operations.) + * + * @private +*/ +function exponentialInterpolation(input, base, lowerValue, upperValue) { + const difference = upperValue - lowerValue; + const progress = input - lowerValue; + if (difference === 0) { + return 0; + } + else if (base === 1) { + return progress / difference; + } + else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} + +class Coalesce { + constructor(type, args) { + this.type = type; + this.args = args; + } + static parse(args, context) { + if (args.length < 2) { + return context.error('Expectected at least one argument.'); + } + let outputType = null; + const expectedType = context.expectedType; + if (expectedType && expectedType.kind !== 'value') { + outputType = expectedType; + } + const parsedArgs = []; + for (const arg of args.slice(1)) { + const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, { typeAnnotation: 'omit' }); + if (!parsed) + return null; + outputType = outputType || parsed.type; + parsedArgs.push(parsed); + } + if (!outputType) + throw new Error('No output type'); + // Above, we parse arguments without inferred type annotation so that + // they don't produce a runtime error for `null` input, which would + // preempt the desired null-coalescing behavior. + // Thus, if any of our arguments would have needed an annotation, we + // need to wrap the enclosing coalesce expression with it instead. + const needsAnnotation = expectedType && + parsedArgs.some(arg => checkSubtype(expectedType, arg.type)); + return needsAnnotation ? + new Coalesce(ValueType, parsedArgs) : + new Coalesce(outputType, parsedArgs); + } + evaluate(ctx) { + let result = null; + let argCount = 0; + let requestedImageName; + for (const arg of this.args) { + argCount++; + result = arg.evaluate(ctx); + // we need to keep track of the first requested image in a coalesce statement + // if coalesce can't find a valid image, we return the first image name so styleimagemissing can fire + if (result && result instanceof ResolvedImage && !result.available) { + if (!requestedImageName) { + requestedImageName = result.name; + } + result = null; + if (argCount === this.args.length) { + result = requestedImageName; + } + } + if (result !== null) + break; + } + return result; + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return this.args.every(arg => arg.outputDefined()); + } +} + +function isComparableType(op, type) { + if (op === '==' || op === '!=') { + // equality operator + return type.kind === 'boolean' || + type.kind === 'string' || + type.kind === 'number' || + type.kind === 'null' || + type.kind === 'value'; + } + else { + // ordering operator + return type.kind === 'string' || + type.kind === 'number' || + type.kind === 'value'; + } +} +function eq(ctx, a, b) { return a === b; } +function neq(ctx, a, b) { return a !== b; } +function lt(ctx, a, b) { return a < b; } +function gt(ctx, a, b) { return a > b; } +function lteq(ctx, a, b) { return a <= b; } +function gteq(ctx, a, b) { return a >= b; } +function eqCollate(ctx, a, b, c) { return c.compare(a, b) === 0; } +function neqCollate(ctx, a, b, c) { return !eqCollate(ctx, a, b, c); } +function ltCollate(ctx, a, b, c) { return c.compare(a, b) < 0; } +function gtCollate(ctx, a, b, c) { return c.compare(a, b) > 0; } +function lteqCollate(ctx, a, b, c) { return c.compare(a, b) <= 0; } +function gteqCollate(ctx, a, b, c) { return c.compare(a, b) >= 0; } +/** + * Special form for comparison operators, implementing the signatures: + * - (T, T, ?Collator) => boolean + * - (T, value, ?Collator) => boolean + * - (value, T, ?Collator) => boolean + * + * For inequalities, T must be either value, string, or number. For ==/!=, it + * can also be boolean or null. + * + * Equality semantics are equivalent to Javascript's strict equality (===/!==) + * -- i.e., when the arguments' types don't match, == evaluates to false, != to + * true. + * + * When types don't match in an ordering comparison, a runtime error is thrown. + * + * @private + */ +function makeComparison(op, compareBasic, compareWithCollator) { + const isOrderComparison = op !== '==' && op !== '!='; + return class Comparison { + constructor(lhs, rhs, collator) { + this.type = BooleanType; + this.lhs = lhs; + this.rhs = rhs; + this.collator = collator; + this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value'; + } + static parse(args, context) { + if (args.length !== 3 && args.length !== 4) + return context.error('Expected two or three arguments.'); + const op = args[0]; + let lhs = context.parse(args[1], 1, ValueType); + if (!lhs) + return null; + if (!isComparableType(op, lhs.type)) { + return context.concat(1).error(`"${op}" comparisons are not supported for type '${toString$1(lhs.type)}'.`); + } + let rhs = context.parse(args[2], 2, ValueType); + if (!rhs) + return null; + if (!isComparableType(op, rhs.type)) { + return context.concat(2).error(`"${op}" comparisons are not supported for type '${toString$1(rhs.type)}'.`); + } + if (lhs.type.kind !== rhs.type.kind && + lhs.type.kind !== 'value' && + rhs.type.kind !== 'value') { + return context.error(`Cannot compare types '${toString$1(lhs.type)}' and '${toString$1(rhs.type)}'.`); + } + if (isOrderComparison) { + // typing rules specific to less/greater than operators + if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') { + // (value, T) + lhs = new Assertion(rhs.type, [lhs]); + } + else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') { + // (T, value) + rhs = new Assertion(lhs.type, [rhs]); + } + } + let collator = null; + if (args.length === 4) { + if (lhs.type.kind !== 'string' && + rhs.type.kind !== 'string' && + lhs.type.kind !== 'value' && + rhs.type.kind !== 'value') { + return context.error('Cannot use collator to compare non-string types.'); + } + collator = context.parse(args[3], 3, CollatorType); + if (!collator) + return null; + } + return new Comparison(lhs, rhs, collator); + } + evaluate(ctx) { + const lhs = this.lhs.evaluate(ctx); + const rhs = this.rhs.evaluate(ctx); + if (isOrderComparison && this.hasUntypedArgument) { + const lt = typeOf(lhs); + const rt = typeOf(rhs); + // check that type is string or number, and equal + if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) { + throw new RuntimeError(`Expected arguments for "${op}" to be (string, string) or (number, number), but found (${lt.kind}, ${rt.kind}) instead.`); + } + } + if (this.collator && !isOrderComparison && this.hasUntypedArgument) { + const lt = typeOf(lhs); + const rt = typeOf(rhs); + if (lt.kind !== 'string' || rt.kind !== 'string') { + return compareBasic(ctx, lhs, rhs); + } + } + return this.collator ? + compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) : + compareBasic(ctx, lhs, rhs); + } + eachChild(fn) { + fn(this.lhs); + fn(this.rhs); + if (this.collator) { + fn(this.collator); + } + } + outputDefined() { + return true; + } + }; +} +const Equals = makeComparison('==', eq, eqCollate); +const NotEquals = makeComparison('!=', neq, neqCollate); +const LessThan = makeComparison('<', lt, ltCollate); +const GreaterThan = makeComparison('>', gt, gtCollate); +const LessThanOrEqual = makeComparison('<=', lteq, lteqCollate); +const GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate); + +class CollatorExpression { + constructor(caseSensitive, diacriticSensitive, locale) { + this.type = CollatorType; + this.locale = locale; + this.caseSensitive = caseSensitive; + this.diacriticSensitive = diacriticSensitive; + } + static parse(args, context) { + if (args.length !== 2) + return context.error('Expected one argument.'); + const options = args[1]; + if (typeof options !== 'object' || Array.isArray(options)) + return context.error('Collator options argument must be an object.'); + const caseSensitive = context.parse(options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType); + if (!caseSensitive) + return null; + const diacriticSensitive = context.parse(options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType); + if (!diacriticSensitive) + return null; + let locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) + return null; + } + return new CollatorExpression(caseSensitive, diacriticSensitive, locale); + } + evaluate(ctx) { + return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null); + } + eachChild(fn) { + fn(this.caseSensitive); + fn(this.diacriticSensitive); + if (this.locale) { + fn(this.locale); + } + } + outputDefined() { + // Technically the set of possible outputs is the combinatoric set of Collators produced + // by all possible outputs of locale/caseSensitive/diacriticSensitive + // But for the primary use of Collators in comparison operators, we ignore the Collator's + // possible outputs anyway, so we can get away with leaving this false for now. + return false; + } +} + +class NumberFormat { + constructor(number, locale, currency, minFractionDigits, maxFractionDigits) { + this.type = StringType; + this.number = number; + this.locale = locale; + this.currency = currency; + this.minFractionDigits = minFractionDigits; + this.maxFractionDigits = maxFractionDigits; + } + static parse(args, context) { + if (args.length !== 3) + return context.error('Expected two arguments.'); + const number = context.parse(args[1], 1, NumberType); + if (!number) + return null; + const options = args[2]; + if (typeof options !== 'object' || Array.isArray(options)) + return context.error('NumberFormat options argument must be an object.'); + let locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) + return null; + } + let currency = null; + if (options['currency']) { + currency = context.parse(options['currency'], 1, StringType); + if (!currency) + return null; + } + let minFractionDigits = null; + if (options['min-fraction-digits']) { + minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType); + if (!minFractionDigits) + return null; + } + let maxFractionDigits = null; + if (options['max-fraction-digits']) { + maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType); + if (!maxFractionDigits) + return null; + } + return new NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits); + } + evaluate(ctx) { + return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], { + style: this.currency ? 'currency' : 'decimal', + currency: this.currency ? this.currency.evaluate(ctx) : undefined, + minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined, + maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined, + }).format(this.number.evaluate(ctx)); + } + eachChild(fn) { + fn(this.number); + if (this.locale) { + fn(this.locale); + } + if (this.currency) { + fn(this.currency); + } + if (this.minFractionDigits) { + fn(this.minFractionDigits); + } + if (this.maxFractionDigits) { + fn(this.maxFractionDigits); + } + } + outputDefined() { + return false; + } +} + +class FormatExpression { + constructor(sections) { + this.type = FormattedType; + this.sections = sections; + } + static parse(args, context) { + if (args.length < 2) { + return context.error('Expected at least one argument.'); + } + const firstArg = args[1]; + if (!Array.isArray(firstArg) && typeof firstArg === 'object') { + return context.error('First argument must be an image or text section.'); + } + const sections = []; + let nextTokenMayBeObject = false; + for (let i = 1; i <= args.length - 1; ++i) { + const arg = args[i]; + if (nextTokenMayBeObject && typeof arg === 'object' && !Array.isArray(arg)) { + nextTokenMayBeObject = false; + let scale = null; + if (arg['font-scale']) { + scale = context.parse(arg['font-scale'], 1, NumberType); + if (!scale) + return null; + } + let font = null; + if (arg['text-font']) { + font = context.parse(arg['text-font'], 1, array$1(StringType)); + if (!font) + return null; + } + let textColor = null; + if (arg['text-color']) { + textColor = context.parse(arg['text-color'], 1, ColorType); + if (!textColor) + return null; + } + const lastExpression = sections[sections.length - 1]; + lastExpression.scale = scale; + lastExpression.font = font; + lastExpression.textColor = textColor; + } + else { + const content = context.parse(args[i], 1, ValueType); + if (!content) + return null; + const kind = content.type.kind; + if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage') + return context.error('Formatted text type must be \'string\', \'value\', \'image\' or \'null\'.'); + nextTokenMayBeObject = true; + sections.push({ content, scale: null, font: null, textColor: null }); + } + } + return new FormatExpression(sections); + } + evaluate(ctx) { + const evaluateSection = section => { + const evaluatedContent = section.content.evaluate(ctx); + if (typeOf(evaluatedContent) === ResolvedImageType) { + return new FormattedSection('', evaluatedContent, null, null, null); + } + return new FormattedSection(toString(evaluatedContent), null, section.scale ? section.scale.evaluate(ctx) : null, section.font ? section.font.evaluate(ctx).join(',') : null, section.textColor ? section.textColor.evaluate(ctx) : null); + }; + return new Formatted(this.sections.map(evaluateSection)); + } + eachChild(fn) { + for (const section of this.sections) { + fn(section.content); + if (section.scale) { + fn(section.scale); + } + if (section.font) { + fn(section.font); + } + if (section.textColor) { + fn(section.textColor); + } + } + } + outputDefined() { + // Technically the combinatoric set of all children + // Usually, this.text will be undefined anyway + return false; + } +} + +class ImageExpression { + constructor(input) { + this.type = ResolvedImageType; + this.input = input; + } + static parse(args, context) { + if (args.length !== 2) { + return context.error('Expected two arguments.'); + } + const name = context.parse(args[1], 1, StringType); + if (!name) + return context.error('No image name provided.'); + return new ImageExpression(name); + } + evaluate(ctx) { + const evaluatedImageName = this.input.evaluate(ctx); + const value = ResolvedImage.fromString(evaluatedImageName); + if (value && ctx.availableImages) + value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1; + return value; + } + eachChild(fn) { + fn(this.input); + } + outputDefined() { + // The output of image is determined by the list of available images in the evaluation context + return false; + } +} + +class Length { + constructor(input) { + this.type = NumberType; + this.input = input; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`); + const input = context.parse(args[1], 1); + if (!input) + return null; + if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value') + return context.error(`Expected argument of type string or array, but found ${toString$1(input.type)} instead.`); + return new Length(input); + } + evaluate(ctx) { + const input = this.input.evaluate(ctx); + if (typeof input === 'string') { + // The length may be affected by surrogate pairs. + return [...input].length; + } + else if (Array.isArray(input)) { + return input.length; + } + else { + throw new RuntimeError(`Expected value to be of type string or array, but found ${toString$1(typeOf(input))} instead.`); + } + } + eachChild(fn) { + fn(this.input); + } + outputDefined() { + return false; + } +} + +const EXTENT$1 = 8192; +function getTileCoordinates(p, canonical) { + const x = mercatorXfromLng$1(p[0]); + const y = mercatorYfromLat$1(p[1]); + const tilesAtZoom = Math.pow(2, canonical.z); + return [Math.round(x * tilesAtZoom * EXTENT$1), Math.round(y * tilesAtZoom * EXTENT$1)]; +} +function getLngLatFromTileCoord(coord, canonical) { + const tilesAtZoom = Math.pow(2, canonical.z); + const x = (coord[0] / EXTENT$1 + canonical.x) / tilesAtZoom; + const y = (coord[1] / EXTENT$1 + canonical.y) / tilesAtZoom; + return [lngFromMercatorXfromLng(x), latFromMercatorY$1(y)]; +} +function mercatorXfromLng$1(lng) { + return (180 + lng) / 360; +} +function lngFromMercatorXfromLng(mercatorX) { + return mercatorX * 360 - 180; +} +function mercatorYfromLat$1(lat) { + return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360; +} +function latFromMercatorY$1(mercatorY) { + return 360 / Math.PI * Math.atan(Math.exp((180 - mercatorY * 360) * Math.PI / 180)) - 90; +} +function updateBBox(bbox, coord) { + bbox[0] = Math.min(bbox[0], coord[0]); + bbox[1] = Math.min(bbox[1], coord[1]); + bbox[2] = Math.max(bbox[2], coord[0]); + bbox[3] = Math.max(bbox[3], coord[1]); +} +function boxWithinBox(bbox1, bbox2) { + if (bbox1[0] <= bbox2[0]) + return false; + if (bbox1[2] >= bbox2[2]) + return false; + if (bbox1[1] <= bbox2[1]) + return false; + if (bbox1[3] >= bbox2[3]) + return false; + return true; +} +function rayIntersect(p, p1, p2) { + 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]); +} +function pointOnBoundary(p, p1, p2) { + const x1 = p[0] - p1[0]; + const y1 = p[1] - p1[1]; + const x2 = p[0] - p2[0]; + const y2 = p[1] - p2[1]; + return (x1 * y2 - x2 * y1 === 0) && (x1 * x2 <= 0) && (y1 * y2 <= 0); +} +// a, b are end points for line segment1, c and d are end points for line segment2 +function segmentIntersectSegment(a, b, c, d) { + // check if two segments are parallel or not + // precondition is end point a, b is inside polygon, if line a->b is + // parallel to polygon edge c->d, then a->b won't intersect with c->d + const vectorP = [b[0] - a[0], b[1] - a[1]]; + const vectorQ = [d[0] - c[0], d[1] - c[1]]; + if (perp(vectorQ, vectorP) === 0) + return false; + // If lines are intersecting with each other, the relative location should be: + // a and b lie in different sides of segment c->d + // c and d lie in different sides of segment a->b + if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) + return true; + return false; +} +function lineIntersectPolygon(p1, p2, polygon) { + for (const ring of polygon) { + // loop through every edge of the ring + for (let j = 0; j < ring.length - 1; ++j) { + if (segmentIntersectSegment(p1, p2, ring[j], ring[j + 1])) { + return true; + } + } + } + return false; +} +// ray casting algorithm for detecting if point is in polygon +function pointWithinPolygon(point, rings, trueIfOnBoundary = false) { + let inside = false; + for (const ring of rings) { + for (let j = 0; j < ring.length - 1; j++) { + if (pointOnBoundary(point, ring[j], ring[j + 1])) + return trueIfOnBoundary; + if (rayIntersect(point, ring[j], ring[j + 1])) + inside = !inside; + } + } + return inside; +} +function pointWithinPolygons(point, polygons) { + for (const polygon of polygons) { + if (pointWithinPolygon(point, polygon)) + return true; + } + return false; +} +function lineStringWithinPolygon(line, polygon) { + // First, check if geometry points of line segments are all inside polygon + for (const point of line) { + if (!pointWithinPolygon(point, polygon)) { + return false; + } + } + // Second, check if there is line segment intersecting polygon edge + for (let i = 0; i < line.length - 1; ++i) { + if (lineIntersectPolygon(line[i], line[i + 1], polygon)) { + return false; + } + } + return true; +} +function lineStringWithinPolygons(line, polygons) { + for (const polygon of polygons) { + if (lineStringWithinPolygon(line, polygon)) + return true; + } + return false; +} +function perp(v1, v2) { + return (v1[0] * v2[1] - v1[1] * v2[0]); +} +// check if p1 and p2 are in different sides of line segment q1->q2 +function twoSided(p1, p2, q1, q2) { + // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3) + const x1 = p1[0] - q1[0]; + const y1 = p1[1] - q1[1]; + const x2 = p2[0] - q1[0]; + const y2 = p2[1] - q1[1]; + const x3 = q2[0] - q1[0]; + const y3 = q2[1] - q1[1]; + const det1 = (x1 * y3 - x3 * y1); + const det2 = (x2 * y3 - x3 * y2); + if ((det1 > 0 && det2 < 0) || (det1 < 0 && det2 > 0)) + return true; + return false; +} + +function getTilePolygon(coordinates, bbox, canonical) { + const polygon = []; + for (let i = 0; i < coordinates.length; i++) { + const ring = []; + for (let j = 0; j < coordinates[i].length; j++) { + const coord = getTileCoordinates(coordinates[i][j], canonical); + updateBBox(bbox, coord); + ring.push(coord); + } + polygon.push(ring); + } + return polygon; +} +function getTilePolygons(coordinates, bbox, canonical) { + const polygons = []; + for (let i = 0; i < coordinates.length; i++) { + const polygon = getTilePolygon(coordinates[i], bbox, canonical); + polygons.push(polygon); + } + return polygons; +} +function updatePoint(p, bbox, polyBBox, worldSize) { + if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) { + const halfWorldSize = worldSize * 0.5; + let shift = (p[0] - polyBBox[0] > halfWorldSize) ? -worldSize : (polyBBox[0] - p[0] > halfWorldSize) ? worldSize : 0; + if (shift === 0) { + shift = (p[0] - polyBBox[2] > halfWorldSize) ? -worldSize : (polyBBox[2] - p[0] > halfWorldSize) ? worldSize : 0; + } + p[0] += shift; + } + updateBBox(bbox, p); +} +function resetBBox(bbox) { + bbox[0] = bbox[1] = Infinity; + bbox[2] = bbox[3] = -Infinity; +} +function getTilePoints(geometry, pointBBox, polyBBox, canonical) { + const worldSize = Math.pow(2, canonical.z) * EXTENT$1; + const shifts = [canonical.x * EXTENT$1, canonical.y * EXTENT$1]; + const tilePoints = []; + for (const points of geometry) { + for (const point of points) { + const p = [point.x + shifts[0], point.y + shifts[1]]; + updatePoint(p, pointBBox, polyBBox, worldSize); + tilePoints.push(p); + } + } + return tilePoints; +} +function getTileLines(geometry, lineBBox, polyBBox, canonical) { + const worldSize = Math.pow(2, canonical.z) * EXTENT$1; + const shifts = [canonical.x * EXTENT$1, canonical.y * EXTENT$1]; + const tileLines = []; + for (const line of geometry) { + const tileLine = []; + for (const point of line) { + const p = [point.x + shifts[0], point.y + shifts[1]]; + updateBBox(lineBBox, p); + tileLine.push(p); + } + tileLines.push(tileLine); + } + if (lineBBox[2] - lineBBox[0] <= worldSize / 2) { + resetBBox(lineBBox); + for (const line of tileLines) { + for (const p of line) { + updatePoint(p, lineBBox, polyBBox, worldSize); + } + } + } + return tileLines; +} +function pointsWithinPolygons(ctx, polygonGeometry) { + const pointBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const polyBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const canonical = ctx.canonicalID(); + if (polygonGeometry.type === 'Polygon') { + const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) + return false; + for (const point of tilePoints) { + if (!pointWithinPolygon(point, tilePolygon)) + return false; + } + } + if (polygonGeometry.type === 'MultiPolygon') { + const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) + return false; + for (const point of tilePoints) { + if (!pointWithinPolygons(point, tilePolygons)) + return false; + } + } + return true; +} +function linesWithinPolygons(ctx, polygonGeometry) { + const lineBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const polyBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const canonical = ctx.canonicalID(); + if (polygonGeometry.type === 'Polygon') { + const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) + return false; + for (const line of tileLines) { + if (!lineStringWithinPolygon(line, tilePolygon)) + return false; + } + } + if (polygonGeometry.type === 'MultiPolygon') { + const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) + return false; + for (const line of tileLines) { + if (!lineStringWithinPolygons(line, tilePolygons)) + return false; + } + } + return true; +} +class Within { + constructor(geojson, geometries) { + this.type = BooleanType; + this.geojson = geojson; + this.geometries = geometries; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (isValue(args[1])) { + const geojson = args[1]; + if (geojson.type === 'FeatureCollection') { + const polygonsCoords = []; + for (const polygon of geojson.features) { + const { type, coordinates } = polygon.geometry; + if (type === 'Polygon') { + polygonsCoords.push(coordinates); + } + if (type === 'MultiPolygon') { + polygonsCoords.push(...coordinates); + } + } + if (polygonsCoords.length) { + const multipolygonWrapper = { + type: 'MultiPolygon', + coordinates: polygonsCoords + }; + return new Within(geojson, multipolygonWrapper); + } + } + else if (geojson.type === 'Feature') { + const type = geojson.geometry.type; + if (type === 'Polygon' || type === 'MultiPolygon') { + return new Within(geojson, geojson.geometry); + } + } + else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') { + return new Within(geojson, geojson); + } + } + return context.error('\'within\' expression requires valid geojson object that contains polygon geometry type.'); + } + evaluate(ctx) { + if (ctx.geometry() != null && ctx.canonicalID() != null) { + if (ctx.geometryType() === 'Point') { + return pointsWithinPolygons(ctx, this.geometries); + } + else if (ctx.geometryType() === 'LineString') { + return linesWithinPolygons(ctx, this.geometries); + } + } + return false; + } + eachChild() { } + outputDefined() { + return true; + } +} + +let TinyQueue$1 = class TinyQueue { + constructor(data = [], compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) { + this.data = data; + this.length = this.data.length; + this.compare = compare; + + if (this.length > 0) { + for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i); + } + } + + push(item) { + this.data.push(item); + this._up(this.length++); + } + + pop() { + if (this.length === 0) return undefined; + + const top = this.data[0]; + const bottom = this.data.pop(); + + if (--this.length > 0) { + this.data[0] = bottom; + this._down(0); + } + + return top; + } + + peek() { + return this.data[0]; + } + + _up(pos) { + const {data, compare} = this; + const item = data[pos]; + + while (pos > 0) { + const parent = (pos - 1) >> 1; + const current = data[parent]; + if (compare(item, current) >= 0) break; + data[pos] = current; + pos = parent; + } + + data[pos] = item; + } + + _down(pos) { + const {data, compare} = this; + const halfLength = this.length >> 1; + const item = data[pos]; + + while (pos < halfLength) { + let bestChild = (pos << 1) + 1; // initially it is the left child + const right = bestChild + 1; + + if (right < this.length && compare(data[right], data[bestChild]) < 0) { + bestChild = right; + } + if (compare(data[bestChild], item) >= 0) break; + + data[pos] = data[bestChild]; + pos = bestChild; + } + + data[pos] = item; + } +}; + +function quickselect(arr, k, left, right, compare) { + quickselectStep(arr, k, left, right || (arr.length - 1), compare || defaultCompare); +} + +function quickselectStep(arr, k, left, right, compare) { + + while (right > left) { + if (right - left > 600) { + var n = right - left + 1; + var m = k - left + 1; + var z = Math.log(n); + var s = 0.5 * Math.exp(2 * z / 3); + var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + quickselectStep(arr, k, newLeft, newRight, compare); + } + + var t = arr[k]; + var i = left; + var j = right; + + swap$2(arr, left, k); + if (compare(arr[right], t) > 0) swap$2(arr, left, right); + + while (i < j) { + swap$2(arr, i, j); + i++; + j--; + while (compare(arr[i], t) < 0) i++; + while (compare(arr[j], t) > 0) j--; + } + + if (compare(arr[left], t) === 0) swap$2(arr, left, j); + else { + j++; + swap$2(arr, j, right); + } + + if (j <= k) left = j + 1; + if (k <= j) right = j - 1; + } +} + +function swap$2(arr, i, j) { + var tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} + +function defaultCompare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * Classifies an array of rings into polygons with outer rings and holes + * @param rings - the rings to classify + * @param maxRings - the maximum number of rings to include in a polygon, use 0 to include all rings + * @returns an array of polygons with internal rings as holes + */ +function classifyRings$1(rings, maxRings) { + const len = rings.length; + if (len <= 1) + return [rings]; + const polygons = []; + let polygon; + let ccw; + for (const ring of rings) { + const area = calculateSignedArea(ring); + if (area === 0) + continue; + ring.area = Math.abs(area); + if (ccw === undefined) + ccw = area < 0; + if (ccw === area < 0) { + if (polygon) + polygons.push(polygon); + polygon = [ring]; + } + else { + polygon.push(ring); + } + } + if (polygon) + polygons.push(polygon); + // Earcut performance degrades with the # of rings in a polygon. For this + // reason, we limit strip out all but the `maxRings` largest rings. + if (maxRings > 1) { + for (let j = 0; j < polygons.length; j++) { + if (polygons[j].length <= maxRings) + continue; + quickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas); + polygons[j] = polygons[j].slice(0, maxRings); + } + } + return polygons; +} +function compareAreas(a, b) { + return b.area - a.area; +} +/** + * Returns the signed area for the polygon ring. Positive areas are exterior rings and + * have a clockwise winding. Negative areas are interior rings and have a counter clockwise + * ordering. + * + * @param ring - Exterior or interior ring + * @returns Signed area + */ +function calculateSignedArea(ring) { + let sum = 0; + for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + return sum; +} + +// This is taken from https://github.com/mapbox/cheap-ruler/ in order to take only the relevant parts +// Values that define WGS84 ellipsoid model of the Earth +const RE = 6378.137; // equatorial radius +const FE = 1 / 298.257223563; // flattening +const E2 = FE * (2 - FE); +const RAD = Math.PI / 180; +class CheapRuler { + constructor(lat) { + // Curvature formulas from https://en.wikipedia.org/wiki/Earth_radius#Meridional + const m = RAD * RE * 1000; + const coslat = Math.cos(lat * RAD); + const w2 = 1 / (1 - E2 * (1 - coslat * coslat)); + const w = Math.sqrt(w2); + // multipliers for converting longitude and latitude degrees into distance + this.kx = m * w * coslat; // based on normal radius of curvature + this.ky = m * w * w2 * (1 - E2); // based on meridonal radius of curvature + } + /** + * Given two points of the form [longitude, latitude], returns the distance. + * + * @param a - point [longitude, latitude] + * @param b - point [longitude, latitude] + * @returns distance + * @example + * const distance = ruler.distance([30.5, 50.5], [30.51, 50.49]); + * //=distance + */ + distance(a, b) { + const dx = this.wrap(a[0] - b[0]) * this.kx; + const dy = (a[1] - b[1]) * this.ky; + return Math.sqrt(dx * dx + dy * dy); + } + /** + * Returns an object of the form {point, index, t}, where point is closest point on the line + * from the given point, index is the start index of the segment with the closest point, + * and t is a parameter from 0 to 1 that indicates where the closest point is on that segment. + * + * @param line - an array of points that form the line + * @param p - point [longitude, latitude] + * @returns the nearest point, its index in the array and the proportion along the line + * @example + * const point = ruler.pointOnLine(line, [-67.04, 50.5]).point; + * //=point + */ + pointOnLine(line, p) { + let minDist = Infinity; + let minX, minY, minI, minT; + for (let i = 0; i < line.length - 1; i++) { + let x = line[i][0]; + let y = line[i][1]; + let dx = this.wrap(line[i + 1][0] - x) * this.kx; + let dy = (line[i + 1][1] - y) * this.ky; + let t = 0; + if (dx !== 0 || dy !== 0) { + t = (this.wrap(p[0] - x) * this.kx * dx + (p[1] - y) * this.ky * dy) / (dx * dx + dy * dy); + if (t > 1) { + x = line[i + 1][0]; + y = line[i + 1][1]; + } + else if (t > 0) { + x += (dx / this.kx) * t; + y += (dy / this.ky) * t; + } + } + dx = this.wrap(p[0] - x) * this.kx; + dy = (p[1] - y) * this.ky; + const sqDist = dx * dx + dy * dy; + if (sqDist < minDist) { + minDist = sqDist; + minX = x; + minY = y; + minI = i; + minT = t; + } + } + return { + point: [minX, minY], + index: minI, + t: Math.max(0, Math.min(1, minT)) + }; + } + wrap(deg) { + while (deg < -180) + deg += 360; + while (deg > 180) + deg -= 360; + return deg; + } +} + +const MinPointsSize = 100; +const MinLinePointsSize = 50; +function compareDistPair(a, b) { + return b[0] - a[0]; +} +function getRangeSize(range) { + return range[1] - range[0] + 1; +} +function isRangeSafe(range, threshold) { + return range[1] >= range[0] && range[1] < threshold; +} +function splitRange(range, isLine) { + if (range[0] > range[1]) { + return [null, null]; + } + const size = getRangeSize(range); + if (isLine) { + if (size === 2) { + return [range, null]; + } + const size1 = Math.floor(size / 2); + return [[range[0], range[0] + size1], + [range[0] + size1, range[1]]]; + } + if (size === 1) { + return [range, null]; + } + const size1 = Math.floor(size / 2) - 1; + return [[range[0], range[0] + size1], + [range[0] + size1 + 1, range[1]]]; +} +function getBBox(coords, range) { + if (!isRangeSafe(range, coords.length)) { + return [Infinity, Infinity, -Infinity, -Infinity]; + } + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + for (let i = range[0]; i <= range[1]; ++i) { + updateBBox(bbox, coords[i]); + } + return bbox; +} +function getPolygonBBox(polygon) { + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + for (const ring of polygon) { + for (const coord of ring) { + updateBBox(bbox, coord); + } + } + return bbox; +} +function isValidBBox(bbox) { + return bbox[0] !== -Infinity && bbox[1] !== -Infinity && bbox[2] !== Infinity && bbox[3] !== Infinity; +} +// Calculate the distance between two bounding boxes. +// Calculate the delta in x and y direction, and use two fake points {0.0, 0.0} +// and {dx, dy} to calculate the distance. Distance will be 0.0 if bounding box are overlapping. +function bboxToBBoxDistance(bbox1, bbox2, ruler) { + if (!isValidBBox(bbox1) || !isValidBBox(bbox2)) { + return NaN; + } + let dx = 0.0; + let dy = 0.0; + // bbox1 in left side + if (bbox1[2] < bbox2[0]) { + dx = bbox2[0] - bbox1[2]; + } + // bbox1 in right side + if (bbox1[0] > bbox2[2]) { + dx = bbox1[0] - bbox2[2]; + } + // bbox1 in above side + if (bbox1[1] > bbox2[3]) { + dy = bbox1[1] - bbox2[3]; + } + // bbox1 in down side + if (bbox1[3] < bbox2[1]) { + dy = bbox2[1] - bbox1[3]; + } + return ruler.distance([0.0, 0.0], [dx, dy]); +} +function pointToLineDistance(point, line, ruler) { + const nearestPoint = ruler.pointOnLine(line, point); + return ruler.distance(point, nearestPoint.point); +} +function segmentToSegmentDistance(p1, p2, q1, q2, ruler) { + const dist1 = Math.min(pointToLineDistance(p1, [q1, q2], ruler), pointToLineDistance(p2, [q1, q2], ruler)); + const dist2 = Math.min(pointToLineDistance(q1, [p1, p2], ruler), pointToLineDistance(q2, [p1, p2], ruler)); + return Math.min(dist1, dist2); +} +function lineToLineDistance(line1, range1, line2, range2, ruler) { + const rangeSafe = isRangeSafe(range1, line1.length) && isRangeSafe(range2, line2.length); + if (!rangeSafe) { + return Infinity; + } + let dist = Infinity; + for (let i = range1[0]; i < range1[1]; ++i) { + const p1 = line1[i]; + const p2 = line1[i + 1]; + for (let j = range2[0]; j < range2[1]; ++j) { + const q1 = line2[j]; + const q2 = line2[j + 1]; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } + dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); + } + } + return dist; +} +function pointsToPointsDistance(points1, range1, points2, range2, ruler) { + const rangeSafe = isRangeSafe(range1, points1.length) && isRangeSafe(range2, points2.length); + if (!rangeSafe) { + return NaN; + } + let dist = Infinity; + for (let i = range1[0]; i <= range1[1]; ++i) { + for (let j = range2[0]; j <= range2[1]; ++j) { + dist = Math.min(dist, ruler.distance(points1[i], points2[j])); + if (dist === 0.0) { + return dist; + } + } + } + return dist; +} +function pointToPolygonDistance(point, polygon, ruler) { + if (pointWithinPolygon(point, polygon, true)) { + return 0.0; + } + let dist = Infinity; + for (const ring of polygon) { + const front = ring[0]; + const back = ring[ring.length - 1]; + if (front !== back) { + dist = Math.min(dist, pointToLineDistance(point, [back, front], ruler)); + if (dist === 0.0) { + return dist; + } + } + const nearestPoint = ruler.pointOnLine(ring, point); + dist = Math.min(dist, ruler.distance(point, nearestPoint.point)); + if (dist === 0.0) { + return dist; + } + } + return dist; +} +function lineToPolygonDistance(line, range, polygon, ruler) { + if (!isRangeSafe(range, line.length)) { + return NaN; + } + for (let i = range[0]; i <= range[1]; ++i) { + if (pointWithinPolygon(line[i], polygon, true)) { + return 0.0; + } + } + let dist = Infinity; + for (let i = range[0]; i < range[1]; ++i) { + const p1 = line[i]; + const p2 = line[i + 1]; + for (const ring of polygon) { + for (let j = 0, len = ring.length, k = len - 1; j < len; k = j++) { + const q1 = ring[k]; + const q2 = ring[j]; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } + dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); + } + } + } + return dist; +} +function polygonIntersect(poly1, poly2) { + for (const ring of poly1) { + for (const point of ring) { + if (pointWithinPolygon(point, poly2, true)) { + return true; + } + } + } + return false; +} +function polygonToPolygonDistance(polygon1, polygon2, ruler, currentMiniDist = Infinity) { + const bbox1 = getPolygonBBox(polygon1); + const bbox2 = getPolygonBBox(polygon2); + if (currentMiniDist !== Infinity && bboxToBBoxDistance(bbox1, bbox2, ruler) >= currentMiniDist) { + return currentMiniDist; + } + if (boxWithinBox(bbox1, bbox2)) { + if (polygonIntersect(polygon1, polygon2)) { + return 0.0; + } + } + else if (polygonIntersect(polygon2, polygon1)) { + return 0.0; + } + let dist = Infinity; + for (const ring1 of polygon1) { + for (let i = 0, len1 = ring1.length, l = len1 - 1; i < len1; l = i++) { + const p1 = ring1[l]; + const p2 = ring1[i]; + for (const ring2 of polygon2) { + for (let j = 0, len2 = ring2.length, k = len2 - 1; j < len2; k = j++) { + const q1 = ring2[k]; + const q2 = ring2[j]; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } + dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); + } + } + } + } + return dist; +} +function updateQueue(distQueue, miniDist, ruler, points, polyBBox, rangeA) { + if (!rangeA) { + return; + } + const tempDist = bboxToBBoxDistance(getBBox(points, rangeA), polyBBox, ruler); + // Insert new pair to the queue if the bbox distance is less than + // miniDist, The pair with biggest distance will be at the top + if (tempDist < miniDist) { + distQueue.push([tempDist, rangeA, [0, 0]]); + } +} +function updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, range1, range2) { + if (!range1 || !range2) { + return; + } + const tempDist = bboxToBBoxDistance(getBBox(pointSet1, range1), getBBox(pointSet2, range2), ruler); + // Insert new pair to the queue if the bbox distance is less than + // miniDist, The pair with biggest distance will be at the top + if (tempDist < miniDist) { + distQueue.push([tempDist, range1, range2]); + } +} +// Divide and conquer, the time complexity is O(n*lgn), faster than Brute force +// O(n*n) Most of the time, use index for in-place processing. +function pointsToPolygonDistance(points, isLine, polygon, ruler, currentMiniDist = Infinity) { + let miniDist = Math.min(ruler.distance(points[0], polygon[0][0]), currentMiniDist); + if (miniDist === 0.0) { + return miniDist; + } + const distQueue = new TinyQueue$1([[0, [0, points.length - 1], [0, 0]]], compareDistPair); + const polyBBox = getPolygonBBox(polygon); + while (distQueue.length > 0) { + const distPair = distQueue.pop(); + if (distPair[0] >= miniDist) { + continue; + } + const range = distPair[1]; + // In case the set size are relatively small, we could use brute-force directly + const threshold = isLine ? MinLinePointsSize : MinPointsSize; + if (getRangeSize(range) <= threshold) { + if (!isRangeSafe(range, points.length)) { + return NaN; + } + if (isLine) { + const tempDist = lineToPolygonDistance(points, range, polygon, ruler); + if (isNaN(tempDist) || tempDist === 0.0) { + return tempDist; + } + miniDist = Math.min(miniDist, tempDist); + } + else { + for (let i = range[0]; i <= range[1]; ++i) { + const tempDist = pointToPolygonDistance(points[i], polygon, ruler); + miniDist = Math.min(miniDist, tempDist); + if (miniDist === 0.0) { + return 0.0; + } + } + } + } + else { + const newRangesA = splitRange(range, isLine); + updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[0]); + updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[1]); + } + } + return miniDist; +} +function pointSetToPointSetDistance(pointSet1, isLine1, pointSet2, isLine2, ruler, currentMiniDist = Infinity) { + let miniDist = Math.min(currentMiniDist, ruler.distance(pointSet1[0], pointSet2[0])); + if (miniDist === 0.0) { + return miniDist; + } + const distQueue = new TinyQueue$1([[0, [0, pointSet1.length - 1], [0, pointSet2.length - 1]]], compareDistPair); + while (distQueue.length > 0) { + const distPair = distQueue.pop(); + if (distPair[0] >= miniDist) { + continue; + } + const rangeA = distPair[1]; + const rangeB = distPair[2]; + const threshold1 = isLine1 ? MinLinePointsSize : MinPointsSize; + const threshold2 = isLine2 ? MinLinePointsSize : MinPointsSize; + // In case the set size are relatively small, we could use brute-force directly + if (getRangeSize(rangeA) <= threshold1 && getRangeSize(rangeB) <= threshold2) { + if (!isRangeSafe(rangeA, pointSet1.length) && isRangeSafe(rangeB, pointSet2.length)) { + return NaN; + } + let tempDist; + if (isLine1 && isLine2) { + tempDist = lineToLineDistance(pointSet1, rangeA, pointSet2, rangeB, ruler); + miniDist = Math.min(miniDist, tempDist); + } + else if (isLine1 && !isLine2) { + const sublibe = pointSet1.slice(rangeA[0], rangeA[1] + 1); + for (let i = rangeB[0]; i <= rangeB[1]; ++i) { + tempDist = pointToLineDistance(pointSet2[i], sublibe, ruler); + miniDist = Math.min(miniDist, tempDist); + if (miniDist === 0.0) { + return miniDist; + } + } + } + else if (!isLine1 && isLine2) { + const sublibe = pointSet2.slice(rangeB[0], rangeB[1] + 1); + for (let i = rangeA[0]; i <= rangeA[1]; ++i) { + tempDist = pointToLineDistance(pointSet1[i], sublibe, ruler); + miniDist = Math.min(miniDist, tempDist); + if (miniDist === 0.0) { + return miniDist; + } + } + } + else { + tempDist = pointsToPointsDistance(pointSet1, rangeA, pointSet2, rangeB, ruler); + miniDist = Math.min(miniDist, tempDist); + } + } + else { + const newRangesA = splitRange(rangeA, isLine1); + const newRangesB = splitRange(rangeB, isLine2); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[0]); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[1]); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[0]); + updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[1]); + } + } + return miniDist; +} +function pointToGeometryDistance(ctx, geometries) { + const tilePoints = ctx.geometry(); + const pointPosition = tilePoints.flat().map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); + if (tilePoints.length === 0) { + return NaN; + } + const ruler = new CheapRuler(pointPosition[0][1]); + let dist = Infinity; + for (const geometry of geometries) { + switch (geometry.type) { + case 'Point': + dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, [geometry.coordinates], false, ruler, dist)); + break; + case 'LineString': + dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, geometry.coordinates, true, ruler, dist)); + break; + case 'Polygon': + dist = Math.min(dist, pointsToPolygonDistance(pointPosition, false, geometry.coordinates, ruler, dist)); + break; + } + if (dist === 0.0) { + return dist; + } + } + return dist; +} +function lineStringToGeometryDistance(ctx, geometries) { + const tileLine = ctx.geometry(); + const linePositions = tileLine.flat().map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); + if (tileLine.length === 0) { + return NaN; + } + const ruler = new CheapRuler(linePositions[0][1]); + let dist = Infinity; + for (const geometry of geometries) { + switch (geometry.type) { + case 'Point': + dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, [geometry.coordinates], false, ruler, dist)); + break; + case 'LineString': + dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, geometry.coordinates, true, ruler, dist)); + break; + case 'Polygon': + dist = Math.min(dist, pointsToPolygonDistance(linePositions, true, geometry.coordinates, ruler, dist)); + break; + } + if (dist === 0.0) { + return dist; + } + } + return dist; +} +function polygonToGeometryDistance(ctx, geometries) { + const tilePolygon = ctx.geometry(); + if (tilePolygon.length === 0 || tilePolygon[0].length === 0) { + return NaN; + } + const polygons = classifyRings$1(tilePolygon, 0).map(polygon => { + return polygon.map(ring => { + return ring.map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical)); + }); + }); + const ruler = new CheapRuler(polygons[0][0][0][1]); + let dist = Infinity; + for (const geometry of geometries) { + for (const polygon of polygons) { + switch (geometry.type) { + case 'Point': + dist = Math.min(dist, pointsToPolygonDistance([geometry.coordinates], false, polygon, ruler, dist)); + break; + case 'LineString': + dist = Math.min(dist, pointsToPolygonDistance(geometry.coordinates, true, polygon, ruler, dist)); + break; + case 'Polygon': + dist = Math.min(dist, polygonToPolygonDistance(polygon, geometry.coordinates, ruler, dist)); + break; + } + if (dist === 0.0) { + return dist; + } + } + } + return dist; +} +function toSimpleGeometry(geometry) { + if (geometry.type === 'MultiPolygon') { + return geometry.coordinates.map(polygon => { + return { + type: 'Polygon', + coordinates: polygon + }; + }); + } + if (geometry.type === 'MultiLineString') { + return geometry.coordinates.map(lineString => { + return { + type: 'LineString', + coordinates: lineString + }; + }); + } + if (geometry.type === 'MultiPoint') { + return geometry.coordinates.map(point => { + return { + type: 'Point', + coordinates: point + }; + }); + } + return [geometry]; +} +class Distance { + constructor(geojson, geometries) { + this.type = NumberType; + this.geojson = geojson; + this.geometries = geometries; + } + static parse(args, context) { + if (args.length !== 2) + return context.error(`'distance' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (isValue(args[1])) { + const geojson = args[1]; + if (geojson.type === 'FeatureCollection') { + return new Distance(geojson, geojson.features.map(feature => toSimpleGeometry(feature.geometry)).flat()); + } + else if (geojson.type === 'Feature') { + return new Distance(geojson, toSimpleGeometry(geojson.geometry)); + } + else if ('type' in geojson && 'coordinates' in geojson) { + return new Distance(geojson, toSimpleGeometry(geojson)); + } + } + return context.error('\'distance\' expression requires valid geojson object that contains polygon geometry type.'); + } + evaluate(ctx) { + if (ctx.geometry() != null && ctx.canonicalID() != null) { + if (ctx.geometryType() === 'Point') { + return pointToGeometryDistance(ctx, this.geometries); + } + else if (ctx.geometryType() === 'LineString') { + return lineStringToGeometryDistance(ctx, this.geometries); + } + else if (ctx.geometryType() === 'Polygon') { + return polygonToGeometryDistance(ctx, this.geometries); + } + } + return NaN; + } + eachChild() { } + outputDefined() { + return true; + } +} + +const expressions$1 = { + // special forms + '==': Equals, + '!=': NotEquals, + '>': GreaterThan, + '<': LessThan, + '>=': GreaterThanOrEqual, + '<=': LessThanOrEqual, + 'array': Assertion, + 'at': At, + 'boolean': Assertion, + 'case': Case, + 'coalesce': Coalesce, + 'collator': CollatorExpression, + 'format': FormatExpression, + 'image': ImageExpression, + 'in': In, + 'index-of': IndexOf, + 'interpolate': Interpolate, + 'interpolate-hcl': Interpolate, + 'interpolate-lab': Interpolate, + 'length': Length, + 'let': Let, + 'literal': Literal, + 'match': Match, + 'number': Assertion, + 'number-format': NumberFormat, + 'object': Assertion, + 'slice': Slice, + 'step': Step, + 'string': Assertion, + 'to-boolean': Coercion, + 'to-color': Coercion, + 'to-number': Coercion, + 'to-string': Coercion, + 'var': Var, + 'within': Within, + 'distance': Distance +}; + +class CompoundExpression { + constructor(name, type, evaluate, args) { + this.name = name; + this.type = type; + this._evaluate = evaluate; + this.args = args; + } + evaluate(ctx) { + return this._evaluate(ctx, this.args); + } + eachChild(fn) { + this.args.forEach(fn); + } + outputDefined() { + return false; + } + static parse(args, context) { + const op = args[0]; + const definition = CompoundExpression.definitions[op]; + if (!definition) { + return context.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); + } + // Now check argument types against each signature + const type = Array.isArray(definition) ? + definition[0] : definition.type; + const availableOverloads = Array.isArray(definition) ? + [[definition[1], definition[2]]] : + definition.overloads; + const overloads = availableOverloads.filter(([signature]) => (!Array.isArray(signature) || // varags + signature.length === args.length - 1 // correct param count + )); + let signatureContext = null; + for (const [params, evaluate] of overloads) { + // Use a fresh context for each attempted signature so that, if + // we eventually succeed, we haven't polluted `context.errors`. + signatureContext = new ParsingContext(context.registry, isExpressionConstant, context.path, null, context.scope); + // First parse all the args, potentially coercing to the + // types expected by this overload. + const parsedArgs = []; + let argParseFailed = false; + for (let i = 1; i < args.length; i++) { + const arg = args[i]; + const expectedType = Array.isArray(params) ? + params[i - 1] : + params.type; + const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType); + if (!parsed) { + argParseFailed = true; + break; + } + parsedArgs.push(parsed); + } + if (argParseFailed) { + // Couldn't coerce args of this overload to expected type, move + // on to next one. + continue; + } + if (Array.isArray(params)) { + if (params.length !== parsedArgs.length) { + signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`); + continue; + } + } + for (let i = 0; i < parsedArgs.length; i++) { + const expected = Array.isArray(params) ? params[i] : params.type; + const arg = parsedArgs[i]; + signatureContext.concat(i + 1).checkSubtype(expected, arg.type); + } + if (signatureContext.errors.length === 0) { + return new CompoundExpression(op, type, evaluate, parsedArgs); + } + } + if (overloads.length === 1) { + context.errors.push(...signatureContext.errors); + } + else { + const expected = overloads.length ? overloads : availableOverloads; + const signatures = expected + .map(([params]) => stringifySignature(params)) + .join(' | '); + const actualTypes = []; + // For error message, re-parse arguments without trying to + // apply any coercions + for (let i = 1; i < args.length; i++) { + const parsed = context.parse(args[i], 1 + actualTypes.length); + if (!parsed) + return null; + actualTypes.push(toString$1(parsed.type)); + } + context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`); + } + return null; + } + static register(registry, definitions) { + CompoundExpression.definitions = definitions; + for (const name in definitions) { + registry[name] = CompoundExpression; + } + } +} +function rgba(ctx, [r, g, b, a]) { + r = r.evaluate(ctx); + g = g.evaluate(ctx); + b = b.evaluate(ctx); + const alpha = a ? a.evaluate(ctx) : 1; + const error = validateRGBA(r, g, b, alpha); + if (error) + throw new RuntimeError(error); + return new Color(r / 255, g / 255, b / 255, alpha, false); +} +function has(key, obj) { + return key in obj; +} +function get(key, obj) { + const v = obj[key]; + return typeof v === 'undefined' ? null : v; +} +function binarySearch(v, a, i, j) { + while (i <= j) { + const m = (i + j) >> 1; + if (a[m] === v) + return true; + if (a[m] > v) + j = m - 1; + else + i = m + 1; + } + return false; +} +function varargs(type) { + return { type }; +} +CompoundExpression.register(expressions$1, { + 'error': [ + ErrorType, + [StringType], + (ctx, [v]) => { throw new RuntimeError(v.evaluate(ctx)); } + ], + 'typeof': [ + StringType, + [ValueType], + (ctx, [v]) => toString$1(typeOf(v.evaluate(ctx))) + ], + 'to-rgba': [ + array$1(NumberType, 4), + [ColorType], + (ctx, [v]) => { + const [r, g, b, a] = v.evaluate(ctx).rgb; + return [r * 255, g * 255, b * 255, a]; + }, + ], + 'rgb': [ + ColorType, + [NumberType, NumberType, NumberType], + rgba + ], + 'rgba': [ + ColorType, + [NumberType, NumberType, NumberType, NumberType], + rgba + ], + 'has': { + type: BooleanType, + overloads: [ + [ + [StringType], + (ctx, [key]) => has(key.evaluate(ctx), ctx.properties()) + ], [ + [StringType, ObjectType], + (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx)) + ] + ] + }, + 'get': { + type: ValueType, + overloads: [ + [ + [StringType], + (ctx, [key]) => get(key.evaluate(ctx), ctx.properties()) + ], [ + [StringType, ObjectType], + (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx)) + ] + ] + }, + 'feature-state': [ + ValueType, + [StringType], + (ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {}) + ], + 'properties': [ + ObjectType, + [], + (ctx) => ctx.properties() + ], + 'geometry-type': [ + StringType, + [], + (ctx) => ctx.geometryType() + ], + 'id': [ + ValueType, + [], + (ctx) => ctx.id() + ], + 'zoom': [ + NumberType, + [], + (ctx) => ctx.globals.zoom + ], + 'heatmap-density': [ + NumberType, + [], + (ctx) => ctx.globals.heatmapDensity || 0 + ], + 'line-progress': [ + NumberType, + [], + (ctx) => ctx.globals.lineProgress || 0 + ], + 'accumulated': [ + ValueType, + [], + (ctx) => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated + ], + '+': [ + NumberType, + varargs(NumberType), + (ctx, args) => { + let result = 0; + for (const arg of args) { + result += arg.evaluate(ctx); + } + return result; + } + ], + '*': [ + NumberType, + varargs(NumberType), + (ctx, args) => { + let result = 1; + for (const arg of args) { + result *= arg.evaluate(ctx); + } + return result; + } + ], + '-': { + type: NumberType, + overloads: [ + [ + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx) + ], [ + [NumberType], + (ctx, [a]) => -a.evaluate(ctx) + ] + ] + }, + '/': [ + NumberType, + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx) + ], + '%': [ + NumberType, + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx) + ], + 'ln2': [ + NumberType, + [], + () => Math.LN2 + ], + 'pi': [ + NumberType, + [], + () => Math.PI + ], + 'e': [ + NumberType, + [], + () => Math.E + ], + '^': [ + NumberType, + [NumberType, NumberType], + (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx)) + ], + 'sqrt': [ + NumberType, + [NumberType], + (ctx, [x]) => Math.sqrt(x.evaluate(ctx)) + ], + 'log10': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10 + ], + 'ln': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) + ], + 'log2': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2 + ], + 'sin': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.sin(n.evaluate(ctx)) + ], + 'cos': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.cos(n.evaluate(ctx)) + ], + 'tan': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.tan(n.evaluate(ctx)) + ], + 'asin': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.asin(n.evaluate(ctx)) + ], + 'acos': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.acos(n.evaluate(ctx)) + ], + 'atan': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.atan(n.evaluate(ctx)) + ], + 'min': [ + NumberType, + varargs(NumberType), + (ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx))) + ], + 'max': [ + NumberType, + varargs(NumberType), + (ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx))) + ], + 'abs': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.abs(n.evaluate(ctx)) + ], + 'round': [ + NumberType, + [NumberType], + (ctx, [n]) => { + const v = n.evaluate(ctx); + // Javascript's Math.round() rounds towards +Infinity for halfway + // values, even when they're negative. It's more common to round + // away from 0 (e.g., this is what python and C++ do) + return v < 0 ? -Math.round(-v) : Math.round(v); + } + ], + 'floor': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.floor(n.evaluate(ctx)) + ], + 'ceil': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.ceil(n.evaluate(ctx)) + ], + 'filter-==': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => ctx.properties()[k.value] === v.value + ], + 'filter-id-==': [ + BooleanType, + [ValueType], + (ctx, [v]) => ctx.id() === v.value + ], + 'filter-type-==': [ + BooleanType, + [StringType], + (ctx, [v]) => ctx.geometryType() === v.value + ], + 'filter-<': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a < b; + } + ], + 'filter-id-<': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a < b; + } + ], + 'filter->': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a > b; + } + ], + 'filter-id->': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a > b; + } + ], + 'filter-<=': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a <= b; + } + ], + 'filter-id-<=': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a <= b; + } + ], + 'filter->=': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[k.value]; + const b = v.value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-id->=': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = v.value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-has': [ + BooleanType, + [ValueType], + (ctx, [k]) => k.value in ctx.properties() + ], + 'filter-has-id': [ + BooleanType, + [], + (ctx) => (ctx.id() !== null && ctx.id() !== undefined) + ], + 'filter-type-in': [ + BooleanType, + [array$1(StringType)], + (ctx, [v]) => v.value.indexOf(ctx.geometryType()) >= 0 + ], + 'filter-id-in': [ + BooleanType, + [array$1(ValueType)], + (ctx, [v]) => v.value.indexOf(ctx.id()) >= 0 + ], + 'filter-in-small': [ + BooleanType, + [StringType, array$1(ValueType)], + // assumes v is an array literal + (ctx, [k, v]) => v.value.indexOf(ctx.properties()[k.value]) >= 0 + ], + 'filter-in-large': [ + BooleanType, + [StringType, array$1(ValueType)], + // assumes v is a array literal with values sorted in ascending order and of a single type + (ctx, [k, v]) => binarySearch(ctx.properties()[k.value], v.value, 0, v.value.length - 1) + ], + 'all': { + type: BooleanType, + overloads: [ + [ + [BooleanType, BooleanType], + (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx) + ], + [ + varargs(BooleanType), + (ctx, args) => { + for (const arg of args) { + if (!arg.evaluate(ctx)) + return false; + } + return true; + } + ] + ] + }, + 'any': { + type: BooleanType, + overloads: [ + [ + [BooleanType, BooleanType], + (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx) + ], + [ + varargs(BooleanType), + (ctx, args) => { + for (const arg of args) { + if (arg.evaluate(ctx)) + return true; + } + return false; + } + ] + ] + }, + '!': [ + BooleanType, + [BooleanType], + (ctx, [b]) => !b.evaluate(ctx) + ], + 'is-supported-script': [ + BooleanType, + [StringType], + // At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant + (ctx, [s]) => { + const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript; + if (isSupportedScript) { + return isSupportedScript(s.evaluate(ctx)); + } + return true; + } + ], + 'upcase': [ + StringType, + [StringType], + (ctx, [s]) => s.evaluate(ctx).toUpperCase() + ], + 'downcase': [ + StringType, + [StringType], + (ctx, [s]) => s.evaluate(ctx).toLowerCase() + ], + 'concat': [ + StringType, + varargs(ValueType), + (ctx, args) => args.map(arg => toString(arg.evaluate(ctx))).join('') + ], + 'resolved-locale': [ + StringType, + [CollatorType], + (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale() + ] +}); +function stringifySignature(signature) { + if (Array.isArray(signature)) { + return `(${signature.map(toString$1).join(', ')})`; + } + else { + return `(${toString$1(signature.type)}...)`; + } +} +function isExpressionConstant(expression) { + if (expression instanceof Var) { + return isExpressionConstant(expression.boundExpression); + } + else if (expression instanceof CompoundExpression && expression.name === 'error') { + return false; + } + else if (expression instanceof CollatorExpression) { + // Although the results of a Collator expression with fixed arguments + // generally shouldn't change between executions, we can't serialize them + // as constant expressions because results change based on environment. + return false; + } + else if (expression instanceof Within) { + return false; + } + else if (expression instanceof Distance) { + return false; + } + const isTypeAnnotation = expression instanceof Coercion || + expression instanceof Assertion; + let childrenConstant = true; + expression.eachChild(child => { + // We can _almost_ assume that if `expressions` children are constant, + // they would already have been evaluated to Literal values when they + // were parsed. Type annotations are the exception, because they might + // have been inferred and added after a child was parsed. + // So we recurse into isConstant() for the children of type annotations, + // but otherwise simply check whether they are Literals. + if (isTypeAnnotation) { + childrenConstant = childrenConstant && isExpressionConstant(child); + } + else { + childrenConstant = childrenConstant && child instanceof Literal; + } + }); + if (!childrenConstant) { + return false; + } + return isFeatureConstant(expression) && + isGlobalPropertyConstant(expression, ['zoom', 'heatmap-density', 'line-progress', 'accumulated', 'is-supported-script']); +} +function isFeatureConstant(e) { + if (e instanceof CompoundExpression) { + if (e.name === 'get' && e.args.length === 1) { + return false; + } + else if (e.name === 'feature-state') { + return false; + } + else if (e.name === 'has' && e.args.length === 1) { + return false; + } + else if (e.name === 'properties' || + e.name === 'geometry-type' || + e.name === 'id') { + return false; + } + else if (/^filter-/.test(e.name)) { + return false; + } + } + if (e instanceof Within) { + return false; + } + if (e instanceof Distance) { + return false; + } + let result = true; + e.eachChild(arg => { + if (result && !isFeatureConstant(arg)) { + result = false; + } + }); + return result; +} +function isStateConstant(e) { + if (e instanceof CompoundExpression) { + if (e.name === 'feature-state') { + return false; + } + } + let result = true; + e.eachChild(arg => { + if (result && !isStateConstant(arg)) { + result = false; + } + }); + return result; +} +function isGlobalPropertyConstant(e, properties) { + if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) { + return false; + } + let result = true; + e.eachChild((arg) => { + if (result && !isGlobalPropertyConstant(arg, properties)) { + result = false; + } + }); + return result; +} + +function success(value) { + return { result: 'success', value }; +} +function error(value) { + return { result: 'error', value }; +} + +function supportsPropertyExpression(spec) { + return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-data-driven'; +} +function supportsZoomExpression(spec) { + return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1; +} +function supportsInterpolation(spec) { + return !!spec.expression && spec.expression.interpolated; +} + +function getType(val) { + if (val instanceof Number) { + return 'number'; + } + else if (val instanceof String) { + return 'string'; + } + else if (val instanceof Boolean) { + return 'boolean'; + } + else if (Array.isArray(val)) { + return 'array'; + } + else if (val === null) { + return 'null'; + } + else { + return typeof val; + } +} + +function isFunction$1(value) { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} +function identityFunction(x) { + return x; +} +function createFunction(parameters, propertySpec) { + const isColor = propertySpec.type === 'color'; + const zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object'; + const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + const zoomDependent = zoomAndFeatureDependent || !featureDependent; + const type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval'); + if (isColor || propertySpec.type === 'padding') { + const parseFn = isColor ? Color.parse : Padding.parse; + parameters = extendBy({}, parameters); + if (parameters.stops) { + parameters.stops = parameters.stops.map((stop) => { + return [stop[0], parseFn(stop[1])]; + }); + } + if (parameters.default) { + parameters.default = parseFn(parameters.default); + } + else { + parameters.default = parseFn(propertySpec.default); + } + } + if (parameters.colorSpace && !isSupportedInterpolationColorSpace(parameters.colorSpace)) { + throw new Error(`Unknown color space: "${parameters.colorSpace}"`); + } + let innerFun; + let hashedStops; + let categoricalKeyType; + if (type === 'exponential') { + innerFun = evaluateExponentialFunction; + } + else if (type === 'interval') { + innerFun = evaluateIntervalFunction; + } + else if (type === 'categorical') { + innerFun = evaluateCategoricalFunction; + // For categorical functions, generate an Object as a hashmap of the stops for fast searching + hashedStops = Object.create(null); + for (const stop of parameters.stops) { + hashedStops[stop[0]] = stop[1]; + } + // Infer key type based on first stop key-- used to encforce strict type checking later + categoricalKeyType = typeof parameters.stops[0][0]; + } + else if (type === 'identity') { + innerFun = evaluateIdentityFunction; + } + else { + throw new Error(`Unknown function type "${type}"`); + } + if (zoomAndFeatureDependent) { + const featureFunctions = {}; + const zoomStops = []; + for (let s = 0; s < parameters.stops.length; s++) { + const stop = parameters.stops[s]; + const zoom = stop[0].zoom; + if (featureFunctions[zoom] === undefined) { + featureFunctions[zoom] = { + zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default, + stops: [] + }; + zoomStops.push(zoom); + } + featureFunctions[zoom].stops.push([stop[0].value, stop[1]]); + } + const featureFunctionStops = []; + for (const z of zoomStops) { + featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]); + } + const interpolationType = { name: 'linear' }; + return { + kind: 'composite', + interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: featureFunctionStops.map(s => s[0]), + evaluate({ zoom }, properties) { + return evaluateExponentialFunction({ + stops: featureFunctionStops, + base: parameters.base + }, propertySpec, zoom).evaluate(zoom, properties); + } + }; + } + else if (zoomDependent) { + const interpolationType = type === 'exponential' ? + { name: 'exponential', base: parameters.base !== undefined ? parameters.base : 1 } : null; + return { + kind: 'camera', + interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: parameters.stops.map(s => s[0]), + evaluate: ({ zoom }) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType) + }; + } + else { + return { + kind: 'source', + evaluate(_, feature) { + const value = feature && feature.properties ? feature.properties[parameters.property] : undefined; + if (value === undefined) { + return coalesce$1(parameters.default, propertySpec.default); + } + return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType); + } + }; + } +} +function coalesce$1(a, b, c) { + if (a !== undefined) + return a; + if (b !== undefined) + return b; + if (c !== undefined) + return c; +} +function evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) { + const evaluated = typeof input === keyType ? hashedStops[input] : undefined; // Enforce strict typing on input + return coalesce$1(evaluated, parameters.default, propertySpec.default); +} +function evaluateIntervalFunction(parameters, propertySpec, input) { + // Edge cases + if (getType(input) !== 'number') + return coalesce$1(parameters.default, propertySpec.default); + const n = parameters.stops.length; + if (n === 1) + return parameters.stops[0][1]; + if (input <= parameters.stops[0][0]) + return parameters.stops[0][1]; + if (input >= parameters.stops[n - 1][0]) + return parameters.stops[n - 1][1]; + const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); + return parameters.stops[index][1]; +} +function evaluateExponentialFunction(parameters, propertySpec, input) { + const base = parameters.base !== undefined ? parameters.base : 1; + // Edge cases + if (getType(input) !== 'number') + return coalesce$1(parameters.default, propertySpec.default); + const n = parameters.stops.length; + if (n === 1) + return parameters.stops[0][1]; + if (input <= parameters.stops[0][0]) + return parameters.stops[0][1]; + if (input >= parameters.stops[n - 1][0]) + return parameters.stops[n - 1][1]; + const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); + const t = interpolationFactor(input, base, parameters.stops[index][0], parameters.stops[index + 1][0]); + const outputLower = parameters.stops[index][1]; + const outputUpper = parameters.stops[index + 1][1]; + const interp = interpolate[propertySpec.type] || identityFunction; + if (typeof outputLower.evaluate === 'function') { + return { + evaluate(...args) { + const evaluatedLower = outputLower.evaluate.apply(undefined, args); + const evaluatedUpper = outputUpper.evaluate.apply(undefined, args); + // Special case for fill-outline-color, which has no spec default. + if (evaluatedLower === undefined || evaluatedUpper === undefined) { + return undefined; + } + return interp(evaluatedLower, evaluatedUpper, t, parameters.colorSpace); + } + }; + } + return interp(outputLower, outputUpper, t, parameters.colorSpace); +} +function evaluateIdentityFunction(parameters, propertySpec, input) { + switch (propertySpec.type) { + case 'color': + input = Color.parse(input); + break; + case 'formatted': + input = Formatted.fromString(input.toString()); + break; + case 'resolvedImage': + input = ResolvedImage.fromString(input.toString()); + break; + case 'padding': + input = Padding.parse(input); + break; + default: + if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) { + input = undefined; + } + } + return coalesce$1(input, parameters.default, propertySpec.default); +} +/** + * Returns a ratio that can be used to interpolate between exponential function + * stops. + * + * 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, + * and `a` and `b` are constants affording sufficient degrees of freedom to fit + * the function to the given stops. + * + * Here's a bit of algebra that lets us compute `f(x)` directly from the stop + * values without explicitly solving for `a` and `b`: + * + * First stop value: `f(x0) = y0 = a * base^x0 + b` + * Second stop value: `f(x1) = y1 = a * base^x1 + b` + * => `y1 - y0 = a(base^x1 - base^x0)` + * => `a = (y1 - y0)/(base^x1 - base^x0)` + * + * Desired value: `f(x) = y = a * base^x + b` + * => `f(x) = y0 + a * (base^x - base^x0)` + * + * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a + * little algebra: + * ``` + * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) + * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) + * ``` + * + * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have + * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as + * an interpolation factor between the two stops' output values. + * + * (Note: a slightly different form for `ratio`, + * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer + * expensive `Math.pow()` operations.) + * + * @private + */ +function interpolationFactor(input, base, lowerValue, upperValue) { + const difference = upperValue - lowerValue; + const progress = input - lowerValue; + if (difference === 0) { + return 0; + } + else if (base === 1) { + return progress / difference; + } + else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} + +class StyleExpression { + constructor(expression, propertySpec) { + this.expression = expression; + this._warningHistory = {}; + this._evaluator = new EvaluationContext(); + this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null; + this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null; + } + evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + this._evaluator.globals = globals; + this._evaluator.feature = feature; + this._evaluator.featureState = featureState; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection; + return this.expression.evaluate(this._evaluator); + } + evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + this._evaluator.globals = globals; + this._evaluator.feature = feature || null; + this._evaluator.featureState = featureState || null; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection || null; + try { + const val = this.expression.evaluate(this._evaluator); + // eslint-disable-next-line no-self-compare + if (val === null || val === undefined || (typeof val === 'number' && val !== val)) { + return this._defaultValue; + } + if (this._enumValues && !(val in this._enumValues)) { + 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.`); + } + return val; + } + catch (e) { + if (!this._warningHistory[e.message]) { + this._warningHistory[e.message] = true; + if (typeof console !== 'undefined') { + console.warn(e.message); + } + } + return this._defaultValue; + } + } +} +function isExpression(expression) { + return Array.isArray(expression) && expression.length > 0 && + typeof expression[0] === 'string' && expression[0] in expressions$1; +} +/** + * Parse and typecheck the given style spec JSON expression. If + * options.defaultValue is provided, then the resulting StyleExpression's + * `evaluate()` method will handle errors by logging a warning (once per + * message) and returning the default value. Otherwise, it will throw + * evaluation errors. + * + * @private + */ +function createExpression(expression, propertySpec) { + const parser = new ParsingContext(expressions$1, isExpressionConstant, [], propertySpec ? getExpectedType(propertySpec) : undefined); + // For string-valued properties, coerce to string at the top level rather than asserting. + const parsed = parser.parse(expression, undefined, undefined, undefined, propertySpec && propertySpec.type === 'string' ? { typeAnnotation: 'coerce' } : undefined); + if (!parsed) { + return error(parser.errors); + } + return success(new StyleExpression(parsed, propertySpec)); +} +class ZoomConstantExpression { + constructor(kind, expression) { + this.kind = kind; + this._styleExpression = expression; + this.isStateDependent = kind !== 'constant' && !isStateConstant(expression.expression); + } + evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + } + evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + } +} +class ZoomDependentExpression { + constructor(kind, expression, zoomStops, interpolationType) { + this.kind = kind; + this.zoomStops = zoomStops; + this._styleExpression = expression; + this.isStateDependent = kind !== 'camera' && !isStateConstant(expression.expression); + this.interpolationType = interpolationType; + } + evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + } + evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + } + interpolationFactor(input, lower, upper) { + if (this.interpolationType) { + return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper); + } + else { + return 0; + } + } +} +function isZoomExpression(expression) { + return expression._styleExpression !== undefined; +} +function createPropertyExpression(expressionInput, propertySpec) { + const expression = createExpression(expressionInput, propertySpec); + if (expression.result === 'error') { + return expression; + } + const parsed = expression.value.expression; + const isFeatureConstantResult = isFeatureConstant(parsed); + if (!isFeatureConstantResult && !supportsPropertyExpression(propertySpec)) { + return error([new ExpressionParsingError('', 'data expressions not supported')]); + } + const isZoomConstant = isGlobalPropertyConstant(parsed, ['zoom']); + if (!isZoomConstant && !supportsZoomExpression(propertySpec)) { + return error([new ExpressionParsingError('', 'zoom expressions not supported')]); + } + const zoomCurve = findZoomCurve(parsed); + if (!zoomCurve && !isZoomConstant) { + return error([new ExpressionParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]); + } + else if (zoomCurve instanceof ExpressionParsingError) { + return error([zoomCurve]); + } + else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) { + return error([new ExpressionParsingError('', '"interpolate" expressions cannot be used with this property')]); + } + if (!zoomCurve) { + return success(isFeatureConstantResult ? + new ZoomConstantExpression('constant', expression.value) : + new ZoomConstantExpression('source', expression.value)); + } + const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined; + return success(isFeatureConstantResult ? + new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType) : + new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType)); +} +// serialization wrapper for old-style stop functions normalized to the +// expression interface +class StylePropertyFunction { + constructor(parameters, specification) { + this._parameters = parameters; + this._specification = specification; + extendBy(this, createFunction(this._parameters, this._specification)); + } + static deserialize(serialized) { + return new StylePropertyFunction(serialized._parameters, serialized._specification); + } + static serialize(input) { + return { + _parameters: input._parameters, + _specification: input._specification + }; + } +} +function normalizePropertyExpression(value, specification) { + if (isFunction$1(value)) { + return new StylePropertyFunction(value, specification); + } + else if (isExpression(value)) { + const expression = createPropertyExpression(value, specification); + if (expression.result === 'error') { + // this should have been caught in validation + throw new Error(expression.value.map(err => `${err.key}: ${err.message}`).join(', ')); + } + return expression.value; + } + else { + let constant = value; + if (specification.type === 'color' && typeof value === 'string') { + constant = Color.parse(value); + } + else if (specification.type === 'padding' && (typeof value === 'number' || Array.isArray(value))) { + constant = Padding.parse(value); + } + else if (specification.type === 'variableAnchorOffsetCollection' && Array.isArray(value)) { + constant = VariableAnchorOffsetCollection.parse(value); + } + return { + kind: 'constant', + evaluate: () => constant + }; + } +} +// Zoom-dependent expressions may only use ["zoom"] as the input to a top-level "step" or "interpolate" +// expression (collectively referred to as a "curve"). The curve may be wrapped in one or more "let" or +// "coalesce" expressions. +function findZoomCurve(expression) { + let result = null; + if (expression instanceof Let) { + result = findZoomCurve(expression.result); + } + else if (expression instanceof Coalesce) { + for (const arg of expression.args) { + result = findZoomCurve(arg); + if (result) { + break; + } + } + } + else if ((expression instanceof Step || expression instanceof Interpolate) && + expression.input instanceof CompoundExpression && + expression.input.name === 'zoom') { + result = expression; + } + if (result instanceof ExpressionParsingError) { + return result; + } + expression.eachChild((child) => { + const childResult = findZoomCurve(child); + if (childResult instanceof ExpressionParsingError) { + result = childResult; + } + else if (!result && childResult) { + result = new ExpressionParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'); + } + else if (result && childResult && result !== childResult) { + result = new ExpressionParsingError('', 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'); + } + }); + return result; +} +function getExpectedType(spec) { + const types = { + color: ColorType, + string: StringType, + number: NumberType, + enum: StringType, + boolean: BooleanType, + formatted: FormattedType, + padding: PaddingType, + resolvedImage: ResolvedImageType, + variableAnchorOffsetCollection: VariableAnchorOffsetCollectionType + }; + if (spec.type === 'array') { + return array$1(types[spec.value] || ValueType, spec.length); + } + return types[spec.type]; +} +function getDefaultValue(spec) { + if (spec.type === 'color' && isFunction$1(spec.default)) { + // Special case for heatmap-color: it uses the 'default:' to define a + // default color ramp, but createExpression expects a simple value to fall + // back to in case of runtime errors + return new Color(0, 0, 0, 0); + } + else if (spec.type === 'color') { + return Color.parse(spec.default) || null; + } + else if (spec.type === 'padding') { + return Padding.parse(spec.default) || null; + } + else if (spec.type === 'variableAnchorOffsetCollection') { + return VariableAnchorOffsetCollection.parse(spec.default) || null; + } + else if (spec.default === undefined) { + return null; + } + else { + return spec.default; + } +} + +function isExpressionFilter(filter) { + if (filter === true || filter === false) { + return true; + } + if (!Array.isArray(filter) || filter.length === 0) { + return false; + } + switch (filter[0]) { + case 'has': + return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type'; + case 'in': + return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2])); + case '!in': + case '!has': + case 'none': + return false; + case '==': + case '!=': + case '>': + case '>=': + case '<': + case '<=': + return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2])); + case 'any': + case 'all': + for (const f of filter.slice(1)) { + if (!isExpressionFilter(f) && typeof f !== 'boolean') { + return false; + } + } + return true; + default: + return true; + } +} +const filterSpec = { + 'type': 'boolean', + 'default': false, + 'transition': false, + 'property-type': 'data-driven', + 'expression': { + 'interpolated': false, + 'parameters': ['zoom', 'feature'] + } +}; +/** + * Given a filter expressed as nested arrays, return a new function + * that evaluates whether a given feature (with a .properties or .tags property) + * passes its test. + * + * @private + * @param {Array} filter MapLibre filter + * @returns {Function} filter-evaluating function + */ +function createFilter(filter) { + if (filter === null || filter === undefined) { + return { filter: () => true, needGeometry: false }; + } + if (!isExpressionFilter(filter)) { + filter = convertFilter$1(filter); + } + const compiled = createExpression(filter, filterSpec); + if (compiled.result === 'error') { + throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', ')); + } + else { + const needGeometry = geometryNeeded(filter); + return { filter: (globalProperties, feature, canonical) => compiled.value.evaluate(globalProperties, feature, {}, canonical), + needGeometry }; + } +} +// Comparison function to sort numbers and strings +function compare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} +function geometryNeeded(filter) { + if (!Array.isArray(filter)) + return false; + if (filter[0] === 'within' || filter[0] === 'distance') + return true; + for (let index = 1; index < filter.length; index++) { + if (geometryNeeded(filter[index])) + return true; + } + return false; +} +function convertFilter$1(filter) { + if (!filter) + return true; + const op = filter[0]; + if (filter.length <= 1) + return (op !== 'any'); + const converted = op === '==' ? convertComparisonOp$1(filter[1], filter[2], '==') : + op === '!=' ? convertNegation(convertComparisonOp$1(filter[1], filter[2], '==')) : + op === '<' || + op === '>' || + op === '<=' || + op === '>=' ? convertComparisonOp$1(filter[1], filter[2], op) : + op === 'any' ? convertDisjunctionOp(filter.slice(1)) : + op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter$1)) : + op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter$1).map(convertNegation)) : + op === 'in' ? convertInOp$1(filter[1], filter.slice(2)) : + op === '!in' ? convertNegation(convertInOp$1(filter[1], filter.slice(2))) : + op === 'has' ? convertHasOp$1(filter[1]) : + op === '!has' ? convertNegation(convertHasOp$1(filter[1])) : + true; + return converted; +} +function convertComparisonOp$1(property, value, op) { + switch (property) { + case '$type': + return [`filter-type-${op}`, value]; + case '$id': + return [`filter-id-${op}`, value]; + default: + return [`filter-${op}`, property, value]; + } +} +function convertDisjunctionOp(filters) { + return ['any'].concat(filters.map(convertFilter$1)); +} +function convertInOp$1(property, values) { + if (values.length === 0) { + return false; + } + switch (property) { + case '$type': + return ['filter-type-in', ['literal', values]]; + case '$id': + return ['filter-id-in', ['literal', values]]; + default: + if (values.length > 200 && !values.some(v => typeof v !== typeof values[0])) { + return ['filter-in-large', property, ['literal', values.sort(compare)]]; + } + else { + return ['filter-in-small', property, ['literal', values]]; + } + } +} +function convertHasOp$1(property) { + switch (property) { + case '$type': + return true; + case '$id': + return ['filter-has-id']; + default: + return ['filter-has', property]; + } +} +function convertNegation(filter) { + return ['!', filter]; +} + +function stringify$1(obj) { + const type = typeof obj; + if (type === 'number' || type === 'boolean' || type === 'string' || obj === undefined || obj === null) + return JSON.stringify(obj); + if (Array.isArray(obj)) { + let str = '['; + for (const val of obj) { + str += `${stringify$1(val)},`; + } + return `${str}]`; + } + const keys = Object.keys(obj).sort(); + let str = '{'; + for (let i = 0; i < keys.length; i++) { + str += `${JSON.stringify(keys[i])}:${stringify$1(obj[keys[i]])},`; + } + return `${str}}`; +} +function getKey(layer) { + let key = ''; + for (const k of refProperties) { + key += `/${stringify$1(layer[k])}`; + } + return key; +} +/** + * Given an array of layers, return an array of arrays of layers where all + * layers in each group have identical layout-affecting properties. These + * are the properties that were formerly used by explicit `ref` mechanism + * for layers: 'type', 'source', 'source-layer', 'minzoom', 'maxzoom', + * 'filter', and 'layout'. + * + * The input is not modified. The output layers are references to the + * input layers. + * + * @private + * @param {Array} layers + * @param {Object} [cachedKeys] - an object to keep already calculated keys. + * @returns {Array>} + */ +function groupByLayout(layers, cachedKeys) { + const groups = {}; + for (let i = 0; i < layers.length; i++) { + const k = (cachedKeys && cachedKeys[layers[i].id]) || getKey(layers[i]); + // update the cache if there is one + if (cachedKeys) + cachedKeys[layers[i].id] = k; + let group = groups[k]; + if (!group) { + group = groups[k] = []; + } + group.push(layers[i]); + } + const result = []; + for (const k in groups) { + result.push(groups[k]); + } + return result; +} + +function emptyStyle() { + const style = {}; + const version = v8Spec['$version']; + for (const styleKey in v8Spec['$root']) { + const spec = v8Spec['$root'][styleKey]; + if (spec.required) { + let value = null; + if (styleKey === 'version') { + value = version; + } + else { + if (spec.type === 'array') { + value = []; + } + else { + value = {}; + } + } + if (value != null) { + style[styleKey] = value; + } + } + } + return style; +} + +function validateConstants(options) { + const key = options.key; + const constants = options.value; + if (constants) { + return [new ValidationError(key, constants, 'constants have been deprecated as of v8')]; + } + else { + return []; + } +} + +// Turn jsonlint-lines-primitives objects into primitive objects +function unbundle(value) { + if (value instanceof Number || value instanceof String || value instanceof Boolean) { + return value.valueOf(); + } + else { + return value; + } +} +function deepUnbundle(value) { + if (Array.isArray(value)) { + return value.map(deepUnbundle); + } + else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) { + const unbundledValue = {}; + for (const key in value) { + unbundledValue[key] = deepUnbundle(value[key]); + } + return unbundledValue; + } + return unbundle(value); +} + +function validateObject(options) { + const key = options.key; + const object = options.value; + const elementSpecs = options.valueSpec || {}; + const elementValidators = options.objectElementValidators || {}; + const style = options.style; + const styleSpec = options.styleSpec; + const validateSpec = options.validateSpec; + let errors = []; + const type = getType(object); + if (type !== 'object') { + return [new ValidationError(key, object, `object expected, ${type} found`)]; + } + for (const objectKey in object) { + const elementSpecKey = objectKey.split('.')[0]; // treat 'paint.*' as 'paint' + const elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*']; + let validateElement; + if (elementValidators[elementSpecKey]) { + validateElement = elementValidators[elementSpecKey]; + } + else if (elementSpecs[elementSpecKey]) { + validateElement = validateSpec; + } + else if (elementValidators['*']) { + validateElement = elementValidators['*']; + } + else if (elementSpecs['*']) { + validateElement = validateSpec; + } + else { + errors.push(new ValidationError(key, object[objectKey], `unknown property "${objectKey}"`)); + continue; + } + errors = errors.concat(validateElement({ + key: (key ? `${key}.` : key) + objectKey, + value: object[objectKey], + valueSpec: elementSpec, + style, + styleSpec, + object, + objectKey, + validateSpec, + }, object)); + } + for (const elementSpecKey in elementSpecs) { + // Don't check `required` when there's a custom validator for that property. + if (elementValidators[elementSpecKey]) { + continue; + } + if (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey]['default'] === undefined && object[elementSpecKey] === undefined) { + errors.push(new ValidationError(key, object, `missing required property "${elementSpecKey}"`)); + } + } + return errors; +} + +function validateArray(options) { + const array = options.value; + const arraySpec = options.valueSpec; + const validateSpec = options.validateSpec; + const style = options.style; + const styleSpec = options.styleSpec; + const key = options.key; + const validateArrayElement = options.arrayElementValidator || validateSpec; + if (getType(array) !== 'array') { + return [new ValidationError(key, array, `array expected, ${getType(array)} found`)]; + } + if (arraySpec.length && array.length !== arraySpec.length) { + return [new ValidationError(key, array, `array length ${arraySpec.length} expected, length ${array.length} found`)]; + } + if (arraySpec['min-length'] && array.length < arraySpec['min-length']) { + return [new ValidationError(key, array, `array length at least ${arraySpec['min-length']} expected, length ${array.length} found`)]; + } + let arrayElementSpec = { + 'type': arraySpec.value, + 'values': arraySpec.values + }; + if (styleSpec.$version < 7) { + arrayElementSpec['function'] = arraySpec.function; + } + if (getType(arraySpec.value) === 'object') { + arrayElementSpec = arraySpec.value; + } + let errors = []; + for (let i = 0; i < array.length; i++) { + errors = errors.concat(validateArrayElement({ + array, + arrayIndex: i, + value: array[i], + valueSpec: arrayElementSpec, + validateSpec: options.validateSpec, + style, + styleSpec, + key: `${key}[${i}]` + })); + } + return errors; +} + +function validateNumber(options) { + const key = options.key; + const value = options.value; + const valueSpec = options.valueSpec; + let type = getType(value); + // eslint-disable-next-line no-self-compare + if (type === 'number' && value !== value) { + type = 'NaN'; + } + if (type !== 'number') { + return [new ValidationError(key, value, `number expected, ${type} found`)]; + } + if ('minimum' in valueSpec && value < valueSpec.minimum) { + return [new ValidationError(key, value, `${value} is less than the minimum value ${valueSpec.minimum}`)]; + } + if ('maximum' in valueSpec && value > valueSpec.maximum) { + return [new ValidationError(key, value, `${value} is greater than the maximum value ${valueSpec.maximum}`)]; + } + return []; +} + +function validateFunction(options) { + const functionValueSpec = options.valueSpec; + const functionType = unbundle(options.value.type); + let stopKeyType; + let stopDomainValues = {}; + let previousStopDomainValue; + let previousStopDomainZoom; + const isZoomFunction = functionType !== 'categorical' && options.value.property === undefined; + const isPropertyFunction = !isZoomFunction; + const isZoomAndPropertyFunction = getType(options.value.stops) === 'array' && + getType(options.value.stops[0]) === 'array' && + getType(options.value.stops[0][0]) === 'object'; + const errors = validateObject({ + key: options.key, + value: options.value, + valueSpec: options.styleSpec.function, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + stops: validateFunctionStops, + default: validateFunctionDefault + } + }); + if (functionType === 'identity' && isZoomFunction) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "property"')); + } + if (functionType !== 'identity' && !options.value.stops) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "stops"')); + } + if (functionType === 'exponential' && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'exponential functions not supported')); + } + if (options.styleSpec.$version >= 8) { + if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'property functions not supported')); + } + else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported')); + } + } + if ((functionType === 'categorical' || isZoomAndPropertyFunction) && options.value.property === undefined) { + errors.push(new ValidationError(options.key, options.value, '"property" property is required')); + } + return errors; + function validateFunctionStops(options) { + if (functionType === 'identity') { + return [new ValidationError(options.key, options.value, 'identity function may not have a "stops" property')]; + } + let errors = []; + const value = options.value; + errors = errors.concat(validateArray({ + key: options.key, + value, + valueSpec: options.valueSpec, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec, + arrayElementValidator: validateFunctionStop + })); + if (getType(value) === 'array' && value.length === 0) { + errors.push(new ValidationError(options.key, value, 'array must have at least one stop')); + } + return errors; + } + function validateFunctionStop(options) { + let errors = []; + const value = options.value; + const key = options.key; + if (getType(value) !== 'array') { + return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; + } + if (value.length !== 2) { + return [new ValidationError(key, value, `array length 2 expected, length ${value.length} found`)]; + } + if (isZoomAndPropertyFunction) { + if (getType(value[0]) !== 'object') { + return [new ValidationError(key, value, `object expected, ${getType(value[0])} found`)]; + } + if (value[0].zoom === undefined) { + return [new ValidationError(key, value, 'object stop key must have zoom')]; + } + if (value[0].value === undefined) { + return [new ValidationError(key, value, 'object stop key must have value')]; + } + if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) { + return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')]; + } + if (unbundle(value[0].zoom) !== previousStopDomainZoom) { + previousStopDomainZoom = unbundle(value[0].zoom); + previousStopDomainValue = undefined; + stopDomainValues = {}; + } + errors = errors.concat(validateObject({ + key: `${key}[0]`, + value: value[0], + valueSpec: { zoom: {} }, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { zoom: validateNumber, value: validateStopDomainValue } + })); + } + else { + errors = errors.concat(validateStopDomainValue({ + key: `${key}[0]`, + value: value[0], + valueSpec: {}, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec + }, value)); + } + if (isExpression(deepUnbundle(value[1]))) { + return errors.concat([new ValidationError(`${key}[1]`, value[1], 'expressions are not allowed in function stops.')]); + } + return errors.concat(options.validateSpec({ + key: `${key}[1]`, + value: value[1], + valueSpec: functionValueSpec, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec + })); + } + function validateStopDomainValue(options, stop) { + const type = getType(options.value); + const value = unbundle(options.value); + const reportValue = options.value !== null ? options.value : stop; + if (!stopKeyType) { + stopKeyType = type; + } + else if (type !== stopKeyType) { + return [new ValidationError(options.key, reportValue, `${type} stop domain type must match previous stop domain type ${stopKeyType}`)]; + } + if (type !== 'number' && type !== 'string' && type !== 'boolean') { + return [new ValidationError(options.key, reportValue, 'stop domain value must be a number, string, or boolean')]; + } + if (type !== 'number' && functionType !== 'categorical') { + let message = `number expected, ${type} found`; + if (supportsPropertyExpression(functionValueSpec) && functionType === undefined) { + message += '\nIf you intended to use a categorical function, specify `"type": "categorical"`.'; + } + return [new ValidationError(options.key, reportValue, message)]; + } + if (functionType === 'categorical' && type === 'number' && (!isFinite(value) || Math.floor(value) !== value)) { + return [new ValidationError(options.key, reportValue, `integer expected, found ${value}`)]; + } + if (functionType !== 'categorical' && type === 'number' && previousStopDomainValue !== undefined && value < previousStopDomainValue) { + return [new ValidationError(options.key, reportValue, 'stop domain values must appear in ascending order')]; + } + else { + previousStopDomainValue = value; + } + if (functionType === 'categorical' && value in stopDomainValues) { + return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')]; + } + else { + stopDomainValues[value] = true; + } + return []; + } + function validateFunctionDefault(options) { + return options.validateSpec({ + key: options.key, + value: options.value, + valueSpec: functionValueSpec, + validateSpec: options.validateSpec, + style: options.style, + styleSpec: options.styleSpec + }); + } +} + +function validateExpression(options) { + const expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec); + if (expression.result === 'error') { + return expression.value.map((error) => { + return new ValidationError(`${options.key}${error.key}`, options.value, error.message); + }); + } + const expressionObj = expression.value.expression || expression.value._styleExpression.expression; + if (options.expressionContext === 'property' && (options.propertyKey === 'text-font') && + !expressionObj.outputDefined()) { + return [new ValidationError(options.key, options.value, `Invalid data expression for "${options.propertyKey}". Output values must be contained as literals within the expression.`)]; + } + if (options.expressionContext === 'property' && options.propertyType === 'layout' && + (!isStateConstant(expressionObj))) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with layout properties.')]; + } + if (options.expressionContext === 'filter' && !isStateConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with filters.')]; + } + if (options.expressionContext && options.expressionContext.indexOf('cluster') === 0) { + if (!isGlobalPropertyConstant(expressionObj, ['zoom', 'feature-state'])) { + return [new ValidationError(options.key, options.value, '"zoom" and "feature-state" expressions are not supported with cluster properties.')]; + } + if (options.expressionContext === 'cluster-initial' && !isFeatureConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')]; + } + } + return []; +} + +function validateBoolean(options) { + const value = options.value; + const key = options.key; + const type = getType(value); + if (type !== 'boolean') { + return [new ValidationError(key, value, `boolean expected, ${type} found`)]; + } + return []; +} + +function validateColor(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + if (type !== 'string') { + return [new ValidationError(key, value, `color expected, ${type} found`)]; + } + if (!Color.parse(String(value))) { // cast String object to string primitive + return [new ValidationError(key, value, `color expected, "${value}" found`)]; + } + return []; +} + +function validateEnum(options) { + const key = options.key; + const value = options.value; + const valueSpec = options.valueSpec; + const errors = []; + if (Array.isArray(valueSpec.values)) { // <=v7 + if (valueSpec.values.indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, `expected one of [${valueSpec.values.join(', ')}], ${JSON.stringify(value)} found`)); + } + } + else { // >=v8 + if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, `expected one of [${Object.keys(valueSpec.values).join(', ')}], ${JSON.stringify(value)} found`)); + } + } + return errors; +} + +function validateFilter(options) { + if (isExpressionFilter(deepUnbundle(options.value))) { + return validateExpression(extendBy({}, options, { + expressionContext: 'filter', + valueSpec: { value: 'boolean' } + })); + } + else { + return validateNonExpressionFilter(options); + } +} +function validateNonExpressionFilter(options) { + const value = options.value; + const key = options.key; + if (getType(value) !== 'array') { + return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; + } + const styleSpec = options.styleSpec; + let type; + let errors = []; + if (value.length < 1) { + return [new ValidationError(key, value, 'filter array must have at least 1 element')]; + } + errors = errors.concat(validateEnum({ + key: `${key}[0]`, + value: value[0], + valueSpec: styleSpec.filter_operator, + style: options.style, + styleSpec: options.styleSpec + })); + switch (unbundle(value[0])) { + case '<': + case '<=': + case '>': + case '>=': + if (value.length >= 2 && unbundle(value[1]) === '$type') { + errors.push(new ValidationError(key, value, `"$type" cannot be use with operator "${value[0]}"`)); + } + /* falls through */ + case '==': + case '!=': + if (value.length !== 3) { + errors.push(new ValidationError(key, value, `filter array for operator "${value[0]}" must have 3 elements`)); + } + /* falls through */ + case 'in': + case '!in': + if (value.length >= 2) { + type = getType(value[1]); + if (type !== 'string') { + errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); + } + } + for (let i = 2; i < value.length; i++) { + type = getType(value[i]); + if (unbundle(value[1]) === '$type') { + errors = errors.concat(validateEnum({ + key: `${key}[${i}]`, + value: value[i], + valueSpec: styleSpec.geometry_type, + style: options.style, + styleSpec: options.styleSpec + })); + } + else if (type !== 'string' && type !== 'number' && type !== 'boolean') { + errors.push(new ValidationError(`${key}[${i}]`, value[i], `string, number, or boolean expected, ${type} found`)); + } + } + break; + case 'any': + case 'all': + case 'none': + for (let i = 1; i < value.length; i++) { + errors = errors.concat(validateNonExpressionFilter({ + key: `${key}[${i}]`, + value: value[i], + style: options.style, + styleSpec: options.styleSpec + })); + } + break; + case 'has': + case '!has': + type = getType(value[1]); + if (value.length !== 2) { + errors.push(new ValidationError(key, value, `filter array for "${value[0]}" operator must have 2 elements`)); + } + else if (type !== 'string') { + errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); + } + break; + } + return errors; +} + +function validateProperty(options, propertyType) { + const key = options.key; + const validateSpec = options.validateSpec; + const style = options.style; + const styleSpec = options.styleSpec; + const value = options.value; + const propertyKey = options.objectKey; + const layerSpec = styleSpec[`${propertyType}_${options.layerType}`]; + if (!layerSpec) + return []; + const transitionMatch = propertyKey.match(/^(.*)-transition$/); + if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) { + return validateSpec({ + key, + value, + valueSpec: styleSpec.transition, + style, + styleSpec + }); + } + const valueSpec = options.valueSpec || layerSpec[propertyKey]; + if (!valueSpec) { + return [new ValidationError(key, value, `unknown property "${propertyKey}"`)]; + } + let tokenMatch; + if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) { + return [new ValidationError(key, value, `"${propertyKey}" does not support interpolation syntax\n` + + `Use an identity property function instead: \`{ "type": "identity", "property": ${JSON.stringify(tokenMatch[1])} }\`.`)]; + } + const errors = []; + if (options.layerType === 'symbol') { + if (propertyKey === 'text-field' && style && !style.glyphs) { + errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property')); + } + if (propertyKey === 'text-font' && isFunction$1(deepUnbundle(value)) && unbundle(value.type) === 'identity') { + errors.push(new ValidationError(key, value, '"text-font" does not support identity functions')); + } + } + return errors.concat(validateSpec({ + key: options.key, + value, + valueSpec, + style, + styleSpec, + expressionContext: 'property', + propertyType, + propertyKey + })); +} + +function validatePaintProperty$1(options) { + return validateProperty(options, 'paint'); +} + +function validateLayoutProperty$1(options) { + return validateProperty(options, 'layout'); +} + +function validateLayer(options) { + let errors = []; + const layer = options.value; + const key = options.key; + const style = options.style; + const styleSpec = options.styleSpec; + if (!layer.type && !layer.ref) { + errors.push(new ValidationError(key, layer, 'either "type" or "ref" is required')); + } + let type = unbundle(layer.type); + const ref = unbundle(layer.ref); + if (layer.id) { + const layerId = unbundle(layer.id); + for (let i = 0; i < options.arrayIndex; i++) { + const otherLayer = style.layers[i]; + if (unbundle(otherLayer.id) === layerId) { + errors.push(new ValidationError(key, layer.id, `duplicate layer id "${layer.id}", previously used at line ${otherLayer.id.__line__}`)); + } + } + } + if ('ref' in layer) { + ['type', 'source', 'source-layer', 'filter', 'layout'].forEach((p) => { + if (p in layer) { + errors.push(new ValidationError(key, layer[p], `"${p}" is prohibited for ref layers`)); + } + }); + let parent; + style.layers.forEach((layer) => { + if (unbundle(layer.id) === ref) + parent = layer; + }); + if (!parent) { + errors.push(new ValidationError(key, layer.ref, `ref layer "${ref}" not found`)); + } + else if (parent.ref) { + errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer')); + } + else { + type = unbundle(parent.type); + } + } + else if (type !== 'background') { + if (!layer.source) { + errors.push(new ValidationError(key, layer, 'missing required property "source"')); + } + else { + const source = style.sources && style.sources[layer.source]; + const sourceType = source && unbundle(source.type); + if (!source) { + errors.push(new ValidationError(key, layer.source, `source "${layer.source}" not found`)); + } + else if (sourceType === 'vector' && type === 'raster') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a raster source`)); + } + else if (sourceType !== 'raster-dem' && type === 'hillshade') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a raster-dem source`)); + } + else if (sourceType === 'raster' && type !== 'raster') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a vector source`)); + } + else if (sourceType === 'vector' && !layer['source-layer']) { + errors.push(new ValidationError(key, layer, `layer "${layer.id}" must specify a "source-layer"`)); + } + else if (sourceType === 'raster-dem' && type !== 'hillshade') { + errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \'hillshade\'.')); + } + else if (type === 'line' && layer.paint && layer.paint['line-gradient'] && + (sourceType !== 'geojson' || !source.lineMetrics)) { + errors.push(new ValidationError(key, layer, `layer "${layer.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)); + } + } + } + errors = errors.concat(validateObject({ + key, + value: layer, + valueSpec: styleSpec.layer, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + objectElementValidators: { + '*'() { + return []; + }, + // We don't want to enforce the spec's `"requires": true` for backward compatibility with refs; + // the actual requirement is validated above. See https://github.com/mapbox/mapbox-gl-js/issues/5772. + type() { + return options.validateSpec({ + key: `${key}.type`, + value: layer.type, + valueSpec: styleSpec.layer.type, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + object: layer, + objectKey: 'type' + }); + }, + filter: validateFilter, + layout(options) { + return validateObject({ + layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + objectElementValidators: { + '*'(options) { + return validateLayoutProperty$1(extendBy({ layerType: type }, options)); + } + } + }); + }, + paint(options) { + return validateObject({ + layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + validateSpec: options.validateSpec, + objectElementValidators: { + '*'(options) { + return validatePaintProperty$1(extendBy({ layerType: type }, options)); + } + } + }); + } + } + })); + return errors; +} + +function validateString(options) { + const value = options.value; + const key = options.key; + const type = getType(value); + if (type !== 'string') { + return [new ValidationError(key, value, `string expected, ${type} found`)]; + } + return []; +} + +function validateRasterDEMSource(options) { + var _a; + const sourceName = (_a = options.sourceName) !== null && _a !== void 0 ? _a : ''; + const rasterDEM = options.value; + const styleSpec = options.styleSpec; + const rasterDEMSpec = styleSpec.source_raster_dem; + const style = options.style; + let errors = []; + const rootType = getType(rasterDEM); + if (rasterDEM === undefined) { + return errors; + } + else if (rootType !== 'object') { + errors.push(new ValidationError('source_raster_dem', rasterDEM, `object expected, ${rootType} found`)); + return errors; + } + const encoding = unbundle(rasterDEM.encoding); + const isCustomEncoding = encoding === 'custom'; + const customEncodingKeys = ['redFactor', 'greenFactor', 'blueFactor', 'baseShift']; + const encodingName = options.value.encoding ? `"${options.value.encoding}"` : 'Default'; + for (const key in rasterDEM) { + if (!isCustomEncoding && customEncodingKeys.includes(key)) { + errors.push(new ValidationError(key, rasterDEM[key], `In "${sourceName}": "${key}" is only valid when "encoding" is set to "custom". ${encodingName} encoding found`)); + } + else if (rasterDEMSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: rasterDEM[key], + valueSpec: rasterDEMSpec[key], + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else { + errors.push(new ValidationError(key, rasterDEM[key], `unknown property "${key}"`)); + } + } + return errors; +} + +const objectElementValidators = { + promoteId: validatePromoteId +}; +function validateSource(options) { + const value = options.value; + const key = options.key; + const styleSpec = options.styleSpec; + const style = options.style; + const validateSpec = options.validateSpec; + if (!value.type) { + return [new ValidationError(key, value, '"type" is required')]; + } + const type = unbundle(value.type); + let errors; + switch (type) { + case 'vector': + case 'raster': + errors = validateObject({ + key, + value, + valueSpec: styleSpec[`source_${type.replace('-', '_')}`], + style: options.style, + styleSpec, + objectElementValidators, + validateSpec, + }); + return errors; + case 'raster-dem': + errors = validateRasterDEMSource({ + sourceName: key, + value, + style: options.style, + styleSpec, + validateSpec, + }); + return errors; + case 'geojson': + errors = validateObject({ + key, + value, + valueSpec: styleSpec.source_geojson, + style, + styleSpec, + validateSpec, + objectElementValidators + }); + if (value.cluster) { + for (const prop in value.clusterProperties) { + const [operator, mapExpr] = value.clusterProperties[prop]; + const reduceExpr = typeof operator === 'string' ? [operator, ['accumulated'], ['get', prop]] : operator; + errors.push(...validateExpression({ + key: `${key}.${prop}.map`, + value: mapExpr, + validateSpec, + expressionContext: 'cluster-map' + })); + errors.push(...validateExpression({ + key: `${key}.${prop}.reduce`, + value: reduceExpr, + validateSpec, + expressionContext: 'cluster-reduce' + })); + } + } + return errors; + case 'video': + return validateObject({ + key, + value, + valueSpec: styleSpec.source_video, + style, + validateSpec, + styleSpec + }); + case 'image': + return validateObject({ + key, + value, + valueSpec: styleSpec.source_image, + style, + validateSpec, + styleSpec + }); + case 'canvas': + return [new ValidationError(key, null, 'Please use runtime APIs to add canvas sources, rather than including them in stylesheets.', 'source.canvas')]; + default: + return validateEnum({ + key: `${key}.type`, + value: value.type, + valueSpec: { values: ['vector', 'raster', 'raster-dem', 'geojson', 'video', 'image'] }, + style, + validateSpec, + styleSpec + }); + } +} +function validatePromoteId({ key, value }) { + if (getType(value) === 'string') { + return validateString({ key, value }); + } + else { + const errors = []; + for (const prop in value) { + errors.push(...validateString({ key: `${key}.${prop}`, value: value[prop] })); + } + return errors; + } +} + +function validateLight$1(options) { + const light = options.value; + const styleSpec = options.styleSpec; + const lightSpec = styleSpec.light; + const style = options.style; + let errors = []; + const rootType = getType(light); + if (light === undefined) { + return errors; + } + else if (rootType !== 'object') { + errors = errors.concat([new ValidationError('light', light, `object expected, ${rootType} found`)]); + return errors; + } + for (const key in light) { + const transitionMatch = key.match(/^(.*)-transition$/); + if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) { + errors = errors.concat(options.validateSpec({ + key, + value: light[key], + valueSpec: styleSpec.transition, + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else if (lightSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: light[key], + valueSpec: lightSpec[key], + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, light[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +function validateSky$1(options) { + const sky = options.value; + const styleSpec = options.styleSpec; + const skySpec = styleSpec.sky; + const style = options.style; + const rootType = getType(sky); + if (sky === undefined) { + return []; + } + else if (rootType !== 'object') { + return [new ValidationError('sky', sky, `object expected, ${rootType} found`)]; + } + let errors = []; + for (const key in sky) { + if (skySpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: sky[key], + valueSpec: skySpec[key], + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, sky[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +function validateTerrain(options) { + const terrain = options.value; + const styleSpec = options.styleSpec; + const terrainSpec = styleSpec.terrain; + const style = options.style; + let errors = []; + const rootType = getType(terrain); + if (terrain === undefined) { + return errors; + } + else if (rootType !== 'object') { + errors = errors.concat([new ValidationError('terrain', terrain, `object expected, ${rootType} found`)]); + return errors; + } + for (const key in terrain) { + if (terrainSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: terrain[key], + valueSpec: terrainSpec[key], + validateSpec: options.validateSpec, + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, terrain[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +function validateFormatted(options) { + if (validateString(options).length === 0) { + return []; + } + return validateExpression(options); +} + +function validateImage(options) { + if (validateString(options).length === 0) { + return []; + } + return validateExpression(options); +} + +function validatePadding(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + if (type === 'array') { + if (value.length < 1 || value.length > 4) { + return [new ValidationError(key, value, `padding requires 1 to 4 values; ${value.length} values found`)]; + } + const arrayElementSpec = { + type: 'number' + }; + let errors = []; + for (let i = 0; i < value.length; i++) { + errors = errors.concat(options.validateSpec({ + key: `${key}[${i}]`, + value: value[i], + validateSpec: options.validateSpec, + valueSpec: arrayElementSpec + })); + } + return errors; + } + else { + return validateNumber({ + key, + value, + valueSpec: {} + }); + } +} + +function validateVariableAnchorOffsetCollection(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + const styleSpec = options.styleSpec; + if (type !== 'array' || value.length < 1 || value.length % 2 !== 0) { + return [new ValidationError(key, value, 'variableAnchorOffsetCollection requires a non-empty array of even length')]; + } + let errors = []; + for (let i = 0; i < value.length; i += 2) { + // Elements in even positions should be values from text-anchor enum + errors = errors.concat(validateEnum({ + key: `${key}[${i}]`, + value: value[i], + valueSpec: styleSpec['layout_symbol']['text-anchor'] + })); + // Elements in odd positions should be points (2-element numeric arrays) + errors = errors.concat(validateArray({ + key: `${key}[${i + 1}]`, + value: value[i + 1], + valueSpec: { + length: 2, + value: 'number' + }, + validateSpec: options.validateSpec, + style: options.style, + styleSpec + })); + } + return errors; +} + +function validateSprite(options) { + let errors = []; + const sprite = options.value; + const key = options.key; + if (!Array.isArray(sprite)) { + return validateString({ + key, + value: sprite + }); + } + else { + const allSpriteIds = []; + const allSpriteURLs = []; + for (const i in sprite) { + if (sprite[i].id && allSpriteIds.includes(sprite[i].id)) + errors.push(new ValidationError(key, sprite, `all the sprites' ids must be unique, but ${sprite[i].id} is duplicated`)); + allSpriteIds.push(sprite[i].id); + if (sprite[i].url && allSpriteURLs.includes(sprite[i].url)) + errors.push(new ValidationError(key, sprite, `all the sprites' URLs must be unique, but ${sprite[i].url} is duplicated`)); + allSpriteURLs.push(sprite[i].url); + const pairSpec = { + id: { + type: 'string', + required: true, + }, + url: { + type: 'string', + required: true, + } + }; + errors = errors.concat(validateObject({ + key: `${key}[${i}]`, + value: sprite[i], + valueSpec: pairSpec, + validateSpec: options.validateSpec, + })); + } + return errors; + } +} + +function validateProjection(options) { + const projection = options.value; + const styleSpec = options.styleSpec; + const projectionSpec = styleSpec.projection; + const style = options.style; + const rootType = getType(projection); + if (projection === undefined) { + return []; + } + else if (rootType !== 'object') { + return [new ValidationError('projection', projection, `object expected, ${rootType} found`)]; + } + let errors = []; + for (const key in projection) { + if (projectionSpec[key]) { + errors = errors.concat(options.validateSpec({ + key, + value: projection[key], + valueSpec: projectionSpec[key], + style, + styleSpec + })); + } + else { + errors = errors.concat([new ValidationError(key, projection[key], `unknown property "${key}"`)]); + } + } + return errors; +} + +const VALIDATORS = { + '*'() { + return []; + }, + 'array': validateArray, + 'boolean': validateBoolean, + 'number': validateNumber, + 'color': validateColor, + 'constants': validateConstants, + 'enum': validateEnum, + 'filter': validateFilter, + 'function': validateFunction, + 'layer': validateLayer, + 'object': validateObject, + 'source': validateSource, + 'light': validateLight$1, + 'sky': validateSky$1, + 'terrain': validateTerrain, + 'projection': validateProjection, + 'string': validateString, + 'formatted': validateFormatted, + 'resolvedImage': validateImage, + 'padding': validatePadding, + 'variableAnchorOffsetCollection': validateVariableAnchorOffsetCollection, + 'sprite': validateSprite, +}; +/** + * Main recursive validation function used internally. + * You should use `validateStyleMin` in the browser or `validateStyle` in node env. + * @param options - the options object + * @param options.key - string representing location of validation in style tree. Used only + * for more informative error reporting. + * @param options.value - current value from style being evaluated. May be anything from a + * high level object that needs to be descended into deeper or a simple + * scalar value. + * @param options.valueSpec - current spec being evaluated. Tracks value. + * @param options.styleSpec - current full spec being evaluated. + * @param options.validateSpec - the validate function itself + * @param options.style - the style object + * @param options.objectElementValidators - optional object of functions that will be called + * @returns an array of errors, or an empty array if no errors are found. + */ +function validate(options) { + const value = options.value; + const valueSpec = options.valueSpec; + const styleSpec = options.styleSpec; + options.validateSpec = validate; + if (valueSpec.expression && isFunction$1(unbundle(value))) { + return validateFunction(options); + } + else if (valueSpec.expression && isExpression(deepUnbundle(value))) { + return validateExpression(options); + } + else if (valueSpec.type && VALIDATORS[valueSpec.type]) { + return VALIDATORS[valueSpec.type](options); + } + else { + const valid = validateObject(extendBy({}, options, { + valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec + })); + return valid; + } +} + +function validateGlyphsUrl(options) { + const value = options.value; + const key = options.key; + const errors = validateString(options); + if (errors.length) + return errors; + if (value.indexOf('{fontstack}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{fontstack}" token')); + } + if (value.indexOf('{range}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{range}" token')); + } + return errors; +} + +/** + * Validate a MapLibre style against the style specification. + * Use this when running in the browser. + * + * @param style - The style to be validated. + * @param styleSpec - The style specification to validate against. + * If omitted, the latest style spec is used. + * @returns an array of errors, or an empty array if no errors are found. + * @example + * const validate = require('@maplibre/maplibre-gl-style-spec/').validateStyleMin; + * const errors = validate(style); + */ +function validateStyleMin(style, styleSpec = v8Spec) { + let errors = []; + errors = errors.concat(validate({ + key: '', + value: style, + valueSpec: styleSpec.$root, + styleSpec, + style, + validateSpec: validate, + objectElementValidators: { + glyphs: validateGlyphsUrl, + '*'() { + return []; + } + } + })); + if (style['constants']) { + errors = errors.concat(validateConstants({ + key: 'constants', + value: style['constants'], + style, + styleSpec, + validateSpec: validate, + })); + } + return sortErrors(errors); +} +validateStyleMin.source = wrapCleanErrors(injectValidateSpec(validateSource)); +validateStyleMin.sprite = wrapCleanErrors(injectValidateSpec(validateSprite)); +validateStyleMin.glyphs = wrapCleanErrors(injectValidateSpec(validateGlyphsUrl)); +validateStyleMin.light = wrapCleanErrors(injectValidateSpec(validateLight$1)); +validateStyleMin.sky = wrapCleanErrors(injectValidateSpec(validateSky$1)); +validateStyleMin.terrain = wrapCleanErrors(injectValidateSpec(validateTerrain)); +validateStyleMin.layer = wrapCleanErrors(injectValidateSpec(validateLayer)); +validateStyleMin.filter = wrapCleanErrors(injectValidateSpec(validateFilter)); +validateStyleMin.paintProperty = wrapCleanErrors(injectValidateSpec(validatePaintProperty$1)); +validateStyleMin.layoutProperty = wrapCleanErrors(injectValidateSpec(validateLayoutProperty$1)); +function injectValidateSpec(validator) { + return function (options) { + return validator({ + ...options, + validateSpec: validate, + }); + }; +} +function sortErrors(errors) { + return [].concat(errors).sort((a, b) => { + return a.line - b.line; + }); +} +function wrapCleanErrors(inner) { + return function (...args) { + return sortErrors(inner.apply(this, args)); + }; +} + +const validateStyle = validateStyleMin; +validateStyle.source; +const validateLight = validateStyle.light; +const validateSky = validateStyle.sky; +validateStyle.terrain; +validateStyle.filter; +const validatePaintProperty = validateStyle.paintProperty; +const validateLayoutProperty = validateStyle.layoutProperty; +function emitValidationErrors(emitter, errors) { + let hasErrors = false; + if (errors && errors.length) { + for (const error of errors) { + emitter.fire(new ErrorEvent(new Error(error.message))); + hasErrors = true; + } + } + return hasErrors; +} + +/* +This file was copied from https://github.com/mapbox/grid-index and was +migrated from JavaScript to TypeScript. + +Copyright (c) 2016, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +*/ +const NUM_PARAMS = 3; +class TransferableGridIndex { + constructor(extent, n, padding) { + const cells = this.cells = []; + if (extent instanceof ArrayBuffer) { + this.arrayBuffer = extent; + const array = new Int32Array(this.arrayBuffer); + extent = array[0]; + n = array[1]; + padding = array[2]; + this.d = n + 2 * padding; + for (let k = 0; k < this.d * this.d; k++) { + const start = array[NUM_PARAMS + k]; + const end = array[NUM_PARAMS + k + 1]; + cells.push(start === end ? null : array.subarray(start, end)); + } + const keysOffset = array[NUM_PARAMS + cells.length]; + const bboxesOffset = array[NUM_PARAMS + cells.length + 1]; + this.keys = array.subarray(keysOffset, bboxesOffset); + this.bboxes = array.subarray(bboxesOffset); + this.insert = this._insertReadonly; + } + else { + this.d = n + 2 * padding; + for (let i = 0; i < this.d * this.d; i++) { + cells.push([]); + } + this.keys = []; + this.bboxes = []; + } + this.n = n; + this.extent = extent; + this.padding = padding; + this.scale = n / extent; + this.uid = 0; + const p = (padding / n) * extent; + this.min = -p; + this.max = extent + p; + } + insert(key, x1, y1, x2, y2) { + this._forEachCell(x1, y1, x2, y2, this._insertCell, this.uid++, undefined, undefined); + this.keys.push(key); + this.bboxes.push(x1); + this.bboxes.push(y1); + this.bboxes.push(x2); + this.bboxes.push(y2); + } + _insertReadonly() { + throw new Error('Cannot insert into a GridIndex created from an ArrayBuffer.'); + } + _insertCell(x1, y1, x2, y2, cellIndex, uid) { + this.cells[cellIndex].push(uid); + } + query(x1, y1, x2, y2, intersectionTest) { + const min = this.min; + const max = this.max; + if (x1 <= min && y1 <= min && max <= x2 && max <= y2 && !intersectionTest) { + // We use `Array#slice` because `this.keys` may be a `Int32Array` and + // some browsers (Safari and IE) do not support `TypedArray#slice` + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice#Browser_compatibility + return Array.prototype.slice.call(this.keys); + } + else { + const result = []; + const seenUids = {}; + this._forEachCell(x1, y1, x2, y2, this._queryCell, result, seenUids, intersectionTest); + return result; + } + } + _queryCell(x1, y1, x2, y2, cellIndex, result, seenUids, intersectionTest) { + const cell = this.cells[cellIndex]; + if (cell !== null) { + const keys = this.keys; + const bboxes = this.bboxes; + for (let u = 0; u < cell.length; u++) { + const uid = cell[u]; + if (seenUids[uid] === undefined) { + const offset = uid * 4; + if (intersectionTest ? + intersectionTest(bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) : + ((x1 <= bboxes[offset + 2]) && + (y1 <= bboxes[offset + 3]) && + (x2 >= bboxes[offset + 0]) && + (y2 >= bboxes[offset + 1]))) { + seenUids[uid] = true; + result.push(keys[uid]); + } + else { + seenUids[uid] = false; + } + } + } + } + } + _forEachCell(x1, y1, x2, y2, fn, arg1, arg2, intersectionTest) { + const cx1 = this._convertToCellCoord(x1); + const cy1 = this._convertToCellCoord(y1); + const cx2 = this._convertToCellCoord(x2); + const cy2 = this._convertToCellCoord(y2); + for (let x = cx1; x <= cx2; x++) { + for (let y = cy1; y <= cy2; y++) { + const cellIndex = this.d * y + x; + if (intersectionTest && !intersectionTest(this._convertFromCellCoord(x), this._convertFromCellCoord(y), this._convertFromCellCoord(x + 1), this._convertFromCellCoord(y + 1))) + continue; + if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, intersectionTest)) + return; + } + } + } + _convertFromCellCoord(x) { + return (x - this.padding) / this.scale; + } + _convertToCellCoord(x) { + return Math.max(0, Math.min(this.d - 1, Math.floor(x * this.scale) + this.padding)); + } + toArrayBuffer() { + if (this.arrayBuffer) + return this.arrayBuffer; + const cells = this.cells; + const metadataLength = NUM_PARAMS + this.cells.length + 1 + 1; + let totalCellLength = 0; + for (let i = 0; i < this.cells.length; i++) { + totalCellLength += this.cells[i].length; + } + const array = new Int32Array(metadataLength + totalCellLength + this.keys.length + this.bboxes.length); + array[0] = this.extent; + array[1] = this.n; + array[2] = this.padding; + let offset = metadataLength; + for (let k = 0; k < cells.length; k++) { + const cell = cells[k]; + array[NUM_PARAMS + k] = offset; + array.set(cell, offset); + offset += cell.length; + } + array[NUM_PARAMS + cells.length] = offset; + array.set(this.keys, offset); + offset += this.keys.length; + array[NUM_PARAMS + cells.length + 1] = offset; + array.set(this.bboxes, offset); + offset += this.bboxes.length; + return array.buffer; + } + static serialize(grid, transferables) { + const buffer = grid.toArrayBuffer(); + if (transferables) { + transferables.push(buffer); + } + return { buffer }; + } + static deserialize(serialized) { + return new TransferableGridIndex(serialized.buffer); + } +} + +const registry = {}; +/** + * Register the given class as serializable. + * + * @param options - the registration options + */ +function register(name, klass, options = {}) { + if (registry[name]) + throw new Error(`${name} is already registered.`); + Object.defineProperty(klass, '_classRegistryKey', { + value: name, + writeable: false + }); + registry[name] = { + klass, + omit: options.omit || [], + shallow: options.shallow || [] + }; +} +register('Object', Object); +register('TransferableGridIndex', TransferableGridIndex); +register('Color', Color); +register('Error', Error); +register('AJAXError', AJAXError); +register('ResolvedImage', ResolvedImage); +register('StylePropertyFunction', StylePropertyFunction); +register('StyleExpression', StyleExpression, { omit: ['_evaluator'] }); +register('ZoomDependentExpression', ZoomDependentExpression); +register('ZoomConstantExpression', ZoomConstantExpression); +register('CompoundExpression', CompoundExpression, { omit: ['_evaluate'] }); +for (const name in expressions$1) { + if (expressions$1[name]._classRegistryKey) + continue; + register(`Expression_${name}`, expressions$1[name]); +} +function isArrayBuffer(value) { + return value && typeof ArrayBuffer !== 'undefined' && + (value instanceof ArrayBuffer || (value.constructor && value.constructor.name === 'ArrayBuffer')); +} +function getClassRegistryKey(input) { + const klass = input.constructor; + return input.$name || klass._classRegistryKey; +} +function isRegistered(input) { + if (input === null || typeof input !== 'object') { + return false; + } + const classRegistryKey = getClassRegistryKey(input); + if (classRegistryKey && classRegistryKey !== 'Object') { + return true; + } + return false; +} +function isSerializeHandledByBuiltin(input) { + return (!isRegistered(input) && (input === null || + input === undefined || + typeof input === 'boolean' || + typeof input === 'number' || + typeof input === 'string' || + input instanceof Boolean || + input instanceof Number || + input instanceof String || + input instanceof Date || + input instanceof RegExp || + input instanceof Blob || + input instanceof Error || + isArrayBuffer(input) || + isImageBitmap(input) || + ArrayBuffer.isView(input) || + input instanceof ImageData)); +} +/** + * Serialize the given object for transfer to or from a web worker. + * + * For non-builtin types, recursively serialize each property (possibly + * omitting certain properties - see register()), and package the result along + * with the constructor's `name` so that the appropriate constructor can be + * looked up in `deserialize()`. + * + * If a `transferables` array is provided, add any transferable objects (i.e., + * any ArrayBuffers or ArrayBuffer views) to the list. (If a copy is needed, + * this should happen in the client code, before using serialize().) + */ +function serialize(input, transferables) { + if (isSerializeHandledByBuiltin(input)) { + if (isArrayBuffer(input) || isImageBitmap(input)) { + if (transferables) { + transferables.push(input); + } + } + if (ArrayBuffer.isView(input)) { + const view = input; + if (transferables) { + transferables.push(view.buffer); + } + } + if (input instanceof ImageData) { + if (transferables) { + transferables.push(input.data.buffer); + } + } + return input; + } + if (Array.isArray(input)) { + const serialized = []; + for (const item of input) { + serialized.push(serialize(item, transferables)); + } + return serialized; + } + if (typeof input !== 'object') { + throw new Error(`can't serialize object of type ${typeof input}`); + } + const classRegistryKey = getClassRegistryKey(input); + if (!classRegistryKey) { + throw new Error(`can't serialize object of unregistered class ${input.constructor.name}`); + } + if (!registry[classRegistryKey]) + throw new Error(`${classRegistryKey} is not registered.`); + const { klass } = registry[classRegistryKey]; + const properties = klass.serialize ? + // (Temporary workaround) allow a class to provide static + // `serialize()` and `deserialize()` methods to bypass the generic + // approach. + // This temporary workaround lets us use the generic serialization + // approach for objects whose members include instances of dynamic + // StructArray types. Once we refactor StructArray to be static, + // we can remove this complexity. + klass.serialize(input, transferables) : {}; + if (!klass.serialize) { + for (const key in input) { + if (!input.hasOwnProperty(key)) + continue; // eslint-disable-line no-prototype-builtins + if (registry[classRegistryKey].omit.indexOf(key) >= 0) + continue; + const property = input[key]; + properties[key] = registry[classRegistryKey].shallow.indexOf(key) >= 0 ? + property : + serialize(property, transferables); + } + if (input instanceof Error) { + properties.message = input.message; + } + } + else { + if (transferables && properties === transferables[transferables.length - 1]) { + throw new Error('statically serialized object won\'t survive transfer of $name property'); + } + } + if (properties.$name) { + throw new Error('$name property is reserved for worker serialization logic.'); + } + if (classRegistryKey !== 'Object') { + properties.$name = classRegistryKey; + } + return properties; +} +function deserialize(input) { + if (isSerializeHandledByBuiltin(input)) { + return input; + } + if (Array.isArray(input)) { + return input.map(deserialize); + } + if (typeof input !== 'object') { + throw new Error(`can't deserialize object of type ${typeof input}`); + } + const classRegistryKey = getClassRegistryKey(input) || 'Object'; + if (!registry[classRegistryKey]) { + throw new Error(`can't deserialize unregistered class ${classRegistryKey}`); + } + const { klass } = registry[classRegistryKey]; + if (!klass) { + throw new Error(`can't deserialize unregistered class ${classRegistryKey}`); + } + if (klass.deserialize) { + return klass.deserialize(input); + } + const result = Object.create(klass.prototype); + for (const key of Object.keys(input)) { + if (key === '$name') + continue; + const value = input[key]; + result[key] = registry[classRegistryKey].shallow.indexOf(key) >= 0 ? value : deserialize(value); + } + return result; +} + +class ZoomHistory { + constructor() { + this.first = true; + } + update(z, now) { + const floorZ = Math.floor(z); + if (this.first) { + this.first = false; + this.lastIntegerZoom = floorZ; + this.lastIntegerZoomTime = 0; + this.lastZoom = z; + this.lastFloorZoom = floorZ; + return true; + } + if (this.lastFloorZoom > floorZ) { + this.lastIntegerZoom = floorZ + 1; + this.lastIntegerZoomTime = now; + } + else if (this.lastFloorZoom < floorZ) { + this.lastIntegerZoom = floorZ; + this.lastIntegerZoomTime = now; + } + if (z !== this.lastZoom) { + this.lastZoom = z; + this.lastFloorZoom = floorZ; + return true; + } + return false; + } +} + +// The following table comes from . +// Keep it synchronized with . +const unicodeBlockLookup = { + // 'Basic Latin': (char) => char >= 0x0000 && char <= 0x007F, + 'Latin-1 Supplement': (char) => char >= 0x0080 && char <= 0x00FF, + // 'Latin Extended-A': (char) => char >= 0x0100 && char <= 0x017F, + // 'Latin Extended-B': (char) => char >= 0x0180 && char <= 0x024F, + // 'IPA Extensions': (char) => char >= 0x0250 && char <= 0x02AF, + // 'Spacing Modifier Letters': (char) => char >= 0x02B0 && char <= 0x02FF, + // 'Combining Diacritical Marks': (char) => char >= 0x0300 && char <= 0x036F, + // 'Greek and Coptic': (char) => char >= 0x0370 && char <= 0x03FF, + // 'Cyrillic': (char) => char >= 0x0400 && char <= 0x04FF, + // 'Cyrillic Supplement': (char) => char >= 0x0500 && char <= 0x052F, + // 'Armenian': (char) => char >= 0x0530 && char <= 0x058F, + //'Hebrew': (char) => char >= 0x0590 && char <= 0x05FF, + // 'Arabic': (char) => char >= 0x0600 && char <= 0x06FF, + //'Syriac': (char) => char >= 0x0700 && char <= 0x074F, + // 'Arabic Supplement': (char) => char >= 0x0750 && char <= 0x077F, + // 'Thaana': (char) => char >= 0x0780 && char <= 0x07BF, + // 'NKo': (char) => char >= 0x07C0 && char <= 0x07FF, + // 'Samaritan': (char) => char >= 0x0800 && char <= 0x083F, + // 'Mandaic': (char) => char >= 0x0840 && char <= 0x085F, + // 'Syriac Supplement': (char) => char >= 0x0860 && char <= 0x086F, + // 'Arabic Extended-B': (char) => char >= 0x0870 && char <= 0x089F, + // 'Arabic Extended-A': (char) => char >= 0x08A0 && char <= 0x08FF, + // 'Devanagari': (char) => char >= 0x0900 && char <= 0x097F, + // 'Bengali': (char) => char >= 0x0980 && char <= 0x09FF, + // 'Gurmukhi': (char) => char >= 0x0A00 && char <= 0x0A7F, + // 'Gujarati': (char) => char >= 0x0A80 && char <= 0x0AFF, + // 'Oriya': (char) => char >= 0x0B00 && char <= 0x0B7F, + // 'Tamil': (char) => char >= 0x0B80 && char <= 0x0BFF, + // 'Telugu': (char) => char >= 0x0C00 && char <= 0x0C7F, + // 'Kannada': (char) => char >= 0x0C80 && char <= 0x0CFF, + // 'Malayalam': (char) => char >= 0x0D00 && char <= 0x0D7F, + // 'Sinhala': (char) => char >= 0x0D80 && char <= 0x0DFF, + // 'Thai': (char) => char >= 0x0E00 && char <= 0x0E7F, + // 'Lao': (char) => char >= 0x0E80 && char <= 0x0EFF, + // 'Tibetan': (char) => char >= 0x0F00 && char <= 0x0FFF, + // 'Myanmar': (char) => char >= 0x1000 && char <= 0x109F, + // 'Georgian': (char) => char >= 0x10A0 && char <= 0x10FF, + 'Hangul Jamo': (char) => char >= 0x1100 && char <= 0x11FF, + // 'Ethiopic': (char) => char >= 0x1200 && char <= 0x137F, + // 'Ethiopic Supplement': (char) => char >= 0x1380 && char <= 0x139F, + // 'Cherokee': (char) => char >= 0x13A0 && char <= 0x13FF, + // 'Unified Canadian Aboriginal Syllabics': (char) => char >= 0x1400 && char <= 0x167F, + // 'Ogham': (char) => char >= 0x1680 && char <= 0x169F, + // 'Runic': (char) => char >= 0x16A0 && char <= 0x16FF, + // 'Tagalog': (char) => char >= 0x1700 && char <= 0x171F, + // 'Hanunoo': (char) => char >= 0x1720 && char <= 0x173F, + // 'Buhid': (char) => char >= 0x1740 && char <= 0x175F, + // 'Tagbanwa': (char) => char >= 0x1760 && char <= 0x177F, + 'Khmer': (char) => char >= 0x1780 && char <= 0x17FF, + // 'Mongolian': (char) => char >= 0x1800 && char <= 0x18AF, + // 'Unified Canadian Aboriginal Syllabics Extended': (char) => char >= 0x18B0 && char <= 0x18FF, + // 'Limbu': (char) => char >= 0x1900 && char <= 0x194F, + // 'Tai Le': (char) => char >= 0x1950 && char <= 0x197F, + // 'New Tai Lue': (char) => char >= 0x1980 && char <= 0x19DF, + // 'Khmer Symbols': (char) => char >= 0x19E0 && char <= 0x19FF, + // 'Buginese': (char) => char >= 0x1A00 && char <= 0x1A1F, + // 'Tai Tham': (char) => char >= 0x1A20 && char <= 0x1AAF, + // 'Combining Diacritical Marks Extended': (char) => char >= 0x1AB0 && char <= 0x1AFF, + // 'Balinese': (char) => char >= 0x1B00 && char <= 0x1B7F, + // 'Sundanese': (char) => char >= 0x1B80 && char <= 0x1BBF, + // 'Batak': (char) => char >= 0x1BC0 && char <= 0x1BFF, + // 'Lepcha': (char) => char >= 0x1C00 && char <= 0x1C4F, + // 'Ol Chiki': (char) => char >= 0x1C50 && char <= 0x1C7F, + // 'Cyrillic Extended-C': (char) => char >= 0x1C80 && char <= 0x1C8F, + // 'Georgian Extended': (char) => char >= 0x1C90 && char <= 0x1CBF, + // 'Sundanese Supplement': (char) => char >= 0x1CC0 && char <= 0x1CCF, + // 'Vedic Extensions': (char) => char >= 0x1CD0 && char <= 0x1CFF, + // 'Phonetic Extensions': (char) => char >= 0x1D00 && char <= 0x1D7F, + // 'Phonetic Extensions Supplement': (char) => char >= 0x1D80 && char <= 0x1DBF, + // 'Combining Diacritical Marks Supplement': (char) => char >= 0x1DC0 && char <= 0x1DFF, + // 'Latin Extended Additional': (char) => char >= 0x1E00 && char <= 0x1EFF, + // 'Greek Extended': (char) => char >= 0x1F00 && char <= 0x1FFF, + 'General Punctuation': (char) => char >= 0x2000 && char <= 0x206F, + // 'Superscripts and Subscripts': (char) => char >= 0x2070 && char <= 0x209F, + // 'Currency Symbols': (char) => char >= 0x20A0 && char <= 0x20CF, + // 'Combining Diacritical Marks for Symbols': (char) => char >= 0x20D0 && char <= 0x20FF, + 'Letterlike Symbols': (char) => char >= 0x2100 && char <= 0x214F, + 'Number Forms': (char) => char >= 0x2150 && char <= 0x218F, + // 'Arrows': (char) => char >= 0x2190 && char <= 0x21FF, + // 'Mathematical Operators': (char) => char >= 0x2200 && char <= 0x22FF, + 'Miscellaneous Technical': (char) => char >= 0x2300 && char <= 0x23FF, + 'Control Pictures': (char) => char >= 0x2400 && char <= 0x243F, + 'Optical Character Recognition': (char) => char >= 0x2440 && char <= 0x245F, + 'Enclosed Alphanumerics': (char) => char >= 0x2460 && char <= 0x24FF, + // 'Box Drawing': (char) => char >= 0x2500 && char <= 0x257F, + // 'Block Elements': (char) => char >= 0x2580 && char <= 0x259F, + 'Geometric Shapes': (char) => char >= 0x25A0 && char <= 0x25FF, + 'Miscellaneous Symbols': (char) => char >= 0x2600 && char <= 0x26FF, + // 'Dingbats': (char) => char >= 0x2700 && char <= 0x27BF, + // 'Miscellaneous Mathematical Symbols-A': (char) => char >= 0x27C0 && char <= 0x27EF, + // 'Supplemental Arrows-A': (char) => char >= 0x27F0 && char <= 0x27FF, + // 'Braille Patterns': (char) => char >= 0x2800 && char <= 0x28FF, + // 'Supplemental Arrows-B': (char) => char >= 0x2900 && char <= 0x297F, + // 'Miscellaneous Mathematical Symbols-B': (char) => char >= 0x2980 && char <= 0x29FF, + // 'Supplemental Mathematical Operators': (char) => char >= 0x2A00 && char <= 0x2AFF, + 'Miscellaneous Symbols and Arrows': (char) => char >= 0x2B00 && char <= 0x2BFF, + // 'Glagolitic': (char) => char >= 0x2C00 && char <= 0x2C5F, + // 'Latin Extended-C': (char) => char >= 0x2C60 && char <= 0x2C7F, + // 'Coptic': (char) => char >= 0x2C80 && char <= 0x2CFF, + // 'Georgian Supplement': (char) => char >= 0x2D00 && char <= 0x2D2F, + // 'Tifinagh': (char) => char >= 0x2D30 && char <= 0x2D7F, + // 'Ethiopic Extended': (char) => char >= 0x2D80 && char <= 0x2DDF, + // 'Cyrillic Extended-A': (char) => char >= 0x2DE0 && char <= 0x2DFF, + // 'Supplemental Punctuation': (char) => char >= 0x2E00 && char <= 0x2E7F, + // 'CJK Radicals Supplement': (char) => char >= 0x2E80 && char <= 0x2EFF, + // 'Kangxi Radicals': (char) => char >= 0x2F00 && char <= 0x2FDF, + 'Ideographic Description Characters': (char) => char >= 0x2FF0 && char <= 0x2FFF, + 'CJK Symbols and Punctuation': (char) => char >= 0x3000 && char <= 0x303F, + // 'Hiragana': (char) => char >= 0x3040 && char <= 0x309F, + 'Katakana': (char) => char >= 0x30A0 && char <= 0x30FF, + // 'Bopomofo': (char) => char >= 0x3100 && char <= 0x312F, + // 'Hangul Compatibility Jamo': (char) => char >= 0x3130 && char <= 0x318F, + 'Kanbun': (char) => char >= 0x3190 && char <= 0x319F, + // 'Bopomofo Extended': (char) => char >= 0x31A0 && char <= 0x31BF, + 'CJK Strokes': (char) => char >= 0x31C0 && char <= 0x31EF, + // 'Katakana Phonetic Extensions': (char) => char >= 0x31F0 && char <= 0x31FF, + 'Enclosed CJK Letters and Months': (char) => char >= 0x3200 && char <= 0x32FF, + 'CJK Compatibility': (char) => char >= 0x3300 && char <= 0x33FF, + // 'CJK Unified Ideographs Extension A': (char) => char >= 0x3400 && char <= 0x4DBF, + 'Yijing Hexagram Symbols': (char) => char >= 0x4DC0 && char <= 0x4DFF, + // 'CJK Unified Ideographs': (char) => char >= 0x4E00 && char <= 0x9FFF, + // 'Yi Syllables': (char) => char >= 0xA000 && char <= 0xA48F, + // 'Yi Radicals': (char) => char >= 0xA490 && char <= 0xA4CF, + // 'Lisu': (char) => char >= 0xA4D0 && char <= 0xA4FF, + // 'Vai': (char) => char >= 0xA500 && char <= 0xA63F, + // 'Cyrillic Extended-B': (char) => char >= 0xA640 && char <= 0xA69F, + // 'Bamum': (char) => char >= 0xA6A0 && char <= 0xA6FF, + // 'Modifier Tone Letters': (char) => char >= 0xA700 && char <= 0xA71F, + // 'Latin Extended-D': (char) => char >= 0xA720 && char <= 0xA7FF, + // 'Syloti Nagri': (char) => char >= 0xA800 && char <= 0xA82F, + // 'Common Indic Number Forms': (char) => char >= 0xA830 && char <= 0xA83F, + // 'Phags-pa': (char) => char >= 0xA840 && char <= 0xA87F, + // 'Saurashtra': (char) => char >= 0xA880 && char <= 0xA8DF, + // 'Devanagari Extended': (char) => char >= 0xA8E0 && char <= 0xA8FF, + // 'Kayah Li': (char) => char >= 0xA900 && char <= 0xA92F, + // 'Rejang': (char) => char >= 0xA930 && char <= 0xA95F, + // 'Hangul Jamo Extended-A': (char) => char >= 0xA960 && char <= 0xA97F, + // 'Javanese': (char) => char >= 0xA980 && char <= 0xA9DF, + // 'Myanmar Extended-B': (char) => char >= 0xA9E0 && char <= 0xA9FF, + // 'Cham': (char) => char >= 0xAA00 && char <= 0xAA5F, + // 'Myanmar Extended-A': (char) => char >= 0xAA60 && char <= 0xAA7F, + // 'Tai Viet': (char) => char >= 0xAA80 && char <= 0xAADF, + // 'Meetei Mayek Extensions': (char) => char >= 0xAAE0 && char <= 0xAAFF, + // 'Ethiopic Extended-A': (char) => char >= 0xAB00 && char <= 0xAB2F, + // 'Latin Extended-E': (char) => char >= 0xAB30 && char <= 0xAB6F, + // 'Cherokee Supplement': (char) => char >= 0xAB70 && char <= 0xABBF, + // 'Meetei Mayek': (char) => char >= 0xABC0 && char <= 0xABFF, + // 'Hangul Syllables': (char) => char >= 0xAC00 && char <= 0xD7AF, + // 'Hangul Jamo Extended-B': (char) => char >= 0xD7B0 && char <= 0xD7FF, + // 'High Surrogates': (char) => char >= 0xD800 && char <= 0xDB7F, + // 'High Private Use Surrogates': (char) => char >= 0xDB80 && char <= 0xDBFF, + // 'Low Surrogates': (char) => char >= 0xDC00 && char <= 0xDFFF, + 'Private Use Area': (char) => char >= 0xE000 && char <= 0xF8FF, + // 'CJK Compatibility Ideographs': (char) => char >= 0xF900 && char <= 0xFAFF, + // 'Alphabetic Presentation Forms': (char) => char >= 0xFB00 && char <= 0xFB4F, + // 'Arabic Presentation Forms-A': (char) => char >= 0xFB50 && char <= 0xFDFF, + // 'Variation Selectors': (char) => char >= 0xFE00 && char <= 0xFE0F, + 'Vertical Forms': (char) => char >= 0xFE10 && char <= 0xFE1F, + // 'Combining Half Marks': (char) => char >= 0xFE20 && char <= 0xFE2F, + 'CJK Compatibility Forms': (char) => char >= 0xFE30 && char <= 0xFE4F, + 'Small Form Variants': (char) => char >= 0xFE50 && char <= 0xFE6F, + // 'Arabic Presentation Forms-B': (char) => char >= 0xFE70 && char <= 0xFEFF, + 'Halfwidth and Fullwidth Forms': (char) => char >= 0xFF00 && char <= 0xFFEF + // 'Specials': (char) => char >= 0xFFF0 && char <= 0xFFFF, + // 'Linear B Syllabary': (char) => char >= 0x10000 && char <= 0x1007F, + // 'Linear B Ideograms': (char) => char >= 0x10080 && char <= 0x100FF, + // 'Aegean Numbers': (char) => char >= 0x10100 && char <= 0x1013F, + // 'Ancient Greek Numbers': (char) => char >= 0x10140 && char <= 0x1018F, + // 'Ancient Symbols': (char) => char >= 0x10190 && char <= 0x101CF, + // 'Phaistos Disc': (char) => char >= 0x101D0 && char <= 0x101FF, + // 'Lycian': (char) => char >= 0x10280 && char <= 0x1029F, + // 'Carian': (char) => char >= 0x102A0 && char <= 0x102DF, + // 'Coptic Epact Numbers': (char) => char >= 0x102E0 && char <= 0x102FF, + // 'Old Italic': (char) => char >= 0x10300 && char <= 0x1032F, + // 'Gothic': (char) => char >= 0x10330 && char <= 0x1034F, + // 'Old Permic': (char) => char >= 0x10350 && char <= 0x1037F, + // 'Ugaritic': (char) => char >= 0x10380 && char <= 0x1039F, + // 'Old Persian': (char) => char >= 0x103A0 && char <= 0x103DF, + // 'Deseret': (char) => char >= 0x10400 && char <= 0x1044F, + // 'Shavian': (char) => char >= 0x10450 && char <= 0x1047F, + // 'Osmanya': (char) => char >= 0x10480 && char <= 0x104AF, + // 'Osage': (char) => char >= 0x104B0 && char <= 0x104FF, + // 'Elbasan': (char) => char >= 0x10500 && char <= 0x1052F, + // 'Caucasian Albanian': (char) => char >= 0x10530 && char <= 0x1056F, + // 'Vithkuqi': (char) => char >= 0x10570 && char <= 0x105BF, + // 'Todhri': (char) => char >= 0x105C0 && char <= 0x105FF, + // 'Linear A': (char) => char >= 0x10600 && char <= 0x1077F, + // 'Latin Extended-F': (char) => char >= 0x10780 && char <= 0x107BF, + // 'Cypriot Syllabary': (char) => char >= 0x10800 && char <= 0x1083F, + // 'Imperial Aramaic': (char) => char >= 0x10840 && char <= 0x1085F, + // 'Palmyrene': (char) => char >= 0x10860 && char <= 0x1087F, + // 'Nabataean': (char) => char >= 0x10880 && char <= 0x108AF, + // 'Hatran': (char) => char >= 0x108E0 && char <= 0x108FF, + // 'Phoenician': (char) => char >= 0x10900 && char <= 0x1091F, + // 'Lydian': (char) => char >= 0x10920 && char <= 0x1093F, + // 'Meroitic Hieroglyphs': (char) => char >= 0x10980 && char <= 0x1099F, + // 'Meroitic Cursive': (char) => char >= 0x109A0 && char <= 0x109FF, + // 'Kharoshthi': (char) => char >= 0x10A00 && char <= 0x10A5F, + // 'Old South Arabian': (char) => char >= 0x10A60 && char <= 0x10A7F, + // 'Old North Arabian': (char) => char >= 0x10A80 && char <= 0x10A9F, + // 'Manichaean': (char) => char >= 0x10AC0 && char <= 0x10AFF, + // 'Avestan': (char) => char >= 0x10B00 && char <= 0x10B3F, + // 'Inscriptional Parthian': (char) => char >= 0x10B40 && char <= 0x10B5F, + // 'Inscriptional Pahlavi': (char) => char >= 0x10B60 && char <= 0x10B7F, + // 'Psalter Pahlavi': (char) => char >= 0x10B80 && char <= 0x10BAF, + // 'Old Turkic': (char) => char >= 0x10C00 && char <= 0x10C4F, + // 'Old Hungarian': (char) => char >= 0x10C80 && char <= 0x10CFF, + // 'Hanifi Rohingya': (char) => char >= 0x10D00 && char <= 0x10D3F, + // 'Garay': (char) => char >= 0x10D40 && char <= 0x10D8F, + // 'Rumi Numeral Symbols': (char) => char >= 0x10E60 && char <= 0x10E7F, + // 'Yezidi': (char) => char >= 0x10E80 && char <= 0x10EBF, + // 'Arabic Extended-C': (char) => char >= 0x10EC0 && char <= 0x10EFF, + // 'Old Sogdian': (char) => char >= 0x10F00 && char <= 0x10F2F, + // 'Sogdian': (char) => char >= 0x10F30 && char <= 0x10F6F, + // 'Old Uyghur': (char) => char >= 0x10F70 && char <= 0x10FAF, + // 'Chorasmian': (char) => char >= 0x10FB0 && char <= 0x10FDF, + // 'Elymaic': (char) => char >= 0x10FE0 && char <= 0x10FFF, + // 'Brahmi': (char) => char >= 0x11000 && char <= 0x1107F, + // 'Kaithi': (char) => char >= 0x11080 && char <= 0x110CF, + // 'Sora Sompeng': (char) => char >= 0x110D0 && char <= 0x110FF, + // 'Chakma': (char) => char >= 0x11100 && char <= 0x1114F, + // 'Mahajani': (char) => char >= 0x11150 && char <= 0x1117F, + // 'Sharada': (char) => char >= 0x11180 && char <= 0x111DF, + // 'Sinhala Archaic Numbers': (char) => char >= 0x111E0 && char <= 0x111FF, + // 'Khojki': (char) => char >= 0x11200 && char <= 0x1124F, + // 'Multani': (char) => char >= 0x11280 && char <= 0x112AF, + // 'Khudawadi': (char) => char >= 0x112B0 && char <= 0x112FF, + // 'Grantha': (char) => char >= 0x11300 && char <= 0x1137F, + // 'Tulu-Tigalari': (char) => char >= 0x11380 && char <= 0x113FF, + // 'Newa': (char) => char >= 0x11400 && char <= 0x1147F, + // 'Tirhuta': (char) => char >= 0x11480 && char <= 0x114DF, + // 'Siddham': (char) => char >= 0x11580 && char <= 0x115FF, + // 'Modi': (char) => char >= 0x11600 && char <= 0x1165F, + // 'Mongolian Supplement': (char) => char >= 0x11660 && char <= 0x1167F, + // 'Takri': (char) => char >= 0x11680 && char <= 0x116CF, + // 'Myanmar Extended-C': (char) => char >= 0x116D0 && char <= 0x116FF, + // 'Ahom': (char) => char >= 0x11700 && char <= 0x1174F, + // 'Dogra': (char) => char >= 0x11800 && char <= 0x1184F, + // 'Warang Citi': (char) => char >= 0x118A0 && char <= 0x118FF, + // 'Dives Akuru': (char) => char >= 0x11900 && char <= 0x1195F, + // 'Nandinagari': (char) => char >= 0x119A0 && char <= 0x119FF, + // 'Zanabazar Square': (char) => char >= 0x11A00 && char <= 0x11A4F, + // 'Soyombo': (char) => char >= 0x11A50 && char <= 0x11AAF, + // 'Unified Canadian Aboriginal Syllabics Extended-A': (char) => char >= 0x11AB0 && char <= 0x11ABF, + // 'Pau Cin Hau': (char) => char >= 0x11AC0 && char <= 0x11AFF, + // 'Devanagari Extended-A': (char) => char >= 0x11B00 && char <= 0x11B5F, + // 'Sunuwar': (char) => char >= 0x11BC0 && char <= 0x11BFF, + // 'Bhaiksuki': (char) => char >= 0x11C00 && char <= 0x11C6F, + // 'Marchen': (char) => char >= 0x11C70 && char <= 0x11CBF, + // 'Masaram Gondi': (char) => char >= 0x11D00 && char <= 0x11D5F, + // 'Gunjala Gondi': (char) => char >= 0x11D60 && char <= 0x11DAF, + // 'Makasar': (char) => char >= 0x11EE0 && char <= 0x11EFF, + // 'Kawi': (char) => char >= 0x11F00 && char <= 0x11F5F, + // 'Lisu Supplement': (char) => char >= 0x11FB0 && char <= 0x11FBF, + // 'Tamil Supplement': (char) => char >= 0x11FC0 && char <= 0x11FFF, + // 'Cuneiform': (char) => char >= 0x12000 && char <= 0x123FF, + // 'Cuneiform Numbers and Punctuation': (char) => char >= 0x12400 && char <= 0x1247F, + // 'Early Dynastic Cuneiform': (char) => char >= 0x12480 && char <= 0x1254F, + // 'Cypro-Minoan': (char) => char >= 0x12F90 && char <= 0x12FFF, + // 'Egyptian Hieroglyphs': (char) => char >= 0x13000 && char <= 0x1342F, + // 'Egyptian Hieroglyph Format Controls': (char) => char >= 0x13430 && char <= 0x1345F, + // 'Egyptian Hieroglyphs Extended-A': (char) => char >= 0x13460 && char <= 0x143FF, + // 'Anatolian Hieroglyphs': (char) => char >= 0x14400 && char <= 0x1467F, + // 'Gurung Khema': (char) => char >= 0x16100 && char <= 0x1613F, + // 'Bamum Supplement': (char) => char >= 0x16800 && char <= 0x16A3F, + // 'Mro': (char) => char >= 0x16A40 && char <= 0x16A6F, + // 'Tangsa': (char) => char >= 0x16A70 && char <= 0x16ACF, + // 'Bassa Vah': (char) => char >= 0x16AD0 && char <= 0x16AFF, + // 'Pahawh Hmong': (char) => char >= 0x16B00 && char <= 0x16B8F, + // 'Kirat Rai': (char) => char >= 0x16D40 && char <= 0x16D7F, + // 'Medefaidrin': (char) => char >= 0x16E40 && char <= 0x16E9F, + // 'Miao': (char) => char >= 0x16F00 && char <= 0x16F9F, + // 'Ideographic Symbols and Punctuation': (char) => char >= 0x16FE0 && char <= 0x16FFF, + // 'Tangut': (char) => char >= 0x17000 && char <= 0x187FF, + // 'Tangut Components': (char) => char >= 0x18800 && char <= 0x18AFF, + // 'Khitan Small Script': (char) => char >= 0x18B00 && char <= 0x18CFF, + // 'Tangut Supplement': (char) => char >= 0x18D00 && char <= 0x18D7F, + // 'Kana Extended-B': (char) => char >= 0x1AFF0 && char <= 0x1AFFF, + // 'Kana Supplement': (char) => char >= 0x1B000 && char <= 0x1B0FF, + // 'Kana Extended-A': (char) => char >= 0x1B100 && char <= 0x1B12F, + // 'Small Kana Extension': (char) => char >= 0x1B130 && char <= 0x1B16F, + // 'Nushu': (char) => char >= 0x1B170 && char <= 0x1B2FF, + // 'Duployan': (char) => char >= 0x1BC00 && char <= 0x1BC9F, + // 'Shorthand Format Controls': (char) => char >= 0x1BCA0 && char <= 0x1BCAF, + // 'Symbols for Legacy Computing Supplement': (char) => char >= 0x1CC00 && char <= 0x1CEBF, + // 'Znamenny Musical Notation': (char) => char >= 0x1CF00 && char <= 0x1CFCF, + // 'Byzantine Musical Symbols': (char) => char >= 0x1D000 && char <= 0x1D0FF, + // 'Musical Symbols': (char) => char >= 0x1D100 && char <= 0x1D1FF, + // 'Ancient Greek Musical Notation': (char) => char >= 0x1D200 && char <= 0x1D24F, + // 'Kaktovik Numerals': (char) => char >= 0x1D2C0 && char <= 0x1D2DF, + // 'Mayan Numerals': (char) => char >= 0x1D2E0 && char <= 0x1D2FF, + // 'Tai Xuan Jing Symbols': (char) => char >= 0x1D300 && char <= 0x1D35F, + // 'Counting Rod Numerals': (char) => char >= 0x1D360 && char <= 0x1D37F, + // 'Mathematical Alphanumeric Symbols': (char) => char >= 0x1D400 && char <= 0x1D7FF, + // 'Sutton SignWriting': (char) => char >= 0x1D800 && char <= 0x1DAAF, + // 'Latin Extended-G': (char) => char >= 0x1DF00 && char <= 0x1DFFF, + // 'Glagolitic Supplement': (char) => char >= 0x1E000 && char <= 0x1E02F, + // 'Cyrillic Extended-D': (char) => char >= 0x1E030 && char <= 0x1E08F, + // 'Nyiakeng Puachue Hmong': (char) => char >= 0x1E100 && char <= 0x1E14F, + // 'Toto': (char) => char >= 0x1E290 && char <= 0x1E2BF, + // 'Wancho': (char) => char >= 0x1E2C0 && char <= 0x1E2FF, + // 'Nag Mundari': (char) => char >= 0x1E4D0 && char <= 0x1E4FF, + // 'Ol Onal': (char) => char >= 0x1E5D0 && char <= 0x1E5FF, + // 'Ethiopic Extended-B': (char) => char >= 0x1E7E0 && char <= 0x1E7FF, + // 'Mende Kikakui': (char) => char >= 0x1E800 && char <= 0x1E8DF, + // 'Adlam': (char) => char >= 0x1E900 && char <= 0x1E95F, + // 'Indic Siyaq Numbers': (char) => char >= 0x1EC70 && char <= 0x1ECBF, + // 'Ottoman Siyaq Numbers': (char) => char >= 0x1ED00 && char <= 0x1ED4F, + // 'Arabic Mathematical Alphabetic Symbols': (char) => char >= 0x1EE00 && char <= 0x1EEFF, + // 'Mahjong Tiles': (char) => char >= 0x1F000 && char <= 0x1F02F, + // 'Domino Tiles': (char) => char >= 0x1F030 && char <= 0x1F09F, + // 'Playing Cards': (char) => char >= 0x1F0A0 && char <= 0x1F0FF, + // 'Enclosed Alphanumeric Supplement': (char) => char >= 0x1F100 && char <= 0x1F1FF, + // 'Enclosed Ideographic Supplement': (char) => char >= 0x1F200 && char <= 0x1F2FF, + // 'Miscellaneous Symbols and Pictographs': (char) => char >= 0x1F300 && char <= 0x1F5FF, + // 'Emoticons': (char) => char >= 0x1F600 && char <= 0x1F64F, + // 'Ornamental Dingbats': (char) => char >= 0x1F650 && char <= 0x1F67F, + // 'Transport and Map Symbols': (char) => char >= 0x1F680 && char <= 0x1F6FF, + // 'Alchemical Symbols': (char) => char >= 0x1F700 && char <= 0x1F77F, + // 'Geometric Shapes Extended': (char) => char >= 0x1F780 && char <= 0x1F7FF, + // 'Supplemental Arrows-C': (char) => char >= 0x1F800 && char <= 0x1F8FF, + // 'Supplemental Symbols and Pictographs': (char) => char >= 0x1F900 && char <= 0x1F9FF, + // 'Chess Symbols': (char) => char >= 0x1FA00 && char <= 0x1FA6F, + // 'Symbols and Pictographs Extended-A': (char) => char >= 0x1FA70 && char <= 0x1FAFF, + // 'Symbols for Legacy Computing': (char) => char >= 0x1FB00 && char <= 0x1FBFF, + // 'CJK Unified Ideographs Extension B': (char) => char >= 0x20000 && char <= 0x2A6DF, + // 'CJK Unified Ideographs Extension C': (char) => char >= 0x2A700 && char <= 0x2B73F, + // 'CJK Unified Ideographs Extension D': (char) => char >= 0x2B740 && char <= 0x2B81F, + // 'CJK Unified Ideographs Extension E': (char) => char >= 0x2B820 && char <= 0x2CEAF, + // 'CJK Unified Ideographs Extension F': (char) => char >= 0x2CEB0 && char <= 0x2EBEF, + // 'CJK Unified Ideographs Extension I': (char) => char >= 0x2EBF0 && char <= 0x2EE5F, + // 'CJK Unified Ideographs Extension G': (char) => char >= 0x30000 && char <= 0x3134F, + // 'CJK Unified Ideographs Extension H': (char) => char >= 0x31350 && char <= 0x323AF, + // 'CJK Compatibility Ideographs Supplement': (char) => char >= 0x2F800 && char <= 0x2FA1F, + // 'Tags': (char) => char >= 0xE0000 && char <= 0xE007F, + // 'Variation Selectors Supplement': (char) => char >= 0xE0100 && char <= 0xE01EF, + // 'Supplementary Private Use Area-A': (char) => char >= 0xF0000 && char <= 0xFFFFF, + // 'Supplementary Private Use Area-B': (char) => char >= 0x100000 && char <= 0x10FFFF, +}; + +/* eslint-disable new-cap */ +function allowsVerticalWritingMode(chars) { + for (const char of chars) { + if (charHasUprightVerticalOrientation(char.charCodeAt(0))) + return true; + } + return false; +} +function allowsLetterSpacing(chars) { + for (const char of chars) { + if (!charAllowsLetterSpacing(char.charCodeAt(0))) + return false; + } + return true; +} +/** + * Returns a regular expression matching the given script codes, excluding any + * code that the execution environment lacks support for in regular expressions. + */ +function sanitizedRegExpFromScriptCodes(scriptCodes) { + const supportedPropertyEscapes = scriptCodes.map(code => { + try { + return new RegExp(`\\p{sc=${code}}`, 'u').source; + } + catch (e) { + return null; + } + }).filter(pe => pe); + return new RegExp(supportedPropertyEscapes.join('|'), 'u'); +} +/** + * ISO 15924 script codes of scripts that disallow letter spacing as of Unicode + * 16.0.0. + * + * In general, cursive scripts are incompatible with letter spacing. + */ +const cursiveScriptCodes = [ + 'Arab', // Arabic + 'Dupl', // Duployan + 'Mong', // Mongolian + 'Ougr', // Old Uyghur + 'Syrc', // Syriac +]; +const cursiveScriptRegExp = sanitizedRegExpFromScriptCodes(cursiveScriptCodes); +function charAllowsLetterSpacing(char) { + return !cursiveScriptRegExp.test(String.fromCodePoint(char)); +} +/** + * ISO 15924 script codes of scripts that allow ideographic line breaking beyond + * the CJKV scripts that are considered ideographic in Unicode 16.0.0. + */ +const ideographicBreakingScriptCodes = [ + 'Bopo', // Bopomofo + 'Hani', // Han + 'Hira', // Hiragana + 'Kana', // Katakana + 'Kits', // Khitan Small Script + 'Nshu', // Nushu + 'Tang', // Tangut + 'Yiii', // Yi +]; +const ideographicBreakingRegExp = sanitizedRegExpFromScriptCodes(ideographicBreakingScriptCodes); +function charAllowsIdeographicBreaking(char) { + // Return early for characters outside all ideographic ranges. + if (char < 0x2E80) + return false; + if (unicodeBlockLookup['CJK Compatibility Forms'](char)) + return true; + if (unicodeBlockLookup['CJK Compatibility'](char)) + return true; + if (unicodeBlockLookup['CJK Strokes'](char)) + return true; + if (unicodeBlockLookup['CJK Symbols and Punctuation'](char)) + return true; + if (unicodeBlockLookup['Enclosed CJK Letters and Months'](char)) + return true; + if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) + return true; + if (unicodeBlockLookup['Ideographic Description Characters'](char)) + return true; + if (unicodeBlockLookup['Vertical Forms'](char)) + return true; + return ideographicBreakingRegExp.test(String.fromCodePoint(char)); +} +// The following logic comes from +// . +// Keep it synchronized with +// . +// The data file denotes with “U” or “Tu” any codepoint that may be drawn +// upright in vertical text but does not distinguish between upright and +// “neutral” characters. +// Blocks in the Unicode supplementary planes are excluded from this module due +// to . +/** + * Returns true if the given Unicode codepoint identifies a character with + * upright orientation. + * + * A character has upright orientation if it is drawn upright (unrotated) + * whether the line is oriented horizontally or vertically, even if both + * adjacent characters can be rotated. For example, a Chinese character is + * always drawn upright. An uprightly oriented character causes an adjacent + * “neutral” character to be drawn upright as well. + */ +function charHasUprightVerticalOrientation(char) { + if (char === 0x02EA /* modifier letter yin departing tone mark */ || + char === 0x02EB /* modifier letter yang departing tone mark */) { + return true; + } + // Return early for characters outside all ranges whose characters remain + // upright in vertical writing mode. + if (char < 0x1100) + return false; + if (unicodeBlockLookup['CJK Compatibility Forms'](char)) { + if (!((char >= 0xFE49 /* dashed overline */ && char <= 0xFE4F) /* wavy low line */)) { + return true; + } + } + if (unicodeBlockLookup['CJK Compatibility'](char)) + return true; + if (unicodeBlockLookup['CJK Strokes'](char)) + return true; + if (unicodeBlockLookup['CJK Symbols and Punctuation'](char)) { + if (!((char >= 0x3008 /* left angle bracket */ && char <= 0x3011) /* right black lenticular bracket */) && + !((char >= 0x3014 /* left tortoise shell bracket */ && char <= 0x301F) /* low double prime quotation mark */) && + char !== 0x3030 /* wavy dash */) { + return true; + } + } + if (unicodeBlockLookup['Enclosed CJK Letters and Months'](char)) + return true; + if (unicodeBlockLookup['Ideographic Description Characters'](char)) + return true; + if (unicodeBlockLookup['Kanbun'](char)) + return true; + if (unicodeBlockLookup['Katakana'](char)) { + if (char !== 0x30FC /* katakana-hiragana prolonged sound mark */) { + return true; + } + } + if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) { + if (char !== 0xFF08 /* fullwidth left parenthesis */ && + char !== 0xFF09 /* fullwidth right parenthesis */ && + char !== 0xFF0D /* fullwidth hyphen-minus */ && + !((char >= 0xFF1A /* fullwidth colon */ && char <= 0xFF1E) /* fullwidth greater-than sign */) && + char !== 0xFF3B /* fullwidth left square bracket */ && + char !== 0xFF3D /* fullwidth right square bracket */ && + char !== 0xFF3F /* fullwidth low line */ && + !(char >= 0xFF5B /* fullwidth left curly bracket */ && char <= 0xFFDF) && + char !== 0xFFE3 /* fullwidth macron */ && + !(char >= 0xFFE8 /* halfwidth forms light vertical */ && char <= 0xFFEF)) { + return true; + } + } + if (unicodeBlockLookup['Small Form Variants'](char)) { + if (!((char >= 0xFE58 /* small em dash */ && char <= 0xFE5E) /* small right tortoise shell bracket */) && + !((char >= 0xFE63 /* small hyphen-minus */ && char <= 0xFE66) /* small equals sign */)) { + return true; + } + } + if (unicodeBlockLookup['Vertical Forms'](char)) + return true; + if (unicodeBlockLookup['Yijing Hexagram Symbols'](char)) + return true; + if ( /* Canadian Aboriginal *//\p{sc=Cans}/u.test(String.fromCodePoint(char))) + return true; + if ( /* Hangul *//\p{sc=Hang}/u.test(String.fromCodePoint(char))) + return true; + if (ideographicBreakingRegExp.test(String.fromCodePoint(char))) + return true; + return false; +} +/** + * Returns true if the given Unicode codepoint identifies a character with + * neutral orientation. + * + * A character has neutral orientation if it may be drawn rotated or unrotated + * when the line is oriented vertically, depending on the orientation of the + * adjacent characters. For example, along a vertically oriented line, the vulgar + * fraction ½ is drawn upright among Chinese characters but rotated among Latin + * letters. A neutrally oriented character does not influence whether an + * adjacent character is drawn upright or rotated. + */ +function charHasNeutralVerticalOrientation(char) { + if (unicodeBlockLookup['Latin-1 Supplement'](char)) { + if (char === 0x00A7 /* section sign */ || + char === 0x00A9 /* copyright sign */ || + char === 0x00AE /* registered sign */ || + char === 0x00B1 /* plus-minus sign */ || + char === 0x00BC /* vulgar fraction one quarter */ || + char === 0x00BD /* vulgar fraction one half */ || + char === 0x00BE /* vulgar fraction three quarters */ || + char === 0x00D7 /* multiplication sign */ || + char === 0x00F7 /* division sign */) { + return true; + } + } + if (unicodeBlockLookup['General Punctuation'](char)) { + if (char === 0x2016 /* double vertical line */ || + char === 0x2020 /* dagger */ || + char === 0x2021 /* double dagger */ || + char === 0x2030 /* per mille sign */ || + char === 0x2031 /* per ten thousand sign */ || + char === 0x203B /* reference mark */ || + char === 0x203C /* double exclamation mark */ || + char === 0x2042 /* asterism */ || + char === 0x2047 /* double question mark */ || + char === 0x2048 /* question exclamation mark */ || + char === 0x2049 /* exclamation question mark */ || + char === 0x2051 /* two asterisks aligned vertically */) { + return true; + } + } + if (unicodeBlockLookup['Letterlike Symbols'](char)) + return true; + if (unicodeBlockLookup['Number Forms'](char)) + return true; + if (unicodeBlockLookup['Miscellaneous Technical'](char)) { + if ((char >= 0x2300 /* diameter sign */ && char <= 0x2307 /* wavy line */) || + (char >= 0x230C /* bottom right crop */ && char <= 0x231F /* bottom right corner */) || + (char >= 0x2324 /* up arrowhead between two horizontal bars */ && char <= 0x2328 /* keyboard */) || + char === 0x232B /* erase to the left */ || + (char >= 0x237D /* shouldered open box */ && char <= 0x239A /* clear screen symbol */) || + (char >= 0x23BE /* dentistry symbol light vertical and top right */ && char <= 0x23CD /* square foot */) || + char === 0x23CF /* eject symbol */ || + (char >= 0x23D1 /* metrical breve */ && char <= 0x23DB /* fuse */) || + (char >= 0x23E2 /* white trapezium */ && char <= 0x23FF)) { + return true; + } + } + if (unicodeBlockLookup['Control Pictures'](char) && char !== 0x2423 /* open box */) + return true; + if (unicodeBlockLookup['Optical Character Recognition'](char)) + return true; + if (unicodeBlockLookup['Enclosed Alphanumerics'](char)) + return true; + if (unicodeBlockLookup['Geometric Shapes'](char)) + return true; + if (unicodeBlockLookup['Miscellaneous Symbols'](char)) { + if (!((char >= 0x261A /* black left pointing index */ && char <= 0x261F) /* white down pointing index */)) { + return true; + } + } + if (unicodeBlockLookup['Miscellaneous Symbols and Arrows'](char)) { + if ((char >= 0x2B12 /* square with top half black */ && char <= 0x2B2F /* white vertical ellipse */) || + (char >= 0x2B50 /* white medium star */ && char <= 0x2B59 /* heavy circled saltire */) || + (char >= 0x2BB8 /* upwards white arrow from bar with horizontal bar */ && char <= 0x2BEB)) { + return true; + } + } + if (unicodeBlockLookup['CJK Symbols and Punctuation'](char)) + return true; + if (unicodeBlockLookup['Katakana'](char)) + return true; + if (unicodeBlockLookup['Private Use Area'](char)) + return true; + if (unicodeBlockLookup['CJK Compatibility Forms'](char)) + return true; + if (unicodeBlockLookup['Small Form Variants'](char)) + return true; + if (unicodeBlockLookup['Halfwidth and Fullwidth Forms'](char)) + return true; + if (char === 0x221E /* infinity */ || + char === 0x2234 /* therefore */ || + char === 0x2235 /* because */ || + (char >= 0x2700 /* black safety scissors */ && char <= 0x2767 /* rotated floral heart bullet */) || + (char >= 0x2776 /* dingbat negative circled digit one */ && char <= 0x2793 /* dingbat negative circled sans-serif number ten */) || + char === 0xFFFC /* object replacement character */ || + char === 0xFFFD /* replacement character */) { + return true; + } + return false; +} +/** + * Returns true if the given Unicode codepoint identifies a character with + * rotated orientation. + * + * A character has rotated orientation if it is drawn rotated when the line is + * oriented vertically, even if both adjacent characters are upright. For + * example, a Latin letter is drawn rotated along a vertical line. A rotated + * character causes an adjacent “neutral” character to be drawn rotated as well. + */ +function charHasRotatedVerticalOrientation(char) { + return !(charHasUprightVerticalOrientation(char) || + charHasNeutralVerticalOrientation(char)); +} +function charInComplexShapingScript(char) { + return /\p{sc=Arab}/u.test(String.fromCodePoint(char)); +} +/** + * ISO 15924 script codes of scripts that are primarily written horizontally + * right-to-left according to Unicode 16.0.0. + */ +const rtlScriptCodes = [ + 'Adlm', // Adlam + 'Arab', // Arabic + 'Armi', // Imperial Aramaic + 'Avst', // Avestan + 'Chrs', // Chorasmian + 'Cprt', // Cypriot + 'Egyp', // Egyptian Hieroglyphs + 'Elym', // Elymaic + 'Gara', // Garay + 'Hatr', // Hatran + 'Hebr', // Hebrew + 'Hung', // Old Hungarian + 'Khar', // Kharoshthi + 'Lydi', // Lydian + 'Mand', // Mandaic + 'Mani', // Manichaean + 'Mend', // Mende Kikakui + 'Merc', // Meroitic Cursive + 'Mero', // Meroitic Hieroglyphs + 'Narb', // Old North Arabian + 'Nbat', // Nabataean + 'Nkoo', // NKo + 'Orkh', // Old Turkic + 'Palm', // Palmyrene + 'Phli', // Inscriptional Pahlavi + 'Phlp', // Psalter Pahlavi + 'Phnx', // Phoenician + 'Prti', // Inscriptional Parthian + 'Rohg', // Hanifi Rohingya + 'Samr', // Samaritan + 'Sarb', // Old South Arabian + 'Sogo', // Old Sogdian + 'Syrc', // Syriac + 'Thaa', // Thaana + 'Todr', // Todhri + 'Yezi', // Yezidi +]; +const rtlScriptRegExp = sanitizedRegExpFromScriptCodes(rtlScriptCodes); +function charInRTLScript(char) { + return rtlScriptRegExp.test(String.fromCodePoint(char)); +} +function charInSupportedScript(char, canRenderRTL) { + // This is a rough heuristic: whether we "can render" a script + // actually depends on the properties of the font being used + // and whether differences from the ideal rendering are considered + // semantically significant. + // Even in Latin script, we "can't render" combinations such as the fi + // ligature, but we don't consider that semantically significant. + if (!canRenderRTL && charInRTLScript(char)) { + return false; + } + if ((char >= 0x0900 && char <= 0x0DFF) || + // Main blocks for Indic scripts and Sinhala + (char >= 0x0F00 && char <= 0x109F) || + // Main blocks for Tibetan and Myanmar + unicodeBlockLookup['Khmer'](char)) { + // These blocks cover common scripts that require + // complex text shaping, based on unicode script metadata: + // https://www.unicode.org/repos/cldr/trunk/common/properties/scriptMetadata.txt + // where "Web Rank <= 32" "Shaping Required = YES" + return false; + } + return true; +} +function stringContainsRTLText(chars) { + for (const char of chars) { + if (charInRTLScript(char.charCodeAt(0))) { + return true; + } + } + return false; +} +function isStringInSupportedScript(chars, canRenderRTL) { + for (const char of chars) { + if (!charInSupportedScript(char.charCodeAt(0), canRenderRTL)) { + return false; + } + } + return true; +} + +class RTLWorkerPlugin { + constructor() { + this.applyArabicShaping = null; + this.processBidirectionalText = null; + this.processStyledBidirectionalText = null; + this.pluginStatus = 'unavailable'; + this.pluginURL = null; + } + setState(state) { + this.pluginStatus = state.pluginStatus; + this.pluginURL = state.pluginURL; + } + getState() { + return { + pluginStatus: this.pluginStatus, + pluginURL: this.pluginURL + }; + } + setMethods(rtlTextPlugin) { + this.applyArabicShaping = rtlTextPlugin.applyArabicShaping; + this.processBidirectionalText = rtlTextPlugin.processBidirectionalText; + this.processStyledBidirectionalText = rtlTextPlugin.processStyledBidirectionalText; + } + isParsed() { + return this.applyArabicShaping != null && + this.processBidirectionalText != null && + this.processStyledBidirectionalText != null; + } + getPluginURL() { + return this.pluginURL; + } + getRTLTextPluginStatus() { + return this.pluginStatus; + } +} +const rtlWorkerPlugin = new RTLWorkerPlugin(); + +/** + * @internal + * A parameter that can be evaluated to a value + */ +class EvaluationParameters { + // "options" may also be another EvaluationParameters to copy, see CrossFadedProperty.possiblyEvaluate + constructor(zoom, options) { + this.zoom = zoom; + if (options) { + this.now = options.now; + this.fadeDuration = options.fadeDuration; + this.zoomHistory = options.zoomHistory; + this.transition = options.transition; + } + else { + this.now = 0; + this.fadeDuration = 0; + this.zoomHistory = new ZoomHistory(); + this.transition = {}; + } + } + isSupportedScript(str) { + return isStringInSupportedScript(str, rtlWorkerPlugin.getRTLTextPluginStatus() === 'loaded'); + } + crossFadingFactor() { + if (this.fadeDuration === 0) { + return 1; + } + else { + return Math.min((this.now - this.zoomHistory.lastIntegerZoomTime) / this.fadeDuration, 1); + } + } + getCrossfadeParameters() { + const z = this.zoom; + const fraction = z - Math.floor(z); + const t = this.crossFadingFactor(); + return z > this.zoomHistory.lastIntegerZoom ? + { fromScale: 2, toScale: 1, t: fraction + (1 - fraction) * t } : + { fromScale: 0.5, toScale: 1, t: 1 - (1 - t) * fraction }; + } +} + +/** + * @internal + * `PropertyValue` represents the value part of a property key-value unit. It's used to represent both + * paint and layout property values, and regardless of whether or not their property supports data-driven + * expressions. + * + * `PropertyValue` stores the raw input value as seen in a style or a runtime styling API call, i.e. one of the + * following: + * + * * A constant value of the type appropriate for the property + * * A function which produces a value of that type (but functions are quasi-deprecated in favor of expressions) + * * An expression which produces a value of that type + * * "undefined"/"not present", in which case the property is assumed to take on its default value. + * + * In addition to storing the original input value, `PropertyValue` also stores a normalized representation, + * effectively treating functions as if they are expressions, and constant or default values as if they are + * (constant) expressions. + */ +class PropertyValue { + constructor(property, value) { + this.property = property; + this.value = value; + this.expression = normalizePropertyExpression(value === undefined ? property.specification.default : value, property.specification); + } + isDataDriven() { + return this.expression.kind === 'source' || this.expression.kind === 'composite'; + } + possiblyEvaluate(parameters, canonical, availableImages) { + return this.property.possiblyEvaluate(this, parameters, canonical, availableImages); + } +} +/** + * @internal + * Paint properties are _transitionable_: they can change in a fluid manner, interpolating or cross-fading between + * old and new value. The duration of the transition, and the delay before it begins, is configurable. + * + * `TransitionablePropertyValue` is a compositional class that stores both the property value and that transition + * configuration. + * + * A `TransitionablePropertyValue` can calculate the next step in the evaluation chain for paint property values: + * `TransitioningPropertyValue`. + */ +class TransitionablePropertyValue { + constructor(property) { + this.property = property; + this.value = new PropertyValue(property, undefined); + } + transitioned(parameters, prior) { + return new TransitioningPropertyValue(this.property, this.value, prior, extend({}, parameters.transition, this.transition), parameters.now); + } + untransitioned() { + return new TransitioningPropertyValue(this.property, this.value, null, {}, 0); + } +} +/** + * @internal + * `Transitionable` stores a map of all (property name, `TransitionablePropertyValue`) pairs for paint properties of a + * given layer type. It can calculate the `TransitioningPropertyValue`s for all of them at once, producing a + * `Transitioning` instance for the same set of properties. + */ +class Transitionable { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultTransitionablePropertyValues); + } + getValue(name) { + return clone$1(this._values[name].value.value); + } + setValue(name, value) { + if (!Object.prototype.hasOwnProperty.call(this._values, name)) { + this._values[name] = new TransitionablePropertyValue(this._values[name].property); + } + // Note that we do not _remove_ an own property in the case where a value is being reset + // to the default: the transition might still be non-default. + this._values[name].value = new PropertyValue(this._values[name].property, value === null ? undefined : clone$1(value)); + } + getTransition(name) { + return clone$1(this._values[name].transition); + } + setTransition(name, value) { + if (!Object.prototype.hasOwnProperty.call(this._values, name)) { + this._values[name] = new TransitionablePropertyValue(this._values[name].property); + } + this._values[name].transition = clone$1(value) || undefined; + } + serialize() { + const result = {}; + for (const property of Object.keys(this._values)) { + const value = this.getValue(property); + if (value !== undefined) { + result[property] = value; + } + const transition = this.getTransition(property); + if (transition !== undefined) { + result[`${property}-transition`] = transition; + } + } + return result; + } + transitioned(parameters, prior) { + const result = new Transitioning(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].transitioned(parameters, prior._values[property]); + } + return result; + } + untransitioned() { + const result = new Transitioning(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].untransitioned(); + } + return result; + } +} +/** + * @internal + * `TransitioningPropertyValue` implements the first of two intermediate steps in the evaluation chain of a paint + * property value. In this step, transitions between old and new values are handled: as long as the transition is in + * progress, `TransitioningPropertyValue` maintains a reference to the prior value, and interpolates between it and + * the new value based on the current time and the configured transition duration and delay. The product is the next + * step in the evaluation chain: the "possibly evaluated" result type `R`. See below for more on this concept. + */ +class TransitioningPropertyValue { + constructor(property, value, prior, transition, now) { + this.property = property; + this.value = value; + this.begin = now + transition.delay || 0; + this.end = this.begin + transition.duration || 0; + if (property.specification.transition && (transition.delay || transition.duration)) { + this.prior = prior; + } + } + possiblyEvaluate(parameters, canonical, availableImages) { + const now = parameters.now || 0; + const finalValue = this.value.possiblyEvaluate(parameters, canonical, availableImages); + const prior = this.prior; + if (!prior) { + // No prior value. + return finalValue; + } + else if (now > this.end) { + // Transition from prior value is now complete. + this.prior = null; + return finalValue; + } + else if (this.value.isDataDriven()) { + // Transitions to data-driven properties are not supported. + // We snap immediately to the data-driven value so that, when we perform layout, + // we see the data-driven function and can use it to populate vertex buffers. + this.prior = null; + return finalValue; + } + else if (now < this.begin) { + // Transition hasn't started yet. + return prior.possiblyEvaluate(parameters, canonical, availableImages); + } + else { + // Interpolate between recursively-calculated prior value and final. + const t = (now - this.begin) / (this.end - this.begin); + return this.property.interpolate(prior.possiblyEvaluate(parameters, canonical, availableImages), finalValue, easeCubicInOut(t)); + } + } +} +/** + * @internal + * `Transitioning` stores a map of all (property name, `TransitioningPropertyValue`) pairs for paint properties of a + * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a + * `PossiblyEvaluated` instance for the same set of properties. + */ +class Transitioning { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultTransitioningPropertyValues); + } + possiblyEvaluate(parameters, canonical, availableImages) { + const result = new PossiblyEvaluated(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages); + } + return result; + } + hasTransition() { + for (const property of Object.keys(this._values)) { + if (this._values[property].prior) { + return true; + } + } + return false; + } +} +// ------- Layout ------- +/** + * Because layout properties are not transitionable, they have a simpler representation and evaluation chain than + * paint properties: `PropertyValue`s are possibly evaluated, producing possibly evaluated values, which are then + * fully evaluated. + * + * `Layout` stores a map of all (property name, `PropertyValue`) pairs for layout properties of a + * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a + * `PossiblyEvaluated` instance for the same set of properties. + */ +class Layout { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultPropertyValues); + } + hasValue(name) { + return this._values[name].value !== undefined; + } + getValue(name) { + return clone$1(this._values[name].value); + } + setValue(name, value) { + this._values[name] = new PropertyValue(this._values[name].property, value === null ? undefined : clone$1(value)); + } + serialize() { + const result = {}; + for (const property of Object.keys(this._values)) { + const value = this.getValue(property); + if (value !== undefined) { + result[property] = value; + } + } + return result; + } + possiblyEvaluate(parameters, canonical, availableImages) { + const result = new PossiblyEvaluated(this._properties); + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages); + } + return result; + } +} +/** + * @internal + * `PossiblyEvaluatedPropertyValue` is used for data-driven paint and layout property values. It holds a + * `PossiblyEvaluatedValue` and the `GlobalProperties` that were used to generate it. You're not allowed to supply + * a different set of `GlobalProperties` when performing the final evaluation because they would be ignored in the + * case where the input value was a constant or camera function. + */ +class PossiblyEvaluatedPropertyValue { + constructor(property, value, parameters) { + this.property = property; + this.value = value; + this.parameters = parameters; + } + isConstant() { + return this.value.kind === 'constant'; + } + constantOr(value) { + if (this.value.kind === 'constant') { + return this.value.value; + } + else { + return value; + } + } + evaluate(feature, featureState, canonical, availableImages) { + return this.property.evaluate(this.value, this.parameters, feature, featureState, canonical, availableImages); + } +} +/** + * @internal + * `PossiblyEvaluated` stores a map of all (property name, `R`) pairs for paint or layout properties of a + * given layer type. + */ +class PossiblyEvaluated { + constructor(properties) { + this._properties = properties; + this._values = Object.create(properties.defaultPossiblyEvaluatedValues); + } + get(name) { + return this._values[name]; + } +} +/** + * @internal + * An implementation of `Property` for properties that do not permit data-driven (source or composite) expressions. + * This restriction allows us to declare statically that the result of possibly evaluating this kind of property + * is in fact always the scalar type `T`, and can be used without further evaluating the value on a per-feature basis. + */ +class DataConstantProperty { + constructor(specification) { + this.specification = specification; + } + possiblyEvaluate(value, parameters) { + if (value.isDataDriven()) + throw new Error('Value should not be data driven'); + return value.expression.evaluate(parameters); + } + interpolate(a, b, t) { + const interpolationType = this.specification.type; + const interpolationFn = interpolate[interpolationType]; + if (interpolationFn) { + return interpolationFn(a, b, t); + } + else { + return a; + } + } +} +/** + * @internal + * An implementation of `Property` for properties that permit data-driven (source or composite) expressions. + * The result of possibly evaluating this kind of property is `PossiblyEvaluatedPropertyValue`; obtaining + * a scalar value `T` requires further evaluation on a per-feature basis. + */ +class DataDrivenProperty { + constructor(specification, overrides) { + this.specification = specification; + this.overrides = overrides; + } + possiblyEvaluate(value, parameters, canonical, availableImages) { + if (value.expression.kind === 'constant' || value.expression.kind === 'camera') { + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: value.expression.evaluate(parameters, null, {}, canonical, availableImages) }, parameters); + } + else { + return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters); + } + } + interpolate(a, b, t) { + // If either possibly-evaluated value is non-constant, give up: we aren't able to interpolate data-driven values. + if (a.value.kind !== 'constant' || b.value.kind !== 'constant') { + return a; + } + // Special case hack solely for fill-outline-color. The undefined value is subsequently handled in + // FillStyleLayer#recalculate, which sets fill-outline-color to the fill-color value if the former + // is a PossiblyEvaluatedPropertyValue containing a constant undefined value. In addition to the + // return value here, the other source of a PossiblyEvaluatedPropertyValue containing a constant + // undefined value is the "default value" for fill-outline-color held in + // `Properties#defaultPossiblyEvaluatedValues`, which serves as the prototype of + // `PossiblyEvaluated#_values`. + if (a.value.value === undefined || b.value.value === undefined) { + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: undefined }, a.parameters); + } + const interpolationType = this.specification.type; + const interpolationFn = interpolate[interpolationType]; + if (interpolationFn) { + const interpolatedValue = interpolationFn(a.value.value, b.value.value, t); + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: interpolatedValue }, a.parameters); + } + else { + return a; + } + } + evaluate(value, parameters, feature, featureState, canonical, availableImages) { + if (value.kind === 'constant') { + return value.value; + } + else { + return value.evaluate(parameters, feature, featureState, canonical, availableImages); + } + } +} +/** + * @internal + * An implementation of `Property` for data driven `line-pattern` which are transitioned by cross-fading + * rather than interpolation. + */ +class CrossFadedDataDrivenProperty extends DataDrivenProperty { + possiblyEvaluate(value, parameters, canonical, availableImages) { + if (value.value === undefined) { + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: undefined }, parameters); + } + else if (value.expression.kind === 'constant') { + const evaluatedValue = value.expression.evaluate(parameters, null, {}, canonical, availableImages); + const isImageExpression = value.property.specification.type === 'resolvedImage'; + const constantValue = isImageExpression && typeof evaluatedValue !== 'string' ? evaluatedValue.name : evaluatedValue; + const constant = this._calculate(constantValue, constantValue, constantValue, parameters); + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: constant }, parameters); + } + else if (value.expression.kind === 'camera') { + const cameraVal = this._calculate(value.expression.evaluate({ zoom: parameters.zoom - 1.0 }), value.expression.evaluate({ zoom: parameters.zoom }), value.expression.evaluate({ zoom: parameters.zoom + 1.0 }), parameters); + return new PossiblyEvaluatedPropertyValue(this, { kind: 'constant', value: cameraVal }, parameters); + } + else { + // source or composite expression + return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters); + } + } + evaluate(value, globals, feature, featureState, canonical, availableImages) { + if (value.kind === 'source') { + const constant = value.evaluate(globals, feature, featureState, canonical, availableImages); + return this._calculate(constant, constant, constant, globals); + } + else if (value.kind === 'composite') { + return this._calculate(value.evaluate({ zoom: Math.floor(globals.zoom) - 1.0 }, feature, featureState), value.evaluate({ zoom: Math.floor(globals.zoom) }, feature, featureState), value.evaluate({ zoom: Math.floor(globals.zoom) + 1.0 }, feature, featureState), globals); + } + else { + return value.value; + } + } + _calculate(min, mid, max, parameters) { + const z = parameters.zoom; + return z > parameters.zoomHistory.lastIntegerZoom ? { from: min, to: mid } : { from: max, to: mid }; + } + interpolate(a) { + return a; + } +} +/** + * @internal + * An implementation of `Property` for `*-pattern` and `line-dasharray`, which are transitioned by cross-fading + * rather than interpolation. + */ +class CrossFadedProperty { + constructor(specification) { + this.specification = specification; + } + possiblyEvaluate(value, parameters, canonical, availableImages) { + if (value.value === undefined) { + return undefined; + } + else if (value.expression.kind === 'constant') { + const constant = value.expression.evaluate(parameters, null, {}, canonical, availableImages); + return this._calculate(constant, constant, constant, parameters); + } + else { + return this._calculate(value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom - 1.0), parameters)), value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom), parameters)), value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom + 1.0), parameters)), parameters); + } + } + _calculate(min, mid, max, parameters) { + const z = parameters.zoom; + return z > parameters.zoomHistory.lastIntegerZoom ? { from: min, to: mid } : { from: max, to: mid }; + } + interpolate(a) { + return a; + } +} +/** + * @internal + * An implementation of `Property` for `heatmap-color` and `line-gradient`. Interpolation is a no-op, and + * evaluation returns a boolean value in order to indicate its presence, but the real + * evaluation happens in StyleLayer classes. + */ +class ColorRampProperty { + constructor(specification) { + this.specification = specification; + } + possiblyEvaluate(value, parameters, canonical, availableImages) { + return !!value.expression.evaluate(parameters, null, {}, canonical, availableImages); + } + interpolate() { return false; } +} +/** + * @internal + * `Properties` holds objects containing default values for the layout or paint property set of a given + * layer type. These objects are immutable, and they are used as the prototypes for the `_values` members of + * `Transitionable`, `Transitioning`, `Layout`, and `PossiblyEvaluated`. This allows these classes to avoid + * doing work in the common case where a property has no explicit value set and should be considered to take + * on the default value: using `for (const property of Object.keys(this._values))`, they can iterate over + * only the _own_ properties of `_values`, skipping repeated calculation of transitions and possible/final + * evaluations for defaults, the result of which will always be the same. + */ +class Properties { + constructor(properties) { + this.properties = properties; + this.defaultPropertyValues = {}; + this.defaultTransitionablePropertyValues = {}; + this.defaultTransitioningPropertyValues = {}; + this.defaultPossiblyEvaluatedValues = {}; + this.overridableProperties = []; + for (const property in properties) { + const prop = properties[property]; + if (prop.specification.overridable) { + this.overridableProperties.push(property); + } + const defaultPropertyValue = this.defaultPropertyValues[property] = + new PropertyValue(prop, undefined); + const defaultTransitionablePropertyValue = this.defaultTransitionablePropertyValues[property] = + new TransitionablePropertyValue(prop); + this.defaultTransitioningPropertyValues[property] = + defaultTransitionablePropertyValue.untransitioned(); + this.defaultPossiblyEvaluatedValues[property] = + defaultPropertyValue.possiblyEvaluate({}); + } + } +} +register('DataDrivenProperty', DataDrivenProperty); +register('DataConstantProperty', DataConstantProperty); +register('CrossFadedDataDrivenProperty', CrossFadedDataDrivenProperty); +register('CrossFadedProperty', CrossFadedProperty); +register('ColorRampProperty', ColorRampProperty); + +const TRANSITION_SUFFIX = '-transition'; +/** + * A base class for style layers + */ +class StyleLayer extends Evented { + constructor(layer, properties) { + super(); + this.id = layer.id; + this.type = layer.type; + this._featureFilter = { filter: () => true, needGeometry: false }; + if (layer.type === 'custom') + return; + layer = layer; + this.metadata = layer.metadata; + this.minzoom = layer.minzoom; + this.maxzoom = layer.maxzoom; + if (layer.type !== 'background') { + this.source = layer.source; + this.sourceLayer = layer['source-layer']; + this.filter = layer.filter; + } + if (properties.layout) { + this._unevaluatedLayout = new Layout(properties.layout); + } + if (properties.paint) { + this._transitionablePaint = new Transitionable(properties.paint); + for (const property in layer.paint) { + this.setPaintProperty(property, layer.paint[property], { validate: false }); + } + for (const property in layer.layout) { + this.setLayoutProperty(property, layer.layout[property], { validate: false }); + } + this._transitioningPaint = this._transitionablePaint.untransitioned(); + //$FlowFixMe + this.paint = new PossiblyEvaluated(properties.paint); + } + } + getCrossfadeParameters() { + return this._crossfadeParameters; + } + getLayoutProperty(name) { + if (name === 'visibility') { + return this.visibility; + } + return this._unevaluatedLayout.getValue(name); + } + setLayoutProperty(name, value, options = {}) { + if (value !== null && value !== undefined) { + const key = `layers.${this.id}.layout.${name}`; + if (this._validate(validateLayoutProperty, key, name, value, options)) { + return; + } + } + if (name === 'visibility') { + this.visibility = value; + return; + } + this._unevaluatedLayout.setValue(name, value); + } + getPaintProperty(name) { + if (name.endsWith(TRANSITION_SUFFIX)) { + return this._transitionablePaint.getTransition(name.slice(0, -TRANSITION_SUFFIX.length)); + } + else { + return this._transitionablePaint.getValue(name); + } + } + setPaintProperty(name, value, options = {}) { + if (value !== null && value !== undefined) { + const key = `layers.${this.id}.paint.${name}`; + if (this._validate(validatePaintProperty, key, name, value, options)) { + return false; + } + } + if (name.endsWith(TRANSITION_SUFFIX)) { + this._transitionablePaint.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), value || undefined); + return false; + } + else { + const transitionable = this._transitionablePaint._values[name]; + const isCrossFadedProperty = transitionable.property.specification['property-type'] === 'cross-faded-data-driven'; + const wasDataDriven = transitionable.value.isDataDriven(); + const oldValue = transitionable.value; + this._transitionablePaint.setValue(name, value); + this._handleSpecialPaintPropertyUpdate(name); + const newValue = this._transitionablePaint._values[name].value; + const isDataDriven = newValue.isDataDriven(); + // if a cross-faded value is changed, we need to make sure the new icons get added to each tile's iconAtlas + // so a call to _updateLayer is necessary, and we return true from this function so it gets called in + // Style#setPaintProperty + return isDataDriven || wasDataDriven || isCrossFadedProperty || this._handleOverridablePaintPropertyUpdate(name, oldValue, newValue); + } + } + _handleSpecialPaintPropertyUpdate(_) { + // No-op; can be overridden by derived classes. + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) { + // No-op; can be overridden by derived classes. + return false; + } + isHidden(zoom) { + if (this.minzoom && zoom < this.minzoom) + return true; + if (this.maxzoom && zoom >= this.maxzoom) + return true; + return this.visibility === 'none'; + } + updateTransitions(parameters) { + this._transitioningPaint = this._transitionablePaint.transitioned(parameters, this._transitioningPaint); + } + hasTransition() { + return this._transitioningPaint.hasTransition(); + } + recalculate(parameters, availableImages) { + if (parameters.getCrossfadeParameters) { + this._crossfadeParameters = parameters.getCrossfadeParameters(); + } + if (this._unevaluatedLayout) { + this.layout = this._unevaluatedLayout.possiblyEvaluate(parameters, undefined, availableImages); + } + this.paint = this._transitioningPaint.possiblyEvaluate(parameters, undefined, availableImages); + } + serialize() { + const output = { + 'id': this.id, + 'type': this.type, + 'source': this.source, + 'source-layer': this.sourceLayer, + 'metadata': this.metadata, + 'minzoom': this.minzoom, + 'maxzoom': this.maxzoom, + 'filter': this.filter, + 'layout': this._unevaluatedLayout && this._unevaluatedLayout.serialize(), + 'paint': this._transitionablePaint && this._transitionablePaint.serialize() + }; + if (this.visibility) { + output.layout = output.layout || {}; + output.layout.visibility = this.visibility; + } + return filterObject(output, (value, key) => { + return value !== undefined && + !(key === 'layout' && !Object.keys(value).length) && + !(key === 'paint' && !Object.keys(value).length); + }); + } + _validate(validate, key, name, value, options = {}) { + if (options && options.validate === false) { + return false; + } + return emitValidationErrors(this, validate.call(validateStyle, { + key, + layerType: this.type, + objectKey: name, + value, + styleSpec: v8Spec, + // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407 + style: { glyphs: true, sprite: true } + })); + } + is3D() { + return false; + } + isTileClipped() { + return false; + } + hasOffscreenPass() { + return false; + } + resize() { + // noop + } + isStateDependent() { + for (const property in this.paint._values) { + const value = this.paint.get(property); + if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) { + continue; + } + if ((value.value.kind === 'source' || value.value.kind === 'composite') && + value.value.isStateDependent) { + return true; + } + } + return false; + } +} + +// Note: all "sizes" are measured in bytes +/** + * @internal + * A view type size + */ +const viewTypes = { + 'Int8': Int8Array, + 'Uint8': Uint8Array, + 'Int16': Int16Array, + 'Uint16': Uint16Array, + 'Int32': Int32Array, + 'Uint32': Uint32Array, + 'Float32': Float32Array +}; +/** @internal */ +class Struct { + /** + * @param structArray - The StructArray the struct is stored in + * @param index - The index of the struct in the StructArray. + */ + constructor(structArray, index) { + this._structArray = structArray; + this._pos1 = index * this.size; + this._pos2 = this._pos1 / 2; + this._pos4 = this._pos1 / 4; + this._pos8 = this._pos1 / 8; + } +} +const DEFAULT_CAPACITY = 128; +const RESIZE_MULTIPLIER = 5; +/** + * @internal + * `StructArray` provides an abstraction over `ArrayBuffer` and `TypedArray` + * making it behave like an array of typed structs. + * + * Conceptually, a StructArray is comprised of elements, i.e., instances of its + * associated struct type. Each particular struct type, together with an + * alignment size, determines the memory layout of a StructArray whose elements + * are of that type. Thus, for each such layout that we need, we have + * a corresponding StructArrayLayout class, inheriting from StructArray and + * implementing `emplaceBack()` and `_refreshViews()`. + * + * In some cases, where we need to access particular elements of a StructArray, + * we implement a more specific subclass that inherits from one of the + * StructArrayLayouts and adds a `get(i): T` accessor that returns a structured + * object whose properties are proxies into the underlying memory space for the + * i-th element. This affords the convenience of working with (seemingly) plain + * Javascript objects without the overhead of serializing/deserializing them + * into ArrayBuffers for efficient web worker transfer. + */ +class StructArray { + constructor() { + this.isTransferred = false; + this.capacity = -1; + this.resize(0); + } + /** + * Serialize a StructArray instance. Serializes both the raw data and the + * metadata needed to reconstruct the StructArray base class during + * deserialization. + */ + static serialize(array, transferables) { + array._trim(); + if (transferables) { + array.isTransferred = true; + transferables.push(array.arrayBuffer); + } + return { + length: array.length, + arrayBuffer: array.arrayBuffer, + }; + } + static deserialize(input) { + const structArray = Object.create(this.prototype); + structArray.arrayBuffer = input.arrayBuffer; + structArray.length = input.length; + structArray.capacity = input.arrayBuffer.byteLength / structArray.bytesPerElement; + structArray._refreshViews(); + return structArray; + } + /** + * Resize the array to discard unused capacity. + */ + _trim() { + if (this.length !== this.capacity) { + this.capacity = this.length; + this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement); + this._refreshViews(); + } + } + /** + * Resets the length of the array to 0 without de-allocating capacity. + */ + clear() { + this.length = 0; + } + /** + * Resize the array. + * If `n` is greater than the current length then additional elements with undefined values are added. + * If `n` is less than the current length then the array will be reduced to the first `n` elements. + * @param n - The new size of the array. + */ + resize(n) { + this.reserve(n); + this.length = n; + } + /** + * Indicate a planned increase in size, so that any necessary allocation may + * be done once, ahead of time. + * @param n - The expected size of the array. + */ + reserve(n) { + if (n > this.capacity) { + this.capacity = Math.max(n, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY); + this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement); + const oldUint8Array = this.uint8; + this._refreshViews(); + if (oldUint8Array) + this.uint8.set(oldUint8Array); + } + } + /** + * Create TypedArray views for the current ArrayBuffer. + */ + _refreshViews() { + throw new Error('_refreshViews() must be implemented by each concrete StructArray layout'); + } +} +/** + * Given a list of member fields, create a full StructArrayLayout, in + * particular calculating the correct byte offset for each field. This data + * is used at build time to generate StructArrayLayout_*#emplaceBack() and + * other accessors, and at runtime for binding vertex buffer attributes. + */ +function createLayout(members, alignment = 1) { + let offset = 0; + let maxSize = 0; + const layoutMembers = members.map((member) => { + const typeSize = sizeOf(member.type); + const memberOffset = offset = align$1(offset, Math.max(alignment, typeSize)); + const components = member.components || 1; + maxSize = Math.max(maxSize, typeSize); + offset += typeSize * components; + return { + name: member.name, + type: member.type, + components, + offset: memberOffset, + }; + }); + const size = align$1(offset, Math.max(maxSize, alignment)); + return { + members: layoutMembers, + size, + alignment + }; +} +function sizeOf(type) { + return viewTypes[type].BYTES_PER_ELEMENT; +} +function align$1(offset, size) { + return Math.ceil(offset / size) * size; +} + +// This file is generated. Edit build/generate-struct-arrays.ts, then run `npm run codegen`. +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * + */ +class StructArrayLayout2i4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1); + } + emplace(i, v0, v1) { + const o2 = i * 2; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + return i; + } +} +StructArrayLayout2i4.prototype.bytesPerElement = 4; +register('StructArrayLayout2i4', StructArrayLayout2i4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[3] + * + */ +class StructArrayLayout3i6 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o2 = i * 3; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + return i; + } +} +StructArrayLayout3i6.prototype.bytesPerElement = 6; +register('StructArrayLayout3i6', StructArrayLayout3i6); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[4] + * + */ +class StructArrayLayout4i8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3); + } + emplace(i, v0, v1, v2, v3) { + const o2 = i * 4; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + return i; + } +} +StructArrayLayout4i8.prototype.bytesPerElement = 8; +register('StructArrayLayout4i8', StructArrayLayout4i8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Int16[4] + * + */ +class StructArrayLayout2i4i12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o2 = i * 6; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + return i; + } +} +StructArrayLayout2i4i12.prototype.bytesPerElement = 12; +register('StructArrayLayout2i4i12', StructArrayLayout2i4i12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Uint8[4] + * + */ +class StructArrayLayout2i4ub8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o2 = i * 4; + const o1 = i * 8; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.uint8[o1 + 4] = v2; + this.uint8[o1 + 5] = v3; + this.uint8[o1 + 6] = v4; + this.uint8[o1 + 7] = v5; + return i; + } +} +StructArrayLayout2i4ub8.prototype.bytesPerElement = 8; +register('StructArrayLayout2i4ub8', StructArrayLayout2i4ub8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[2] + * + */ +class StructArrayLayout2f8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1); + } + emplace(i, v0, v1) { + const o4 = i * 2; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + return i; + } +} +StructArrayLayout2f8.prototype.bytesPerElement = 8; +register('StructArrayLayout2f8', StructArrayLayout2f8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[10] + * + */ +class StructArrayLayout10ui20 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) { + const o2 = i * 10; + this.uint16[o2 + 0] = v0; + this.uint16[o2 + 1] = v1; + this.uint16[o2 + 2] = v2; + this.uint16[o2 + 3] = v3; + this.uint16[o2 + 4] = v4; + this.uint16[o2 + 5] = v5; + this.uint16[o2 + 6] = v6; + this.uint16[o2 + 7] = v7; + this.uint16[o2 + 8] = v8; + this.uint16[o2 + 9] = v9; + return i; + } +} +StructArrayLayout10ui20.prototype.bytesPerElement = 20; +register('StructArrayLayout10ui20', StructArrayLayout10ui20); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[4] + * [8] - Uint16[4] + * [16] - Int16[4] + * + */ +class StructArrayLayout4i4ui4i24 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) { + const o2 = i * 12; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.uint16[o2 + 4] = v4; + this.uint16[o2 + 5] = v5; + this.uint16[o2 + 6] = v6; + this.uint16[o2 + 7] = v7; + this.int16[o2 + 8] = v8; + this.int16[o2 + 9] = v9; + this.int16[o2 + 10] = v10; + this.int16[o2 + 11] = v11; + return i; + } +} +StructArrayLayout4i4ui4i24.prototype.bytesPerElement = 24; +register('StructArrayLayout4i4ui4i24', StructArrayLayout4i4ui4i24); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[3] + * + */ +class StructArrayLayout3f12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o4 = i * 3; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + return i; + } +} +StructArrayLayout3f12.prototype.bytesPerElement = 12; +register('StructArrayLayout3f12', StructArrayLayout3f12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint32[1] + * + */ +class StructArrayLayout1ul4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + } + emplaceBack(v0) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0); + } + emplace(i, v0) { + const o4 = i * 1; + this.uint32[o4 + 0] = v0; + return i; + } +} +StructArrayLayout1ul4.prototype.bytesPerElement = 4; +register('StructArrayLayout1ul4', StructArrayLayout1ul4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[6] + * [12] - Uint32[1] + * [16] - Uint16[2] + * + */ +class StructArrayLayout6i1ul2ui20 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8) { + const o2 = i * 10; + const o4 = i * 5; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + this.uint32[o4 + 3] = v6; + this.uint16[o2 + 8] = v7; + this.uint16[o2 + 9] = v8; + return i; + } +} +StructArrayLayout6i1ul2ui20.prototype.bytesPerElement = 20; +register('StructArrayLayout6i1ul2ui20', StructArrayLayout6i1ul2ui20); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Int16[2] + * [8] - Int16[2] + * + */ +class StructArrayLayout2i2i2i12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o2 = i * 6; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + return i; + } +} +StructArrayLayout2i2i2i12.prototype.bytesPerElement = 12; +register('StructArrayLayout2i2i2i12', StructArrayLayout2i2i2i12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[2] + * [8] - Float32[1] + * [12] - Int16[2] + * + */ +class StructArrayLayout2f1f2i16 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4); + } + emplace(i, v0, v1, v2, v3, v4) { + const o4 = i * 4; + const o2 = i * 8; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + this.int16[o2 + 6] = v3; + this.int16[o2 + 7] = v4; + return i; + } +} +StructArrayLayout2f1f2i16.prototype.bytesPerElement = 16; +register('StructArrayLayout2f1f2i16', StructArrayLayout2f1f2i16); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint8[2] + * [4] - Float32[2] + * [12] - Int16[2] + * + */ +class StructArrayLayout2ub2f2i16 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5); + } + emplace(i, v0, v1, v2, v3, v4, v5) { + const o1 = i * 16; + const o4 = i * 4; + const o2 = i * 8; + this.uint8[o1 + 0] = v0; + this.uint8[o1 + 1] = v1; + this.float32[o4 + 1] = v2; + this.float32[o4 + 2] = v3; + this.int16[o2 + 6] = v4; + this.int16[o2 + 7] = v5; + return i; + } +} +StructArrayLayout2ub2f2i16.prototype.bytesPerElement = 16; +register('StructArrayLayout2ub2f2i16', StructArrayLayout2ub2f2i16); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[3] + * + */ +class StructArrayLayout3ui6 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o2 = i * 3; + this.uint16[o2 + 0] = v0; + this.uint16[o2 + 1] = v1; + this.uint16[o2 + 2] = v2; + return i; + } +} +StructArrayLayout3ui6.prototype.bytesPerElement = 6; +register('StructArrayLayout3ui6', StructArrayLayout3ui6); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[2] + * [4] - Uint16[2] + * [8] - Uint32[3] + * [20] - Uint16[3] + * [28] - Float32[2] + * [36] - Uint8[3] + * [40] - Uint32[1] + * [44] - Int16[1] + * + */ +class StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16); + } + emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) { + const o2 = i * 24; + const o4 = i * 12; + const o1 = i * 48; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.uint16[o2 + 2] = v2; + this.uint16[o2 + 3] = v3; + this.uint32[o4 + 2] = v4; + this.uint32[o4 + 3] = v5; + this.uint32[o4 + 4] = v6; + this.uint16[o2 + 10] = v7; + this.uint16[o2 + 11] = v8; + this.uint16[o2 + 12] = v9; + this.float32[o4 + 7] = v10; + this.float32[o4 + 8] = v11; + this.uint8[o1 + 36] = v12; + this.uint8[o1 + 37] = v13; + this.uint8[o1 + 38] = v14; + this.uint32[o4 + 10] = v15; + this.int16[o2 + 22] = v16; + return i; + } +} +StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48.prototype.bytesPerElement = 48; +register('StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48', StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Int16[8] + * [16] - Uint16[15] + * [48] - Uint32[1] + * [52] - Float32[2] + * [60] - Uint16[2] + * + */ +class StructArrayLayout8i15ui1ul2f2ui64 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.int16 = new Int16Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(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) { + const i = this.length; + this.resize(i + 1); + 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); + } + 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) { + const o2 = i * 32; + const o4 = i * 16; + this.int16[o2 + 0] = v0; + this.int16[o2 + 1] = v1; + this.int16[o2 + 2] = v2; + this.int16[o2 + 3] = v3; + this.int16[o2 + 4] = v4; + this.int16[o2 + 5] = v5; + this.int16[o2 + 6] = v6; + this.int16[o2 + 7] = v7; + this.uint16[o2 + 8] = v8; + this.uint16[o2 + 9] = v9; + this.uint16[o2 + 10] = v10; + this.uint16[o2 + 11] = v11; + this.uint16[o2 + 12] = v12; + this.uint16[o2 + 13] = v13; + this.uint16[o2 + 14] = v14; + this.uint16[o2 + 15] = v15; + this.uint16[o2 + 16] = v16; + this.uint16[o2 + 17] = v17; + this.uint16[o2 + 18] = v18; + this.uint16[o2 + 19] = v19; + this.uint16[o2 + 20] = v20; + this.uint16[o2 + 21] = v21; + this.uint16[o2 + 22] = v22; + this.uint32[o4 + 12] = v23; + this.float32[o4 + 13] = v24; + this.float32[o4 + 14] = v25; + this.uint16[o2 + 30] = v26; + this.uint16[o2 + 31] = v27; + return i; + } +} +StructArrayLayout8i15ui1ul2f2ui64.prototype.bytesPerElement = 64; +register('StructArrayLayout8i15ui1ul2f2ui64', StructArrayLayout8i15ui1ul2f2ui64); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[1] + * + */ +class StructArrayLayout1f4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0); + } + emplace(i, v0) { + const o4 = i * 1; + this.float32[o4 + 0] = v0; + return i; + } +} +StructArrayLayout1f4.prototype.bytesPerElement = 4; +register('StructArrayLayout1f4', StructArrayLayout1f4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[1] + * [4] - Float32[2] + * + */ +class StructArrayLayout1ui2f12 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o2 = i * 6; + const o4 = i * 3; + this.uint16[o2 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + return i; + } +} +StructArrayLayout1ui2f12.prototype.bytesPerElement = 12; +register('StructArrayLayout1ui2f12', StructArrayLayout1ui2f12); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint32[1] + * [4] - Uint16[2] + * + */ +class StructArrayLayout1ul2ui8 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint32 = new Uint32Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2); + } + emplace(i, v0, v1, v2) { + const o4 = i * 2; + const o2 = i * 4; + this.uint32[o4 + 0] = v0; + this.uint16[o2 + 2] = v1; + this.uint16[o2 + 3] = v2; + return i; + } +} +StructArrayLayout1ul2ui8.prototype.bytesPerElement = 8; +register('StructArrayLayout1ul2ui8', StructArrayLayout1ul2ui8); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[2] + * + */ +class StructArrayLayout2ui4 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0, v1) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1); + } + emplace(i, v0, v1) { + const o2 = i * 2; + this.uint16[o2 + 0] = v0; + this.uint16[o2 + 1] = v1; + return i; + } +} +StructArrayLayout2ui4.prototype.bytesPerElement = 4; +register('StructArrayLayout2ui4', StructArrayLayout2ui4); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Uint16[1] + * + */ +class StructArrayLayout1ui2 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.uint16 = new Uint16Array(this.arrayBuffer); + } + emplaceBack(v0) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0); + } + emplace(i, v0) { + const o2 = i * 1; + this.uint16[o2 + 0] = v0; + return i; + } +} +StructArrayLayout1ui2.prototype.bytesPerElement = 2; +register('StructArrayLayout1ui2', StructArrayLayout1ui2); +/** + * @internal + * Implementation of the StructArray layout: + * [0] - Float32[4] + * + */ +class StructArrayLayout4f16 extends StructArray { + _refreshViews() { + this.uint8 = new Uint8Array(this.arrayBuffer); + this.float32 = new Float32Array(this.arrayBuffer); + } + emplaceBack(v0, v1, v2, v3) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, v0, v1, v2, v3); + } + emplace(i, v0, v1, v2, v3) { + const o4 = i * 4; + this.float32[o4 + 0] = v0; + this.float32[o4 + 1] = v1; + this.float32[o4 + 2] = v2; + this.float32[o4 + 3] = v3; + return i; + } +} +StructArrayLayout4f16.prototype.bytesPerElement = 16; +register('StructArrayLayout4f16', StructArrayLayout4f16); +/** @internal */ +class CollisionBoxStruct extends Struct { + get anchorPointX() { return this._structArray.int16[this._pos2 + 0]; } + get anchorPointY() { return this._structArray.int16[this._pos2 + 1]; } + get x1() { return this._structArray.int16[this._pos2 + 2]; } + get y1() { return this._structArray.int16[this._pos2 + 3]; } + get x2() { return this._structArray.int16[this._pos2 + 4]; } + get y2() { return this._structArray.int16[this._pos2 + 5]; } + get featureIndex() { return this._structArray.uint32[this._pos4 + 3]; } + get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 8]; } + get bucketIndex() { return this._structArray.uint16[this._pos2 + 9]; } + get anchorPoint() { return new Point$2(this.anchorPointX, this.anchorPointY); } +} +CollisionBoxStruct.prototype.size = 20; +/** @internal */ +class CollisionBoxArray extends StructArrayLayout6i1ul2ui20 { + /** + * Return the CollisionBoxStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new CollisionBoxStruct(this, index); + } +} +register('CollisionBoxArray', CollisionBoxArray); +/** @internal */ +class PlacedSymbolStruct extends Struct { + get anchorX() { return this._structArray.int16[this._pos2 + 0]; } + get anchorY() { return this._structArray.int16[this._pos2 + 1]; } + get glyphStartIndex() { return this._structArray.uint16[this._pos2 + 2]; } + get numGlyphs() { return this._structArray.uint16[this._pos2 + 3]; } + get vertexStartIndex() { return this._structArray.uint32[this._pos4 + 2]; } + get lineStartIndex() { return this._structArray.uint32[this._pos4 + 3]; } + get lineLength() { return this._structArray.uint32[this._pos4 + 4]; } + get segment() { return this._structArray.uint16[this._pos2 + 10]; } + get lowerSize() { return this._structArray.uint16[this._pos2 + 11]; } + get upperSize() { return this._structArray.uint16[this._pos2 + 12]; } + get lineOffsetX() { return this._structArray.float32[this._pos4 + 7]; } + get lineOffsetY() { return this._structArray.float32[this._pos4 + 8]; } + get writingMode() { return this._structArray.uint8[this._pos1 + 36]; } + get placedOrientation() { return this._structArray.uint8[this._pos1 + 37]; } + set placedOrientation(x) { this._structArray.uint8[this._pos1 + 37] = x; } + get hidden() { return this._structArray.uint8[this._pos1 + 38]; } + set hidden(x) { this._structArray.uint8[this._pos1 + 38] = x; } + get crossTileID() { return this._structArray.uint32[this._pos4 + 10]; } + set crossTileID(x) { this._structArray.uint32[this._pos4 + 10] = x; } + get associatedIconIndex() { return this._structArray.int16[this._pos2 + 22]; } +} +PlacedSymbolStruct.prototype.size = 48; +/** @internal */ +class PlacedSymbolArray extends StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 { + /** + * Return the PlacedSymbolStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new PlacedSymbolStruct(this, index); + } +} +register('PlacedSymbolArray', PlacedSymbolArray); +/** @internal */ +class SymbolInstanceStruct extends Struct { + get anchorX() { return this._structArray.int16[this._pos2 + 0]; } + get anchorY() { return this._structArray.int16[this._pos2 + 1]; } + get rightJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 2]; } + get centerJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 3]; } + get leftJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 4]; } + get verticalPlacedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 5]; } + get placedIconSymbolIndex() { return this._structArray.int16[this._pos2 + 6]; } + get verticalPlacedIconSymbolIndex() { return this._structArray.int16[this._pos2 + 7]; } + get key() { return this._structArray.uint16[this._pos2 + 8]; } + get textBoxStartIndex() { return this._structArray.uint16[this._pos2 + 9]; } + get textBoxEndIndex() { return this._structArray.uint16[this._pos2 + 10]; } + get verticalTextBoxStartIndex() { return this._structArray.uint16[this._pos2 + 11]; } + get verticalTextBoxEndIndex() { return this._structArray.uint16[this._pos2 + 12]; } + get iconBoxStartIndex() { return this._structArray.uint16[this._pos2 + 13]; } + get iconBoxEndIndex() { return this._structArray.uint16[this._pos2 + 14]; } + get verticalIconBoxStartIndex() { return this._structArray.uint16[this._pos2 + 15]; } + get verticalIconBoxEndIndex() { return this._structArray.uint16[this._pos2 + 16]; } + get featureIndex() { return this._structArray.uint16[this._pos2 + 17]; } + get numHorizontalGlyphVertices() { return this._structArray.uint16[this._pos2 + 18]; } + get numVerticalGlyphVertices() { return this._structArray.uint16[this._pos2 + 19]; } + get numIconVertices() { return this._structArray.uint16[this._pos2 + 20]; } + get numVerticalIconVertices() { return this._structArray.uint16[this._pos2 + 21]; } + get useRuntimeCollisionCircles() { return this._structArray.uint16[this._pos2 + 22]; } + get crossTileID() { return this._structArray.uint32[this._pos4 + 12]; } + set crossTileID(x) { this._structArray.uint32[this._pos4 + 12] = x; } + get textBoxScale() { return this._structArray.float32[this._pos4 + 13]; } + get collisionCircleDiameter() { return this._structArray.float32[this._pos4 + 14]; } + get textAnchorOffsetStartIndex() { return this._structArray.uint16[this._pos2 + 30]; } + get textAnchorOffsetEndIndex() { return this._structArray.uint16[this._pos2 + 31]; } +} +SymbolInstanceStruct.prototype.size = 64; +/** @internal */ +class SymbolInstanceArray extends StructArrayLayout8i15ui1ul2f2ui64 { + /** + * Return the SymbolInstanceStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new SymbolInstanceStruct(this, index); + } +} +register('SymbolInstanceArray', SymbolInstanceArray); +/** @internal */ +class GlyphOffsetArray extends StructArrayLayout1f4 { + getoffsetX(index) { return this.float32[index * 1 + 0]; } +} +register('GlyphOffsetArray', GlyphOffsetArray); +/** @internal */ +class SymbolLineVertexArray extends StructArrayLayout3i6 { + getx(index) { return this.int16[index * 3 + 0]; } + gety(index) { return this.int16[index * 3 + 1]; } + gettileUnitDistanceFromAnchor(index) { return this.int16[index * 3 + 2]; } +} +register('SymbolLineVertexArray', SymbolLineVertexArray); +/** @internal */ +class TextAnchorOffsetStruct extends Struct { + get textAnchor() { return this._structArray.uint16[this._pos2 + 0]; } + get textOffset0() { return this._structArray.float32[this._pos4 + 1]; } + get textOffset1() { return this._structArray.float32[this._pos4 + 2]; } +} +TextAnchorOffsetStruct.prototype.size = 12; +/** @internal */ +class TextAnchorOffsetArray extends StructArrayLayout1ui2f12 { + /** + * Return the TextAnchorOffsetStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new TextAnchorOffsetStruct(this, index); + } +} +register('TextAnchorOffsetArray', TextAnchorOffsetArray); +/** @internal */ +class FeatureIndexStruct extends Struct { + get featureIndex() { return this._structArray.uint32[this._pos4 + 0]; } + get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 2]; } + get bucketIndex() { return this._structArray.uint16[this._pos2 + 3]; } +} +FeatureIndexStruct.prototype.size = 8; +/** @internal */ +class FeatureIndexArray extends StructArrayLayout1ul2ui8 { + /** + * Return the FeatureIndexStruct at the given location in the array. + * @param index The index of the element. + */ + get(index) { + return new FeatureIndexStruct(this, index); + } +} +register('FeatureIndexArray', FeatureIndexArray); +class PosArray extends StructArrayLayout2i4 { +} +class Pos3dArray extends StructArrayLayout3i6 { +} +class RasterBoundsArray extends StructArrayLayout4i8 { +} +class CircleLayoutArray extends StructArrayLayout2i4 { +} +class FillLayoutArray extends StructArrayLayout2i4 { +} +class FillExtrusionLayoutArray extends StructArrayLayout2i4i12 { +} +class LineLayoutArray extends StructArrayLayout2i4ub8 { +} +class LineExtLayoutArray extends StructArrayLayout2f8 { +} +class PatternLayoutArray extends StructArrayLayout10ui20 { +} +class SymbolLayoutArray extends StructArrayLayout4i4ui4i24 { +} +class SymbolDynamicLayoutArray extends StructArrayLayout3f12 { +} +class SymbolOpacityArray extends StructArrayLayout1ul4 { +} +class CollisionBoxLayoutArray extends StructArrayLayout2i2i2i12 { +} +class CollisionCircleLayoutArray extends StructArrayLayout2f1f2i16 { +} +class CollisionVertexArray extends StructArrayLayout2ub2f2i16 { +} +class QuadTriangleArray extends StructArrayLayout3ui6 { +} +class TriangleIndexArray extends StructArrayLayout3ui6 { +} +class LineIndexArray extends StructArrayLayout2ui4 { +} +class LineStripIndexArray extends StructArrayLayout1ui2 { +} + +const layout$6 = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' } +], 4); +const { members: members$4, size: size$4, alignment: alignment$4 } = layout$6; + +/** + * @internal + * Used for calculations on vector segments + */ +class SegmentVector { + constructor(segments = []) { + this.segments = segments; + } + prepareSegment(numVertices, layoutVertexArray, indexArray, sortKey) { + let segment = this.segments[this.segments.length - 1]; + if (numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) + warnOnce(`Max vertices per segment is ${SegmentVector.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${numVertices}`); + if (!segment || segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH || segment.sortKey !== sortKey) { + segment = { + vertexOffset: layoutVertexArray.length, + primitiveOffset: indexArray.length, + vertexLength: 0, + primitiveLength: 0 + }; + if (sortKey !== undefined) + segment.sortKey = sortKey; + this.segments.push(segment); + } + return segment; + } + get() { + return this.segments; + } + destroy() { + for (const segment of this.segments) { + for (const k in segment.vaos) { + segment.vaos[k].destroy(); + } + } + } + static simpleSegment(vertexOffset, primitiveOffset, vertexLength, primitiveLength) { + return new SegmentVector([{ + vertexOffset, + primitiveOffset, + vertexLength, + primitiveLength, + vaos: {}, + sortKey: 0 + }]); + } +} +/** + * The maximum size of a vertex array. This limit is imposed by WebGL's 16 bit + * addressing of vertex buffers. + */ +SegmentVector.MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1; +register('SegmentVector', SegmentVector); + +/** + * Packs two numbers, interpreted as 8-bit unsigned integers, into a single + * float. Unpack them in the shader using the `unpack_float()` function, + * defined in _prelude.vertex.glsl + */ +function packUint8ToFloat(a, b) { + // coerce a and b to 8-bit ints + a = clamp$1(Math.floor(a), 0, 255); + b = clamp$1(Math.floor(b), 0, 255); + return 256 * a + b; +} + +const patternAttributes = createLayout([ + // [tl.x, tl.y, br.x, br.y] + { name: 'a_pattern_from', components: 4, type: 'Uint16' }, + { name: 'a_pattern_to', components: 4, type: 'Uint16' }, + { name: 'a_pixel_ratio_from', components: 1, type: 'Uint16' }, + { name: 'a_pixel_ratio_to', components: 1, type: 'Uint16' }, +]); + +var murmurhashJs = {exports: {}}; + +var murmurhash3_gc = {exports: {}}; + +/** + * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} key ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ + +(function (module) { + function murmurhash3_32_gc(key, seed) { + var remainder, bytes, h1, h1b, c1, c2, k1, i; + + remainder = key.length & 3; // key.length % 4 + bytes = key.length - remainder; + h1 = seed; + c1 = 0xcc9e2d51; + c2 = 0x1b873593; + i = 0; + + while (i < bytes) { + k1 = + ((key.charCodeAt(i) & 0xff)) | + ((key.charCodeAt(++i) & 0xff) << 8) | + ((key.charCodeAt(++i) & 0xff) << 16) | + ((key.charCodeAt(++i) & 0xff) << 24); + ++i; + + k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff; + + h1 ^= k1; + h1 = (h1 << 13) | (h1 >>> 19); + h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff; + h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16)); + } + + k1 = 0; + + switch (remainder) { + case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; + case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; + case 1: k1 ^= (key.charCodeAt(i) & 0xff); + + k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; + h1 ^= k1; + } + + h1 ^= key.length; + + h1 ^= h1 >>> 16; + h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; + h1 ^= h1 >>> 13; + h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff; + h1 ^= h1 >>> 16; + + return h1 >>> 0; + } + + { + module.exports = murmurhash3_32_gc; + } +} (murmurhash3_gc)); + +var murmurhash3_gcExports = murmurhash3_gc.exports; + +var murmurhash2_gc = {exports: {}}; + +/** + * JS Implementation of MurmurHash2 + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} str ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ + +(function (module) { + function murmurhash2_32_gc(str, seed) { + var + l = str.length, + h = seed ^ l, + i = 0, + k; + + while (l >= 4) { + k = + ((str.charCodeAt(i) & 0xff)) | + ((str.charCodeAt(++i) & 0xff) << 8) | + ((str.charCodeAt(++i) & 0xff) << 16) | + ((str.charCodeAt(++i) & 0xff) << 24); + + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + k ^= k >>> 24; + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; + + l -= 4; + ++i; + } + + switch (l) { + case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; + case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; + case 1: h ^= (str.charCodeAt(i) & 0xff); + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + } + + h ^= h >>> 13; + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + h ^= h >>> 15; + + return h >>> 0; + } + + { + module.exports = murmurhash2_32_gc; + } +} (murmurhash2_gc)); + +var murmurhash2_gcExports = murmurhash2_gc.exports; + +var murmur3 = murmurhash3_gcExports; +var murmur2 = murmurhash2_gcExports; + +murmurhashJs.exports = murmur3; +murmurhashJs.exports.murmur3 = murmur3; +murmurhashJs.exports.murmur2 = murmur2; + +var murmurhashJsExports = murmurhashJs.exports; +var murmur3$1 = /*@__PURE__*/getDefaultExportFromCjs$1(murmurhashJsExports); + +// A transferable data structure that maps feature ids to their indices and buffer offsets +class FeaturePositionMap { + constructor() { + this.ids = []; + this.positions = []; + this.indexed = false; + } + add(id, index, start, end) { + this.ids.push(getNumericId(id)); + this.positions.push(index, start, end); + } + getPositions(id) { + if (!this.indexed) + throw new Error('Trying to get index, but feature positions are not indexed'); + const intId = getNumericId(id); + // binary search for the first occurrence of id in this.ids; + // relies on ids/positions being sorted by id, which happens in serialization + let i = 0; + let j = this.ids.length - 1; + while (i < j) { + const m = (i + j) >> 1; + if (this.ids[m] >= intId) { + j = m; + } + else { + i = m + 1; + } + } + const positions = []; + while (this.ids[i] === intId) { + const index = this.positions[3 * i]; + const start = this.positions[3 * i + 1]; + const end = this.positions[3 * i + 2]; + positions.push({ index, start, end }); + i++; + } + return positions; + } + static serialize(map, transferables) { + const ids = new Float64Array(map.ids); + const positions = new Uint32Array(map.positions); + sort$1(ids, positions, 0, ids.length - 1); + if (transferables) { + transferables.push(ids.buffer, positions.buffer); + } + return { ids, positions }; + } + static deserialize(obj) { + const map = new FeaturePositionMap(); + // after transferring, we only use these arrays statically (no pushes), + // so TypedArray vs Array distinction that flow points out doesn't matter + map.ids = obj.ids; + map.positions = obj.positions; + map.indexed = true; + return map; + } +} +function getNumericId(value) { + const numValue = +value; + if (!isNaN(numValue) && numValue <= Number.MAX_SAFE_INTEGER) { + return numValue; + } + return murmur3$1(String(value)); +} +// custom quicksort that sorts ids, indices and offsets together (by ids) +// uses Hoare partitioning & manual tail call optimization to avoid worst case scenarios +function sort$1(ids, positions, left, right) { + while (left < right) { + const pivot = ids[(left + right) >> 1]; + let i = left - 1; + let j = right + 1; + while (true) { + do + i++; + while (ids[i] < pivot); + do + j--; + while (ids[j] > pivot); + if (i >= j) + break; + swap$1(ids, i, j); + swap$1(positions, 3 * i, 3 * j); + swap$1(positions, 3 * i + 1, 3 * j + 1); + swap$1(positions, 3 * i + 2, 3 * j + 2); + } + if (j - left < right - j) { + sort$1(ids, positions, left, j); + left = j + 1; + } + else { + sort$1(ids, positions, j + 1, right); + right = j; + } + } +} +function swap$1(arr, i, j) { + const tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} +register('FeaturePositionMap', FeaturePositionMap); + +/** + * @internal + * A base uniform abstract class + */ +class Uniform { + constructor(context, location) { + this.gl = context.gl; + this.location = location; + } +} +class Uniform1i extends Uniform { + constructor(context, location) { + super(context, location); + this.current = 0; + } + set(v) { + if (this.current !== v) { + this.current = v; + this.gl.uniform1i(this.location, v); + } + } +} +class Uniform1f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = 0; + } + set(v) { + if (this.current !== v) { + this.current = v; + this.gl.uniform1f(this.location, v); + } + } +} +class Uniform2f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = [0, 0]; + } + set(v) { + if (v[0] !== this.current[0] || v[1] !== this.current[1]) { + this.current = v; + this.gl.uniform2f(this.location, v[0], v[1]); + } + } +} +class Uniform3f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = [0, 0, 0]; + } + set(v) { + if (v[0] !== this.current[0] || v[1] !== this.current[1] || v[2] !== this.current[2]) { + this.current = v; + this.gl.uniform3f(this.location, v[0], v[1], v[2]); + } + } +} +class Uniform4f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = [0, 0, 0, 0]; + } + set(v) { + if (v[0] !== this.current[0] || v[1] !== this.current[1] || + v[2] !== this.current[2] || v[3] !== this.current[3]) { + this.current = v; + this.gl.uniform4f(this.location, v[0], v[1], v[2], v[3]); + } + } +} +class UniformColor extends Uniform { + constructor(context, location) { + super(context, location); + this.current = Color.transparent; + } + set(v) { + if (v.r !== this.current.r || v.g !== this.current.g || + v.b !== this.current.b || v.a !== this.current.a) { + this.current = v; + this.gl.uniform4f(this.location, v.r, v.g, v.b, v.a); + } + } +} +const emptyMat4 = new Float32Array(16); +class UniformMatrix4f extends Uniform { + constructor(context, location) { + super(context, location); + this.current = emptyMat4; + } + set(v) { + // The vast majority of matrix comparisons that will trip this set + // happen at i=12 or i=0, so we check those first to avoid lots of + // unnecessary iteration: + if (v[12] !== this.current[12] || v[0] !== this.current[0]) { + this.current = v; + this.gl.uniformMatrix4fv(this.location, false, v); + return; + } + for (let i = 1; i < 16; i++) { + if (v[i] !== this.current[i]) { + this.current = v; + this.gl.uniformMatrix4fv(this.location, false, v); + break; + } + } + } +} + +function packColor(color) { + return [ + packUint8ToFloat(255 * color.r, 255 * color.g), + packUint8ToFloat(255 * color.b, 255 * color.a) + ]; +} +class ConstantBinder { + constructor(value, names, type) { + this.value = value; + this.uniformNames = names.map(name => `u_${name}`); + this.type = type; + } + setUniform(uniform, globals, currentValue) { + uniform.set(currentValue.constantOr(this.value)); + } + getBinding(context, location, _) { + return (this.type === 'color') ? + new UniformColor(context, location) : + new Uniform1f(context, location); + } +} +class CrossFadedConstantBinder { + constructor(value, names) { + this.uniformNames = names.map(name => `u_${name}`); + this.patternFrom = null; + this.patternTo = null; + this.pixelRatioFrom = 1.0; + this.pixelRatioTo = 1.0; + } + setConstantPatternPositions(posTo, posFrom) { + this.pixelRatioFrom = posFrom.pixelRatio; + this.pixelRatioTo = posTo.pixelRatio; + this.patternFrom = posFrom.tlbr; + this.patternTo = posTo.tlbr; + } + setUniform(uniform, globals, currentValue, uniformName) { + const pos = uniformName === 'u_pattern_to' ? this.patternTo : + uniformName === 'u_pattern_from' ? this.patternFrom : + uniformName === 'u_pixel_ratio_to' ? this.pixelRatioTo : + uniformName === 'u_pixel_ratio_from' ? this.pixelRatioFrom : null; + if (pos) + uniform.set(pos); + } + getBinding(context, location, name) { + return name.substr(0, 9) === 'u_pattern' ? + new Uniform4f(context, location) : + new Uniform1f(context, location); + } +} +class SourceExpressionBinder { + constructor(expression, names, type, PaintVertexArray) { + this.expression = expression; + this.type = type; + this.maxValue = 0; + this.paintVertexAttributes = names.map((name) => ({ + name: `a_${name}`, + type: 'Float32', + components: type === 'color' ? 2 : 1, + offset: 0 + })); + this.paintVertexArray = new PaintVertexArray(); + } + populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection) { + const start = this.paintVertexArray.length; + const value = this.expression.evaluate(new EvaluationParameters(0), feature, {}, canonical, [], formattedSection); + this.paintVertexArray.resize(newLength); + this._setPaintValue(start, newLength, value); + } + updatePaintArray(start, end, feature, featureState) { + const value = this.expression.evaluate({ zoom: 0 }, feature, featureState); + this._setPaintValue(start, end, value); + } + _setPaintValue(start, end, value) { + if (this.type === 'color') { + const color = packColor(value); + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, color[0], color[1]); + } + } + else { + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, value); + } + this.maxValue = Math.max(this.maxValue, Math.abs(value)); + } + } + upload(context) { + if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) { + if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) { + this.paintVertexBuffer.updateData(this.paintVertexArray); + } + else { + this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent); + } + } + } + destroy() { + if (this.paintVertexBuffer) { + this.paintVertexBuffer.destroy(); + } + } +} +class CompositeExpressionBinder { + constructor(expression, names, type, useIntegerZoom, zoom, PaintVertexArray) { + this.expression = expression; + this.uniformNames = names.map(name => `u_${name}_t`); + this.type = type; + this.useIntegerZoom = useIntegerZoom; + this.zoom = zoom; + this.maxValue = 0; + this.paintVertexAttributes = names.map((name) => ({ + name: `a_${name}`, + type: 'Float32', + components: type === 'color' ? 4 : 2, + offset: 0 + })); + this.paintVertexArray = new PaintVertexArray(); + } + populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection) { + const min = this.expression.evaluate(new EvaluationParameters(this.zoom), feature, {}, canonical, [], formattedSection); + const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1), feature, {}, canonical, [], formattedSection); + const start = this.paintVertexArray.length; + this.paintVertexArray.resize(newLength); + this._setPaintValue(start, newLength, min, max); + } + updatePaintArray(start, end, feature, featureState) { + const min = this.expression.evaluate({ zoom: this.zoom }, feature, featureState); + const max = this.expression.evaluate({ zoom: this.zoom + 1 }, feature, featureState); + this._setPaintValue(start, end, min, max); + } + _setPaintValue(start, end, min, max) { + if (this.type === 'color') { + const minColor = packColor(min); + const maxColor = packColor(max); + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, minColor[0], minColor[1], maxColor[0], maxColor[1]); + } + } + else { + for (let i = start; i < end; i++) { + this.paintVertexArray.emplace(i, min, max); + } + this.maxValue = Math.max(this.maxValue, Math.abs(min), Math.abs(max)); + } + } + upload(context) { + if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) { + if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) { + this.paintVertexBuffer.updateData(this.paintVertexArray); + } + else { + this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent); + } + } + } + destroy() { + if (this.paintVertexBuffer) { + this.paintVertexBuffer.destroy(); + } + } + setUniform(uniform, globals) { + const currentZoom = this.useIntegerZoom ? Math.floor(globals.zoom) : globals.zoom; + const factor = clamp$1(this.expression.interpolationFactor(currentZoom, this.zoom, this.zoom + 1), 0, 1); + uniform.set(factor); + } + getBinding(context, location, _) { + return new Uniform1f(context, location); + } +} +class CrossFadedCompositeBinder { + constructor(expression, type, useIntegerZoom, zoom, PaintVertexArray, layerId) { + this.expression = expression; + this.type = type; + this.useIntegerZoom = useIntegerZoom; + this.zoom = zoom; + this.layerId = layerId; + this.zoomInPaintVertexArray = new PaintVertexArray(); + this.zoomOutPaintVertexArray = new PaintVertexArray(); + } + populatePaintArray(length, feature, imagePositions) { + const start = this.zoomInPaintVertexArray.length; + this.zoomInPaintVertexArray.resize(length); + this.zoomOutPaintVertexArray.resize(length); + this._setPaintValues(start, length, feature.patterns && feature.patterns[this.layerId], imagePositions); + } + updatePaintArray(start, end, feature, featureState, imagePositions) { + this._setPaintValues(start, end, feature.patterns && feature.patterns[this.layerId], imagePositions); + } + _setPaintValues(start, end, patterns, positions) { + if (!positions || !patterns) + return; + const { min, mid, max } = patterns; + const imageMin = positions[min]; + const imageMid = positions[mid]; + const imageMax = positions[max]; + if (!imageMin || !imageMid || !imageMax) + return; + // We populate two paint arrays because, for cross-faded properties, we don't know which direction + // we're cross-fading to at layout time. In order to keep vertex attributes to a minimum and not pass + // unnecessary vertex data to the shaders, we determine which to upload at draw time. + for (let i = start; i < end; i++) { + this.zoomInPaintVertexArray.emplace(i, imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1], imageMin.tl[0], imageMin.tl[1], imageMin.br[0], imageMin.br[1], imageMid.pixelRatio, imageMin.pixelRatio); + this.zoomOutPaintVertexArray.emplace(i, imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1], imageMax.tl[0], imageMax.tl[1], imageMax.br[0], imageMax.br[1], imageMid.pixelRatio, imageMax.pixelRatio); + } + } + upload(context) { + if (this.zoomInPaintVertexArray && this.zoomInPaintVertexArray.arrayBuffer && this.zoomOutPaintVertexArray && this.zoomOutPaintVertexArray.arrayBuffer) { + this.zoomInPaintVertexBuffer = context.createVertexBuffer(this.zoomInPaintVertexArray, patternAttributes.members, this.expression.isStateDependent); + this.zoomOutPaintVertexBuffer = context.createVertexBuffer(this.zoomOutPaintVertexArray, patternAttributes.members, this.expression.isStateDependent); + } + } + destroy() { + if (this.zoomOutPaintVertexBuffer) + this.zoomOutPaintVertexBuffer.destroy(); + if (this.zoomInPaintVertexBuffer) + this.zoomInPaintVertexBuffer.destroy(); + } +} +/** + * @internal + * ProgramConfiguration contains the logic for binding style layer properties and tile + * layer feature data into GL program uniforms and vertex attributes. + * + * Non-data-driven property values are bound to shader uniforms. Data-driven property + * values are bound to vertex attributes. In order to support a uniform GLSL syntax over + * both, [Mapbox GL Shaders](https://github.com/mapbox/mapbox-gl-shaders) defines a `#pragma` + * abstraction, which ProgramConfiguration is responsible for implementing. At runtime, + * it examines the attributes of a particular layer, combines this with fixed knowledge + * about how layers of the particular type are implemented, and determines which uniforms + * and vertex attributes will be required. It can then substitute the appropriate text + * into the shader source code, create and link a program, and bind the uniforms and + * vertex attributes in preparation for drawing. + * + * When a vector tile is parsed, this same configuration information is used to + * populate the attribute buffers needed for data-driven styling using the zoom + * level and feature property data. + */ +class ProgramConfiguration { + constructor(layer, zoom, filterProperties) { + this.binders = {}; + this._buffers = []; + const keys = []; + for (const property in layer.paint._values) { + if (!filterProperties(property)) + continue; + const value = layer.paint.get(property); + if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) { + continue; + } + const names = paintAttributeNames(property, layer.type); + const expression = value.value; + const type = value.property.specification.type; + const useIntegerZoom = value.property.useIntegerZoom; + const propType = value.property.specification['property-type']; + const isCrossFaded = propType === 'cross-faded' || propType === 'cross-faded-data-driven'; + if (expression.kind === 'constant') { + this.binders[property] = isCrossFaded ? + new CrossFadedConstantBinder(expression.value, names) : + new ConstantBinder(expression.value, names, type); + keys.push(`/u_${property}`); + } + else if (expression.kind === 'source' || isCrossFaded) { + const StructArrayLayout = layoutType(property, type, 'source'); + this.binders[property] = isCrossFaded ? + new CrossFadedCompositeBinder(expression, type, useIntegerZoom, zoom, StructArrayLayout, layer.id) : + new SourceExpressionBinder(expression, names, type, StructArrayLayout); + keys.push(`/a_${property}`); + } + else { + const StructArrayLayout = layoutType(property, type, 'composite'); + this.binders[property] = new CompositeExpressionBinder(expression, names, type, useIntegerZoom, zoom, StructArrayLayout); + keys.push(`/z_${property}`); + } + } + this.cacheKey = keys.sort().join(''); + } + getMaxValue(property) { + const binder = this.binders[property]; + return binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder ? binder.maxValue : 0; + } + populatePaintArrays(newLength, feature, imagePositions, canonical, formattedSection) { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) + binder.populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection); + } + } + setConstantPatternPositions(posTo, posFrom) { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof CrossFadedConstantBinder) + binder.setConstantPatternPositions(posTo, posFrom); + } + } + updatePaintArrays(featureStates, featureMap, vtLayer, layer, imagePositions) { + let dirty = false; + for (const id in featureStates) { + const positions = featureMap.getPositions(id); + for (const pos of positions) { + const feature = vtLayer.feature(pos.index); + for (const property in this.binders) { + const binder = this.binders[property]; + if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || + binder instanceof CrossFadedCompositeBinder) && binder.expression.isStateDependent === true) { + //AHM: Remove after https://github.com/mapbox/mapbox-gl-js/issues/6255 + const value = layer.paint.get(property); + binder.expression = value.value; + binder.updatePaintArray(pos.start, pos.end, feature, featureStates[id], imagePositions); + dirty = true; + } + } + } + } + return dirty; + } + defines() { + const result = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder) { + result.push(...binder.uniformNames.map(name => `#define HAS_UNIFORM_${name}`)); + } + } + return result; + } + getBinderAttributes() { + const result = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) { + for (let i = 0; i < binder.paintVertexAttributes.length; i++) { + result.push(binder.paintVertexAttributes[i].name); + } + } + else if (binder instanceof CrossFadedCompositeBinder) { + for (let i = 0; i < patternAttributes.members.length; i++) { + result.push(patternAttributes.members[i].name); + } + } + } + return result; + } + getBinderUniforms() { + const uniforms = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) { + for (const uniformName of binder.uniformNames) { + uniforms.push(uniformName); + } + } + } + return uniforms; + } + getPaintVertexBuffers() { + return this._buffers; + } + getUniforms(context, locations) { + const uniforms = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) { + for (const name of binder.uniformNames) { + if (locations[name]) { + const binding = binder.getBinding(context, locations[name], name); + uniforms.push({ name, property, binding }); + } + } + } + } + return uniforms; + } + setUniforms(context, binderUniforms, properties, globals) { + // Uniform state bindings are owned by the Program, but we set them + // from within the ProgramConfiguration's binder members. + for (const { name, property, binding } of binderUniforms) { + this.binders[property].setUniform(binding, globals, properties.get(property), name); + } + } + updatePaintBuffers(crossfade) { + this._buffers = []; + for (const property in this.binders) { + const binder = this.binders[property]; + if (crossfade && binder instanceof CrossFadedCompositeBinder) { + const patternVertexBuffer = crossfade.fromScale === 2 ? binder.zoomInPaintVertexBuffer : binder.zoomOutPaintVertexBuffer; + if (patternVertexBuffer) + this._buffers.push(patternVertexBuffer); + } + else if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) && binder.paintVertexBuffer) { + this._buffers.push(binder.paintVertexBuffer); + } + } + } + upload(context) { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) + binder.upload(context); + } + this.updatePaintBuffers(); + } + destroy() { + for (const property in this.binders) { + const binder = this.binders[property]; + if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) + binder.destroy(); + } + } +} +class ProgramConfigurationSet { + constructor(layers, zoom, filterProperties = () => true) { + this.programConfigurations = {}; + for (const layer of layers) { + this.programConfigurations[layer.id] = new ProgramConfiguration(layer, zoom, filterProperties); + } + this.needsUpload = false; + this._featureMap = new FeaturePositionMap(); + this._bufferOffset = 0; + } + populatePaintArrays(length, feature, index, imagePositions, canonical, formattedSection) { + for (const key in this.programConfigurations) { + this.programConfigurations[key].populatePaintArrays(length, feature, imagePositions, canonical, formattedSection); + } + if (feature.id !== undefined) { + this._featureMap.add(feature.id, index, this._bufferOffset, length); + } + this._bufferOffset = length; + this.needsUpload = true; + } + updatePaintArrays(featureStates, vtLayer, layers, imagePositions) { + for (const layer of layers) { + this.needsUpload = this.programConfigurations[layer.id].updatePaintArrays(featureStates, this._featureMap, vtLayer, layer, imagePositions) || this.needsUpload; + } + } + get(layerId) { + return this.programConfigurations[layerId]; + } + upload(context) { + if (!this.needsUpload) + return; + for (const layerId in this.programConfigurations) { + this.programConfigurations[layerId].upload(context); + } + this.needsUpload = false; + } + destroy() { + for (const layerId in this.programConfigurations) { + this.programConfigurations[layerId].destroy(); + } + } +} +function paintAttributeNames(property, type) { + const attributeNameExceptions = { + 'text-opacity': ['opacity'], + 'icon-opacity': ['opacity'], + 'text-color': ['fill_color'], + 'icon-color': ['fill_color'], + 'text-halo-color': ['halo_color'], + 'icon-halo-color': ['halo_color'], + 'text-halo-blur': ['halo_blur'], + 'icon-halo-blur': ['halo_blur'], + 'text-halo-width': ['halo_width'], + 'icon-halo-width': ['halo_width'], + 'line-gap-width': ['gapwidth'], + 'line-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'], + 'fill-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'], + 'fill-extrusion-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'], + }; + return attributeNameExceptions[property] || [property.replace(`${type}-`, '').replace(/-/g, '_')]; +} +function getLayoutException(property) { + const propertyExceptions = { + 'line-pattern': { + 'source': PatternLayoutArray, + 'composite': PatternLayoutArray + }, + 'fill-pattern': { + 'source': PatternLayoutArray, + 'composite': PatternLayoutArray + }, + 'fill-extrusion-pattern': { + 'source': PatternLayoutArray, + 'composite': PatternLayoutArray + } + }; + return propertyExceptions[property]; +} +function layoutType(property, type, binderType) { + const defaultLayouts = { + 'color': { + 'source': StructArrayLayout2f8, + 'composite': StructArrayLayout4f16 + }, + 'number': { + 'source': StructArrayLayout1f4, + 'composite': StructArrayLayout2f8 + } + }; + const layoutException = getLayoutException(property); + return layoutException && layoutException[binderType] || defaultLayouts[type][binderType]; +} +register('ConstantBinder', ConstantBinder); +register('CrossFadedConstantBinder', CrossFadedConstantBinder); +register('SourceExpressionBinder', SourceExpressionBinder); +register('CrossFadedCompositeBinder', CrossFadedCompositeBinder); +register('CompositeExpressionBinder', CompositeExpressionBinder); +register('ProgramConfiguration', ProgramConfiguration, { omit: ['_buffers'] }); +register('ProgramConfigurationSet', ProgramConfigurationSet); + +/** + * The maximum value of a coordinate in the internal tile coordinate system. Coordinates of + * all source features normalized to this extent upon load. + * + * The value is a consequence of the following: + * + * * Vertex buffer store positions as signed 16 bit integers. + * * One bit is lost for signedness to support tile buffers. + * * One bit is lost because the line vertex buffer used to pack 1 bit of other data into the int. + * * One bit is lost to support features extending past the extent on the right edge of the tile. + * * This leaves us with 2^13 = 8192 + */ +const EXTENT = 8192; + +// These bounds define the minimum and maximum supported coordinate values. +// While visible coordinates are within [0, EXTENT], tiles may theoretically +// contain coordinates within [-Infinity, Infinity]. Our range is limited by the +// number of bits used to represent the coordinate. +const BITS = 15; +const MAX = Math.pow(2, BITS - 1) - 1; +const MIN = -MAX - 1; +/** + * Loads a geometry from a VectorTileFeature and scales it to the common extent + * used internally. + * @param feature - the vector tile feature to load + */ +function loadGeometry(feature) { + const scale = EXTENT / feature.extent; + const geometry = feature.loadGeometry(); + for (let r = 0; r < geometry.length; r++) { + const ring = geometry[r]; + for (let p = 0; p < ring.length; p++) { + const point = ring[p]; + // round here because mapbox-gl-native uses integers to represent + // points and we need to do the same to avoid renering differences. + const x = Math.round(point.x * scale); + const y = Math.round(point.y * scale); + point.x = clamp$1(x, MIN, MAX); + point.y = clamp$1(y, MIN, MAX); + if (x < point.x || x > point.x + 1 || y < point.y || y > point.y + 1) { + // warn when exceeding allowed extent except for the 1-px-off case + // https://github.com/mapbox/mapbox-gl-js/issues/8992 + warnOnce('Geometry exceeds allowed extent, reduce your vector tile buffer size'); + } + } + } + return geometry; +} + +/** + * Construct a new feature based on a VectorTileFeature for expression evaluation, the geometry of which + * will be loaded based on necessity. + * @param feature - the feature to evaluate + * @param needGeometry - if set to true this will load the geometry + */ +function toEvaluationFeature(feature, needGeometry) { + return { type: feature.type, + id: feature.id, + properties: feature.properties, + geometry: needGeometry ? loadGeometry(feature) : [] }; +} + +function addCircleVertex(layoutVertexArray, x, y, extrudeX, extrudeY) { + layoutVertexArray.emplaceBack((x * 2) + ((extrudeX + 1) / 2), (y * 2) + ((extrudeY + 1) / 2)); +} +/** + * @internal + * Circles are represented by two triangles. + * + * Each corner has a pos that is the center of the circle and an extrusion + * vector that is where it points. + */ +class CircleBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.layoutVertexArray = new CircleLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.segments = new SegmentVector(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + const styleLayer = this.layers[0]; + const bucketFeatures = []; + let circleSortKey = null; + let sortFeaturesByKey = false; + // Heatmap layers are handled in this bucket and have no evaluated properties, so we check our access + if (styleLayer.type === 'circle') { + circleSortKey = styleLayer.layout.get('circle-sort-key'); + sortFeaturesByKey = !circleSortKey.isConstant(); + } + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const sortKey = sortFeaturesByKey ? + circleSortKey.evaluate(evaluationFeature, {}, canonical) : + undefined; + const bucketFeature = { + id, + properties: feature.properties, + type: feature.type, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + patterns: {}, + sortKey + }; + bucketFeatures.push(bucketFeature); + } + if (sortFeaturesByKey) { + bucketFeatures.sort((a, b) => a.sortKey - b.sortKey); + } + for (const bucketFeature of bucketFeatures) { + const { geometry, index, sourceLayerIndex } = bucketFeature; + const feature = features[index].feature; + this.addFeature(bucketFeature, geometry, index, canonical); + options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + isEmpty() { + return this.layoutVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$4); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + } + addFeature(feature, geometry, index, canonical) { + for (const ring of geometry) { + for (const point of ring) { + const x = point.x; + const y = point.y; + // Do not include points that are outside the tile boundaries. + if (x < 0 || x >= EXTENT || y < 0 || y >= EXTENT) + continue; + // this geometry will be of the Point type, and we'll derive + // two triangles from it. + // + // ┌─────────┐ + // │ 3 2 │ + // │ │ + // │ 0 1 │ + // └─────────┘ + const segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray, feature.sortKey); + const index = segment.vertexLength; + addCircleVertex(this.layoutVertexArray, x, y, -1, -1); + addCircleVertex(this.layoutVertexArray, x, y, 1, -1); + addCircleVertex(this.layoutVertexArray, x, y, 1, 1); + addCircleVertex(this.layoutVertexArray, x, y, -1, 1); + this.indexArray.emplaceBack(index, index + 1, index + 2); + this.indexArray.emplaceBack(index, index + 3, index + 2); + segment.vertexLength += 4; + segment.primitiveLength += 2; + } + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, {}, canonical); + } +} +register('CircleBucket', CircleBucket, { omit: ['layers'] }); + +function polygonIntersectsPolygon(polygonA, polygonB) { + for (let i = 0; i < polygonA.length; i++) { + if (polygonContainsPoint(polygonB, polygonA[i])) + return true; + } + for (let i = 0; i < polygonB.length; i++) { + if (polygonContainsPoint(polygonA, polygonB[i])) + return true; + } + if (lineIntersectsLine(polygonA, polygonB)) + return true; + return false; +} +function polygonIntersectsBufferedPoint(polygon, point, radius) { + if (polygonContainsPoint(polygon, point)) + return true; + if (pointIntersectsBufferedLine(point, polygon, radius)) + return true; + return false; +} +function polygonIntersectsMultiPolygon(polygon, multiPolygon) { + if (polygon.length === 1) { + return multiPolygonContainsPoint(multiPolygon, polygon[0]); + } + for (let m = 0; m < multiPolygon.length; m++) { + const ring = multiPolygon[m]; + for (let n = 0; n < ring.length; n++) { + if (polygonContainsPoint(polygon, ring[n])) + return true; + } + } + for (let i = 0; i < polygon.length; i++) { + if (multiPolygonContainsPoint(multiPolygon, polygon[i])) + return true; + } + for (let k = 0; k < multiPolygon.length; k++) { + if (lineIntersectsLine(polygon, multiPolygon[k])) + return true; + } + return false; +} +function polygonIntersectsBufferedMultiLine(polygon, multiLine, radius) { + for (let i = 0; i < multiLine.length; i++) { + const line = multiLine[i]; + if (polygon.length >= 3) { + for (let k = 0; k < line.length; k++) { + if (polygonContainsPoint(polygon, line[k])) + return true; + } + } + if (lineIntersectsBufferedLine(polygon, line, radius)) + return true; + } + return false; +} +function lineIntersectsBufferedLine(lineA, lineB, radius) { + if (lineA.length > 1) { + if (lineIntersectsLine(lineA, lineB)) + return true; + // Check whether any point in either line is within radius of the other line + for (let j = 0; j < lineB.length; j++) { + if (pointIntersectsBufferedLine(lineB[j], lineA, radius)) + return true; + } + } + for (let k = 0; k < lineA.length; k++) { + if (pointIntersectsBufferedLine(lineA[k], lineB, radius)) + return true; + } + return false; +} +function lineIntersectsLine(lineA, lineB) { + if (lineA.length === 0 || lineB.length === 0) + return false; + for (let i = 0; i < lineA.length - 1; i++) { + const a0 = lineA[i]; + const a1 = lineA[i + 1]; + for (let j = 0; j < lineB.length - 1; j++) { + const b0 = lineB[j]; + const b1 = lineB[j + 1]; + if (lineSegmentIntersectsLineSegment(a0, a1, b0, b1)) + return true; + } + } + return false; +} +function lineSegmentIntersectsLineSegment(a0, a1, b0, b1) { + return isCounterClockwise(a0, b0, b1) !== isCounterClockwise(a1, b0, b1) && + isCounterClockwise(a0, a1, b0) !== isCounterClockwise(a0, a1, b1); +} +function pointIntersectsBufferedLine(p, line, radius) { + const radiusSquared = radius * radius; + if (line.length === 1) + return p.distSqr(line[0]) < radiusSquared; + for (let i = 1; i < line.length; i++) { + // Find line segments that have a distance <= radius^2 to p + // In that case, we treat the line as "containing point p". + const v = line[i - 1], w = line[i]; + if (distToSegmentSquared(p, v, w) < radiusSquared) + return true; + } + return false; +} +// Code from https://stackoverflow.com/a/1501725/331379. +function distToSegmentSquared(p, v, w) { + const l2 = v.distSqr(w); + if (l2 === 0) + return p.distSqr(v); + const t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2; + if (t < 0) + return p.distSqr(v); + if (t > 1) + return p.distSqr(w); + return p.distSqr(w.sub(v)._mult(t)._add(v)); +} +// point in polygon ray casting algorithm +function multiPolygonContainsPoint(rings, p) { + let c = false, ring, p1, p2; + for (let k = 0; k < rings.length; k++) { + ring = rings[k]; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + 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)) { + c = !c; + } + } + } + return c; +} +function polygonContainsPoint(ring, p) { + let c = false; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const p1 = ring[i]; + const p2 = ring[j]; + 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)) { + c = !c; + } + } + return c; +} +function polygonIntersectsBox(ring, boxX1, boxY1, boxX2, boxY2) { + for (const p of ring) { + if (boxX1 <= p.x && + boxY1 <= p.y && + boxX2 >= p.x && + boxY2 >= p.y) + return true; + } + const corners = [ + new Point$2(boxX1, boxY1), + new Point$2(boxX1, boxY2), + new Point$2(boxX2, boxY2), + new Point$2(boxX2, boxY1) + ]; + if (ring.length > 2) { + for (const corner of corners) { + if (polygonContainsPoint(ring, corner)) + return true; + } + } + for (let i = 0; i < ring.length - 1; i++) { + const p1 = ring[i]; + const p2 = ring[i + 1]; + if (edgeIntersectsBox(p1, p2, corners)) + return true; + } + return false; +} +function edgeIntersectsBox(e1, e2, corners) { + const tl = corners[0]; + const br = corners[2]; + // the edge and box do not intersect in either the x or y dimensions + if (((e1.x < tl.x) && (e2.x < tl.x)) || + ((e1.x > br.x) && (e2.x > br.x)) || + ((e1.y < tl.y) && (e2.y < tl.y)) || + ((e1.y > br.y) && (e2.y > br.y))) + return false; + // check if all corners of the box are on the same side of the edge + const dir = isCounterClockwise(e1, e2, corners[0]); + return dir !== isCounterClockwise(e1, e2, corners[1]) || + dir !== isCounterClockwise(e1, e2, corners[2]) || + dir !== isCounterClockwise(e1, e2, corners[3]); +} + +function getMaximumPaintValue(property, layer, bucket) { + const value = layer.paint.get(property).value; + if (value.kind === 'constant') { + return value.value; + } + else { + return bucket.programConfigurations.get(layer.id).getMaxValue(property); + } +} +function translateDistance(translate) { + return Math.sqrt(translate[0] * translate[0] + translate[1] * translate[1]); +} +function translate$1(queryGeometry, translate, translateAnchor, bearing, pixelsToTileUnits) { + if (!translate[0] && !translate[1]) { + return queryGeometry; + } + const pt = Point$2.convert(translate)._mult(pixelsToTileUnits); + if (translateAnchor === 'viewport') { + pt._rotate(-bearing); + } + const translated = []; + for (let i = 0; i < queryGeometry.length; i++) { + const point = queryGeometry[i]; + translated.push(point.sub(pt)); + } + return translated; +} +function offsetLine(rings, offset) { + const newRings = []; + for (let ringIndex = 0; ringIndex < rings.length; ringIndex++) { + const ring = rings[ringIndex]; + const newRing = []; + for (let index = 0; index < ring.length; index++) { + const a = ring[index - 1]; + const b = ring[index]; + const c = ring[index + 1]; + const aToB = index === 0 ? new Point$2(0, 0) : b.sub(a)._unit()._perp(); + const bToC = index === ring.length - 1 ? new Point$2(0, 0) : c.sub(b)._unit()._perp(); + const extrude = aToB._add(bToC)._unit(); + const cosHalfAngle = extrude.x * bToC.x + extrude.y * bToC.y; + if (cosHalfAngle !== 0) { + extrude._mult(1 / cosHalfAngle); + } + newRing.push(extrude._mult(offset)._add(b)); + } + newRings.push(newRing); + } + return newRings; +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout$5; +const getLayout$3 = () => layout$5 = layout$5 || new Properties({ + "circle-sort-key": new DataDrivenProperty(v8Spec["layout_circle"]["circle-sort-key"]), +}); +let paint$8; +const getPaint$8 = () => paint$8 = paint$8 || new Properties({ + "circle-radius": new DataDrivenProperty(v8Spec["paint_circle"]["circle-radius"]), + "circle-color": new DataDrivenProperty(v8Spec["paint_circle"]["circle-color"]), + "circle-blur": new DataDrivenProperty(v8Spec["paint_circle"]["circle-blur"]), + "circle-opacity": new DataDrivenProperty(v8Spec["paint_circle"]["circle-opacity"]), + "circle-translate": new DataConstantProperty(v8Spec["paint_circle"]["circle-translate"]), + "circle-translate-anchor": new DataConstantProperty(v8Spec["paint_circle"]["circle-translate-anchor"]), + "circle-pitch-scale": new DataConstantProperty(v8Spec["paint_circle"]["circle-pitch-scale"]), + "circle-pitch-alignment": new DataConstantProperty(v8Spec["paint_circle"]["circle-pitch-alignment"]), + "circle-stroke-width": new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-width"]), + "circle-stroke-color": new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-color"]), + "circle-stroke-opacity": new DataDrivenProperty(v8Spec["paint_circle"]["circle-stroke-opacity"]), +}); +var properties$8 = ({ get paint() { return getPaint$8(); }, get layout() { return getLayout$3(); } }); + +/** + * Common utilities + * @module glMatrix + */ +// Configuration Constants +var EPSILON = 0.000001; +var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; +if (!Math.hypot) Math.hypot = function () { + var y = 0, + i = arguments.length; + + while (i--) { + y += arguments[i] * arguments[i]; + } + + return Math.sqrt(y); +}; + +/** + * 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied. + * @module mat4 + */ + +/** + * Creates a new identity mat4 + * + * @returns {mat4} a new 4x4 matrix + */ + +function create$1() { + var out = new ARRAY_TYPE(16); + + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + } + + out[0] = 1; + out[5] = 1; + out[10] = 1; + out[15] = 1; + return out; +} +/** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param {ReadonlyMat4} a matrix to clone + * @returns {mat4} a new 4x4 matrix + */ + +function clone(a) { + var out = new ARRAY_TYPE(16); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +/** + * Copy the values from one mat4 to another + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function copy(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +/** + * Set a mat4 to the identity matrix + * + * @param {mat4} out the receiving matrix + * @returns {mat4} out + */ + +function identity(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Inverts a mat4 + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the source matrix + * @returns {mat4} out + */ + +function invert(out, a) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; + var b00 = a00 * a11 - a01 * a10; + var b01 = a00 * a12 - a02 * a10; + var b02 = a00 * a13 - a03 * a10; + var b03 = a01 * a12 - a02 * a11; + var b04 = a01 * a13 - a03 * a11; + var b05 = a02 * a13 - a03 * a12; + var b06 = a20 * a31 - a21 * a30; + var b07 = a20 * a32 - a22 * a30; + var b08 = a20 * a33 - a23 * a30; + var b09 = a21 * a32 - a22 * a31; + var b10 = a21 * a33 - a23 * a31; + var b11 = a22 * a33 - a23 * a32; // Calculate the determinant + + var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + + det = 1.0 / det; + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + return out; +} +/** + * Multiplies two mat4s + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the first operand + * @param {ReadonlyMat4} b the second operand + * @returns {mat4} out + */ + +function multiply$1(out, a, b) { + var a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3]; + var a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + var a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + var a30 = a[12], + a31 = a[13], + a32 = a[14], + a33 = a[15]; // Cache only the current line of the second matrix + + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[4]; + b1 = b[5]; + b2 = b[6]; + b3 = b[7]; + out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[8]; + b1 = b[9]; + b2 = b[10]; + b3 = b[11]; + out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[12]; + b1 = b[13]; + b2 = b[14]; + b3 = b[15]; + out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + return out; +} +/** + * Translate a mat4 by the given vector + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to translate + * @param {ReadonlyVec3} v vector to translate by + * @returns {mat4} out + */ + +function translate(out, a, v) { + var x = v[0], + y = v[1], + z = v[2]; + var a00, a01, a02, a03; + var a10, a11, a12, a13; + var a20, a21, a22, a23; + + if (a === out) { + out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + } else { + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; + out[0] = a00; + out[1] = a01; + out[2] = a02; + out[3] = a03; + out[4] = a10; + out[5] = a11; + out[6] = a12; + out[7] = a13; + out[8] = a20; + out[9] = a21; + out[10] = a22; + out[11] = a23; + out[12] = a00 * x + a10 * y + a20 * z + a[12]; + out[13] = a01 * x + a11 * y + a21 * z + a[13]; + out[14] = a02 * x + a12 * y + a22 * z + a[14]; + out[15] = a03 * x + a13 * y + a23 * z + a[15]; + } + + return out; +} +/** + * Scales the mat4 by the dimensions in the given vec3 not using vectorization + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to scale + * @param {ReadonlyVec3} v the vec3 to scale the matrix by + * @returns {mat4} out + **/ + +function scale(out, a, v) { + var x = v[0], + y = v[1], + z = v[2]; + out[0] = a[0] * x; + out[1] = a[1] * x; + out[2] = a[2] * x; + out[3] = a[3] * x; + out[4] = a[4] * y; + out[5] = a[5] * y; + out[6] = a[6] * y; + out[7] = a[7] * y; + out[8] = a[8] * z; + out[9] = a[9] * z; + out[10] = a[10] * z; + out[11] = a[11] * z; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +/** + * Rotates a matrix by the given angle around the X axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function rotateX(out, a, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + var a20 = a[8]; + var a21 = a[9]; + var a22 = a[10]; + var a23 = a[11]; + + if (a !== out) { + // If the source and destination differ, copy the unchanged rows + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } // Perform axis-specific matrix multiplication + + + out[4] = a10 * c + a20 * s; + out[5] = a11 * c + a21 * s; + out[6] = a12 * c + a22 * s; + out[7] = a13 * c + a23 * s; + out[8] = a20 * c - a10 * s; + out[9] = a21 * c - a11 * s; + out[10] = a22 * c - a12 * s; + out[11] = a23 * c - a13 * s; + return out; +} +/** + * Rotates a matrix by the given angle around the Z axis + * + * @param {mat4} out the receiving matrix + * @param {ReadonlyMat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + +function rotateZ(out, a, rad) { + var s = Math.sin(rad); + var c = Math.cos(rad); + var a00 = a[0]; + var a01 = a[1]; + var a02 = a[2]; + var a03 = a[3]; + var a10 = a[4]; + var a11 = a[5]; + var a12 = a[6]; + var a13 = a[7]; + + if (a !== out) { + // If the source and destination differ, copy the unchanged last row + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } // Perform axis-specific matrix multiplication + + + out[0] = a00 * c + a10 * s; + out[1] = a01 * c + a11 * s; + out[2] = a02 * c + a12 * s; + out[3] = a03 * c + a13 * s; + out[4] = a10 * c - a00 * s; + out[5] = a11 * c - a01 * s; + out[6] = a12 * c - a02 * s; + out[7] = a13 * c - a03 * s; + return out; +} +/** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {ReadonlyVec3} v Scaling vector + * @returns {mat4} out + */ + +function fromScaling(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = v[1]; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = v[2]; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +/** + * Generates a perspective projection matrix with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1], + * which matches WebGL/OpenGL's clip volume. + * Passing null/undefined/no value for far will generate infinite projection matrix. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} fovy Vertical field of view in radians + * @param {number} aspect Aspect ratio. typically viewport width/height + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum, can be null or Infinity + * @returns {mat4} out + */ + +function perspectiveNO(out, fovy, aspect, near, far) { + var f = 1.0 / Math.tan(fovy / 2), + nf; + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[15] = 0; + + if (far != null && far !== Infinity) { + nf = 1 / (near - far); + out[10] = (far + near) * nf; + out[14] = 2 * far * near * nf; + } else { + out[10] = -1; + out[14] = -2 * near; + } + + return out; +} +/** + * Alias for {@link mat4.perspectiveNO} + * @function + */ + +var perspective = perspectiveNO; +/** + * Generates a orthogonal projection matrix with the given bounds. + * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1], + * which matches WebGL/OpenGL's clip volume. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} left Left bound of the frustum + * @param {number} right Right bound of the frustum + * @param {number} bottom Bottom bound of the frustum + * @param {number} top Top bound of the frustum + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + +function orthoNO(out, left, right, bottom, top, near, far) { + var lr = 1 / (left - right); + var bt = 1 / (bottom - top); + var nf = 1 / (near - far); + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 2 * nf; + out[11] = 0; + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = (far + near) * nf; + out[15] = 1; + return out; +} +/** + * Alias for {@link mat4.orthoNO} + * @function + */ + +var ortho = orthoNO; +/** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {ReadonlyMat4} a The first matrix. + * @param {ReadonlyMat4} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function exactEquals(a, b) { + 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]; +} +/** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {ReadonlyMat4} a The first matrix. + * @param {ReadonlyMat4} b The second matrix. + * @returns {Boolean} True if the matrices are equal, false otherwise. + */ + +function equals$1(a, b) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var a4 = a[4], + a5 = a[5], + a6 = a[6], + a7 = a[7]; + var a8 = a[8], + a9 = a[9], + a10 = a[10], + a11 = a[11]; + var a12 = a[12], + a13 = a[13], + a14 = a[14], + a15 = a[15]; + var b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3]; + var b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7]; + var b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11]; + var b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15)); +} +/** + * Alias for {@link mat4.multiply} + * @function + */ + +var mul$1 = multiply$1; + +/** + * 4 Dimensional Vector + * @module vec4 + */ + +/** + * Creates a new, empty vec4 + * + * @returns {vec4} a new 4D vector + */ + +function create() { + var out = new ARRAY_TYPE(4); + + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 0; + } + + return out; +} +/** + * Multiplies two vec4's + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {vec4} out + */ + +function multiply(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + out[2] = a[2] * b[2]; + out[3] = a[3] * b[3]; + return out; +} +/** + * Calculates the dot product of two vec4's + * + * @param {ReadonlyVec4} a the first operand + * @param {ReadonlyVec4} b the second operand + * @returns {Number} dot product of a and b + */ + +function dot$1(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; +} +/** + * Transforms the vec4 with a mat4. + * + * @param {vec4} out the receiving vector + * @param {ReadonlyVec4} a the vector to transform + * @param {ReadonlyMat4} m matrix to transform with + * @returns {vec4} out + */ + +function transformMat4(out, a, m) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w; + out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w; + out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w; + out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w; + return out; +} +/** + * Alias for {@link vec4.multiply} + * @function + */ + +var mul = multiply; +/** + * Perform some operation over an array of vec4s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ + +(function () { + var vec = create(); + return function (a, stride, offset, count, fn, arg) { + var i, l; + + if (!stride) { + stride = 4; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min(count * stride + offset, a.length); + } else { + l = a.length; + } + + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + vec[2] = a[i + 2]; + vec[3] = a[i + 3]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + a[i + 2] = vec[2]; + a[i + 3] = vec[3]; + } + + return a; + }; +})(); + +/** + * A style layer that defines a circle + */ +class CircleStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$8); + } + createBucket(parameters) { + return new CircleBucket(parameters); + } + queryRadius(bucket) { + const circleBucket = bucket; + return getMaximumPaintValue('circle-radius', this, circleBucket) + + getMaximumPaintValue('circle-stroke-width', this, circleBucket) + + translateDistance(this.paint.get('circle-translate')); + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits, pixelPosMatrix) { + const translatedPolygon = translate$1(queryGeometry, this.paint.get('circle-translate'), this.paint.get('circle-translate-anchor'), transform.angle, pixelsToTileUnits); + const radius = this.paint.get('circle-radius').evaluate(feature, featureState); + const stroke = this.paint.get('circle-stroke-width').evaluate(feature, featureState); + const size = radius + stroke; + // For pitch-alignment: map, compare feature geometry to query geometry in the plane of the tile + // // Otherwise, compare geometry in the plane of the viewport + // // A circle with fixed scaling relative to the viewport gets larger in tile space as it moves into the distance + // // A circle with fixed scaling relative to the map gets smaller in viewport space as it moves into the distance + const alignWithMap = this.paint.get('circle-pitch-alignment') === 'map'; + const transformedPolygon = alignWithMap ? translatedPolygon : projectQueryGeometry$1(translatedPolygon, pixelPosMatrix); + const transformedSize = alignWithMap ? size * pixelsToTileUnits : size; + for (const ring of geometry) { + for (const point of ring) { + const transformedPoint = alignWithMap ? point : projectPoint(point, pixelPosMatrix); + let adjustedSize = transformedSize; + const projectedCenter = transformMat4([], [point.x, point.y, 0, 1], pixelPosMatrix); + if (this.paint.get('circle-pitch-scale') === 'viewport' && this.paint.get('circle-pitch-alignment') === 'map') { + adjustedSize *= projectedCenter[3] / transform.cameraToCenterDistance; + } + else if (this.paint.get('circle-pitch-scale') === 'map' && this.paint.get('circle-pitch-alignment') === 'viewport') { + adjustedSize *= transform.cameraToCenterDistance / projectedCenter[3]; + } + if (polygonIntersectsBufferedPoint(transformedPolygon, transformedPoint, adjustedSize)) + return true; + } + } + return false; + } +} +function projectPoint(p, pixelPosMatrix) { + const point = transformMat4([], [p.x, p.y, 0, 1], pixelPosMatrix); + return new Point$2(point[0] / point[3], point[1] / point[3]); +} +function projectQueryGeometry$1(queryGeometry, pixelPosMatrix) { + return queryGeometry.map((p) => { + return projectPoint(p, pixelPosMatrix); + }); +} + +class HeatmapBucket extends CircleBucket { +} +register('HeatmapBucket', HeatmapBucket, { omit: ['layers'] }); + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$7; +const getPaint$7 = () => paint$7 = paint$7 || new Properties({ + "heatmap-radius": new DataDrivenProperty(v8Spec["paint_heatmap"]["heatmap-radius"]), + "heatmap-weight": new DataDrivenProperty(v8Spec["paint_heatmap"]["heatmap-weight"]), + "heatmap-intensity": new DataConstantProperty(v8Spec["paint_heatmap"]["heatmap-intensity"]), + "heatmap-color": new ColorRampProperty(v8Spec["paint_heatmap"]["heatmap-color"]), + "heatmap-opacity": new DataConstantProperty(v8Spec["paint_heatmap"]["heatmap-opacity"]), +}); +var properties$7 = ({ get paint() { return getPaint$7(); } }); + +function createImage(image, { width, height }, channels, data) { + if (!data) { + data = new Uint8Array(width * height * channels); + } + else if (data instanceof Uint8ClampedArray) { + data = new Uint8Array(data.buffer); + } + else if (data.length !== width * height * channels) { + throw new RangeError(`mismatched image size. expected: ${data.length} but got: ${width * height * channels}`); + } + image.width = width; + image.height = height; + image.data = data; + return image; +} +function resizeImage(image, { width, height }, channels) { + if (width === image.width && height === image.height) { + return; + } + const newImage = createImage({}, { width, height }, channels); + copyImage(image, newImage, { x: 0, y: 0 }, { x: 0, y: 0 }, { + width: Math.min(image.width, width), + height: Math.min(image.height, height) + }, channels); + image.width = width; + image.height = height; + image.data = newImage.data; +} +function copyImage(srcImg, dstImg, srcPt, dstPt, size, channels) { + if (size.width === 0 || size.height === 0) { + return dstImg; + } + if (size.width > srcImg.width || + size.height > srcImg.height || + srcPt.x > srcImg.width - size.width || + srcPt.y > srcImg.height - size.height) { + throw new RangeError('out of range source coordinates for image copy'); + } + if (size.width > dstImg.width || + size.height > dstImg.height || + dstPt.x > dstImg.width - size.width || + dstPt.y > dstImg.height - size.height) { + throw new RangeError('out of range destination coordinates for image copy'); + } + const srcData = srcImg.data; + const dstData = dstImg.data; + if (srcData === dstData) + throw new Error('srcData equals dstData, so image is already copied'); + for (let y = 0; y < size.height; y++) { + const srcOffset = ((srcPt.y + y) * srcImg.width + srcPt.x) * channels; + const dstOffset = ((dstPt.y + y) * dstImg.width + dstPt.x) * channels; + for (let i = 0; i < size.width * channels; i++) { + dstData[dstOffset + i] = srcData[srcOffset + i]; + } + } + return dstImg; +} +/** + * An image with alpha color value + */ +class AlphaImage { + constructor(size, data) { + createImage(this, size, 1, data); + } + resize(size) { + resizeImage(this, size, 1); + } + clone() { + return new AlphaImage({ width: this.width, height: this.height }, new Uint8Array(this.data)); + } + static copy(srcImg, dstImg, srcPt, dstPt, size) { + copyImage(srcImg, dstImg, srcPt, dstPt, size, 1); + } +} +/** + * An object to store image data not premultiplied, because ImageData is not premultiplied. + * UNPACK_PREMULTIPLY_ALPHA_WEBGL must be used when uploading to a texture. + */ +class RGBAImage { + constructor(size, data) { + createImage(this, size, 4, data); + } + resize(size) { + resizeImage(this, size, 4); + } + replace(data, copy) { + if (copy) { + this.data.set(data); + } + else if (data instanceof Uint8ClampedArray) { + this.data = new Uint8Array(data.buffer); + } + else { + this.data = data; + } + } + clone() { + return new RGBAImage({ width: this.width, height: this.height }, new Uint8Array(this.data)); + } + static copy(srcImg, dstImg, srcPt, dstPt, size) { + copyImage(srcImg, dstImg, srcPt, dstPt, size, 4); + } +} +register('AlphaImage', AlphaImage); +register('RGBAImage', RGBAImage); + +/** + * Given an expression that should evaluate to a color ramp, + * return a RGBA image representing that ramp expression. + */ +function renderColorRamp(params) { + const evaluationGlobals = {}; + const width = params.resolution || 256; + const height = params.clips ? params.clips.length : 1; + const image = params.image || new RGBAImage({ width, height }); + if (!isPowerOfTwo(width)) + throw new Error(`width is not a power of 2 - ${width}`); + const renderPixel = (stride, index, progress) => { + evaluationGlobals[params.evaluationKey] = progress; + const pxColor = params.expression.evaluate(evaluationGlobals); + // the colors are being unpremultiplied because Color uses + // premultiplied values, and the Texture class expects unpremultiplied ones + image.data[stride + index + 0] = Math.floor(pxColor.r * 255 / pxColor.a); + image.data[stride + index + 1] = Math.floor(pxColor.g * 255 / pxColor.a); + image.data[stride + index + 2] = Math.floor(pxColor.b * 255 / pxColor.a); + image.data[stride + index + 3] = Math.floor(pxColor.a * 255); + }; + if (!params.clips) { + for (let i = 0, j = 0; i < width; i++, j += 4) { + const progress = i / (width - 1); + renderPixel(0, j, progress); + } + } + else { + for (let clip = 0, stride = 0; clip < height; ++clip, stride += width * 4) { + for (let i = 0, j = 0; i < width; i++, j += 4) { + // Remap progress between clips + const progress = i / (width - 1); + const { start, end } = params.clips[clip]; + const evaluationProgress = start * (1 - progress) + end * progress; + renderPixel(stride, j, evaluationProgress); + } + } + } + return image; +} + +const HEATMAP_FULL_RENDER_FBO_KEY = 'big-fb'; +/** + * A style layer that defines a heatmap + */ +class HeatmapStyleLayer extends StyleLayer { + createBucket(options) { + return new HeatmapBucket(options); + } + constructor(layer) { + super(layer, properties$7); + this.heatmapFbos = new Map(); + // make sure color ramp texture is generated for default heatmap color too + this._updateColorRamp(); + } + _handleSpecialPaintPropertyUpdate(name) { + if (name === 'heatmap-color') { + this._updateColorRamp(); + } + } + _updateColorRamp() { + const expression = this._transitionablePaint._values['heatmap-color'].value.expression; + this.colorRamp = renderColorRamp({ + expression, + evaluationKey: 'heatmapDensity', + image: this.colorRamp + }); + this.colorRampTexture = null; + } + resize() { + if (this.heatmapFbos.has(HEATMAP_FULL_RENDER_FBO_KEY)) { + this.heatmapFbos.delete(HEATMAP_FULL_RENDER_FBO_KEY); + } + } + queryRadius() { + return 0; + } + queryIntersectsFeature() { + return false; + } + hasOffscreenPass() { + return this.paint.get('heatmap-opacity') !== 0 && this.visibility !== 'none'; + } +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$6; +const getPaint$6 = () => paint$6 = paint$6 || new Properties({ + "hillshade-illumination-direction": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-illumination-direction"]), + "hillshade-illumination-anchor": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-illumination-anchor"]), + "hillshade-exaggeration": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-exaggeration"]), + "hillshade-shadow-color": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-shadow-color"]), + "hillshade-highlight-color": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-highlight-color"]), + "hillshade-accent-color": new DataConstantProperty(v8Spec["paint_hillshade"]["hillshade-accent-color"]), +}); +var properties$6 = ({ get paint() { return getPaint$6(); } }); + +class HillshadeStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$6); + } + hasOffscreenPass() { + return this.paint.get('hillshade-exaggeration') !== 0 && this.visibility !== 'none'; + } +} + +const layout$4 = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' } +], 4); +const { members: members$3, size: size$3, alignment: alignment$3 } = layout$4; + +function earcut(data, holeIndices, dim = 2) { + + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data.length; + let outerNode = linkedList(data, 0, outerLen, dim, true); + const triangles = []; + + if (!outerNode || outerNode.next === outerNode.prev) return triangles; + + let minX, minY, invSize; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = Infinity; + minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + + for (let i = dim; i < outerLen; i += dim) { + const x = data[i]; + const y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + let last; + + if (clockwise === (signedArea$1(data, start, end, dim) > 0)) { + for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); + } else { + for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + let p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + + let stop = ear; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + const prev = ear.prev; + const next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + triangles.push(prev.i, ear.i, next.i); // cut off the triangle + + removeNode(ear); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + const a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + let p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, invSize) { + const a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + const x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + // z-order range for the current triangle bbox; + const minZ = zOrder(x0, y0, minX, minY, invSize), + maxZ = zOrder(x1, y1, minX, minY, invSize); + + let p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles) { + let p = start; + do { + const a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i, p.i, b.i); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return filterPoints(p); +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + let a = start; + do { + let b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + let c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + const queue = []; + + for (let i = 0, len = holeIndices.length; i < len; i++) { + const start = holeIndices[i] * dim; + const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + const list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (let i = 0; i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + const bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + + const bridgeReverse = splitPolygon(bridge, hole); + + // filter collinear points around the cuts + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + let p = outerNode; + const hx = hole.x; + const hy = hole.y; + let qx = -Infinity; + let m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + const stop = m; + const mx = m.x; + const my = m.y; + let tanMin = Infinity; + + p = m; + + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if (locallyInside(p, hole) && + (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } while (p !== stop); + + return m; +} + +// whether sector in vertex m contains sector in vertex p in the same coordinates +function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, invSize) { + let p = start; + do { + if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + let numMerges; + let inSize = 1; + + do { + let p = list; + let e; + list = null; + let tail = null; + numMerges = 0; + + while (p) { + numMerges++; + let q = p; + let pSize = 0; + for (let i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + let qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + let p = start, + leftmost = start; + do { + if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && + (ax - px) * (by - py) >= (bx - px) * (ay - py) && + (bx - px) * (cy - py) >= (cx - px) * (by - py); +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges + (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors + equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + const o1 = sign(area(p1, q1, p2)); + const o2 = sign(area(p1, q1, q2)); + const o3 = sign(area(p2, q2, p1)); + const o4 = sign(area(p2, q2, q1)); + + if (o1 !== o2 && o3 !== o4) return true; // general case + + if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 + + return false; +} + +// for collinear points p, q, r, check if point q lies on segment pr +function onSegment(p, q, r) { + 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); +} + +function sign(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + let p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + let p = a; + let inside = false; + const px = (a.x + b.x) / 2; + const py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + const a2 = createNode(a.i, a.x, a.y), + b2 = createNode(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + const p = createNode(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function createNode(i, x, y) { + return { + i, // vertex index in coordinates array + x, y, // vertex coordinates + prev: null, // previous and next vertex nodes in a polygon ring + next: null, + z: 0, // z-order curve value + prevZ: null, // previous and next nodes in z-order + nextZ: null, + steiner: false // indicates whether this is a steiner point + }; +} + +function signedArea$1(data, start, end, dim) { + let sum = 0; + for (let i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +function hasPattern(type, layers, options) { + const patterns = options.patternDependencies; + let hasPattern = false; + for (const layer of layers) { + const patternProperty = layer.paint.get(`${type}-pattern`); + if (!patternProperty.isConstant()) { + hasPattern = true; + } + const constantPattern = patternProperty.constantOr(null); + if (constantPattern) { + hasPattern = true; + patterns[constantPattern.to] = true; + patterns[constantPattern.from] = true; + } + } + return hasPattern; +} +function addPatternDependencies(type, layers, patternFeature, zoom, options) { + const patterns = options.patternDependencies; + for (const layer of layers) { + const patternProperty = layer.paint.get(`${type}-pattern`); + const patternPropertyValue = patternProperty.value; + if (patternPropertyValue.kind !== 'constant') { + let min = patternPropertyValue.evaluate({ zoom: zoom - 1 }, patternFeature, {}, options.availableImages); + let mid = patternPropertyValue.evaluate({ zoom }, patternFeature, {}, options.availableImages); + let max = patternPropertyValue.evaluate({ zoom: zoom + 1 }, patternFeature, {}, options.availableImages); + min = min && min.name ? min.name : min; + mid = mid && mid.name ? mid.name : mid; + max = max && max.name ? max.name : max; + // add to patternDependencies + patterns[min] = true; + patterns[mid] = true; + patterns[max] = true; + // save for layout + patternFeature.patterns[layer.id] = { min, mid, max }; + } + } + return patternFeature; +} + +const EARCUT_MAX_RINGS$1 = 500; +class FillBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.patternFeatures = []; + this.layoutVertexArray = new FillLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.indexArray2 = new LineIndexArray(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.segments = new SegmentVector(); + this.segments2 = new SegmentVector(); + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + this.hasPattern = hasPattern('fill', this.layers, options); + const fillSortKey = this.layers[0].layout.get('fill-sort-key'); + const sortFeaturesByKey = !fillSortKey.isConstant(); + const bucketFeatures = []; + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const sortKey = sortFeaturesByKey ? + fillSortKey.evaluate(evaluationFeature, {}, canonical, options.availableImages) : + undefined; + const bucketFeature = { + id, + properties: feature.properties, + type: feature.type, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + patterns: {}, + sortKey + }; + bucketFeatures.push(bucketFeature); + } + if (sortFeaturesByKey) { + bucketFeatures.sort((a, b) => a.sortKey - b.sortKey); + } + for (const bucketFeature of bucketFeatures) { + const { geometry, index, sourceLayerIndex } = bucketFeature; + if (this.hasPattern) { + const patternFeature = addPatternDependencies('fill', this.layers, bucketFeature, this.zoom, options); + // pattern features are added only once the pattern is loaded into the image atlas + // so are stored during populate until later updated with positions by tile worker in addFeatures + this.patternFeatures.push(patternFeature); + } + else { + this.addFeature(bucketFeature, geometry, index, canonical, {}); + } + const feature = features[index].feature; + options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + addFeatures(options, canonical, imagePositions) { + for (const feature of this.patternFeatures) { + this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions); + } + } + isEmpty() { + return this.layoutVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$3); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + this.indexBuffer2 = context.createIndexBuffer(this.indexArray2); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.indexBuffer2.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + this.segments2.destroy(); + } + addFeature(feature, geometry, index, canonical, imagePositions) { + for (const polygon of classifyRings$1(geometry, EARCUT_MAX_RINGS$1)) { + let numVertices = 0; + for (const ring of polygon) { + numVertices += ring.length; + } + const triangleSegment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray); + const triangleIndex = triangleSegment.vertexLength; + const flattened = []; + const holeIndices = []; + for (const ring of polygon) { + if (ring.length === 0) { + continue; + } + if (ring !== polygon[0]) { + holeIndices.push(flattened.length / 2); + } + const lineSegment = this.segments2.prepareSegment(ring.length, this.layoutVertexArray, this.indexArray2); + const lineIndex = lineSegment.vertexLength; + this.layoutVertexArray.emplaceBack(ring[0].x, ring[0].y); + this.indexArray2.emplaceBack(lineIndex + ring.length - 1, lineIndex); + flattened.push(ring[0].x); + flattened.push(ring[0].y); + for (let i = 1; i < ring.length; i++) { + this.layoutVertexArray.emplaceBack(ring[i].x, ring[i].y); + this.indexArray2.emplaceBack(lineIndex + i - 1, lineIndex + i); + flattened.push(ring[i].x); + flattened.push(ring[i].y); + } + lineSegment.vertexLength += ring.length; + lineSegment.primitiveLength += ring.length; + } + const indices = earcut(flattened, holeIndices); + for (let i = 0; i < indices.length; i += 3) { + this.indexArray.emplaceBack(triangleIndex + indices[i], triangleIndex + indices[i + 1], triangleIndex + indices[i + 2]); + } + triangleSegment.vertexLength += numVertices; + triangleSegment.primitiveLength += indices.length / 3; + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical); + } +} +register('FillBucket', FillBucket, { omit: ['layers', 'patternFeatures'] }); + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout$3; +const getLayout$2 = () => layout$3 = layout$3 || new Properties({ + "fill-sort-key": new DataDrivenProperty(v8Spec["layout_fill"]["fill-sort-key"]), +}); +let paint$5; +const getPaint$5 = () => paint$5 = paint$5 || new Properties({ + "fill-antialias": new DataConstantProperty(v8Spec["paint_fill"]["fill-antialias"]), + "fill-opacity": new DataDrivenProperty(v8Spec["paint_fill"]["fill-opacity"]), + "fill-color": new DataDrivenProperty(v8Spec["paint_fill"]["fill-color"]), + "fill-outline-color": new DataDrivenProperty(v8Spec["paint_fill"]["fill-outline-color"]), + "fill-translate": new DataConstantProperty(v8Spec["paint_fill"]["fill-translate"]), + "fill-translate-anchor": new DataConstantProperty(v8Spec["paint_fill"]["fill-translate-anchor"]), + "fill-pattern": new CrossFadedDataDrivenProperty(v8Spec["paint_fill"]["fill-pattern"]), +}); +var properties$5 = ({ get paint() { return getPaint$5(); }, get layout() { return getLayout$2(); } }); + +class FillStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$5); + } + recalculate(parameters, availableImages) { + super.recalculate(parameters, availableImages); + const outlineColor = this.paint._values['fill-outline-color']; + if (outlineColor.value.kind === 'constant' && outlineColor.value.value === undefined) { + this.paint._values['fill-outline-color'] = this.paint._values['fill-color']; + } + } + createBucket(parameters) { + return new FillBucket(parameters); + } + queryRadius() { + return translateDistance(this.paint.get('fill-translate')); + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits) { + const translatedPolygon = translate$1(queryGeometry, this.paint.get('fill-translate'), this.paint.get('fill-translate-anchor'), transform.angle, pixelsToTileUnits); + return polygonIntersectsMultiPolygon(translatedPolygon, geometry); + } + isTileClipped() { + return true; + } +} + +const layout$2 = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' }, + { name: 'a_normal_ed', components: 4, type: 'Int16' }, +], 4); +const centroidAttributes = createLayout([ + { name: 'a_centroid', components: 2, type: 'Int16' } +], 4); +const { members: members$2, size: size$2, alignment: alignment$2 } = layout$2; + +var vectorTile = {}; + +var Point = pointGeometry; + +var vectortilefeature = VectorTileFeature$1; + +function VectorTileFeature$1(pbf, end, extent, keys, values) { + // Public + this.properties = {}; + this.extent = extent; + this.type = 0; + + // Private + this._pbf = pbf; + this._geometry = -1; + this._keys = keys; + this._values = values; + + pbf.readFields(readFeature, this, end); +} + +function readFeature(tag, feature, pbf) { + if (tag == 1) feature.id = pbf.readVarint(); + else if (tag == 2) readTag(pbf, feature); + else if (tag == 3) feature.type = pbf.readVarint(); + else if (tag == 4) feature._geometry = pbf.pos; +} + +function readTag(pbf, feature) { + var end = pbf.readVarint() + pbf.pos; + + while (pbf.pos < end) { + var key = feature._keys[pbf.readVarint()], + value = feature._values[pbf.readVarint()]; + feature.properties[key] = value; + } +} + +VectorTileFeature$1.types = ['Unknown', 'Point', 'LineString', 'Polygon']; + +VectorTileFeature$1.prototype.loadGeometry = function() { + var pbf = this._pbf; + pbf.pos = this._geometry; + + var end = pbf.readVarint() + pbf.pos, + cmd = 1, + length = 0, + x = 0, + y = 0, + lines = [], + line; + + while (pbf.pos < end) { + if (length <= 0) { + var cmdLen = pbf.readVarint(); + cmd = cmdLen & 0x7; + length = cmdLen >> 3; + } + + length--; + + if (cmd === 1 || cmd === 2) { + x += pbf.readSVarint(); + y += pbf.readSVarint(); + + if (cmd === 1) { // moveTo + if (line) lines.push(line); + line = []; + } + + line.push(new Point(x, y)); + + } else if (cmd === 7) { + + // Workaround for https://github.com/mapbox/mapnik-vector-tile/issues/90 + if (line) { + line.push(line[0].clone()); // closePolygon + } + + } else { + throw new Error('unknown command ' + cmd); + } + } + + if (line) lines.push(line); + + return lines; +}; + +VectorTileFeature$1.prototype.bbox = function() { + var pbf = this._pbf; + pbf.pos = this._geometry; + + var end = pbf.readVarint() + pbf.pos, + cmd = 1, + length = 0, + x = 0, + y = 0, + x1 = Infinity, + x2 = -Infinity, + y1 = Infinity, + y2 = -Infinity; + + while (pbf.pos < end) { + if (length <= 0) { + var cmdLen = pbf.readVarint(); + cmd = cmdLen & 0x7; + length = cmdLen >> 3; + } + + length--; + + if (cmd === 1 || cmd === 2) { + x += pbf.readSVarint(); + y += pbf.readSVarint(); + if (x < x1) x1 = x; + if (x > x2) x2 = x; + if (y < y1) y1 = y; + if (y > y2) y2 = y; + + } else if (cmd !== 7) { + throw new Error('unknown command ' + cmd); + } + } + + return [x1, y1, x2, y2]; +}; + +VectorTileFeature$1.prototype.toGeoJSON = function(x, y, z) { + var size = this.extent * Math.pow(2, z), + x0 = this.extent * x, + y0 = this.extent * y, + coords = this.loadGeometry(), + type = VectorTileFeature$1.types[this.type], + i, j; + + function project(line) { + for (var j = 0; j < line.length; j++) { + var p = line[j], y2 = 180 - (p.y + y0) * 360 / size; + line[j] = [ + (p.x + x0) * 360 / size - 180, + 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90 + ]; + } + } + + switch (this.type) { + case 1: + var points = []; + for (i = 0; i < coords.length; i++) { + points[i] = coords[i][0]; + } + coords = points; + project(coords); + break; + + case 2: + for (i = 0; i < coords.length; i++) { + project(coords[i]); + } + break; + + case 3: + coords = classifyRings(coords); + for (i = 0; i < coords.length; i++) { + for (j = 0; j < coords[i].length; j++) { + project(coords[i][j]); + } + } + break; + } + + if (coords.length === 1) { + coords = coords[0]; + } else { + type = 'Multi' + type; + } + + var result = { + type: "Feature", + geometry: { + type: type, + coordinates: coords + }, + properties: this.properties + }; + + if ('id' in this) { + result.id = this.id; + } + + return result; +}; + +// classifies an array of rings into polygons with outer rings and holes + +function classifyRings(rings) { + var len = rings.length; + + if (len <= 1) return [rings]; + + var polygons = [], + polygon, + ccw; + + for (var i = 0; i < len; i++) { + var area = signedArea(rings[i]); + if (area === 0) continue; + + if (ccw === undefined) ccw = area < 0; + + if (ccw === area < 0) { + if (polygon) polygons.push(polygon); + polygon = [rings[i]]; + + } else { + polygon.push(rings[i]); + } + } + if (polygon) polygons.push(polygon); + + return polygons; +} + +function signedArea(ring) { + var sum = 0; + for (var i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + return sum; +} + +var VectorTileFeature = vectortilefeature; + +var vectortilelayer = VectorTileLayer$1; + +function VectorTileLayer$1(pbf, end) { + // Public + this.version = 1; + this.name = null; + this.extent = 4096; + this.length = 0; + + // Private + this._pbf = pbf; + this._keys = []; + this._values = []; + this._features = []; + + pbf.readFields(readLayer, this, end); + + this.length = this._features.length; +} + +function readLayer(tag, layer, pbf) { + if (tag === 15) layer.version = pbf.readVarint(); + else if (tag === 1) layer.name = pbf.readString(); + else if (tag === 5) layer.extent = pbf.readVarint(); + else if (tag === 2) layer._features.push(pbf.pos); + else if (tag === 3) layer._keys.push(pbf.readString()); + else if (tag === 4) layer._values.push(readValueMessage(pbf)); +} + +function readValueMessage(pbf) { + var value = null, + end = pbf.readVarint() + pbf.pos; + + while (pbf.pos < end) { + var tag = pbf.readVarint() >> 3; + + value = tag === 1 ? pbf.readString() : + tag === 2 ? pbf.readFloat() : + tag === 3 ? pbf.readDouble() : + tag === 4 ? pbf.readVarint64() : + tag === 5 ? pbf.readVarint() : + tag === 6 ? pbf.readSVarint() : + tag === 7 ? pbf.readBoolean() : null; + } + + return value; +} + +// return feature `i` from this layer as a `VectorTileFeature` +VectorTileLayer$1.prototype.feature = function(i) { + if (i < 0 || i >= this._features.length) throw new Error('feature index out of bounds'); + + this._pbf.pos = this._features[i]; + + var end = this._pbf.readVarint() + this._pbf.pos; + return new VectorTileFeature(this._pbf, end, this.extent, this._keys, this._values); +}; + +var VectorTileLayer = vectortilelayer; + +var vectortile = VectorTile; + +function VectorTile(pbf, end) { + this.layers = pbf.readFields(readTile, {}, end); +} + +function readTile(tag, layers, pbf) { + if (tag === 3) { + var layer = new VectorTileLayer(pbf, pbf.readVarint() + pbf.pos); + if (layer.length) layers[layer.name] = layer; + } +} + +vectorTile.VectorTile = vectortile; +vectorTile.VectorTileFeature = vectortilefeature; +vectorTile.VectorTileLayer = vectortilelayer; + +const vectorTileFeatureTypes$2 = vectorTile.VectorTileFeature.types; +const EARCUT_MAX_RINGS = 500; +const FACTOR = Math.pow(2, 13); +function addVertex$1(vertexArray, x, y, nx, ny, nz, t, e) { + vertexArray.emplaceBack( + // a_pos + x, y, + // a_normal_ed: 3-component normal and 1-component edgedistance + Math.floor(nx * FACTOR) * 2 + t, ny * FACTOR * 2, nz * FACTOR * 2, + // edgedistance (used for wrapping patterns around extrusion sides) + Math.round(e)); +} +class FillExtrusionBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.layoutVertexArray = new FillExtrusionLayoutArray(); + this.centroidVertexArray = new PosArray(); + this.indexArray = new TriangleIndexArray(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.segments = new SegmentVector(); + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + this.features = []; + this.hasPattern = hasPattern('fill-extrusion', this.layers, options); + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const bucketFeature = { + id, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + properties: feature.properties, + type: feature.type, + patterns: {} + }; + if (this.hasPattern) { + this.features.push(addPatternDependencies('fill-extrusion', this.layers, bucketFeature, this.zoom, options)); + } + else { + this.addFeature(bucketFeature, bucketFeature.geometry, index, canonical, {}); + } + options.featureIndex.insert(feature, bucketFeature.geometry, index, sourceLayerIndex, this.index, true); + } + } + addFeatures(options, canonical, imagePositions) { + for (const feature of this.features) { + const { geometry } = feature; + this.addFeature(feature, geometry, feature.index, canonical, imagePositions); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + isEmpty() { + return this.layoutVertexArray.length === 0 && this.centroidVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$2); + this.centroidVertexBuffer = context.createVertexBuffer(this.centroidVertexArray, centroidAttributes.members, true); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + this.centroidVertexBuffer.destroy(); + } + addFeature(feature, geometry, index, canonical, imagePositions) { + for (const polygon of classifyRings$1(geometry, EARCUT_MAX_RINGS)) { + const centroid = { x: 0, y: 0, vertexCount: 0 }; + let numVertices = 0; + for (const ring of polygon) { + numVertices += ring.length; + } + let segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray); + for (const ring of polygon) { + if (ring.length === 0) { + continue; + } + if (isEntirelyOutside(ring)) { + continue; + } + let edgeDistance = 0; + for (let p = 0; p < ring.length; p++) { + const p1 = ring[p]; + if (p >= 1) { + const p2 = ring[p - 1]; + if (!isBoundaryEdge(p1, p2)) { + if (segment.vertexLength + 4 > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) { + segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray); + } + const perp = p1.sub(p2)._perp()._unit(); + const dist = p2.dist(p1); + if (edgeDistance + dist > 32768) + edgeDistance = 0; + addVertex$1(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 0, edgeDistance); + addVertex$1(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 1, edgeDistance); + centroid.x += 2 * p1.x; + centroid.y += 2 * p1.y; + centroid.vertexCount += 2; + edgeDistance += dist; + addVertex$1(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 0, edgeDistance); + addVertex$1(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 1, edgeDistance); + centroid.x += 2 * p2.x; + centroid.y += 2 * p2.y; + centroid.vertexCount += 2; + const bottomRight = segment.vertexLength; + // ┌──────┐ + // │ 0 1 │ Counter-clockwise winding order. + // │ │ Triangle 1: 0 => 2 => 1 + // │ 2 3 │ Triangle 2: 1 => 2 => 3 + // └──────┘ + this.indexArray.emplaceBack(bottomRight, bottomRight + 2, bottomRight + 1); + this.indexArray.emplaceBack(bottomRight + 1, bottomRight + 2, bottomRight + 3); + segment.vertexLength += 4; + segment.primitiveLength += 2; + } + } + } + } + if (segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) { + segment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray); + } + //Only triangulate and draw the area of the feature if it is a polygon + //Other feature types (e.g. LineString) do not have area, so triangulation is pointless / undefined + if (vectorTileFeatureTypes$2[feature.type] !== 'Polygon') + continue; + const flattened = []; + const holeIndices = []; + const triangleIndex = segment.vertexLength; + for (const ring of polygon) { + if (ring.length === 0) { + continue; + } + if (ring !== polygon[0]) { + holeIndices.push(flattened.length / 2); + } + for (let i = 0; i < ring.length; i++) { + const p = ring[i]; + addVertex$1(this.layoutVertexArray, p.x, p.y, 0, 0, 1, 1, 0); + centroid.x += p.x; + centroid.y += p.y; + centroid.vertexCount += 1; + flattened.push(p.x); + flattened.push(p.y); + } + } + const indices = earcut(flattened, holeIndices); + for (let j = 0; j < indices.length; j += 3) { + // Counter-clockwise winding order. + this.indexArray.emplaceBack(triangleIndex + indices[j], triangleIndex + indices[j + 2], triangleIndex + indices[j + 1]); + } + segment.primitiveLength += indices.length / 3; + segment.vertexLength += numVertices; + // remember polygon centroid to calculate elevation in GPU + for (let i = 0; i < centroid.vertexCount; i++) { + const averageX = Math.floor(centroid.x / centroid.vertexCount); + const averageY = Math.floor(centroid.y / centroid.vertexCount); + this.centroidVertexArray.emplaceBack(averageX, averageY); + } + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical); + } +} +register('FillExtrusionBucket', FillExtrusionBucket, { omit: ['layers', 'features'] }); +function isBoundaryEdge(p1, p2) { + return (p1.x === p2.x && (p1.x < 0 || p1.x > EXTENT)) || + (p1.y === p2.y && (p1.y < 0 || p1.y > EXTENT)); +} +function isEntirelyOutside(ring) { + return ring.every(p => p.x < 0) || + ring.every(p => p.x > EXTENT) || + ring.every(p => p.y < 0) || + ring.every(p => p.y > EXTENT); +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$4; +const getPaint$4 = () => paint$4 = paint$4 || new Properties({ + "fill-extrusion-opacity": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-opacity"]), + "fill-extrusion-color": new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-color"]), + "fill-extrusion-translate": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-translate"]), + "fill-extrusion-translate-anchor": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]), + "fill-extrusion-pattern": new CrossFadedDataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-pattern"]), + "fill-extrusion-height": new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-height"]), + "fill-extrusion-base": new DataDrivenProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-base"]), + "fill-extrusion-vertical-gradient": new DataConstantProperty(v8Spec["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"]), +}); +var properties$4 = ({ get paint() { return getPaint$4(); } }); + +class FillExtrusionStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$4); + } + createBucket(parameters) { + return new FillExtrusionBucket(parameters); + } + queryRadius() { + return translateDistance(this.paint.get('fill-extrusion-translate')); + } + is3D() { + return true; + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits, pixelPosMatrix) { + const translatedPolygon = translate$1(queryGeometry, this.paint.get('fill-extrusion-translate'), this.paint.get('fill-extrusion-translate-anchor'), transform.angle, pixelsToTileUnits); + const height = this.paint.get('fill-extrusion-height').evaluate(feature, featureState); + const base = this.paint.get('fill-extrusion-base').evaluate(feature, featureState); + const projectedQueryGeometry = projectQueryGeometry(translatedPolygon, pixelPosMatrix, transform, 0); + const projected = projectExtrusion(geometry, base, height, pixelPosMatrix); + const projectedBase = projected[0]; + const projectedTop = projected[1]; + return checkIntersection(projectedBase, projectedTop, projectedQueryGeometry); + } +} +function dot(a, b) { + return a.x * b.x + a.y * b.y; +} +function getIntersectionDistance(projectedQueryGeometry, projectedFace) { + if (projectedQueryGeometry.length === 1) { + // For point queries calculate the z at which the point intersects the face + // using barycentric coordinates. + // Find the barycentric coordinates of the projected point within the first + // triangle of the face, using only the xy plane. It doesn't matter if the + // point is outside the first triangle because all the triangles in the face + // are in the same plane. + // + // Check whether points are coincident and use other points if they are. + let i = 0; + const a = projectedFace[i++]; + let b; + while (!b || a.equals(b)) { + b = projectedFace[i++]; + if (!b) + return Infinity; + } + // Loop until point `c` is not colinear with points `a` and `b`. + for (; i < projectedFace.length; i++) { + const c = projectedFace[i]; + const p = projectedQueryGeometry[0]; + const ab = b.sub(a); + const ac = c.sub(a); + const ap = p.sub(a); + const dotABAB = dot(ab, ab); + const dotABAC = dot(ab, ac); + const dotACAC = dot(ac, ac); + const dotAPAB = dot(ap, ab); + const dotAPAC = dot(ap, ac); + const denom = dotABAB * dotACAC - dotABAC * dotABAC; + const v = (dotACAC * dotAPAB - dotABAC * dotAPAC) / denom; + const w = (dotABAB * dotAPAC - dotABAC * dotAPAB) / denom; + const u = 1 - v - w; + // Use the barycentric weighting along with the original triangle z coordinates to get the point of intersection. + const distance = a.z * u + b.z * v + c.z * w; + if (isFinite(distance)) + return distance; + } + return Infinity; + } + else { + // The counts as closest is less clear when the query is a box. This + // returns the distance to the nearest point on the face, whether it is + // within the query or not. It could be more correct to return the + // distance to the closest point within the query box but this would be + // more complicated and expensive to calculate with little benefit. + let closestDistance = Infinity; + for (const p of projectedFace) { + closestDistance = Math.min(closestDistance, p.z); + } + return closestDistance; + } +} +function checkIntersection(projectedBase, projectedTop, projectedQueryGeometry) { + let closestDistance = Infinity; + if (polygonIntersectsMultiPolygon(projectedQueryGeometry, projectedTop)) { + closestDistance = getIntersectionDistance(projectedQueryGeometry, projectedTop[0]); + } + for (let r = 0; r < projectedTop.length; r++) { + const ringTop = projectedTop[r]; + const ringBase = projectedBase[r]; + for (let p = 0; p < ringTop.length - 1; p++) { + const topA = ringTop[p]; + const topB = ringTop[p + 1]; + const baseA = ringBase[p]; + const baseB = ringBase[p + 1]; + const face = [topA, topB, baseB, baseA, topA]; + if (polygonIntersectsPolygon(projectedQueryGeometry, face)) { + closestDistance = Math.min(closestDistance, getIntersectionDistance(projectedQueryGeometry, face)); + } + } + } + return closestDistance === Infinity ? false : closestDistance; +} +/* + * Project the geometry using matrix `m`. This is essentially doing + * `vec4.transformMat4([], [p.x, p.y, z, 1], m)` but the multiplication + * is inlined so that parts of the projection that are the same across + * different points can only be done once. This produced a measurable + * performance improvement. + */ +function projectExtrusion(geometry, zBase, zTop, m) { + const projectedBase = []; + const projectedTop = []; + const baseXZ = m[8] * zBase; + const baseYZ = m[9] * zBase; + const baseZZ = m[10] * zBase; + const baseWZ = m[11] * zBase; + const topXZ = m[8] * zTop; + const topYZ = m[9] * zTop; + const topZZ = m[10] * zTop; + const topWZ = m[11] * zTop; + for (const r of geometry) { + const ringBase = []; + const ringTop = []; + for (const p of r) { + const x = p.x; + const y = p.y; + const sX = m[0] * x + m[4] * y + m[12]; + const sY = m[1] * x + m[5] * y + m[13]; + const sZ = m[2] * x + m[6] * y + m[14]; + const sW = m[3] * x + m[7] * y + m[15]; + const baseX = sX + baseXZ; + const baseY = sY + baseYZ; + const baseZ = sZ + baseZZ; + const baseW = sW + baseWZ; + const topX = sX + topXZ; + const topY = sY + topYZ; + const topZ = sZ + topZZ; + const topW = sW + topWZ; + const b = new Point$2(baseX / baseW, baseY / baseW); + b.z = baseZ / baseW; + ringBase.push(b); + const t = new Point$2(topX / topW, topY / topW); + t.z = topZ / topW; + ringTop.push(t); + } + projectedBase.push(ringBase); + projectedTop.push(ringTop); + } + return [projectedBase, projectedTop]; +} +function projectQueryGeometry(queryGeometry, pixelPosMatrix, transform, z) { + const projectedQueryGeometry = []; + for (const p of queryGeometry) { + const v = [p.x, p.y, z, 1]; + transformMat4(v, v, pixelPosMatrix); + projectedQueryGeometry.push(new Point$2(v[0] / v[3], v[1] / v[3])); + } + return projectedQueryGeometry; +} + +const lineLayoutAttributes = createLayout([ + { name: 'a_pos_normal', components: 2, type: 'Int16' }, + { name: 'a_data', components: 4, type: 'Uint8' } +], 4); +const { members: members$1, size: size$1, alignment: alignment$1 } = lineLayoutAttributes; + +const lineLayoutAttributesExt = createLayout([ + { name: 'a_uv_x', components: 1, type: 'Float32' }, + { name: 'a_split_index', components: 1, type: 'Float32' }, +]); +const { members, size, alignment } = lineLayoutAttributesExt; + +const vectorTileFeatureTypes$1 = vectorTile.VectorTileFeature.types; +// NOTE ON EXTRUDE SCALE: +// scale the extrusion vector so that the normal length is this value. +// contains the "texture" normals (-1..1). this is distinct from the extrude +// normals for line joins, because the x-value remains 0 for the texture +// normal array, while the extrude normal actually moves the vertex to create +// the acute/bevelled line join. +const EXTRUDE_SCALE = 63; +/* + * Sharp corners cause dashed lines to tilt because the distance along the line + * is the same at both the inner and outer corners. To improve the appearance of + * dashed lines we add extra points near sharp corners so that a smaller part + * of the line is tilted. + * + * COS_HALF_SHARP_CORNER controls how sharp a corner has to be for us to add an + * extra vertex. The default is 75 degrees. + * + * The newly created vertices are placed SHARP_CORNER_OFFSET pixels from the corner. + */ +const COS_HALF_SHARP_CORNER = Math.cos(75 / 2 * (Math.PI / 180)); +const SHARP_CORNER_OFFSET = 15; +// Angle per triangle for approximating round line joins. +const DEG_PER_TRIANGLE = 20; +// The number of bits that is used to store the line distance in the buffer. +const LINE_DISTANCE_BUFFER_BITS = 15; +// We don't have enough bits for the line distance as we'd like to have, so +// use this value to scale the line distance (in tile units) down to a smaller +// value. This lets us store longer distances while sacrificing precision. +const LINE_DISTANCE_SCALE = 1 / 2; +// The maximum line distance, in tile units, that fits in the buffer. +const MAX_LINE_DISTANCE = Math.pow(2, LINE_DISTANCE_BUFFER_BITS - 1) / LINE_DISTANCE_SCALE; +/** + * @internal + * Line bucket class + */ +class LineBucket { + constructor(options) { + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.hasPattern = false; + this.patternFeatures = []; + this.lineClipsArray = []; + this.gradients = {}; + this.layers.forEach(layer => { + this.gradients[layer.id] = {}; + }); + this.layoutVertexArray = new LineLayoutArray(); + this.layoutVertexArray2 = new LineExtLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom); + this.segments = new SegmentVector(); + this.maxLineLength = 0; + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + } + populate(features, options, canonical) { + this.hasPattern = hasPattern('line', this.layers, options); + const lineSortKey = this.layers[0].layout.get('line-sort-key'); + const sortFeaturesByKey = !lineSortKey.isConstant(); + const bucketFeatures = []; + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = this.layers[0]._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) + continue; + const sortKey = sortFeaturesByKey ? + lineSortKey.evaluate(evaluationFeature, {}, canonical) : + undefined; + const bucketFeature = { + id, + properties: feature.properties, + type: feature.type, + sourceLayerIndex, + index, + geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature), + patterns: {}, + sortKey + }; + bucketFeatures.push(bucketFeature); + } + if (sortFeaturesByKey) { + bucketFeatures.sort((a, b) => { + return (a.sortKey) - (b.sortKey); + }); + } + for (const bucketFeature of bucketFeatures) { + const { geometry, index, sourceLayerIndex } = bucketFeature; + if (this.hasPattern) { + const patternBucketFeature = addPatternDependencies('line', this.layers, bucketFeature, this.zoom, options); + // pattern features are added only once the pattern is loaded into the image atlas + // so are stored during populate until later updated with positions by tile worker in addFeatures + this.patternFeatures.push(patternBucketFeature); + } + else { + this.addFeature(bucketFeature, geometry, index, canonical, {}); + } + const feature = features[index].feature; + options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions); + } + addFeatures(options, canonical, imagePositions) { + for (const feature of this.patternFeatures) { + this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions); + } + } + isEmpty() { + return this.layoutVertexArray.length === 0; + } + uploadPending() { + return !this.uploaded || this.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded) { + if (this.layoutVertexArray2.length !== 0) { + this.layoutVertexBuffer2 = context.createVertexBuffer(this.layoutVertexArray2, members); + } + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$1); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + } + this.programConfigurations.upload(context); + this.uploaded = true; + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + } + lineFeatureClips(feature) { + if (!!feature.properties && Object.prototype.hasOwnProperty.call(feature.properties, 'mapbox_clip_start') && Object.prototype.hasOwnProperty.call(feature.properties, 'mapbox_clip_end')) { + const start = +feature.properties['mapbox_clip_start']; + const end = +feature.properties['mapbox_clip_end']; + return { start, end }; + } + } + addFeature(feature, geometry, index, canonical, imagePositions) { + const layout = this.layers[0].layout; + const join = layout.get('line-join').evaluate(feature, {}); + const cap = layout.get('line-cap'); + const miterLimit = layout.get('line-miter-limit'); + const roundLimit = layout.get('line-round-limit'); + this.lineClips = this.lineFeatureClips(feature); + for (const line of geometry) { + this.addLine(line, feature, join, cap, miterLimit, roundLimit); + } + this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical); + } + addLine(vertices, feature, join, cap, miterLimit, roundLimit) { + this.distance = 0; + this.scaledDistance = 0; + this.totalDistance = 0; + if (this.lineClips) { + this.lineClipsArray.push(this.lineClips); + // Calculate the total distance, in tile units, of this tiled line feature + for (let i = 0; i < vertices.length - 1; i++) { + this.totalDistance += vertices[i].dist(vertices[i + 1]); + } + this.updateScaledDistance(); + this.maxLineLength = Math.max(this.maxLineLength, this.totalDistance); + } + const isPolygon = vectorTileFeatureTypes$1[feature.type] === 'Polygon'; + // If the line has duplicate vertices at the ends, adjust start/length to remove them. + let len = vertices.length; + while (len >= 2 && vertices[len - 1].equals(vertices[len - 2])) { + len--; + } + let first = 0; + while (first < len - 1 && vertices[first].equals(vertices[first + 1])) { + first++; + } + // Ignore invalid geometry. + if (len < (isPolygon ? 3 : 2)) + return; + if (join === 'bevel') + miterLimit = 1.05; + const sharpCornerOffset = this.overscaling <= 16 ? + SHARP_CORNER_OFFSET * EXTENT / (512 * this.overscaling) : + 0; + // we could be more precise, but it would only save a negligible amount of space + const segment = this.segments.prepareSegment(len * 10, this.layoutVertexArray, this.indexArray); + let currentVertex; + let prevVertex; + let nextVertex; + let prevNormal; + let nextNormal; + // the last two vertices added + this.e1 = this.e2 = -1; + if (isPolygon) { + currentVertex = vertices[len - 2]; + nextNormal = vertices[first].sub(currentVertex)._unit()._perp(); + } + for (let i = first; i < len; i++) { + nextVertex = i === len - 1 ? + (isPolygon ? vertices[first + 1] : undefined) : // if it's a polygon, treat the last vertex like the first + vertices[i + 1]; // just the next vertex + // if two consecutive vertices exist, skip the current one + if (nextVertex && vertices[i].equals(nextVertex)) + continue; + if (nextNormal) + prevNormal = nextNormal; + if (currentVertex) + prevVertex = currentVertex; + currentVertex = vertices[i]; + // Calculate the normal towards the next vertex in this line. In case + // there is no next vertex, pretend that the line is continuing straight, + // meaning that we are just using the previous normal. + nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal; + // If we still don't have a previous normal, this is the beginning of a + // non-closed line, so we're doing a straight "join". + prevNormal = prevNormal || nextNormal; + // Determine the normal of the join extrusion. It is the angle bisector + // of the segments between the previous line and the next line. + // In the case of 180° angles, the prev and next normals cancel each other out: + // prevNormal + nextNormal = (0, 0), its magnitude is 0, so the unit vector would be + // undefined. In that case, we're keeping the joinNormal at (0, 0), so that the cosHalfAngle + // below will also become 0 and miterLength will become Infinity. + let joinNormal = prevNormal.add(nextNormal); + if (joinNormal.x !== 0 || joinNormal.y !== 0) { + joinNormal._unit(); + } + /* joinNormal prevNormal + * ↖ ↑ + * .________. prevVertex + * | + * nextNormal ← | currentVertex + * | + * nextVertex ! + * + */ + // calculate cosines of the angle (and its half) using dot product + const cosAngle = prevNormal.x * nextNormal.x + prevNormal.y * nextNormal.y; + const cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y; + // Calculate the length of the miter (the ratio of the miter to the width) + // as the inverse of cosine of the angle between next and join normals + const miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity; + // approximate angle from cosine + const approxAngle = 2 * Math.sqrt(2 - 2 * cosHalfAngle); + const isSharpCorner = cosHalfAngle < COS_HALF_SHARP_CORNER && prevVertex && nextVertex; + const lineTurnsLeft = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0; + if (isSharpCorner && i > first) { + const prevSegmentLength = currentVertex.dist(prevVertex); + if (prevSegmentLength > 2 * sharpCornerOffset) { + const newPrevVertex = currentVertex.sub(currentVertex.sub(prevVertex)._mult(sharpCornerOffset / prevSegmentLength)._round()); + this.updateDistance(prevVertex, newPrevVertex); + this.addCurrentVertex(newPrevVertex, prevNormal, 0, 0, segment); + prevVertex = newPrevVertex; + } + } + // The join if a middle vertex, otherwise the cap. + const middleVertex = prevVertex && nextVertex; + let currentJoin = middleVertex ? join : isPolygon ? 'butt' : cap; + if (middleVertex && currentJoin === 'round') { + if (miterLength < roundLimit) { + currentJoin = 'miter'; + } + else if (miterLength <= 2) { + currentJoin = 'fakeround'; + } + } + if (currentJoin === 'miter' && miterLength > miterLimit) { + currentJoin = 'bevel'; + } + if (currentJoin === 'bevel') { + // The maximum extrude length is 128 / 63 = 2 times the width of the line + // so if miterLength >= 2 we need to draw a different type of bevel here. + if (miterLength > 2) + currentJoin = 'flipbevel'; + // If the miterLength is really small and the line bevel wouldn't be visible, + // just draw a miter join to save a triangle. + if (miterLength < miterLimit) + currentJoin = 'miter'; + } + // Calculate how far along the line the currentVertex is + if (prevVertex) + this.updateDistance(prevVertex, currentVertex); + if (currentJoin === 'miter') { + joinNormal._mult(miterLength); + this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); + } + else if (currentJoin === 'flipbevel') { + // miter is too big, flip the direction to make a beveled join + if (miterLength > 100) { + // Almost parallel lines + joinNormal = nextNormal.mult(-1); + } + else { + const bevelLength = miterLength * prevNormal.add(nextNormal).mag() / prevNormal.sub(nextNormal).mag(); + joinNormal._perp()._mult(bevelLength * (lineTurnsLeft ? -1 : 1)); + } + this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); + this.addCurrentVertex(currentVertex, joinNormal.mult(-1), 0, 0, segment); + } + else if (currentJoin === 'bevel' || currentJoin === 'fakeround') { + const offset = -Math.sqrt(miterLength * miterLength - 1); + const offsetA = lineTurnsLeft ? offset : 0; + const offsetB = lineTurnsLeft ? 0 : offset; + // Close previous segment with a bevel + if (prevVertex) { + this.addCurrentVertex(currentVertex, prevNormal, offsetA, offsetB, segment); + } + if (currentJoin === 'fakeround') { + // The join angle is sharp enough that a round join would be visible. + // Bevel joins fill the gap between segments with a single pie slice triangle. + // Create a round join by adding multiple pie slices. The join isn't actually round, but + // it looks like it is at the sizes we render lines at. + // pick the number of triangles for approximating round join by based on the angle between normals + const n = Math.round((approxAngle * 180 / Math.PI) / DEG_PER_TRIANGLE); + for (let m = 1; m < n; m++) { + let t = m / n; + if (t !== 0.5) { + // approximate spherical interpolation https://observablehq.com/@mourner/approximating-geometric-slerp + const t2 = t - 0.5; + const A = 1.0904 + cosAngle * (-3.2452 + cosAngle * (3.55645 - cosAngle * 1.43519)); + const B = 0.848013 + cosAngle * (-1.06021 + cosAngle * 0.215638); + t = t + t * t2 * (t - 1) * (A * t2 * t2 + B); + } + const extrude = nextNormal.sub(prevNormal)._mult(t)._add(prevNormal)._unit()._mult(lineTurnsLeft ? -1 : 1); + this.addHalfVertex(currentVertex, extrude.x, extrude.y, false, lineTurnsLeft, 0, segment); + } + } + if (nextVertex) { + // Start next segment + this.addCurrentVertex(currentVertex, nextNormal, -offsetA, -offsetB, segment); + } + } + else if (currentJoin === 'butt') { + this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); // butt cap + } + else if (currentJoin === 'square') { + const offset = prevVertex ? 1 : -1; // closing or starting square cap + this.addCurrentVertex(currentVertex, joinNormal, offset, offset, segment); + } + else if (currentJoin === 'round') { + if (prevVertex) { + // Close previous segment with butt + this.addCurrentVertex(currentVertex, prevNormal, 0, 0, segment); + // Add round cap or linejoin at end of segment + this.addCurrentVertex(currentVertex, prevNormal, 1, 1, segment, true); + } + if (nextVertex) { + // Add round cap before first segment + this.addCurrentVertex(currentVertex, nextNormal, -1, -1, segment, true); + // Start next segment with a butt + this.addCurrentVertex(currentVertex, nextNormal, 0, 0, segment); + } + } + if (isSharpCorner && i < len - 1) { + const nextSegmentLength = currentVertex.dist(nextVertex); + if (nextSegmentLength > 2 * sharpCornerOffset) { + const newCurrentVertex = currentVertex.add(nextVertex.sub(currentVertex)._mult(sharpCornerOffset / nextSegmentLength)._round()); + this.updateDistance(currentVertex, newCurrentVertex); + this.addCurrentVertex(newCurrentVertex, nextNormal, 0, 0, segment); + currentVertex = newCurrentVertex; + } + } + } + } + /** + * Add two vertices to the buffers. + * + * @param p - the line vertex to add buffer vertices for + * @param normal - vertex normal + * @param endLeft - extrude to shift the left vertex along the line + * @param endRight - extrude to shift the left vertex along the line + * @param segment - the segment object to add the vertex to + * @param round - whether this is a round cap + */ + addCurrentVertex(p, normal, endLeft, endRight, segment, round = false) { + // left and right extrude vectors, perpendicularly shifted by endLeft/endRight + const leftX = normal.x + normal.y * endLeft; + const leftY = normal.y - normal.x * endLeft; + const rightX = -normal.x + normal.y * endRight; + const rightY = -normal.y - normal.x * endRight; + this.addHalfVertex(p, leftX, leftY, round, false, endLeft, segment); + this.addHalfVertex(p, rightX, rightY, round, true, -endRight, segment); + // There is a maximum "distance along the line" that we can store in the buffers. + // When we get close to the distance, reset it to zero and add the vertex again with + // a distance of zero. The max distance is determined by the number of bits we allocate + // to `linesofar`. + if (this.distance > MAX_LINE_DISTANCE / 2 && this.totalDistance === 0) { + this.distance = 0; + this.updateScaledDistance(); + this.addCurrentVertex(p, normal, endLeft, endRight, segment, round); + } + } + addHalfVertex({ x, y }, extrudeX, extrudeY, round, up, dir, segment) { + const totalDistance = this.lineClips ? this.scaledDistance * (MAX_LINE_DISTANCE - 1) : this.scaledDistance; + // scale down so that we can store longer distances while sacrificing precision. + const linesofarScaled = totalDistance * LINE_DISTANCE_SCALE; + this.layoutVertexArray.emplaceBack( + // a_pos_normal + // Encode round/up the least significant bits + (x << 1) + (round ? 1 : 0), (y << 1) + (up ? 1 : 0), + // a_data + // add 128 to store a byte in an unsigned byte + Math.round(EXTRUDE_SCALE * extrudeX) + 128, Math.round(EXTRUDE_SCALE * extrudeY) + 128, + // Encode the -1/0/1 direction value into the first two bits of .z of a_data. + // Combine it with the lower 6 bits of `linesofarScaled` (shifted by 2 bits to make + // room for the direction value). The upper 8 bits of `linesofarScaled` are placed in + // the `w` component. + ((dir === 0 ? 0 : (dir < 0 ? -1 : 1)) + 1) | ((linesofarScaled & 0x3F) << 2), linesofarScaled >> 6); + // Constructs a second vertex buffer with higher precision line progress + if (this.lineClips) { + const progressRealigned = this.scaledDistance - this.lineClips.start; + const endClipRealigned = this.lineClips.end - this.lineClips.start; + const uvX = progressRealigned / endClipRealigned; + this.layoutVertexArray2.emplaceBack(uvX, this.lineClipsArray.length); + } + const e = segment.vertexLength++; + if (this.e1 >= 0 && this.e2 >= 0) { + this.indexArray.emplaceBack(this.e1, this.e2, e); + segment.primitiveLength++; + } + if (up) { + this.e2 = e; + } + else { + this.e1 = e; + } + } + updateScaledDistance() { + // Knowing the ratio of the full linestring covered by this tiled feature, as well + // as the total distance (in tile units) of this tiled feature, and the distance + // (in tile units) of the current vertex, we can determine the relative distance + // of this vertex along the full linestring feature and scale it to [0, 2^15) + this.scaledDistance = this.lineClips ? + this.lineClips.start + (this.lineClips.end - this.lineClips.start) * this.distance / this.totalDistance : + this.distance; + } + updateDistance(prev, next) { + this.distance += prev.dist(next); + this.updateScaledDistance(); + } +} +register('LineBucket', LineBucket, { omit: ['layers', 'patternFeatures'] }); + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout$1; +const getLayout$1 = () => layout$1 = layout$1 || new Properties({ + "line-cap": new DataConstantProperty(v8Spec["layout_line"]["line-cap"]), + "line-join": new DataDrivenProperty(v8Spec["layout_line"]["line-join"]), + "line-miter-limit": new DataConstantProperty(v8Spec["layout_line"]["line-miter-limit"]), + "line-round-limit": new DataConstantProperty(v8Spec["layout_line"]["line-round-limit"]), + "line-sort-key": new DataDrivenProperty(v8Spec["layout_line"]["line-sort-key"]), +}); +let paint$3; +const getPaint$3 = () => paint$3 = paint$3 || new Properties({ + "line-opacity": new DataDrivenProperty(v8Spec["paint_line"]["line-opacity"]), + "line-color": new DataDrivenProperty(v8Spec["paint_line"]["line-color"]), + "line-translate": new DataConstantProperty(v8Spec["paint_line"]["line-translate"]), + "line-translate-anchor": new DataConstantProperty(v8Spec["paint_line"]["line-translate-anchor"]), + "line-width": new DataDrivenProperty(v8Spec["paint_line"]["line-width"]), + "line-gap-width": new DataDrivenProperty(v8Spec["paint_line"]["line-gap-width"]), + "line-offset": new DataDrivenProperty(v8Spec["paint_line"]["line-offset"]), + "line-blur": new DataDrivenProperty(v8Spec["paint_line"]["line-blur"]), + "line-dasharray": new CrossFadedProperty(v8Spec["paint_line"]["line-dasharray"]), + "line-pattern": new CrossFadedDataDrivenProperty(v8Spec["paint_line"]["line-pattern"]), + "line-gradient": new ColorRampProperty(v8Spec["paint_line"]["line-gradient"]), +}); +var properties$3 = ({ get paint() { return getPaint$3(); }, get layout() { return getLayout$1(); } }); + +class LineFloorwidthProperty extends DataDrivenProperty { + possiblyEvaluate(value, parameters) { + parameters = new EvaluationParameters(Math.floor(parameters.zoom), { + now: parameters.now, + fadeDuration: parameters.fadeDuration, + zoomHistory: parameters.zoomHistory, + transition: parameters.transition + }); + return super.possiblyEvaluate(value, parameters); + } + evaluate(value, globals, feature, featureState) { + globals = extend({}, globals, { zoom: Math.floor(globals.zoom) }); + return super.evaluate(value, globals, feature, featureState); + } +} +let lineFloorwidthProperty; +class LineStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$3); + this.gradientVersion = 0; + if (!lineFloorwidthProperty) { + lineFloorwidthProperty = + new LineFloorwidthProperty(properties$3.paint.properties['line-width'].specification); + lineFloorwidthProperty.useIntegerZoom = true; + } + } + _handleSpecialPaintPropertyUpdate(name) { + if (name === 'line-gradient') { + const expression = this.gradientExpression(); + if (isZoomExpression(expression)) { + this.stepInterpolant = expression._styleExpression.expression instanceof Step; + } + else { + this.stepInterpolant = false; + } + this.gradientVersion = (this.gradientVersion + 1) % Number.MAX_SAFE_INTEGER; + } + } + gradientExpression() { + return this._transitionablePaint._values['line-gradient'].value.expression; + } + recalculate(parameters, availableImages) { + super.recalculate(parameters, availableImages); + this.paint._values['line-floorwidth'] = + lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values['line-width'].value, parameters); + } + createBucket(parameters) { + return new LineBucket(parameters); + } + queryRadius(bucket) { + const lineBucket = bucket; + const width = getLineWidth(getMaximumPaintValue('line-width', this, lineBucket), getMaximumPaintValue('line-gap-width', this, lineBucket)); + const offset = getMaximumPaintValue('line-offset', this, lineBucket); + return width / 2 + Math.abs(offset) + translateDistance(this.paint.get('line-translate')); + } + queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits) { + const translatedPolygon = translate$1(queryGeometry, this.paint.get('line-translate'), this.paint.get('line-translate-anchor'), transform.angle, pixelsToTileUnits); + const halfWidth = pixelsToTileUnits / 2 * getLineWidth(this.paint.get('line-width').evaluate(feature, featureState), this.paint.get('line-gap-width').evaluate(feature, featureState)); + const lineOffset = this.paint.get('line-offset').evaluate(feature, featureState); + if (lineOffset) { + geometry = offsetLine(geometry, lineOffset * pixelsToTileUnits); + } + return polygonIntersectsBufferedMultiLine(translatedPolygon, geometry, halfWidth); + } + isTileClipped() { + return true; + } +} +function getLineWidth(lineWidth, lineGapWidth) { + if (lineGapWidth > 0) { + return lineGapWidth + 2 * lineWidth; + } + else { + return lineWidth; + } +} + +const symbolLayoutAttributes = createLayout([ + { name: 'a_pos_offset', components: 4, type: 'Int16' }, + { name: 'a_data', components: 4, type: 'Uint16' }, + { name: 'a_pixeloffset', components: 4, type: 'Int16' } +], 4); +const dynamicLayoutAttributes = createLayout([ + { name: 'a_projected_pos', components: 3, type: 'Float32' } +], 4); +createLayout([ + { name: 'a_fade_opacity', components: 1, type: 'Uint32' } +], 4); +const collisionVertexAttributes = createLayout([ + { name: 'a_placed', components: 2, type: 'Uint8' }, + { name: 'a_shift', components: 2, type: 'Float32' }, + { name: 'a_box_real', components: 2, type: 'Int16' }, +]); +createLayout([ + // the box is centered around the anchor point + { type: 'Int16', name: 'anchorPointX' }, + { type: 'Int16', name: 'anchorPointY' }, + // distances to the edges from the anchor + { type: 'Int16', name: 'x1' }, + { type: 'Int16', name: 'y1' }, + { type: 'Int16', name: 'x2' }, + { type: 'Int16', name: 'y2' }, + // the index of the feature in the original vectortile + { type: 'Uint32', name: 'featureIndex' }, + // the source layer the feature appears in + { type: 'Uint16', name: 'sourceLayerIndex' }, + // the bucket the feature appears in + { type: 'Uint16', name: 'bucketIndex' }, +]); +const collisionBoxLayout = createLayout([ + { name: 'a_pos', components: 2, type: 'Int16' }, + { name: 'a_anchor_pos', components: 2, type: 'Int16' }, + { name: 'a_extrude', components: 2, type: 'Int16' } +], 4); +const collisionCircleLayout = createLayout([ + { name: 'a_pos', components: 2, type: 'Float32' }, + { name: 'a_radius', components: 1, type: 'Float32' }, + { name: 'a_flags', components: 2, type: 'Int16' } +], 4); +createLayout([ + { name: 'triangle', components: 3, type: 'Uint16' }, +]); +createLayout([ + { type: 'Int16', name: 'anchorX' }, + { type: 'Int16', name: 'anchorY' }, + { type: 'Uint16', name: 'glyphStartIndex' }, + { type: 'Uint16', name: 'numGlyphs' }, + { type: 'Uint32', name: 'vertexStartIndex' }, + { type: 'Uint32', name: 'lineStartIndex' }, + { type: 'Uint32', name: 'lineLength' }, + { type: 'Uint16', name: 'segment' }, + { type: 'Uint16', name: 'lowerSize' }, + { type: 'Uint16', name: 'upperSize' }, + { type: 'Float32', name: 'lineOffsetX' }, + { type: 'Float32', name: 'lineOffsetY' }, + { type: 'Uint8', name: 'writingMode' }, + { type: 'Uint8', name: 'placedOrientation' }, + { type: 'Uint8', name: 'hidden' }, + { type: 'Uint32', name: 'crossTileID' }, + { type: 'Int16', name: 'associatedIconIndex' } +]); +createLayout([ + { type: 'Int16', name: 'anchorX' }, + { type: 'Int16', name: 'anchorY' }, + { type: 'Int16', name: 'rightJustifiedTextSymbolIndex' }, + { type: 'Int16', name: 'centerJustifiedTextSymbolIndex' }, + { type: 'Int16', name: 'leftJustifiedTextSymbolIndex' }, + { type: 'Int16', name: 'verticalPlacedTextSymbolIndex' }, + { type: 'Int16', name: 'placedIconSymbolIndex' }, + { type: 'Int16', name: 'verticalPlacedIconSymbolIndex' }, + { type: 'Uint16', name: 'key' }, + { type: 'Uint16', name: 'textBoxStartIndex' }, + { type: 'Uint16', name: 'textBoxEndIndex' }, + { type: 'Uint16', name: 'verticalTextBoxStartIndex' }, + { type: 'Uint16', name: 'verticalTextBoxEndIndex' }, + { type: 'Uint16', name: 'iconBoxStartIndex' }, + { type: 'Uint16', name: 'iconBoxEndIndex' }, + { type: 'Uint16', name: 'verticalIconBoxStartIndex' }, + { type: 'Uint16', name: 'verticalIconBoxEndIndex' }, + { type: 'Uint16', name: 'featureIndex' }, + { type: 'Uint16', name: 'numHorizontalGlyphVertices' }, + { type: 'Uint16', name: 'numVerticalGlyphVertices' }, + { type: 'Uint16', name: 'numIconVertices' }, + { type: 'Uint16', name: 'numVerticalIconVertices' }, + { type: 'Uint16', name: 'useRuntimeCollisionCircles' }, + { type: 'Uint32', name: 'crossTileID' }, + { type: 'Float32', name: 'textBoxScale' }, + { type: 'Float32', name: 'collisionCircleDiameter' }, + { type: 'Uint16', name: 'textAnchorOffsetStartIndex' }, + { type: 'Uint16', name: 'textAnchorOffsetEndIndex' } +]); +createLayout([ + { type: 'Float32', name: 'offsetX' } +]); +createLayout([ + { type: 'Int16', name: 'x' }, + { type: 'Int16', name: 'y' }, + { type: 'Int16', name: 'tileUnitDistanceFromAnchor' } +]); +createLayout([ + { type: 'Uint16', name: 'textAnchor' }, + { type: 'Float32', components: 2, name: 'textOffset' } +]); + +function transformTextInternal(text, layer, feature) { + const transform = layer.layout.get('text-transform').evaluate(feature, {}); + if (transform === 'uppercase') { + text = text.toLocaleUpperCase(); + } + else if (transform === 'lowercase') { + text = text.toLocaleLowerCase(); + } + if (rtlWorkerPlugin.applyArabicShaping) { + text = rtlWorkerPlugin.applyArabicShaping(text); + } + return text; +} +function transformText(text, layer, feature) { + text.sections.forEach(section => { + section.text = transformTextInternal(section.text, layer, feature); + }); + return text; +} + +function mergeLines(features) { + const leftIndex = {}; + const rightIndex = {}; + const mergedFeatures = []; + let mergedIndex = 0; + function add(k) { + mergedFeatures.push(features[k]); + mergedIndex++; + } + function mergeFromRight(leftKey, rightKey, geom) { + const i = rightIndex[leftKey]; + delete rightIndex[leftKey]; + rightIndex[rightKey] = i; + mergedFeatures[i].geometry[0].pop(); + mergedFeatures[i].geometry[0] = mergedFeatures[i].geometry[0].concat(geom[0]); + return i; + } + function mergeFromLeft(leftKey, rightKey, geom) { + const i = leftIndex[rightKey]; + delete leftIndex[rightKey]; + leftIndex[leftKey] = i; + mergedFeatures[i].geometry[0].shift(); + mergedFeatures[i].geometry[0] = geom[0].concat(mergedFeatures[i].geometry[0]); + return i; + } + function getKey(text, geom, onRight) { + const point = onRight ? geom[0][geom[0].length - 1] : geom[0][0]; + return `${text}:${point.x}:${point.y}`; + } + for (let k = 0; k < features.length; k++) { + const feature = features[k]; + const geom = feature.geometry; + const text = feature.text ? feature.text.toString() : null; + if (!text) { + add(k); + continue; + } + const leftKey = getKey(text, geom), rightKey = getKey(text, geom, true); + if ((leftKey in rightIndex) && (rightKey in leftIndex) && (rightIndex[leftKey] !== leftIndex[rightKey])) { + // found lines with the same text adjacent to both ends of the current line, merge all three + const j = mergeFromLeft(leftKey, rightKey, geom); + const i = mergeFromRight(leftKey, rightKey, mergedFeatures[j].geometry); + delete leftIndex[leftKey]; + delete rightIndex[rightKey]; + rightIndex[getKey(text, mergedFeatures[i].geometry, true)] = i; + mergedFeatures[j].geometry = null; + } + else if (leftKey in rightIndex) { + // found mergeable line adjacent to the start of the current line, merge + mergeFromRight(leftKey, rightKey, geom); + } + else if (rightKey in leftIndex) { + // found mergeable line adjacent to the end of the current line, merge + mergeFromLeft(leftKey, rightKey, geom); + } + else { + // no adjacent lines, add as a new item + add(k); + leftIndex[leftKey] = mergedIndex - 1; + rightIndex[rightKey] = mergedIndex - 1; + } + } + return mergedFeatures.filter((f) => f.geometry); +} + +const verticalizedCharacterMap = { + '!': '︕', + '#': '#', + '$': '$', + '%': '%', + '&': '&', + '(': '︵', + ')': '︶', + '*': '*', + '+': '+', + ',': '︐', + '-': '︲', + '.': '・', + '/': '/', + ':': '︓', + ';': '︔', + '<': '︿', + '=': '=', + '>': '﹀', + '?': '︖', + '@': '@', + '[': '﹇', + '\\': '\', + ']': '﹈', + '^': '^', + '_': '︳', + '`': '`', + '{': '︷', + '|': '―', + '}': '︸', + '~': '~', + '¢': '¢', + '£': '£', + '¥': '¥', + '¦': '¦', + '¬': '¬', + '¯': ' ̄', + '–': '︲', + '—': '︱', + '‘': '﹃', + '’': '﹄', + '“': '﹁', + '”': '﹂', + '…': '︙', + '‧': '・', + '₩': '₩', + '、': '︑', + '。': '︒', + '〈': '︿', + '〉': '﹀', + '《': '︽', + '》': '︾', + '「': '﹁', + '」': '﹂', + '『': '﹃', + '』': '﹄', + '【': '︻', + '】': '︼', + '〔': '︹', + '〕': '︺', + '〖': '︗', + '〗': '︘', + '!': '︕', + '(': '︵', + ')': '︶', + ',': '︐', + '-': '︲', + '.': '・', + ':': '︓', + ';': '︔', + '<': '︿', + '>': '﹀', + '?': '︖', + '[': '﹇', + ']': '﹈', + '_': '︳', + '{': '︷', + '|': '―', + '}': '︸', + '⦅': '︵', + '⦆': '︶', + '。': '︒', + '「': '﹁', + '」': '﹂' +}; +function verticalizePunctuation(input) { + let output = ''; + for (let i = 0; i < input.length; i++) { + const nextCharCode = input.charCodeAt(i + 1) || null; + const prevCharCode = input.charCodeAt(i - 1) || null; + const canReplacePunctuation = ((!nextCharCode || !charHasRotatedVerticalOrientation(nextCharCode) || verticalizedCharacterMap[input[i + 1]]) && + (!prevCharCode || !charHasRotatedVerticalOrientation(prevCharCode) || verticalizedCharacterMap[input[i - 1]])); + if (canReplacePunctuation && verticalizedCharacterMap[input[i]]) { + output += verticalizedCharacterMap[input[i]]; + } + else { + output += input[i]; + } + } + return output; +} + +// ONE_EM constant used to go between "em" units used in style spec and "points" used internally for layout +var ONE_EM = 24; + +var ieee754$1 = {}; + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + +ieee754$1.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = (nBytes * 8) - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +}; + +ieee754$1.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = (nBytes * 8) - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +}; + +var pbf = Pbf; + +var ieee754 = ieee754$1; + +function Pbf(buf) { + this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0); + this.pos = 0; + this.type = 0; + this.length = this.buf.length; +} + +Pbf.Varint = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum +Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64 +Pbf.Bytes = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields +Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32 + +var SHIFT_LEFT_32 = (1 << 16) * (1 << 16), + SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32; + +// Threshold chosen based on both benchmarking and knowledge about browser string +// data structures (which currently switch structure types at 12 bytes or more) +var TEXT_DECODER_MIN_LENGTH = 12; +var utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8'); + +Pbf.prototype = { + + destroy: function() { + this.buf = null; + }, + + // === READING ================================================================= + + readFields: function(readField, result, end) { + end = end || this.length; + + while (this.pos < end) { + var val = this.readVarint(), + tag = val >> 3, + startPos = this.pos; + + this.type = val & 0x7; + readField(tag, result, this); + + if (this.pos === startPos) this.skip(val); + } + return result; + }, + + readMessage: function(readField, result) { + return this.readFields(readField, result, this.readVarint() + this.pos); + }, + + readFixed32: function() { + var val = readUInt32(this.buf, this.pos); + this.pos += 4; + return val; + }, + + readSFixed32: function() { + var val = readInt32(this.buf, this.pos); + this.pos += 4; + return val; + }, + + // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed) + + readFixed64: function() { + var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; + this.pos += 8; + return val; + }, + + readSFixed64: function() { + var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; + this.pos += 8; + return val; + }, + + readFloat: function() { + var val = ieee754.read(this.buf, this.pos, true, 23, 4); + this.pos += 4; + return val; + }, + + readDouble: function() { + var val = ieee754.read(this.buf, this.pos, true, 52, 8); + this.pos += 8; + return val; + }, + + readVarint: function(isSigned) { + var buf = this.buf, + val, b; + + b = buf[this.pos++]; val = b & 0x7f; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val; + b = buf[this.pos]; val |= (b & 0x0f) << 28; + + return readVarintRemainder(val, isSigned, this); + }, + + readVarint64: function() { // for compatibility with v2.0.1 + return this.readVarint(true); + }, + + readSVarint: function() { + var num = this.readVarint(); + return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding + }, + + readBoolean: function() { + return Boolean(this.readVarint()); + }, + + readString: function() { + var end = this.readVarint() + this.pos; + var pos = this.pos; + this.pos = end; + + if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) { + // longer strings are fast with the built-in browser TextDecoder API + return readUtf8TextDecoder(this.buf, pos, end); + } + // short strings are fast with our custom implementation + return readUtf8(this.buf, pos, end); + }, + + readBytes: function() { + var end = this.readVarint() + this.pos, + buffer = this.buf.subarray(this.pos, end); + this.pos = end; + return buffer; + }, + + // verbose for performance reasons; doesn't affect gzipped size + + readPackedVarint: function(arr, isSigned) { + if (this.type !== Pbf.Bytes) return arr.push(this.readVarint(isSigned)); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readVarint(isSigned)); + return arr; + }, + readPackedSVarint: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSVarint()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSVarint()); + return arr; + }, + readPackedBoolean: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readBoolean()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readBoolean()); + return arr; + }, + readPackedFloat: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFloat()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFloat()); + return arr; + }, + readPackedDouble: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readDouble()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readDouble()); + return arr; + }, + readPackedFixed32: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFixed32()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFixed32()); + return arr; + }, + readPackedSFixed32: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed32()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSFixed32()); + return arr; + }, + readPackedFixed64: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFixed64()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFixed64()); + return arr; + }, + readPackedSFixed64: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed64()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSFixed64()); + return arr; + }, + + skip: function(val) { + var type = val & 0x7; + if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {} + else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos; + else if (type === Pbf.Fixed32) this.pos += 4; + else if (type === Pbf.Fixed64) this.pos += 8; + else throw new Error('Unimplemented type: ' + type); + }, + + // === WRITING ================================================================= + + writeTag: function(tag, type) { + this.writeVarint((tag << 3) | type); + }, + + realloc: function(min) { + var length = this.length || 16; + + while (length < this.pos + min) length *= 2; + + if (length !== this.length) { + var buf = new Uint8Array(length); + buf.set(this.buf); + this.buf = buf; + this.length = length; + } + }, + + finish: function() { + this.length = this.pos; + this.pos = 0; + return this.buf.subarray(0, this.length); + }, + + writeFixed32: function(val) { + this.realloc(4); + writeInt32(this.buf, val, this.pos); + this.pos += 4; + }, + + writeSFixed32: function(val) { + this.realloc(4); + writeInt32(this.buf, val, this.pos); + this.pos += 4; + }, + + writeFixed64: function(val) { + this.realloc(8); + writeInt32(this.buf, val & -1, this.pos); + writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4); + this.pos += 8; + }, + + writeSFixed64: function(val) { + this.realloc(8); + writeInt32(this.buf, val & -1, this.pos); + writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4); + this.pos += 8; + }, + + writeVarint: function(val) { + val = +val || 0; + + if (val > 0xfffffff || val < 0) { + writeBigVarint(val, this); + return; + } + + this.realloc(4); + + this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = (val >>> 7) & 0x7f; + }, + + writeSVarint: function(val) { + this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2); + }, + + writeBoolean: function(val) { + this.writeVarint(Boolean(val)); + }, + + writeString: function(str) { + str = String(str); + this.realloc(str.length * 4); + + this.pos++; // reserve 1 byte for short string length + + var startPos = this.pos; + // write the string directly to the buffer and see how much was written + this.pos = writeUtf8(this.buf, str, this.pos); + var len = this.pos - startPos; + + if (len >= 0x80) makeRoomForExtraLength(startPos, len, this); + + // finally, write the message length in the reserved place and restore the position + this.pos = startPos - 1; + this.writeVarint(len); + this.pos += len; + }, + + writeFloat: function(val) { + this.realloc(4); + ieee754.write(this.buf, val, this.pos, true, 23, 4); + this.pos += 4; + }, + + writeDouble: function(val) { + this.realloc(8); + ieee754.write(this.buf, val, this.pos, true, 52, 8); + this.pos += 8; + }, + + writeBytes: function(buffer) { + var len = buffer.length; + this.writeVarint(len); + this.realloc(len); + for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i]; + }, + + writeRawMessage: function(fn, obj) { + this.pos++; // reserve 1 byte for short message length + + // write the message directly to the buffer and see how much was written + var startPos = this.pos; + fn(obj, this); + var len = this.pos - startPos; + + if (len >= 0x80) makeRoomForExtraLength(startPos, len, this); + + // finally, write the message length in the reserved place and restore the position + this.pos = startPos - 1; + this.writeVarint(len); + this.pos += len; + }, + + writeMessage: function(tag, fn, obj) { + this.writeTag(tag, Pbf.Bytes); + this.writeRawMessage(fn, obj); + }, + + writePackedVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedVarint, arr); }, + writePackedSVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSVarint, arr); }, + writePackedBoolean: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedBoolean, arr); }, + writePackedFloat: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFloat, arr); }, + writePackedDouble: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedDouble, arr); }, + writePackedFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed32, arr); }, + writePackedSFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr); }, + writePackedFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed64, arr); }, + writePackedSFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr); }, + + writeBytesField: function(tag, buffer) { + this.writeTag(tag, Pbf.Bytes); + this.writeBytes(buffer); + }, + writeFixed32Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeFixed32(val); + }, + writeSFixed32Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeSFixed32(val); + }, + writeFixed64Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeFixed64(val); + }, + writeSFixed64Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeSFixed64(val); + }, + writeVarintField: function(tag, val) { + this.writeTag(tag, Pbf.Varint); + this.writeVarint(val); + }, + writeSVarintField: function(tag, val) { + this.writeTag(tag, Pbf.Varint); + this.writeSVarint(val); + }, + writeStringField: function(tag, str) { + this.writeTag(tag, Pbf.Bytes); + this.writeString(str); + }, + writeFloatField: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeFloat(val); + }, + writeDoubleField: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeDouble(val); + }, + writeBooleanField: function(tag, val) { + this.writeVarintField(tag, Boolean(val)); + } +}; + +function readVarintRemainder(l, s, p) { + var buf = p.buf, + h, b; + + b = buf[p.pos++]; h = (b & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s); + + throw new Error('Expected varint not more than 10 bytes'); +} + +function readPackedEnd(pbf) { + return pbf.type === Pbf.Bytes ? + pbf.readVarint() + pbf.pos : pbf.pos + 1; +} + +function toNum(low, high, isSigned) { + if (isSigned) { + return high * 0x100000000 + (low >>> 0); + } + + return ((high >>> 0) * 0x100000000) + (low >>> 0); +} + +function writeBigVarint(val, pbf) { + var low, high; + + if (val >= 0) { + low = (val % 0x100000000) | 0; + high = (val / 0x100000000) | 0; + } else { + low = ~(-val % 0x100000000); + high = ~(-val / 0x100000000); + + if (low ^ 0xffffffff) { + low = (low + 1) | 0; + } else { + low = 0; + high = (high + 1) | 0; + } + } + + if (val >= 0x10000000000000000 || val < -0x10000000000000000) { + throw new Error('Given varint doesn\'t fit into 10 bytes'); + } + + pbf.realloc(10); + + writeBigVarintLow(low, high, pbf); + writeBigVarintHigh(high, pbf); +} + +function writeBigVarintLow(low, high, pbf) { + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos] = low & 0x7f; +} + +function writeBigVarintHigh(high, pbf) { + var lsb = (high & 0x07) << 4; + + pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f; +} + +function makeRoomForExtraLength(startPos, len, pbf) { + var extraLen = + len <= 0x3fff ? 1 : + len <= 0x1fffff ? 2 : + len <= 0xfffffff ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7)); + + // if 1 byte isn't enough for encoding message length, shift the data to the right + pbf.realloc(extraLen); + for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i]; +} + +function writePackedVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]); } +function writePackedSVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); } +function writePackedFloat(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); } +function writePackedDouble(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); } +function writePackedBoolean(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); } +function writePackedFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); } +function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); } +function writePackedFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); } +function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); } + +// Buffer code below from https://github.com/feross/buffer, MIT-licensed + +function readUInt32(buf, pos) { + return ((buf[pos]) | + (buf[pos + 1] << 8) | + (buf[pos + 2] << 16)) + + (buf[pos + 3] * 0x1000000); +} + +function writeInt32(buf, val, pos) { + buf[pos] = val; + buf[pos + 1] = (val >>> 8); + buf[pos + 2] = (val >>> 16); + buf[pos + 3] = (val >>> 24); +} + +function readInt32(buf, pos) { + return ((buf[pos]) | + (buf[pos + 1] << 8) | + (buf[pos + 2] << 16)) + + (buf[pos + 3] << 24); +} + +function readUtf8(buf, pos, end) { + var str = ''; + var i = pos; + + while (i < end) { + var b0 = buf[i]; + var c = null; // codepoint + var bytesPerSequence = + b0 > 0xEF ? 4 : + b0 > 0xDF ? 3 : + b0 > 0xBF ? 2 : 1; + + if (i + bytesPerSequence > end) break; + + var b1, b2, b3; + + if (bytesPerSequence === 1) { + if (b0 < 0x80) { + c = b0; + } + } else if (bytesPerSequence === 2) { + b1 = buf[i + 1]; + if ((b1 & 0xC0) === 0x80) { + c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F); + if (c <= 0x7F) { + c = null; + } + } + } else if (bytesPerSequence === 3) { + b1 = buf[i + 1]; + b2 = buf[i + 2]; + if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) { + c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F); + if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) { + c = null; + } + } + } else if (bytesPerSequence === 4) { + b1 = buf[i + 1]; + b2 = buf[i + 2]; + b3 = buf[i + 3]; + if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) { + c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F); + if (c <= 0xFFFF || c >= 0x110000) { + c = null; + } + } + } + + if (c === null) { + c = 0xFFFD; + bytesPerSequence = 1; + + } else if (c > 0xFFFF) { + c -= 0x10000; + str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800); + c = 0xDC00 | c & 0x3FF; + } + + str += String.fromCharCode(c); + i += bytesPerSequence; + } + + return str; +} + +function readUtf8TextDecoder(buf, pos, end) { + return utf8TextDecoder.decode(buf.subarray(pos, end)); +} + +function writeUtf8(buf, str, pos) { + for (var i = 0, c, lead; i < str.length; i++) { + c = str.charCodeAt(i); // code point + + if (c > 0xD7FF && c < 0xE000) { + if (lead) { + if (c < 0xDC00) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + lead = c; + continue; + } else { + c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000; + lead = null; + } + } else { + if (c > 0xDBFF || (i + 1 === str.length)) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + } else { + lead = c; + } + continue; + } + } else if (lead) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + lead = null; + } + + if (c < 0x80) { + buf[pos++] = c; + } else { + if (c < 0x800) { + buf[pos++] = c >> 0x6 | 0xC0; + } else { + if (c < 0x10000) { + buf[pos++] = c >> 0xC | 0xE0; + } else { + buf[pos++] = c >> 0x12 | 0xF0; + buf[pos++] = c >> 0xC & 0x3F | 0x80; + } + buf[pos++] = c >> 0x6 & 0x3F | 0x80; + } + buf[pos++] = c & 0x3F | 0x80; + } + } + return pos; +} + +var Protobuf = /*@__PURE__*/getDefaultExportFromCjs$1(pbf); + +const border$1 = 3; +function readFontstacks(tag, glyphs, pbf) { + if (tag === 1) { + pbf.readMessage(readFontstack, glyphs); + } +} +function readFontstack(tag, glyphs, pbf) { + if (tag === 3) { + const { id, bitmap, width, height, left, top, advance } = pbf.readMessage(readGlyph, {}); + glyphs.push({ + id, + bitmap: new AlphaImage({ + width: width + 2 * border$1, + height: height + 2 * border$1 + }, bitmap), + metrics: { width, height, left, top, advance } + }); + } +} +function readGlyph(tag, glyph, pbf) { + if (tag === 1) + glyph.id = pbf.readVarint(); + else if (tag === 2) + glyph.bitmap = pbf.readBytes(); + else if (tag === 3) + glyph.width = pbf.readVarint(); + else if (tag === 4) + glyph.height = pbf.readVarint(); + else if (tag === 5) + glyph.left = pbf.readSVarint(); + else if (tag === 6) + glyph.top = pbf.readSVarint(); + else if (tag === 7) + glyph.advance = pbf.readVarint(); +} +function parseGlyphPbf(data) { + return new Protobuf(data).readFields(readFontstacks, []); +} +const GLYPH_PBF_BORDER = border$1; + +function potpack(boxes) { + + // calculate total box area and maximum box width + let area = 0; + let maxWidth = 0; + + for (const box of boxes) { + area += box.w * box.h; + maxWidth = Math.max(maxWidth, box.w); + } + + // sort the boxes for insertion by height, descending + boxes.sort((a, b) => b.h - a.h); + + // aim for a squarish resulting container, + // slightly adjusted for sub-100% space utilization + const startWidth = Math.max(Math.ceil(Math.sqrt(area / 0.95)), maxWidth); + + // start with a single empty space, unbounded at the bottom + const spaces = [{x: 0, y: 0, w: startWidth, h: Infinity}]; + + let width = 0; + let height = 0; + + for (const box of boxes) { + // look through spaces backwards so that we check smaller spaces first + for (let i = spaces.length - 1; i >= 0; i--) { + const space = spaces[i]; + + // look for empty spaces that can accommodate the current box + if (box.w > space.w || box.h > space.h) continue; + + // found the space; add the box to its top-left corner + // |-------|-------| + // | box | | + // |_______| | + // | space | + // |_______________| + box.x = space.x; + box.y = space.y; + + height = Math.max(height, box.y + box.h); + width = Math.max(width, box.x + box.w); + + if (box.w === space.w && box.h === space.h) { + // space matches the box exactly; remove it + const last = spaces.pop(); + if (i < spaces.length) spaces[i] = last; + + } else if (box.h === space.h) { + // space matches the box height; update it accordingly + // |-------|---------------| + // | box | updated space | + // |_______|_______________| + space.x += box.w; + space.w -= box.w; + + } else if (box.w === space.w) { + // space matches the box width; update it accordingly + // |---------------| + // | box | + // |_______________| + // | updated space | + // |_______________| + space.y += box.h; + space.h -= box.h; + + } else { + // otherwise the box splits the space into two spaces + // |-------|-----------| + // | box | new space | + // |_______|___________| + // | updated space | + // |___________________| + spaces.push({ + x: space.x + box.w, + y: space.y, + w: space.w - box.w, + h: box.h + }); + space.y += box.h; + space.h -= box.h; + } + break; + } + } + + return { + w: width, // container width + h: height, // container height + fill: (area / (width * height)) || 0 // space utilization + }; +} + +/* eslint-disable key-spacing */ +const IMAGE_PADDING = 1; +class ImagePosition { + constructor(paddedRect, { pixelRatio, version, stretchX, stretchY, content, textFitWidth, textFitHeight }) { + this.paddedRect = paddedRect; + this.pixelRatio = pixelRatio; + this.stretchX = stretchX; + this.stretchY = stretchY; + this.content = content; + this.version = version; + this.textFitWidth = textFitWidth; + this.textFitHeight = textFitHeight; + } + get tl() { + return [ + this.paddedRect.x + IMAGE_PADDING, + this.paddedRect.y + IMAGE_PADDING + ]; + } + get br() { + return [ + this.paddedRect.x + this.paddedRect.w - IMAGE_PADDING, + this.paddedRect.y + this.paddedRect.h - IMAGE_PADDING + ]; + } + get tlbr() { + return this.tl.concat(this.br); + } + get displaySize() { + return [ + (this.paddedRect.w - IMAGE_PADDING * 2) / this.pixelRatio, + (this.paddedRect.h - IMAGE_PADDING * 2) / this.pixelRatio + ]; + } +} +/** + * A class holding all the images + */ +class ImageAtlas { + constructor(icons, patterns) { + const iconPositions = {}, patternPositions = {}; + this.haveRenderCallbacks = []; + const bins = []; + this.addImages(icons, iconPositions, bins); + this.addImages(patterns, patternPositions, bins); + const { w, h } = potpack(bins); + const image = new RGBAImage({ width: w || 1, height: h || 1 }); + for (const id in icons) { + const src = icons[id]; + const bin = iconPositions[id].paddedRect; + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x: bin.x + IMAGE_PADDING, y: bin.y + IMAGE_PADDING }, src.data); + } + for (const id in patterns) { + const src = patterns[id]; + const bin = patternPositions[id].paddedRect; + const x = bin.x + IMAGE_PADDING, y = bin.y + IMAGE_PADDING, w = src.data.width, h = src.data.height; + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x, y }, src.data); + // Add 1 pixel wrapped padding on each side of the image. + RGBAImage.copy(src.data, image, { x: 0, y: h - 1 }, { x, y: y - 1 }, { width: w, height: 1 }); // T + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x, y: y + h }, { width: w, height: 1 }); // B + RGBAImage.copy(src.data, image, { x: w - 1, y: 0 }, { x: x - 1, y }, { width: 1, height: h }); // L + RGBAImage.copy(src.data, image, { x: 0, y: 0 }, { x: x + w, y }, { width: 1, height: h }); // R + } + this.image = image; + this.iconPositions = iconPositions; + this.patternPositions = patternPositions; + } + addImages(images, positions, bins) { + for (const id in images) { + const src = images[id]; + const bin = { + x: 0, + y: 0, + w: src.data.width + 2 * IMAGE_PADDING, + h: src.data.height + 2 * IMAGE_PADDING, + }; + bins.push(bin); + positions[id] = new ImagePosition(bin, src); + if (src.hasRenderCallback) { + this.haveRenderCallbacks.push(id); + } + } + } + patchUpdatedImages(imageManager, texture) { + imageManager.dispatchRenderCallbacks(this.haveRenderCallbacks); + for (const name in imageManager.updatedImages) { + this.patchUpdatedImage(this.iconPositions[name], imageManager.getImage(name), texture); + this.patchUpdatedImage(this.patternPositions[name], imageManager.getImage(name), texture); + } + } + patchUpdatedImage(position, image, texture) { + if (!position || !image) + return; + if (position.version === image.version) + return; + position.version = image.version; + const [x, y] = position.tl; + texture.update(image.data, undefined, { x, y }); + } +} +register('ImagePosition', ImagePosition); +register('ImageAtlas', ImageAtlas); + +exports.ah = void 0; +(function (WritingMode) { + WritingMode[WritingMode["none"] = 0] = "none"; + WritingMode[WritingMode["horizontal"] = 1] = "horizontal"; + WritingMode[WritingMode["vertical"] = 2] = "vertical"; + WritingMode[WritingMode["horizontalOnly"] = 3] = "horizontalOnly"; +})(exports.ah || (exports.ah = {})); +const SHAPING_DEFAULT_OFFSET = -17; +function isEmpty(positionedLines) { + for (const line of positionedLines) { + if (line.positionedGlyphs.length !== 0) { + return false; + } + } + return true; +} +// Max number of images in label is 6401 U+E000–U+F8FF that covers +// Basic Multilingual Plane Unicode Private Use Area (PUA). +const PUAbegin = 0xE000; +const PUAend = 0xF8FF; +class SectionOptions { + constructor() { + this.scale = 1.0; + this.fontStack = ''; + this.imageName = null; + } + static forText(scale, fontStack) { + const textOptions = new SectionOptions(); + textOptions.scale = scale || 1; + textOptions.fontStack = fontStack; + return textOptions; + } + static forImage(imageName) { + const imageOptions = new SectionOptions(); + imageOptions.imageName = imageName; + return imageOptions; + } +} +class TaggedString { + constructor() { + this.text = ''; + this.sectionIndex = []; + this.sections = []; + this.imageSectionID = null; + } + static fromFeature(text, defaultFontStack) { + const result = new TaggedString(); + for (let i = 0; i < text.sections.length; i++) { + const section = text.sections[i]; + if (!section.image) { + result.addTextSection(section, defaultFontStack); + } + else { + result.addImageSection(section); + } + } + return result; + } + length() { + return this.text.length; + } + getSection(index) { + return this.sections[this.sectionIndex[index]]; + } + getSectionIndex(index) { + return this.sectionIndex[index]; + } + getCharCode(index) { + return this.text.charCodeAt(index); + } + verticalizePunctuation() { + this.text = verticalizePunctuation(this.text); + } + trim() { + let beginningWhitespace = 0; + for (let i = 0; i < this.text.length && whitespace[this.text.charCodeAt(i)]; i++) { + beginningWhitespace++; + } + let trailingWhitespace = this.text.length; + for (let i = this.text.length - 1; i >= 0 && i >= beginningWhitespace && whitespace[this.text.charCodeAt(i)]; i--) { + trailingWhitespace--; + } + this.text = this.text.substring(beginningWhitespace, trailingWhitespace); + this.sectionIndex = this.sectionIndex.slice(beginningWhitespace, trailingWhitespace); + } + substring(start, end) { + const substring = new TaggedString(); + substring.text = this.text.substring(start, end); + substring.sectionIndex = this.sectionIndex.slice(start, end); + substring.sections = this.sections; + return substring; + } + toString() { + return this.text; + } + getMaxScale() { + return this.sectionIndex.reduce((max, index) => Math.max(max, this.sections[index].scale), 0); + } + addTextSection(section, defaultFontStack) { + this.text += section.text; + this.sections.push(SectionOptions.forText(section.scale, section.fontStack || defaultFontStack)); + const index = this.sections.length - 1; + for (let i = 0; i < section.text.length; ++i) { + this.sectionIndex.push(index); + } + } + addImageSection(section) { + const imageName = section.image ? section.image.name : ''; + if (imageName.length === 0) { + warnOnce('Can\'t add FormattedSection with an empty image.'); + return; + } + const nextImageSectionCharCode = this.getNextImageSectionCharCode(); + if (!nextImageSectionCharCode) { + warnOnce(`Reached maximum number of images ${PUAend - PUAbegin + 2}`); + return; + } + this.text += String.fromCharCode(nextImageSectionCharCode); + this.sections.push(SectionOptions.forImage(imageName)); + this.sectionIndex.push(this.sections.length - 1); + } + getNextImageSectionCharCode() { + if (!this.imageSectionID) { + this.imageSectionID = PUAbegin; + return this.imageSectionID; + } + if (this.imageSectionID >= PUAend) + return null; + return ++this.imageSectionID; + } +} +function breakLines(input, lineBreakPoints) { + const lines = []; + const text = input.text; + let start = 0; + for (const lineBreak of lineBreakPoints) { + lines.push(input.substring(start, lineBreak)); + start = lineBreak; + } + if (start < text.length) { + lines.push(input.substring(start, text.length)); + } + return lines; +} +function shapeText(text, glyphMap, glyphPositions, imagePositions, defaultFontStack, maxWidth, lineHeight, textAnchor, textJustify, spacing, translate, writingMode, allowVerticalPlacement, layoutTextSize, layoutTextSizeThisZoom) { + const logicalInput = TaggedString.fromFeature(text, defaultFontStack); + if (writingMode === exports.ah.vertical) { + logicalInput.verticalizePunctuation(); + } + let lines; + const { processBidirectionalText, processStyledBidirectionalText } = rtlWorkerPlugin; + if (processBidirectionalText && logicalInput.sections.length === 1) { + // Bidi doesn't have to be style-aware + lines = []; + const untaggedLines = processBidirectionalText(logicalInput.toString(), determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + for (const line of untaggedLines) { + const taggedLine = new TaggedString(); + taggedLine.text = line; + taggedLine.sections = logicalInput.sections; + for (let i = 0; i < line.length; i++) { + taggedLine.sectionIndex.push(0); + } + lines.push(taggedLine); + } + } + else if (processStyledBidirectionalText) { + // Need version of mapbox-gl-rtl-text with style support for combining RTL text + // with formatting + lines = []; + const processedLines = processStyledBidirectionalText(logicalInput.text, logicalInput.sectionIndex, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + for (const line of processedLines) { + const taggedLine = new TaggedString(); + taggedLine.text = line[0]; + taggedLine.sectionIndex = line[1]; + taggedLine.sections = logicalInput.sections; + lines.push(taggedLine); + } + } + else { + lines = breakLines(logicalInput, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize)); + } + const positionedLines = []; + const shaping = { + positionedLines, + text: logicalInput.toString(), + top: translate[1], + bottom: translate[1], + left: translate[0], + right: translate[0], + writingMode, + iconsInText: false, + verticalizable: false + }; + shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom); + if (isEmpty(positionedLines)) + return false; + return shaping; +} +// using computed properties due to https://github.com/facebook/flow/issues/380 +/* eslint no-useless-computed-key: 0 */ +const whitespace = { + [0x09]: true, // tab + [0x0a]: true, // newline + [0x0b]: true, // vertical tab + [0x0c]: true, // form feed + [0x0d]: true, // carriage return + [0x20]: true, // space +}; +const breakable = { + [0x0a]: true, // newline + [0x20]: true, // space + [0x26]: true, // ampersand + [0x29]: true, // right parenthesis + [0x2b]: true, // plus sign + [0x2d]: true, // hyphen-minus + [0x2f]: true, // solidus + [0xad]: true, // soft hyphen + [0xb7]: true, // middle dot + [0x200b]: true, // zero-width space + [0x2010]: true, // hyphen + [0x2013]: true, // en dash + [0x2027]: true // interpunct + // Many other characters may be reasonable breakpoints + // Consider "neutral orientation" characters at scriptDetection.charHasNeutralVerticalOrientation + // See https://github.com/mapbox/mapbox-gl-js/issues/3658 +}; +// Allow breaks depending on the following character +const breakableBefore = { + [0x28]: true, // left parenthesis +}; +function getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize) { + if (!section.imageName) { + const positions = glyphMap[section.fontStack]; + const glyph = positions && positions[codePoint]; + if (!glyph) + return 0; + return glyph.metrics.advance * section.scale + spacing; + } + else { + const imagePosition = imagePositions[section.imageName]; + if (!imagePosition) + return 0; + return imagePosition.displaySize[0] * section.scale * ONE_EM / layoutTextSize + spacing; + } +} +function determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) { + let totalWidth = 0; + for (let index = 0; index < logicalInput.length(); index++) { + const section = logicalInput.getSection(index); + totalWidth += getGlyphAdvance(logicalInput.getCharCode(index), section, glyphMap, imagePositions, spacing, layoutTextSize); + } + const lineCount = Math.max(1, Math.ceil(totalWidth / maxWidth)); + return totalWidth / lineCount; +} +function calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) { + const raggedness = Math.pow(lineWidth - targetWidth, 2); + if (isLastBreak) { + // Favor finals lines shorter than average over longer than average + if (lineWidth < targetWidth) { + return raggedness / 2; + } + else { + return raggedness * 2; + } + } + return raggedness + Math.abs(penalty) * penalty; +} +function calculatePenalty(codePoint, nextCodePoint, penalizableIdeographicBreak) { + let penalty = 0; + // Force break on newline + if (codePoint === 0x0a) { + penalty -= 10000; + } + // Penalize breaks between characters that allow ideographic breaking because + // they are less preferable than breaks at spaces (or zero width spaces). + if (penalizableIdeographicBreak) { + penalty += 150; + } + // Penalize open parenthesis at end of line + if (codePoint === 0x28 || codePoint === 0xff08) { + penalty += 50; + } + // Penalize close parenthesis at beginning of line + if (nextCodePoint === 0x29 || nextCodePoint === 0xff09) { + penalty += 50; + } + return penalty; +} +function evaluateBreak(breakIndex, breakX, targetWidth, potentialBreaks, penalty, isLastBreak) { + // We could skip evaluating breaks where the line length (breakX - priorBreak.x) > maxWidth + // ...but in fact we allow lines longer than maxWidth (if there's no break points) + // ...and when targetWidth and maxWidth are close, strictly enforcing maxWidth can give + // more lopsided results. + let bestPriorBreak = null; + let bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak); + for (const potentialBreak of potentialBreaks) { + const lineWidth = breakX - potentialBreak.x; + const breakBadness = calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness; + if (breakBadness <= bestBreakBadness) { + bestPriorBreak = potentialBreak; + bestBreakBadness = breakBadness; + } + } + return { + index: breakIndex, + x: breakX, + priorBreak: bestPriorBreak, + badness: bestBreakBadness + }; +} +function leastBadBreaks(lastLineBreak) { + if (!lastLineBreak) { + return []; + } + return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index); +} +function determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) { + if (!logicalInput) + return []; + const potentialLineBreaks = []; + const targetWidth = determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize); + const hasServerSuggestedBreakpoints = logicalInput.text.indexOf('\u200b') >= 0; + let currentX = 0; + for (let i = 0; i < logicalInput.length(); i++) { + const section = logicalInput.getSection(i); + const codePoint = logicalInput.getCharCode(i); + if (!whitespace[codePoint]) + currentX += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize); + // Ideographic characters, spaces, and word-breaking punctuation that often appear without + // surrounding spaces. + if ((i < logicalInput.length() - 1)) { + const ideographicBreak = charAllowsIdeographicBreaking(codePoint); + if (breakable[codePoint] || ideographicBreak || section.imageName || (i !== logicalInput.length() - 2 && breakableBefore[logicalInput.getCharCode(i + 1)])) { + potentialLineBreaks.push(evaluateBreak(i + 1, currentX, targetWidth, potentialLineBreaks, calculatePenalty(codePoint, logicalInput.getCharCode(i + 1), ideographicBreak && hasServerSuggestedBreakpoints), false)); + } + } + } + return leastBadBreaks(evaluateBreak(logicalInput.length(), currentX, targetWidth, potentialLineBreaks, 0, true)); +} +function getAnchorAlignment(anchor) { + let horizontalAlign = 0.5, verticalAlign = 0.5; + switch (anchor) { + case 'right': + case 'top-right': + case 'bottom-right': + horizontalAlign = 1; + break; + case 'left': + case 'top-left': + case 'bottom-left': + horizontalAlign = 0; + break; + } + switch (anchor) { + case 'bottom': + case 'bottom-right': + case 'bottom-left': + verticalAlign = 1; + break; + case 'top': + case 'top-right': + case 'top-left': + verticalAlign = 0; + break; + } + return { horizontalAlign, verticalAlign }; +} +function shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom) { + let x = 0; + let y = SHAPING_DEFAULT_OFFSET; + let maxLineLength = 0; + let maxLineHeight = 0; + const justify = textJustify === 'right' ? 1 : + textJustify === 'left' ? 0 : 0.5; + let lineIndex = 0; + for (const line of lines) { + line.trim(); + const lineMaxScale = line.getMaxScale(); + const maxLineOffset = (lineMaxScale - 1) * ONE_EM; + const positionedLine = { positionedGlyphs: [], lineOffset: 0 }; + shaping.positionedLines[lineIndex] = positionedLine; + const positionedGlyphs = positionedLine.positionedGlyphs; + let lineOffset = 0.0; + if (!line.length()) { + y += lineHeight; // Still need a line feed after empty line + ++lineIndex; + continue; + } + for (let i = 0; i < line.length(); i++) { + const section = line.getSection(i); + const sectionIndex = line.getSectionIndex(i); + const codePoint = line.getCharCode(i); + let baselineOffset = 0.0; + let metrics = null; + let rect = null; + let imageName = null; + let verticalAdvance = ONE_EM; + const vertical = !(writingMode === exports.ah.horizontal || + // Don't verticalize glyphs that have no upright orientation if vertical placement is disabled. + (!allowVerticalPlacement && !charHasUprightVerticalOrientation(codePoint)) || + // If vertical placement is enabled, don't verticalize glyphs that + // are from complex text layout script, or whitespaces. + (allowVerticalPlacement && (whitespace[codePoint] || charInComplexShapingScript(codePoint)))); + if (!section.imageName) { + const positions = glyphPositions[section.fontStack]; + const glyphPosition = positions && positions[codePoint]; + if (glyphPosition && glyphPosition.rect) { + rect = glyphPosition.rect; + metrics = glyphPosition.metrics; + } + else { + const glyphs = glyphMap[section.fontStack]; + const glyph = glyphs && glyphs[codePoint]; + if (!glyph) + continue; + metrics = glyph.metrics; + } + // We don't know the baseline, but since we're laying out + // at 24 points, we can calculate how much it will move when + // we scale up or down. + baselineOffset = (lineMaxScale - section.scale) * ONE_EM; + } + else { + const imagePosition = imagePositions[section.imageName]; + if (!imagePosition) + continue; + imageName = section.imageName; + shaping.iconsInText = shaping.iconsInText || true; + rect = imagePosition.paddedRect; + const size = imagePosition.displaySize; + // If needed, allow to set scale factor for an image using + // alias "image-scale" that could be alias for "font-scale" + // when FormattedSection is an image section. + section.scale = section.scale * ONE_EM / layoutTextSizeThisZoom; + metrics = { width: size[0], + height: size[1], + left: IMAGE_PADDING, + top: -GLYPH_PBF_BORDER, + advance: vertical ? size[1] : size[0] }; + // Difference between one EM and an image size. + // Aligns bottom of an image to a baseline level. + const imageOffset = ONE_EM - size[1] * section.scale; + baselineOffset = maxLineOffset + imageOffset; + verticalAdvance = metrics.advance; + // Difference between height of an image and one EM at max line scale. + // Pushes current line down if an image size is over 1 EM at max line scale. + const offset = vertical ? size[0] * section.scale - ONE_EM * lineMaxScale : + size[1] * section.scale - ONE_EM * lineMaxScale; + if (offset > 0 && offset > lineOffset) { + lineOffset = offset; + } + } + if (!vertical) { + positionedGlyphs.push({ glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect }); + x += metrics.advance * section.scale + spacing; + } + else { + shaping.verticalizable = true; + positionedGlyphs.push({ glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect }); + x += verticalAdvance * section.scale + spacing; + } + } + // Only justify if we placed at least one glyph + if (positionedGlyphs.length !== 0) { + const lineLength = x - spacing; + maxLineLength = Math.max(lineLength, maxLineLength); + justifyLine(positionedGlyphs, 0, positionedGlyphs.length - 1, justify, lineOffset); + } + x = 0; + const currentLineHeight = lineHeight * lineMaxScale + lineOffset; + positionedLine.lineOffset = Math.max(lineOffset, maxLineOffset); + y += currentLineHeight; + maxLineHeight = Math.max(currentLineHeight, maxLineHeight); + ++lineIndex; + } + // Calculate the bounding box and justify / align text block. + const height = y - SHAPING_DEFAULT_OFFSET; + const { horizontalAlign, verticalAlign } = getAnchorAlignment(textAnchor); + align(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, height, lines.length); + shaping.top += -verticalAlign * height; + shaping.bottom = shaping.top + height; + shaping.left += -horizontalAlign * maxLineLength; + shaping.right = shaping.left + maxLineLength; +} +// justify right = 1, left = 0, center = 0.5 +function justifyLine(positionedGlyphs, start, end, justify, lineOffset) { + if (!justify && !lineOffset) + return; + const lastPositionedGlyph = positionedGlyphs[end]; + const lastAdvance = lastPositionedGlyph.metrics.advance * lastPositionedGlyph.scale; + const lineIndent = (positionedGlyphs[end].x + lastAdvance) * justify; + for (let j = start; j <= end; j++) { + positionedGlyphs[j].x -= lineIndent; + positionedGlyphs[j].y += lineOffset; + } +} +function align(positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, blockHeight, lineCount) { + const shiftX = (justify - horizontalAlign) * maxLineLength; + let shiftY = 0; + if (maxLineHeight !== lineHeight) { + shiftY = -blockHeight * verticalAlign - SHAPING_DEFAULT_OFFSET; + } + else { + shiftY = (-verticalAlign * lineCount + 0.5) * lineHeight; + } + for (const line of positionedLines) { + for (const positionedGlyph of line.positionedGlyphs) { + positionedGlyph.x += shiftX; + positionedGlyph.y += shiftY; + } + } +} +function shapeIcon(image, iconOffset, iconAnchor) { + const { horizontalAlign, verticalAlign } = getAnchorAlignment(iconAnchor); + const dx = iconOffset[0]; + const dy = iconOffset[1]; + const x1 = dx - image.displaySize[0] * horizontalAlign; + const x2 = x1 + image.displaySize[0]; + const y1 = dy - image.displaySize[1] * verticalAlign; + const y2 = y1 + image.displaySize[1]; + return { image, top: y1, bottom: y2, left: x1, right: x2 }; +} +/** + * Called after a PositionedIcon has already been run through fitIconToText, + * but needs further adjustment to apply textFitWidth and textFitHeight. + * @param shapedIcon - The icon that will be adjusted. + * @returns Extents of the shapedIcon with text fit adjustments if necessary. + */ +function applyTextFit(shapedIcon) { + var _a, _b; + // Assume shapedIcon.image is set or this wouldn't be called. + // Size of the icon after it was adjusted using stretchX and Y + let iconLeft = shapedIcon.left; + let iconTop = shapedIcon.top; + let iconWidth = shapedIcon.right - iconLeft; + let iconHeight = shapedIcon.bottom - iconTop; + // Size of the original content area + const contentWidth = shapedIcon.image.content[2] - shapedIcon.image.content[0]; + const contentHeight = shapedIcon.image.content[3] - shapedIcon.image.content[1]; + const textFitWidth = (_a = shapedIcon.image.textFitWidth) !== null && _a !== void 0 ? _a : "stretchOrShrink" /* TextFit.stretchOrShrink */; + const textFitHeight = (_b = shapedIcon.image.textFitHeight) !== null && _b !== void 0 ? _b : "stretchOrShrink" /* TextFit.stretchOrShrink */; + const contentAspectRatio = contentWidth / contentHeight; + // Scale to the proportional axis first note that height takes precedence if + // both axes are set to proportional. + if (textFitHeight === "proportional" /* TextFit.proportional */) { + if ((textFitWidth === "stretchOnly" /* TextFit.stretchOnly */ && iconWidth / iconHeight < contentAspectRatio) || textFitWidth === "proportional" /* TextFit.proportional */) { + // Push the width of the icon back out to match the content aspect ratio + const newIconWidth = Math.ceil(iconHeight * contentAspectRatio); + iconLeft *= newIconWidth / iconWidth; + iconWidth = newIconWidth; + } + } + else if (textFitWidth === "proportional" /* TextFit.proportional */) { + if (textFitHeight === "stretchOnly" /* TextFit.stretchOnly */ && contentAspectRatio !== 0 && iconWidth / iconHeight > contentAspectRatio) { + // Push the height of the icon back out to match the content aspect ratio + const newIconHeight = Math.ceil(iconWidth / contentAspectRatio); + iconTop *= newIconHeight / iconHeight; + iconHeight = newIconHeight; + } + } + else ; + return { x1: iconLeft, y1: iconTop, x2: iconLeft + iconWidth, y2: iconTop + iconHeight }; +} +function fitIconToText(shapedIcon, shapedText, textFit, padding, iconOffset, fontScale) { + const image = shapedIcon.image; + let collisionPadding; + if (image.content) { + const content = image.content; + const pixelRatio = image.pixelRatio || 1; + collisionPadding = [ + content[0] / pixelRatio, + content[1] / pixelRatio, + image.displaySize[0] - content[2] / pixelRatio, + image.displaySize[1] - content[3] / pixelRatio + ]; + } + // We don't respect the icon-anchor, because icon-text-fit is set. Instead, + // the icon will be centered on the text, then stretched in the given + // dimensions. + const textLeft = shapedText.left * fontScale; + const textRight = shapedText.right * fontScale; + let top, right, bottom, left; + if (textFit === 'width' || textFit === 'both') { + // Stretched horizontally to the text width + left = iconOffset[0] + textLeft - padding[3]; + right = iconOffset[0] + textRight + padding[1]; + } + else { + // Centered on the text + left = iconOffset[0] + (textLeft + textRight - image.displaySize[0]) / 2; + right = left + image.displaySize[0]; + } + const textTop = shapedText.top * fontScale; + const textBottom = shapedText.bottom * fontScale; + if (textFit === 'height' || textFit === 'both') { + // Stretched vertically to the text height + top = iconOffset[1] + textTop - padding[0]; + bottom = iconOffset[1] + textBottom + padding[2]; + } + else { + // Centered on the text + top = iconOffset[1] + (textTop + textBottom - image.displaySize[1]) / 2; + bottom = top + image.displaySize[1]; + } + return { image, top, right, bottom, left, collisionPadding }; +} + +const MAX_GLYPH_ICON_SIZE = 255; +const SIZE_PACK_FACTOR = 128; +const MAX_PACKED_SIZE = MAX_GLYPH_ICON_SIZE * SIZE_PACK_FACTOR; +// For {text,icon}-size, get the bucket-level data that will be needed by +// the painter to set symbol-size-related uniforms +function getSizeData(tileZoom, value) { + const { expression } = value; + if (expression.kind === 'constant') { + const layoutSize = expression.evaluate(new EvaluationParameters(tileZoom + 1)); + return { kind: 'constant', layoutSize }; + } + else if (expression.kind === 'source') { + return { kind: 'source' }; + } + else { + const { zoomStops, interpolationType } = expression; + // calculate covering zoom stops for zoom-dependent values + let lower = 0; + while (lower < zoomStops.length && zoomStops[lower] <= tileZoom) + lower++; + lower = Math.max(0, lower - 1); + let upper = lower; + while (upper < zoomStops.length && zoomStops[upper] < tileZoom + 1) + upper++; + upper = Math.min(zoomStops.length - 1, upper); + const minZoom = zoomStops[lower]; + const maxZoom = zoomStops[upper]; + // We'd like to be able to use CameraExpression or CompositeExpression in these + // return types rather than ExpressionSpecification, but the former are not + // transferrable across Web Worker boundaries. + if (expression.kind === 'composite') { + return { kind: 'composite', minZoom, maxZoom, interpolationType }; + } + // for camera functions, also save off the function values + // evaluated at the covering zoom levels + const minSize = expression.evaluate(new EvaluationParameters(minZoom)); + const maxSize = expression.evaluate(new EvaluationParameters(maxZoom)); + return { kind: 'camera', minZoom, maxZoom, minSize, maxSize, interpolationType }; + } +} +function evaluateSizeForFeature(sizeData, { uSize, uSizeT }, { lowerSize, upperSize }) { + if (sizeData.kind === 'source') { + return lowerSize / SIZE_PACK_FACTOR; + } + else if (sizeData.kind === 'composite') { + return interpolate.number(lowerSize / SIZE_PACK_FACTOR, upperSize / SIZE_PACK_FACTOR, uSizeT); + } + return uSize; +} +function evaluateSizeForZoom(sizeData, zoom) { + let uSizeT = 0; + let uSize = 0; + if (sizeData.kind === 'constant') { + uSize = sizeData.layoutSize; + } + else if (sizeData.kind !== 'source') { + const { interpolationType, minZoom, maxZoom } = sizeData; + // Even though we could get the exact value of the camera function + // at z = tr.zoom, we intentionally do not: instead, we interpolate + // between the camera function values at a pair of zoom stops covering + // [tileZoom, tileZoom + 1] in order to be consistent with this + // restriction on composite functions + const t = !interpolationType ? 0 : clamp$1(Interpolate.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1); + if (sizeData.kind === 'camera') { + uSize = interpolate.number(sizeData.minSize, sizeData.maxSize, t); + } + else { + uSizeT = t; + } + } + return { uSizeT, uSize }; +} + +function getOverlapMode(layout, overlapProp, allowOverlapProp) { + let result = 'never'; + const overlap = layout.get(overlapProp); + if (overlap) { + // if -overlap is set, use it + result = overlap; + } + else if (layout.get(allowOverlapProp)) { + // fall back to -allow-overlap, with false='never', true='always' + result = 'always'; + } + return result; +} + +const vectorTileFeatureTypes = vectorTile.VectorTileFeature.types; +// Opacity arrays are frequently updated but don't contain a lot of information, so we pack them +// tight. Each Uint32 is actually four duplicate Uint8s for the four corners of a glyph +// 7 bits are for the current opacity, and the lowest bit is the target opacity +// actually defined in symbol_attributes.js +// const placementOpacityAttributes = [ +// { name: 'a_fade_opacity', components: 1, type: 'Uint32' } +// ]; +const shaderOpacityAttributes = [ + { name: 'a_fade_opacity', components: 1, type: 'Uint8', offset: 0 } +]; +function addVertex(array, anchorX, anchorY, ox, oy, tx, ty, sizeVertex, isSDF, pixelOffsetX, pixelOffsetY, minFontScaleX, minFontScaleY) { + const aSizeX = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[0])) : 0; + const aSizeY = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[1])) : 0; + array.emplaceBack( + // a_pos_offset + anchorX, anchorY, Math.round(ox * 32), Math.round(oy * 32), + // a_data + tx, // x coordinate of symbol on glyph atlas texture + ty, // y coordinate of symbol on glyph atlas texture + (aSizeX << 1) + (isSDF ? 1 : 0), aSizeY, pixelOffsetX * 16, pixelOffsetY * 16, minFontScaleX * 256, minFontScaleY * 256); +} +function addDynamicAttributes(dynamicLayoutVertexArray, p, angle) { + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); + dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); +} +function containsRTLText(formattedText) { + for (const section of formattedText.sections) { + if (stringContainsRTLText(section.text)) { + return true; + } + } + return false; +} +class SymbolBuffers { + constructor(programConfigurations) { + this.layoutVertexArray = new SymbolLayoutArray(); + this.indexArray = new TriangleIndexArray(); + this.programConfigurations = programConfigurations; + this.segments = new SegmentVector(); + this.dynamicLayoutVertexArray = new SymbolDynamicLayoutArray(); + this.opacityVertexArray = new SymbolOpacityArray(); + this.hasVisibleVertices = false; + this.placedSymbolArray = new PlacedSymbolArray(); + } + isEmpty() { + return this.layoutVertexArray.length === 0 && + this.indexArray.length === 0 && + this.dynamicLayoutVertexArray.length === 0 && + this.opacityVertexArray.length === 0; + } + upload(context, dynamicIndexBuffer, upload, update) { + if (this.isEmpty()) { + return; + } + if (upload) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members); + this.indexBuffer = context.createIndexBuffer(this.indexArray, dynamicIndexBuffer); + this.dynamicLayoutVertexBuffer = context.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, true); + this.opacityVertexBuffer = context.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, true); + // This is a performance hack so that we can write to opacityVertexArray with uint32s + // even though the shaders read uint8s + this.opacityVertexBuffer.itemSize = 1; + } + if (upload || update) { + this.programConfigurations.upload(context); + } + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.programConfigurations.destroy(); + this.segments.destroy(); + this.dynamicLayoutVertexBuffer.destroy(); + this.opacityVertexBuffer.destroy(); + } +} +register('SymbolBuffers', SymbolBuffers); +class CollisionBuffers { + constructor(LayoutArray, layoutAttributes, IndexArray) { + this.layoutVertexArray = new LayoutArray(); + this.layoutAttributes = layoutAttributes; + this.indexArray = new IndexArray(); + this.segments = new SegmentVector(); + this.collisionVertexArray = new CollisionVertexArray(); + } + upload(context) { + this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes); + this.indexBuffer = context.createIndexBuffer(this.indexArray); + this.collisionVertexBuffer = context.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, true); + } + destroy() { + if (!this.layoutVertexBuffer) + return; + this.layoutVertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.segments.destroy(); + this.collisionVertexBuffer.destroy(); + } +} +register('CollisionBuffers', CollisionBuffers); +/** + * @internal + * Unlike other buckets, which simply implement #addFeature with type-specific + * logic for (essentially) triangulating feature geometries, SymbolBucket + * requires specialized behavior: + * + * 1. WorkerTile#parse(), the logical owner of the bucket creation process, + * calls SymbolBucket#populate(), which resolves text and icon tokens on + * each feature, adds each glyphs and symbols needed to the passed-in + * collections options.glyphDependencies and options.iconDependencies, and + * stores the feature data for use in subsequent step (this.features). + * + * 2. WorkerTile asynchronously requests from the main thread all of the glyphs + * and icons needed (by this bucket and any others). When glyphs and icons + * have been received, the WorkerTile creates a CollisionIndex and invokes: + * + * 3. performSymbolLayout(bucket, stacks, icons) perform texts shaping and + * layout on a Symbol Bucket. This step populates: + * `this.symbolInstances`: metadata on generated symbols + * `this.collisionBoxArray`: collision data for use by foreground + * `this.text`: SymbolBuffers for text symbols + * `this.icons`: SymbolBuffers for icons + * `this.iconCollisionBox`: Debug SymbolBuffers for icon collision boxes + * `this.textCollisionBox`: Debug SymbolBuffers for text collision boxes + * The results are sent to the foreground for rendering + * + * 4. placement.ts is run on the foreground, + * and uses the CollisionIndex along with current camera settings to determine + * which symbols can actually show on the map. Collided symbols are hidden + * using a dynamic "OpacityVertexArray". + */ +class SymbolBucket { + constructor(options) { + this.collisionBoxArray = options.collisionBoxArray; + this.zoom = options.zoom; + this.overscaling = options.overscaling; + this.layers = options.layers; + this.layerIds = this.layers.map(layer => layer.id); + this.index = options.index; + this.pixelRatio = options.pixelRatio; + this.sourceLayerIndex = options.sourceLayerIndex; + this.hasPattern = false; + this.hasRTLText = false; + this.sortKeyRanges = []; + this.collisionCircleArray = []; + this.placementInvProjMatrix = identity([]); + this.placementViewportMatrix = identity([]); + const layer = this.layers[0]; + const unevaluatedLayoutValues = layer._unevaluatedLayout._values; + this.textSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['text-size']); + this.iconSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['icon-size']); + const layout = this.layers[0].layout; + const sortKey = layout.get('symbol-sort-key'); + const zOrder = layout.get('symbol-z-order'); + this.canOverlap = + getOverlapMode(layout, 'text-overlap', 'text-allow-overlap') !== 'never' || + getOverlapMode(layout, 'icon-overlap', 'icon-allow-overlap') !== 'never' || + layout.get('text-ignore-placement') || + layout.get('icon-ignore-placement'); + this.sortFeaturesByKey = zOrder !== 'viewport-y' && !sortKey.isConstant(); + const zOrderByViewportY = zOrder === 'viewport-y' || (zOrder === 'auto' && !this.sortFeaturesByKey); + this.sortFeaturesByY = zOrderByViewportY && this.canOverlap; + if (layout.get('symbol-placement') === 'point') { + this.writingModes = layout.get('text-writing-mode').map(wm => exports.ah[wm]); + } + this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); + this.sourceID = options.sourceID; + } + createArrays() { + this.text = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^text/.test(property))); + this.icon = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^icon/.test(property))); + this.glyphOffsetArray = new GlyphOffsetArray(); + this.lineVertexArray = new SymbolLineVertexArray(); + this.symbolInstances = new SymbolInstanceArray(); + this.textAnchorOffsets = new TextAnchorOffsetArray(); + } + calculateGlyphDependencies(text, stack, textAlongLine, allowVerticalPlacement, doesAllowVerticalWritingMode) { + for (let i = 0; i < text.length; i++) { + stack[text.charCodeAt(i)] = true; + if ((textAlongLine || allowVerticalPlacement) && doesAllowVerticalWritingMode) { + const verticalChar = verticalizedCharacterMap[text.charAt(i)]; + if (verticalChar) { + stack[verticalChar.charCodeAt(0)] = true; + } + } + } + } + populate(features, options, canonical) { + const layer = this.layers[0]; + const layout = layer.layout; + const textFont = layout.get('text-font'); + const textField = layout.get('text-field'); + const iconImage = layout.get('icon-image'); + const hasText = (textField.value.kind !== 'constant' || + (textField.value.value instanceof Formatted && !textField.value.value.isEmpty()) || + textField.value.value.toString().length > 0) && + (textFont.value.kind !== 'constant' || textFont.value.value.length > 0); + // we should always resolve the icon-image value if the property was defined in the style + // this allows us to fire the styleimagemissing event if image evaluation returns null + // the only way to distinguish between null returned from a coalesce statement with no valid images + // and null returned because icon-image wasn't defined is to check whether or not iconImage.parameters is an empty object + const hasIcon = iconImage.value.kind !== 'constant' || !!iconImage.value.value || Object.keys(iconImage.parameters).length > 0; + const symbolSortKey = layout.get('symbol-sort-key'); + this.features = []; + if (!hasText && !hasIcon) { + return; + } + const icons = options.iconDependencies; + const stacks = options.glyphDependencies; + const availableImages = options.availableImages; + const globalProperties = new EvaluationParameters(this.zoom); + for (const { feature, id, index, sourceLayerIndex } of features) { + const needGeometry = layer._featureFilter.needGeometry; + const evaluationFeature = toEvaluationFeature(feature, needGeometry); + if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) { + continue; + } + if (!needGeometry) + evaluationFeature.geometry = loadGeometry(feature); + let text; + if (hasText) { + // Expression evaluation will automatically coerce to Formatted + // but plain string token evaluation skips that pathway so do the + // conversion here. + const resolvedTokens = layer.getValueAndResolveTokens('text-field', evaluationFeature, canonical, availableImages); + const formattedText = Formatted.factory(resolvedTokens); + // on this instance: if hasRTLText is already true, all future calls to containsRTLText can be skipped. + const bucketHasRTLText = this.hasRTLText = (this.hasRTLText || containsRTLText(formattedText)); + if (!bucketHasRTLText || // non-rtl text so can proceed safely + rtlWorkerPlugin.getRTLTextPluginStatus() === 'unavailable' || // We don't intend to lazy-load the rtl text plugin, so proceed with incorrect shaping + bucketHasRTLText && rtlWorkerPlugin.isParsed() // Use the rtlText plugin to shape text + ) { + text = transformText(formattedText, layer, evaluationFeature); + } + } + let icon; + if (hasIcon) { + // Expression evaluation will automatically coerce to Image + // but plain string token evaluation skips that pathway so do the + // conversion here. + const resolvedTokens = layer.getValueAndResolveTokens('icon-image', evaluationFeature, canonical, availableImages); + if (resolvedTokens instanceof ResolvedImage) { + icon = resolvedTokens; + } + else { + icon = ResolvedImage.fromString(resolvedTokens); + } + } + if (!text && !icon) { + continue; + } + const sortKey = this.sortFeaturesByKey ? + symbolSortKey.evaluate(evaluationFeature, {}, canonical) : + undefined; + const symbolFeature = { + id, + text, + icon, + index, + sourceLayerIndex, + geometry: evaluationFeature.geometry, + properties: feature.properties, + type: vectorTileFeatureTypes[feature.type], + sortKey + }; + this.features.push(symbolFeature); + if (icon) { + icons[icon.name] = true; + } + if (text) { + const fontStack = textFont.evaluate(evaluationFeature, {}, canonical).join(','); + const textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point'; + this.allowVerticalPlacement = this.writingModes && this.writingModes.indexOf(exports.ah.vertical) >= 0; + for (const section of text.sections) { + if (!section.image) { + const doesAllowVerticalWritingMode = allowsVerticalWritingMode(text.toString()); + const sectionFont = section.fontStack || fontStack; + const sectionStack = stacks[sectionFont] = stacks[sectionFont] || {}; + this.calculateGlyphDependencies(section.text, sectionStack, textAlongLine, this.allowVerticalPlacement, doesAllowVerticalWritingMode); + } + else { + // Add section image to the list of dependencies. + icons[section.image.name] = true; + } + } + } + } + if (layout.get('symbol-placement') === 'line') { + // Merge adjacent lines with the same text to improve labelling. + // It's better to place labels on one long line than on many short segments. + this.features = mergeLines(this.features); + } + if (this.sortFeaturesByKey) { + this.features.sort((a, b) => { + // a.sortKey is always a number when sortFeaturesByKey is true + return a.sortKey - b.sortKey; + }); + } + } + update(states, vtLayer, imagePositions) { + if (!this.stateDependentLayers.length) + return; + this.text.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions); + this.icon.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions); + } + isEmpty() { + // When the bucket encounters only rtl-text but the plugin isn't loaded, no symbol instances will be created. + // In order for the bucket to be serialized, and not discarded as an empty bucket both checks are necessary. + return this.symbolInstances.length === 0 && !this.hasRTLText; + } + uploadPending() { + return !this.uploaded || this.text.programConfigurations.needsUpload || this.icon.programConfigurations.needsUpload; + } + upload(context) { + if (!this.uploaded && this.hasDebugData()) { + this.textCollisionBox.upload(context); + this.iconCollisionBox.upload(context); + } + this.text.upload(context, this.sortFeaturesByY, !this.uploaded, this.text.programConfigurations.needsUpload); + this.icon.upload(context, this.sortFeaturesByY, !this.uploaded, this.icon.programConfigurations.needsUpload); + this.uploaded = true; + } + destroyDebugData() { + this.textCollisionBox.destroy(); + this.iconCollisionBox.destroy(); + } + destroy() { + this.text.destroy(); + this.icon.destroy(); + if (this.hasDebugData()) { + this.destroyDebugData(); + } + } + addToLineVertexArray(anchor, line) { + const lineStartIndex = this.lineVertexArray.length; + if (anchor.segment !== undefined) { + let sumForwardLength = anchor.dist(line[anchor.segment + 1]); + let sumBackwardLength = anchor.dist(line[anchor.segment]); + const vertices = {}; + for (let i = anchor.segment + 1; i < line.length; i++) { + vertices[i] = { x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumForwardLength }; + if (i < line.length - 1) { + sumForwardLength += line[i + 1].dist(line[i]); + } + } + for (let i = anchor.segment || 0; i >= 0; i--) { + vertices[i] = { x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumBackwardLength }; + if (i > 0) { + sumBackwardLength += line[i - 1].dist(line[i]); + } + } + for (let i = 0; i < line.length; i++) { + const vertex = vertices[i]; + this.lineVertexArray.emplaceBack(vertex.x, vertex.y, vertex.tileUnitDistanceFromAnchor); + } + } + return { + lineStartIndex, + lineLength: this.lineVertexArray.length - lineStartIndex + }; + } + addSymbols(arrays, quads, sizeVertex, lineOffset, alongLine, feature, writingMode, labelAnchor, lineStartIndex, lineLength, associatedIconIndex, canonical) { + const indexArray = arrays.indexArray; + const layoutVertexArray = arrays.layoutVertexArray; + const segment = arrays.segments.prepareSegment(4 * quads.length, layoutVertexArray, indexArray, this.canOverlap ? feature.sortKey : undefined); + const glyphOffsetArrayStart = this.glyphOffsetArray.length; + const vertexStartIndex = segment.vertexLength; + const angle = (this.allowVerticalPlacement && writingMode === exports.ah.vertical) ? Math.PI / 2 : 0; + const sections = feature.text && feature.text.sections; + for (let i = 0; i < quads.length; i++) { + const { tl, tr, bl, br, tex, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, glyphOffset, isSDF, sectionIndex } = quads[i]; + const index = segment.vertexLength; + const y = glyphOffset[1]; + addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY); + 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); + 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); + 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); + addDynamicAttributes(arrays.dynamicLayoutVertexArray, labelAnchor, angle); + indexArray.emplaceBack(index, index + 1, index + 2); + indexArray.emplaceBack(index + 1, index + 2, index + 3); + segment.vertexLength += 4; + segment.primitiveLength += 2; + this.glyphOffsetArray.emplaceBack(glyphOffset[0]); + if (i === quads.length - 1 || sectionIndex !== quads[i + 1].sectionIndex) { + arrays.programConfigurations.populatePaintArrays(layoutVertexArray.length, feature, feature.index, {}, canonical, sections && sections[sectionIndex]); + } + } + arrays.placedSymbolArray.emplaceBack(labelAnchor.x, labelAnchor.y, glyphOffsetArrayStart, this.glyphOffsetArray.length - glyphOffsetArrayStart, vertexStartIndex, lineStartIndex, lineLength, labelAnchor.segment, sizeVertex ? sizeVertex[0] : 0, sizeVertex ? sizeVertex[1] : 0, lineOffset[0], lineOffset[1], writingMode, + // placedOrientation is null initially; will be updated to horizontal(1)/vertical(2) if placed + 0, false, + // The crossTileID is only filled/used on the foreground for dynamic text anchors + 0, associatedIconIndex); + } + _addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, point, anchorX, anchorY, extrude) { + collisionVertexArray.emplaceBack(0, 0); + return layoutVertexArray.emplaceBack( + // pos + point.x, point.y, + // a_anchor_pos + anchorX, anchorY, + // extrude + Math.round(extrude.x), Math.round(extrude.y)); + } + addCollisionDebugVertices(x1, y1, x2, y2, arrays, boxAnchorPoint, symbolInstance) { + const segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray); + const index = segment.vertexLength; + const layoutVertexArray = arrays.layoutVertexArray; + const collisionVertexArray = arrays.collisionVertexArray; + const anchorX = symbolInstance.anchorX; + const anchorY = symbolInstance.anchorY; + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$2(x1, y1)); + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$2(x2, y1)); + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$2(x2, y2)); + this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point$2(x1, y2)); + segment.vertexLength += 4; + const indexArray = arrays.indexArray; + indexArray.emplaceBack(index, index + 1); + indexArray.emplaceBack(index + 1, index + 2); + indexArray.emplaceBack(index + 2, index + 3); + indexArray.emplaceBack(index + 3, index); + segment.primitiveLength += 4; + } + addDebugCollisionBoxes(startIndex, endIndex, symbolInstance, isText) { + for (let b = startIndex; b < endIndex; b++) { + const box = this.collisionBoxArray.get(b); + const x1 = box.x1; + const y1 = box.y1; + const x2 = box.x2; + const y2 = box.y2; + this.addCollisionDebugVertices(x1, y1, x2, y2, isText ? this.textCollisionBox : this.iconCollisionBox, box.anchorPoint, symbolInstance); + } + } + generateCollisionDebugBuffers() { + if (this.hasDebugData()) { + this.destroyDebugData(); + } + this.textCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray); + this.iconCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray); + for (let i = 0; i < this.symbolInstances.length; i++) { + const symbolInstance = this.symbolInstances.get(i); + this.addDebugCollisionBoxes(symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance, true); + this.addDebugCollisionBoxes(symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance, true); + this.addDebugCollisionBoxes(symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance, false); + this.addDebugCollisionBoxes(symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance, false); + } + } + // These flat arrays are meant to be quicker to iterate over than the source + // CollisionBoxArray + _deserializeCollisionBoxesForSymbol(collisionBoxArray, textStartIndex, textEndIndex, verticalTextStartIndex, verticalTextEndIndex, iconStartIndex, iconEndIndex, verticalIconStartIndex, verticalIconEndIndex) { + const collisionArrays = {}; + for (let k = textStartIndex; k < textEndIndex; k++) { + const box = collisionBoxArray.get(k); + collisionArrays.textBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.textFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + for (let k = verticalTextStartIndex; k < verticalTextEndIndex; k++) { + const box = collisionBoxArray.get(k); + collisionArrays.verticalTextBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.verticalTextFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + for (let k = iconStartIndex; k < iconEndIndex; k++) { + // An icon can only have one box now, so this indexing is a bit vestigial... + const box = collisionBoxArray.get(k); + collisionArrays.iconBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.iconFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + for (let k = verticalIconStartIndex; k < verticalIconEndIndex; k++) { + // An icon can only have one box now, so this indexing is a bit vestigial... + const box = collisionBoxArray.get(k); + collisionArrays.verticalIconBox = { x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY }; + collisionArrays.verticalIconFeatureIndex = box.featureIndex; + break; // Only one box allowed per instance + } + return collisionArrays; + } + deserializeCollisionBoxes(collisionBoxArray) { + this.collisionArrays = []; + for (let i = 0; i < this.symbolInstances.length; i++) { + const symbolInstance = this.symbolInstances.get(i); + this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(collisionBoxArray, symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex)); + } + } + hasTextData() { + return this.text.segments.get().length > 0; + } + hasIconData() { + return this.icon.segments.get().length > 0; + } + hasDebugData() { + return this.textCollisionBox && this.iconCollisionBox; + } + hasTextCollisionBoxData() { + return this.hasDebugData() && this.textCollisionBox.segments.get().length > 0; + } + hasIconCollisionBoxData() { + return this.hasDebugData() && this.iconCollisionBox.segments.get().length > 0; + } + addIndicesForPlacedSymbol(iconOrText, placedSymbolIndex) { + const placedSymbol = iconOrText.placedSymbolArray.get(placedSymbolIndex); + const endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4; + for (let vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) { + iconOrText.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2); + iconOrText.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3); + } + } + getSortedSymbolIndexes(angle) { + if (this.sortedAngle === angle && this.symbolInstanceIndexes !== undefined) { + return this.symbolInstanceIndexes; + } + const sin = Math.sin(angle); + const cos = Math.cos(angle); + const rotatedYs = []; + const featureIndexes = []; + const result = []; + for (let i = 0; i < this.symbolInstances.length; ++i) { + result.push(i); + const symbolInstance = this.symbolInstances.get(i); + rotatedYs.push(Math.round(sin * symbolInstance.anchorX + cos * symbolInstance.anchorY) | 0); + featureIndexes.push(symbolInstance.featureIndex); + } + result.sort((aIndex, bIndex) => { + return (rotatedYs[aIndex] - rotatedYs[bIndex]) || + (featureIndexes[bIndex] - featureIndexes[aIndex]); + }); + return result; + } + addToSortKeyRanges(symbolInstanceIndex, sortKey) { + const last = this.sortKeyRanges[this.sortKeyRanges.length - 1]; + if (last && last.sortKey === sortKey) { + last.symbolInstanceEnd = symbolInstanceIndex + 1; + } + else { + this.sortKeyRanges.push({ + sortKey, + symbolInstanceStart: symbolInstanceIndex, + symbolInstanceEnd: symbolInstanceIndex + 1 + }); + } + } + sortFeatures(angle) { + if (!this.sortFeaturesByY) + return; + if (this.sortedAngle === angle) + return; + // The current approach to sorting doesn't sort across segments so don't try. + // Sorting within segments separately seemed not to be worth the complexity. + if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1) + return; + // If the symbols are allowed to overlap sort them by their vertical screen position. + // The index array buffer is rewritten to reference the (unchanged) vertices in the + // sorted order. + // To avoid sorting the actual symbolInstance array we sort an array of indexes. + this.symbolInstanceIndexes = this.getSortedSymbolIndexes(angle); + this.sortedAngle = angle; + this.text.indexArray.clear(); + this.icon.indexArray.clear(); + this.featureSortOrder = []; + for (const i of this.symbolInstanceIndexes) { + const symbolInstance = this.symbolInstances.get(i); + this.featureSortOrder.push(symbolInstance.featureIndex); + [ + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.leftJustifiedTextSymbolIndex + ].forEach((index, i, array) => { + // Only add a given index the first time it shows up, + // to avoid duplicate opacity entries when multiple justifications + // share the same glyphs. + if (index >= 0 && array.indexOf(index) === i) { + this.addIndicesForPlacedSymbol(this.text, index); + } + }); + if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) { + this.addIndicesForPlacedSymbol(this.text, symbolInstance.verticalPlacedTextSymbolIndex); + } + if (symbolInstance.placedIconSymbolIndex >= 0) { + this.addIndicesForPlacedSymbol(this.icon, symbolInstance.placedIconSymbolIndex); + } + if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) { + this.addIndicesForPlacedSymbol(this.icon, symbolInstance.verticalPlacedIconSymbolIndex); + } + } + if (this.text.indexBuffer) + this.text.indexBuffer.updateData(this.text.indexArray); + if (this.icon.indexBuffer) + this.icon.indexBuffer.updateData(this.icon.indexArray); + } +} +register('SymbolBucket', SymbolBucket, { + omit: ['layers', 'collisionBoxArray', 'features', 'compareText'] +}); +// this constant is based on the size of StructArray indexes used in a symbol +// bucket--namely, glyphOffsetArrayStart +// eg the max valid UInt16 is 65,535 +// See https://github.com/mapbox/mapbox-gl-js/issues/2907 for motivation +// lineStartIndex and textBoxStartIndex could potentially be concerns +// but we expect there to be many fewer boxes/lines than glyphs +SymbolBucket.MAX_GLYPHS = 65535; +SymbolBucket.addDynamicAttributes = addDynamicAttributes; + +/** + * Replace tokens in a string template with values in an object + * + * @param properties - a key/value relationship between tokens and replacements + * @param text - the template string + * @returns the template with tokens replaced + */ +function resolveTokens(properties, text) { + return text.replace(/{([^{}]+)}/g, (match, key) => { + return properties && key in properties ? String(properties[key]) : ''; + }); +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let layout; +const getLayout = () => layout = layout || new Properties({ + "symbol-placement": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-placement"]), + "symbol-spacing": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-spacing"]), + "symbol-avoid-edges": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-avoid-edges"]), + "symbol-sort-key": new DataDrivenProperty(v8Spec["layout_symbol"]["symbol-sort-key"]), + "symbol-z-order": new DataConstantProperty(v8Spec["layout_symbol"]["symbol-z-order"]), + "icon-allow-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["icon-allow-overlap"]), + "icon-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["icon-overlap"]), + "icon-ignore-placement": new DataConstantProperty(v8Spec["layout_symbol"]["icon-ignore-placement"]), + "icon-optional": new DataConstantProperty(v8Spec["layout_symbol"]["icon-optional"]), + "icon-rotation-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["icon-rotation-alignment"]), + "icon-size": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-size"]), + "icon-text-fit": new DataConstantProperty(v8Spec["layout_symbol"]["icon-text-fit"]), + "icon-text-fit-padding": new DataConstantProperty(v8Spec["layout_symbol"]["icon-text-fit-padding"]), + "icon-image": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-image"]), + "icon-rotate": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-rotate"]), + "icon-padding": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-padding"]), + "icon-keep-upright": new DataConstantProperty(v8Spec["layout_symbol"]["icon-keep-upright"]), + "icon-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-offset"]), + "icon-anchor": new DataDrivenProperty(v8Spec["layout_symbol"]["icon-anchor"]), + "icon-pitch-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["icon-pitch-alignment"]), + "text-pitch-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["text-pitch-alignment"]), + "text-rotation-alignment": new DataConstantProperty(v8Spec["layout_symbol"]["text-rotation-alignment"]), + "text-field": new DataDrivenProperty(v8Spec["layout_symbol"]["text-field"]), + "text-font": new DataDrivenProperty(v8Spec["layout_symbol"]["text-font"]), + "text-size": new DataDrivenProperty(v8Spec["layout_symbol"]["text-size"]), + "text-max-width": new DataDrivenProperty(v8Spec["layout_symbol"]["text-max-width"]), + "text-line-height": new DataConstantProperty(v8Spec["layout_symbol"]["text-line-height"]), + "text-letter-spacing": new DataDrivenProperty(v8Spec["layout_symbol"]["text-letter-spacing"]), + "text-justify": new DataDrivenProperty(v8Spec["layout_symbol"]["text-justify"]), + "text-radial-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["text-radial-offset"]), + "text-variable-anchor": new DataConstantProperty(v8Spec["layout_symbol"]["text-variable-anchor"]), + "text-variable-anchor-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["text-variable-anchor-offset"]), + "text-anchor": new DataDrivenProperty(v8Spec["layout_symbol"]["text-anchor"]), + "text-max-angle": new DataConstantProperty(v8Spec["layout_symbol"]["text-max-angle"]), + "text-writing-mode": new DataConstantProperty(v8Spec["layout_symbol"]["text-writing-mode"]), + "text-rotate": new DataDrivenProperty(v8Spec["layout_symbol"]["text-rotate"]), + "text-padding": new DataConstantProperty(v8Spec["layout_symbol"]["text-padding"]), + "text-keep-upright": new DataConstantProperty(v8Spec["layout_symbol"]["text-keep-upright"]), + "text-transform": new DataDrivenProperty(v8Spec["layout_symbol"]["text-transform"]), + "text-offset": new DataDrivenProperty(v8Spec["layout_symbol"]["text-offset"]), + "text-allow-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["text-allow-overlap"]), + "text-overlap": new DataConstantProperty(v8Spec["layout_symbol"]["text-overlap"]), + "text-ignore-placement": new DataConstantProperty(v8Spec["layout_symbol"]["text-ignore-placement"]), + "text-optional": new DataConstantProperty(v8Spec["layout_symbol"]["text-optional"]), +}); +let paint$2; +const getPaint$2 = () => paint$2 = paint$2 || new Properties({ + "icon-opacity": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-opacity"]), + "icon-color": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-color"]), + "icon-halo-color": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-color"]), + "icon-halo-width": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-width"]), + "icon-halo-blur": new DataDrivenProperty(v8Spec["paint_symbol"]["icon-halo-blur"]), + "icon-translate": new DataConstantProperty(v8Spec["paint_symbol"]["icon-translate"]), + "icon-translate-anchor": new DataConstantProperty(v8Spec["paint_symbol"]["icon-translate-anchor"]), + "text-opacity": new DataDrivenProperty(v8Spec["paint_symbol"]["text-opacity"]), + "text-color": new DataDrivenProperty(v8Spec["paint_symbol"]["text-color"], { runtimeType: ColorType, getOverride: (o) => o.textColor, hasOverride: (o) => !!o.textColor }), + "text-halo-color": new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-color"]), + "text-halo-width": new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-width"]), + "text-halo-blur": new DataDrivenProperty(v8Spec["paint_symbol"]["text-halo-blur"]), + "text-translate": new DataConstantProperty(v8Spec["paint_symbol"]["text-translate"]), + "text-translate-anchor": new DataConstantProperty(v8Spec["paint_symbol"]["text-translate-anchor"]), +}); +var properties$2 = ({ get paint() { return getPaint$2(); }, get layout() { return getLayout(); } }); + +// This is an internal expression class. It is only used in GL JS and +// has GL JS dependencies which can break the standalone style-spec module +class FormatSectionOverride { + constructor(defaultValue) { + if (defaultValue.property.overrides === undefined) + throw new Error('overrides must be provided to instantiate FormatSectionOverride class'); + this.type = defaultValue.property.overrides ? defaultValue.property.overrides.runtimeType : NullType; + this.defaultValue = defaultValue; + } + evaluate(ctx) { + if (ctx.formattedSection) { + const overrides = this.defaultValue.property.overrides; + if (overrides && overrides.hasOverride(ctx.formattedSection)) { + return overrides.getOverride(ctx.formattedSection); + } + } + if (ctx.feature && ctx.featureState) { + return this.defaultValue.evaluate(ctx.feature, ctx.featureState); + } + return this.defaultValue.property.specification.default; + } + eachChild(fn) { + if (!this.defaultValue.isConstant()) { + const expr = this.defaultValue.value; + fn(expr._styleExpression.expression); + } + } + // Cannot be statically evaluated, as the output depends on the evaluation context. + outputDefined() { + return false; + } + serialize() { + return null; + } +} +register('FormatSectionOverride', FormatSectionOverride, { omit: ['defaultValue'] }); + +class SymbolStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$2); + } + recalculate(parameters, availableImages) { + super.recalculate(parameters, availableImages); + if (this.layout.get('icon-rotation-alignment') === 'auto') { + if (this.layout.get('symbol-placement') !== 'point') { + this.layout._values['icon-rotation-alignment'] = 'map'; + } + else { + this.layout._values['icon-rotation-alignment'] = 'viewport'; + } + } + if (this.layout.get('text-rotation-alignment') === 'auto') { + if (this.layout.get('symbol-placement') !== 'point') { + this.layout._values['text-rotation-alignment'] = 'map'; + } + else { + this.layout._values['text-rotation-alignment'] = 'viewport'; + } + } + // If unspecified, `*-pitch-alignment` inherits `*-rotation-alignment` + if (this.layout.get('text-pitch-alignment') === 'auto') { + this.layout._values['text-pitch-alignment'] = this.layout.get('text-rotation-alignment') === 'map' ? 'map' : 'viewport'; + } + if (this.layout.get('icon-pitch-alignment') === 'auto') { + this.layout._values['icon-pitch-alignment'] = this.layout.get('icon-rotation-alignment'); + } + if (this.layout.get('symbol-placement') === 'point') { + const writingModes = this.layout.get('text-writing-mode'); + if (writingModes) { + // remove duplicates, preserving order + const deduped = []; + for (const m of writingModes) { + if (deduped.indexOf(m) < 0) + deduped.push(m); + } + this.layout._values['text-writing-mode'] = deduped; + } + else { + this.layout._values['text-writing-mode'] = ['horizontal']; + } + } + this._setPaintOverrides(); + } + getValueAndResolveTokens(name, feature, canonical, availableImages) { + const value = this.layout.get(name).evaluate(feature, {}, canonical, availableImages); + const unevaluated = this._unevaluatedLayout._values[name]; + if (!unevaluated.isDataDriven() && !isExpression(unevaluated.value) && value) { + return resolveTokens(feature.properties, value); + } + return value; + } + createBucket(parameters) { + return new SymbolBucket(parameters); + } + queryRadius() { + return 0; + } + queryIntersectsFeature() { + throw new Error('Should take a different path in FeatureIndex'); + } + _setPaintOverrides() { + for (const overridable of properties$2.paint.overridableProperties) { + if (!SymbolStyleLayer.hasPaintOverride(this.layout, overridable)) { + continue; + } + const overridden = this.paint.get(overridable); + const override = new FormatSectionOverride(overridden); + const styleExpression = new StyleExpression(override, overridden.property.specification); + let expression = null; + if (overridden.value.kind === 'constant' || overridden.value.kind === 'source') { + expression = new ZoomConstantExpression('source', styleExpression); + } + else { + expression = new ZoomDependentExpression('composite', styleExpression, overridden.value.zoomStops); + } + this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overridden.property, expression, overridden.parameters); + } + } + _handleOverridablePaintPropertyUpdate(name, oldValue, newValue) { + if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) { + return false; + } + return SymbolStyleLayer.hasPaintOverride(this.layout, name); + } + static hasPaintOverride(layout, propertyName) { + const textField = layout.get('text-field'); + const property = properties$2.paint.properties[propertyName]; + let hasOverrides = false; + const checkSections = (sections) => { + for (const section of sections) { + if (property.overrides && property.overrides.hasOverride(section)) { + hasOverrides = true; + return; + } + } + }; + if (textField.value.kind === 'constant' && textField.value.value instanceof Formatted) { + checkSections(textField.value.value.sections); + } + else if (textField.value.kind === 'source') { + const checkExpression = (expression) => { + if (hasOverrides) + return; + if (expression instanceof Literal && typeOf(expression.value) === FormattedType) { + const formatted = expression.value; + checkSections(formatted.sections); + } + else if (expression instanceof FormatExpression) { + checkSections(expression.sections); + } + else { + expression.eachChild(checkExpression); + } + }; + const expr = textField.value; + if (expr._styleExpression) { + checkExpression(expr._styleExpression.expression); + } + } + return hasOverrides; + } +} +function getIconPadding(layout, feature, canonical, pixelRatio = 1) { + // Support text-padding in addition to icon-padding? Unclear how to apply asymmetric text-padding to the radius for collision circles. + const result = layout.get('icon-padding').evaluate(feature, {}, canonical); + const values = result && result.values; + return [ + values[0] * pixelRatio, + values[1] * pixelRatio, + values[2] * pixelRatio, + values[3] * pixelRatio, + ]; +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint$1; +const getPaint$1 = () => paint$1 = paint$1 || new Properties({ + "background-color": new DataConstantProperty(v8Spec["paint_background"]["background-color"]), + "background-pattern": new CrossFadedProperty(v8Spec["paint_background"]["background-pattern"]), + "background-opacity": new DataConstantProperty(v8Spec["paint_background"]["background-opacity"]), +}); +var properties$1 = ({ get paint() { return getPaint$1(); } }); + +class BackgroundStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties$1); + } +} + +// This file is generated. Edit build/generate-style-code.ts, then run 'npm run codegen'. +/* eslint-disable */ +let paint; +const getPaint = () => paint = paint || new Properties({ + "raster-opacity": new DataConstantProperty(v8Spec["paint_raster"]["raster-opacity"]), + "raster-hue-rotate": new DataConstantProperty(v8Spec["paint_raster"]["raster-hue-rotate"]), + "raster-brightness-min": new DataConstantProperty(v8Spec["paint_raster"]["raster-brightness-min"]), + "raster-brightness-max": new DataConstantProperty(v8Spec["paint_raster"]["raster-brightness-max"]), + "raster-saturation": new DataConstantProperty(v8Spec["paint_raster"]["raster-saturation"]), + "raster-contrast": new DataConstantProperty(v8Spec["paint_raster"]["raster-contrast"]), + "raster-resampling": new DataConstantProperty(v8Spec["paint_raster"]["raster-resampling"]), + "raster-fade-duration": new DataConstantProperty(v8Spec["paint_raster"]["raster-fade-duration"]), +}); +var properties = ({ get paint() { return getPaint(); } }); + +class RasterStyleLayer extends StyleLayer { + constructor(layer) { + super(layer, properties); + } +} + +function validateCustomStyleLayer(layerObject) { + const errors = []; + const id = layerObject.id; + if (id === undefined) { + errors.push({ + message: `layers.${id}: missing required property "id"` + }); + } + if (layerObject.render === undefined) { + errors.push({ + message: `layers.${id}: missing required method "render"` + }); + } + if (layerObject.renderingMode && + layerObject.renderingMode !== '2d' && + layerObject.renderingMode !== '3d') { + errors.push({ + message: `layers.${id}: property "renderingMode" must be either "2d" or "3d"` + }); + } + return errors; +} +class CustomStyleLayer extends StyleLayer { + constructor(implementation) { + super(implementation, {}); + this.onAdd = (map) => { + if (this.implementation.onAdd) { + this.implementation.onAdd(map, map.painter.context.gl); + } + }; + this.onRemove = (map) => { + if (this.implementation.onRemove) { + this.implementation.onRemove(map, map.painter.context.gl); + } + }; + this.implementation = implementation; + } + is3D() { + return this.implementation.renderingMode === '3d'; + } + hasOffscreenPass() { + return this.implementation.prerender !== undefined; + } + recalculate() { } + updateTransitions() { } + hasTransition() { return false; } + serialize() { + throw new Error('Custom layers cannot be serialized'); + } +} + +function createStyleLayer(layer) { + if (layer.type === 'custom') { + return new CustomStyleLayer(layer); + } + switch (layer.type) { + case 'background': + return new BackgroundStyleLayer(layer); + case 'circle': + return new CircleStyleLayer(layer); + case 'fill': + return new FillStyleLayer(layer); + case 'fill-extrusion': + return new FillExtrusionStyleLayer(layer); + case 'heatmap': + return new HeatmapStyleLayer(layer); + case 'hillshade': + return new HillshadeStyleLayer(layer); + case 'line': + return new LineStyleLayer(layer); + case 'raster': + return new RasterStyleLayer(layer); + case 'symbol': + return new SymbolStyleLayer(layer); + } +} + +/** + * Invokes the wrapped function in a non-blocking way when trigger() is called. + * Invocation requests are ignored until the function was actually invoked. + */ +class ThrottledInvoker { + constructor(methodToThrottle) { + this._methodToThrottle = methodToThrottle; + this._triggered = false; + if (typeof MessageChannel !== 'undefined') { + this._channel = new MessageChannel(); + this._channel.port2.onmessage = () => { + this._triggered = false; + this._methodToThrottle(); + }; + } + } + trigger() { + if (this._triggered) { + return; + } + this._triggered = true; + if (this._channel) { + this._channel.port1.postMessage(true); + } + else { + setTimeout(() => { + this._triggered = false; + this._methodToThrottle(); + }, 0); + } + } + remove() { + delete this._channel; + this._methodToThrottle = () => { }; + } +} + +/** + * An implementation of the [Actor design pattern](https://en.wikipedia.org/wiki/Actor_model) + * that maintains the relationship between asynchronous tasks and the objects + * that spin them off - in this case, tasks like parsing parts of styles, + * owned by the styles + */ +class Actor { + /** + * @param target - The target + * @param mapId - A unique identifier for the Map instance using this Actor. + */ + constructor(target, mapId) { + this.target = target; + this.mapId = mapId; + this.resolveRejects = {}; + this.tasks = {}; + this.taskQueue = []; + this.abortControllers = {}; + this.messageHandlers = {}; + this.invoker = new ThrottledInvoker(() => this.process()); + this.subscription = subscribe(this.target, 'message', (message) => this.receive(message), false); + this.globalScope = isWorker(self) ? target : window; + } + registerMessageHandler(type, handler) { + this.messageHandlers[type] = handler; + } + /** + * Sends a message from a main-thread map to a Worker or from a Worker back to + * a main-thread map instance. + * @param message - the message to send + * @param abortController - an optional AbortController to abort the request + * @returns a promise that will be resolved with the response data + */ + sendAsync(message, abortController) { + return new Promise((resolve, reject) => { + // We're using a string ID instead of numbers because they are being used as object keys + // anyway, and thus stringified implicitly. We use random IDs because an actor may receive + // message from multiple other actors which could run in different execution context. A + // linearly increasing ID could produce collisions. + const id = Math.round((Math.random() * 1e18)).toString(36).substring(0, 10); + this.resolveRejects[id] = { + resolve, + reject + }; + if (abortController) { + abortController.signal.addEventListener('abort', () => { + delete this.resolveRejects[id]; + const cancelMessage = { + id, + type: '', + origin: location.origin, + targetMapId: message.targetMapId, + sourceMapId: this.mapId + }; + this.target.postMessage(cancelMessage); + // In case of abort the current behavior is to keep the promise pending. + }, { once: true }); + } + const buffers = []; + const messageToPost = Object.assign(Object.assign({}, message), { id, sourceMapId: this.mapId, origin: location.origin, data: serialize(message.data, buffers) }); + this.target.postMessage(messageToPost, { transfer: buffers }); + }); + } + receive(message) { + const data = message.data; + const id = data.id; + if (data.origin !== 'file://' && location.origin !== 'file://' && data.origin !== 'resource://android' && location.origin !== 'resource://android' && data.origin !== location.origin) { + return; + } + if (data.targetMapId && this.mapId !== data.targetMapId) { + return; + } + if (data.type === '') { + // Remove the original request from the queue. This is only possible if it + // hasn't been kicked off yet. The id will remain in the queue, but because + // there is no associated task, it will be dropped once it's time to execute it. + delete this.tasks[id]; + const abortController = this.abortControllers[id]; + delete this.abortControllers[id]; + if (abortController) { + abortController.abort(); + } + return; + } + if (isWorker(self) || data.mustQueue) { + // In workers, store the tasks that we need to process before actually processing them. This + // is necessary because we want to keep receiving messages, and in particular, + // messages. Some tasks may take a while in the worker thread, so before + // executing the next task in our queue, postMessage preempts this and + // messages can be processed. We're using a MessageChannel object to get throttle the + // process() flow to one at a time. + this.tasks[id] = data; + this.taskQueue.push(id); + this.invoker.trigger(); + return; + } + // In the main thread, process messages immediately so that other work does not slip in + // between getting partial data back from workers. + this.processTask(id, data); + } + process() { + if (this.taskQueue.length === 0) { + return; + } + const id = this.taskQueue.shift(); + const task = this.tasks[id]; + delete this.tasks[id]; + // Schedule another process call if we know there's more to process _before_ invoking the + // current task. This is necessary so that processing continues even if the current task + // doesn't execute successfully. + if (this.taskQueue.length > 0) { + this.invoker.trigger(); + } + if (!task) { + // If the task ID doesn't have associated task data anymore, it was canceled. + return; + } + this.processTask(id, task); + } + processTask(id, task) { + return __awaiter(this, void 0, void 0, function* () { + if (task.type === '') { + // The `completeTask` function in the counterpart actor has been called, and we are now + // resolving or rejecting the promise in the originating actor, if there is one. + const resolveReject = this.resolveRejects[id]; + delete this.resolveRejects[id]; + if (!resolveReject) { + // If we get a response, but don't have a resolve or reject, the request was canceled. + return; + } + if (task.error) { + resolveReject.reject(deserialize(task.error)); + } + else { + resolveReject.resolve(deserialize(task.data)); + } + return; + } + if (!this.messageHandlers[task.type]) { + this.completeTask(id, new Error(`Could not find a registered handler for ${task.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(', ')}`)); + return; + } + const params = deserialize(task.data); + const abortController = new AbortController(); + this.abortControllers[id] = abortController; + try { + const data = yield this.messageHandlers[task.type](task.sourceMapId, params, abortController); + this.completeTask(id, null, data); + } + catch (err) { + this.completeTask(id, err); + } + }); + } + completeTask(id, err, data) { + const buffers = []; + delete this.abortControllers[id]; + const responseMessage = { + id, + type: '', + sourceMapId: this.mapId, + origin: location.origin, + error: err ? serialize(err) : null, + data: serialize(data, buffers) + }; + this.target.postMessage(responseMessage, { transfer: buffers }); + } + remove() { + this.invoker.remove(); + this.subscription.unsubscribe(); + } +} + +/* +* Approximate radius of the earth in meters. +* 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 +* 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 +*/ +const earthRadius = 6371008.8; +/** + * A `LngLat` object represents a given longitude and latitude coordinate, measured in degrees. + * These coordinates are based on the [WGS84 (EPSG:4326) standard](https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84). + * + * MapLibre GL JS uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match the + * [GeoJSON specification](https://tools.ietf.org/html/rfc7946). + * + * Note that any MapLibre GL JS method that accepts a `LngLat` object as an argument or option + * can also accept an `Array` of two numbers and will perform an implicit conversion. + * This flexible type is documented as {@link LngLatLike}. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let ll = new LngLat(-123.9749, 40.7736); + * ll.lng; // = -123.9749 + * ``` + * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/) + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Create a timeline animation](https://maplibre.org/maplibre-gl-js/docs/examples/timeline-animation/) + */ +class LngLat { + /** + * @param lng - Longitude, measured in degrees. + * @param lat - Latitude, measured in degrees. + */ + constructor(lng, lat) { + if (isNaN(lng) || isNaN(lat)) { + throw new Error(`Invalid LngLat object: (${lng}, ${lat})`); + } + this.lng = +lng; + this.lat = +lat; + if (this.lat > 90 || this.lat < -90) { + throw new Error('Invalid LngLat latitude value: must be between -90 and 90'); + } + } + /** + * Returns a new `LngLat` object whose longitude is wrapped to the range (-180, 180). + * + * @returns The wrapped `LngLat` object. + * @example + * ```ts + * let ll = new LngLat(286.0251, 40.7736); + * let wrapped = ll.wrap(); + * wrapped.lng; // = -73.9749 + * ``` + */ + wrap() { + return new LngLat(wrap(this.lng, -180, 180), this.lat); + } + /** + * Returns the coordinates represented as an array of two numbers. + * + * @returns The coordinates represented as an array of longitude and latitude. + * @example + * ```ts + * let ll = new LngLat(-73.9749, 40.7736); + * ll.toArray(); // = [-73.9749, 40.7736] + * ``` + */ + toArray() { + return [this.lng, this.lat]; + } + /** + * Returns the coordinates represent as a string. + * + * @returns The coordinates represented as a string of the format `'LngLat(lng, lat)'`. + * @example + * ```ts + * let ll = new LngLat(-73.9749, 40.7736); + * ll.toString(); // = "LngLat(-73.9749, 40.7736)" + * ``` + */ + toString() { + return `LngLat(${this.lng}, ${this.lat})`; + } + /** + * Returns the approximate distance between a pair of coordinates in meters + * Uses the Haversine Formula (from R.W. Sinnott, "Virtues of the Haversine", Sky and Telescope, vol. 68, no. 2, 1984, p. 159) + * + * @param lngLat - coordinates to compute the distance to + * @returns Distance in meters between the two coordinates. + * @example + * ```ts + * let new_york = new LngLat(-74.0060, 40.7128); + * let los_angeles = new LngLat(-118.2437, 34.0522); + * new_york.distanceTo(los_angeles); // = 3935751.690893987, "true distance" using a non-spherical approximation is ~3966km + * ``` + */ + distanceTo(lngLat) { + const rad = Math.PI / 180; + const lat1 = this.lat * rad; + const lat2 = lngLat.lat * rad; + const a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((lngLat.lng - this.lng) * rad); + const maxMeters = earthRadius * Math.acos(Math.min(a, 1)); + return maxMeters; + } + /** + * Converts an array of two numbers or an object with `lng` and `lat` or `lon` and `lat` properties + * to a `LngLat` object. + * + * If a `LngLat` object is passed in, the function returns it unchanged. + * + * @param input - An array of two numbers or object to convert, or a `LngLat` object to return. + * @returns A new `LngLat` object, if a conversion occurred, or the original `LngLat` object. + * @example + * ```ts + * let arr = [-73.9749, 40.7736]; + * let ll = LngLat.convert(arr); + * ll; // = LngLat {lng: -73.9749, lat: 40.7736} + * ``` + */ + static convert(input) { + if (input instanceof LngLat) { + return input; + } + if (Array.isArray(input) && (input.length === 2 || input.length === 3)) { + return new LngLat(Number(input[0]), Number(input[1])); + } + if (!Array.isArray(input) && typeof input === 'object' && input !== null) { + return new LngLat( + // flow can't refine this to have one of lng or lat, so we have to cast to any + Number('lng' in input ? input.lng : input.lon), Number(input.lat)); + } + throw new Error('`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]'); + } +} + +/* + * The average circumference of the world in meters. + */ +const earthCircumference = 2 * Math.PI * earthRadius; // meters +/* + * The circumference at a line of latitude in meters. + */ +function circumferenceAtLatitude(latitude) { + return earthCircumference * Math.cos(latitude * Math.PI / 180); +} +function mercatorXfromLng(lng) { + return (180 + lng) / 360; +} +function mercatorYfromLat(lat) { + return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360; +} +function mercatorZfromAltitude(altitude, lat) { + return altitude / circumferenceAtLatitude(lat); +} +function lngFromMercatorX(x) { + return x * 360 - 180; +} +function latFromMercatorY(y) { + const y2 = 180 - y * 360; + return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90; +} +function altitudeFromMercatorZ(z, y) { + return z * circumferenceAtLatitude(latFromMercatorY(y)); +} +/** + * Determine the Mercator scale factor for a given latitude, see + * https://en.wikipedia.org/wiki/Mercator_projection#Scale_factor + * + * At the equator the scale factor will be 1, which increases at higher latitudes. + * + * @param lat - Latitude + * @returns scale factor + */ +function mercatorScale(lat) { + return 1 / Math.cos(lat * Math.PI / 180); +} +/** + * A `MercatorCoordinate` object represents a projected three dimensional position. + * + * `MercatorCoordinate` uses the web mercator projection ([EPSG:3857](https://epsg.io/3857)) with slightly different units: + * + * - the size of 1 unit is the width of the projected world instead of the "mercator meter" + * - the origin of the coordinate space is at the north-west corner instead of the middle + * + * For example, `MercatorCoordinate(0, 0, 0)` is the north-west corner of the mercator world and + * `MercatorCoordinate(1, 1, 0)` is the south-east corner. If you are familiar with + * [vector tiles](https://github.com/mapbox/vector-tile-spec) it may be helpful to think + * of the coordinate space as the `0/0/0` tile with an extent of `1`. + * + * The `z` dimension of `MercatorCoordinate` is conformal. A cube in the mercator coordinate space would be rendered as a cube. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let nullIsland = new MercatorCoordinate(0.5, 0.5, 0); + * ``` + * @see [Add a custom style layer](https://maplibre.org/maplibre-gl-js/docs/examples/custom-style-layer/) + */ +class MercatorCoordinate { + /** + * @param x - The x component of the position. + * @param y - The y component of the position. + * @param z - The z component of the position. + */ + constructor(x, y, z = 0) { + this.x = +x; + this.y = +y; + this.z = +z; + } + /** + * Project a `LngLat` to a `MercatorCoordinate`. + * + * @param lngLatLike - The location to project. + * @param altitude - The altitude in meters of the position. + * @returns The projected mercator coordinate. + * @example + * ```ts + * let coord = MercatorCoordinate.fromLngLat({ lng: 0, lat: 0}, 0); + * coord; // MercatorCoordinate(0.5, 0.5, 0) + * ``` + */ + static fromLngLat(lngLatLike, altitude = 0) { + const lngLat = LngLat.convert(lngLatLike); + return new MercatorCoordinate(mercatorXfromLng(lngLat.lng), mercatorYfromLat(lngLat.lat), mercatorZfromAltitude(altitude, lngLat.lat)); + } + /** + * Returns the `LngLat` for the coordinate. + * + * @returns The `LngLat` object. + * @example + * ```ts + * let coord = new MercatorCoordinate(0.5, 0.5, 0); + * let lngLat = coord.toLngLat(); // LngLat(0, 0) + * ``` + */ + toLngLat() { + return new LngLat(lngFromMercatorX(this.x), latFromMercatorY(this.y)); + } + /** + * Returns the altitude in meters of the coordinate. + * + * @returns The altitude in meters. + * @example + * ```ts + * let coord = new MercatorCoordinate(0, 0, 0.02); + * coord.toAltitude(); // 6914.281956295339 + * ``` + */ + toAltitude() { + return altitudeFromMercatorZ(this.z, this.y); + } + /** + * Returns the distance of 1 meter in `MercatorCoordinate` units at this latitude. + * + * For coordinates in real world units using meters, this naturally provides the scale + * to transform into `MercatorCoordinate`s. + * + * @returns Distance of 1 meter in `MercatorCoordinate` units. + */ + meterInMercatorCoordinateUnits() { + // 1 meter / circumference at equator in meters * Mercator projection scale factor at this latitude + return 1 / earthCircumference * mercatorScale(latFromMercatorY(this.y)); + } +} + +/** + * getTileBBox + * + * @param {Number} x Tile coordinate x + * @param {Number} y Tile coordinate y + * @param {Number} z Tile zoom + * @returns {String} String of the bounding box + */ +function getTileBBox(x, y, z) { + // for Google/OSM tile scheme we need to alter the y + y = (Math.pow(2, z) - y - 1); + + var min = getMercCoords(x * 256, y * 256, z), + max = getMercCoords((x + 1) * 256, (y + 1) * 256, z); + + return min[0] + ',' + min[1] + ',' + max[0] + ',' + max[1]; +} + + +/** + * getMercCoords + * + * @param {Number} x Pixel coordinate x + * @param {Number} y Pixel coordinate y + * @param {Number} z Tile zoom + * @returns {Array} [x, y] + */ +function getMercCoords(x, y, z) { + var resolution = (2 * Math.PI * 6378137 / 256) / Math.pow(2, z), + merc_x = (x * resolution - 2 * Math.PI * 6378137 / 2.0), + merc_y = (y * resolution - 2 * Math.PI * 6378137 / 2.0); + + return [merc_x, merc_y]; +} + +/** + * Returns true if a given tile zoom (Z), X, and Y are in the bounds of the world. + * Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive). + * X and Y bounds are 0 (inclusive) to their respective zoom-dependent maxima (exclusive). + * + * @param zoom - the tile zoom (Z) + * @param x - the tile X + * @param y - the tile Y + * @returns `true` if a given tile zoom, X, and Y are in the bounds of the world. + */ +function isInBoundsForTileZoomXY(zoom, x, y) { + return !(zoom < MIN_TILE_ZOOM || + zoom > MAX_TILE_ZOOM || + y < 0 || + y >= Math.pow(2, zoom) || + x < 0 || + x >= Math.pow(2, zoom)); +} +/** + * Returns true if a given zoom and `LngLat` are in the bounds of the world. + * Does not wrap `LngLat` when checking if in bounds. + * Zoom bounds are the minimum zoom (inclusive) through the maximum zoom (inclusive). + * `LngLat` bounds are the mercator world's north-west corner (inclusive) to its south-east corner (exclusive). + * + * @param zoom - the tile zoom (Z) + * @param LngLat - the `LngLat` object containing the longitude and latitude + * @returns `true` if a given zoom and `LngLat` are in the bounds of the world. + */ +function isInBoundsForZoomLngLat(zoom, lnglat) { + const { x, y } = MercatorCoordinate.fromLngLat(lnglat); + return !(zoom < MIN_TILE_ZOOM || + zoom > MAX_TILE_ZOOM || + y < 0 || + y >= 1 || + x < 0 || + x >= 1); +} + +/** + * A canonical way to define a tile ID + */ +class CanonicalTileID { + constructor(z, x, y) { + if (!isInBoundsForTileZoomXY(z, x, y)) { + throw new Error(`x=${x}, y=${y}, z=${z} outside of bounds. 0<=x<${Math.pow(2, z)}, 0<=y<${Math.pow(2, z)} ${MIN_TILE_ZOOM}<=z<=${MAX_TILE_ZOOM} `); + } + this.z = z; + this.x = x; + this.y = y; + this.key = calculateKey(0, z, z, x, y); + } + equals(id) { + return this.z === id.z && this.x === id.x && this.y === id.y; + } + // given a list of urls, choose a url template and return a tile URL + url(urls, pixelRatio, scheme) { + const bbox = getTileBBox(this.x, this.y, this.z); + const quadkey = getQuadkey(this.z, this.x, this.y); + return urls[(this.x + this.y) % urls.length] + .replace(/{prefix}/g, (this.x % 16).toString(16) + (this.y % 16).toString(16)) + .replace(/{z}/g, String(this.z)) + .replace(/{x}/g, String(this.x)) + .replace(/{y}/g, String(scheme === 'tms' ? (Math.pow(2, this.z) - this.y - 1) : this.y)) + .replace(/{ratio}/g, pixelRatio > 1 ? '@2x' : '') + .replace(/{quadkey}/g, quadkey) + .replace(/{bbox-epsg-3857}/g, bbox); + } + isChildOf(parent) { + const dz = this.z - parent.z; + return dz > 0 && parent.x === (this.x >> dz) && parent.y === (this.y >> dz); + } + getTilePoint(coord) { + const tilesAtZoom = Math.pow(2, this.z); + return new Point$2((coord.x * tilesAtZoom - this.x) * EXTENT, (coord.y * tilesAtZoom - this.y) * EXTENT); + } + toString() { + return `${this.z}/${this.x}/${this.y}`; + } +} +/** + * @internal + * An unwrapped tile identifier + */ +class UnwrappedTileID { + constructor(wrap, canonical) { + this.wrap = wrap; + this.canonical = canonical; + this.key = calculateKey(wrap, canonical.z, canonical.z, canonical.x, canonical.y); + } +} +/** + * An overscaled tile identifier + */ +class OverscaledTileID { + constructor(overscaledZ, wrap, z, x, y) { + if (overscaledZ < z) + throw new Error(`overscaledZ should be >= z; overscaledZ = ${overscaledZ}; z = ${z}`); + this.overscaledZ = overscaledZ; + this.wrap = wrap; + this.canonical = new CanonicalTileID(z, +x, +y); + this.key = calculateKey(wrap, overscaledZ, z, x, y); + } + clone() { + return new OverscaledTileID(this.overscaledZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } + equals(id) { + return this.overscaledZ === id.overscaledZ && this.wrap === id.wrap && this.canonical.equals(id.canonical); + } + scaledTo(targetZ) { + if (targetZ > this.overscaledZ) + throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`); + const zDifference = this.canonical.z - targetZ; + if (targetZ > this.canonical.z) { + return new OverscaledTileID(targetZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } + else { + return new OverscaledTileID(targetZ, this.wrap, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference); + } + } + /* + * calculateScaledKey is an optimization: + * when withWrap == true, implements the same as this.scaledTo(z).key, + * when withWrap == false, implements the same as this.scaledTo(z).wrapped().key. + */ + calculateScaledKey(targetZ, withWrap) { + if (targetZ > this.overscaledZ) + throw new Error(`targetZ > this.overscaledZ; targetZ = ${targetZ}; overscaledZ = ${this.overscaledZ}`); + const zDifference = this.canonical.z - targetZ; + if (targetZ > this.canonical.z) { + return calculateKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y); + } + else { + return calculateKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference); + } + } + isChildOf(parent) { + if (parent.wrap !== this.wrap) { + // We can't be a child if we're in a different world copy + return false; + } + const zDifference = this.canonical.z - parent.canonical.z; + // We're first testing for z == 0, to avoid a 32 bit shift, which is undefined. + return parent.overscaledZ === 0 || (parent.overscaledZ < this.overscaledZ && + parent.canonical.x === (this.canonical.x >> zDifference) && + parent.canonical.y === (this.canonical.y >> zDifference)); + } + children(sourceMaxZoom) { + if (this.overscaledZ >= sourceMaxZoom) { + // return a single tile coord representing a an overscaled tile + return [new OverscaledTileID(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)]; + } + const z = this.canonical.z + 1; + const x = this.canonical.x * 2; + const y = this.canonical.y * 2; + return [ + new OverscaledTileID(z, this.wrap, z, x, y), + new OverscaledTileID(z, this.wrap, z, x + 1, y), + new OverscaledTileID(z, this.wrap, z, x, y + 1), + new OverscaledTileID(z, this.wrap, z, x + 1, y + 1) + ]; + } + isLessThan(rhs) { + if (this.wrap < rhs.wrap) + return true; + if (this.wrap > rhs.wrap) + return false; + if (this.overscaledZ < rhs.overscaledZ) + return true; + if (this.overscaledZ > rhs.overscaledZ) + return false; + if (this.canonical.x < rhs.canonical.x) + return true; + if (this.canonical.x > rhs.canonical.x) + return false; + if (this.canonical.y < rhs.canonical.y) + return true; + return false; + } + wrapped() { + return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y); + } + unwrapTo(wrap) { + return new OverscaledTileID(this.overscaledZ, wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } + overscaleFactor() { + return Math.pow(2, this.overscaledZ - this.canonical.z); + } + toUnwrapped() { + return new UnwrappedTileID(this.wrap, this.canonical); + } + toString() { + return `${this.overscaledZ}/${this.canonical.x}/${this.canonical.y}`; + } + getTilePoint(coord) { + return this.canonical.getTilePoint(new MercatorCoordinate(coord.x - this.wrap, coord.y)); + } +} +function calculateKey(wrap, overscaledZ, z, x, y) { + wrap *= 2; + if (wrap < 0) + wrap = wrap * -1 - 1; + const dim = 1 << z; + return (dim * dim * wrap + dim * y + x).toString(36) + z.toString(36) + overscaledZ.toString(36); +} +function getQuadkey(z, x, y) { + let quadkey = '', mask; + for (let i = z; i > 0; i--) { + mask = 1 << (i - 1); + quadkey += ((x & mask ? 1 : 0) + (y & mask ? 2 : 0)); + } + return quadkey; +} +register('CanonicalTileID', CanonicalTileID); +register('OverscaledTileID', OverscaledTileID, { omit: ['posMatrix'] }); + +/** + * DEMData is a data structure for decoding, backfilling, and storing elevation data for processing in the hillshade shaders + * data can be populated either from a pngraw image tile or from serialized data sent back from a worker. When data is initially + * loaded from a image tile, we decode the pixel values using the appropriate decoding formula, but we store the + * elevation data as an Int32 value. we add 65536 (2^16) to eliminate negative values and enable the use of + * integer overflow when creating the texture used in the hillshadePrepare step. + * + * DEMData also handles the backfilling of data from a tile's neighboring tiles. This is necessary because we use a pixel's 8 + * surrounding pixel values to compute the slope at that pixel, and we cannot accurately calculate the slope at pixels on a + * tile's edge without backfilling from neighboring tiles. + */ +class DEMData { + /** + * Constructs a `DEMData` object + * @param uid - the tile's unique id + * @param data - RGBAImage data has uniform 1px padding on all sides: square tile edge size defines stride + // and dim is calculated as stride - 2. + * @param encoding - the encoding type of the data + * @param redFactor - the red channel factor used to unpack the data, used for `custom` encoding only + * @param greenFactor - the green channel factor used to unpack the data, used for `custom` encoding only + * @param blueFactor - the blue channel factor used to unpack the data, used for `custom` encoding only + * @param baseShift - the base shift used to unpack the data, used for `custom` encoding only + */ + constructor(uid, data, encoding, redFactor = 1.0, greenFactor = 1.0, blueFactor = 1.0, baseShift = 0.0) { + this.uid = uid; + if (data.height !== data.width) + throw new RangeError('DEM tiles must be square'); + if (encoding && !['mapbox', 'terrarium', 'custom'].includes(encoding)) { + warnOnce(`"${encoding}" is not a valid encoding type. Valid types include "mapbox", "terrarium" and "custom".`); + return; + } + this.stride = data.height; + const dim = this.dim = data.height - 2; + this.data = new Uint32Array(data.data.buffer); + switch (encoding) { + case 'terrarium': + // unpacking formula for mapzen terrarium: + // https://aws.amazon.com/public-datasets/terrain/ + this.redFactor = 256.0; + this.greenFactor = 1.0; + this.blueFactor = 1.0 / 256.0; + this.baseShift = 32768.0; + break; + case 'custom': + this.redFactor = redFactor; + this.greenFactor = greenFactor; + this.blueFactor = blueFactor; + this.baseShift = baseShift; + break; + case 'mapbox': + default: + // unpacking formula for mapbox.terrain-rgb: + // https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb + this.redFactor = 6553.6; + this.greenFactor = 25.6; + this.blueFactor = 0.1; + this.baseShift = 10000.0; + break; + } + // in order to avoid flashing seams between tiles, here we are initially populating a 1px border of pixels around the image + // with the data of the nearest pixel from the image. this data is eventually replaced when the tile's neighboring + // tiles are loaded and the accurate data can be backfilled using DEMData#backfillBorder + for (let x = 0; x < dim; x++) { + // left vertical border + this.data[this._idx(-1, x)] = this.data[this._idx(0, x)]; + // right vertical border + this.data[this._idx(dim, x)] = this.data[this._idx(dim - 1, x)]; + // left horizontal border + this.data[this._idx(x, -1)] = this.data[this._idx(x, 0)]; + // right horizontal border + this.data[this._idx(x, dim)] = this.data[this._idx(x, dim - 1)]; + } + // corners + this.data[this._idx(-1, -1)] = this.data[this._idx(0, 0)]; + this.data[this._idx(dim, -1)] = this.data[this._idx(dim - 1, 0)]; + this.data[this._idx(-1, dim)] = this.data[this._idx(0, dim - 1)]; + this.data[this._idx(dim, dim)] = this.data[this._idx(dim - 1, dim - 1)]; + // calculate min/max values + this.min = Number.MAX_SAFE_INTEGER; + this.max = Number.MIN_SAFE_INTEGER; + for (let x = 0; x < dim; x++) { + for (let y = 0; y < dim; y++) { + const ele = this.get(x, y); + if (ele > this.max) + this.max = ele; + if (ele < this.min) + this.min = ele; + } + } + } + get(x, y) { + const pixels = new Uint8Array(this.data.buffer); + const index = this._idx(x, y) * 4; + return this.unpack(pixels[index], pixels[index + 1], pixels[index + 2]); + } + getUnpackVector() { + return [this.redFactor, this.greenFactor, this.blueFactor, this.baseShift]; + } + _idx(x, y) { + if (x < -1 || x >= this.dim + 1 || y < -1 || y >= this.dim + 1) + throw new RangeError('out of range source coordinates for DEM data'); + return (y + 1) * this.stride + (x + 1); + } + unpack(r, g, b) { + return (r * this.redFactor + g * this.greenFactor + b * this.blueFactor - this.baseShift); + } + getPixels() { + return new RGBAImage({ width: this.stride, height: this.stride }, new Uint8Array(this.data.buffer)); + } + backfillBorder(borderTile, dx, dy) { + if (this.dim !== borderTile.dim) + throw new Error('dem dimension mismatch'); + let xMin = dx * this.dim, xMax = dx * this.dim + this.dim, yMin = dy * this.dim, yMax = dy * this.dim + this.dim; + switch (dx) { + case -1: + xMin = xMax - 1; + break; + case 1: + xMax = xMin + 1; + break; + } + switch (dy) { + case -1: + yMin = yMax - 1; + break; + case 1: + yMax = yMin + 1; + break; + } + const ox = -dx * this.dim; + const oy = -dy * this.dim; + for (let y = yMin; y < yMax; y++) { + for (let x = xMin; x < xMax; x++) { + this.data[this._idx(x, y)] = borderTile.data[this._idx(x + ox, y + oy)]; + } + } + } +} +register('DEMData', DEMData); + +class DictionaryCoder { + constructor(strings) { + this._stringToNumber = {}; + this._numberToString = []; + for (let i = 0; i < strings.length; i++) { + const string = strings[i]; + this._stringToNumber[string] = i; + this._numberToString[i] = string; + } + } + encode(string) { + return this._stringToNumber[string]; + } + decode(n) { + if (n >= this._numberToString.length) + throw new Error(`Out of bounds. Index requested n=${n} can't be >= this._numberToString.length ${this._numberToString.length}`); + return this._numberToString[n]; + } +} + +/** + * A geojson feature + */ +class GeoJSONFeature { + constructor(vectorTileFeature, z, x, y, id) { + this.type = 'Feature'; + this._vectorTileFeature = vectorTileFeature; + vectorTileFeature._z = z; + vectorTileFeature._x = x; + vectorTileFeature._y = y; + this.properties = vectorTileFeature.properties; + this.id = id; + } + get geometry() { + if (this._geometry === undefined) { + this._geometry = this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x, this._vectorTileFeature._y, this._vectorTileFeature._z).geometry; + } + return this._geometry; + } + set geometry(g) { + this._geometry = g; + } + toJSON() { + const json = { + geometry: this.geometry + }; + for (const i in this) { + if (i === '_geometry' || i === '_vectorTileFeature') + continue; + json[i] = (this)[i]; + } + return json; + } +} + +/** + * An in memory index class to allow fast interaction with features + */ +class FeatureIndex { + constructor(tileID, promoteId) { + this.tileID = tileID; + this.x = tileID.canonical.x; + this.y = tileID.canonical.y; + this.z = tileID.canonical.z; + this.grid = new TransferableGridIndex(EXTENT, 16, 0); + this.grid3D = new TransferableGridIndex(EXTENT, 16, 0); + this.featureIndexArray = new FeatureIndexArray(); + this.promoteId = promoteId; + } + insert(feature, geometry, featureIndex, sourceLayerIndex, bucketIndex, is3D) { + const key = this.featureIndexArray.length; + this.featureIndexArray.emplaceBack(featureIndex, sourceLayerIndex, bucketIndex); + const grid = is3D ? this.grid3D : this.grid; + for (let r = 0; r < geometry.length; r++) { + const ring = geometry[r]; + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + for (let i = 0; i < ring.length; i++) { + const p = ring[i]; + bbox[0] = Math.min(bbox[0], p.x); + bbox[1] = Math.min(bbox[1], p.y); + bbox[2] = Math.max(bbox[2], p.x); + bbox[3] = Math.max(bbox[3], p.y); + } + if (bbox[0] < EXTENT && + bbox[1] < EXTENT && + bbox[2] >= 0 && + bbox[3] >= 0) { + grid.insert(key, bbox[0], bbox[1], bbox[2], bbox[3]); + } + } + } + loadVTLayers() { + if (!this.vtLayers) { + this.vtLayers = new vectorTile.VectorTile(new Protobuf(this.rawTileData)).layers; + this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : ['_geojsonTileLayer']); + } + return this.vtLayers; + } + // Finds non-symbol features in this tile at a particular position. + query(args, styleLayers, serializedLayers, sourceFeatureState) { + this.loadVTLayers(); + const params = args.params || {}, pixelsToTileUnits = EXTENT / args.tileSize / args.scale, filter = createFilter(params.filter); + const queryGeometry = args.queryGeometry; + const queryPadding = args.queryPadding * pixelsToTileUnits; + const bounds = getBounds(queryGeometry); + const matching = this.grid.query(bounds.minX - queryPadding, bounds.minY - queryPadding, bounds.maxX + queryPadding, bounds.maxY + queryPadding); + const cameraBounds = getBounds(args.cameraQueryGeometry); + const matching3D = this.grid3D.query(cameraBounds.minX - queryPadding, cameraBounds.minY - queryPadding, cameraBounds.maxX + queryPadding, cameraBounds.maxY + queryPadding, (bx1, by1, bx2, by2) => { + return polygonIntersectsBox(args.cameraQueryGeometry, bx1 - queryPadding, by1 - queryPadding, bx2 + queryPadding, by2 + queryPadding); + }); + for (const key of matching3D) { + matching.push(key); + } + matching.sort(topDownFeatureComparator); + const result = {}; + let previousIndex; + for (let k = 0; k < matching.length; k++) { + const index = matching[k]; + // don't check the same feature more than once + if (index === previousIndex) + continue; + previousIndex = index; + const match = this.featureIndexArray.get(index); + let featureGeometry = null; + this.loadMatchingFeature(result, match.bucketIndex, match.sourceLayerIndex, match.featureIndex, filter, params.layers, params.availableImages, styleLayers, serializedLayers, sourceFeatureState, (feature, styleLayer, featureState) => { + if (!featureGeometry) { + featureGeometry = loadGeometry(feature); + } + return styleLayer.queryIntersectsFeature(queryGeometry, feature, featureState, featureGeometry, this.z, args.transform, pixelsToTileUnits, args.pixelPosMatrix); + }); + } + return result; + } + loadMatchingFeature(result, bucketIndex, sourceLayerIndex, featureIndex, filter, filterLayerIDs, availableImages, styleLayers, serializedLayers, sourceFeatureState, intersectionTest) { + const layerIDs = this.bucketLayerIDs[bucketIndex]; + if (filterLayerIDs && !arraysIntersect(filterLayerIDs, layerIDs)) + return; + const sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex); + const sourceLayer = this.vtLayers[sourceLayerName]; + const feature = sourceLayer.feature(featureIndex); + if (filter.needGeometry) { + const evaluationFeature = toEvaluationFeature(feature, true); + if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) { + return; + } + } + else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) { + return; + } + const id = this.getId(feature, sourceLayerName); + for (let l = 0; l < layerIDs.length; l++) { + const layerID = layerIDs[l]; + if (filterLayerIDs && filterLayerIDs.indexOf(layerID) < 0) { + continue; + } + const styleLayer = styleLayers[layerID]; + if (!styleLayer) + continue; + let featureState = {}; + if (id && sourceFeatureState) { + // `feature-state` expression evaluation requires feature state to be available + featureState = sourceFeatureState.getState(styleLayer.sourceLayer || '_geojsonTileLayer', id); + } + const serializedLayer = extend({}, serializedLayers[layerID]); + serializedLayer.paint = evaluateProperties(serializedLayer.paint, styleLayer.paint, feature, featureState, availableImages); + serializedLayer.layout = evaluateProperties(serializedLayer.layout, styleLayer.layout, feature, featureState, availableImages); + const intersectionZ = !intersectionTest || intersectionTest(feature, styleLayer, featureState); + if (!intersectionZ) { + // Only applied for non-symbol features + continue; + } + const geojsonFeature = new GeoJSONFeature(feature, this.z, this.x, this.y, id); + geojsonFeature.layer = serializedLayer; + let layerResult = result[layerID]; + if (layerResult === undefined) { + layerResult = result[layerID] = []; + } + layerResult.push({ featureIndex, feature: geojsonFeature, intersectionZ }); + } + } + // Given a set of symbol indexes that have already been looked up, + // return a matching set of GeoJSONFeatures + lookupSymbolFeatures(symbolFeatureIndexes, serializedLayers, bucketIndex, sourceLayerIndex, filterSpec, filterLayerIDs, availableImages, styleLayers) { + const result = {}; + this.loadVTLayers(); + const filter = createFilter(filterSpec); + for (const symbolFeatureIndex of symbolFeatureIndexes) { + this.loadMatchingFeature(result, bucketIndex, sourceLayerIndex, symbolFeatureIndex, filter, filterLayerIDs, availableImages, styleLayers, serializedLayers); + } + return result; + } + hasLayer(id) { + for (const layerIDs of this.bucketLayerIDs) { + for (const layerID of layerIDs) { + if (id === layerID) + return true; + } + } + return false; + } + getId(feature, sourceLayerId) { + let id = feature.id; + if (this.promoteId) { + const propName = typeof this.promoteId === 'string' ? this.promoteId : this.promoteId[sourceLayerId]; + id = feature.properties[propName]; + if (typeof id === 'boolean') + id = Number(id); + } + return id; + } +} +register('FeatureIndex', FeatureIndex, { omit: ['rawTileData', 'sourceLayerCoder'] }); +function evaluateProperties(serializedProperties, styleLayerProperties, feature, featureState, availableImages) { + return mapObject(serializedProperties, (property, key) => { + const prop = styleLayerProperties instanceof PossiblyEvaluated ? styleLayerProperties.get(key) : null; + return prop && prop.evaluate ? prop.evaluate(feature, featureState, availableImages) : prop; + }); +} +function getBounds(geometry) { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const p of geometry) { + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + return { minX, minY, maxX, maxY }; +} +function topDownFeatureComparator(a, b) { + return b - a; +} + +/** + * Returns the part of a multiline that intersects with the provided rectangular box. + * + * @param lines - the lines to check + * @param x1 - the left edge of the box + * @param y1 - the top edge of the box + * @param x2 - the right edge of the box + * @param y2 - the bottom edge of the box + * @returns lines + */ +function clipLine(lines, x1, y1, x2, y2) { + const clippedLines = []; + for (let l = 0; l < lines.length; l++) { + const line = lines[l]; + let clippedLine; + for (let i = 0; i < line.length - 1; i++) { + let p0 = line[i]; + let p1 = line[i + 1]; + if (p0.x < x1 && p1.x < x1) { + continue; + } + else if (p0.x < x1) { + p0 = new Point$2(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); + } + else if (p1.x < x1) { + p1 = new Point$2(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); + } + if (p0.y < y1 && p1.y < y1) { + continue; + } + else if (p0.y < y1) { + p0 = new Point$2(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); + } + else if (p1.y < y1) { + p1 = new Point$2(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); + } + if (p0.x >= x2 && p1.x >= x2) { + continue; + } + else if (p0.x >= x2) { + p0 = new Point$2(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); + } + else if (p1.x >= x2) { + p1 = new Point$2(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); + } + if (p0.y >= y2 && p1.y >= y2) { + continue; + } + else if (p0.y >= y2) { + p0 = new Point$2(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); + } + else if (p1.y >= y2) { + p1 = new Point$2(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); + } + if (!clippedLine || !p0.equals(clippedLine[clippedLine.length - 1])) { + clippedLine = [p0]; + clippedLines.push(clippedLine); + } + clippedLine.push(p1); + } + } + return clippedLines; +} + +class Anchor extends Point$2 { + constructor(x, y, angle, segment) { + super(x, y); + this.angle = angle; + if (segment !== undefined) { + this.segment = segment; + } + } + clone() { + return new Anchor(this.x, this.y, this.angle, this.segment); + } +} +register('Anchor', Anchor); + +/** + * Labels placed around really sharp angles aren't readable. Check if any + * part of the potential label has a combined angle that is too big. + * + * @param line - The line to check + * @param anchor - The point on the line around which the label is anchored. + * @param labelLength - The length of the label in geometry units. + * @param windowSize - The check fails if the combined angles within a part of the line that is `windowSize` long is too big. + * @param maxAngle - The maximum combined angle that any window along the label is allowed to have. + * + * @returns whether the label should be placed + */ +function checkMaxAngle(line, anchor, labelLength, windowSize, maxAngle) { + // horizontal labels and labels with length 0 always pass + if (anchor.segment === undefined || labelLength === 0) + return true; + let p = anchor; + let index = anchor.segment + 1; + let anchorDistance = 0; + // move backwards along the line to the first segment the label appears on + while (anchorDistance > -labelLength / 2) { + index--; + // there isn't enough room for the label after the beginning of the line + if (index < 0) + return false; + anchorDistance -= line[index].dist(p); + p = line[index]; + } + anchorDistance += line[index].dist(line[index + 1]); + index++; + // store recent corners and their total angle difference + const recentCorners = []; + let recentAngleDelta = 0; + // move forwards by the length of the label and check angles along the way + while (anchorDistance < labelLength / 2) { + const prev = line[index - 1]; + const current = line[index]; + const next = line[index + 1]; + // there isn't enough room for the label before the end of the line + if (!next) + return false; + let angleDelta = prev.angleTo(current) - current.angleTo(next); + // restrict angle to -pi..pi range + angleDelta = Math.abs(((angleDelta + 3 * Math.PI) % (Math.PI * 2)) - Math.PI); + recentCorners.push({ + distance: anchorDistance, + angleDelta + }); + recentAngleDelta += angleDelta; + // remove corners that are far enough away from the list of recent anchors + while (anchorDistance - recentCorners[0].distance > windowSize) { + recentAngleDelta -= recentCorners.shift().angleDelta; + } + // the sum of angles within the window area exceeds the maximum allowed value. check fails. + if (recentAngleDelta > maxAngle) + return false; + index++; + anchorDistance += current.dist(next); + } + // no part of the line had an angle greater than the maximum allowed. check passes. + return true; +} + +function getLineLength(line) { + let lineLength = 0; + for (let k = 0; k < line.length - 1; k++) { + lineLength += line[k].dist(line[k + 1]); + } + return lineLength; +} +function getAngleWindowSize(shapedText, glyphSize, boxScale) { + return shapedText ? + 3 / 5 * glyphSize * boxScale : + 0; +} +function getShapedLabelLength(shapedText, shapedIcon) { + return Math.max(shapedText ? shapedText.right - shapedText.left : 0, shapedIcon ? shapedIcon.right - shapedIcon.left : 0); +} +function getCenterAnchor(line, maxAngle, shapedText, shapedIcon, glyphSize, boxScale) { + const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); + const labelLength = getShapedLabelLength(shapedText, shapedIcon) * boxScale; + let prevDistance = 0; + const centerDistance = getLineLength(line) / 2; + for (let i = 0; i < line.length - 1; i++) { + const a = line[i], b = line[i + 1]; + const segmentDistance = a.dist(b); + if (prevDistance + segmentDistance > centerDistance) { + // The center is on this segment + const t = (centerDistance - prevDistance) / segmentDistance, x = interpolate.number(a.x, b.x, t), y = interpolate.number(a.y, b.y, t); + const anchor = new Anchor(x, y, b.angleTo(a), i); + anchor._round(); + if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { + return anchor; + } + else { + return; + } + } + prevDistance += segmentDistance; + } +} +function getAnchors(line, spacing, maxAngle, shapedText, shapedIcon, glyphSize, boxScale, overscaling, tileExtent) { + // Resample a line to get anchor points for labels and check that each + // potential label passes text-max-angle check and has enough room to fit + // on the line. + const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); + const shapedLabelLength = getShapedLabelLength(shapedText, shapedIcon); + const labelLength = shapedLabelLength * boxScale; + // Is the line continued from outside the tile boundary? + const isLineContinued = line[0].x === 0 || line[0].x === tileExtent || line[0].y === 0 || line[0].y === tileExtent; + // Is the label long, relative to the spacing? + // If so, adjust the spacing so there is always a minimum space of `spacing / 4` between label edges. + if (spacing - labelLength < spacing / 4) { + spacing = labelLength + spacing / 4; + } + // Offset the first anchor by: + // Either half the label length plus a fixed extra offset if the line is not continued + // Or half the spacing if the line is continued. + // For non-continued lines, add a bit of fixed extra offset to avoid collisions at T intersections. + const fixedExtraOffset = glyphSize * 2; + const offset = !isLineContinued ? + ((shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling) % spacing : + (spacing / 2 * overscaling) % spacing; + return resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, false, tileExtent); +} +function resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, placeAtMiddle, tileExtent) { + const halfLabelLength = labelLength / 2; + const lineLength = getLineLength(line); + let distance = 0, markedDistance = offset - spacing; + let anchors = []; + for (let i = 0; i < line.length - 1; i++) { + const a = line[i], b = line[i + 1]; + const segmentDist = a.dist(b), angle = b.angleTo(a); + while (markedDistance + spacing < distance + segmentDist) { + markedDistance += spacing; + const t = (markedDistance - distance) / segmentDist, x = interpolate.number(a.x, b.x, t), y = interpolate.number(a.y, b.y, t); + // Check that the point is within the tile boundaries and that + // the label would fit before the beginning and end of the line + // if placed at this point. + if (x >= 0 && x < tileExtent && y >= 0 && y < tileExtent && + markedDistance - halfLabelLength >= 0 && + markedDistance + halfLabelLength <= lineLength) { + const anchor = new Anchor(x, y, angle, i); + anchor._round(); + if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { + anchors.push(anchor); + } + } + } + distance += segmentDist; + } + if (!placeAtMiddle && !anchors.length && !isLineContinued) { + // The first attempt at finding anchors at which labels can be placed failed. + // Try again, but this time just try placing one anchor at the middle of the line. + // This has the most effect for short lines in overscaled tiles, since the + // initial offset used in overscaled tiles is calculated to align labels with positions in + // parent tiles instead of placing the label as close to the beginning as possible. + anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, true, tileExtent); + } + return anchors; +} + +// If you have a 10px icon that isn't perfectly aligned to the pixel grid it will cover 11 actual +// pixels. The quad needs to be padded to account for this, otherwise they'll look slightly clipped +// on one edge in some cases. +const border = IMAGE_PADDING; +/** + * Create the quads used for rendering an icon. + */ +function getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit) { + const quads = []; + const image = shapedIcon.image; + const pixelRatio = image.pixelRatio; + const imageWidth = image.paddedRect.w - 2 * border; + const imageHeight = image.paddedRect.h - 2 * border; + let icon = { + x1: shapedIcon.left, + y1: shapedIcon.top, + x2: shapedIcon.right, + y2: shapedIcon.bottom + }; + const stretchX = image.stretchX || [[0, imageWidth]]; + const stretchY = image.stretchY || [[0, imageHeight]]; + const reduceRanges = (sum, range) => sum + range[1] - range[0]; + const stretchWidth = stretchX.reduce(reduceRanges, 0); + const stretchHeight = stretchY.reduce(reduceRanges, 0); + const fixedWidth = imageWidth - stretchWidth; + const fixedHeight = imageHeight - stretchHeight; + let stretchOffsetX = 0; + let stretchContentWidth = stretchWidth; + let stretchOffsetY = 0; + let stretchContentHeight = stretchHeight; + let fixedOffsetX = 0; + let fixedContentWidth = fixedWidth; + let fixedOffsetY = 0; + let fixedContentHeight = fixedHeight; + if (image.content && hasIconTextFit) { + const content = image.content; + const contentWidth = content[2] - content[0]; + const contentHeight = content[3] - content[1]; + // Constrict content area to fit target aspect ratio + if (image.textFitWidth || image.textFitHeight) { + icon = applyTextFit(shapedIcon); + } + stretchOffsetX = sumWithinRange(stretchX, 0, content[0]); + stretchOffsetY = sumWithinRange(stretchY, 0, content[1]); + stretchContentWidth = sumWithinRange(stretchX, content[0], content[2]); + stretchContentHeight = sumWithinRange(stretchY, content[1], content[3]); + fixedOffsetX = content[0] - stretchOffsetX; + fixedOffsetY = content[1] - stretchOffsetY; + fixedContentWidth = contentWidth - stretchContentWidth; + fixedContentHeight = contentHeight - stretchContentHeight; + } + const iconLeft = icon.x1; + const iconTop = icon.y1; + const iconWidth = icon.x2 - iconLeft; + const iconHeight = icon.y2 - iconTop; + const makeBox = (left, top, right, bottom) => { + const leftEm = getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, iconLeft); + const leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth); + const topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, iconTop); + const topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight); + const rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, iconLeft); + const rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth); + const bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, iconTop); + const bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight); + const tl = new Point$2(leftEm, topEm); + const tr = new Point$2(rightEm, topEm); + const br = new Point$2(rightEm, bottomEm); + const bl = new Point$2(leftEm, bottomEm); + const pixelOffsetTL = new Point$2(leftPx / pixelRatio, topPx / pixelRatio); + const pixelOffsetBR = new Point$2(rightPx / pixelRatio, bottomPx / pixelRatio); + const angle = iconRotate * Math.PI / 180; + if (angle) { + const sin = Math.sin(angle), cos = Math.cos(angle), matrix = [cos, -sin, sin, cos]; + tl._matMult(matrix); + tr._matMult(matrix); + bl._matMult(matrix); + br._matMult(matrix); + } + const x1 = left.stretch + left.fixed; + const x2 = right.stretch + right.fixed; + const y1 = top.stretch + top.fixed; + const y2 = bottom.stretch + bottom.fixed; + const subRect = { + x: image.paddedRect.x + border + x1, + y: image.paddedRect.y + border + y1, + w: x2 - x1, + h: y2 - y1 + }; + const minFontScaleX = fixedContentWidth / pixelRatio / iconWidth; + const minFontScaleY = fixedContentHeight / pixelRatio / iconHeight; + // Icon quad is padded, so texture coordinates also need to be padded. + return { tl, tr, bl, br, tex: subRect, writingMode: undefined, glyphOffset: [0, 0], sectionIndex: 0, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, isSDF: isSDFIcon }; + }; + if (!hasIconTextFit || (!image.stretchX && !image.stretchY)) { + quads.push(makeBox({ fixed: 0, stretch: -1 }, { fixed: 0, stretch: -1 }, { fixed: 0, stretch: imageWidth + 1 }, { fixed: 0, stretch: imageHeight + 1 })); + } + else { + const xCuts = stretchZonesToCuts(stretchX, fixedWidth, stretchWidth); + const yCuts = stretchZonesToCuts(stretchY, fixedHeight, stretchHeight); + for (let xi = 0; xi < xCuts.length - 1; xi++) { + const x1 = xCuts[xi]; + const x2 = xCuts[xi + 1]; + for (let yi = 0; yi < yCuts.length - 1; yi++) { + const y1 = yCuts[yi]; + const y2 = yCuts[yi + 1]; + quads.push(makeBox(x1, y1, x2, y2)); + } + } + } + return quads; +} +function sumWithinRange(ranges, min, max) { + let sum = 0; + for (const range of ranges) { + sum += Math.max(min, Math.min(max, range[1])) - Math.max(min, Math.min(max, range[0])); + } + return sum; +} +function stretchZonesToCuts(stretchZones, fixedSize, stretchSize) { + const cuts = [{ fixed: -border, stretch: 0 }]; + for (const [c1, c2] of stretchZones) { + const last = cuts[cuts.length - 1]; + cuts.push({ + fixed: c1 - last.stretch, + stretch: last.stretch + }); + cuts.push({ + fixed: c1 - last.stretch, + stretch: last.stretch + (c2 - c1) + }); + } + cuts.push({ + fixed: fixedSize + border, + stretch: stretchSize + }); + return cuts; +} +function getEmOffset(stretchOffset, stretchSize, iconSize, iconOffset) { + return stretchOffset / stretchSize * iconSize + iconOffset; +} +function getPxOffset(fixedOffset, fixedSize, stretchOffset, stretchSize) { + return fixedOffset - fixedSize * stretchOffset / stretchSize; +} +/** + * Create the quads used for rendering a text label. + */ +function getGlyphQuads(anchor, shaping, textOffset, layer, alongLine, feature, imageMap, allowVerticalPlacement) { + const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}) * Math.PI / 180; + const quads = []; + for (const line of shaping.positionedLines) { + for (const positionedGlyph of line.positionedGlyphs) { + if (!positionedGlyph.rect) + continue; + const textureRect = positionedGlyph.rect || {}; + // The rects have an additional buffer that is not included in their size. + const glyphPadding = 1.0; + let rectBuffer = GLYPH_PBF_BORDER + glyphPadding; + let isSDF = true; + let pixelRatio = 1.0; + let lineOffset = 0.0; + const rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical; + const halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2; + // Align images and scaled glyphs in the middle of a vertical line. + if (allowVerticalPlacement && shaping.verticalizable) { + const scaledGlyphOffset = (positionedGlyph.scale - 1) * ONE_EM; + const imageOffset = (ONE_EM - positionedGlyph.metrics.width * positionedGlyph.scale) / 2; + lineOffset = line.lineOffset / 2 - (positionedGlyph.imageName ? -imageOffset : scaledGlyphOffset); + } + if (positionedGlyph.imageName) { + const image = imageMap[positionedGlyph.imageName]; + isSDF = image.sdf; + pixelRatio = image.pixelRatio; + rectBuffer = IMAGE_PADDING / pixelRatio; + } + const glyphOffset = alongLine ? + [positionedGlyph.x + halfAdvance, positionedGlyph.y] : + [0, 0]; + let builtInOffset = alongLine ? + [0, 0] : + [positionedGlyph.x + halfAdvance + textOffset[0], positionedGlyph.y + textOffset[1] - lineOffset]; + let verticalizedLabelOffset = [0, 0]; + if (rotateVerticalGlyph) { + // Vertical POI labels that are rotated 90deg CW and whose glyphs must preserve upright orientation + // need to be rotated 90deg CCW. After a quad is rotated, it is translated to the original built-in offset. + verticalizedLabelOffset = builtInOffset; + builtInOffset = [0, 0]; + } + const textureScale = positionedGlyph.metrics.isDoubleResolution ? 2 : 1; + const x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0]; + const y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1]; + const x2 = x1 + textureRect.w / textureScale * positionedGlyph.scale / pixelRatio; + const y2 = y1 + textureRect.h / textureScale * positionedGlyph.scale / pixelRatio; + const tl = new Point$2(x1, y1); + const tr = new Point$2(x2, y1); + const bl = new Point$2(x1, y2); + const br = new Point$2(x2, y2); + if (rotateVerticalGlyph) { + // Vertical-supporting glyphs are laid out in 24x24 point boxes (1 square em) + // In horizontal orientation, the y values for glyphs are below the midline + // and we use a "yOffset" of -17 to pull them up to the middle. + // By rotating counter-clockwise around the point at the center of the left + // edge of a 24x24 layout box centered below the midline, we align the center + // of the glyphs with the horizontal midline, so the yOffset is no longer + // necessary, but we also pull the glyph to the left along the x axis. + // The y coordinate includes baseline yOffset, thus needs to be accounted + // for when glyph is rotated and translated. + const center = new Point$2(-halfAdvance, halfAdvance - SHAPING_DEFAULT_OFFSET); + const verticalRotation = -Math.PI / 2; + // xHalfWidthOffsetCorrection is a difference between full-width and half-width + // advance, should be 0 for full-width glyphs and will pull up half-width glyphs. + const xHalfWidthOffsetCorrection = ONE_EM / 2 - halfAdvance; + const yImageOffsetCorrection = positionedGlyph.imageName ? xHalfWidthOffsetCorrection : 0.0; + const halfWidthOffsetCorrection = new Point$2(5 - SHAPING_DEFAULT_OFFSET - xHalfWidthOffsetCorrection, -yImageOffsetCorrection); + const verticalOffsetCorrection = new Point$2(...verticalizedLabelOffset); + tl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + tr._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + bl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + br._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + } + if (textRotate) { + const sin = Math.sin(textRotate), cos = Math.cos(textRotate), matrix = [cos, -sin, sin, cos]; + tl._matMult(matrix); + tr._matMult(matrix); + bl._matMult(matrix); + br._matMult(matrix); + } + const pixelOffsetTL = new Point$2(0, 0); + const pixelOffsetBR = new Point$2(0, 0); + const minFontScaleX = 0; + const minFontScaleY = 0; + quads.push({ tl, tr, bl, br, tex: textureRect, writingMode: shaping.writingMode, glyphOffset, sectionIndex: positionedGlyph.sectionIndex, isSDF, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY }); + } + } + return quads; +} + +/** + * A CollisionFeature represents the area of the tile covered by a single label. + * It is used with CollisionIndex to check if the label overlaps with any + * previous labels. A CollisionFeature is mostly just a set of CollisionBox + * objects. + */ +class CollisionFeature { + /** + * Create a CollisionFeature, adding its collision box data to the given collisionBoxArray in the process. + * For line aligned labels a collision circle diameter is computed instead. + * + * @param anchor - The point along the line around which the label is anchored. + * @param shaped - The text or icon shaping results. + * @param boxScale - A magic number used to convert from glyph metrics units to geometry units. + * @param padding - The amount of padding to add around the label edges. + * @param alignLine - Whether the label is aligned with the line or the viewport. + */ + constructor(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaped, boxScale, padding, alignLine, rotate) { + var _a; + this.boxStartIndex = collisionBoxArray.length; + if (alignLine) { + // Compute height of the shape in glyph metrics and apply collision padding. + // Note that the pixel based 'text-padding' is applied at runtime + let top = shaped.top; + let bottom = shaped.bottom; + const collisionPadding = shaped.collisionPadding; + if (collisionPadding) { + top -= collisionPadding[1]; + bottom += collisionPadding[3]; + } + let height = bottom - top; + if (height > 0) { + // set minimum box height to avoid very many small labels + height = Math.max(10, height); + this.circleDiameter = height; + } + } + else { + const icon = ((_a = shaped.image) === null || _a === void 0 ? void 0 : _a.content) && (shaped.image.textFitWidth || shaped.image.textFitHeight) ? + applyTextFit(shaped) : + { + x1: shaped.left, + y1: shaped.top, + x2: shaped.right, + y2: shaped.bottom + }; + // margin is in CSS order: [top, right, bottom, left] + icon.y1 = icon.y1 * boxScale - padding[0]; + icon.y2 = icon.y2 * boxScale + padding[2]; + icon.x1 = icon.x1 * boxScale - padding[3]; + icon.x2 = icon.x2 * boxScale + padding[1]; + const collisionPadding = shaped.collisionPadding; + if (collisionPadding) { + icon.x1 -= collisionPadding[0] * boxScale; + icon.y1 -= collisionPadding[1] * boxScale; + icon.x2 += collisionPadding[2] * boxScale; + icon.y2 += collisionPadding[3] * boxScale; + } + if (rotate) { + // Account for *-rotate in point collision boxes + // See https://github.com/mapbox/mapbox-gl-js/issues/6075 + // Doesn't account for icon-text-fit + const tl = new Point$2(icon.x1, icon.y1); + const tr = new Point$2(icon.x2, icon.y1); + const bl = new Point$2(icon.x1, icon.y2); + const br = new Point$2(icon.x2, icon.y2); + const rotateRadians = rotate * Math.PI / 180; + tl._rotate(rotateRadians); + tr._rotate(rotateRadians); + bl._rotate(rotateRadians); + br._rotate(rotateRadians); + // Collision features require an "on-axis" geometry, + // so take the envelope of the rotated geometry + // (may be quite large for wide labels rotated 45 degrees) + icon.x1 = Math.min(tl.x, tr.x, bl.x, br.x); + icon.x2 = Math.max(tl.x, tr.x, bl.x, br.x); + icon.y1 = Math.min(tl.y, tr.y, bl.y, br.y); + icon.y2 = Math.max(tl.y, tr.y, bl.y, br.y); + } + collisionBoxArray.emplaceBack(anchor.x, anchor.y, icon.x1, icon.y1, icon.x2, icon.y2, featureIndex, sourceLayerIndex, bucketIndex); + } + this.boxEndIndex = collisionBoxArray.length; + } +} + +class TinyQueue { + constructor(data = [], compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) { + this.data = data; + this.length = this.data.length; + this.compare = compare; + + if (this.length > 0) { + for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i); + } + } + + push(item) { + this.data.push(item); + this._up(this.length++); + } + + pop() { + if (this.length === 0) return undefined; + + const top = this.data[0]; + const bottom = this.data.pop(); + + if (--this.length > 0) { + this.data[0] = bottom; + this._down(0); + } + + return top; + } + + peek() { + return this.data[0]; + } + + _up(pos) { + const {data, compare} = this; + const item = data[pos]; + + while (pos > 0) { + const parent = (pos - 1) >> 1; + const current = data[parent]; + if (compare(item, current) >= 0) break; + data[pos] = current; + pos = parent; + } + + data[pos] = item; + } + + _down(pos) { + const {data, compare} = this; + const halfLength = this.length >> 1; + const item = data[pos]; + + while (pos < halfLength) { + let bestChild = (pos << 1) + 1; // initially it is the left child + const right = bestChild + 1; + + if (right < this.length && compare(data[right], data[bestChild]) < 0) { + bestChild = right; + } + if (compare(data[bestChild], item) >= 0) break; + + data[pos] = data[bestChild]; + pos = bestChild; + } + + data[pos] = item; + } +} + +/** + * Finds an approximation of a polygon's Pole Of Inaccessibility https://en.wikipedia.org/wiki/Pole_of_inaccessibility + * This is a copy of https://github.com/mapbox/polylabel adapted to use Points + * + * @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 + * @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 + * @param debug - Print some statistics to the console during execution + * @returns Pole of Inaccessibility. + */ +function findPoleOfInaccessibility(polygonRings, precision = 1, debug = false) { + // find the bounding box of the outer ring + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + const outerRing = polygonRings[0]; + for (let i = 0; i < outerRing.length; i++) { + const p = outerRing[i]; + if (!i || p.x < minX) + minX = p.x; + if (!i || p.y < minY) + minY = p.y; + if (!i || p.x > maxX) + maxX = p.x; + if (!i || p.y > maxY) + maxY = p.y; + } + const width = maxX - minX; + const height = maxY - minY; + const cellSize = Math.min(width, height); + let h = cellSize / 2; + // a priority queue of cells in order of their "potential" (max distance to polygon) + const cellQueue = new TinyQueue([], compareMax); + if (cellSize === 0) + return new Point$2(minX, minY); + // cover polygon with initial cells + for (let x = minX; x < maxX; x += cellSize) { + for (let y = minY; y < maxY; y += cellSize) { + cellQueue.push(new Cell(x + h, y + h, h, polygonRings)); + } + } + // take centroid as the first best guess + let bestCell = getCentroidCell(polygonRings); + let numProbes = cellQueue.length; + while (cellQueue.length) { + // pick the most promising cell from the queue + const cell = cellQueue.pop(); + // update the best cell if we found a better one + if (cell.d > bestCell.d || !bestCell.d) { + bestCell = cell; + if (debug) + console.log('found best %d after %d probes', Math.round(1e4 * cell.d) / 1e4, numProbes); + } + // do not drill down further if there's no chance of a better solution + if (cell.max - bestCell.d <= precision) + continue; + // split the cell into four cells + h = cell.h / 2; + cellQueue.push(new Cell(cell.p.x - h, cell.p.y - h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x + h, cell.p.y - h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x - h, cell.p.y + h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x + h, cell.p.y + h, h, polygonRings)); + numProbes += 4; + } + if (debug) { + console.log(`num probes: ${numProbes}`); + console.log(`best distance: ${bestCell.d}`); + } + return bestCell.p; +} +function compareMax(a, b) { + return b.max - a.max; +} +function Cell(x, y, h, polygon) { + this.p = new Point$2(x, y); + this.h = h; // half the cell size + this.d = pointToPolygonDist(this.p, polygon); // distance from cell center to polygon + this.max = this.d + this.h * Math.SQRT2; // max distance to polygon within a cell +} +// signed distance from point to polygon outline (negative if point is outside) +function pointToPolygonDist(p, polygon) { + let inside = false; + let minDistSq = Infinity; + for (let k = 0; k < polygon.length; k++) { + const ring = polygon[k]; + for (let i = 0, len = ring.length, j = len - 1; i < len; j = i++) { + const a = ring[i]; + const b = ring[j]; + if ((a.y > p.y !== b.y > p.y) && + (p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x)) + inside = !inside; + minDistSq = Math.min(minDistSq, distToSegmentSquared(p, a, b)); + } + } + return (inside ? 1 : -1) * Math.sqrt(minDistSq); +} +// get polygon centroid +function getCentroidCell(polygon) { + let area = 0; + let x = 0; + let y = 0; + const points = polygon[0]; + for (let i = 0, len = points.length, j = len - 1; i < len; j = i++) { + const a = points[i]; + const b = points[j]; + const f = a.x * b.y - b.x * a.y; + x += (a.x + b.x) * f; + y += (a.y + b.y) * f; + area += f * 3; + } + return new Cell(x / area, y / area, 0, polygon); +} + +exports.aq = void 0; +(function (TextAnchorEnum) { + TextAnchorEnum[TextAnchorEnum["center"] = 1] = "center"; + TextAnchorEnum[TextAnchorEnum["left"] = 2] = "left"; + TextAnchorEnum[TextAnchorEnum["right"] = 3] = "right"; + TextAnchorEnum[TextAnchorEnum["top"] = 4] = "top"; + TextAnchorEnum[TextAnchorEnum["bottom"] = 5] = "bottom"; + TextAnchorEnum[TextAnchorEnum["top-left"] = 6] = "top-left"; + TextAnchorEnum[TextAnchorEnum["top-right"] = 7] = "top-right"; + TextAnchorEnum[TextAnchorEnum["bottom-left"] = 8] = "bottom-left"; + TextAnchorEnum[TextAnchorEnum["bottom-right"] = 9] = "bottom-right"; +})(exports.aq || (exports.aq = {})); +// The radial offset is to the edge of the text box +// In the horizontal direction, the edge of the text box is where glyphs start +// But in the vertical direction, the glyphs appear to "start" at the baseline +// We don't actually load baseline data, but we assume an offset of ONE_EM - 17 +// (see "yOffset" in shaping.js) +const baselineOffset = 7; +const INVALID_TEXT_OFFSET = Number.POSITIVE_INFINITY; +function evaluateVariableOffset(anchor, offset) { + function fromRadialOffset(anchor, radialOffset) { + let x = 0, y = 0; + if (radialOffset < 0) + radialOffset = 0; // Ignore negative offset. + // solve for r where r^2 + r^2 = radialOffset^2 + const hypotenuse = radialOffset / Math.SQRT2; + switch (anchor) { + case 'top-right': + case 'top-left': + y = hypotenuse - baselineOffset; + break; + case 'bottom-right': + case 'bottom-left': + y = -hypotenuse + baselineOffset; + break; + case 'bottom': + y = -radialOffset + baselineOffset; + break; + case 'top': + y = radialOffset - baselineOffset; + break; + } + switch (anchor) { + case 'top-right': + case 'bottom-right': + x = -hypotenuse; + break; + case 'top-left': + case 'bottom-left': + x = hypotenuse; + break; + case 'left': + x = radialOffset; + break; + case 'right': + x = -radialOffset; + break; + } + return [x, y]; + } + function fromTextOffset(anchor, offsetX, offsetY) { + let x = 0, y = 0; + // Use absolute offset values. + offsetX = Math.abs(offsetX); + offsetY = Math.abs(offsetY); + switch (anchor) { + case 'top-right': + case 'top-left': + case 'top': + y = offsetY - baselineOffset; + break; + case 'bottom-right': + case 'bottom-left': + case 'bottom': + y = -offsetY + baselineOffset; + break; + } + switch (anchor) { + case 'top-right': + case 'bottom-right': + case 'right': + x = -offsetX; + break; + case 'top-left': + case 'bottom-left': + case 'left': + x = offsetX; + break; + } + return [x, y]; + } + return (offset[1] !== INVALID_TEXT_OFFSET) ? fromTextOffset(anchor, offset[0], offset[1]) : fromRadialOffset(anchor, offset[0]); +} +// Helper to support both text-variable-anchor and text-variable-anchor-offset. Offset values converted from EMs to PXs +function getTextVariableAnchorOffset(layer, feature, canonical) { + var _a; + const layout = layer.layout; + // If style specifies text-variable-anchor-offset, just return it + const variableAnchorOffset = (_a = layout.get('text-variable-anchor-offset')) === null || _a === void 0 ? void 0 : _a.evaluate(feature, {}, canonical); + if (variableAnchorOffset) { + const sourceValues = variableAnchorOffset.values; + const destValues = []; + // Convert offsets from EM to PX, and apply baseline shift + for (let i = 0; i < sourceValues.length; i += 2) { + const anchor = destValues[i] = sourceValues[i]; + const offset = sourceValues[i + 1].map(t => t * ONE_EM); + if (anchor.startsWith('top')) { + offset[1] -= baselineOffset; + } + else if (anchor.startsWith('bottom')) { + offset[1] += baselineOffset; + } + destValues[i + 1] = offset; + } + return new VariableAnchorOffsetCollection(destValues); + } + // If style specifies text-variable-anchor, convert to the new format + const variableAnchor = layout.get('text-variable-anchor'); + if (variableAnchor) { + let textOffset; + const unevaluatedLayout = layer._unevaluatedLayout; + // The style spec says don't use `text-offset` and `text-radial-offset` together + // but doesn't actually specify what happens if you use both. We go with the radial offset. + if (unevaluatedLayout.getValue('text-radial-offset') !== undefined) { + textOffset = [layout.get('text-radial-offset').evaluate(feature, {}, canonical) * ONE_EM, INVALID_TEXT_OFFSET]; + } + else { + textOffset = layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM); + } + const anchorOffsets = []; + for (const anchor of variableAnchor) { + anchorOffsets.push(anchor, evaluateVariableOffset(anchor, textOffset)); + } + return new VariableAnchorOffsetCollection(anchorOffsets); + } + return null; +} + +function performSymbolLayout(args) { + args.bucket.createArrays(); + const tileSize = 512 * args.bucket.overscaling; + args.bucket.tilePixelRatio = EXTENT / tileSize; + args.bucket.compareText = {}; + args.bucket.iconsNeedLinear = false; + const layer = args.bucket.layers[0]; + const layout = layer.layout; + const unevaluatedLayoutValues = layer._unevaluatedLayout._values; + const sizes = { + // Filled in below, if *SizeData.kind is 'composite' + // compositeIconSizes: undefined, + // compositeTextSizes: undefined, + layoutIconSize: unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical), + layoutTextSize: unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(args.bucket.zoom + 1), args.canonical), + textMaxSize: unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(18)) + }; + if (args.bucket.textSizeData.kind === 'composite') { + const { minZoom, maxZoom } = args.bucket.textSizeData; + sizes.compositeTextSizes = [ + unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical), + unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical) + ]; + } + if (args.bucket.iconSizeData.kind === 'composite') { + const { minZoom, maxZoom } = args.bucket.iconSizeData; + sizes.compositeIconSizes = [ + unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(minZoom), args.canonical), + unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), args.canonical) + ]; + } + const lineHeight = layout.get('text-line-height') * ONE_EM; + const textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point'; + const keepUpright = layout.get('text-keep-upright'); + const textSize = layout.get('text-size'); + for (const feature of args.bucket.features) { + const fontstack = layout.get('text-font').evaluate(feature, {}, args.canonical).join(','); + const layoutTextSizeThisZoom = textSize.evaluate(feature, {}, args.canonical); + const layoutTextSize = sizes.layoutTextSize.evaluate(feature, {}, args.canonical); + const layoutIconSize = sizes.layoutIconSize.evaluate(feature, {}, args.canonical); + const shapedTextOrientations = { + horizontal: {}, + vertical: undefined + }; + const text = feature.text; + let textOffset = [0, 0]; + if (text) { + const unformattedText = text.toString(); + const spacing = layout.get('text-letter-spacing').evaluate(feature, {}, args.canonical) * ONE_EM; + const spacingIfAllowed = allowsLetterSpacing(unformattedText) ? spacing : 0; + const textAnchor = layout.get('text-anchor').evaluate(feature, {}, args.canonical); + const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, args.canonical); + if (!variableAnchorOffset) { + const radialOffset = layout.get('text-radial-offset').evaluate(feature, {}, args.canonical); + // Layers with variable anchors use the `text-radial-offset` property and the [x, y] offset vector + // is calculated at placement time instead of layout time + if (radialOffset) { + // The style spec says don't use `text-offset` and `text-radial-offset` together + // but doesn't actually specify what happens if you use both. We go with the radial offset. + textOffset = evaluateVariableOffset(textAnchor, [radialOffset * ONE_EM, INVALID_TEXT_OFFSET]); + } + else { + textOffset = layout.get('text-offset').evaluate(feature, {}, args.canonical).map(t => t * ONE_EM); + } + } + let textJustify = textAlongLine ? + 'center' : + layout.get('text-justify').evaluate(feature, {}, args.canonical); + const symbolPlacement = layout.get('symbol-placement'); + const maxWidth = symbolPlacement === 'point' ? + layout.get('text-max-width').evaluate(feature, {}, args.canonical) * ONE_EM : + Infinity; + const addVerticalShapingForPointLabelIfNeeded = () => { + if (args.bucket.allowVerticalPlacement && allowsVerticalWritingMode(unformattedText)) { + // Vertical POI label placement is meant to be used for scripts that support vertical + // writing mode, thus, default left justification is used. If Latin + // scripts would need to be supported, this should take into account other justifications. + shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, 'left', spacingIfAllowed, textOffset, exports.ah.vertical, true, layoutTextSize, layoutTextSizeThisZoom); + } + }; + // If this layer uses text-variable-anchor, generate shapings for all justification possibilities. + if (!textAlongLine && variableAnchorOffset) { + const justifications = new Set(); + if (textJustify === 'auto') { + for (let i = 0; i < variableAnchorOffset.values.length; i += 2) { + justifications.add(getAnchorJustification(variableAnchorOffset.values[i])); + } + } + else { + justifications.add(textJustify); + } + let singleLine = false; + for (const justification of justifications) { + if (shapedTextOrientations.horizontal[justification]) + continue; + if (singleLine) { + // If the shaping for the first justification was only a single line, we + // can re-use it for the other justifications + shapedTextOrientations.horizontal[justification] = shapedTextOrientations.horizontal[0]; + } + else { + // If using text-variable-anchor for the layer, we use a center anchor for all shapings and apply + // the offsets for the anchor in the placement step. + const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, 'center', justification, spacingIfAllowed, textOffset, exports.ah.horizontal, false, layoutTextSize, layoutTextSizeThisZoom); + if (shaping) { + shapedTextOrientations.horizontal[justification] = shaping; + singleLine = shaping.positionedLines.length === 1; + } + } + } + addVerticalShapingForPointLabelIfNeeded(); + } + else { + if (textJustify === 'auto') { + textJustify = getAnchorJustification(textAnchor); + } + // Horizontal point or line label. + const shaping = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, exports.ah.horizontal, false, layoutTextSize, layoutTextSizeThisZoom); + if (shaping) + shapedTextOrientations.horizontal[textJustify] = shaping; + // Vertical point label (if allowVerticalPlacement is enabled). + addVerticalShapingForPointLabelIfNeeded(); + // Verticalized line label. + if (allowsVerticalWritingMode(unformattedText) && textAlongLine && keepUpright) { + shapedTextOrientations.vertical = shapeText(text, args.glyphMap, args.glyphPositions, args.imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, exports.ah.vertical, false, layoutTextSize, layoutTextSizeThisZoom); + } + } + } + let shapedIcon; + let isSDFIcon = false; + if (feature.icon && feature.icon.name) { + const image = args.imageMap[feature.icon.name]; + if (image) { + shapedIcon = shapeIcon(args.imagePositions[feature.icon.name], layout.get('icon-offset').evaluate(feature, {}, args.canonical), layout.get('icon-anchor').evaluate(feature, {}, args.canonical)); + // null/undefined SDF property treated same as default (false) + isSDFIcon = !!image.sdf; + if (args.bucket.sdfIcons === undefined) { + args.bucket.sdfIcons = isSDFIcon; + } + else if (args.bucket.sdfIcons !== isSDFIcon) { + warnOnce('Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer'); + } + if (image.pixelRatio !== args.bucket.pixelRatio) { + args.bucket.iconsNeedLinear = true; + } + else if (layout.get('icon-rotate').constantOr(1) !== 0) { + args.bucket.iconsNeedLinear = true; + } + } + } + const shapedText = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical; + args.bucket.iconsInText = shapedText ? shapedText.iconsInText : false; + if (shapedText || shapedIcon) { + addFeature(args.bucket, feature, shapedTextOrientations, shapedIcon, args.imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, args.canonical); + } + } + if (args.showCollisionBoxes) { + args.bucket.generateCollisionDebugBuffers(); + } +} +// Choose the justification that matches the direction of the TextAnchor +function getAnchorJustification(anchor) { + switch (anchor) { + case 'right': + case 'top-right': + case 'bottom-right': + return 'right'; + case 'left': + case 'top-left': + case 'bottom-left': + return 'left'; + } + return 'center'; +} +/** + * Given a feature and its shaped text and icon data, add a 'symbol + * instance' for each _possible_ placement of the symbol feature. + * (At render timePlaceSymbols#place() selects which of these instances to + * show or hide based on collisions with symbols in other layers.) + */ +function addFeature(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, canonical) { + // To reduce the number of labels that jump around when zooming we need + // to use a text-size value that is the same for all zoom levels. + // bucket calculates text-size at a high zoom level so that all tiles can + // use the same value when calculating anchor positions. + let textMaxSize = sizes.textMaxSize.evaluate(feature, {}); + if (textMaxSize === undefined) { + textMaxSize = layoutTextSize; + } + const layout = bucket.layers[0].layout; + const iconOffset = layout.get('icon-offset').evaluate(feature, {}, canonical); + const defaultHorizontalShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal); + const glyphSize = 24, fontScale = layoutTextSize / glyphSize, textBoxScale = bucket.tilePixelRatio * fontScale, textMaxBoxScale = bucket.tilePixelRatio * textMaxSize / glyphSize, iconBoxScale = bucket.tilePixelRatio * layoutIconSize, symbolMinDistance = bucket.tilePixelRatio * layout.get('symbol-spacing'), textPadding = layout.get('text-padding') * bucket.tilePixelRatio, iconPadding = getIconPadding(layout, feature, canonical, bucket.tilePixelRatio), textMaxAngle = layout.get('text-max-angle') / 180 * Math.PI, textAlongLine = layout.get('text-rotation-alignment') !== 'viewport' && layout.get('symbol-placement') !== 'point', iconAlongLine = layout.get('icon-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point', symbolPlacement = layout.get('symbol-placement'), textRepeatDistance = symbolMinDistance / 2; + const iconTextFit = layout.get('icon-text-fit'); + let verticallyShapedIcon; + // Adjust shaped icon size when icon-text-fit is used. + if (shapedIcon && iconTextFit !== 'none') { + if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) { + verticallyShapedIcon = fitIconToText(shapedIcon, shapedTextOrientations.vertical, iconTextFit, layout.get('icon-text-fit-padding'), iconOffset, fontScale); + } + if (defaultHorizontalShaping) { + shapedIcon = fitIconToText(shapedIcon, defaultHorizontalShaping, iconTextFit, layout.get('icon-text-fit-padding'), iconOffset, fontScale); + } + } + const addSymbolAtAnchor = (line, anchor) => { + if (anchor.x < 0 || anchor.x >= EXTENT || anchor.y < 0 || anchor.y >= EXTENT) { + // Symbol layers are drawn across tile boundaries, We filter out symbols + // outside our tile boundaries (which may be included in vector tile buffers) + // to prevent double-drawing symbols. + return; + } + addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, bucket.layers[0], bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex, bucket.index, textBoxScale, [textPadding, textPadding, textPadding, textPadding], textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, canonical, layoutTextSize); + }; + if (symbolPlacement === 'line') { + for (const line of clipLine(feature.geometry, 0, 0, EXTENT, EXTENT)) { + const anchors = getAnchors(line, symbolMinDistance, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale, bucket.overscaling, EXTENT); + for (const anchor of anchors) { + const shapedText = defaultHorizontalShaping; + if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) { + addSymbolAtAnchor(line, anchor); + } + } + } + } + else if (symbolPlacement === 'line-center') { + // No clipping, multiple lines per feature are allowed + // "lines" with only one point are ignored as in clipLines + for (const line of feature.geometry) { + if (line.length > 1) { + const anchor = getCenterAnchor(line, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale); + if (anchor) { + addSymbolAtAnchor(line, anchor); + } + } + } + } + else if (feature.type === 'Polygon') { + for (const polygon of classifyRings$1(feature.geometry, 0)) { + // 16 here represents 2 pixels + const poi = findPoleOfInaccessibility(polygon, 16); + addSymbolAtAnchor(polygon[0], new Anchor(poi.x, poi.y, 0)); + } + } + else if (feature.type === 'LineString') { + // https://github.com/mapbox/mapbox-gl-js/issues/3808 + for (const line of feature.geometry) { + addSymbolAtAnchor(line, new Anchor(line[0].x, line[0].y, 0)); + } + } + else if (feature.type === 'Point') { + for (const points of feature.geometry) { + for (const point of points) { + addSymbolAtAnchor([point], new Anchor(point.x, point.y, 0)); + } + } + } +} +function addTextVariableAnchorOffsets(textAnchorOffsets, variableAnchorOffset) { + const startIndex = textAnchorOffsets.length; + const values = variableAnchorOffset === null || variableAnchorOffset === void 0 ? void 0 : variableAnchorOffset.values; + if ((values === null || values === void 0 ? void 0 : values.length) > 0) { + for (let i = 0; i < values.length; i += 2) { + const anchor = exports.aq[values[i]]; + const offset = values[i + 1]; + textAnchorOffsets.emplaceBack(anchor, offset[0], offset[1]); + } + } + return [startIndex, textAnchorOffsets.length]; +} +function addTextVertices(bucket, anchor, shapedText, imageMap, layer, textAlongLine, feature, textOffset, lineArray, writingMode, placementTypes, placedTextSymbolIndices, placedIconIndex, sizes, canonical) { + const glyphQuads = getGlyphQuads(anchor, shapedText, textOffset, layer, textAlongLine, feature, imageMap, bucket.allowVerticalPlacement); + const sizeData = bucket.textSizeData; + let textSizeData = null; + if (sizeData.kind === 'source') { + textSizeData = [ + SIZE_PACK_FACTOR * layer.layout.get('text-size').evaluate(feature, {}) + ]; + if (textSizeData[0] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`); + } + } + else if (sizeData.kind === 'composite') { + textSizeData = [ + SIZE_PACK_FACTOR * sizes.compositeTextSizes[0].evaluate(feature, {}, canonical), + SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical) + ]; + if (textSizeData[0] > MAX_PACKED_SIZE || textSizeData[1] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`); + } + } + bucket.addSymbols(bucket.text, glyphQuads, textSizeData, textOffset, textAlongLine, feature, writingMode, anchor, lineArray.lineStartIndex, lineArray.lineLength, placedIconIndex, canonical); + // The placedSymbolArray is used at render time in drawTileSymbols + // These indices allow access to the array at collision detection time + for (const placementType of placementTypes) { + placedTextSymbolIndices[placementType] = bucket.text.placedSymbolArray.length - 1; + } + return glyphQuads.length * 4; +} +function getDefaultHorizontalShaping(horizontalShaping) { + // We don't care which shaping we get because this is used for collision purposes + // and all the justifications have the same collision box + for (const justification in horizontalShaping) { + return horizontalShaping[justification]; + } + return null; +} +/** + * Add a single label & icon placement. + */ +function addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, layer, collisionBoxArray, featureIndex, sourceLayerIndex, bucketIndex, textBoxScale, textPadding, textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, canonical, layoutTextSize) { + const lineArray = bucket.addToLineVertexArray(anchor, line); + let textCollisionFeature, iconCollisionFeature, verticalTextCollisionFeature, verticalIconCollisionFeature; + let numIconVertices = 0; + let numVerticalIconVertices = 0; + let numHorizontalGlyphVertices = 0; + let numVerticalGlyphVertices = 0; + let placedIconSymbolIndex = -1; + let verticalPlacedIconSymbolIndex = -1; + const placedTextSymbolIndices = {}; + let key = murmur3$1(''); + if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) { + const textRotation = layer.layout.get('text-rotate').evaluate(feature, {}, canonical); + const verticalTextRotation = textRotation + 90.0; + const verticalShaping = shapedTextOrientations.vertical; + verticalTextCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textBoxScale, textPadding, textAlongLine, verticalTextRotation); + if (verticallyShapedIcon) { + verticalIconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconBoxScale, iconPadding, textAlongLine, verticalTextRotation); + } + } + //Place icon first, so text can have a reference to its index in the placed symbol array. + //Text symbols can lazily shift at render-time because of variable anchor placement. + //If the style specifies an `icon-text-fit` then the icon would have to shift along with it. + // For more info check `updateVariableAnchors` in `draw_symbol.js` . + if (shapedIcon) { + const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {}); + const hasIconTextFit = layer.layout.get('icon-text-fit') !== 'none'; + const iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit); + const verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit) : undefined; + iconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconBoxScale, iconPadding, /*align boxes to line*/ false, iconRotate); + numIconVertices = iconQuads.length * 4; + const sizeData = bucket.iconSizeData; + let iconSizeData = null; + if (sizeData.kind === 'source') { + iconSizeData = [ + SIZE_PACK_FACTOR * layer.layout.get('icon-size').evaluate(feature, {}) + ]; + if (iconSizeData[0] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`); + } + } + else if (sizeData.kind === 'composite') { + iconSizeData = [ + SIZE_PACK_FACTOR * sizes.compositeIconSizes[0].evaluate(feature, {}, canonical), + SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical) + ]; + if (iconSizeData[0] > MAX_PACKED_SIZE || iconSizeData[1] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`); + } + } + bucket.addSymbols(bucket.icon, iconQuads, iconSizeData, iconOffset, iconAlongLine, feature, exports.ah.none, anchor, lineArray.lineStartIndex, lineArray.lineLength, + // The icon itself does not have an associated symbol since the text isn't placed yet + -1, canonical); + placedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; + if (verticalIconQuads) { + numVerticalIconVertices = verticalIconQuads.length * 4; + bucket.addSymbols(bucket.icon, verticalIconQuads, iconSizeData, iconOffset, iconAlongLine, feature, exports.ah.vertical, anchor, lineArray.lineStartIndex, lineArray.lineLength, + // The icon itself does not have an associated symbol since the text isn't placed yet + -1, canonical); + verticalPlacedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; + } + } + const justifications = Object.keys(shapedTextOrientations.horizontal); + for (const justification of justifications) { + const shaping = shapedTextOrientations.horizontal[justification]; + if (!textCollisionFeature) { + key = murmur3$1(shaping.text); + const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}, canonical); + // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature + // We're counting on all versions having similar dimensions + textCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textBoxScale, textPadding, textAlongLine, textRotate); + } + const singleLine = shaping.positionedLines.length === 1; + numHorizontalGlyphVertices += addTextVertices(bucket, anchor, shaping, imageMap, layer, textAlongLine, feature, textOffset, lineArray, shapedTextOrientations.vertical ? exports.ah.horizontal : exports.ah.horizontalOnly, singleLine ? justifications : [justification], placedTextSymbolIndices, placedIconSymbolIndex, sizes, canonical); + if (singleLine) { + break; + } + } + if (shapedTextOrientations.vertical) { + numVerticalGlyphVertices += addTextVertices(bucket, anchor, shapedTextOrientations.vertical, imageMap, layer, textAlongLine, feature, textOffset, lineArray, exports.ah.vertical, ['vertical'], placedTextSymbolIndices, verticalPlacedIconSymbolIndex, sizes, canonical); + } + const textBoxStartIndex = textCollisionFeature ? textCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const textBoxEndIndex = textCollisionFeature ? textCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + const verticalTextBoxStartIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const verticalTextBoxEndIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + const iconBoxStartIndex = iconCollisionFeature ? iconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const iconBoxEndIndex = iconCollisionFeature ? iconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + const verticalIconBoxStartIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const verticalIconBoxEndIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + // Check if runtime collision circles should be used for any of the collision features. + // It is enough to choose the tallest feature shape as circles are always placed on a line. + // All measurements are in glyph metrics and later converted into pixels using proper font size "layoutTextSize" + let collisionCircleDiameter = -1; + const getCollisionCircleHeight = (feature, prevHeight) => { + if (feature && feature.circleDiameter) + return Math.max(feature.circleDiameter, prevHeight); + return prevHeight; + }; + collisionCircleDiameter = getCollisionCircleHeight(textCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(verticalTextCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(iconCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(verticalIconCollisionFeature, collisionCircleDiameter); + const useRuntimeCollisionCircles = (collisionCircleDiameter > -1) ? 1 : 0; + // Convert circle collision height into pixels + if (useRuntimeCollisionCircles) + collisionCircleDiameter *= layoutTextSize / ONE_EM; + if (bucket.glyphOffsetArray.length >= SymbolBucket.MAX_GLYPHS) + warnOnce('Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907'); + if (feature.sortKey !== undefined) { + bucket.addToSortKeyRanges(bucket.symbolInstances.length, feature.sortKey); + } + const variableAnchorOffset = getTextVariableAnchorOffset(layer, feature, canonical); + const [textAnchorOffsetStartIndex, textAnchorOffsetEndIndex] = addTextVariableAnchorOffsets(bucket.textAnchorOffsets, variableAnchorOffset); + bucket.symbolInstances.emplaceBack(anchor.x, anchor.y, placedTextSymbolIndices.right >= 0 ? placedTextSymbolIndices.right : -1, placedTextSymbolIndices.center >= 0 ? placedTextSymbolIndices.center : -1, placedTextSymbolIndices.left >= 0 ? placedTextSymbolIndices.left : -1, placedTextSymbolIndices.vertical || -1, placedIconSymbolIndex, verticalPlacedIconSymbolIndex, key, textBoxStartIndex, textBoxEndIndex, verticalTextBoxStartIndex, verticalTextBoxEndIndex, iconBoxStartIndex, iconBoxEndIndex, verticalIconBoxStartIndex, verticalIconBoxEndIndex, featureIndex, numHorizontalGlyphVertices, numVerticalGlyphVertices, numIconVertices, numVerticalIconVertices, useRuntimeCollisionCircles, 0, textBoxScale, collisionCircleDiameter, textAnchorOffsetStartIndex, textAnchorOffsetEndIndex); +} +function anchorIsTooClose(bucket, text, repeatDistance, anchor) { + const compareText = bucket.compareText; + if (!(text in compareText)) { + compareText[text] = []; + } + else { + const otherAnchors = compareText[text]; + for (let k = otherAnchors.length - 1; k >= 0; k--) { + if (anchor.dist(otherAnchors[k]) < repeatDistance) { + // If it's within repeatDistance of one anchor, stop looking + return true; + } + } + } + // If anchor is not within repeatDistance of any other anchor, add to array + compareText[text].push(anchor); + return false; +} + +const ARRAY_TYPES = [ + Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, + Int32Array, Uint32Array, Float32Array, Float64Array +]; + +/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */ + +const VERSION = 1; // serialized format version +const HEADER_SIZE = 8; + +class KDBush { + + /** + * Creates an index from raw `ArrayBuffer` data. + * @param {ArrayBuffer} data + */ + static from(data) { + if (!(data instanceof ArrayBuffer)) { + throw new Error('Data must be an instance of ArrayBuffer.'); + } + const [magic, versionAndType] = new Uint8Array(data, 0, 2); + if (magic !== 0xdb) { + throw new Error('Data does not appear to be in a KDBush format.'); + } + const version = versionAndType >> 4; + if (version !== VERSION) { + throw new Error(`Got v${version} data when expected v${VERSION}.`); + } + const ArrayType = ARRAY_TYPES[versionAndType & 0x0f]; + if (!ArrayType) { + throw new Error('Unrecognized array type.'); + } + const [nodeSize] = new Uint16Array(data, 2, 1); + const [numItems] = new Uint32Array(data, 4, 1); + + return new KDBush(numItems, nodeSize, ArrayType, data); + } + + /** + * Creates an index that will hold a given number of items. + * @param {number} numItems + * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default). + * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default). + * @param {ArrayBuffer} [data] (For internal use only) + */ + constructor(numItems, nodeSize = 64, ArrayType = Float64Array, data) { + if (isNaN(numItems) || numItems < 0) throw new Error(`Unpexpected numItems value: ${numItems}.`); + + this.numItems = +numItems; + this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535); + this.ArrayType = ArrayType; + this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array; + + const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType); + const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT; + const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT; + const padCoords = (8 - idsByteSize % 8) % 8; + + if (arrayTypeIndex < 0) { + throw new Error(`Unexpected typed array class: ${ArrayType}.`); + } + + if (data && (data instanceof ArrayBuffer)) { // reconstruct an index from a buffer + this.data = data; + this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems); + this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2); + this._pos = numItems * 2; + this._finished = true; + } else { // initialize a new index + this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords); + this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems); + this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2); + this._pos = 0; + this._finished = false; + + // set header + new Uint8Array(this.data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]); + new Uint16Array(this.data, 2, 1)[0] = nodeSize; + new Uint32Array(this.data, 4, 1)[0] = numItems; + } + } + + /** + * Add a point to the index. + * @param {number} x + * @param {number} y + * @returns {number} An incremental index associated with the added item (starting from `0`). + */ + add(x, y) { + const index = this._pos >> 1; + this.ids[index] = index; + this.coords[this._pos++] = x; + this.coords[this._pos++] = y; + return index; + } + + /** + * Perform indexing of the added points. + */ + finish() { + const numAdded = this._pos >> 1; + if (numAdded !== this.numItems) { + throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`); + } + // kd-sort both arrays for efficient search + sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0); + + this._finished = true; + return this; + } + + /** + * Search the index for items within a given bounding box. + * @param {number} minX + * @param {number} minY + * @param {number} maxX + * @param {number} maxY + * @returns {number[]} An array of indices correponding to the found items. + */ + range(minX, minY, maxX, maxY) { + if (!this._finished) throw new Error('Data not yet indexed - call index.finish().'); + + const {ids, coords, nodeSize} = this; + const stack = [0, ids.length - 1, 0]; + const result = []; + + // recursively search for items in range in the kd-sorted arrays + while (stack.length) { + const axis = stack.pop() || 0; + const right = stack.pop() || 0; + const left = stack.pop() || 0; + + // if we reached "tree node", search linearly + if (right - left <= nodeSize) { + for (let i = left; i <= right; i++) { + const x = coords[2 * i]; + const y = coords[2 * i + 1]; + if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]); + } + continue; + } + + // otherwise find the middle index + const m = (left + right) >> 1; + + // include the middle item if it's in range + const x = coords[2 * m]; + const y = coords[2 * m + 1]; + if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]); + + // queue search in halves that intersect the query + if (axis === 0 ? minX <= x : minY <= y) { + stack.push(left); + stack.push(m - 1); + stack.push(1 - axis); + } + if (axis === 0 ? maxX >= x : maxY >= y) { + stack.push(m + 1); + stack.push(right); + stack.push(1 - axis); + } + } + + return result; + } + + /** + * Search the index for items within a given radius. + * @param {number} qx + * @param {number} qy + * @param {number} r Query radius. + * @returns {number[]} An array of indices correponding to the found items. + */ + within(qx, qy, r) { + if (!this._finished) throw new Error('Data not yet indexed - call index.finish().'); + + const {ids, coords, nodeSize} = this; + const stack = [0, ids.length - 1, 0]; + const result = []; + const r2 = r * r; + + // recursively search for items within radius in the kd-sorted arrays + while (stack.length) { + const axis = stack.pop() || 0; + const right = stack.pop() || 0; + const left = stack.pop() || 0; + + // if we reached "tree node", search linearly + if (right - left <= nodeSize) { + for (let i = left; i <= right; i++) { + if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]); + } + continue; + } + + // otherwise find the middle index + const m = (left + right) >> 1; + + // include the middle item if it's in range + const x = coords[2 * m]; + const y = coords[2 * m + 1]; + if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]); + + // queue search in halves that intersect the query + if (axis === 0 ? qx - r <= x : qy - r <= y) { + stack.push(left); + stack.push(m - 1); + stack.push(1 - axis); + } + if (axis === 0 ? qx + r >= x : qy + r >= y) { + stack.push(m + 1); + stack.push(right); + stack.push(1 - axis); + } + } + + return result; + } +} + +/** + * @param {Uint16Array | Uint32Array} ids + * @param {InstanceType} coords + * @param {number} nodeSize + * @param {number} left + * @param {number} right + * @param {number} axis + */ +function sort(ids, coords, nodeSize, left, right, axis) { + if (right - left <= nodeSize) return; + + const m = (left + right) >> 1; // middle index + + // sort ids and coords around the middle index so that the halves lie + // either left/right or top/bottom correspondingly (taking turns) + select(ids, coords, m, left, right, axis); + + // recursively kd-sort first half and second half on the opposite axis + sort(ids, coords, nodeSize, left, m - 1, 1 - axis); + sort(ids, coords, nodeSize, m + 1, right, 1 - axis); +} + +/** + * Custom Floyd-Rivest selection algorithm: sort ids and coords so that + * [left..k-1] items are smaller than k-th item (on either x or y axis) + * @param {Uint16Array | Uint32Array} ids + * @param {InstanceType} coords + * @param {number} k + * @param {number} left + * @param {number} right + * @param {number} axis + */ +function select(ids, coords, k, left, right, axis) { + + while (right > left) { + if (right - left > 600) { + const n = right - left + 1; + const m = k - left + 1; + const z = Math.log(n); + const s = 0.5 * Math.exp(2 * z / 3); + const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + const newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + select(ids, coords, k, newLeft, newRight, axis); + } + + const t = coords[2 * k + axis]; + let i = left; + let j = right; + + swapItem(ids, coords, left, k); + if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right); + + while (i < j) { + swapItem(ids, coords, i, j); + i++; + j--; + while (coords[2 * i + axis] < t) i++; + while (coords[2 * j + axis] > t) j--; + } + + if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j); + else { + j++; + swapItem(ids, coords, j, right); + } + + if (j <= k) left = j + 1; + if (k <= j) right = j - 1; + } +} + +/** + * @param {Uint16Array | Uint32Array} ids + * @param {InstanceType} coords + * @param {number} i + * @param {number} j + */ +function swapItem(ids, coords, i, j) { + swap(ids, i, j); + swap(coords, 2 * i, 2 * j); + swap(coords, 2 * i + 1, 2 * j + 1); +} + +/** + * @param {InstanceType} arr + * @param {number} i + * @param {number} j + */ +function swap(arr, i, j) { + const tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} + +/** + * @param {number} ax + * @param {number} ay + * @param {number} bx + * @param {number} by + */ +function sqDist(ax, ay, bx, by) { + const dx = ax - bx; + const dy = ay - by; + return dx * dx + dy * dy; +} + +exports.bg = void 0; +(function (PerformanceMarkers) { + PerformanceMarkers["create"] = "create"; + PerformanceMarkers["load"] = "load"; + PerformanceMarkers["fullLoad"] = "fullLoad"; +})(exports.bg || (exports.bg = {})); +let lastFrameTime = null; +let frameTimes = []; +const minFramerateTarget = 60; +const frameTimeTarget = 1000 / minFramerateTarget; +const loadTimeKey = 'loadTime'; +const fullLoadTimeKey = 'fullLoadTime'; +const PerformanceUtils = { + mark(marker) { + performance.mark(marker); + }, + frame(timestamp) { + const currTimestamp = timestamp; + if (lastFrameTime != null) { + const frameTime = currTimestamp - lastFrameTime; + frameTimes.push(frameTime); + } + lastFrameTime = currTimestamp; + }, + clearMetrics() { + lastFrameTime = null; + frameTimes = []; + performance.clearMeasures(loadTimeKey); + performance.clearMeasures(fullLoadTimeKey); + for (const marker in exports.bg) { + performance.clearMarks(exports.bg[marker]); + } + }, + getPerformanceMetrics() { + performance.measure(loadTimeKey, exports.bg.create, exports.bg.load); + performance.measure(fullLoadTimeKey, exports.bg.create, exports.bg.fullLoad); + const loadTime = performance.getEntriesByName(loadTimeKey)[0].duration; + const fullLoadTime = performance.getEntriesByName(fullLoadTimeKey)[0].duration; + const totalFrames = frameTimes.length; + const avgFrameTime = frameTimes.reduce((prev, curr) => prev + curr, 0) / totalFrames / 1000; + const fps = 1 / avgFrameTime; + // count frames that missed our framerate target + const droppedFrames = frameTimes + .filter((frameTime) => frameTime > frameTimeTarget) + .reduce((acc, curr) => { + return acc + (curr - frameTimeTarget) / frameTimeTarget; + }, 0); + const percentDroppedFrames = (droppedFrames / (totalFrames + droppedFrames)) * 100; + return { + loadTime, + fullLoadTime, + fps, + percentDroppedFrames, + totalFrames + }; + } +}; +/** + * @internal + * Safe wrapper for the performance resource timing API in web workers with graceful degradation + */ +class RequestPerformance { + constructor(request) { + this._marks = { + start: [request.url, 'start'].join('#'), + end: [request.url, 'end'].join('#'), + measure: request.url.toString() + }; + performance.mark(this._marks.start); + } + finish() { + performance.mark(this._marks.end); + let resourceTimingData = performance.getEntriesByName(this._marks.measure); + // fallback if web worker implementation of perf.getEntriesByName returns empty + if (resourceTimingData.length === 0) { + performance.measure(this._marks.measure, this._marks.start, this._marks.end); + resourceTimingData = performance.getEntriesByName(this._marks.measure); + // cleanup + performance.clearMarks(this._marks.start); + performance.clearMarks(this._marks.end); + performance.clearMeasures(this._marks.measure); + } + return resourceTimingData; + } +} + +exports.$ = RasterBoundsArray; +exports.A = ARRAY_TYPE; +exports.B = validateSky; +exports.C = isSafari; +exports.D = DataConstantProperty; +exports.E = Evented; +exports.F = Actor; +exports.G = GLOBAL_DISPATCHER_ID; +exports.H = create$1; +exports.I = ImagePosition; +exports.J = translate; +exports.K = scale; +exports.L = multiply$1; +exports.M = pick; +exports.N = LngLat; +exports.O = mercatorXfromLng; +exports.P = Point$2; +exports.Q = mercatorYfromLat; +exports.R = RGBAImage; +exports.S = OverscaledTileID; +exports.T = Transitionable; +exports.U = offscreenCanvasSupported; +exports.V = isOffscreenCanvasDistorted; +exports.W = readImageUsingVideoFrame; +exports.X = EXTENT; +exports.Y = createLayout; +exports.Z = MercatorCoordinate; +exports._ = __awaiter; +exports.a = config; +exports.a$ = equals$1; +exports.a0 = SegmentVector; +exports.a1 = CanonicalTileID; +exports.a2 = ValidationError; +exports.a3 = getVideo; +exports.a4 = uniqueId; +exports.a5 = CollisionBoxArray; +exports.a6 = SymbolBucket; +exports.a7 = createFilter; +exports.a8 = toEvaluationFeature; +exports.a9 = GeoJSONFeature; +exports.aA = createStyleLayer; +exports.aB = clone$1; +exports.aC = diffStyles; +exports.aD = validateCustomStyleLayer; +exports.aE = deepEqual$1; +exports.aF = mapObject; +exports.aG = filterObject; +exports.aH = Uniform1i; +exports.aI = Uniform1f; +exports.aJ = UniformMatrix4f; +exports.aK = Uniform4f; +exports.aL = UniformColor; +exports.aM = Color; +exports.aN = Uniform3f; +exports.aO = Uniform2f; +exports.aP = ortho; +exports.aQ = mul$1; +exports.aR = CollisionCircleLayoutArray; +exports.aS = collisionCircleLayout; +exports.aT = QuadTriangleArray; +exports.aU = HEATMAP_FULL_RENDER_FBO_KEY; +exports.aV = nextPowerOfTwo; +exports.aW = renderColorRamp; +exports.aX = PosArray; +exports.aY = TriangleIndexArray; +exports.aZ = LineStripIndexArray; +exports.a_ = exactEquals; +exports.aa = parseCacheControl; +exports.ab = keysDifference; +exports.ac = clamp$1; +exports.ad = rotateZ; +exports.ae = clone; +exports.af = transformMat4; +exports.ag = evaluateSizeForZoom; +exports.ai = evaluateSizeForFeature; +exports.aj = addDynamicAttributes; +exports.ak = findLineIntersection; +exports.al = clipLine; +exports.am = polygonIntersectsPolygon; +exports.an = identity; +exports.ao = getAABB; +exports.ap = ONE_EM; +exports.ar = getOverlapMode; +exports.as = invert; +exports.at = getAnchorJustification; +exports.au = getAnchorAlignment; +exports.av = KDBush; +exports.aw = emptyStyle; +exports.ax = ZoomHistory; +exports.ay = getReferrer; +exports.az = derefLayers; +exports.b = isImageBitmap; +exports.b0 = copy; +exports.b1 = mul; +exports.b2 = dot$1; +exports.b3 = wrap; +exports.b4 = UnwrappedTileID; +exports.b5 = mercatorZfromAltitude; +exports.b6 = perspective; +exports.b7 = rotateX; +exports.b8 = bezier; +exports.b9 = defaultEasing; +exports.bA = pbf; +exports.bB = isAbortError; +exports.bC = createExpression; +exports.bD = rtlWorkerPlugin; +exports.ba = degreesToRadians; +exports.bb = isInBoundsForZoomLngLat; +exports.bc = fromScaling; +exports.bd = Pos3dArray; +exports.be = earthRadius; +exports.bf = PerformanceUtils; +exports.bh = AJAXError; +exports.bi = addProtocol; +exports.bj = removeProtocol; +exports.bk = groupByLayout; +exports.bl = register; +exports.bm = DictionaryCoder; +exports.bn = FeatureIndex; +exports.bo = ImageAtlas; +exports.bp = performSymbolLayout; +exports.bq = LineBucket; +exports.br = FillBucket; +exports.bs = FillExtrusionBucket; +exports.bt = vectorTile; +exports.bu = Protobuf; +exports.bv = RequestPerformance; +exports.bw = getImageData; +exports.bx = DEMData; +exports.by = getDefaultExportFromCjs$1; +exports.bz = pointGeometry; +exports.c = createAbortError; +exports.d = arrayBufferToImageBitmap; +exports.e = extend; +exports.f = arrayBufferToImage; +exports.g = getProtocol; +exports.h = getJSON; +exports.i = isWorker; +exports.j = ErrorEvent; +exports.k = Event; +exports.l = getArrayBuffer; +exports.m = makeRequest; +exports.n = parseGlyphPbf; +exports.o = AlphaImage; +exports.p = potpack; +exports.q = Properties; +exports.r = validateLight; +exports.s = sameOrigin; +exports.t = emitValidationErrors; +exports.u = validateStyle; +exports.v = v8Spec; +exports.w = warnOnce; +exports.x = sphericalToCartesian; +exports.y = interpolate; +exports.z = EvaluationParameters; + +})); + +define('worker', ['./shared'], (function (performance) { 'use strict'; + +class StyleLayerIndex { + constructor(layerConfigs) { + this.keyCache = {}; + if (layerConfigs) { + this.replace(layerConfigs); + } + } + replace(layerConfigs) { + this._layerConfigs = {}; + this._layers = {}; + this.update(layerConfigs, []); + } + update(layerConfigs, removedIds) { + for (const layerConfig of layerConfigs) { + this._layerConfigs[layerConfig.id] = layerConfig; + const layer = this._layers[layerConfig.id] = performance.aA(layerConfig); + layer._featureFilter = performance.a7(layer.filter); + if (this.keyCache[layerConfig.id]) + delete this.keyCache[layerConfig.id]; + } + for (const id of removedIds) { + delete this.keyCache[id]; + delete this._layerConfigs[id]; + delete this._layers[id]; + } + this.familiesBySource = {}; + const groups = performance.bk(Object.values(this._layerConfigs), this.keyCache); + for (const layerConfigs of groups) { + const layers = layerConfigs.map((layerConfig) => this._layers[layerConfig.id]); + const layer = layers[0]; + if (layer.visibility === 'none') { + continue; + } + const sourceId = layer.source || ''; + let sourceGroup = this.familiesBySource[sourceId]; + if (!sourceGroup) { + sourceGroup = this.familiesBySource[sourceId] = {}; + } + const sourceLayerId = layer.sourceLayer || '_geojsonTileLayer'; + let sourceLayerFamilies = sourceGroup[sourceLayerId]; + if (!sourceLayerFamilies) { + sourceLayerFamilies = sourceGroup[sourceLayerId] = []; + } + sourceLayerFamilies.push(layers); + } + } +} + +const padding = 1; +class GlyphAtlas { + constructor(stacks) { + const positions = {}; + const bins = []; + for (const stack in stacks) { + const glyphs = stacks[stack]; + const stackPositions = positions[stack] = {}; + for (const id in glyphs) { + const src = glyphs[+id]; + if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) + continue; + const bin = { + x: 0, + y: 0, + w: src.bitmap.width + 2 * padding, + h: src.bitmap.height + 2 * padding + }; + bins.push(bin); + stackPositions[id] = { rect: bin, metrics: src.metrics }; + } + } + const { w, h } = performance.p(bins); + const image = new performance.o({ width: w || 1, height: h || 1 }); + for (const stack in stacks) { + const glyphs = stacks[stack]; + for (const id in glyphs) { + const src = glyphs[+id]; + if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) + continue; + const bin = positions[stack][id].rect; + performance.o.copy(src.bitmap, image, { x: 0, y: 0 }, { x: bin.x + padding, y: bin.y + padding }, src.bitmap); + } + } + this.image = image; + this.positions = positions; + } +} +performance.bl('GlyphAtlas', GlyphAtlas); + +class WorkerTile { + constructor(params) { + this.tileID = new performance.S(params.tileID.overscaledZ, params.tileID.wrap, params.tileID.canonical.z, params.tileID.canonical.x, params.tileID.canonical.y); + this.uid = params.uid; + this.zoom = params.zoom; + this.pixelRatio = params.pixelRatio; + this.tileSize = params.tileSize; + this.source = params.source; + this.overscaling = this.tileID.overscaleFactor(); + this.showCollisionBoxes = params.showCollisionBoxes; + this.collectResourceTiming = !!params.collectResourceTiming; + this.returnDependencies = !!params.returnDependencies; + this.promoteId = params.promoteId; + this.inFlightDependencies = []; + } + parse(data, layerIndex, availableImages, actor) { + return performance._(this, void 0, void 0, function* () { + this.status = 'parsing'; + this.data = data; + this.collisionBoxArray = new performance.a5(); + const sourceLayerCoder = new performance.bm(Object.keys(data.layers).sort()); + const featureIndex = new performance.bn(this.tileID, this.promoteId); + featureIndex.bucketLayerIDs = []; + const buckets = {}; + const options = { + featureIndex, + iconDependencies: {}, + patternDependencies: {}, + glyphDependencies: {}, + availableImages + }; + const layerFamilies = layerIndex.familiesBySource[this.source]; + for (const sourceLayerId in layerFamilies) { + const sourceLayer = data.layers[sourceLayerId]; + if (!sourceLayer) { + continue; + } + if (sourceLayer.version === 1) { + performance.w(`Vector tile source "${this.source}" layer "${sourceLayerId}" ` + + 'does not use vector tile spec v2 and therefore may have some rendering errors.'); + } + const sourceLayerIndex = sourceLayerCoder.encode(sourceLayerId); + const features = []; + for (let index = 0; index < sourceLayer.length; index++) { + const feature = sourceLayer.feature(index); + const id = featureIndex.getId(feature, sourceLayerId); + features.push({ feature, id, index, sourceLayerIndex }); + } + for (const family of layerFamilies[sourceLayerId]) { + const layer = family[0]; + if (layer.source !== this.source) { + performance.w(`layer.source = ${layer.source} does not equal this.source = ${this.source}`); + } + if (layer.minzoom && this.zoom < Math.floor(layer.minzoom)) + continue; + if (layer.maxzoom && this.zoom >= layer.maxzoom) + continue; + if (layer.visibility === 'none') + continue; + recalculateLayers(family, this.zoom, availableImages); + const bucket = buckets[layer.id] = layer.createBucket({ + index: featureIndex.bucketLayerIDs.length, + layers: family, + zoom: this.zoom, + pixelRatio: this.pixelRatio, + overscaling: this.overscaling, + collisionBoxArray: this.collisionBoxArray, + sourceLayerIndex, + sourceID: this.source + }); + bucket.populate(features, options, this.tileID.canonical); + featureIndex.bucketLayerIDs.push(family.map((l) => l.id)); + } + } + // options.glyphDependencies looks like: {"SomeFontName":{"10":true,"32":true}} + // this line makes an object like: {"SomeFontName":[10,32]} + const stacks = performance.aF(options.glyphDependencies, (glyphs) => Object.keys(glyphs).map(Number)); + this.inFlightDependencies.forEach((request) => request === null || request === void 0 ? void 0 : request.abort()); + this.inFlightDependencies = []; + let getGlyphsPromise = Promise.resolve({}); + if (Object.keys(stacks).length) { + const abortController = new AbortController(); + this.inFlightDependencies.push(abortController); + getGlyphsPromise = actor.sendAsync({ type: "GG" /* MessageType.getGlyphs */, data: { stacks, source: this.source, tileID: this.tileID, type: 'glyphs' } }, abortController); + } + const icons = Object.keys(options.iconDependencies); + let getIconsPromise = Promise.resolve({}); + let getIconBackgroundsPromise = Promise.resolve({}); + if (icons.length) { + const abortController = new AbortController(); + this.inFlightDependencies.push(abortController); + getIconsPromise = actor.sendAsync({ type: "GI" /* MessageType.getImages */, data: { icons, source: this.source, tileID: this.tileID, type: 'icons' } }, abortController); + // If there are MSDF icons we also need to add the background + const msdfIcons = icons.filter(i => i.includes('msdf')); + const backgroundIcons = msdfIcons.map(i => i.replace('msdf', 'msdf-backgrounds')); + if (backgroundIcons.length) { + getIconBackgroundsPromise = actor.sendAsync({ type: "GI" /* MessageType.getImages */, data: { icons: backgroundIcons, source: this.source, tileID: this.tileID, type: 'icons' } }, abortController); + } + } + const patterns = Object.keys(options.patternDependencies); + let getPatternsPromise = Promise.resolve({}); + if (patterns.length) { + const abortController = new AbortController(); + this.inFlightDependencies.push(abortController); + getPatternsPromise = actor.sendAsync({ type: "GI" /* MessageType.getImages */, data: { icons: patterns, source: this.source, tileID: this.tileID, type: 'patterns' } }, abortController); + } + const [glyphMap, iconMap, iconBackgroundsMap, patternMap] = yield Promise.all([getGlyphsPromise, getIconsPromise, getIconBackgroundsPromise, getPatternsPromise]); + const glyphAtlas = new GlyphAtlas(glyphMap); + const imageAtlas = new performance.bo(iconMap, patternMap); + const imageBackgroundsAtlas = new performance.bo(iconBackgroundsMap, {}); + for (const key in buckets) { + const bucket = buckets[key]; + if (bucket instanceof performance.a6) { + recalculateLayers(bucket.layers, this.zoom, availableImages); + performance.bp({ + bucket, + glyphMap, + glyphPositions: glyphAtlas.positions, + imageMap: iconMap, + imagePositions: imageAtlas.iconPositions, + showCollisionBoxes: this.showCollisionBoxes, + canonical: this.tileID.canonical + }); + } + else if (bucket.hasPattern && + (bucket instanceof performance.bq || + bucket instanceof performance.br || + bucket instanceof performance.bs)) { + recalculateLayers(bucket.layers, this.zoom, availableImages); + bucket.addFeatures(options, this.tileID.canonical, imageAtlas.patternPositions); + } + } + this.status = 'done'; + return { + buckets: Object.values(buckets).filter(b => !b.isEmpty()), + featureIndex, + collisionBoxArray: this.collisionBoxArray, + glyphAtlasImage: glyphAtlas.image, + imageAtlas, + imageBackgroundsAtlas, + // Only used for benchmarking: + glyphMap: this.returnDependencies ? glyphMap : null, + iconMap: this.returnDependencies ? iconMap : null, + glyphPositions: this.returnDependencies ? glyphAtlas.positions : null + }; + }); + } +} +function recalculateLayers(layers, zoom, availableImages) { + // Layers are shared and may have been used by a WorkerTile with a different zoom. + const parameters = new performance.z(zoom); + for (const layer of layers) { + layer.recalculate(parameters, availableImages); + } +} + +/** + * The {@link WorkerSource} implementation that supports {@link VectorTileSource}. + * This class is designed to be easily reused to support custom source types + * for data formats that can be parsed/converted into an in-memory VectorTile + * representation. To do so, override its `loadVectorTile` method. + */ +class VectorTileWorkerSource { + /** + * @param loadVectorData - Optional method for custom loading of a VectorTile + * object based on parameters passed from the main-thread Source. See + * {@link VectorTileWorkerSource#loadTile}. The default implementation simply + * loads the pbf at `params.url`. + */ + constructor(actor, layerIndex, availableImages) { + this.actor = actor; + this.layerIndex = layerIndex; + this.availableImages = availableImages; + this.fetching = {}; + this.loading = {}; + this.loaded = {}; + } + /** + * Loads a vector tile + */ + loadVectorTile(params, abortController) { + return performance._(this, void 0, void 0, function* () { + const response = yield performance.l(params.request, abortController); + try { + const vectorTile = new performance.bt.VectorTile(new performance.bu(response.data)); + return { + vectorTile, + rawData: response.data, + cacheControl: response.cacheControl, + expires: response.expires + }; + } + catch (ex) { + const bytes = new Uint8Array(response.data); + const isGzipped = bytes[0] === 0x1f && bytes[1] === 0x8b; + let errorMessage = `Unable to parse the tile at ${params.request.url}, `; + if (isGzipped) { + errorMessage += 'please make sure the data is not gzipped and that you have configured the relevant header in the server'; + } + else { + errorMessage += `got error: ${ex.message}`; + } + throw new Error(errorMessage); + } + }); + } + /** + * Implements {@link WorkerSource#loadTile}. Delegates to + * {@link VectorTileWorkerSource#loadVectorData} (which by default expects + * a `params.url` property) for fetching and producing a VectorTile object. + */ + loadTile(params) { + return performance._(this, void 0, void 0, function* () { + const tileUid = params.uid; + const perf = (params && params.request && params.request.collectResourceTiming) ? + new performance.bv(params.request) : false; + const workerTile = new WorkerTile(params); + this.loading[tileUid] = workerTile; + const abortController = new AbortController(); + workerTile.abort = abortController; + try { + const response = yield this.loadVectorTile(params, abortController); + delete this.loading[tileUid]; + if (!response) { + return null; + } + const rawTileData = response.rawData; + const cacheControl = {}; + if (response.expires) + cacheControl.expires = response.expires; + if (response.cacheControl) + cacheControl.cacheControl = response.cacheControl; + const resourceTiming = {}; + if (perf) { + const resourceTimingData = perf.finish(); + // it's necessary to eval the result of getEntriesByName() here via parse/stringify + // late evaluation in the main thread causes TypeError: illegal invocation + if (resourceTimingData) + resourceTiming.resourceTiming = JSON.parse(JSON.stringify(resourceTimingData)); + } + workerTile.vectorTile = response.vectorTile; + const parsePromise = workerTile.parse(response.vectorTile, this.layerIndex, this.availableImages, this.actor); + this.loaded[tileUid] = workerTile; + // keep the original fetching state so that reload tile can pick it up if the original parse is cancelled by reloads' parse + this.fetching[tileUid] = { rawTileData, cacheControl, resourceTiming }; + try { + const result = yield parsePromise; + // Transferring a copy of rawTileData because the worker needs to retain its copy. + return performance.e({ rawTileData: rawTileData.slice(0) }, result, cacheControl, resourceTiming); + } + finally { + delete this.fetching[tileUid]; + } + } + catch (err) { + delete this.loading[tileUid]; + workerTile.status = 'done'; + this.loaded[tileUid] = workerTile; + throw err; + } + }); + } + /** + * Implements {@link WorkerSource#reloadTile}. + */ + reloadTile(params) { + return performance._(this, void 0, void 0, function* () { + const uid = params.uid; + if (!this.loaded || !this.loaded[uid]) { + throw new Error('Should not be trying to reload a tile that was never loaded or has been removed'); + } + const workerTile = this.loaded[uid]; + workerTile.showCollisionBoxes = params.showCollisionBoxes; + if (workerTile.status === 'parsing') { + const result = yield workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor); + // if we have cancelled the original parse, make sure to pass the rawTileData from the original fetch + let parseResult; + if (this.fetching[uid]) { + const { rawTileData, cacheControl, resourceTiming } = this.fetching[uid]; + delete this.fetching[uid]; + parseResult = performance.e({ rawTileData: rawTileData.slice(0) }, result, cacheControl, resourceTiming); + } + else { + parseResult = result; + } + return parseResult; + } + // if there was no vector tile data on the initial load, don't try and re-parse tile + if (workerTile.status === 'done' && workerTile.vectorTile) { + // this seems like a missing case where cache control is lost? see #3309 + return workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor); + } + }); + } + /** + * Implements {@link WorkerSource#abortTile}. + */ + abortTile(params) { + return performance._(this, void 0, void 0, function* () { + const loading = this.loading; + const uid = params.uid; + if (loading && loading[uid] && loading[uid].abort) { + loading[uid].abort.abort(); + delete loading[uid]; + } + }); + } + /** + * Implements {@link WorkerSource#removeTile}. + */ + removeTile(params) { + return performance._(this, void 0, void 0, function* () { + if (this.loaded && this.loaded[params.uid]) { + delete this.loaded[params.uid]; + } + }); + } +} + +class RasterDEMTileWorkerSource { + constructor() { + this.loaded = {}; + } + loadTile(params) { + return performance._(this, void 0, void 0, function* () { + const { uid, encoding, rawImageData, redFactor, greenFactor, blueFactor, baseShift } = params; + const width = rawImageData.width + 2; + const height = rawImageData.height + 2; + const imagePixels = performance.b(rawImageData) ? + new performance.R({ width, height }, yield performance.bw(rawImageData, -1, -1, width, height)) : + rawImageData; + const dem = new performance.bx(uid, imagePixels, encoding, redFactor, greenFactor, blueFactor, baseShift); + this.loaded = this.loaded || {}; + this.loaded[uid] = dem; + return dem; + }); + } + removeTile(params) { + const loaded = this.loaded, uid = params.uid; + if (loaded && loaded[uid]) { + delete loaded[uid]; + } + } +} + +var geojsonRewind = rewind$1; + +function rewind$1(gj, outer) { + var type = gj && gj.type, i; + + if (type === 'FeatureCollection') { + for (i = 0; i < gj.features.length; i++) rewind$1(gj.features[i], outer); + + } else if (type === 'GeometryCollection') { + for (i = 0; i < gj.geometries.length; i++) rewind$1(gj.geometries[i], outer); + + } else if (type === 'Feature') { + rewind$1(gj.geometry, outer); + + } else if (type === 'Polygon') { + rewindRings(gj.coordinates, outer); + + } else if (type === 'MultiPolygon') { + for (i = 0; i < gj.coordinates.length; i++) rewindRings(gj.coordinates[i], outer); + } + + return gj; +} + +function rewindRings(rings, outer) { + if (rings.length === 0) return; + + rewindRing(rings[0], outer); + for (var i = 1; i < rings.length; i++) { + rewindRing(rings[i], !outer); + } +} + +function rewindRing(ring, dir) { + var area = 0, err = 0; + for (var i = 0, len = ring.length, j = len - 1; i < len; j = i++) { + var k = (ring[i][0] - ring[j][0]) * (ring[j][1] + ring[i][1]); + var m = area + k; + err += Math.abs(area) >= Math.abs(k) ? area - m + k : k - m + area; + area = m; + } + if (area + err >= 0 !== !!dir) ring.reverse(); +} + +var rewind$2 = /*@__PURE__*/performance.by(geojsonRewind); + +const toGeoJSON = performance.bt.VectorTileFeature.prototype.toGeoJSON; +let FeatureWrapper$1 = class FeatureWrapper { + constructor(feature) { + this._feature = feature; + this.extent = performance.X; + this.type = feature.type; + this.properties = feature.tags; + // If the feature has a top-level `id` property, copy it over, but only + // if it can be coerced to an integer, because this wrapper is used for + // serializing geojson feature data into vector tile PBF data, and the + // vector tile spec only supports integer values for feature ids -- + // allowing non-integer values here results in a non-compliant PBF + // that causes an exception when it is parsed with vector-tile-js + if ('id' in feature && !isNaN(feature.id)) { + this.id = parseInt(feature.id, 10); + } + } + loadGeometry() { + if (this._feature.type === 1) { + const geometry = []; + for (const point of this._feature.geometry) { + geometry.push([new performance.P(point[0], point[1])]); + } + return geometry; + } + else { + const geometry = []; + for (const ring of this._feature.geometry) { + const newRing = []; + for (const point of ring) { + newRing.push(new performance.P(point[0], point[1])); + } + geometry.push(newRing); + } + return geometry; + } + } + toGeoJSON(x, y, z) { + return toGeoJSON.call(this, x, y, z); + } +}; +let GeoJSONWrapper$2 = class GeoJSONWrapper { + constructor(features) { + this.layers = { '_geojsonTileLayer': this }; + this.name = '_geojsonTileLayer'; + this.extent = performance.X; + this.length = features.length; + this._features = features; + } + feature(i) { + return new FeatureWrapper$1(this._features[i]); + } +}; + +var vtPbf = {exports: {}}; + +var Point = performance.bz; +var VectorTileFeature = performance.bt.VectorTileFeature; + +var geojson_wrapper = GeoJSONWrapper$1; + +// conform to vectortile api +function GeoJSONWrapper$1 (features, options) { + this.options = options || {}; + this.features = features; + this.length = features.length; +} + +GeoJSONWrapper$1.prototype.feature = function (i) { + return new FeatureWrapper(this.features[i], this.options.extent) +}; + +function FeatureWrapper (feature, extent) { + this.id = typeof feature.id === 'number' ? feature.id : undefined; + this.type = feature.type; + this.rawGeometry = feature.type === 1 ? [feature.geometry] : feature.geometry; + this.properties = feature.tags; + this.extent = extent || 4096; +} + +FeatureWrapper.prototype.loadGeometry = function () { + var rings = this.rawGeometry; + this.geometry = []; + + for (var i = 0; i < rings.length; i++) { + var ring = rings[i]; + var newRing = []; + for (var j = 0; j < ring.length; j++) { + newRing.push(new Point(ring[j][0], ring[j][1])); + } + this.geometry.push(newRing); + } + return this.geometry +}; + +FeatureWrapper.prototype.bbox = function () { + if (!this.geometry) this.loadGeometry(); + + var rings = this.geometry; + var x1 = Infinity; + var x2 = -Infinity; + var y1 = Infinity; + var y2 = -Infinity; + + for (var i = 0; i < rings.length; i++) { + var ring = rings[i]; + + for (var j = 0; j < ring.length; j++) { + var coord = ring[j]; + + x1 = Math.min(x1, coord.x); + x2 = Math.max(x2, coord.x); + y1 = Math.min(y1, coord.y); + y2 = Math.max(y2, coord.y); + } + } + + return [x1, y1, x2, y2] +}; + +FeatureWrapper.prototype.toGeoJSON = VectorTileFeature.prototype.toGeoJSON; + +var Pbf = performance.bA; +var GeoJSONWrapper = geojson_wrapper; + +vtPbf.exports = fromVectorTileJs; +vtPbf.exports.fromVectorTileJs = fromVectorTileJs; +vtPbf.exports.fromGeojsonVt = fromGeojsonVt; +vtPbf.exports.GeoJSONWrapper = GeoJSONWrapper; + +/** + * Serialize a vector-tile-js-created tile to pbf + * + * @param {Object} tile + * @return {Buffer} uncompressed, pbf-serialized tile data + */ +function fromVectorTileJs (tile) { + var out = new Pbf(); + writeTile(tile, out); + return out.finish() +} + +/** + * Serialized a geojson-vt-created tile to pbf. + * + * @param {Object} layers - An object mapping layer names to geojson-vt-created vector tile objects + * @param {Object} [options] - An object specifying the vector-tile specification version and extent that were used to create `layers`. + * @param {Number} [options.version=1] - Version of vector-tile spec used + * @param {Number} [options.extent=4096] - Extent of the vector tile + * @return {Buffer} uncompressed, pbf-serialized tile data + */ +function fromGeojsonVt (layers, options) { + options = options || {}; + var l = {}; + for (var k in layers) { + l[k] = new GeoJSONWrapper(layers[k].features, options); + l[k].name = k; + l[k].version = options.version; + l[k].extent = options.extent; + } + return fromVectorTileJs({ layers: l }) +} + +function writeTile (tile, pbf) { + for (var key in tile.layers) { + pbf.writeMessage(3, writeLayer, tile.layers[key]); + } +} + +function writeLayer (layer, pbf) { + pbf.writeVarintField(15, layer.version || 1); + pbf.writeStringField(1, layer.name || ''); + pbf.writeVarintField(5, layer.extent || 4096); + + var i; + var context = { + keys: [], + values: [], + keycache: {}, + valuecache: {} + }; + + for (i = 0; i < layer.length; i++) { + context.feature = layer.feature(i); + pbf.writeMessage(2, writeFeature, context); + } + + var keys = context.keys; + for (i = 0; i < keys.length; i++) { + pbf.writeStringField(3, keys[i]); + } + + var values = context.values; + for (i = 0; i < values.length; i++) { + pbf.writeMessage(4, writeValue, values[i]); + } +} + +function writeFeature (context, pbf) { + var feature = context.feature; + + if (feature.id !== undefined) { + pbf.writeVarintField(1, feature.id); + } + + pbf.writeMessage(2, writeProperties, context); + pbf.writeVarintField(3, feature.type); + pbf.writeMessage(4, writeGeometry, feature); +} + +function writeProperties (context, pbf) { + var feature = context.feature; + var keys = context.keys; + var values = context.values; + var keycache = context.keycache; + var valuecache = context.valuecache; + + for (var key in feature.properties) { + var value = feature.properties[key]; + + var keyIndex = keycache[key]; + if (value === null) continue // don't encode null value properties + + if (typeof keyIndex === 'undefined') { + keys.push(key); + keyIndex = keys.length - 1; + keycache[key] = keyIndex; + } + pbf.writeVarint(keyIndex); + + var type = typeof value; + if (type !== 'string' && type !== 'boolean' && type !== 'number') { + value = JSON.stringify(value); + } + var valueKey = type + ':' + value; + var valueIndex = valuecache[valueKey]; + if (typeof valueIndex === 'undefined') { + values.push(value); + valueIndex = values.length - 1; + valuecache[valueKey] = valueIndex; + } + pbf.writeVarint(valueIndex); + } +} + +function command (cmd, length) { + return (length << 3) + (cmd & 0x7) +} + +function zigzag (num) { + return (num << 1) ^ (num >> 31) +} + +function writeGeometry (feature, pbf) { + var geometry = feature.loadGeometry(); + var type = feature.type; + var x = 0; + var y = 0; + var rings = geometry.length; + for (var r = 0; r < rings; r++) { + var ring = geometry[r]; + var count = 1; + if (type === 1) { + count = ring.length; + } + pbf.writeVarint(command(1, count)); // moveto + // do not write polygon closing path as lineto + var lineCount = type === 3 ? ring.length - 1 : ring.length; + for (var i = 0; i < lineCount; i++) { + if (i === 1 && type !== 1) { + pbf.writeVarint(command(2, lineCount - 1)); // lineto + } + var dx = ring[i].x - x; + var dy = ring[i].y - y; + pbf.writeVarint(zigzag(dx)); + pbf.writeVarint(zigzag(dy)); + x += dx; + y += dy; + } + if (type === 3) { + pbf.writeVarint(command(7, 1)); // closepath + } + } +} + +function writeValue (value, pbf) { + var type = typeof value; + if (type === 'string') { + pbf.writeStringField(1, value); + } else if (type === 'boolean') { + pbf.writeBooleanField(7, value); + } else if (type === 'number') { + if (value % 1 !== 0) { + pbf.writeDoubleField(3, value); + } else if (value < 0) { + pbf.writeSVarintField(6, value); + } else { + pbf.writeVarintField(5, value); + } + } +} + +var vtPbfExports = vtPbf.exports; +var vtpbf = /*@__PURE__*/performance.by(vtPbfExports); + +const defaultOptions$1 = { + minZoom: 0, // min zoom to generate clusters on + maxZoom: 16, // max zoom level to cluster the points on + minPoints: 2, // minimum points to form a cluster + radius: 40, // cluster radius in pixels + extent: 512, // tile extent (radius is calculated relative to it) + nodeSize: 64, // size of the KD-tree leaf node, affects performance + log: false, // whether to log timing info + + // whether to generate numeric ids for input features (in vector tiles) + generateId: false, + + // a reduce function for calculating custom cluster properties + reduce: null, // (accumulated, props) => { accumulated.sum += props.sum; } + + // properties to use for individual points when running the reducer + map: props => props // props => ({sum: props.my_value}) +}; + +const fround = Math.fround || (tmp => ((x) => { tmp[0] = +x; return tmp[0]; }))(new Float32Array(1)); + +const OFFSET_ZOOM = 2; +const OFFSET_ID = 3; +const OFFSET_PARENT = 4; +const OFFSET_NUM = 5; +const OFFSET_PROP = 6; + +class Supercluster { + constructor(options) { + this.options = Object.assign(Object.create(defaultOptions$1), options); + this.trees = new Array(this.options.maxZoom + 1); + this.stride = this.options.reduce ? 7 : 6; + this.clusterProps = []; + } + + load(points) { + const {log, minZoom, maxZoom} = this.options; + + if (log) console.time('total time'); + + const timerId = `prepare ${ points.length } points`; + if (log) console.time(timerId); + + this.points = points; + + // generate a cluster object for each point and index input points into a KD-tree + const data = []; + + for (let i = 0; i < points.length; i++) { + const p = points[i]; + if (!p.geometry) continue; + + const [lng, lat] = p.geometry.coordinates; + const x = fround(lngX(lng)); + const y = fround(latY(lat)); + // store internal point/cluster data in flat numeric arrays for performance + data.push( + x, y, // projected point coordinates + Infinity, // the last zoom the point was processed at + i, // index of the source feature in the original input array + -1, // parent cluster id + 1 // number of points in a cluster + ); + if (this.options.reduce) data.push(0); // noop + } + let tree = this.trees[maxZoom + 1] = this._createTree(data); + + if (log) console.timeEnd(timerId); + + // cluster points on max zoom, then cluster the results on previous zoom, etc.; + // results in a cluster hierarchy across zoom levels + for (let z = maxZoom; z >= minZoom; z--) { + const now = +Date.now(); + + // create a new set of clusters for the zoom and index them with a KD-tree + tree = this.trees[z] = this._createTree(this._cluster(tree, z)); + + if (log) console.log('z%d: %d clusters in %dms', z, tree.numItems, +Date.now() - now); + } + + if (log) console.timeEnd('total time'); + + return this; + } + + getClusters(bbox, zoom) { + let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180; + const minLat = Math.max(-90, Math.min(90, bbox[1])); + let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180; + const maxLat = Math.max(-90, Math.min(90, bbox[3])); + + if (bbox[2] - bbox[0] >= 360) { + minLng = -180; + maxLng = 180; + } else if (minLng > maxLng) { + const easternHem = this.getClusters([minLng, minLat, 180, maxLat], zoom); + const westernHem = this.getClusters([-180, minLat, maxLng, maxLat], zoom); + return easternHem.concat(westernHem); + } + + const tree = this.trees[this._limitZoom(zoom)]; + const ids = tree.range(lngX(minLng), latY(maxLat), lngX(maxLng), latY(minLat)); + const data = tree.data; + const clusters = []; + for (const id of ids) { + const k = this.stride * id; + clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]); + } + return clusters; + } + + getChildren(clusterId) { + const originId = this._getOriginId(clusterId); + const originZoom = this._getOriginZoom(clusterId); + const errorMsg = 'No cluster with the specified id.'; + + const tree = this.trees[originZoom]; + if (!tree) throw new Error(errorMsg); + + const data = tree.data; + if (originId * this.stride >= data.length) throw new Error(errorMsg); + + const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1)); + const x = data[originId * this.stride]; + const y = data[originId * this.stride + 1]; + const ids = tree.within(x, y, r); + const children = []; + for (const id of ids) { + const k = id * this.stride; + if (data[k + OFFSET_PARENT] === clusterId) { + children.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]); + } + } + + if (children.length === 0) throw new Error(errorMsg); + + return children; + } + + getLeaves(clusterId, limit, offset) { + limit = limit || 10; + offset = offset || 0; + + const leaves = []; + this._appendLeaves(leaves, clusterId, limit, offset, 0); + + return leaves; + } + + getTile(z, x, y) { + const tree = this.trees[this._limitZoom(z)]; + const z2 = Math.pow(2, z); + const {extent, radius} = this.options; + const p = radius / extent; + const top = (y - p) / z2; + const bottom = (y + 1 + p) / z2; + + const tile = { + features: [] + }; + + this._addTileFeatures( + tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), + tree.data, x, y, z2, tile); + + if (x === 0) { + this._addTileFeatures( + tree.range(1 - p / z2, top, 1, bottom), + tree.data, z2, y, z2, tile); + } + if (x === z2 - 1) { + this._addTileFeatures( + tree.range(0, top, p / z2, bottom), + tree.data, -1, y, z2, tile); + } + + return tile.features.length ? tile : null; + } + + getClusterExpansionZoom(clusterId) { + let expansionZoom = this._getOriginZoom(clusterId) - 1; + while (expansionZoom <= this.options.maxZoom) { + const children = this.getChildren(clusterId); + expansionZoom++; + if (children.length !== 1) break; + clusterId = children[0].properties.cluster_id; + } + return expansionZoom; + } + + _appendLeaves(result, clusterId, limit, offset, skipped) { + const children = this.getChildren(clusterId); + + for (const child of children) { + const props = child.properties; + + if (props && props.cluster) { + if (skipped + props.point_count <= offset) { + // skip the whole cluster + skipped += props.point_count; + } else { + // enter the cluster + skipped = this._appendLeaves(result, props.cluster_id, limit, offset, skipped); + // exit the cluster + } + } else if (skipped < offset) { + // skip a single point + skipped++; + } else { + // add a single point + result.push(child); + } + if (result.length === limit) break; + } + + return skipped; + } + + _createTree(data) { + const tree = new performance.av(data.length / this.stride | 0, this.options.nodeSize, Float32Array); + for (let i = 0; i < data.length; i += this.stride) tree.add(data[i], data[i + 1]); + tree.finish(); + tree.data = data; + return tree; + } + + _addTileFeatures(ids, data, x, y, z2, tile) { + for (const i of ids) { + const k = i * this.stride; + const isCluster = data[k + OFFSET_NUM] > 1; + + let tags, px, py; + if (isCluster) { + tags = getClusterProperties(data, k, this.clusterProps); + px = data[k]; + py = data[k + 1]; + } else { + const p = this.points[data[k + OFFSET_ID]]; + tags = p.properties; + const [lng, lat] = p.geometry.coordinates; + px = lngX(lng); + py = latY(lat); + } + + const f = { + type: 1, + geometry: [[ + Math.round(this.options.extent * (px * z2 - x)), + Math.round(this.options.extent * (py * z2 - y)) + ]], + tags + }; + + // assign id + let id; + if (isCluster || this.options.generateId) { + // optionally generate id for points + id = data[k + OFFSET_ID]; + } else { + // keep id if already assigned + id = this.points[data[k + OFFSET_ID]].id; + } + + if (id !== undefined) f.id = id; + + tile.features.push(f); + } + } + + _limitZoom(z) { + return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1)); + } + + _cluster(tree, zoom) { + const {radius, extent, reduce, minPoints} = this.options; + const r = radius / (extent * Math.pow(2, zoom)); + const data = tree.data; + const nextData = []; + const stride = this.stride; + + // loop through each point + for (let i = 0; i < data.length; i += stride) { + // if we've already visited the point at this zoom level, skip it + if (data[i + OFFSET_ZOOM] <= zoom) continue; + data[i + OFFSET_ZOOM] = zoom; + + // find all nearby points + const x = data[i]; + const y = data[i + 1]; + const neighborIds = tree.within(data[i], data[i + 1], r); + + const numPointsOrigin = data[i + OFFSET_NUM]; + let numPoints = numPointsOrigin; + + // count the number of points in a potential cluster + for (const neighborId of neighborIds) { + const k = neighborId * stride; + // filter out neighbors that are already processed + if (data[k + OFFSET_ZOOM] > zoom) numPoints += data[k + OFFSET_NUM]; + } + + // if there were neighbors to merge, and there are enough points to form a cluster + if (numPoints > numPointsOrigin && numPoints >= minPoints) { + let wx = x * numPointsOrigin; + let wy = y * numPointsOrigin; + + let clusterProperties; + let clusterPropIndex = -1; + + // encode both zoom and point index on which the cluster originated -- offset by total length of features + const id = ((i / stride | 0) << 5) + (zoom + 1) + this.points.length; + + for (const neighborId of neighborIds) { + const k = neighborId * stride; + + if (data[k + OFFSET_ZOOM] <= zoom) continue; + data[k + OFFSET_ZOOM] = zoom; // save the zoom (so it doesn't get processed twice) + + const numPoints2 = data[k + OFFSET_NUM]; + wx += data[k] * numPoints2; // accumulate coordinates for calculating weighted center + wy += data[k + 1] * numPoints2; + + data[k + OFFSET_PARENT] = id; + + if (reduce) { + if (!clusterProperties) { + clusterProperties = this._map(data, i, true); + clusterPropIndex = this.clusterProps.length; + this.clusterProps.push(clusterProperties); + } + reduce(clusterProperties, this._map(data, k)); + } + } + + data[i + OFFSET_PARENT] = id; + nextData.push(wx / numPoints, wy / numPoints, Infinity, id, -1, numPoints); + if (reduce) nextData.push(clusterPropIndex); + + } else { // left points as unclustered + for (let j = 0; j < stride; j++) nextData.push(data[i + j]); + + if (numPoints > 1) { + for (const neighborId of neighborIds) { + const k = neighborId * stride; + if (data[k + OFFSET_ZOOM] <= zoom) continue; + data[k + OFFSET_ZOOM] = zoom; + for (let j = 0; j < stride; j++) nextData.push(data[k + j]); + } + } + } + } + + return nextData; + } + + // get index of the point from which the cluster originated + _getOriginId(clusterId) { + return (clusterId - this.points.length) >> 5; + } + + // get zoom of the point from which the cluster originated + _getOriginZoom(clusterId) { + return (clusterId - this.points.length) % 32; + } + + _map(data, i, clone) { + if (data[i + OFFSET_NUM] > 1) { + const props = this.clusterProps[data[i + OFFSET_PROP]]; + return clone ? Object.assign({}, props) : props; + } + const original = this.points[data[i + OFFSET_ID]].properties; + const result = this.options.map(original); + return clone && result === original ? Object.assign({}, result) : result; + } +} + +function getClusterJSON(data, i, clusterProps) { + return { + type: 'Feature', + id: data[i + OFFSET_ID], + properties: getClusterProperties(data, i, clusterProps), + geometry: { + type: 'Point', + coordinates: [xLng(data[i]), yLat(data[i + 1])] + } + }; +} + +function getClusterProperties(data, i, clusterProps) { + const count = data[i + OFFSET_NUM]; + const abbrev = + count >= 10000 ? `${Math.round(count / 1000) }k` : + count >= 1000 ? `${Math.round(count / 100) / 10 }k` : count; + const propIndex = data[i + OFFSET_PROP]; + const properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]); + return Object.assign(properties, { + cluster: true, + cluster_id: data[i + OFFSET_ID], + point_count: count, + point_count_abbreviated: abbrev + }); +} + +// longitude/latitude to spherical mercator in [0..1] range +function lngX(lng) { + return lng / 360 + 0.5; +} +function latY(lat) { + const sin = Math.sin(lat * Math.PI / 180); + const y = (0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI); + return y < 0 ? 0 : y > 1 ? 1 : y; +} + +// spherical mercator to longitude/latitude +function xLng(x) { + return (x - 0.5) * 360; +} +function yLat(y) { + const y2 = (180 - y * 360) * Math.PI / 180; + return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90; +} + +// calculate simplification data using optimized Douglas-Peucker algorithm + +function simplify(coords, first, last, sqTolerance) { + let maxSqDist = sqTolerance; + const mid = first + ((last - first) >> 1); + let minPosToMid = last - first; + let index; + + const ax = coords[first]; + const ay = coords[first + 1]; + const bx = coords[last]; + const by = coords[last + 1]; + + for (let i = first + 3; i < last; i += 3) { + const d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by); + + if (d > maxSqDist) { + index = i; + maxSqDist = d; + + } else if (d === maxSqDist) { + // a workaround to ensure we choose a pivot close to the middle of the list, + // reducing recursion depth, for certain degenerate inputs + // https://github.com/mapbox/geojson-vt/issues/104 + const posToMid = Math.abs(i - mid); + if (posToMid < minPosToMid) { + index = i; + minPosToMid = posToMid; + } + } + } + + if (maxSqDist > sqTolerance) { + if (index - first > 3) simplify(coords, first, index, sqTolerance); + coords[index + 2] = maxSqDist; + if (last - index > 3) simplify(coords, index, last, sqTolerance); + } +} + +// square distance from a point to a segment +function getSqSegDist(px, py, x, y, bx, by) { + + let dx = bx - x; + let dy = by - y; + + if (dx !== 0 || dy !== 0) { + + const t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy); + + if (t > 1) { + x = bx; + y = by; + + } else if (t > 0) { + x += dx * t; + y += dy * t; + } + } + + dx = px - x; + dy = py - y; + + return dx * dx + dy * dy; +} + +function createFeature(id, type, geom, tags) { + const feature = { + id: id == null ? null : id, + type, + geometry: geom, + tags, + minX: Infinity, + minY: Infinity, + maxX: -Infinity, + maxY: -Infinity + }; + + if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') { + calcLineBBox(feature, geom); + + } else if (type === 'Polygon') { + // the outer ring (ie [0]) contains all inner rings + calcLineBBox(feature, geom[0]); + + } else if (type === 'MultiLineString') { + for (const line of geom) { + calcLineBBox(feature, line); + } + + } else if (type === 'MultiPolygon') { + for (const polygon of geom) { + // the outer ring (ie [0]) contains all inner rings + calcLineBBox(feature, polygon[0]); + } + } + + return feature; +} + +function calcLineBBox(feature, geom) { + for (let i = 0; i < geom.length; i += 3) { + feature.minX = Math.min(feature.minX, geom[i]); + feature.minY = Math.min(feature.minY, geom[i + 1]); + feature.maxX = Math.max(feature.maxX, geom[i]); + feature.maxY = Math.max(feature.maxY, geom[i + 1]); + } +} + +// converts GeoJSON feature into an intermediate projected JSON vector format with simplification data + +function convert(data, options) { + const features = []; + if (data.type === 'FeatureCollection') { + for (let i = 0; i < data.features.length; i++) { + convertFeature(features, data.features[i], options, i); + } + + } else if (data.type === 'Feature') { + convertFeature(features, data, options); + + } else { + // single geometry or a geometry collection + convertFeature(features, {geometry: data}, options); + } + + return features; +} + +function convertFeature(features, geojson, options, index) { + if (!geojson.geometry) return; + + const coords = geojson.geometry.coordinates; + if (coords && coords.length === 0) return; + + const type = geojson.geometry.type; + const tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2); + let geometry = []; + let id = geojson.id; + if (options.promoteId) { + id = geojson.properties[options.promoteId]; + } else if (options.generateId) { + id = index || 0; + } + if (type === 'Point') { + convertPoint(coords, geometry); + + } else if (type === 'MultiPoint') { + for (const p of coords) { + convertPoint(p, geometry); + } + + } else if (type === 'LineString') { + convertLine(coords, geometry, tolerance, false); + + } else if (type === 'MultiLineString') { + if (options.lineMetrics) { + // explode into linestrings to be able to track metrics + for (const line of coords) { + geometry = []; + convertLine(line, geometry, tolerance, false); + features.push(createFeature(id, 'LineString', geometry, geojson.properties)); + } + return; + } else { + convertLines(coords, geometry, tolerance, false); + } + + } else if (type === 'Polygon') { + convertLines(coords, geometry, tolerance, true); + + } else if (type === 'MultiPolygon') { + for (const polygon of coords) { + const newPolygon = []; + convertLines(polygon, newPolygon, tolerance, true); + geometry.push(newPolygon); + } + } else if (type === 'GeometryCollection') { + for (const singleGeometry of geojson.geometry.geometries) { + convertFeature(features, { + id, + geometry: singleGeometry, + properties: geojson.properties + }, options, index); + } + return; + } else { + throw new Error('Input data is not a valid GeoJSON object.'); + } + + features.push(createFeature(id, type, geometry, geojson.properties)); +} + +function convertPoint(coords, out) { + out.push(projectX(coords[0]), projectY(coords[1]), 0); +} + +function convertLine(ring, out, tolerance, isPolygon) { + let x0, y0; + let size = 0; + + for (let j = 0; j < ring.length; j++) { + const x = projectX(ring[j][0]); + const y = projectY(ring[j][1]); + + out.push(x, y, 0); + + if (j > 0) { + if (isPolygon) { + size += (x0 * y - x * y0) / 2; // area + } else { + size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)); // length + } + } + x0 = x; + y0 = y; + } + + const last = out.length - 3; + out[2] = 1; + simplify(out, 0, last, tolerance); + out[last + 2] = 1; + + out.size = Math.abs(size); + out.start = 0; + out.end = out.size; +} + +function convertLines(rings, out, tolerance, isPolygon) { + for (let i = 0; i < rings.length; i++) { + const geom = []; + convertLine(rings[i], geom, tolerance, isPolygon); + out.push(geom); + } +} + +function projectX(x) { + return x / 360 + 0.5; +} + +function projectY(y) { + const sin = Math.sin(y * Math.PI / 180); + const y2 = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI; + return y2 < 0 ? 0 : y2 > 1 ? 1 : y2; +} + +/* clip features between two vertical or horizontal axis-parallel lines: + * | | + * ___|___ | / + * / | \____|____/ + * | | + * + * k1 and k2 are the line coordinates + * axis: 0 for x, 1 for y + * minAll and maxAll: minimum and maximum coordinate value for all features + */ +function clip(features, scale, k1, k2, axis, minAll, maxAll, options) { + k1 /= scale; + k2 /= scale; + + if (minAll >= k1 && maxAll < k2) return features; // trivial accept + else if (maxAll < k1 || minAll >= k2) return null; // trivial reject + + const clipped = []; + + for (const feature of features) { + const geometry = feature.geometry; + let type = feature.type; + + const min = axis === 0 ? feature.minX : feature.minY; + const max = axis === 0 ? feature.maxX : feature.maxY; + + if (min >= k1 && max < k2) { // trivial accept + clipped.push(feature); + continue; + } else if (max < k1 || min >= k2) { // trivial reject + continue; + } + + let newGeometry = []; + + if (type === 'Point' || type === 'MultiPoint') { + clipPoints(geometry, newGeometry, k1, k2, axis); + + } else if (type === 'LineString') { + clipLine(geometry, newGeometry, k1, k2, axis, false, options.lineMetrics); + + } else if (type === 'MultiLineString') { + clipLines(geometry, newGeometry, k1, k2, axis, false); + + } else if (type === 'Polygon') { + clipLines(geometry, newGeometry, k1, k2, axis, true); + + } else if (type === 'MultiPolygon') { + for (const polygon of geometry) { + const newPolygon = []; + clipLines(polygon, newPolygon, k1, k2, axis, true); + if (newPolygon.length) { + newGeometry.push(newPolygon); + } + } + } + + if (newGeometry.length) { + if (options.lineMetrics && type === 'LineString') { + for (const line of newGeometry) { + clipped.push(createFeature(feature.id, type, line, feature.tags)); + } + continue; + } + + if (type === 'LineString' || type === 'MultiLineString') { + if (newGeometry.length === 1) { + type = 'LineString'; + newGeometry = newGeometry[0]; + } else { + type = 'MultiLineString'; + } + } + if (type === 'Point' || type === 'MultiPoint') { + type = newGeometry.length === 3 ? 'Point' : 'MultiPoint'; + } + + clipped.push(createFeature(feature.id, type, newGeometry, feature.tags)); + } + } + + return clipped.length ? clipped : null; +} + +function clipPoints(geom, newGeom, k1, k2, axis) { + for (let i = 0; i < geom.length; i += 3) { + const a = geom[i + axis]; + + if (a >= k1 && a <= k2) { + addPoint(newGeom, geom[i], geom[i + 1], geom[i + 2]); + } + } +} + +function clipLine(geom, newGeom, k1, k2, axis, isPolygon, trackMetrics) { + + let slice = newSlice(geom); + const intersect = axis === 0 ? intersectX : intersectY; + let len = geom.start; + let segLen, t; + + for (let i = 0; i < geom.length - 3; i += 3) { + const ax = geom[i]; + const ay = geom[i + 1]; + const az = geom[i + 2]; + const bx = geom[i + 3]; + const by = geom[i + 4]; + const a = axis === 0 ? ax : ay; + const b = axis === 0 ? bx : by; + let exited = false; + + if (trackMetrics) segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2)); + + if (a < k1) { + // ---|--> | (line enters the clip region from the left) + if (b > k1) { + t = intersect(slice, ax, ay, bx, by, k1); + if (trackMetrics) slice.start = len + segLen * t; + } + } else if (a > k2) { + // | <--|--- (line enters the clip region from the right) + if (b < k2) { + t = intersect(slice, ax, ay, bx, by, k2); + if (trackMetrics) slice.start = len + segLen * t; + } + } else { + addPoint(slice, ax, ay, az); + } + if (b < k1 && a >= k1) { + // <--|--- | or <--|-----|--- (line exits the clip region on the left) + t = intersect(slice, ax, ay, bx, by, k1); + exited = true; + } + if (b > k2 && a <= k2) { + // | ---|--> or ---|-----|--> (line exits the clip region on the right) + t = intersect(slice, ax, ay, bx, by, k2); + exited = true; + } + + if (!isPolygon && exited) { + if (trackMetrics) slice.end = len + segLen * t; + newGeom.push(slice); + slice = newSlice(geom); + } + + if (trackMetrics) len += segLen; + } + + // add the last point + let last = geom.length - 3; + const ax = geom[last]; + const ay = geom[last + 1]; + const az = geom[last + 2]; + const a = axis === 0 ? ax : ay; + if (a >= k1 && a <= k2) addPoint(slice, ax, ay, az); + + // close the polygon if its endpoints are not the same after clipping + last = slice.length - 3; + if (isPolygon && last >= 3 && (slice[last] !== slice[0] || slice[last + 1] !== slice[1])) { + addPoint(slice, slice[0], slice[1], slice[2]); + } + + // add the final slice + if (slice.length) { + newGeom.push(slice); + } +} + +function newSlice(line) { + const slice = []; + slice.size = line.size; + slice.start = line.start; + slice.end = line.end; + return slice; +} + +function clipLines(geom, newGeom, k1, k2, axis, isPolygon) { + for (const line of geom) { + clipLine(line, newGeom, k1, k2, axis, isPolygon, false); + } +} + +function addPoint(out, x, y, z) { + out.push(x, y, z); +} + +function intersectX(out, ax, ay, bx, by, x) { + const t = (x - ax) / (bx - ax); + addPoint(out, x, ay + (by - ay) * t, 1); + return t; +} + +function intersectY(out, ax, ay, bx, by, y) { + const t = (y - ay) / (by - ay); + addPoint(out, ax + (bx - ax) * t, y, 1); + return t; +} + +function wrap(features, options) { + const buffer = options.buffer / options.extent; + let merged = features; + const left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options); // left world copy + const right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2, options); // right world copy + + if (left || right) { + merged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2, options) || []; // center world copy + + if (left) merged = shiftFeatureCoords(left, 1).concat(merged); // merge left into center + if (right) merged = merged.concat(shiftFeatureCoords(right, -1)); // merge right into center + } + + return merged; +} + +function shiftFeatureCoords(features, offset) { + const newFeatures = []; + + for (let i = 0; i < features.length; i++) { + const feature = features[i]; + const type = feature.type; + + let newGeometry; + + if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') { + newGeometry = shiftCoords(feature.geometry, offset); + + } else if (type === 'MultiLineString' || type === 'Polygon') { + newGeometry = []; + for (const line of feature.geometry) { + newGeometry.push(shiftCoords(line, offset)); + } + } else if (type === 'MultiPolygon') { + newGeometry = []; + for (const polygon of feature.geometry) { + const newPolygon = []; + for (const line of polygon) { + newPolygon.push(shiftCoords(line, offset)); + } + newGeometry.push(newPolygon); + } + } + + newFeatures.push(createFeature(feature.id, type, newGeometry, feature.tags)); + } + + return newFeatures; +} + +function shiftCoords(points, offset) { + const newPoints = []; + newPoints.size = points.size; + + if (points.start !== undefined) { + newPoints.start = points.start; + newPoints.end = points.end; + } + + for (let i = 0; i < points.length; i += 3) { + newPoints.push(points[i] + offset, points[i + 1], points[i + 2]); + } + return newPoints; +} + +// Transforms the coordinates of each feature in the given tile from +// mercator-projected space into (extent x extent) tile space. +function transformTile(tile, extent) { + if (tile.transformed) return tile; + + const z2 = 1 << tile.z; + const tx = tile.x; + const ty = tile.y; + + for (const feature of tile.features) { + const geom = feature.geometry; + const type = feature.type; + + feature.geometry = []; + + if (type === 1) { + for (let j = 0; j < geom.length; j += 2) { + feature.geometry.push(transformPoint(geom[j], geom[j + 1], extent, z2, tx, ty)); + } + } else { + for (let j = 0; j < geom.length; j++) { + const ring = []; + for (let k = 0; k < geom[j].length; k += 2) { + ring.push(transformPoint(geom[j][k], geom[j][k + 1], extent, z2, tx, ty)); + } + feature.geometry.push(ring); + } + } + } + + tile.transformed = true; + + return tile; +} + +function transformPoint(x, y, extent, z2, tx, ty) { + return [ + Math.round(extent * (x * z2 - tx)), + Math.round(extent * (y * z2 - ty))]; +} + +function createTile(features, z, tx, ty, options) { + const tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent); + const tile = { + features: [], + numPoints: 0, + numSimplified: 0, + numFeatures: features.length, + source: null, + x: tx, + y: ty, + z, + transformed: false, + minX: 2, + minY: 1, + maxX: -1, + maxY: 0 + }; + for (const feature of features) { + addFeature(tile, feature, tolerance, options); + } + return tile; +} + +function addFeature(tile, feature, tolerance, options) { + const geom = feature.geometry; + const type = feature.type; + const simplified = []; + + tile.minX = Math.min(tile.minX, feature.minX); + tile.minY = Math.min(tile.minY, feature.minY); + tile.maxX = Math.max(tile.maxX, feature.maxX); + tile.maxY = Math.max(tile.maxY, feature.maxY); + + if (type === 'Point' || type === 'MultiPoint') { + for (let i = 0; i < geom.length; i += 3) { + simplified.push(geom[i], geom[i + 1]); + tile.numPoints++; + tile.numSimplified++; + } + + } else if (type === 'LineString') { + addLine(simplified, geom, tile, tolerance, false, false); + + } else if (type === 'MultiLineString' || type === 'Polygon') { + for (let i = 0; i < geom.length; i++) { + addLine(simplified, geom[i], tile, tolerance, type === 'Polygon', i === 0); + } + + } else if (type === 'MultiPolygon') { + + for (let k = 0; k < geom.length; k++) { + const polygon = geom[k]; + for (let i = 0; i < polygon.length; i++) { + addLine(simplified, polygon[i], tile, tolerance, true, i === 0); + } + } + } + + if (simplified.length) { + let tags = feature.tags || null; + + if (type === 'LineString' && options.lineMetrics) { + tags = {}; + for (const key in feature.tags) tags[key] = feature.tags[key]; + tags['mapbox_clip_start'] = geom.start / geom.size; + tags['mapbox_clip_end'] = geom.end / geom.size; + } + + const tileFeature = { + geometry: simplified, + type: type === 'Polygon' || type === 'MultiPolygon' ? 3 : + (type === 'LineString' || type === 'MultiLineString' ? 2 : 1), + tags + }; + if (feature.id !== null) { + tileFeature.id = feature.id; + } + tile.features.push(tileFeature); + } +} + +function addLine(result, geom, tile, tolerance, isPolygon, isOuter) { + const sqTolerance = tolerance * tolerance; + + if (tolerance > 0 && (geom.size < (isPolygon ? sqTolerance : tolerance))) { + tile.numPoints += geom.length / 3; + return; + } + + const ring = []; + + for (let i = 0; i < geom.length; i += 3) { + if (tolerance === 0 || geom[i + 2] > sqTolerance) { + tile.numSimplified++; + ring.push(geom[i], geom[i + 1]); + } + tile.numPoints++; + } + + if (isPolygon) rewind(ring, isOuter); + + result.push(ring); +} + +function rewind(ring, clockwise) { + let area = 0; + for (let i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) { + area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]); + } + if (area > 0 === clockwise) { + for (let i = 0, len = ring.length; i < len / 2; i += 2) { + const x = ring[i]; + const y = ring[i + 1]; + ring[i] = ring[len - 2 - i]; + ring[i + 1] = ring[len - 1 - i]; + ring[len - 2 - i] = x; + ring[len - 1 - i] = y; + } + } +} + +const defaultOptions = { + maxZoom: 14, // max zoom to preserve detail on + indexMaxZoom: 5, // max zoom in the tile index + indexMaxPoints: 100000, // max number of points per tile in the tile index + tolerance: 3, // simplification tolerance (higher means simpler) + extent: 4096, // tile extent + buffer: 64, // tile buffer on each side + lineMetrics: false, // whether to calculate line metrics + promoteId: null, // name of a feature property to be promoted to feature.id + generateId: false, // whether to generate feature ids. Cannot be used with promoteId + debug: 0 // logging level (0, 1 or 2) +}; + +class GeoJSONVT { + constructor(data, options) { + options = this.options = extend(Object.create(defaultOptions), options); + + const debug = options.debug; + + if (debug) console.time('preprocess data'); + + if (options.maxZoom < 0 || options.maxZoom > 24) throw new Error('maxZoom should be in the 0-24 range'); + if (options.promoteId && options.generateId) throw new Error('promoteId and generateId cannot be used together.'); + + // projects and adds simplification info + let features = convert(data, options); + + // tiles and tileCoords are part of the public API + this.tiles = {}; + this.tileCoords = []; + + if (debug) { + console.timeEnd('preprocess data'); + console.log('index: maxZoom: %d, maxPoints: %d', options.indexMaxZoom, options.indexMaxPoints); + console.time('generate tiles'); + this.stats = {}; + this.total = 0; + } + + // wraps features (ie extreme west and extreme east) + features = wrap(features, options); + + // start slicing from the top tile down + if (features.length) this.splitTile(features, 0, 0, 0); + + if (debug) { + if (features.length) console.log('features: %d, points: %d', this.tiles[0].numFeatures, this.tiles[0].numPoints); + console.timeEnd('generate tiles'); + console.log('tiles generated:', this.total, JSON.stringify(this.stats)); + } + } + + // splits features from a parent tile to sub-tiles. + // z, x, and y are the coordinates of the parent tile + // cz, cx, and cy are the coordinates of the target tile + // + // If no target tile is specified, splitting stops when we reach the maximum + // zoom or the number of points is low as specified in the options. + splitTile(features, z, x, y, cz, cx, cy) { + + const stack = [features, z, x, y]; + const options = this.options; + const debug = options.debug; + + // avoid recursion by using a processing queue + while (stack.length) { + y = stack.pop(); + x = stack.pop(); + z = stack.pop(); + features = stack.pop(); + + const z2 = 1 << z; + const id = toID(z, x, y); + let tile = this.tiles[id]; + + if (!tile) { + if (debug > 1) console.time('creation'); + + tile = this.tiles[id] = createTile(features, z, x, y, options); + this.tileCoords.push({z, x, y}); + + if (debug) { + if (debug > 1) { + console.log('tile z%d-%d-%d (features: %d, points: %d, simplified: %d)', + z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified); + console.timeEnd('creation'); + } + const key = `z${ z}`; + this.stats[key] = (this.stats[key] || 0) + 1; + this.total++; + } + } + + // save reference to original geometry in tile so that we can drill down later if we stop now + tile.source = features; + + // if it's the first-pass tiling + if (cz == null) { + // stop tiling if we reached max zoom, or if the tile is too simple + if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints) continue; + // if a drilldown to a specific tile + } else if (z === options.maxZoom || z === cz) { + // stop tiling if we reached base zoom or our target tile zoom + continue; + } else if (cz != null) { + // stop tiling if it's not an ancestor of the target tile + const zoomSteps = cz - z; + if (x !== cx >> zoomSteps || y !== cy >> zoomSteps) continue; + } + + // if we slice further down, no need to keep source geometry + tile.source = null; + + if (features.length === 0) continue; + + if (debug > 1) console.time('clipping'); + + // values we'll use for clipping + const k1 = 0.5 * options.buffer / options.extent; + const k2 = 0.5 - k1; + const k3 = 0.5 + k1; + const k4 = 1 + k1; + + let tl = null; + let bl = null; + let tr = null; + let br = null; + + let left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options); + let right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX, options); + features = null; + + if (left) { + tl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options); + bl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options); + left = null; + } + + if (right) { + tr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options); + br = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options); + right = null; + } + + if (debug > 1) console.timeEnd('clipping'); + + stack.push(tl || [], z + 1, x * 2, y * 2); + stack.push(bl || [], z + 1, x * 2, y * 2 + 1); + stack.push(tr || [], z + 1, x * 2 + 1, y * 2); + stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1); + } + } + + getTile(z, x, y) { + z = +z; + x = +x; + y = +y; + + const options = this.options; + const {extent, debug} = options; + + if (z < 0 || z > 24) return null; + + const z2 = 1 << z; + x = (x + z2) & (z2 - 1); // wrap tile x coordinate + + const id = toID(z, x, y); + if (this.tiles[id]) return transformTile(this.tiles[id], extent); + + if (debug > 1) console.log('drilling down to z%d-%d-%d', z, x, y); + + let z0 = z; + let x0 = x; + let y0 = y; + let parent; + + while (!parent && z0 > 0) { + z0--; + x0 = x0 >> 1; + y0 = y0 >> 1; + parent = this.tiles[toID(z0, x0, y0)]; + } + + if (!parent || !parent.source) return null; + + // if we found a parent tile containing the original geometry, we can drill down from it + if (debug > 1) { + console.log('found parent tile z%d-%d-%d', z0, x0, y0); + console.time('drilling down'); + } + this.splitTile(parent.source, z0, x0, y0, z, x, y); + if (debug > 1) console.timeEnd('drilling down'); + + return this.tiles[id] ? transformTile(this.tiles[id], extent) : null; + } +} + +function toID(z, x, y) { + return (((1 << z) * y + x) * 32) + z; +} + +function extend(dest, src) { + for (const i in src) dest[i] = src[i]; + return dest; +} + +function geojsonvt(data, options) { + return new GeoJSONVT(data, options); +} + +function getFeatureId(feature, promoteId) { + return promoteId ? feature.properties[promoteId] : feature.id; +} +function isUpdateableGeoJSON(data, promoteId) { + // null can be updated + if (data == null) { + return true; + } + // a single feature with an id can be updated, need to explicitly check against null because 0 is a valid feature id that is falsy + if (data.type === 'Feature') { + return getFeatureId(data, promoteId) != null; + } + // a feature collection can be updated if every feature has an id, and the ids are all unique + // this prevents us from silently dropping features if ids get reused + if (data.type === 'FeatureCollection') { + const seenIds = new Set(); + for (const feature of data.features) { + const id = getFeatureId(feature, promoteId); + if (id == null) { + return false; + } + if (seenIds.has(id)) { + return false; + } + seenIds.add(id); + } + return true; + } + return false; +} +function toUpdateable(data, promoteId) { + const result = new Map(); + if (data == null) ; + else if (data.type === 'Feature') { + result.set(getFeatureId(data, promoteId), data); + } + else { + for (const feature of data.features) { + result.set(getFeatureId(feature, promoteId), feature); + } + } + return result; +} +// mutates updateable +function applySourceDiff(updateable, diff, promoteId) { + var _a, _b, _c, _d; + if (diff.removeAll) { + updateable.clear(); + } + if (diff.remove) { + for (const id of diff.remove) { + updateable.delete(id); + } + } + if (diff.add) { + for (const feature of diff.add) { + const id = getFeatureId(feature, promoteId); + if (id != null) { + updateable.set(id, feature); + } + } + } + if (diff.update) { + for (const update of diff.update) { + let feature = updateable.get(update.id); + if (feature == null) { + continue; + } + // be careful to clone the feature and/or properties objects to avoid mutating our input + const cloneFeature = update.newGeometry || update.removeAllProperties; + // note: removeAllProperties gives us a new properties object, so we can skip the clone step + const cloneProperties = !update.removeAllProperties && (((_a = update.removeProperties) === null || _a === void 0 ? void 0 : _a.length) > 0 || ((_b = update.addOrUpdateProperties) === null || _b === void 0 ? void 0 : _b.length) > 0); + if (cloneFeature || cloneProperties) { + feature = Object.assign({}, feature); + updateable.set(update.id, feature); + if (cloneProperties) { + feature.properties = Object.assign({}, feature.properties); + } + } + if (update.newGeometry) { + feature.geometry = update.newGeometry; + } + if (update.removeAllProperties) { + feature.properties = {}; + } + else if (((_c = update.removeProperties) === null || _c === void 0 ? void 0 : _c.length) > 0) { + for (const prop of update.removeProperties) { + if (Object.prototype.hasOwnProperty.call(feature.properties, prop)) { + delete feature.properties[prop]; + } + } + } + if (((_d = update.addOrUpdateProperties) === null || _d === void 0 ? void 0 : _d.length) > 0) { + for (const { key, value } of update.addOrUpdateProperties) { + feature.properties[key] = value; + } + } + } + } +} + +/** + * The {@link WorkerSource} implementation that supports {@link GeoJSONSource}. + * This class is designed to be easily reused to support custom source types + * for data formats that can be parsed/converted into an in-memory GeoJSON + * representation. To do so, create it with + * `new GeoJSONWorkerSource(actor, layerIndex, customLoadGeoJSONFunction)`. + * For a full example, see [mapbox-gl-topojson](https://github.com/developmentseed/mapbox-gl-topojson). + */ +class GeoJSONWorkerSource extends VectorTileWorkerSource { + constructor() { + super(...arguments); + this._dataUpdateable = new Map(); + } + loadVectorTile(params, _abortController) { + return performance._(this, void 0, void 0, function* () { + const canonical = params.tileID.canonical; + if (!this._geoJSONIndex) { + throw new Error('Unable to parse the data into a cluster or geojson'); + } + const geoJSONTile = this._geoJSONIndex.getTile(canonical.z, canonical.x, canonical.y); + if (!geoJSONTile) { + return null; + } + const geojsonWrapper = new GeoJSONWrapper$2(geoJSONTile.features); + // Encode the geojson-vt tile into binary vector tile form. This + // is a convenience that allows `FeatureIndex` to operate the same way + // across `VectorTileSource` and `GeoJSONSource` data. + let pbf = vtpbf(geojsonWrapper); + if (pbf.byteOffset !== 0 || pbf.byteLength !== pbf.buffer.byteLength) { + // Compatibility with node Buffer (https://github.com/mapbox/pbf/issues/35) + pbf = new Uint8Array(pbf); + } + return { + vectorTile: geojsonWrapper, + rawData: pbf.buffer + }; + }); + } + /** + * Fetches (if appropriate), parses, and index geojson data into tiles. This + * preparatory method must be called before {@link GeoJSONWorkerSource#loadTile} + * can correctly serve up tiles. + * + * Defers to {@link GeoJSONWorkerSource#loadAndProcessGeoJSON} for the pre-processing. + * + * When a `loadData` request comes in while a previous one is being processed, + * the previous one is aborted. + * + * @param params - the parameters + * @returns a promise that resolves when the data is loaded and parsed into a GeoJSON object + */ + loadData(params) { + return performance._(this, void 0, void 0, function* () { + var _a; + (_a = this._pendingRequest) === null || _a === void 0 ? void 0 : _a.abort(); + const perf = (params && params.request && params.request.collectResourceTiming) ? + new performance.bv(params.request) : false; + this._pendingRequest = new AbortController(); + try { + this._pendingData = this.loadAndProcessGeoJSON(params, this._pendingRequest); + this._geoJSONIndex = params.cluster ? + new Supercluster(getSuperclusterOptions(params)).load((yield this._pendingData).features) : + geojsonvt(yield this._pendingData, params.geojsonVtOptions); + this.loaded = {}; + const result = {}; + if (perf) { + const resourceTimingData = perf.finish(); + // it's necessary to eval the result of getEntriesByName() here via parse/stringify + // late evaluation in the main thread causes TypeError: illegal invocation + if (resourceTimingData) { + result.resourceTiming = {}; + result.resourceTiming[params.source] = JSON.parse(JSON.stringify(resourceTimingData)); + } + } + return result; + } + catch (err) { + delete this._pendingRequest; + if (performance.bB(err)) { + return { abandoned: true }; + } + throw err; + } + }); + } + /** + * Allows to get the source's actual GeoJSON. + * + * @returns a promise which is resolved with the source's actual GeoJSON + */ + getData() { + return performance._(this, void 0, void 0, function* () { + return this._pendingData; + }); + } + /** + * Implements {@link WorkerSource#reloadTile}. + * + * If the tile is loaded, uses the implementation in VectorTileWorkerSource. + * Otherwise, such as after a setData() call, we load the tile fresh. + * + * @param params - the parameters + * @returns A promise that resolves when the tile is reloaded + */ + reloadTile(params) { + const loaded = this.loaded, uid = params.uid; + if (loaded && loaded[uid]) { + return super.reloadTile(params); + } + else { + return this.loadTile(params); + } + } + /** + * Fetch, parse and process GeoJSON according to the given params. + * + * Defers to {@link GeoJSONWorkerSource#loadGeoJSON} for the fetching and parsing. + * + * @param params - the parameters + * @param abortController - the abort controller that allows aborting this operation + * @returns a promise that is resolved with the processes GeoJSON + */ + loadAndProcessGeoJSON(params, abortController) { + return performance._(this, void 0, void 0, function* () { + let data = yield this.loadGeoJSON(params, abortController); + delete this._pendingRequest; + if (typeof data !== 'object') { + throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`); + } + rewind$2(data, true); + if (params.filter) { + const compiled = performance.bC(params.filter, { type: 'boolean', 'property-type': 'data-driven', overridable: false, transition: false }); + if (compiled.result === 'error') + throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', ')); + const features = data.features.filter(feature => compiled.value.evaluate({ zoom: 0 }, feature)); + data = { type: 'FeatureCollection', features }; + } + return data; + }); + } + /** + * Fetch and parse GeoJSON according to the given params. + * + * GeoJSON is loaded and parsed from `params.url` if it exists, or else + * expected as a literal (string or object) `params.data`. + * + * @param params - the parameters + * @param abortController - the abort controller that allows aborting this operation + * @returns a promise that resolves when the data is loaded + */ + loadGeoJSON(params, abortController) { + return performance._(this, void 0, void 0, function* () { + const { promoteId } = params; + if (params.request) { + const response = yield performance.h(params.request, abortController); + this._dataUpdateable = isUpdateableGeoJSON(response.data, promoteId) ? toUpdateable(response.data, promoteId) : undefined; + return response.data; + } + if (typeof params.data === 'string') { + try { + const parsed = JSON.parse(params.data); + this._dataUpdateable = isUpdateableGeoJSON(parsed, promoteId) ? toUpdateable(parsed, promoteId) : undefined; + return parsed; + } + catch (e) { + throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`); + } + } + if (!params.dataDiff) { + throw new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`); + } + if (!this._dataUpdateable) { + throw new Error(`Cannot update existing geojson data in ${params.source}`); + } + applySourceDiff(this._dataUpdateable, params.dataDiff, promoteId); + return { type: 'FeatureCollection', features: Array.from(this._dataUpdateable.values()) }; + }); + } + removeSource(_params) { + return performance._(this, void 0, void 0, function* () { + if (this._pendingRequest) { + this._pendingRequest.abort(); + } + }); + } + getClusterExpansionZoom(params) { + return this._geoJSONIndex.getClusterExpansionZoom(params.clusterId); + } + getClusterChildren(params) { + return this._geoJSONIndex.getChildren(params.clusterId); + } + getClusterLeaves(params) { + return this._geoJSONIndex.getLeaves(params.clusterId, params.limit, params.offset); + } +} +function getSuperclusterOptions({ superclusterOptions, clusterProperties }) { + if (!clusterProperties || !superclusterOptions) + return superclusterOptions; + const mapExpressions = {}; + const reduceExpressions = {}; + const globals = { accumulated: null, zoom: 0 }; + const feature = { properties: null }; + const propertyNames = Object.keys(clusterProperties); + for (const key of propertyNames) { + const [operator, mapExpression] = clusterProperties[key]; + const mapExpressionParsed = performance.bC(mapExpression); + const reduceExpressionParsed = performance.bC(typeof operator === 'string' ? [operator, ['accumulated'], ['get', key]] : operator); + mapExpressions[key] = mapExpressionParsed.value; + reduceExpressions[key] = reduceExpressionParsed.value; + } + superclusterOptions.map = (pointProperties) => { + feature.properties = pointProperties; + const properties = {}; + for (const key of propertyNames) { + properties[key] = mapExpressions[key].evaluate(globals, feature); + } + return properties; + }; + superclusterOptions.reduce = (accumulated, clusterProperties) => { + feature.properties = clusterProperties; + for (const key of propertyNames) { + globals.accumulated = accumulated[key]; + accumulated[key] = reduceExpressions[key].evaluate(globals, feature); + } + }; + return superclusterOptions; +} + +/** + * The Worker class responsible for background thread related execution + */ +class Worker { + constructor(self) { + this.self = self; + this.actor = new performance.F(self); + this.layerIndexes = {}; + this.availableImages = {}; + this.workerSources = {}; + this.demWorkerSources = {}; + this.externalWorkerSourceTypes = {}; + this.self.registerWorkerSource = (name, WorkerSource) => { + if (this.externalWorkerSourceTypes[name]) { + throw new Error(`Worker source with name "${name}" already registered.`); + } + this.externalWorkerSourceTypes[name] = WorkerSource; + }; + this.self.addProtocol = performance.bi; + this.self.removeProtocol = performance.bj; + // This is invoked by the RTL text plugin when the download via the `importScripts` call has finished, and the code has been parsed. + this.self.registerRTLTextPlugin = (rtlTextPlugin) => { + if (performance.bD.isParsed()) { + throw new Error('RTL text plugin already registered.'); + } + performance.bD.setMethods(rtlTextPlugin); + }; + this.actor.registerMessageHandler("LDT" /* MessageType.loadDEMTile */, (mapId, params) => { + return this._getDEMWorkerSource(mapId, params.source).loadTile(params); + }); + this.actor.registerMessageHandler("RDT" /* MessageType.removeDEMTile */, (mapId, params) => performance._(this, void 0, void 0, function* () { + this._getDEMWorkerSource(mapId, params.source).removeTile(params); + })); + this.actor.registerMessageHandler("GCEZ" /* MessageType.getClusterExpansionZoom */, (mapId, params) => performance._(this, void 0, void 0, function* () { + return this._getWorkerSource(mapId, params.type, params.source).getClusterExpansionZoom(params); + })); + this.actor.registerMessageHandler("GCC" /* MessageType.getClusterChildren */, (mapId, params) => performance._(this, void 0, void 0, function* () { + return this._getWorkerSource(mapId, params.type, params.source).getClusterChildren(params); + })); + this.actor.registerMessageHandler("GCL" /* MessageType.getClusterLeaves */, (mapId, params) => performance._(this, void 0, void 0, function* () { + return this._getWorkerSource(mapId, params.type, params.source).getClusterLeaves(params); + })); + this.actor.registerMessageHandler("LD" /* MessageType.loadData */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).loadData(params); + }); + this.actor.registerMessageHandler("GD" /* MessageType.getData */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).getData(); + }); + this.actor.registerMessageHandler("LT" /* MessageType.loadTile */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).loadTile(params); + }); + this.actor.registerMessageHandler("RT" /* MessageType.reloadTile */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).reloadTile(params); + }); + this.actor.registerMessageHandler("AT" /* MessageType.abortTile */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).abortTile(params); + }); + this.actor.registerMessageHandler("RMT" /* MessageType.removeTile */, (mapId, params) => { + return this._getWorkerSource(mapId, params.type, params.source).removeTile(params); + }); + this.actor.registerMessageHandler("RS" /* MessageType.removeSource */, (mapId, params) => performance._(this, void 0, void 0, function* () { + if (!this.workerSources[mapId] || + !this.workerSources[mapId][params.type] || + !this.workerSources[mapId][params.type][params.source]) { + return; + } + const worker = this.workerSources[mapId][params.type][params.source]; + delete this.workerSources[mapId][params.type][params.source]; + if (worker.removeSource !== undefined) { + worker.removeSource(params); + } + })); + this.actor.registerMessageHandler("RM" /* MessageType.removeMap */, (mapId) => performance._(this, void 0, void 0, function* () { + delete this.layerIndexes[mapId]; + delete this.availableImages[mapId]; + delete this.workerSources[mapId]; + delete this.demWorkerSources[mapId]; + })); + this.actor.registerMessageHandler("SR" /* MessageType.setReferrer */, (_mapId, params) => performance._(this, void 0, void 0, function* () { + this.referrer = params; + })); + this.actor.registerMessageHandler("SRPS" /* MessageType.syncRTLPluginState */, (mapId, params) => { + return this._syncRTLPluginState(mapId, params); + }); + this.actor.registerMessageHandler("IS" /* MessageType.importScript */, (_mapId, params) => performance._(this, void 0, void 0, function* () { + this.self.importScripts(params); + })); + this.actor.registerMessageHandler("SI" /* MessageType.setImages */, (mapId, params) => { + return this._setImages(mapId, params); + }); + this.actor.registerMessageHandler("UL" /* MessageType.updateLayers */, (mapId, params) => performance._(this, void 0, void 0, function* () { + this._getLayerIndex(mapId).update(params.layers, params.removedIds); + })); + this.actor.registerMessageHandler("SL" /* MessageType.setLayers */, (mapId, params) => performance._(this, void 0, void 0, function* () { + this._getLayerIndex(mapId).replace(params); + })); + } + _setImages(mapId, images) { + return performance._(this, void 0, void 0, function* () { + this.availableImages[mapId] = images; + for (const workerSource in this.workerSources[mapId]) { + const ws = this.workerSources[mapId][workerSource]; + for (const source in ws) { + ws[source].availableImages = images; + } + } + }); + } + _syncRTLPluginState(mapId, incomingState) { + return performance._(this, void 0, void 0, function* () { + // Parsed plugin cannot be changed, so just return its current state. + if (performance.bD.isParsed()) { + return performance.bD.getState(); + } + if (incomingState.pluginStatus !== 'loading') { + // simply sync and done + performance.bD.setState(incomingState); + return incomingState; + } + const urlToLoad = incomingState.pluginURL; + this.self.importScripts(urlToLoad); + const complete = performance.bD.isParsed(); + if (complete) { + const loadedState = { + pluginStatus: 'loaded', + pluginURL: urlToLoad + }; + performance.bD.setState(loadedState); + return loadedState; + } + // error case + performance.bD.setState({ + pluginStatus: 'error', + pluginURL: '' + }); + throw new Error(`RTL Text Plugin failed to import scripts from ${urlToLoad}`); + }); + } + _getAvailableImages(mapId) { + let availableImages = this.availableImages[mapId]; + if (!availableImages) { + availableImages = []; + } + return availableImages; + } + _getLayerIndex(mapId) { + let layerIndexes = this.layerIndexes[mapId]; + if (!layerIndexes) { + layerIndexes = this.layerIndexes[mapId] = new StyleLayerIndex(); + } + return layerIndexes; + } + /** + * This is basically a lazy initialization of a worker per mapId and sourceType and sourceName + * @param mapId - the mapId + * @param sourceType - the source type - 'vector' for example + * @param sourceName - the source name - 'osm' for example + * @returns a new instance or a cached one + */ + _getWorkerSource(mapId, sourceType, sourceName) { + if (!this.workerSources[mapId]) + this.workerSources[mapId] = {}; + if (!this.workerSources[mapId][sourceType]) + this.workerSources[mapId][sourceType] = {}; + if (!this.workerSources[mapId][sourceType][sourceName]) { + // use a wrapped actor so that we can attach a target mapId param + // to any messages invoked by the WorkerSource, this is very important when there are multiple maps + const actor = { + sendAsync: (message, abortController) => { + message.targetMapId = mapId; + return this.actor.sendAsync(message, abortController); + } + }; + switch (sourceType) { + case 'vector': + this.workerSources[mapId][sourceType][sourceName] = new VectorTileWorkerSource(actor, this._getLayerIndex(mapId), this._getAvailableImages(mapId)); + break; + case 'geojson': + this.workerSources[mapId][sourceType][sourceName] = new GeoJSONWorkerSource(actor, this._getLayerIndex(mapId), this._getAvailableImages(mapId)); + break; + default: + this.workerSources[mapId][sourceType][sourceName] = new (this.externalWorkerSourceTypes[sourceType])(actor, this._getLayerIndex(mapId), this._getAvailableImages(mapId)); + break; + } + } + return this.workerSources[mapId][sourceType][sourceName]; + } + /** + * This is basically a lazy initialization of a worker per mapId and source + * @param mapId - the mapId + * @param sourceType - the source type - 'raster-dem' for example + * @returns a new instance or a cached one + */ + _getDEMWorkerSource(mapId, sourceType) { + if (!this.demWorkerSources[mapId]) + this.demWorkerSources[mapId] = {}; + if (!this.demWorkerSources[mapId][sourceType]) { + this.demWorkerSources[mapId][sourceType] = new RasterDEMTileWorkerSource(); + } + return this.demWorkerSources[mapId][sourceType]; + } +} +if (performance.i(self)) { + self.worker = new Worker(self); +} + +return Worker; + +})); + +define('index', ['exports', './shared'], (function (exports, performance$1) { 'use strict'; + +var name = "maplibre-gl"; +var description = "BSD licensed community fork of mapbox-gl, a WebGL interactive maps library"; +var version$2 = "4.7.0"; +var main = "dist/maplibre-gl.js"; +var style = "dist/maplibre-gl.css"; +var license = "BSD-3-Clause"; +var homepage = "https://maplibre.org/"; +var funding = "https://github.com/maplibre/maplibre-gl-js?sponsor=1"; +var bugs = { + url: "https://github.com/maplibre/maplibre-gl-js/issues/" +}; +var repository = { + type: "git", + url: "git://github.com/maplibre/maplibre-gl-js.git" +}; +var types = "dist/maplibre-gl.d.ts"; +var type = "module"; +var dependencies = { + "@mapbox/geojson-rewind": "^0.5.2", + "@mapbox/jsonlint-lines-primitives": "^2.0.2", + "@mapbox/point-geometry": "^0.1.0", + "@mapbox/tiny-sdf": "^2.0.6", + "@mapbox/unitbezier": "^0.0.1", + "@mapbox/vector-tile": "^1.3.1", + "@mapbox/whoots-js": "^3.1.0", + "@maplibre/maplibre-gl-style-spec": "^20.3.1", + "@types/geojson": "^7946.0.14", + "@types/geojson-vt": "3.2.5", + "@types/mapbox__point-geometry": "^0.1.4", + "@types/mapbox__vector-tile": "^1.3.4", + "@types/pbf": "^3.0.5", + "@types/supercluster": "^7.1.3", + earcut: "^3.0.0", + "geojson-vt": "^4.0.2", + "gl-matrix": "^3.4.3", + "global-prefix": "^4.0.0", + kdbush: "^4.0.2", + "murmurhash-js": "^1.0.0", + pbf: "^3.3.0", + potpack: "^2.0.0", + quickselect: "^3.0.0", + supercluster: "^8.0.1", + tinyqueue: "^3.0.0", + "vt-pbf": "^3.1.3" +}; +var devDependencies = { + autoprefixer: "^10.4.20", + "@mapbox/mapbox-gl-rtl-text": "^0.3.0", + "@mapbox/mvt-fixtures": "^3.10.0", + "@rollup/plugin-commonjs": "^26.0.1", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-replace": "^5.0.7", + "@rollup/plugin-strip": "^3.0.4", + "@rollup/plugin-terser": "^0.4.4", + "@rollup/plugin-typescript": "^11.1.6", + "@types/benchmark": "^2.1.5", + "@types/cssnano": "^5.0.0", + "@types/d3": "^7.4.3", + "@types/diff": "^5.2.2", + "@types/earcut": "^2.1.4", + "@types/eslint": "^8.56.7", + "@types/gl": "^6.0.5", + "@types/glob": "^8.1.0", + "@types/jest": "^29.5.12", + "@types/jsdom": "^21.1.7", + "@types/minimist": "^1.2.5", + "@types/murmurhash-js": "^1.0.6", + "@types/nise": "^1.4.5", + "@types/node": "^22.5.4", + "@types/offscreencanvas": "^2019.7.3", + "@types/pixelmatch": "^5.2.6", + "@types/pngjs": "^6.0.5", + "@types/react": "^18.3.5", + "@types/react-dom": "^18.3.0", + "@types/request": "^2.48.12", + "@types/shuffle-seed": "^1.1.3", + "@types/window-or-global": "^1.0.6", + "@typescript-eslint/eslint-plugin": "^7.18.0", + "@typescript-eslint/parser": "^7.18.0", + address: "^2.0.3", + benchmark: "^2.1.4", + canvas: "^2.11.2", + cssnano: "^7.0.6", + d3: "^7.9.0", + "d3-queue": "^3.0.7", + "devtools-protocol": "^0.0.1352404", + diff: "^7.0.0", + "dts-bundle-generator": "^9.5.1", + eslint: "^8.57.0", + "eslint-config-mourner": "^3.0.0", + "eslint-plugin-html": "^8.1.1", + "eslint-plugin-import": "^2.30.0", + "eslint-plugin-jest": "^28.8.3", + "eslint-plugin-react": "^7.35.2", + "eslint-plugin-tsdoc": "0.3.0", + expect: "^29.7.0", + glob: "^11.0.0", + "is-builtin-module": "^4.0.0", + jest: "^29.7.0", + "jest-environment-jsdom": "^29.7.0", + "jest-junit": "^16.0.0", + "jest-monocart-coverage": "^1.1.1", + "jest-webgl-canvas-mock": "^2.5.3", + jsdom: "^25.0.0", + "junit-report-builder": "^5.0.0", + minimist: "^1.2.8", + "mock-geolocation": "^1.0.11", + "monocart-coverage-reports": "^2.10.3", + nise: "^6.0.0", + "npm-font-open-sans": "^1.1.0", + "npm-run-all": "^4.1.5", + "pdf-merger-js": "^5.1.2", + pixelmatch: "^6.0.0", + pngjs: "^7.0.0", + postcss: "^8.4.45", + "postcss-cli": "^11.0.0", + "postcss-inline-svg": "^6.0.0", + "pretty-bytes": "^6.1.1", + puppeteer: "^23.3.0", + react: "^18.3.1", + "react-dom": "^18.3.1", + rollup: "^4.21.2", + "rollup-plugin-sourcemaps": "^0.6.3", + rw: "^1.3.3", + semver: "^7.6.3", + "shuffle-seed": "^1.1.6", + "source-map-explorer": "^2.5.3", + st: "^3.0.0", + stylelint: "^16.9.0", + "stylelint-config-standard": "^36.0.1", + "ts-jest": "^29.2.5", + "ts-node": "^10.9.2", + tslib: "^2.7.0", + typedoc: "^0.26.6", + "typedoc-plugin-markdown": "^4.2.7", + "typedoc-plugin-missing-exports": "^3.0.0", + typescript: "^5.5.4" +}; +var scripts = { + "generate-dist-package": "node --no-warnings --loader ts-node/esm build/generate-dist-package.js", + "generate-shaders": "node --no-warnings --loader ts-node/esm build/generate-shaders.ts", + "generate-struct-arrays": "node --no-warnings --loader ts-node/esm build/generate-struct-arrays.ts", + "generate-style-code": "node --no-warnings --loader ts-node/esm build/generate-style-code.ts", + "generate-typings": "dts-bundle-generator --export-referenced-types --umd-module-name=maplibregl -o ./dist/maplibre-gl.d.ts ./src/index.ts", + "generate-docs": "typedoc && node --no-warnings --loader ts-node/esm build/generate-docs.ts", + "generate-images": "node --no-warnings --loader ts-node/esm build/generate-doc-images.ts", + "build-dist": "npm run build-css && npm run generate-typings && npm run build-dev && npm run build-csp-dev && npm run build-prod && npm run build-prod-unminified && npm run build-csp", + "build-dev": "rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:dev", + "watch-dev": "rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:dev --watch", + "build-prod": "rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:production,MINIFY:true", + "build-prod-unminified": "rollup --configPlugin @rollup/plugin-typescript -c --environment BUILD:production", + "build-csp": "rollup --configPlugin @rollup/plugin-typescript -c rollup.config.csp.ts --environment BUILD:production,MINIFY:true", + "build-csp-dev": "rollup --configPlugin @rollup/plugin-typescript -c rollup.config.csp.ts --environment BUILD:dev", + "build-css": "postcss -o dist/maplibre-gl.css src/css/maplibre-gl.css", + "watch-css": "postcss --watch -o dist/maplibre-gl.css src/css/maplibre-gl.css", + "build-benchmarks": "npm run build-dev && rollup --configPlugin @rollup/plugin-typescript -c test/bench/rollup_config_benchmarks.ts", + "watch-benchmarks": "rollup --configPlugin @rollup/plugin-typescript -c test/bench/rollup_config_benchmarks.ts --watch", + "start-server": "st --no-cache -H localhost --port 9966 .", + "start-docs": "docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material", + start: "run-p watch-css watch-dev start-server", + "start-bench": "run-p watch-css watch-benchmarks start-server", + lint: "eslint --cache --ext .ts,.tsx,.js,.html --ignore-path .gitignore .", + "lint-css": "stylelint **/*.css --fix -f verbose", + test: "run-p lint lint-css test-render jest", + jest: "jest", + "test-build": "jest --selectProjects=build --reporters=default", + "test-build-ci": "jest --selectProjects=build", + "test-integration": "jest --selectProjects=integration --reporters=default", + "test-integration-ci": "jest --coverage --selectProjects=integration", + "test-render": "node --no-warnings --loader ts-node/esm test/integration/render/run_render_tests.ts", + "test-unit": "jest --selectProjects=unit --reporters=default", + "test-unit-ci": "jest --coverage --selectProjects unit", + "test-watch-roots": "jest --watch", + codegen: "run-p --print-label generate-dist-package generate-style-code generate-struct-arrays generate-shaders && npm run generate-typings", + benchmark: "node --no-warnings --loader ts-node/esm test/bench/run-benchmarks.ts", + "gl-stats": "node --no-warnings --loader ts-node/esm test/bench/gl-stats.ts", + prepare: "npm run codegen", + typecheck: "tsc --noEmit && tsc --project tsconfig.dist.json", + tsnode: "node --experimental-loader=ts-node/esm --no-warnings" +}; +var files = [ + "build/", + "dist/*", + "src/" +]; +var engines = { + npm: ">=8.1.0", + node: ">=16.14.0" +}; +var packageJSON = { + name: name, + description: description, + version: version$2, + main: main, + style: style, + license: license, + homepage: homepage, + funding: funding, + bugs: bugs, + repository: repository, + types: types, + type: type, + dependencies: dependencies, + devDependencies: devDependencies, + scripts: scripts, + files: files, + engines: engines +}; + +const now = typeof performance !== 'undefined' && performance && performance.now ? + performance.now.bind(performance) : + Date.now.bind(Date); +let linkEl; +let reducedMotionQuery; +/** */ +const browser = { + /** + * Provides a function that outputs milliseconds: either performance.now() + * or a fallback to Date.now() + */ + now, + frameAsync(abortController) { + return new Promise((resolve, reject) => { + const frame = requestAnimationFrame(resolve); + abortController.signal.addEventListener('abort', () => { + cancelAnimationFrame(frame); + reject(performance$1.c()); + }); + }); + }, + getImageData(img, padding = 0) { + const context = this.getImageCanvasContext(img); + return context.getImageData(-padding, -padding, img.width + 2 * padding, img.height + 2 * padding); + }, + getImageCanvasContext(img) { + const canvas = window.document.createElement('canvas'); + const context = canvas.getContext('2d', { willReadFrequently: true }); + if (!context) { + throw new Error('failed to create canvas 2d context'); + } + canvas.width = img.width; + canvas.height = img.height; + context.drawImage(img, 0, 0, img.width, img.height); + return context; + }, + resolveURL(path) { + if (!linkEl) + linkEl = document.createElement('a'); + linkEl.href = path; + return linkEl.href; + }, + hardwareConcurrency: typeof navigator !== 'undefined' && navigator.hardwareConcurrency || 4, + get prefersReducedMotion() { + // In case your test crashes when checking matchMedia, call setMatchMedia from 'src/util/test/util' + if (!matchMedia) + return false; + //Lazily initialize media query + if (reducedMotionQuery == null) { + reducedMotionQuery = matchMedia('(prefers-reduced-motion: reduce)'); + } + return reducedMotionQuery.matches; + }, +}; + +class DOM { + static testProp(props) { + if (!DOM.docStyle) + return props[0]; + for (let i = 0; i < props.length; i++) { + if (props[i] in DOM.docStyle) { + return props[i]; + } + } + return props[0]; + } + static create(tagName, className, container) { + const el = window.document.createElement(tagName); + if (className !== undefined) + el.className = className; + if (container) + container.appendChild(el); + return el; + } + static createNS(namespaceURI, tagName) { + const el = window.document.createElementNS(namespaceURI, tagName); + return el; + } + static disableDrag() { + if (DOM.docStyle && DOM.selectProp) { + DOM.userSelect = DOM.docStyle[DOM.selectProp]; + DOM.docStyle[DOM.selectProp] = 'none'; + } + } + static enableDrag() { + if (DOM.docStyle && DOM.selectProp) { + DOM.docStyle[DOM.selectProp] = DOM.userSelect; + } + } + static setTransform(el, value) { + el.style[DOM.transformProp] = value; + } + static addEventListener(target, type, callback, options = {}) { + if ('passive' in options) { + target.addEventListener(type, callback, options); + } + else { + target.addEventListener(type, callback, options.capture); + } + } + static removeEventListener(target, type, callback, options = {}) { + if ('passive' in options) { + target.removeEventListener(type, callback, options); + } + else { + target.removeEventListener(type, callback, options.capture); + } + } + // Suppress the next click, but only if it's immediate. + static suppressClickInternal(e) { + e.preventDefault(); + e.stopPropagation(); + window.removeEventListener('click', DOM.suppressClickInternal, true); + } + static suppressClick() { + window.addEventListener('click', DOM.suppressClickInternal, true); + window.setTimeout(() => { + window.removeEventListener('click', DOM.suppressClickInternal, true); + }, 0); + } + static getScale(element) { + const rect = element.getBoundingClientRect(); + return { + x: (rect.width / element.offsetWidth) || 1, + y: (rect.height / element.offsetHeight) || 1, + boundingClientRect: rect, + }; + } + static getPoint(el, scale, e) { + const rect = scale.boundingClientRect; + return new performance$1.P( + // rect.left/top values are in page scale (like clientX/Y), + // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies). + ((e.clientX - rect.left) / scale.x) - el.clientLeft, ((e.clientY - rect.top) / scale.y) - el.clientTop); + } + static mousePos(el, e) { + const scale = DOM.getScale(el); + return DOM.getPoint(el, scale, e); + } + static touchPos(el, touches) { + const points = []; + const scale = DOM.getScale(el); + for (let i = 0; i < touches.length; i++) { + points.push(DOM.getPoint(el, scale, touches[i])); + } + return points; + } + static mouseButton(e) { + return e.button; + } + static remove(node) { + if (node.parentNode) { + node.parentNode.removeChild(node); + } + } +} +DOM.docStyle = typeof window !== 'undefined' && window.document && window.document.documentElement.style; +DOM.selectProp = DOM.testProp(['userSelect', 'MozUserSelect', 'WebkitUserSelect', 'msUserSelect']); +DOM.transformProp = DOM.testProp(['transform', 'WebkitTransform']); + +const webpSupported = { + supported: false, + testSupport +}; +let glForTesting; +let webpCheckComplete = false; +let webpImgTest; +let webpImgTestOnloadComplete = false; +if (typeof document !== 'undefined') { + webpImgTest = document.createElement('img'); + webpImgTest.onload = () => { + if (glForTesting) + testWebpTextureUpload(glForTesting); + glForTesting = null; + webpImgTestOnloadComplete = true; + }; + webpImgTest.onerror = () => { + webpCheckComplete = true; + glForTesting = null; + }; + webpImgTest.src = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA='; +} +function testSupport(gl) { + if (webpCheckComplete || !webpImgTest) + return; + // HTMLImageElement.complete is set when an image is done loading it's source + // regardless of whether the load was successful or not. + // It's possible for an error to set HTMLImageElement.complete to true which would trigger + // testWebpTextureUpload and mistakenly set exported.supported to true in browsers which don't support webp + // To avoid this, we set a flag in the image's onload handler and only call testWebpTextureUpload + // after a successful image load event. + if (webpImgTestOnloadComplete) { + testWebpTextureUpload(gl); + } + else { + glForTesting = gl; + } +} +function testWebpTextureUpload(gl) { + // Edge 18 supports WebP but not uploading a WebP image to a gl texture + // Test support for this before allowing WebP images. + // https://github.com/mapbox/mapbox-gl-js/issues/7671 + const texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + try { + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, webpImgTest); + // The error does not get triggered in Edge if the context is lost + if (gl.isContextLost()) + return; + webpSupported.supported = true; + } + catch (e) { + // Catch "Unspecified Error." in Edge 18. + } + gl.deleteTexture(texture); + webpCheckComplete = true; +} + +/** + * By default, the image queue is self driven, meaning as soon as one requested item is processed, + * it will move on to next one as quickly as it can while limiting + * the number of concurrent requests to MAX_PARALLEL_IMAGE_REQUESTS. The default behavior + * ensures that static views of the map can be rendered with minimal delay. + * + * However, the default behavior can prevent dynamic views of the map from rendering + * smoothly in that many requests can finish in one render frame, putting too much pressure on GPU. + * + * When the view of the map is moving dynamically, smoother frame rates can be achieved + * by throttling the number of items processed by the queue per frame. This can be + * accomplished by using {@link addThrottleControl} to allow the caller to + * use a lambda function to determine when the queue should be throttled (e.g. when isMoving()) + * and manually calling {@link processQueue} in the render loop. + */ +var ImageRequest; +(function (ImageRequest) { + let imageRequestQueue; + let currentParallelImageRequests; + let throttleControlCallbackHandleCounter; + let throttleControlCallbacks; + /** + * Reset the image request queue, removing all pending requests. + */ + ImageRequest.resetRequestQueue = () => { + imageRequestQueue = []; + currentParallelImageRequests = 0; + throttleControlCallbackHandleCounter = 0; + throttleControlCallbacks = {}; + }; + /** + * Install a callback to control when image queue throttling is desired. + * (e.g. when the map view is moving) + * @param callback - The callback function to install + * @returns handle that identifies the installed callback. + */ + ImageRequest.addThrottleControl = (callback) => { + const handle = throttleControlCallbackHandleCounter++; + throttleControlCallbacks[handle] = callback; + return handle; + }; + /** + * Remove a previously installed callback by passing in the handle returned + * by {@link addThrottleControl}. + * @param callbackHandle - The handle for the callback to remove. + */ + ImageRequest.removeThrottleControl = (callbackHandle) => { + delete throttleControlCallbacks[callbackHandle]; + // Try updating the queue + processQueue(); + }; + /** + * Check to see if any of the installed callbacks are requesting the queue + * to be throttled. + * @returns `true` if any callback is causing the queue to be throttled. + */ + const isThrottled = () => { + for (const key of Object.keys(throttleControlCallbacks)) { + if (throttleControlCallbacks[key]()) { + return true; + } + } + return false; + }; + /** + * Request to load an image. + * @param requestParameters - Request parameters. + * @param abortController - allows to abort the request. + * @param supportImageRefresh - `true`, if the image request need to support refresh based on cache headers. + * @returns - A promise resolved when the image is loaded. + */ + ImageRequest.getImage = (requestParameters, abortController, supportImageRefresh = true) => { + return new Promise((resolve, reject) => { + if (webpSupported.supported) { + if (!requestParameters.headers) { + requestParameters.headers = {}; + } + requestParameters.headers.accept = 'image/webp,*/*'; + } + performance$1.e(requestParameters, { type: 'image' }); + const request = { + abortController, + requestParameters, + supportImageRefresh, + state: 'queued', + onError: (error) => { + reject(error); + }, + onSuccess: (response) => { + resolve(response); + } + }; + imageRequestQueue.push(request); + processQueue(); + }); + }; + const arrayBufferToCanvasImageSource = (data) => { + const imageBitmapSupported = typeof createImageBitmap === 'function'; + if (imageBitmapSupported) { + return performance$1.d(data); + } + else { + return performance$1.f(data); + } + }; + const doImageRequest = (itemInQueue) => performance$1._(this, void 0, void 0, function* () { + itemInQueue.state = 'running'; + const { requestParameters, supportImageRefresh, onError, onSuccess, abortController } = itemInQueue; + // - If refreshExpiredTiles is false, then we can use HTMLImageElement to download raster images. + // - Fetch/XHR (via MakeRequest API) will be used to download images for following scenarios: + // 1. Style image sprite will had a issue with HTMLImageElement as described + // here: https://github.com/mapbox/mapbox-gl-js/issues/1470 + // 2. If refreshExpiredTiles is true (default), then in order to read the image cache header, + // fetch/XHR request will be required + // - For any special case handling like use of AddProtocol, worker initiated request or additional headers + // let makeRequest handle it. + // - HtmlImageElement request automatically adds accept header for all the browser supported images + const canUseHTMLImageElement = supportImageRefresh === false && + !performance$1.i(self) && + !performance$1.g(requestParameters.url) && + (!requestParameters.headers || + Object.keys(requestParameters.headers).reduce((acc, item) => acc && item === 'accept', true)); + currentParallelImageRequests++; + const getImagePromise = canUseHTMLImageElement ? + getImageUsingHtmlImage(requestParameters, abortController) : + performance$1.m(requestParameters, abortController); + try { + const response = yield getImagePromise; + delete itemInQueue.abortController; + itemInQueue.state = 'completed'; + if (response.data instanceof HTMLImageElement || performance$1.b(response.data)) { + // User using addProtocol can directly return HTMLImageElement/ImageBitmap type + // If HtmlImageElement is used to get image then response type will be HTMLImageElement + onSuccess(response); + } + else if (response.data) { + const img = yield arrayBufferToCanvasImageSource(response.data); + onSuccess({ data: img, cacheControl: response.cacheControl, expires: response.expires }); + } + } + catch (err) { + delete itemInQueue.abortController; + onError(err); + } + finally { + currentParallelImageRequests--; + processQueue(); + } + }); + /** + * Process some number of items in the image request queue. + */ + const processQueue = () => { + const maxImageRequests = isThrottled() ? + performance$1.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME : + performance$1.a.MAX_PARALLEL_IMAGE_REQUESTS; + // limit concurrent image loads to help with raster sources performance on big screens + for (let numImageRequests = currentParallelImageRequests; numImageRequests < maxImageRequests && imageRequestQueue.length > 0; numImageRequests++) { + const topItemInQueue = imageRequestQueue.shift(); + if (topItemInQueue.abortController.signal.aborted) { + numImageRequests--; + continue; + } + doImageRequest(topItemInQueue); + } + }; + const getImageUsingHtmlImage = (requestParameters, abortController) => { + return new Promise((resolve, reject) => { + const image = new Image(); + const url = requestParameters.url; + const credentials = requestParameters.credentials; + if (credentials && credentials === 'include') { + image.crossOrigin = 'use-credentials'; + } + else if ((credentials && credentials === 'same-origin') || !performance$1.s(url)) { + image.crossOrigin = 'anonymous'; + } + abortController.signal.addEventListener('abort', () => { + // Set src to '' to actually cancel the request + image.src = ''; + reject(performance$1.c()); + }); + image.fetchPriority = 'high'; + image.onload = () => { + image.onerror = image.onload = null; + resolve({ data: image }); + }; + image.onerror = () => { + image.onerror = image.onload = null; + if (abortController.signal.aborted) { + return; + } + reject(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.')); + }; + image.src = url; + }); + }; +})(ImageRequest || (ImageRequest = {})); +ImageRequest.resetRequestQueue(); + +class RequestManager { + constructor(transformRequestFn) { + this._transformRequestFn = transformRequestFn; + } + transformRequest(url, type) { + if (this._transformRequestFn) { + return this._transformRequestFn(url, type) || { url }; + } + return { url }; + } + setTransformRequest(transformRequest) { + this._transformRequestFn = transformRequest; + } +} + +/** + * 2x2 Matrix + * @module mat2 + */ + +/** + * Creates a new identity mat2 + * + * @returns {mat2} a new 2x2 matrix + */ + +function create$4() { + var out = new performance$1.A(4); + + if (performance$1.A != Float32Array) { + out[1] = 0; + out[2] = 0; + } + + out[0] = 1; + out[3] = 1; + return out; +} +/** + * Rotates a mat2 by the given angle + * + * @param {mat2} out the receiving matrix + * @param {ReadonlyMat2} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + +function rotate(out, a, rad) { + var a0 = a[0], + a1 = a[1], + a2 = a[2], + a3 = a[3]; + var s = Math.sin(rad); + var c = Math.cos(rad); + out[0] = a0 * c + a2 * s; + out[1] = a1 * c + a3 * s; + out[2] = a0 * -s + a2 * c; + out[3] = a1 * -s + a3 * c; + return out; +} + +/** + * 3x3 Matrix + * @module mat3 + */ + +/** + * Creates a new identity mat3 + * + * @returns {mat3} a new 3x3 matrix + */ + +function create$3() { + var out = new performance$1.A(9); + + if (performance$1.A != Float32Array) { + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[5] = 0; + out[6] = 0; + out[7] = 0; + } + + out[0] = 1; + out[4] = 1; + out[8] = 1; + return out; +} +/** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.rotate(dest, dest, rad); + * + * @param {mat3} out mat3 receiving operation result + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + +function fromRotation(out, rad) { + var s = Math.sin(rad), + c = Math.cos(rad); + out[0] = c; + out[1] = s; + out[2] = 0; + out[3] = -s; + out[4] = c; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +} + +/** + * 3 Dimensional Vector + * @module vec3 + */ + +/** + * Creates a new, empty vec3 + * + * @returns {vec3} a new 3D vector + */ + +function create$2() { + var out = new performance$1.A(3); + + if (performance$1.A != Float32Array) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + } + + return out; +} +/** + * Creates a new vec3 initialized with values from an existing vector + * + * @param {ReadonlyVec3} a vector to clone + * @returns {vec3} a new 3D vector + */ + +function clone(a) { + var out = new performance$1.A(3); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + return out; +} +/** + * Adds two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function add(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + return out; +} +/** + * Subtracts vector b from vector a + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function subtract(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + return out; +} +/** + * Scales a vec3 by a scalar number + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec3} out + */ + +function scale(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + return out; +} +/** + * Normalize a vec3 + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a vector to normalize + * @returns {vec3} out + */ + +function normalize(out, a) { + var x = a[0]; + var y = a[1]; + var z = a[2]; + var len = x * x + y * y + z * z; + + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + } + + out[0] = a[0] * len; + out[1] = a[1] * len; + out[2] = a[2] * len; + return out; +} +/** + * Calculates the dot product of two vec3's + * + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {Number} dot product of a and b + */ + +function dot(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +} +/** + * Computes the cross product of two vec3's + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the first operand + * @param {ReadonlyVec3} b the second operand + * @returns {vec3} out + */ + +function cross(out, a, b) { + var ax = a[0], + ay = a[1], + az = a[2]; + var bx = b[0], + by = b[1], + bz = b[2]; + out[0] = ay * bz - az * by; + out[1] = az * bx - ax * bz; + out[2] = ax * by - ay * bx; + return out; +} +/** + * Transforms the vec3 with a mat3. + * + * @param {vec3} out the receiving vector + * @param {ReadonlyVec3} a the vector to transform + * @param {ReadonlyMat3} m the 3x3 matrix to transform with + * @returns {vec3} out + */ + +function transformMat3(out, a, m) { + var x = a[0], + y = a[1], + z = a[2]; + out[0] = x * m[0] + y * m[3] + z * m[6]; + out[1] = x * m[1] + y * m[4] + z * m[7]; + out[2] = x * m[2] + y * m[5] + z * m[8]; + return out; +} +/** + * Alias for {@link vec3.subtract} + * @function + */ + +var sub = subtract; +/** + * Perform some operation over an array of vec3s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ + +(function () { + var vec = create$2(); + return function (a, stride, offset, count, fn, arg) { + var i, l; + + if (!stride) { + stride = 3; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min(count * stride + offset, a.length); + } else { + l = a.length; + } + + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + vec[2] = a[i + 2]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + a[i + 2] = vec[2]; + } + + return a; + }; +})(); + +/** + * 2 Dimensional Vector + * @module vec2 + */ + +/** + * Creates a new, empty vec2 + * + * @returns {vec2} a new 2D vector + */ + +function create$1() { + var out = new performance$1.A(2); + + if (performance$1.A != Float32Array) { + out[0] = 0; + out[1] = 0; + } + + return out; +} +/** + * Calculates the squared length of a vec2 + * + * @param {ReadonlyVec2} a vector to calculate squared length of + * @returns {Number} squared length of a + */ + +function squaredLength(a) { + var x = a[0], + y = a[1]; + return x * x + y * y; +} +/** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param {vec2} out the receiving vector + * @param {ReadonlyVec2} a the vector to transform + * @param {ReadonlyMat4} m matrix to transform with + * @returns {vec2} out + */ + +function transformMat4(out, a, m) { + var x = a[0]; + var y = a[1]; + out[0] = m[0] * x + m[4] * y + m[12]; + out[1] = m[1] * x + m[5] * y + m[13]; + return out; +} +/** + * Alias for {@link vec2.squaredLength} + * @function + */ + +var sqrLen = squaredLength; +/** + * Perform some operation over an array of vec2s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ + +(function () { + var vec = create$1(); + return function (a, stride, offset, count, fn, arg) { + var i, l; + + if (!stride) { + stride = 2; + } + + if (!offset) { + offset = 0; + } + + if (count) { + l = Math.min(count * stride + offset, a.length); + } else { + l = a.length; + } + + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + } + + return a; + }; +})(); + +/** + * Takes a SpriteSpecification value and returns it in its array form. If `undefined` is passed as an input value, an + * empty array is returned. + * duplicated entries with identical id/url will be removed in returned array + * @param sprite - optional sprite to coerce + * @returns an empty array in case `undefined` is passed; id-url pairs otherwise + */ +function coerceSpriteToArray(sprite) { + const resultArray = []; + if (typeof sprite === 'string') { + resultArray.push({ id: 'default', url: sprite }); + } + else if (sprite && sprite.length > 0) { + const dedupArray = []; + for (const { id, url } of sprite) { + const key = `${id}${url}`; + if (dedupArray.indexOf(key) === -1) { + dedupArray.push(key); + resultArray.push({ id, url }); + } + } + } + return resultArray; +} + +function normalizeSpriteURL(url, format, extension) { + const split = url.split('?'); + split[0] += `${format}${extension}`; + return split.join('?'); +} +function loadSprite(originalSprite, requestManager, pixelRatio, abortController) { + return performance$1._(this, void 0, void 0, function* () { + const spriteArray = coerceSpriteToArray(originalSprite); + const format = pixelRatio > 1 ? '@2x' : ''; + const jsonsMap = {}; + const imagesMap = {}; + for (const { id, url } of spriteArray) { + const jsonRequestParameters = requestManager.transformRequest(normalizeSpriteURL(url, format, '.json'), "SpriteJSON" /* ResourceType.SpriteJSON */); + jsonsMap[id] = performance$1.h(jsonRequestParameters, abortController); + const imageRequestParameters = requestManager.transformRequest(normalizeSpriteURL(url, format, '.png'), "SpriteImage" /* ResourceType.SpriteImage */); + imagesMap[id] = ImageRequest.getImage(imageRequestParameters, abortController); + } + yield Promise.all([...Object.values(jsonsMap), ...Object.values(imagesMap)]); + return doOnceCompleted(jsonsMap, imagesMap); + }); +} +/** + * @param jsonsMap - JSON data map + * @param imagesMap - image data map + */ +function doOnceCompleted(jsonsMap, imagesMap) { + return performance$1._(this, void 0, void 0, function* () { + const result = {}; + for (const spriteName in jsonsMap) { + result[spriteName] = {}; + const context = browser.getImageCanvasContext((yield imagesMap[spriteName]).data); + const json = (yield jsonsMap[spriteName]).data; + for (const id in json) { + const { width, height, x, y, sdf, pixelRatio, stretchX, stretchY, content, textFitWidth, textFitHeight } = json[id]; + const spriteData = { width, height, x, y, context }; + result[spriteName][id] = { data: null, pixelRatio, sdf, stretchX, stretchY, content, textFitWidth, textFitHeight, spriteData }; + } + } + return result; + }); +} + +/** + * @internal + * A `Texture` GL related object + */ +class Texture { + constructor(context, image, format, options) { + this.context = context; + this.format = format; + this.texture = context.gl.createTexture(); + this.update(image, options); + } + update(image, options, position) { + const { width, height } = image; + const resize = (!this.size || this.size[0] !== width || this.size[1] !== height) && !position; + const { context } = this; + const { gl } = context; + this.useMipmap = Boolean(options && options.useMipmap); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + context.pixelStoreUnpackFlipY.set(false); + context.pixelStoreUnpack.set(1); + context.pixelStoreUnpackPremultiplyAlpha.set(this.format === gl.RGBA && (!options || options.premultiply !== false)); + if (resize) { + this.size = [width, height]; + if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || performance$1.b(image)) { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, gl.UNSIGNED_BYTE, image); + } + else { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, gl.UNSIGNED_BYTE, image.data); + } + } + else { + const { x, y } = position || { x: 0, y: 0 }; + if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || performance$1.b(image)) { + gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, gl.RGBA, gl.UNSIGNED_BYTE, image); + } + else { + gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, image.data); + } + } + if (this.useMipmap && this.isSizePowerOfTwo()) { + gl.generateMipmap(gl.TEXTURE_2D); + } + } + bind(filter, wrap, minFilter) { + const { context } = this; + const { gl } = context; + gl.bindTexture(gl.TEXTURE_2D, this.texture); + if (minFilter === gl.LINEAR_MIPMAP_NEAREST && !this.isSizePowerOfTwo()) { + minFilter = gl.LINEAR; + } + if (filter !== this.filter) { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter || filter); + this.filter = filter; + } + if (wrap !== this.wrap) { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap); + this.wrap = wrap; + } + } + isSizePowerOfTwo() { + return this.size[0] === this.size[1] && (Math.log(this.size[0]) / Math.LN2) % 1 === 0; + } + destroy() { + const { gl } = this.context; + gl.deleteTexture(this.texture); + this.texture = null; + } +} + +function renderStyleImage(image) { + const { userImage } = image; + if (userImage && userImage.render) { + const updated = userImage.render(); + if (updated) { + image.data.replace(new Uint8Array(userImage.data.buffer)); + return true; + } + } + return false; +} + +/* eslint-disable key-spacing */ +/** + * When copied into the atlas texture, image data is padded by one pixel on each side. Icon + * images are padded with fully transparent pixels, while pattern images are padded with a + * copy of the image data wrapped from the opposite side. In both cases, this ensures the + * correct behavior of GL_LINEAR texture sampling mode. + */ +const padding = 1; +/** + * ImageManager does three things: + * + * 1. Tracks requests for icon images from tile workers and sends responses when the requests are fulfilled. + * 2. Builds a texture atlas for pattern images. + * 3. Rerenders renderable images once per frame + * + * These are disparate responsibilities and should eventually be handled by different classes. When we implement + * data-driven support for `*-pattern`, we'll likely use per-bucket pattern atlases, and that would be a good time + * to refactor this. +*/ +class ImageManager extends performance$1.E { + constructor() { + super(); + this.images = {}; + this.updatedImages = {}; + this.callbackDispatchedThisFrame = {}; + this.loaded = false; + this.requestors = []; + this.patterns = {}; + this.atlasImage = new performance$1.R({ width: 1, height: 1 }); + this.dirty = true; + } + isLoaded() { + return this.loaded; + } + setLoaded(loaded) { + if (this.loaded === loaded) { + return; + } + this.loaded = loaded; + if (loaded) { + for (const { ids, promiseResolve } of this.requestors) { + promiseResolve(this._getImagesForIds(ids)); + } + this.requestors = []; + } + } + getImage(id) { + const image = this.images[id]; + // Extract sprite image data on demand + if (image && !image.data && image.spriteData) { + const spriteData = image.spriteData; + image.data = new performance$1.R({ + width: spriteData.width, + height: spriteData.height + }, spriteData.context.getImageData(spriteData.x, spriteData.y, spriteData.width, spriteData.height).data); + image.spriteData = null; + } + return image; + } + addImage(id, image) { + if (this.images[id]) + throw new Error(`Image id ${id} already exist, use updateImage instead`); + if (this._validate(id, image)) { + this.images[id] = image; + } + } + _validate(id, image) { + let valid = true; + const data = image.data || image.spriteData; + if (!this._validateStretch(image.stretchX, data && data.width)) { + this.fire(new performance$1.j(new Error(`Image "${id}" has invalid "stretchX" value`))); + valid = false; + } + if (!this._validateStretch(image.stretchY, data && data.height)) { + this.fire(new performance$1.j(new Error(`Image "${id}" has invalid "stretchY" value`))); + valid = false; + } + if (!this._validateContent(image.content, image)) { + this.fire(new performance$1.j(new Error(`Image "${id}" has invalid "content" value`))); + valid = false; + } + return valid; + } + _validateStretch(stretch, size) { + if (!stretch) + return true; + let last = 0; + for (const part of stretch) { + if (part[0] < last || part[1] < part[0] || size < part[1]) + return false; + last = part[1]; + } + return true; + } + _validateContent(content, image) { + if (!content) + return true; + if (content.length !== 4) + return false; + const spriteData = image.spriteData; + const width = (spriteData && spriteData.width) || image.data.width; + const height = (spriteData && spriteData.height) || image.data.height; + if (content[0] < 0 || width < content[0]) + return false; + if (content[1] < 0 || height < content[1]) + return false; + if (content[2] < 0 || width < content[2]) + return false; + if (content[3] < 0 || height < content[3]) + return false; + if (content[2] < content[0]) + return false; + if (content[3] < content[1]) + return false; + return true; + } + updateImage(id, image, validate = true) { + const oldImage = this.getImage(id); + if (validate && (oldImage.data.width !== image.data.width || oldImage.data.height !== image.data.height)) { + throw new Error(`size mismatch between old image (${oldImage.data.width}x${oldImage.data.height}) and new image (${image.data.width}x${image.data.height}).`); + } + image.version = oldImage.version + 1; + this.images[id] = image; + this.updatedImages[id] = true; + } + removeImage(id) { + const image = this.images[id]; + delete this.images[id]; + delete this.patterns[id]; + if (image.userImage && image.userImage.onRemove) { + image.userImage.onRemove(); + } + } + listImages() { + return Object.keys(this.images); + } + getImages(ids) { + return new Promise((resolve, _reject) => { + // If the sprite has been loaded, or if all the icon dependencies are already present + // (i.e. if they've been added via runtime styling), then notify the requestor immediately. + // Otherwise, delay notification until the sprite is loaded. At that point, if any of the + // dependencies are still unavailable, we'll just assume they are permanently missing. + let hasAllDependencies = true; + if (!this.isLoaded()) { + for (const id of ids) { + if (!this.images[id]) { + hasAllDependencies = false; + } + } + } + if (this.isLoaded() || hasAllDependencies) { + resolve(this._getImagesForIds(ids)); + } + else { + this.requestors.push({ ids, promiseResolve: resolve }); + } + }); + } + _getImagesForIds(ids) { + const response = {}; + for (const id of ids) { + let image = this.getImage(id); + if (!image) { + this.fire(new performance$1.k('styleimagemissing', { id })); + //Try to acquire image again in case styleimagemissing has populated it + image = this.getImage(id); + } + if (image) { + // Clone the image so that our own copy of its ArrayBuffer doesn't get transferred. + response[id] = { + data: image.data.clone(), + pixelRatio: image.pixelRatio, + sdf: image.sdf, + version: image.version, + stretchX: image.stretchX, + stretchY: image.stretchY, + content: image.content, + textFitWidth: image.textFitWidth, + textFitHeight: image.textFitHeight, + hasRenderCallback: Boolean(image.userImage && image.userImage.render) + }; + } + else { + performance$1.w(`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.`); + } + } + return response; + } + // Pattern stuff + getPixelSize() { + const { width, height } = this.atlasImage; + return { width, height }; + } + getPattern(id) { + const pattern = this.patterns[id]; + const image = this.getImage(id); + if (!image) { + return null; + } + if (pattern && pattern.position.version === image.version) { + return pattern.position; + } + if (!pattern) { + const w = image.data.width + padding * 2; + const h = image.data.height + padding * 2; + const bin = { w, h, x: 0, y: 0 }; + const position = new performance$1.I(bin, image); + this.patterns[id] = { bin, position }; + } + else { + pattern.position.version = image.version; + } + this._updatePatternAtlas(); + return this.patterns[id].position; + } + bind(context) { + const gl = context.gl; + if (!this.atlasTexture) { + this.atlasTexture = new Texture(context, this.atlasImage, gl.RGBA); + } + else if (this.dirty) { + this.atlasTexture.update(this.atlasImage); + this.dirty = false; + } + this.atlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + } + _updatePatternAtlas() { + const bins = []; + for (const id in this.patterns) { + bins.push(this.patterns[id].bin); + } + const { w, h } = performance$1.p(bins); + const dst = this.atlasImage; + dst.resize({ width: w || 1, height: h || 1 }); + for (const id in this.patterns) { + const { bin } = this.patterns[id]; + const x = bin.x + padding; + const y = bin.y + padding; + const src = this.getImage(id).data; + const w = src.width; + const h = src.height; + performance$1.R.copy(src, dst, { x: 0, y: 0 }, { x, y }, { width: w, height: h }); + // Add 1 pixel wrapped padding on each side of the image. + performance$1.R.copy(src, dst, { x: 0, y: h - 1 }, { x, y: y - 1 }, { width: w, height: 1 }); // T + performance$1.R.copy(src, dst, { x: 0, y: 0 }, { x, y: y + h }, { width: w, height: 1 }); // B + performance$1.R.copy(src, dst, { x: w - 1, y: 0 }, { x: x - 1, y }, { width: 1, height: h }); // L + performance$1.R.copy(src, dst, { x: 0, y: 0 }, { x: x + w, y }, { width: 1, height: h }); // R + } + this.dirty = true; + } + beginFrame() { + this.callbackDispatchedThisFrame = {}; + } + dispatchRenderCallbacks(ids) { + for (const id of ids) { + // the callback for the image was already dispatched for a different frame + if (this.callbackDispatchedThisFrame[id]) + continue; + this.callbackDispatchedThisFrame[id] = true; + const image = this.getImage(id); + if (!image) + performance$1.w(`Image with ID: "${id}" was not found`); + const updated = renderStyleImage(image); + if (updated) { + this.updateImage(id, image); + } + } + } +} + +function loadGlyphRange(fontstack, range, urlTemplate, requestManager) { + return performance$1._(this, void 0, void 0, function* () { + const begin = range * 256; + const end = begin + 255; + const request = requestManager.transformRequest(urlTemplate.replace('{fontstack}', fontstack).replace('{range}', `${begin}-${end}`), "Glyphs" /* ResourceType.Glyphs */); + const response = yield performance$1.l(request, new AbortController()); + if (!response || !response.data) { + throw new Error(`Could not load glyph range. range: ${range}, ${begin}-${end}`); + } + const glyphs = {}; + for (const glyph of performance$1.n(response.data)) { + glyphs[glyph.id] = glyph; + } + return glyphs; + }); +} + +const INF = 1e20; + +class TinySDF { + constructor({ + fontSize = 24, + buffer = 3, + radius = 8, + cutoff = 0.25, + fontFamily = 'sans-serif', + fontWeight = 'normal', + fontStyle = 'normal' + } = {}) { + this.buffer = buffer; + this.cutoff = cutoff; + this.radius = radius; + + // make the canvas size big enough to both have the specified buffer around the glyph + // for "halo", and account for some glyphs possibly being larger than their font size + const size = this.size = fontSize + buffer * 4; + + const canvas = this._createCanvas(size); + const ctx = this.ctx = canvas.getContext('2d', {willReadFrequently: true}); + ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`; + + ctx.textBaseline = 'alphabetic'; + ctx.textAlign = 'left'; // Necessary so that RTL text doesn't have different alignment + ctx.fillStyle = 'black'; + + // temporary arrays for the distance transform + this.gridOuter = new Float64Array(size * size); + this.gridInner = new Float64Array(size * size); + this.f = new Float64Array(size); + this.z = new Float64Array(size + 1); + this.v = new Uint16Array(size); + } + + _createCanvas(size) { + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = size; + return canvas; + } + + draw(char) { + const { + width: glyphAdvance, + actualBoundingBoxAscent, + actualBoundingBoxDescent, + actualBoundingBoxLeft, + actualBoundingBoxRight + } = this.ctx.measureText(char); + + // The integer/pixel part of the top alignment is encoded in metrics.glyphTop + // The remainder is implicitly encoded in the rasterization + const glyphTop = Math.ceil(actualBoundingBoxAscent); + const glyphLeft = 0; + + // If the glyph overflows the canvas size, it will be clipped at the bottom/right + const glyphWidth = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(actualBoundingBoxRight - actualBoundingBoxLeft))); + const glyphHeight = Math.min(this.size - this.buffer, glyphTop + Math.ceil(actualBoundingBoxDescent)); + + const width = glyphWidth + 2 * this.buffer; + const height = glyphHeight + 2 * this.buffer; + + const len = Math.max(width * height, 0); + const data = new Uint8ClampedArray(len); + const glyph = {data, width, height, glyphWidth, glyphHeight, glyphTop, glyphLeft, glyphAdvance}; + if (glyphWidth === 0 || glyphHeight === 0) return glyph; + + const {ctx, buffer, gridInner, gridOuter} = this; + ctx.clearRect(buffer, buffer, glyphWidth, glyphHeight); + ctx.fillText(char, buffer, buffer + glyphTop); + const imgData = ctx.getImageData(buffer, buffer, glyphWidth, glyphHeight); + + // Initialize grids outside the glyph range to alpha 0 + gridOuter.fill(INF, 0, len); + gridInner.fill(0, 0, len); + + for (let y = 0; y < glyphHeight; y++) { + for (let x = 0; x < glyphWidth; x++) { + const a = imgData.data[4 * (y * glyphWidth + x) + 3] / 255; // alpha value + if (a === 0) continue; // empty pixels + + const j = (y + buffer) * width + x + buffer; + + if (a === 1) { // fully drawn pixels + gridOuter[j] = 0; + gridInner[j] = INF; + + } else { // aliased pixels + const d = 0.5 - a; + gridOuter[j] = d > 0 ? d * d : 0; + gridInner[j] = d < 0 ? d * d : 0; + } + } + } + + edt(gridOuter, 0, 0, width, height, width, this.f, this.v, this.z); + edt(gridInner, buffer, buffer, glyphWidth, glyphHeight, width, this.f, this.v, this.z); + + for (let i = 0; i < len; i++) { + const d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]); + data[i] = Math.round(255 - 255 * (d / this.radius + this.cutoff)); + } + + return glyph; + } +} + +// 2D Euclidean squared distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf +function edt(data, x0, y0, width, height, gridSize, f, v, z) { + for (let x = x0; x < x0 + width; x++) edt1d(data, y0 * gridSize + x, gridSize, height, f, v, z); + for (let y = y0; y < y0 + height; y++) edt1d(data, y * gridSize + x0, 1, width, f, v, z); +} + +// 1D squared distance transform +function edt1d(grid, offset, stride, length, f, v, z) { + v[0] = 0; + z[0] = -INF; + z[1] = INF; + f[0] = grid[offset]; + + for (let q = 1, k = 0, s = 0; q < length; q++) { + f[q] = grid[offset + q * stride]; + const q2 = q * q; + do { + const r = v[k]; + s = (f[q] - f[r] + q2 - r * r) / (q - r) / 2; + } while (s <= z[k] && --k > -1); + + k++; + v[k] = q; + z[k] = s; + z[k + 1] = INF; + } + + for (let q = 0, k = 0; q < length; q++) { + while (z[k + 1] < q) k++; + const r = v[k]; + const qr = q - r; + grid[offset + q * stride] = f[r] + qr * qr; + } +} + +class GlyphManager { + constructor(requestManager, localIdeographFontFamily) { + this.requestManager = requestManager; + this.localIdeographFontFamily = localIdeographFontFamily; + this.entries = {}; + } + setURL(url) { + this.url = url; + } + getGlyphs(glyphs) { + return performance$1._(this, void 0, void 0, function* () { + const glyphsPromises = []; + for (const stack in glyphs) { + for (const id of glyphs[stack]) { + glyphsPromises.push(this._getAndCacheGlyphsPromise(stack, id)); + } + } + const updatedGlyphs = yield Promise.all(glyphsPromises); + const result = {}; + for (const { stack, id, glyph } of updatedGlyphs) { + if (!result[stack]) { + result[stack] = {}; + } + // Clone the glyph so that our own copy of its ArrayBuffer doesn't get transferred. + result[stack][id] = glyph && { + id: glyph.id, + bitmap: glyph.bitmap.clone(), + metrics: glyph.metrics + }; + } + return result; + }); + } + _getAndCacheGlyphsPromise(stack, id) { + return performance$1._(this, void 0, void 0, function* () { + let entry = this.entries[stack]; + if (!entry) { + entry = this.entries[stack] = { + glyphs: {}, + requests: {}, + ranges: {} + }; + } + let glyph = entry.glyphs[id]; + if (glyph !== undefined) { + return { stack, id, glyph }; + } + glyph = this._tinySDF(entry, stack, id); + if (glyph) { + entry.glyphs[id] = glyph; + return { stack, id, glyph }; + } + const range = Math.floor(id / 256); + if (range * 256 > 65535) { + throw new Error('glyphs > 65535 not supported'); + } + if (entry.ranges[range]) { + return { stack, id, glyph }; + } + if (!this.url) { + throw new Error('glyphsUrl is not set'); + } + if (!entry.requests[range]) { + const promise = GlyphManager.loadGlyphRange(stack, range, this.url, this.requestManager); + entry.requests[range] = promise; + } + const response = yield entry.requests[range]; + for (const id in response) { + if (!this._doesCharSupportLocalGlyph(+id)) { + entry.glyphs[+id] = response[+id]; + } + } + entry.ranges[range] = true; + return { stack, id, glyph: response[id] || null }; + }); + } + _doesCharSupportLocalGlyph(id) { + // The CJK Unified Ideographs blocks and Hangul Syllables blocks are + // spread across many glyph PBFs and are typically accessed very + // randomly. Preferring local rendering for these blocks reduces + // wasteful bandwidth consumption. For visual consistency within CJKV + // text, also include any other CJKV or siniform ideograph or hangul, + // hiragana, or katakana character. + return !!this.localIdeographFontFamily && + /\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(id)); + } + _tinySDF(entry, stack, id) { + const fontFamily = this.localIdeographFontFamily; + if (!fontFamily) { + return; + } + if (!this._doesCharSupportLocalGlyph(id)) { + return; + } + // Client-generated glyphs are rendered at 2x texture scale, + // because CJK glyphs are more detailed than others. + const textureScale = 2; + let tinySDF = entry.tinySDF; + if (!tinySDF) { + let fontWeight = '400'; + if (/bold/i.test(stack)) { + fontWeight = '900'; + } + else if (/medium/i.test(stack)) { + fontWeight = '500'; + } + else if (/light/i.test(stack)) { + fontWeight = '200'; + } + tinySDF = entry.tinySDF = new GlyphManager.TinySDF({ + fontSize: 24 * textureScale, + buffer: 3 * textureScale, + radius: 8 * textureScale, + cutoff: 0.25, + fontFamily, + fontWeight + }); + } + const char = tinySDF.draw(String.fromCharCode(id)); + /** + * TinySDF's "top" is the distance from the alphabetic baseline to the top of the glyph. + * Server-generated fonts specify "top" relative to an origin above the em box (the origin + * comes from FreeType, but I'm unclear on exactly how it's derived) + * ref: https://github.com/mapbox/sdf-glyph-foundry + * + * Server fonts don't yet include baseline information, so we can't line up exactly with them + * (and they don't line up with each other) + * ref: https://github.com/mapbox/node-fontnik/pull/160 + * + * To approximately align TinySDF glyphs with server-provided glyphs, we use this baseline adjustment + * factor calibrated to be in between DIN Pro and Arial Unicode (but closer to Arial Unicode) + */ + const topAdjustment = 27.5; + const leftAdjustment = 0.5; + return { + id, + bitmap: new performance$1.o({ width: char.width || 30 * textureScale, height: char.height || 30 * textureScale }, char.data), + metrics: { + width: char.glyphWidth / textureScale || 24, + height: char.glyphHeight / textureScale || 24, + left: (char.glyphLeft / textureScale + leftAdjustment) || 0, + top: char.glyphTop / textureScale - topAdjustment || -8, + advance: char.glyphAdvance / textureScale || 24, + isDoubleResolution: true + } + }; + } +} +// exposed as statics to enable stubbing in unit tests +GlyphManager.loadGlyphRange = loadGlyphRange; +GlyphManager.TinySDF = TinySDF; + +class LightPositionProperty { + constructor() { + this.specification = performance$1.v.light.position; + } + possiblyEvaluate(value, parameters) { + return performance$1.x(value.expression.evaluate(parameters)); + } + interpolate(a, b, t) { + return { + x: performance$1.y.number(a.x, b.x, t), + y: performance$1.y.number(a.y, b.y, t), + z: performance$1.y.number(a.z, b.z, t), + }; + } +} +const TRANSITION_SUFFIX$1 = '-transition'; +let lightProperties; +/* + * Represents the light used to light extruded features. + */ +class Light extends performance$1.E { + constructor(lightOptions) { + super(); + lightProperties = lightProperties || new performance$1.q({ + 'anchor': new performance$1.D(performance$1.v.light.anchor), + 'position': new LightPositionProperty(), + 'color': new performance$1.D(performance$1.v.light.color), + 'intensity': new performance$1.D(performance$1.v.light.intensity), + }); + this._transitionable = new performance$1.T(lightProperties); + this.setLight(lightOptions); + this._transitioning = this._transitionable.untransitioned(); + } + getLight() { + return this._transitionable.serialize(); + } + setLight(light, options = {}) { + if (this._validate(performance$1.r, light, options)) { + return; + } + for (const name in light) { + const value = light[name]; + if (name.endsWith(TRANSITION_SUFFIX$1)) { + this._transitionable.setTransition(name.slice(0, -TRANSITION_SUFFIX$1.length), value); + } + else { + this._transitionable.setValue(name, value); + } + } + } + updateTransitions(parameters) { + this._transitioning = this._transitionable.transitioned(parameters, this._transitioning); + } + hasTransition() { + return this._transitioning.hasTransition(); + } + recalculate(parameters) { + this.properties = this._transitioning.possiblyEvaluate(parameters); + } + _validate(validate, value, options) { + if (options && options.validate === false) { + return false; + } + return performance$1.t(this, validate.call(performance$1.u, { + value, + // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407 + style: { glyphs: true, sprite: true }, + styleSpec: performance$1.v + })); + } +} + +const properties = new performance$1.q({ + 'sky-color': new performance$1.D(performance$1.v.sky['sky-color']), + 'horizon-color': new performance$1.D(performance$1.v.sky['horizon-color']), + 'fog-color': new performance$1.D(performance$1.v.sky['fog-color']), + 'fog-ground-blend': new performance$1.D(performance$1.v.sky['fog-ground-blend']), + 'horizon-fog-blend': new performance$1.D(performance$1.v.sky['horizon-fog-blend']), + 'sky-horizon-blend': new performance$1.D(performance$1.v.sky['sky-horizon-blend']), + 'atmosphere-blend': new performance$1.D(performance$1.v.sky['atmosphere-blend']) +}); +const TRANSITION_SUFFIX = '-transition'; +class Sky extends performance$1.E { + constructor(sky) { + super(); + this._transitionable = new performance$1.T(properties); + this.setSky(sky); + this._transitioning = this._transitionable.untransitioned(); + this.recalculate(new performance$1.z(0)); + } + setSky(sky, options = {}) { + if (this._validate(performance$1.B, sky, options)) + return; + if (!sky) { + sky = { + 'sky-color': 'transparent', + 'horizon-color': 'transparent', + 'fog-color': 'transparent', + 'fog-ground-blend': 1, + 'atmosphere-blend': 0, + }; + } + for (const name in sky) { + const value = sky[name]; + if (name.endsWith(TRANSITION_SUFFIX)) { + this._transitionable.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), value); + } + else { + this._transitionable.setValue(name, value); + } + } + } + getSky() { + return this._transitionable.serialize(); + } + updateTransitions(parameters) { + this._transitioning = this._transitionable.transitioned(parameters, this._transitioning); + } + hasTransition() { + return this._transitioning.hasTransition(); + } + recalculate(parameters) { + this.properties = this._transitioning.possiblyEvaluate(parameters); + } + _validate(validate, value, options = {}) { + if ((options === null || options === void 0 ? void 0 : options.validate) === false) { + return false; + } + return performance$1.t(this, validate.call(performance$1.u, performance$1.e({ + value, + // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407 + style: { glyphs: true, sprite: true }, + styleSpec: performance$1.v + }))); + } + /** + * Currently fog is a very simple implementation, and should only used + * to create an atmosphere near the horizon. + * But because the fog is drawn from the far-clipping-plane to + * map-center, and because the fog does nothing know about the horizon, + * this method does a fadeout in respect of pitch. So, when the horizon + * gets out of view, which is at about pitch 70, this methods calculates + * the corresponding opacity values. Below pitch 60 the fog is completely + * invisible. + */ + calculateFogBlendOpacity(pitch) { + if (pitch < 60) + return 0; // disable + if (pitch < 70) + return (pitch - 60) / 10; // fade in + return 1; + } +} + +/** + * @internal + * A LineAtlas lets us reuse rendered dashed lines + * by writing many of them to a texture and then fetching their positions + * using {@link LineAtlas#getDash}. + * + * @param width - the width + * @param height - the height + */ +class LineAtlas { + constructor(width, height) { + this.width = width; + this.height = height; + this.nextRow = 0; + this.data = new Uint8Array(this.width * this.height); + this.dashEntry = {}; + } + /** + * Get or create a dash line pattern. + * + * @param dasharray - the key (represented by numbers) to get the dash texture + * @param round - whether to add circle caps in between dash segments + * @returns position of dash texture in {@link DashEntry} + */ + getDash(dasharray, round) { + const key = dasharray.join(',') + String(round); + if (!this.dashEntry[key]) { + this.dashEntry[key] = this.addDash(dasharray, round); + } + return this.dashEntry[key]; + } + getDashRanges(dasharray, lineAtlasWidth, stretch) { + // If dasharray has an odd length, both the first and last parts + // are dashes and should be joined seamlessly. + const oddDashArray = dasharray.length % 2 === 1; + const ranges = []; + let left = oddDashArray ? -dasharray[dasharray.length - 1] * stretch : 0; + let right = dasharray[0] * stretch; + let isDash = true; + ranges.push({ left, right, isDash, zeroLength: dasharray[0] === 0 }); + let currentDashLength = dasharray[0]; + for (let i = 1; i < dasharray.length; i++) { + isDash = !isDash; + const dashLength = dasharray[i]; + left = currentDashLength * stretch; + currentDashLength += dashLength; + right = currentDashLength * stretch; + ranges.push({ left, right, isDash, zeroLength: dashLength === 0 }); + } + return ranges; + } + addRoundDash(ranges, stretch, n) { + const halfStretch = stretch / 2; + for (let y = -n; y <= n; y++) { + const row = this.nextRow + n + y; + const index = this.width * row; + let currIndex = 0; + let range = ranges[currIndex]; + for (let x = 0; x < this.width; x++) { + if (x / range.right > 1) { + range = ranges[++currIndex]; + } + const distLeft = Math.abs(x - range.left); + const distRight = Math.abs(x - range.right); + const minDist = Math.min(distLeft, distRight); + let signedDistance; + const distMiddle = y / n * (halfStretch + 1); + if (range.isDash) { + const distEdge = halfStretch - Math.abs(distMiddle); + signedDistance = Math.sqrt(minDist * minDist + distEdge * distEdge); + } + else { + signedDistance = halfStretch - Math.sqrt(minDist * minDist + distMiddle * distMiddle); + } + this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128)); + } + } + } + addRegularDash(ranges) { + // Collapse any zero-length range + // Collapse neighbouring same-type parts into a single part + for (let i = ranges.length - 1; i >= 0; --i) { + const part = ranges[i]; + const next = ranges[i + 1]; + if (part.zeroLength) { + ranges.splice(i, 1); + } + else if (next && next.isDash === part.isDash) { + next.left = part.left; + ranges.splice(i, 1); + } + } + // Combine the first and last parts if possible + const first = ranges[0]; + const last = ranges[ranges.length - 1]; + if (first.isDash === last.isDash) { + first.left = last.left - this.width; + last.right = first.right + this.width; + } + const index = this.width * this.nextRow; + let currIndex = 0; + let range = ranges[currIndex]; + for (let x = 0; x < this.width; x++) { + if (x / range.right > 1) { + range = ranges[++currIndex]; + } + const distLeft = Math.abs(x - range.left); + const distRight = Math.abs(x - range.right); + const minDist = Math.min(distLeft, distRight); + const signedDistance = range.isDash ? minDist : -minDist; + this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128)); + } + } + addDash(dasharray, round) { + const n = round ? 7 : 0; + const height = 2 * n + 1; + if (this.nextRow + height > this.height) { + performance$1.w('LineAtlas out of space'); + return null; + } + let length = 0; + for (let i = 0; i < dasharray.length; i++) { + length += dasharray[i]; + } + if (length !== 0) { + const stretch = this.width / length; + const ranges = this.getDashRanges(dasharray, this.width, stretch); + if (round) { + this.addRoundDash(ranges, stretch, n); + } + else { + this.addRegularDash(ranges); + } + } + const dashEntry = { + y: (this.nextRow + n + 0.5) / this.height, + height: 2 * n / this.height, + width: length + }; + this.nextRow += height; + this.dirty = true; + return dashEntry; + } + bind(context) { + const gl = context.gl; + if (!this.texture) { + this.texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, this.width, this.height, 0, gl.ALPHA, gl.UNSIGNED_BYTE, this.data); + } + else { + gl.bindTexture(gl.TEXTURE_2D, this.texture); + if (this.dirty) { + this.dirty = false; + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.width, this.height, gl.ALPHA, gl.UNSIGNED_BYTE, this.data); + } + } + } +} + +function workerFactory() { + return new Worker(performance$1.a.WORKER_URL); +} + +const PRELOAD_POOL_ID = 'maplibre_preloaded_worker_pool'; +/** + * Constructs a worker pool. + */ +class WorkerPool { + constructor() { + this.active = {}; + } + acquire(mapId) { + if (!this.workers) { + // Lazily look up the value of getWorkerCount so that + // client code has had a chance to set it. + this.workers = []; + while (this.workers.length < WorkerPool.workerCount) { + this.workers.push(workerFactory()); + } + } + this.active[mapId] = true; + return this.workers.slice(); + } + release(mapId) { + delete this.active[mapId]; + if (this.numActive() === 0) { + this.workers.forEach((w) => { + w.terminate(); + }); + this.workers = null; + } + } + isPreloaded() { + return !!this.active[PRELOAD_POOL_ID]; + } + numActive() { + return Object.keys(this.active).length; + } +} +// Based on results from A/B testing: https://github.com/maplibre/maplibre-gl-js/pull/2354 +const availableLogicalProcessors = Math.floor(browser.hardwareConcurrency / 2); +WorkerPool.workerCount = performance$1.C(globalThis) ? Math.max(Math.min(availableLogicalProcessors, 3), 1) : 1; + +let globalWorkerPool; +/** + * Creates (if necessary) and returns the single, global WorkerPool instance + * to be shared across each Map + */ +function getGlobalWorkerPool() { + if (!globalWorkerPool) { + globalWorkerPool = new WorkerPool(); + } + return globalWorkerPool; +} +/** + * Initializes resources like WebWorkers that can be shared across maps to lower load + * times in some situations. `setWorkerUrl()` and `setWorkerCount()`, if being + * used, must be set before `prewarm()` is called to have an effect. + * + * By default, the lifecycle of these resources is managed automatically, and they are + * lazily initialized when a Map is first created. By invoking `prewarm()`, these + * resources will be created ahead of time, and will not be cleared when the last Map + * is removed from the page. This allows them to be re-used by new Map instances that + * are created later. They can be manually cleared by calling + * `clearPrewarmedResources()`. This is only necessary if your web page remains + * active but stops using maps altogether. + * + * This is primarily useful when using GL-JS maps in a single page app, wherein a user + * would navigate between various views that can cause Map instances to constantly be + * created and destroyed. + * + * @example + * ```ts + * prewarm() + * ``` + */ +function prewarm() { + const workerPool = getGlobalWorkerPool(); + workerPool.acquire(PRELOAD_POOL_ID); +} +/** + * Clears up resources that have previously been created by `prewarm()`. + * Note that this is typically not necessary. You should only call this function + * if you expect the user of your app to not return to a Map view at any point + * in your application. + * + * @example + * ```ts + * clearPrewarmedResources() + * ``` + */ +function clearPrewarmedResources() { + const pool = globalWorkerPool; + if (pool) { + // Remove the pool only if all maps that referenced the preloaded global worker pool have been removed. + if (pool.isPreloaded() && pool.numActive() === 1) { + pool.release(PRELOAD_POOL_ID); + globalWorkerPool = null; + } + else { + 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()'); + } + } +} + +/** + * Responsible for sending messages from a {@link Source} to an associated + * {@link WorkerSource}. + */ +class Dispatcher { + constructor(workerPool, mapId) { + this.workerPool = workerPool; + this.actors = []; + this.currentActor = 0; + this.id = mapId; + const workers = this.workerPool.acquire(mapId); + for (let i = 0; i < workers.length; i++) { + const worker = workers[i]; + const actor = new performance$1.F(worker, mapId); + actor.name = `Worker ${i}`; + this.actors.push(actor); + } + if (!this.actors.length) + throw new Error('No actors found'); + } + /** + * Broadcast a message to all Workers. + */ + broadcast(type, data) { + const promises = []; + for (const actor of this.actors) { + promises.push(actor.sendAsync({ type, data })); + } + return Promise.all(promises); + } + /** + * Acquires an actor to dispatch messages to. The actors are distributed in round-robin fashion. + * @returns An actor object backed by a web worker for processing messages. + */ + getActor() { + this.currentActor = (this.currentActor + 1) % this.actors.length; + return this.actors[this.currentActor]; + } + remove(mapRemoved = true) { + this.actors.forEach((actor) => { actor.remove(); }); + this.actors = []; + if (mapRemoved) + this.workerPool.release(this.id); + } + registerMessageHandler(type, handler) { + for (const actor of this.actors) { + actor.registerMessageHandler(type, handler); + } + } +} +let globalDispatcher; +function getGlobalDispatcher() { + if (!globalDispatcher) { + globalDispatcher = new Dispatcher(getGlobalWorkerPool(), performance$1.G); + globalDispatcher.registerMessageHandler("GR" /* MessageType.getResource */, (_mapId, params, abortController) => { + return performance$1.m(params, abortController); + }); + } + return globalDispatcher; +} + +/* + * Returns a matrix that can be used to convert from tile coordinates to viewport pixel coordinates. + */ +function getPixelPosMatrix(transform, tileID) { + const t = performance$1.H(); + performance$1.J(t, t, [1, 1, 0]); + performance$1.K(t, t, [transform.width * 0.5, transform.height * 0.5, 1]); + return performance$1.L(t, t, transform.calculatePosMatrix(tileID.toUnwrapped())); +} +function queryIncludes3DLayer(layers, styleLayers, sourceID) { + if (layers) { + for (const layerID of layers) { + const layer = styleLayers[layerID]; + if (layer && layer.source === sourceID && layer.type === 'fill-extrusion') { + return true; + } + } + } + else { + for (const key in styleLayers) { + const layer = styleLayers[key]; + if (layer.source === sourceID && layer.type === 'fill-extrusion') { + return true; + } + } + } + return false; +} +function queryRenderedFeatures(sourceCache, styleLayers, serializedLayers, queryGeometry, params, transform) { + const has3DLayer = queryIncludes3DLayer(params && params.layers, styleLayers, sourceCache.id); + const maxPitchScaleFactor = transform.maxPitchScaleFactor(); + const tilesIn = sourceCache.tilesIn(queryGeometry, maxPitchScaleFactor, has3DLayer); + tilesIn.sort(sortTilesIn); + const renderedFeatureLayers = []; + for (const tileIn of tilesIn) { + renderedFeatureLayers.push({ + wrappedTileID: tileIn.tileID.wrapped().key, + queryResults: tileIn.tile.queryRenderedFeatures(styleLayers, serializedLayers, sourceCache._state, tileIn.queryGeometry, tileIn.cameraQueryGeometry, tileIn.scale, params, transform, maxPitchScaleFactor, getPixelPosMatrix(sourceCache.transform, tileIn.tileID)) + }); + } + const result = mergeRenderedFeatureLayers(renderedFeatureLayers); + // Merge state from SourceCache into the results + for (const layerID in result) { + result[layerID].forEach((featureWrapper) => { + const feature = featureWrapper.feature; + const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id); + feature.source = feature.layer.source; + if (feature.layer['source-layer']) { + feature.sourceLayer = feature.layer['source-layer']; + } + feature.state = state; + }); + } + return result; +} +function queryRenderedSymbols(styleLayers, serializedLayers, sourceCaches, queryGeometry, params, collisionIndex, retainedQueryData) { + const result = {}; + const renderedSymbols = collisionIndex.queryRenderedSymbols(queryGeometry); + const bucketQueryData = []; + for (const bucketInstanceId of Object.keys(renderedSymbols).map(Number)) { + bucketQueryData.push(retainedQueryData[bucketInstanceId]); + } + bucketQueryData.sort(sortTilesIn); + for (const queryData of bucketQueryData) { + const bucketSymbols = queryData.featureIndex.lookupSymbolFeatures(renderedSymbols[queryData.bucketInstanceId], serializedLayers, queryData.bucketIndex, queryData.sourceLayerIndex, params.filter, params.layers, params.availableImages, styleLayers); + for (const layerID in bucketSymbols) { + const resultFeatures = result[layerID] = result[layerID] || []; + const layerSymbols = bucketSymbols[layerID]; + layerSymbols.sort((a, b) => { + // Match topDownFeatureComparator from FeatureIndex, but using + // most recent sorting of features from bucket.sortFeatures + const featureSortOrder = queryData.featureSortOrder; + if (featureSortOrder) { + // queryRenderedSymbols documentation says we'll return features in + // "top-to-bottom" rendering order (aka last-to-first). + // Actually there can be multiple symbol instances per feature, so + // we sort each feature based on the first matching symbol instance. + const sortedA = featureSortOrder.indexOf(a.featureIndex); + const sortedB = featureSortOrder.indexOf(b.featureIndex); + return sortedB - sortedA; + } + else { + // Bucket hasn't been re-sorted based on angle, so use the + // reverse of the order the features appeared in the data. + return b.featureIndex - a.featureIndex; + } + }); + for (const symbolFeature of layerSymbols) { + resultFeatures.push(symbolFeature); + } + } + } + // Merge state from SourceCache into the results + for (const layerName in result) { + result[layerName].forEach((featureWrapper) => { + const feature = featureWrapper.feature; + const layer = styleLayers[layerName]; + const sourceCache = sourceCaches[layer.source]; + const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id); + feature.source = feature.layer.source; + if (feature.layer['source-layer']) { + feature.sourceLayer = feature.layer['source-layer']; + } + feature.state = state; + }); + } + return result; +} +function querySourceFeatures(sourceCache, params) { + const tiles = sourceCache.getRenderableIds().map((id) => { + return sourceCache.getTileByID(id); + }); + const result = []; + const dataTiles = {}; + for (let i = 0; i < tiles.length; i++) { + const tile = tiles[i]; + const dataID = tile.tileID.canonical.key; + if (!dataTiles[dataID]) { + dataTiles[dataID] = true; + tile.querySourceFeatures(result, params); + } + } + return result; +} +function sortTilesIn(a, b) { + const idA = a.tileID; + const idB = b.tileID; + return (idA.overscaledZ - idB.overscaledZ) || (idA.canonical.y - idB.canonical.y) || (idA.wrap - idB.wrap) || (idA.canonical.x - idB.canonical.x); +} +function mergeRenderedFeatureLayers(tiles) { + // Merge results from all tiles, but if two tiles share the same + // wrapped ID, don't duplicate features between the two tiles + const result = {}; + const wrappedIDLayerMap = {}; + for (const tile of tiles) { + const queryResults = tile.queryResults; + const wrappedID = tile.wrappedTileID; + const wrappedIDLayers = wrappedIDLayerMap[wrappedID] = wrappedIDLayerMap[wrappedID] || {}; + for (const layerID in queryResults) { + const tileFeatures = queryResults[layerID]; + const wrappedIDFeatures = wrappedIDLayers[layerID] = wrappedIDLayers[layerID] || {}; + const resultFeatures = result[layerID] = result[layerID] || []; + for (const tileFeature of tileFeatures) { + if (!wrappedIDFeatures[tileFeature.featureIndex]) { + wrappedIDFeatures[tileFeature.featureIndex] = true; + resultFeatures.push(tileFeature); + } + } + } + } + return result; +} + +function loadTileJson(options, requestManager, abortController) { + return performance$1._(this, void 0, void 0, function* () { + let tileJSON = options; + if (options.url) { + const response = yield performance$1.h(requestManager.transformRequest(options.url, "Source" /* ResourceType.Source */), abortController); + tileJSON = response.data; + } + else { + yield browser.frameAsync(abortController); + } + if (!tileJSON) { + return null; + } + const result = performance$1.M( + // explicit source options take precedence over TileJSON + performance$1.e(tileJSON, options), ['tiles', 'minzoom', 'maxzoom', 'attribution', 'bounds', 'scheme', 'tileSize', 'encoding']); + if ('vector_layers' in tileJSON && tileJSON.vector_layers) { + result.vectorLayerIds = tileJSON.vector_layers.map((layer) => { return layer.id; }); + } + return result; + }); +} + +/** + * A `LngLatBounds` object represents a geographical bounding box, + * defined by its southwest and northeast points in longitude and latitude. + * + * If no arguments are provided to the constructor, a `null` bounding box is created. + * + * Note that any Mapbox GL method that accepts a `LngLatBounds` object as an argument or option + * can also accept an `Array` of two {@link LngLatLike} constructs and will perform an implicit conversion. + * This flexible type is documented as {@link LngLatBoundsLike}. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let sw = new LngLat(-73.9876, 40.7661); + * let ne = new LngLat(-73.9397, 40.8002); + * let llb = new LngLatBounds(sw, ne); + * ``` + */ +class LngLatBounds { + /** + * @param sw - The southwest corner of the bounding box. + * OR array of 4 numbers in the order of west, south, east, north + * OR array of 2 LngLatLike: [sw,ne] + * @param ne - The northeast corner of the bounding box. + * @example + * ```ts + * let sw = new LngLat(-73.9876, 40.7661); + * let ne = new LngLat(-73.9397, 40.8002); + * let llb = new LngLatBounds(sw, ne); + * ``` + * OR + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661, -73.9397, 40.8002]); + * ``` + * OR + * ```ts + * let llb = new LngLatBounds([sw, ne]); + * ``` + */ + constructor(sw, ne) { + if (!sw) ; + else if (ne) { + this.setSouthWest(sw).setNorthEast(ne); + } + else if (Array.isArray(sw)) { + if (sw.length === 4) { + // 4 element array: west, south, east, north + this.setSouthWest([sw[0], sw[1]]).setNorthEast([sw[2], sw[3]]); + } + else { + this.setSouthWest(sw[0]).setNorthEast(sw[1]); + } + } + } + /** + * Set the northeast corner of the bounding box + * + * @param ne - a {@link LngLatLike} object describing the northeast corner of the bounding box. + */ + setNorthEast(ne) { + this._ne = ne instanceof performance$1.N ? new performance$1.N(ne.lng, ne.lat) : performance$1.N.convert(ne); + return this; + } + /** + * Set the southwest corner of the bounding box + * + * @param sw - a {@link LngLatLike} object describing the southwest corner of the bounding box. + */ + setSouthWest(sw) { + this._sw = sw instanceof performance$1.N ? new performance$1.N(sw.lng, sw.lat) : performance$1.N.convert(sw); + return this; + } + /** + * Extend the bounds to include a given LngLatLike or LngLatBoundsLike. + * + * @param obj - object to extend to + */ + extend(obj) { + const sw = this._sw, ne = this._ne; + let sw2, ne2; + if (obj instanceof performance$1.N) { + sw2 = obj; + ne2 = obj; + } + else if (obj instanceof LngLatBounds) { + sw2 = obj._sw; + ne2 = obj._ne; + if (!sw2 || !ne2) + return this; + } + else { + if (Array.isArray(obj)) { + if (obj.length === 4 || obj.every(Array.isArray)) { + const lngLatBoundsObj = obj; + return this.extend(LngLatBounds.convert(lngLatBoundsObj)); + } + else { + const lngLatObj = obj; + return this.extend(performance$1.N.convert(lngLatObj)); + } + } + else if (obj && ('lng' in obj || 'lon' in obj) && 'lat' in obj) { + return this.extend(performance$1.N.convert(obj)); + } + return this; + } + if (!sw && !ne) { + this._sw = new performance$1.N(sw2.lng, sw2.lat); + this._ne = new performance$1.N(ne2.lng, ne2.lat); + } + else { + sw.lng = Math.min(sw2.lng, sw.lng); + sw.lat = Math.min(sw2.lat, sw.lat); + ne.lng = Math.max(ne2.lng, ne.lng); + ne.lat = Math.max(ne2.lat, ne.lat); + } + return this; + } + /** + * Returns the geographical coordinate equidistant from the bounding box's corners. + * + * @returns The bounding box's center. + * @example + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]); + * llb.getCenter(); // = LngLat {lng: -73.96365, lat: 40.78315} + * ``` + */ + getCenter() { + return new performance$1.N((this._sw.lng + this._ne.lng) / 2, (this._sw.lat + this._ne.lat) / 2); + } + /** + * Returns the southwest corner of the bounding box. + * + * @returns The southwest corner of the bounding box. + */ + getSouthWest() { return this._sw; } + /** + * Returns the northeast corner of the bounding box. + * + * @returns The northeast corner of the bounding box. + */ + getNorthEast() { return this._ne; } + /** + * Returns the northwest corner of the bounding box. + * + * @returns The northwest corner of the bounding box. + */ + getNorthWest() { return new performance$1.N(this.getWest(), this.getNorth()); } + /** + * Returns the southeast corner of the bounding box. + * + * @returns The southeast corner of the bounding box. + */ + getSouthEast() { return new performance$1.N(this.getEast(), this.getSouth()); } + /** + * Returns the west edge of the bounding box. + * + * @returns The west edge of the bounding box. + */ + getWest() { return this._sw.lng; } + /** + * Returns the south edge of the bounding box. + * + * @returns The south edge of the bounding box. + */ + getSouth() { return this._sw.lat; } + /** + * Returns the east edge of the bounding box. + * + * @returns The east edge of the bounding box. + */ + getEast() { return this._ne.lng; } + /** + * Returns the north edge of the bounding box. + * + * @returns The north edge of the bounding box. + */ + getNorth() { return this._ne.lat; } + /** + * Returns the bounding box represented as an array. + * + * @returns The bounding box represented as an array, consisting of the + * southwest and northeast coordinates of the bounding represented as arrays of numbers. + * @example + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]); + * llb.toArray(); // = [[-73.9876, 40.7661], [-73.9397, 40.8002]] + * ``` + */ + toArray() { + return [this._sw.toArray(), this._ne.toArray()]; + } + /** + * Return the bounding box represented as a string. + * + * @returns The bounding box represents as a string of the format + * `'LngLatBounds(LngLat(lng, lat), LngLat(lng, lat))'`. + * @example + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]); + * llb.toString(); // = "LngLatBounds(LngLat(-73.9876, 40.7661), LngLat(-73.9397, 40.8002))" + * ``` + */ + toString() { + return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`; + } + /** + * Check if the bounding box is an empty/`null`-type box. + * + * @returns True if bounds have been defined, otherwise false. + */ + isEmpty() { + return !(this._sw && this._ne); + } + /** + * Check if the point is within the bounding box. + * + * @param lnglat - geographic point to check against. + * @returns `true` if the point is within the bounding box. + * @example + * ```ts + * let llb = new LngLatBounds( + * new LngLat(-73.9876, 40.7661), + * new LngLat(-73.9397, 40.8002) + * ); + * + * let ll = new LngLat(-73.9567, 40.7789); + * + * console.log(llb.contains(ll)); // = true + * ``` + */ + contains(lnglat) { + const { lng, lat } = performance$1.N.convert(lnglat); + const containsLatitude = this._sw.lat <= lat && lat <= this._ne.lat; + let containsLongitude = this._sw.lng <= lng && lng <= this._ne.lng; + if (this._sw.lng > this._ne.lng) { // wrapped coordinates + containsLongitude = this._sw.lng >= lng && lng >= this._ne.lng; + } + return containsLatitude && containsLongitude; + } + /** + * Converts an array to a `LngLatBounds` object. + * + * If a `LngLatBounds` object is passed in, the function returns it unchanged. + * + * Internally, the function calls `LngLat#convert` to convert arrays to `LngLat` values. + * + * @param input - An array of two coordinates to convert, or a `LngLatBounds` object to return. + * @returns A new `LngLatBounds` object, if a conversion occurred, or the original `LngLatBounds` object. + * @example + * ```ts + * let arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]]; + * let llb = LngLatBounds.convert(arr); // = LngLatBounds {_sw: LngLat {lng: -73.9876, lat: 40.7661}, _ne: LngLat {lng: -73.9397, lat: 40.8002}} + * ``` + */ + static convert(input) { + if (input instanceof LngLatBounds) + return input; + if (!input) + return input; + return new LngLatBounds(input); + } + /** + * Returns a `LngLatBounds` from the coordinates extended by a given `radius`. The returned `LngLatBounds` completely contains the `radius`. + * + * @param center - center coordinates of the new bounds. + * @param radius - Distance in meters from the coordinates to extend the bounds. + * @returns A new `LngLatBounds` object representing the coordinates extended by the `radius`. + * @example + * ```ts + * let center = new LngLat(-73.9749, 40.7736); + * LngLatBounds.fromLngLat(100).toArray(); // = [[-73.97501862141328, 40.77351016847229], [-73.97478137858673, 40.77368983152771]] + * ``` + */ + static fromLngLat(center, radius = 0) { + const earthCircumferenceInMetersAtEquator = 40075017; + const latAccuracy = 360 * radius / earthCircumferenceInMetersAtEquator, lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * center.lat); + return new LngLatBounds(new performance$1.N(center.lng - lngAccuracy, center.lat - latAccuracy), new performance$1.N(center.lng + lngAccuracy, center.lat + latAccuracy)); + } + /** + * Adjusts the given bounds to handle the case where the bounds cross the 180th meridian (antimeridian). + * + * @returns The adjusted LngLatBounds + * @example + * ```ts + * let bounds = new LngLatBounds([175.813127, -20.157768], [-178. 340903, -15.449124]); + * let adjustedBounds = bounds.adjustAntiMeridian(); + * // adjustedBounds will be: [[175.813127, -20.157768], [181.659097, -15.449124]] + * ``` + */ + adjustAntiMeridian() { + const sw = new performance$1.N(this._sw.lng, this._sw.lat); + const ne = new performance$1.N(this._ne.lng, this._ne.lat); + if (sw.lng > ne.lng) { + return new LngLatBounds(sw, new performance$1.N(ne.lng + 360, ne.lat)); + } + return new LngLatBounds(sw, ne); + } +} + +class TileBounds { + constructor(bounds, minzoom, maxzoom) { + this.bounds = LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + } + validateBounds(bounds) { + // make sure the bounds property contains valid longitude and latitudes + if (!Array.isArray(bounds) || bounds.length !== 4) + return [-180, -90, 180, 90]; + return [Math.max(-180, bounds[0]), Math.max(-90, bounds[1]), Math.min(180, bounds[2]), Math.min(90, bounds[3])]; + } + contains(tileID) { + const worldSize = Math.pow(2, tileID.z); + const level = { + minX: Math.floor(performance$1.O(this.bounds.getWest()) * worldSize), + minY: Math.floor(performance$1.Q(this.bounds.getNorth()) * worldSize), + maxX: Math.ceil(performance$1.O(this.bounds.getEast()) * worldSize), + maxY: Math.ceil(performance$1.Q(this.bounds.getSouth()) * worldSize) + }; + const hit = tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY; + return hit; + } +} + +/** + * A source containing vector tiles in [Mapbox Vector Tile format](https://docs.mapbox.com/vector-tiles/reference/). + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'vector', + * url: 'https://demotiles.maplibre.org/tiles/tiles.json' + * }); + * ``` + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'vector', + * tiles: ['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt'], + * minzoom: 6, + * maxzoom: 14 + * }); + * ``` + * + * @example + * ```ts + * map.getSource('some id').setUrl("https://demotiles.maplibre.org/tiles/tiles.json"); + * ``` + * + * @example + * ```ts + * map.getSource('some id').setTiles(['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt']); + * ``` + * @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/vector-source/) + */ +class VectorTileSource extends performance$1.E { + constructor(id, options, dispatcher, eventedParent) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.type = 'vector'; + this.minzoom = 0; + this.maxzoom = 22; + this.scheme = 'xyz'; + this.tileSize = 512; + this.reparseOverscaled = true; + this.isTileClipped = true; + this._loaded = false; + performance$1.e(this, performance$1.M(options, ['url', 'scheme', 'tileSize', 'promoteId'])); + this._options = performance$1.e({ type: 'vector' }, options); + this._collectResourceTiming = options.collectResourceTiming; + if (this.tileSize !== 512) { + throw new Error('vector tile sources must have a tileSize of 512'); + } + this.setEventedParent(eventedParent); + } + load() { + return performance$1._(this, void 0, void 0, function* () { + this._loaded = false; + this.fire(new performance$1.k('dataloading', { dataType: 'source' })); + this._tileJSONRequest = new AbortController(); + try { + const tileJSON = yield loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest); + this._tileJSONRequest = null; + this._loaded = true; + this.map.style.sourceCaches[this.id].clearTiles(); + if (tileJSON) { + performance$1.e(this, tileJSON); + if (tileJSON.bounds) + this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom); + // `content` is included here to prevent a race condition where `Style#_updateSources` is called + // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives + // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088 + this.fire(new performance$1.k('data', { dataType: 'source', sourceDataType: 'metadata' })); + this.fire(new performance$1.k('data', { dataType: 'source', sourceDataType: 'content' })); + } + } + catch (err) { + this._tileJSONRequest = null; + this.fire(new performance$1.j(err)); + } + }); + } + loaded() { + return this._loaded; + } + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + onAdd(map) { + this.map = map; + this.load(); + } + setSourceProperty(callback) { + if (this._tileJSONRequest) { + this._tileJSONRequest.abort(); + } + callback(); + this.load(); + } + /** + * Sets the source `tiles` property and re-renders the map. + * + * @param tiles - An array of one or more tile source URLs, as in the TileJSON spec. + */ + setTiles(tiles) { + this.setSourceProperty(() => { + this._options.tiles = tiles; + }); + return this; + } + /** + * Sets the source `url` property and re-renders the map. + * + * @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`. + */ + setUrl(url) { + this.setSourceProperty(() => { + this.url = url; + this._options.url = url; + }); + return this; + } + onRemove() { + if (this._tileJSONRequest) { + this._tileJSONRequest.abort(); + this._tileJSONRequest = null; + } + } + serialize() { + return performance$1.e({}, this._options); + } + loadTile(tile) { + return performance$1._(this, void 0, void 0, function* () { + const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme); + const params = { + request: this.map._requestManager.transformRequest(url, "Tile" /* ResourceType.Tile */), + uid: tile.uid, + tileID: tile.tileID, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: this.type, + source: this.id, + pixelRatio: this.map.getPixelRatio(), + showCollisionBoxes: this.map.showCollisionBoxes, + promoteId: this.promoteId + }; + params.request.collectResourceTiming = this._collectResourceTiming; + let messageType = "RT" /* MessageType.reloadTile */; + if (!tile.actor || tile.state === 'expired') { + tile.actor = this.dispatcher.getActor(); + messageType = "LT" /* MessageType.loadTile */; + } + else if (tile.state === 'loading') { + return new Promise((resolve, reject) => { + tile.reloadPromise = { resolve, reject }; + }); + } + tile.abortController = new AbortController(); + try { + const data = yield tile.actor.sendAsync({ type: messageType, data: params }, tile.abortController); + delete tile.abortController; + if (tile.aborted) { + return; + } + this._afterTileLoadWorkerResponse(tile, data); + } + catch (err) { + delete tile.abortController; + if (tile.aborted) { + return; + } + if (err && err.status !== 404) { + throw err; + } + this._afterTileLoadWorkerResponse(tile, null); + } + }); + } + _afterTileLoadWorkerResponse(tile, data) { + if (data && data.resourceTiming) { + tile.resourceTiming = data.resourceTiming; + } + if (data && this.map._refreshExpiredTiles) { + tile.setExpiryData(data); + } + tile.loadVectorData(data, this.map.painter); + if (tile.reloadPromise) { + const reloadPromise = tile.reloadPromise; + tile.reloadPromise = null; + this.loadTile(tile).then(reloadPromise.resolve).catch(reloadPromise.reject); + } + } + abortTile(tile) { + return performance$1._(this, void 0, void 0, function* () { + if (tile.abortController) { + tile.abortController.abort(); + delete tile.abortController; + } + if (tile.actor) { + yield tile.actor.sendAsync({ + type: "AT" /* MessageType.abortTile */, + data: { uid: tile.uid, type: this.type, source: this.id } + }); + } + }); + } + unloadTile(tile) { + return performance$1._(this, void 0, void 0, function* () { + tile.unloadVectorData(); + if (tile.actor) { + yield tile.actor.sendAsync({ + type: "RMT" /* MessageType.removeTile */, + data: { + uid: tile.uid, + type: this.type, + source: this.id + } + }); + } + }); + } + hasTransition() { + return false; + } +} + +/** + * A source containing raster tiles (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * map.addSource('raster-source', { + * 'type': 'raster', + * 'tiles': ['https://tiles.stadiamaps.com/tiles/stamen_watercolor/{z}/{x}/{y}.jpg'], + * 'tileSize': 256, + * }); + * ``` + * + * @example + * ```ts + * map.addSource('wms-test-source', { + * 'type': 'raster', + * // use the tiles option to specify a WMS tile source URL + * 'tiles': [ + * 'https://img.nj.gov/imagerywms/Natural2015?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&transparent=true&width=256&height=256&layers=Natural2015' + * ], + * 'tileSize': 256 + * }); + * ``` + * @see [Add a raster tile source](https://maplibre.org/maplibre-gl-js/docs/examples/map-tiles/) + * @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/wms/) + * @see [Display a satellite map](https://maplibre.org/maplibre-gl-js/docs/examples/satellite-map/) + */ +class RasterTileSource extends performance$1.E { + constructor(id, options, dispatcher, eventedParent) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.setEventedParent(eventedParent); + this.type = 'raster'; + this.minzoom = 0; + this.maxzoom = 22; + this.roundZoom = true; + this.scheme = 'xyz'; + this.tileSize = 512; + this._loaded = false; + this._options = performance$1.e({ type: 'raster' }, options); + performance$1.e(this, performance$1.M(options, ['url', 'scheme', 'tileSize'])); + } + load() { + return performance$1._(this, void 0, void 0, function* () { + this._loaded = false; + this.fire(new performance$1.k('dataloading', { dataType: 'source' })); + this._tileJSONRequest = new AbortController(); + try { + const tileJSON = yield loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest); + this._tileJSONRequest = null; + this._loaded = true; + if (tileJSON) { + performance$1.e(this, tileJSON); + if (tileJSON.bounds) + this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom); + // `content` is included here to prevent a race condition where `Style#_updateSources` is called + // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives + // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088 + this.fire(new performance$1.k('data', { dataType: 'source', sourceDataType: 'metadata' })); + this.fire(new performance$1.k('data', { dataType: 'source', sourceDataType: 'content' })); + } + } + catch (err) { + this._tileJSONRequest = null; + this.fire(new performance$1.j(err)); + } + }); + } + loaded() { + return this._loaded; + } + onAdd(map) { + this.map = map; + this.load(); + } + onRemove() { + if (this._tileJSONRequest) { + this._tileJSONRequest.abort(); + this._tileJSONRequest = null; + } + } + setSourceProperty(callback) { + if (this._tileJSONRequest) { + this._tileJSONRequest.abort(); + this._tileJSONRequest = null; + } + callback(); + this.load(); + } + /** + * Sets the source `tiles` property and re-renders the map. + * + * @param tiles - An array of one or more tile source URLs, as in the raster tiles spec (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) + */ + setTiles(tiles) { + this.setSourceProperty(() => { + this._options.tiles = tiles; + }); + return this; + } + /** + * Sets the source `url` property and re-renders the map. + * + * @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`. + */ + setUrl(url) { + this.setSourceProperty(() => { + this.url = url; + this._options.url = url; + }); + return this; + } + serialize() { + return performance$1.e({}, this._options); + } + hasTile(tileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + loadTile(tile) { + return performance$1._(this, void 0, void 0, function* () { + const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme); + tile.abortController = new AbortController(); + try { + const response = yield ImageRequest.getImage(this.map._requestManager.transformRequest(url, "Tile" /* ResourceType.Tile */), tile.abortController, this.map._refreshExpiredTiles); + delete tile.abortController; + if (tile.aborted) { + tile.state = 'unloaded'; + return; + } + if (response && response.data) { + if (this.map._refreshExpiredTiles && response.cacheControl && response.expires) { + tile.setExpiryData({ cacheControl: response.cacheControl, expires: response.expires }); + } + const context = this.map.painter.context; + const gl = context.gl; + const img = response.data; + tile.texture = this.map.painter.getTileTexture(img.width); + if (tile.texture) { + tile.texture.update(img, { useMipmap: true }); + } + else { + tile.texture = new Texture(context, img, gl.RGBA, { useMipmap: true }); + tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST); + } + tile.state = 'loaded'; + } + } + catch (err) { + delete tile.abortController; + if (tile.aborted) { + tile.state = 'unloaded'; + } + else if (err) { + tile.state = 'errored'; + throw err; + } + } + }); + } + abortTile(tile) { + return performance$1._(this, void 0, void 0, function* () { + if (tile.abortController) { + tile.abortController.abort(); + delete tile.abortController; + } + }); + } + unloadTile(tile) { + return performance$1._(this, void 0, void 0, function* () { + if (tile.texture) { + this.map.painter.saveTileTexture(tile.texture); + } + }); + } + hasTransition() { + return false; + } +} + +/** + * A source containing raster DEM tiles (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.) + * This source can be used to show hillshading and 3D terrain + * + * @group Sources + * + * @example + * ```ts + * map.addSource('raster-dem-source', { + * type: 'raster-dem', + * url: 'https://demotiles.maplibre.org/terrain-tiles/tiles.json', + * tileSize: 256 + * }); + * ``` + * @see [3D Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/3d-terrain/) + */ +class RasterDEMTileSource extends RasterTileSource { + constructor(id, options, dispatcher, eventedParent) { + super(id, options, dispatcher, eventedParent); + this.type = 'raster-dem'; + this.maxzoom = 22; + this._options = performance$1.e({ type: 'raster-dem' }, options); + this.encoding = options.encoding || 'mapbox'; + this.redFactor = options.redFactor; + this.greenFactor = options.greenFactor; + this.blueFactor = options.blueFactor; + this.baseShift = options.baseShift; + } + loadTile(tile) { + return performance$1._(this, void 0, void 0, function* () { + const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme); + const request = this.map._requestManager.transformRequest(url, "Tile" /* ResourceType.Tile */); + tile.neighboringTiles = this._getNeighboringTiles(tile.tileID); + tile.abortController = new AbortController(); + try { + const response = yield ImageRequest.getImage(request, tile.abortController, this.map._refreshExpiredTiles); + delete tile.abortController; + if (tile.aborted) { + tile.state = 'unloaded'; + return; + } + if (response && response.data) { + const img = response.data; + if (this.map._refreshExpiredTiles && response.cacheControl && response.expires) { + tile.setExpiryData({ cacheControl: response.cacheControl, expires: response.expires }); + } + const transfer = performance$1.b(img) && performance$1.U(); + const rawImageData = transfer ? img : yield this.readImageNow(img); + const params = { + type: this.type, + uid: tile.uid, + source: this.id, + rawImageData, + encoding: this.encoding, + redFactor: this.redFactor, + greenFactor: this.greenFactor, + blueFactor: this.blueFactor, + baseShift: this.baseShift + }; + if (!tile.actor || tile.state === 'expired') { + tile.actor = this.dispatcher.getActor(); + /* eslint-disable require-atomic-updates */ + const data = yield tile.actor.sendAsync({ type: "LDT" /* MessageType.loadDEMTile */, data: params }); + tile.dem = data; + tile.needsHillshadePrepare = true; + tile.needsTerrainPrepare = true; + tile.state = 'loaded'; + /* eslint-enable require-atomic-updates */ + } + } + } + catch (err) { + delete tile.abortController; + if (tile.aborted) { + tile.state = 'unloaded'; + } + else if (err) { + tile.state = 'errored'; + throw err; + } + } + }); + } + readImageNow(img) { + return performance$1._(this, void 0, void 0, function* () { + if (typeof VideoFrame !== 'undefined' && performance$1.V()) { + const width = img.width + 2; + const height = img.height + 2; + try { + return new performance$1.R({ width, height }, yield performance$1.W(img, -1, -1, width, height)); + } + catch (e) { + // fall-back to browser canvas decoding + } + } + return browser.getImageData(img, 1); + }); + } + _getNeighboringTiles(tileID) { + const canonical = tileID.canonical; + const dim = Math.pow(2, canonical.z); + const px = (canonical.x - 1 + dim) % dim; + const pxw = canonical.x === 0 ? tileID.wrap - 1 : tileID.wrap; + const nx = (canonical.x + 1 + dim) % dim; + const nxw = canonical.x + 1 === dim ? tileID.wrap + 1 : tileID.wrap; + const neighboringTiles = {}; + // add adjacent tiles + neighboringTiles[new performance$1.S(tileID.overscaledZ, pxw, canonical.z, px, canonical.y).key] = { backfilled: false }; + neighboringTiles[new performance$1.S(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y).key] = { backfilled: false }; + // Add upper neighboringTiles + if (canonical.y > 0) { + neighboringTiles[new performance$1.S(tileID.overscaledZ, pxw, canonical.z, px, canonical.y - 1).key] = { backfilled: false }; + neighboringTiles[new performance$1.S(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y - 1).key] = { backfilled: false }; + neighboringTiles[new performance$1.S(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y - 1).key] = { backfilled: false }; + } + // Add lower neighboringTiles + if (canonical.y + 1 < dim) { + neighboringTiles[new performance$1.S(tileID.overscaledZ, pxw, canonical.z, px, canonical.y + 1).key] = { backfilled: false }; + neighboringTiles[new performance$1.S(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y + 1).key] = { backfilled: false }; + neighboringTiles[new performance$1.S(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y + 1).key] = { backfilled: false }; + } + return neighboringTiles; + } + unloadTile(tile) { + return performance$1._(this, void 0, void 0, function* () { + if (tile.demTexture) + this.map.painter.saveTileTexture(tile.demTexture); + if (tile.fbo) { + tile.fbo.destroy(); + delete tile.fbo; + } + if (tile.dem) + delete tile.dem; + delete tile.neighboringTiles; + tile.state = 'unloaded'; + if (tile.actor) { + yield tile.actor.sendAsync({ type: "RDT" /* MessageType.removeDEMTile */, data: { type: this.type, uid: tile.uid, source: this.id } }); + } + }); + } +} + +/** + * A source containing GeoJSON. + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-geojson) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'geojson', + * data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson' + * }); + * ``` + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'geojson', + * data: { + * "type": "FeatureCollection", + * "features": [{ + * "type": "Feature", + * "properties": {}, + * "geometry": { + * "type": "Point", + * "coordinates": [ + * -76.53063297271729, + * 39.18174077994108 + * ] + * } + * }] + * } + * }); + * ``` + * + * @example + * ```ts + * map.getSource('some id').setData({ + * "type": "FeatureCollection", + * "features": [{ + * "type": "Feature", + * "properties": { "name": "Null Island" }, + * "geometry": { + * "type": "Point", + * "coordinates": [ 0, 0 ] + * } + * }] + * }); + * ``` + * @see [Draw GeoJSON points](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-markers/) + * @see [Add a GeoJSON line](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-line/) + * @see [Create a heatmap from points](https://maplibre.org/maplibre-gl-js/docs/examples/heatmap-layer/) + * @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/cluster/) + */ +class GeoJSONSource extends performance$1.E { + /** @internal */ + constructor(id, options, dispatcher, eventedParent) { + super(); + this.id = id; + // `type` is a property rather than a constant to make it easy for 3rd + // parties to use GeoJSONSource to build their own source types. + this.type = 'geojson'; + this.minzoom = 0; + this.maxzoom = 18; + this.tileSize = 512; + this.isTileClipped = true; + this.reparseOverscaled = true; + this._removed = false; + this._pendingLoads = 0; + this.actor = dispatcher.getActor(); + this.setEventedParent(eventedParent); + this._data = options.data; + this._options = performance$1.e({}, options); + this._collectResourceTiming = options.collectResourceTiming; + if (options.maxzoom !== undefined) + this.maxzoom = options.maxzoom; + if (options.type) + this.type = options.type; + if (options.attribution) + this.attribution = options.attribution; + this.promoteId = options.promoteId; + const scale = performance$1.X / this.tileSize; + if (options.clusterMaxZoom !== undefined && this.maxzoom <= options.clusterMaxZoom) { + performance$1.w(`The maxzoom value "${this.maxzoom}" is expected to be greater than the clusterMaxZoom value "${options.clusterMaxZoom}".`); + } + // sent to the worker, along with `url: ...` or `data: literal geojson`, + // so that it can load/parse/index the geojson data + // extending with `options.workerOptions` helps to make it easy for + // third-party sources to hack/reuse GeoJSONSource. + this.workerOptions = performance$1.e({ + source: this.id, + cluster: options.cluster || false, + geojsonVtOptions: { + buffer: (options.buffer !== undefined ? options.buffer : 128) * scale, + tolerance: (options.tolerance !== undefined ? options.tolerance : 0.375) * scale, + extent: performance$1.X, + maxZoom: this.maxzoom, + lineMetrics: options.lineMetrics || false, + generateId: options.generateId || false + }, + superclusterOptions: { + maxZoom: options.clusterMaxZoom !== undefined ? options.clusterMaxZoom : this.maxzoom - 1, + minPoints: Math.max(2, options.clusterMinPoints || 2), + extent: performance$1.X, + radius: (options.clusterRadius || 50) * scale, + log: false, + generateId: options.generateId || false + }, + clusterProperties: options.clusterProperties, + filter: options.filter + }, options.workerOptions); + // send the promoteId to the worker to have more flexible updates, but only if it is a string + if (typeof this.promoteId === 'string') { + this.workerOptions.promoteId = this.promoteId; + } + } + load() { + return performance$1._(this, void 0, void 0, function* () { + yield this._updateWorkerData(); + }); + } + onAdd(map) { + this.map = map; + this.load(); + } + /** + * Sets the GeoJSON data and re-renders the map. + * + * @param data - A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files. + */ + setData(data) { + this._data = data; + this._updateWorkerData(); + return this; + } + /** + * Updates the source's GeoJSON, and re-renders the map. + * + * For sources with lots of features, this method can be used to make updates more quickly. + * + * This approach requires unique IDs for every feature in the source. The IDs can either be specified on the feature, + * or by using the promoteId option to specify which property should be used as the ID. + * + * It is an error to call updateData on a source that did not have unique IDs for each of its features already. + * + * Updates are applied on a best-effort basis, updating an ID that does not exist will not result in an error. + * + * @param diff - The changes that need to be applied. + */ + updateData(diff) { + this._updateWorkerData(diff); + return this; + } + /** + * Allows to get the source's actual GeoJSON data. + * + * @returns a promise which resolves to the source's actual GeoJSON data + */ + getData() { + return performance$1._(this, void 0, void 0, function* () { + const options = performance$1.e({ type: this.type }, this.workerOptions); + return this.actor.sendAsync({ type: "GD" /* MessageType.getData */, data: options }); + }); + } + /** + * To disable/enable clustering on the source options + * @param options - The options to set + * @example + * ```ts + * map.getSource('some id').setClusterOptions({cluster: false}); + * map.getSource('some id').setClusterOptions({cluster: false, clusterRadius: 50, clusterMaxZoom: 14}); + * ``` + */ + setClusterOptions(options) { + this.workerOptions.cluster = options.cluster; + if (options) { + if (options.clusterRadius !== undefined) + this.workerOptions.superclusterOptions.radius = options.clusterRadius; + if (options.clusterMaxZoom !== undefined) + this.workerOptions.superclusterOptions.maxZoom = options.clusterMaxZoom; + } + this._updateWorkerData(); + return this; + } + /** + * For clustered sources, fetches the zoom at which the given cluster expands. + * + * @param clusterId - The value of the cluster's `cluster_id` property. + * @returns a promise that is resolved with the zoom number + */ + getClusterExpansionZoom(clusterId) { + return this.actor.sendAsync({ type: "GCEZ" /* MessageType.getClusterExpansionZoom */, data: { type: this.type, clusterId, source: this.id } }); + } + /** + * For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features). + * + * @param clusterId - The value of the cluster's `cluster_id` property. + * @returns a promise that is resolved when the features are retrieved + */ + getClusterChildren(clusterId) { + return this.actor.sendAsync({ type: "GCC" /* MessageType.getClusterChildren */, data: { type: this.type, clusterId, source: this.id } }); + } + /** + * For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features). + * + * @param clusterId - The value of the cluster's `cluster_id` property. + * @param limit - The maximum number of features to return. + * @param offset - The number of features to skip (e.g. for pagination). + * @returns a promise that is resolved when the features are retrieved + * @example + * Retrieve cluster leaves on click + * ```ts + * map.on('click', 'clusters', (e) => { + * let features = map.queryRenderedFeatures(e.point, { + * layers: ['clusters'] + * }); + * + * let clusterId = features[0].properties.cluster_id; + * let pointCount = features[0].properties.point_count; + * let clusterSource = map.getSource('clusters'); + * + * const features = await clusterSource.getClusterLeaves(clusterId, pointCount); + * // Print cluster leaves in the console + * console.log('Cluster leaves:', features); + * }); + * ``` + */ + getClusterLeaves(clusterId, limit, offset) { + return this.actor.sendAsync({ type: "GCL" /* MessageType.getClusterLeaves */, data: { + type: this.type, + source: this.id, + clusterId, + limit, + offset + } }); + } + /** + * Responsible for invoking WorkerSource's geojson.loadData target, which + * handles loading the geojson data and preparing to serve it up as tiles, + * using geojson-vt or supercluster as appropriate. + * @param diff - the diff object + */ + _updateWorkerData(diff) { + return performance$1._(this, void 0, void 0, function* () { + const options = performance$1.e({ type: this.type }, this.workerOptions); + if (diff) { + options.dataDiff = diff; + } + else if (typeof this._data === 'string') { + options.request = this.map._requestManager.transformRequest(browser.resolveURL(this._data), "Source" /* ResourceType.Source */); + options.request.collectResourceTiming = this._collectResourceTiming; + } + else { + options.data = JSON.stringify(this._data); + } + this._pendingLoads++; + this.fire(new performance$1.k('dataloading', { dataType: 'source' })); + try { + const result = yield this.actor.sendAsync({ type: "LD" /* MessageType.loadData */, data: options }); + this._pendingLoads--; + if (this._removed || result.abandoned) { + this.fire(new performance$1.k('dataabort', { dataType: 'source' })); + return; + } + let resourceTiming = null; + if (result.resourceTiming && result.resourceTiming[this.id]) { + resourceTiming = result.resourceTiming[this.id].slice(0); + } + const data = { dataType: 'source' }; + if (this._collectResourceTiming && resourceTiming && resourceTiming.length > 0) { + performance$1.e(data, { resourceTiming }); + } + // although GeoJSON sources contain no metadata, we fire this event to let the SourceCache + // know its ok to start requesting tiles. + this.fire(new performance$1.k('data', Object.assign(Object.assign({}, data), { sourceDataType: 'metadata' }))); + this.fire(new performance$1.k('data', Object.assign(Object.assign({}, data), { sourceDataType: 'content' }))); + } + catch (err) { + this._pendingLoads--; + if (this._removed) { + this.fire(new performance$1.k('dataabort', { dataType: 'source' })); + return; + } + this.fire(new performance$1.j(err)); + } + }); + } + loaded() { + return this._pendingLoads === 0; + } + loadTile(tile) { + return performance$1._(this, void 0, void 0, function* () { + const message = !tile.actor ? "LT" /* MessageType.loadTile */ : "RT" /* MessageType.reloadTile */; + tile.actor = this.actor; + const params = { + type: this.type, + uid: tile.uid, + tileID: tile.tileID, + zoom: tile.tileID.overscaledZ, + maxZoom: this.maxzoom, + tileSize: this.tileSize, + source: this.id, + pixelRatio: this.map.getPixelRatio(), + showCollisionBoxes: this.map.showCollisionBoxes, + promoteId: this.promoteId + }; + tile.abortController = new AbortController(); + const data = yield this.actor.sendAsync({ type: message, data: params }, tile.abortController); + delete tile.abortController; + tile.unloadVectorData(); + if (!tile.aborted) { + tile.loadVectorData(data, this.map.painter, message === "RT" /* MessageType.reloadTile */); + } + }); + } + abortTile(tile) { + return performance$1._(this, void 0, void 0, function* () { + if (tile.abortController) { + tile.abortController.abort(); + delete tile.abortController; + } + tile.aborted = true; + }); + } + unloadTile(tile) { + return performance$1._(this, void 0, void 0, function* () { + tile.unloadVectorData(); + yield this.actor.sendAsync({ type: "RMT" /* MessageType.removeTile */, data: { uid: tile.uid, type: this.type, source: this.id } }); + }); + } + onRemove() { + this._removed = true; + this.actor.sendAsync({ type: "RS" /* MessageType.removeSource */, data: { type: this.type, source: this.id } }); + } + serialize() { + return performance$1.e({}, this._options, { + type: this.type, + data: this._data + }); + } + hasTransition() { + return false; + } +} + +var rasterBoundsAttributes = performance$1.Y([ + { name: 'a_pos', type: 'Int16', components: 2 }, + { name: 'a_texture_pos', type: 'Int16', components: 2 } +]); + +/** + * A data source containing an image. + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-image) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * // add to map + * map.addSource('some id', { + * type: 'image', + * url: 'https://www.maplibre.org/images/foo.png', + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update coordinates + * let mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * // update url and coordinates simultaneously + * mySource.updateImage({ + * url: 'https://www.maplibre.org/images/bar.png', + * coordinates: [ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ] + * }) + * + * map.removeSource('some id'); // remove + * ``` + */ +class ImageSource extends performance$1.E { + /** @internal */ + constructor(id, options, dispatcher, eventedParent) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.coordinates = options.coordinates; + this.type = 'image'; + this.minzoom = 0; + this.maxzoom = 22; + this.tileSize = 512; + this.tiles = {}; + this._loaded = false; + this.setEventedParent(eventedParent); + this.options = options; + } + load(newCoordinates) { + return performance$1._(this, void 0, void 0, function* () { + this._loaded = false; + this.fire(new performance$1.k('dataloading', { dataType: 'source' })); + this.url = this.options.url; + this._request = new AbortController(); + try { + const image = yield ImageRequest.getImage(this.map._requestManager.transformRequest(this.url, "Image" /* ResourceType.Image */), this._request); + this._request = null; + this._loaded = true; + if (image && image.data) { + this.image = image.data; + if (newCoordinates) { + this.coordinates = newCoordinates; + } + this._finishLoading(); + } + } + catch (err) { + this._request = null; + this._loaded = true; + this.fire(new performance$1.j(err)); + } + }); + } + loaded() { + return this._loaded; + } + /** + * Updates the image URL and, optionally, the coordinates. To avoid having the image flash after changing, + * set the `raster-fade-duration` paint property on the raster layer to 0. + * + * @param options - The options object. + */ + updateImage(options) { + if (!options.url) { + return this; + } + if (this._request) { + this._request.abort(); + this._request = null; + } + this.options.url = options.url; + this.load(options.coordinates).finally(() => { this.texture = null; }); + return this; + } + _finishLoading() { + if (this.map) { + this.setCoordinates(this.coordinates); + this.fire(new performance$1.k('data', { dataType: 'source', sourceDataType: 'metadata' })); + } + } + onAdd(map) { + this.map = map; + this.load(); + } + onRemove() { + if (this._request) { + this._request.abort(); + this._request = null; + } + } + /** + * Sets the image's coordinates and re-renders the map. + * + * @param coordinates - Four geographical coordinates, + * represented as arrays of longitude and latitude numbers, which define the corners of the image. + * The coordinates start at the top left corner of the image and proceed in clockwise order. + * They do not have to represent a rectangle. + */ + setCoordinates(coordinates) { + this.coordinates = coordinates; + // Calculate which mercator tile is suitable for rendering the video in + // and create a buffer with the corner coordinates. These coordinates + // may be outside the tile, because raster tiles aren't clipped when rendering. + // transform the geo coordinates into (zoom 0) tile space coordinates + const cornerCoords = coordinates.map(performance$1.Z.fromLngLat); + // Compute the coordinates of the tile we'll use to hold this image's + // render data + this.tileID = getCoordinatesCenterTileID(cornerCoords); + // Constrain min/max zoom to our tile's zoom level in order to force + // SourceCache to request this tile (no matter what the map's zoom + // level) + this.minzoom = this.maxzoom = this.tileID.z; + // Transform the corner coordinates into the coordinate space of our + // tile. + const tileCoords = cornerCoords.map((coord) => this.tileID.getTilePoint(coord)._round()); + this._boundsArray = new performance$1.$(); + this._boundsArray.emplaceBack(tileCoords[0].x, tileCoords[0].y, 0, 0); + this._boundsArray.emplaceBack(tileCoords[1].x, tileCoords[1].y, performance$1.X, 0); + this._boundsArray.emplaceBack(tileCoords[3].x, tileCoords[3].y, 0, performance$1.X); + this._boundsArray.emplaceBack(tileCoords[2].x, tileCoords[2].y, performance$1.X, performance$1.X); + if (this.boundsBuffer) { + this.boundsBuffer.destroy(); + delete this.boundsBuffer; + } + this.fire(new performance$1.k('data', { dataType: 'source', sourceDataType: 'content' })); + return this; + } + prepare() { + if (Object.keys(this.tiles).length === 0 || !this.image) { + return; + } + const context = this.map.painter.context; + const gl = context.gl; + if (!this.boundsBuffer) { + this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members); + } + if (!this.boundsSegments) { + this.boundsSegments = performance$1.a0.simpleSegment(0, 0, 4, 2); + } + if (!this.texture) { + this.texture = new Texture(context, this.image, gl.RGBA); + this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + } + let newTilesLoaded = false; + for (const w in this.tiles) { + const tile = this.tiles[w]; + if (tile.state !== 'loaded') { + tile.state = 'loaded'; + tile.texture = this.texture; + newTilesLoaded = true; + } + } + if (newTilesLoaded) { + this.fire(new performance$1.k('data', { dataType: 'source', sourceDataType: 'idle', sourceId: this.id })); + } + } + loadTile(tile) { + return performance$1._(this, void 0, void 0, function* () { + // We have a single tile -- whose coordinates are this.tileID -- that + // covers the image we want to render. If that's the one being + // requested, set it up with the image; otherwise, mark the tile as + // `errored` to indicate that we have no data for it. + // If the world wraps, we may have multiple "wrapped" copies of the + // single tile. + if (this.tileID && this.tileID.equals(tile.tileID.canonical)) { + this.tiles[String(tile.tileID.wrap)] = tile; + tile.buckets = {}; + } + else { + tile.state = 'errored'; + } + }); + } + serialize() { + return { + type: 'image', + url: this.options.url, + coordinates: this.coordinates + }; + } + hasTransition() { + return false; + } +} +/** + * Given a list of coordinates, get their center as a coordinate. + * + * @returns centerpoint + * @internal + */ +function getCoordinatesCenterTileID(coords) { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const coord of coords) { + minX = Math.min(minX, coord.x); + minY = Math.min(minY, coord.y); + maxX = Math.max(maxX, coord.x); + maxY = Math.max(maxY, coord.y); + } + const dx = maxX - minX; + const dy = maxY - minY; + const dMax = Math.max(dx, dy); + const zoom = Math.max(0, Math.floor(-Math.log(dMax) / Math.LN2)); + const tilesAtZoom = Math.pow(2, zoom); + return new performance$1.a1(zoom, Math.floor((minX + maxX) / 2 * tilesAtZoom), Math.floor((minY + maxY) / 2 * tilesAtZoom)); +} + +/** + * A data source containing video. + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-video) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * // add to map + * map.addSource('some id', { + * type: 'video', + * url: [ + * 'https://www.mapbox.com/blog/assets/baltimore-smoke.mp4', + * 'https://www.mapbox.com/blog/assets/baltimore-smoke.webm' + * ], + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update + * let mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * map.removeSource('some id'); // remove + * ``` + * @see [Add a video](https://maplibre.org/maplibre-gl-js/docs/examples/video-on-a-map/) + * + * Note that when rendered as a raster layer, the layer's `raster-fade-duration` property will cause the video to fade in. + * This happens when playback is started, paused and resumed, or when the video's coordinates are updated. To avoid this behavior, + * set the layer's `raster-fade-duration` property to `0`. + */ +class VideoSource extends ImageSource { + constructor(id, options, dispatcher, eventedParent) { + super(id, options, dispatcher, eventedParent); + this.roundZoom = true; + this.type = 'video'; + this.options = options; + } + load() { + return performance$1._(this, void 0, void 0, function* () { + this._loaded = false; + const options = this.options; + this.urls = []; + for (const url of options.urls) { + this.urls.push(this.map._requestManager.transformRequest(url, "Source" /* ResourceType.Source */).url); + } + try { + const video = yield performance$1.a3(this.urls); + this._loaded = true; + if (!video) { + return; + } + this.video = video; + this.video.loop = true; + // Start repainting when video starts playing. hasTransition() will then return + // true to trigger additional frames as long as the videos continues playing. + this.video.addEventListener('playing', () => { + this.map.triggerRepaint(); + }); + if (this.map) { + this.video.play(); + } + this._finishLoading(); + } + catch (err) { + this.fire(new performance$1.j(err)); + } + }); + } + /** + * Pauses the video. + */ + pause() { + if (this.video) { + this.video.pause(); + } + } + /** + * Plays the video. + */ + play() { + if (this.video) { + this.video.play(); + } + } + /** + * Sets playback to a timestamp, in seconds. + */ + seek(seconds) { + if (this.video) { + const seekableRange = this.video.seekable; + if (seconds < seekableRange.start(0) || seconds > seekableRange.end(0)) { + this.fire(new performance$1.j(new performance$1.a2(`sources.${this.id}`, null, `Playback for this video can be set only between the ${seekableRange.start(0)} and ${seekableRange.end(0)}-second mark.`))); + } + else + this.video.currentTime = seconds; + } + } + /** + * Returns the HTML `video` element. + * + * @returns The HTML `video` element. + */ + getVideo() { + return this.video; + } + onAdd(map) { + if (this.map) + return; + this.map = map; + this.load(); + if (this.video) { + this.video.play(); + this.setCoordinates(this.coordinates); + } + } + /** + * Sets the video's coordinates and re-renders the map. + */ + prepare() { + if (Object.keys(this.tiles).length === 0 || this.video.readyState < 2) { + return; // not enough data for current position + } + const context = this.map.painter.context; + const gl = context.gl; + if (!this.boundsBuffer) { + this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members); + } + if (!this.boundsSegments) { + this.boundsSegments = performance$1.a0.simpleSegment(0, 0, 4, 2); + } + if (!this.texture) { + this.texture = new Texture(context, this.video, gl.RGBA); + this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + } + else if (!this.video.paused) { + this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.video); + } + let newTilesLoaded = false; + for (const w in this.tiles) { + const tile = this.tiles[w]; + if (tile.state !== 'loaded') { + tile.state = 'loaded'; + tile.texture = this.texture; + newTilesLoaded = true; + } + } + if (newTilesLoaded) { + this.fire(new performance$1.k('data', { dataType: 'source', sourceDataType: 'idle', sourceId: this.id })); + } + } + serialize() { + return { + type: 'video', + urls: this.urls, + coordinates: this.coordinates + }; + } + hasTransition() { + return this.video && !this.video.paused; + } +} + +/** + * A data source containing the contents of an HTML canvas. See {@link CanvasSourceSpecification} for detailed documentation of options. + * + * @group Sources + * + * @example + * ```ts + * // add to map + * map.addSource('some id', { + * type: 'canvas', + * canvas: 'idOfMyHTMLCanvas', + * animate: true, + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update + * let mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * map.removeSource('some id'); // remove + * ``` + */ +class CanvasSource extends ImageSource { + /** @internal */ + constructor(id, options, dispatcher, eventedParent) { + super(id, options, dispatcher, eventedParent); + // We build in some validation here, since canvas sources aren't included in the style spec: + if (!options.coordinates) { + this.fire(new performance$1.j(new performance$1.a2(`sources.${id}`, null, 'missing required property "coordinates"'))); + } + else if (!Array.isArray(options.coordinates) || options.coordinates.length !== 4 || + options.coordinates.some(c => !Array.isArray(c) || c.length !== 2 || c.some(l => typeof l !== 'number'))) { + this.fire(new performance$1.j(new performance$1.a2(`sources.${id}`, null, '"coordinates" property must be an array of 4 longitude/latitude array pairs'))); + } + if (options.animate && typeof options.animate !== 'boolean') { + this.fire(new performance$1.j(new performance$1.a2(`sources.${id}`, null, 'optional "animate" property must be a boolean value'))); + } + if (!options.canvas) { + this.fire(new performance$1.j(new performance$1.a2(`sources.${id}`, null, 'missing required property "canvas"'))); + } + else if (typeof options.canvas !== 'string' && !(options.canvas instanceof HTMLCanvasElement)) { + this.fire(new performance$1.j(new performance$1.a2(`sources.${id}`, null, '"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))); + } + this.options = options; + this.animate = options.animate !== undefined ? options.animate : true; + } + load() { + return performance$1._(this, void 0, void 0, function* () { + this._loaded = true; + if (!this.canvas) { + this.canvas = (this.options.canvas instanceof HTMLCanvasElement) ? + this.options.canvas : + document.getElementById(this.options.canvas); + // cast to HTMLCanvasElement in else of ternary + // should we do a safety check and throw if it's not actually HTMLCanvasElement? + } + this.width = this.canvas.width; + this.height = this.canvas.height; + if (this._hasInvalidDimensions()) { + this.fire(new performance$1.j(new Error('Canvas dimensions cannot be less than or equal to zero.'))); + return; + } + this.play = function () { + this._playing = true; + this.map.triggerRepaint(); + }; + this.pause = function () { + if (this._playing) { + this.prepare(); + this._playing = false; + } + }; + this._finishLoading(); + }); + } + /** + * Returns the HTML `canvas` element. + * + * @returns The HTML `canvas` element. + */ + getCanvas() { + return this.canvas; + } + onAdd(map) { + this.map = map; + this.load(); + if (this.canvas) { + if (this.animate) + this.play(); + } + } + onRemove() { + this.pause(); + } + prepare() { + let resize = false; + if (this.canvas.width !== this.width) { + this.width = this.canvas.width; + resize = true; + } + if (this.canvas.height !== this.height) { + this.height = this.canvas.height; + resize = true; + } + if (this._hasInvalidDimensions()) + return; + if (Object.keys(this.tiles).length === 0) + return; // not enough data for current position + const context = this.map.painter.context; + const gl = context.gl; + if (!this.boundsBuffer) { + this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members); + } + if (!this.boundsSegments) { + this.boundsSegments = performance$1.a0.simpleSegment(0, 0, 4, 2); + } + if (!this.texture) { + this.texture = new Texture(context, this.canvas, gl.RGBA, { premultiply: true }); + } + else if (resize || this._playing) { + this.texture.update(this.canvas, { premultiply: true }); + } + let newTilesLoaded = false; + for (const w in this.tiles) { + const tile = this.tiles[w]; + if (tile.state !== 'loaded') { + tile.state = 'loaded'; + tile.texture = this.texture; + newTilesLoaded = true; + } + } + if (newTilesLoaded) { + this.fire(new performance$1.k('data', { dataType: 'source', sourceDataType: 'idle', sourceId: this.id })); + } + } + serialize() { + return { + type: 'canvas', + coordinates: this.coordinates + }; + } + hasTransition() { + return this._playing; + } + _hasInvalidDimensions() { + for (const x of [this.canvas.width, this.canvas.height]) { + if (isNaN(x) || x <= 0) + return true; + } + return false; + } +} + +const registeredSources = {}; +/** + * Creates a tiled data source instance given an options object. + * + * @param id - The id for the source. Must not be used by any existing source. + * @param specification - Source options, specific to the source type (except for `options.type`, which is always required). + * @param source - A source definition object compliant with + * [`maplibre-gl-style-spec`](https://maplibre.org/maplibre-style-spec/#sources) or, for a third-party source type, + * with that type's requirements. + * @param dispatcher - A {@link Dispatcher} instance, which can be used to send messages to the workers. + * @returns a newly created source + */ +const create = (id, specification, dispatcher, eventedParent) => { + const Class = getSourceType(specification.type); + const source = new Class(id, specification, dispatcher, eventedParent); + if (source.id !== id) { + throw new Error(`Expected Source id to be ${id} instead of ${source.id}`); + } + return source; +}; +const getSourceType = (name) => { + switch (name) { + case 'geojson': + return GeoJSONSource; + case 'image': + return ImageSource; + case 'raster': + return RasterTileSource; + case 'raster-dem': + return RasterDEMTileSource; + case 'vector': + return VectorTileSource; + case 'video': + return VideoSource; + case 'canvas': + return CanvasSource; + } + return registeredSources[name]; +}; +const setSourceType = (name, type) => { + registeredSources[name] = type; +}; +/** + * Adds a custom source type, making it available for use with {@link Map#addSource}. + * @param name - The name of the source type; source definition objects use this name in the `{type: ...}` field. + * @param SourceType - A {@link SourceClass} - which is a constructor for the `Source` interface. + * @returns a promise that is resolved when the source type is ready or rejected with an error. + */ +const addSourceType = (name, SourceType) => performance$1._(void 0, void 0, void 0, function* () { + if (getSourceType(name)) { + throw new Error(`A source type called "${name}" already exists.`); + } + setSourceType(name, SourceType); +}); + +function deserialize(input, style) { + const output = {}; + // Guard against the case where the map's style has been set to null while + // this bucket has been parsing. + if (!style) + return output; + for (const bucket of input) { + const layers = bucket.layerIds + .map((id) => style.getLayer(id)) + .filter(Boolean); + if (layers.length === 0) { + continue; + } + // look up StyleLayer objects from layer ids (since we don't + // want to waste time serializing/copying them from the worker) + bucket.layers = layers; + if (bucket.stateDependentLayerIds) { + bucket.stateDependentLayers = bucket.stateDependentLayerIds.map((lId) => layers.filter((l) => l.id === lId)[0]); + } + for (const layer of layers) { + output[layer.id] = bucket; + } + } + return output; +} + +const RTLPluginLoadedEventName = 'RTLPluginLoaded'; + +class RTLMainThreadPlugin extends performance$1.E { + constructor() { + super(...arguments); + this.status = 'unavailable'; + this.url = null; + this.dispatcher = getGlobalDispatcher(); + } + /** Sync RTL plugin state by broadcasting a message to the worker */ + _syncState(statusToSend) { + this.status = statusToSend; + return this.dispatcher.broadcast("SRPS" /* MessageType.syncRTLPluginState */, { pluginStatus: statusToSend, pluginURL: this.url }) + .catch((e) => { + this.status = 'error'; + throw e; + }); + } + /** This one is exposed to outside */ + getRTLTextPluginStatus() { + return this.status; + } + clearRTLTextPlugin() { + this.status = 'unavailable'; + this.url = null; + } + setRTLTextPlugin(url_1) { + return performance$1._(this, arguments, void 0, function* (url, deferred = false) { + if (this.url) { + // error + throw new Error('setRTLTextPlugin cannot be called multiple times.'); + } + this.url = browser.resolveURL(url); + if (!this.url) { + throw new Error(`requested url ${url} is invalid`); + } + if (this.status === 'unavailable') { + // from initial state: + if (deferred) { + this.status = 'deferred'; + // fire and forget: in this case it does not need wait for the broadcasting result + // it is important to sync the deferred status once because + // symbol_bucket will be checking it in worker + this._syncState(this.status); + } + else { + return this._requestImport(); + } + } + else if (this.status === 'requested') { + return this._requestImport(); + } + }); + } + /** Send a message to worker which will import the RTL plugin script */ + _requestImport() { + return performance$1._(this, void 0, void 0, function* () { + // all errors/exceptions will be handled by _syncState + yield this._syncState('loading'); + this.status = 'loaded'; + this.fire(new performance$1.k(RTLPluginLoadedEventName)); + }); + } + /** Start a lazy loading process of RTL plugin */ + lazyLoad() { + if (this.status === 'unavailable') { + this.status = 'requested'; + } + else if (this.status === 'deferred') { + this._requestImport(); + } + } +} +let rtlMainThreadPlugin = null; +function rtlMainThreadPluginFactory() { + if (!rtlMainThreadPlugin) { + rtlMainThreadPlugin = new RTLMainThreadPlugin(); + } + return rtlMainThreadPlugin; +} + +const CLOCK_SKEW_RETRY_TIMEOUT = 30000; +/** + * A tile object is the combination of a Coordinate, which defines + * its place, as well as a unique ID and data tracking for its content + */ +class Tile { + /** + * @param tileID - the tile ID + * @param size - The tile size + */ + constructor(tileID, size) { + this.timeAdded = 0; + this.fadeEndTime = 0; + this.tileID = tileID; + this.uid = performance$1.a4(); + this.uses = 0; + this.tileSize = size; + this.buckets = {}; + this.expirationTime = null; + this.queryPadding = 0; + this.hasSymbolBuckets = false; + this.hasRTLText = false; + this.dependencies = {}; + this.rtt = []; + this.rttCoords = {}; + // Counts the number of times a response was already expired when + // received. We're using this to add a delay when making a new request + // so we don't have to keep retrying immediately in case of a server + // serving expired tiles. + this.expiredRequestCount = 0; + this.state = 'loading'; + } + registerFadeDuration(duration) { + const fadeEndTime = duration + this.timeAdded; + if (fadeEndTime < this.fadeEndTime) { + return; + } + this.fadeEndTime = fadeEndTime; + } + wasRequested() { + return this.state === 'errored' || this.state === 'loaded' || this.state === 'reloading'; + } + clearTextures(painter) { + if (this.demTexture) + painter.saveTileTexture(this.demTexture); + this.demTexture = null; + } + /** + * Given a data object with a 'buffers' property, load it into + * this tile's elementGroups and buffers properties and set loaded + * to true. If the data is null, like in the case of an empty + * GeoJSON tile, no-op but still set loaded to true. + * @param data - The data from the worker + * @param painter - the painter + * @param justReloaded - `true` to just reload + */ + loadVectorData(data, painter, justReloaded) { + if (this.hasData()) { + this.unloadVectorData(); + } + this.state = 'loaded'; + // empty GeoJSON tile + if (!data) { + this.collisionBoxArray = new performance$1.a5(); + return; + } + if (data.featureIndex) { + this.latestFeatureIndex = data.featureIndex; + if (data.rawTileData) { + // Only vector tiles have rawTileData, and they won't update it for + // 'reloadTile' + this.latestRawTileData = data.rawTileData; + this.latestFeatureIndex.rawTileData = data.rawTileData; + } + else if (this.latestRawTileData) { + // If rawTileData hasn't updated, hold onto a pointer to the last + // one we received + this.latestFeatureIndex.rawTileData = this.latestRawTileData; + } + } + this.collisionBoxArray = data.collisionBoxArray; + this.buckets = deserialize(data.buckets, painter.style); + this.hasSymbolBuckets = false; + for (const id in this.buckets) { + const bucket = this.buckets[id]; + if (bucket instanceof performance$1.a6) { + this.hasSymbolBuckets = true; + if (justReloaded) { + bucket.justReloaded = true; + } + else { + break; + } + } + } + this.hasRTLText = false; + if (this.hasSymbolBuckets) { + for (const id in this.buckets) { + const bucket = this.buckets[id]; + if (bucket instanceof performance$1.a6) { + if (bucket.hasRTLText) { + this.hasRTLText = true; + rtlMainThreadPluginFactory().lazyLoad(); + break; + } + } + } + } + this.queryPadding = 0; + for (const id in this.buckets) { + const bucket = this.buckets[id]; + this.queryPadding = Math.max(this.queryPadding, painter.style.getLayer(id).queryRadius(bucket)); + } + if (data.imageAtlas) { + this.imageAtlas = data.imageAtlas; + } + if (data.imageBackgroundsAtlas) { + this.imageBackgroundsAtlas = data.imageBackgroundsAtlas; + } + if (data.glyphAtlasImage) { + this.glyphAtlasImage = data.glyphAtlasImage; + } + } + /** + * Release any data or WebGL resources referenced by this tile. + */ + unloadVectorData() { + for (const id in this.buckets) { + this.buckets[id].destroy(); + } + this.buckets = {}; + if (this.imageAtlasTexture) { + this.imageAtlasTexture.destroy(); + } + if (this.imageBackgroundsAtlasTexture) { + this.imageBackgroundsAtlasTexture.destroy(); + } + if (this.imageAtlas) { + this.imageAtlas = null; + } + if (this.imageBackgroundsAtlas) { + this.imageBackgroundsAtlas = null; + } + if (this.glyphAtlasTexture) { + this.glyphAtlasTexture.destroy(); + } + this.latestFeatureIndex = null; + this.state = 'unloaded'; + } + getBucket(layer) { + return this.buckets[layer.id]; + } + upload(context) { + for (const id in this.buckets) { + const bucket = this.buckets[id]; + if (bucket.uploadPending()) { + bucket.upload(context); + } + } + const gl = context.gl; + if (this.imageAtlas && !this.imageAtlas.uploaded) { + this.imageAtlasTexture = new Texture(context, this.imageAtlas.image, gl.RGBA); + this.imageAtlas.uploaded = true; + } + if (this.imageBackgroundsAtlas && !this.imageBackgroundsAtlas.uploaded) { + this.imageBackgroundsAtlasTexture = new Texture(context, this.imageBackgroundsAtlas.image, gl.RGBA); + this.imageBackgroundsAtlas.uploaded = true; + } + if (this.glyphAtlasImage) { + this.glyphAtlasTexture = new Texture(context, this.glyphAtlasImage, gl.ALPHA); + this.glyphAtlasImage = null; + } + } + prepare(imageManager) { + if (this.imageAtlas) { + this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture); + } + if (this.imageBackgroundsAtlas) { + this.imageBackgroundsAtlas.patchUpdatedImages(imageManager, this.imageBackgroundsAtlasTexture); + } + } + // Queries non-symbol features rendered for this tile. + // Symbol features are queried globally + queryRenderedFeatures(layers, serializedLayers, sourceFeatureState, queryGeometry, cameraQueryGeometry, scale, params, transform, maxPitchScaleFactor, pixelPosMatrix) { + if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData) + return {}; + return this.latestFeatureIndex.query({ + queryGeometry, + cameraQueryGeometry, + scale, + tileSize: this.tileSize, + pixelPosMatrix, + transform, + params, + queryPadding: this.queryPadding * maxPitchScaleFactor + }, layers, serializedLayers, sourceFeatureState); + } + querySourceFeatures(result, params) { + const featureIndex = this.latestFeatureIndex; + if (!featureIndex || !featureIndex.rawTileData) + return; + const vtLayers = featureIndex.loadVTLayers(); + const sourceLayer = params && params.sourceLayer ? params.sourceLayer : ''; + const layer = vtLayers._geojsonTileLayer || vtLayers[sourceLayer]; + if (!layer) + return; + const filter = performance$1.a7(params && params.filter); + const { z, x, y } = this.tileID.canonical; + const coord = { z, x, y }; + for (let i = 0; i < layer.length; i++) { + const feature = layer.feature(i); + if (filter.needGeometry) { + const evaluationFeature = performance$1.a8(feature, true); + if (!filter.filter(new performance$1.z(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) + continue; + } + else if (!filter.filter(new performance$1.z(this.tileID.overscaledZ), feature)) { + continue; + } + const id = featureIndex.getId(feature, sourceLayer); + const geojsonFeature = new performance$1.a9(feature, z, x, y, id); + geojsonFeature.tile = coord; + result.push(geojsonFeature); + } + } + hasData() { + return this.state === 'loaded' || this.state === 'reloading' || this.state === 'expired'; + } + patternsLoaded() { + return this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length; + } + setExpiryData(data) { + const prior = this.expirationTime; + if (data.cacheControl) { + const parsedCC = performance$1.aa(data.cacheControl); + if (parsedCC['max-age']) + this.expirationTime = Date.now() + parsedCC['max-age'] * 1000; + } + else if (data.expires) { + this.expirationTime = new Date(data.expires).getTime(); + } + if (this.expirationTime) { + const now = Date.now(); + let isExpired = false; + if (this.expirationTime > now) { + isExpired = false; + } + else if (!prior) { + isExpired = true; + } + else if (this.expirationTime < prior) { + // Expiring date is going backwards: + // fall back to exponential backoff + isExpired = true; + } + else { + const delta = this.expirationTime - prior; + if (!delta) { + // Server is serving the same expired resource over and over: fall + // back to exponential backoff. + isExpired = true; + } + else { + // Assume that either the client or the server clock is wrong and + // try to interpolate a valid expiration date (from the client POV) + // observing a minimum timeout. + this.expirationTime = now + Math.max(delta, CLOCK_SKEW_RETRY_TIMEOUT); + } + } + if (isExpired) { + this.expiredRequestCount++; + this.state = 'expired'; + } + else { + this.expiredRequestCount = 0; + } + } + } + getExpiryTimeout() { + if (this.expirationTime) { + if (this.expiredRequestCount) { + return 1000 * (1 << Math.min(this.expiredRequestCount - 1, 31)); + } + else { + // Max value for `setTimeout` implementations is a 32 bit integer; cap this accordingly + return Math.min(this.expirationTime - new Date().getTime(), Math.pow(2, 31) - 1); + } + } + } + setFeatureState(states, painter) { + if (!this.latestFeatureIndex || + !this.latestFeatureIndex.rawTileData || + Object.keys(states).length === 0) { + return; + } + const vtLayers = this.latestFeatureIndex.loadVTLayers(); + for (const id in this.buckets) { + if (!painter.style.hasLayer(id)) + continue; + const bucket = this.buckets[id]; + // Buckets are grouped by common source-layer + const sourceLayerId = bucket.layers[0]['sourceLayer'] || '_geojsonTileLayer'; + const sourceLayer = vtLayers[sourceLayerId]; + const sourceLayerStates = states[sourceLayerId]; + if (!sourceLayer || !sourceLayerStates || Object.keys(sourceLayerStates).length === 0) + continue; + bucket.update(sourceLayerStates, sourceLayer, this.imageAtlas && this.imageAtlas.patternPositions || {}); + const layer = painter && painter.style && painter.style.getLayer(id); + if (layer) { + this.queryPadding = Math.max(this.queryPadding, layer.queryRadius(bucket)); + } + } + } + holdingForFade() { + return this.symbolFadeHoldUntil !== undefined; + } + symbolFadeFinished() { + return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < browser.now(); + } + clearFadeHold() { + this.symbolFadeHoldUntil = undefined; + } + setHoldDuration(duration) { + this.symbolFadeHoldUntil = browser.now() + duration; + } + setDependencies(namespace, dependencies) { + const index = {}; + for (const dep of dependencies) { + index[dep] = true; + } + this.dependencies[namespace] = index; + } + hasDependency(namespaces, keys) { + for (const namespace of namespaces) { + const dependencies = this.dependencies[namespace]; + if (dependencies) { + for (const key of keys) { + if (dependencies[key]) { + return true; + } + } + } + } + return false; + } +} + +/** + * @internal + * A [least-recently-used cache](https://en.wikipedia.org/wiki/Cache_algorithms) + * with hash lookup made possible by keeping a list of keys in parallel to + * an array of dictionary of values + */ +class TileCache { + /** + * @param max - number of permitted values + * @param onRemove - callback called with items when they expire + */ + constructor(max, onRemove) { + this.max = max; + this.onRemove = onRemove; + this.reset(); + } + /** + * Clear the cache + * + * @returns this cache + */ + reset() { + for (const key in this.data) { + for (const removedData of this.data[key]) { + if (removedData.timeout) + clearTimeout(removedData.timeout); + this.onRemove(removedData.value); + } + } + this.data = {}; + this.order = []; + return this; + } + /** + * Add a key, value combination to the cache, trimming its size if this pushes + * it over max length. + * + * @param tileID - lookup key for the item + * @param data - tile data + * + * @returns this cache + */ + add(tileID, data, expiryTimeout) { + const key = tileID.wrapped().key; + if (this.data[key] === undefined) { + this.data[key] = []; + } + const dataWrapper = { + value: data, + timeout: undefined + }; + if (expiryTimeout !== undefined) { + dataWrapper.timeout = setTimeout(() => { + this.remove(tileID, dataWrapper); + }, expiryTimeout); + } + this.data[key].push(dataWrapper); + this.order.push(key); + if (this.order.length > this.max) { + const removedData = this._getAndRemoveByKey(this.order[0]); + if (removedData) + this.onRemove(removedData); + } + return this; + } + /** + * Determine whether the value attached to `key` is present + * + * @param tileID - the key to be looked-up + * @returns whether the cache has this value + */ + has(tileID) { + return tileID.wrapped().key in this.data; + } + /** + * Get the value attached to a specific key and remove data from cache. + * If the key is not found, returns `null` + * + * @param tileID - the key to look up + * @returns the tile data, or null if it isn't found + */ + getAndRemove(tileID) { + if (!this.has(tileID)) { + return null; + } + return this._getAndRemoveByKey(tileID.wrapped().key); + } + /* + * Get and remove the value with the specified key. + */ + _getAndRemoveByKey(key) { + const data = this.data[key].shift(); + if (data.timeout) + clearTimeout(data.timeout); + if (this.data[key].length === 0) { + delete this.data[key]; + } + this.order.splice(this.order.indexOf(key), 1); + return data.value; + } + /* + * Get the value with the specified (wrapped tile) key. + */ + getByKey(key) { + const data = this.data[key]; + return data ? data[0].value : null; + } + /** + * Get the value attached to a specific key without removing data + * from the cache. If the key is not found, returns `null` + * + * @param tileID - the key to look up + * @returns the tile data, or null if it isn't found + */ + get(tileID) { + if (!this.has(tileID)) { + return null; + } + const data = this.data[tileID.wrapped().key][0]; + return data.value; + } + /** + * Remove a key/value combination from the cache. + * + * @param tileID - the key for the pair to delete + * @param value - If a value is provided, remove that exact version of the value. + * @returns this cache + */ + remove(tileID, value) { + if (!this.has(tileID)) { + return this; + } + const key = tileID.wrapped().key; + const dataIndex = value === undefined ? 0 : this.data[key].indexOf(value); + const data = this.data[key][dataIndex]; + this.data[key].splice(dataIndex, 1); + if (data.timeout) + clearTimeout(data.timeout); + if (this.data[key].length === 0) { + delete this.data[key]; + } + this.onRemove(data.value); + this.order.splice(this.order.indexOf(key), 1); + return this; + } + /** + * Change the max size of the cache. + * + * @param max - the max size of the cache + * @returns this cache + */ + setMaxSize(max) { + this.max = max; + while (this.order.length > this.max) { + const removedData = this._getAndRemoveByKey(this.order[0]); + if (removedData) + this.onRemove(removedData); + } + return this; + } + /** + * Remove entries that do not pass a filter function. Used for removing + * stale tiles from the cache. + * + * @param filterFn - Determines whether the tile is filtered. If the supplied function returns false, the tile will be filtered out. + */ + filter(filterFn) { + const removed = []; + for (const key in this.data) { + for (const entry of this.data[key]) { + if (!filterFn(entry.value)) { + removed.push(entry); + } + } + } + for (const r of removed) { + this.remove(r.value.tileID, r); + } + } +} + +/** + * @internal + * SourceFeatureState manages the state and pending changes + * to features in a source, separated by source layer. + * stateChanges and deletedStates batch all changes to the tile (updates and removes, respectively) + * between coalesce() events. addFeatureState() and removeFeatureState() also update their counterpart's + * list of changes, such that coalesce() can apply the proper state changes while agnostic to the order of operations. + * In deletedStates, all null's denote complete removal of state at that scope +*/ +class SourceFeatureState { + constructor() { + this.state = {}; + this.stateChanges = {}; + this.deletedStates = {}; + } + updateState(sourceLayer, featureId, newState) { + const feature = String(featureId); + this.stateChanges[sourceLayer] = this.stateChanges[sourceLayer] || {}; + this.stateChanges[sourceLayer][feature] = this.stateChanges[sourceLayer][feature] || {}; + performance$1.e(this.stateChanges[sourceLayer][feature], newState); + if (this.deletedStates[sourceLayer] === null) { + this.deletedStates[sourceLayer] = {}; + for (const ft in this.state[sourceLayer]) { + if (ft !== feature) + this.deletedStates[sourceLayer][ft] = null; + } + } + else { + const featureDeletionQueued = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] === null; + if (featureDeletionQueued) { + this.deletedStates[sourceLayer][feature] = {}; + for (const prop in this.state[sourceLayer][feature]) { + if (!newState[prop]) + this.deletedStates[sourceLayer][feature][prop] = null; + } + } + else { + for (const key in newState) { + const deletionInQueue = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] && this.deletedStates[sourceLayer][feature][key] === null; + if (deletionInQueue) + delete this.deletedStates[sourceLayer][feature][key]; + } + } + } + } + removeFeatureState(sourceLayer, featureId, key) { + const sourceLayerDeleted = this.deletedStates[sourceLayer] === null; + if (sourceLayerDeleted) + return; + const feature = String(featureId); + this.deletedStates[sourceLayer] = this.deletedStates[sourceLayer] || {}; + if (key && featureId !== undefined) { + if (this.deletedStates[sourceLayer][feature] !== null) { + this.deletedStates[sourceLayer][feature] = this.deletedStates[sourceLayer][feature] || {}; + this.deletedStates[sourceLayer][feature][key] = null; + } + } + else if (featureId !== undefined) { + const updateInQueue = this.stateChanges[sourceLayer] && this.stateChanges[sourceLayer][feature]; + if (updateInQueue) { + this.deletedStates[sourceLayer][feature] = {}; + for (key in this.stateChanges[sourceLayer][feature]) + this.deletedStates[sourceLayer][feature][key] = null; + } + else { + this.deletedStates[sourceLayer][feature] = null; + } + } + else { + this.deletedStates[sourceLayer] = null; + } + } + getState(sourceLayer, featureId) { + const feature = String(featureId); + const base = this.state[sourceLayer] || {}; + const changes = this.stateChanges[sourceLayer] || {}; + const reconciledState = performance$1.e({}, base[feature], changes[feature]); + //return empty object if the whole source layer is awaiting deletion + if (this.deletedStates[sourceLayer] === null) + return {}; + else if (this.deletedStates[sourceLayer]) { + const featureDeletions = this.deletedStates[sourceLayer][featureId]; + if (featureDeletions === null) + return {}; + for (const prop in featureDeletions) + delete reconciledState[prop]; + } + return reconciledState; + } + initializeTileState(tile, painter) { + tile.setFeatureState(this.state, painter); + } + coalesceChanges(tiles, painter) { + //track changes with full state objects, but only for features that got modified + const featuresChanged = {}; + for (const sourceLayer in this.stateChanges) { + this.state[sourceLayer] = this.state[sourceLayer] || {}; + const layerStates = {}; + for (const feature in this.stateChanges[sourceLayer]) { + if (!this.state[sourceLayer][feature]) + this.state[sourceLayer][feature] = {}; + performance$1.e(this.state[sourceLayer][feature], this.stateChanges[sourceLayer][feature]); + layerStates[feature] = this.state[sourceLayer][feature]; + } + featuresChanged[sourceLayer] = layerStates; + } + for (const sourceLayer in this.deletedStates) { + this.state[sourceLayer] = this.state[sourceLayer] || {}; + const layerStates = {}; + if (this.deletedStates[sourceLayer] === null) { + for (const ft in this.state[sourceLayer]) { + layerStates[ft] = {}; + this.state[sourceLayer][ft] = {}; + } + } + else { + for (const feature in this.deletedStates[sourceLayer]) { + const deleteWholeFeatureState = this.deletedStates[sourceLayer][feature] === null; + if (deleteWholeFeatureState) + this.state[sourceLayer][feature] = {}; + else { + for (const key of Object.keys(this.deletedStates[sourceLayer][feature])) { + delete this.state[sourceLayer][feature][key]; + } + } + layerStates[feature] = this.state[sourceLayer][feature]; + } + } + featuresChanged[sourceLayer] = featuresChanged[sourceLayer] || {}; + performance$1.e(featuresChanged[sourceLayer], layerStates); + } + this.stateChanges = {}; + this.deletedStates = {}; + if (Object.keys(featuresChanged).length === 0) + return; + for (const id in tiles) { + const tile = tiles[id]; + tile.setFeatureState(featuresChanged, painter); + } + } +} + +/** + * @internal + * `SourceCache` is responsible for + * + * - creating an instance of `Source` + * - forwarding events from `Source` + * - caching tiles loaded from an instance of `Source` + * - loading the tiles needed to render a given viewport + * - unloading the cached tiles not needed to render a given viewport + */ +class SourceCache extends performance$1.E { + constructor(id, options, dispatcher) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.on('data', (e) => this._dataHandler(e)); + this.on('dataloading', () => { + this._sourceErrored = false; + }); + this.on('error', () => { + // Only set _sourceErrored if the source does not have pending loads. + this._sourceErrored = this._source.loaded(); + }); + this._source = create(id, options, dispatcher, this); + this._tiles = {}; + this._cache = new TileCache(0, (tile) => this._unloadTile(tile)); + this._timers = {}; + this._cacheTimers = {}; + this._maxTileCacheSize = null; + this._maxTileCacheZoomLevels = null; + this._loadedParentTiles = {}; + this._coveredTiles = {}; + this._state = new SourceFeatureState(); + this._didEmitContent = false; + this._updated = false; + } + onAdd(map) { + this.map = map; + this._maxTileCacheSize = map ? map._maxTileCacheSize : null; + this._maxTileCacheZoomLevels = map ? map._maxTileCacheZoomLevels : null; + if (this._source && this._source.onAdd) { + this._source.onAdd(map); + } + } + onRemove(map) { + this.clearTiles(); + if (this._source && this._source.onRemove) { + this._source.onRemove(map); + } + } + /** + * Return true if no tile data is pending, tiles will not change unless + * an additional API call is received. + */ + loaded() { + if (this._sourceErrored) { + return true; + } + if (!this._sourceLoaded) { + return false; + } + if (!this._source.loaded()) { + return false; + } + if ((this.used !== undefined || this.usedForTerrain !== undefined) && !this.used && !this.usedForTerrain) { + return true; + } + // do not consider as loaded if the update hasn't been called yet (we do not know if we will have any tiles to fetch) + if (!this._updated) { + return false; + } + for (const t in this._tiles) { + const tile = this._tiles[t]; + if (tile.state !== 'loaded' && tile.state !== 'errored') + return false; + } + return true; + } + getSource() { + return this._source; + } + pause() { + this._paused = true; + } + resume() { + if (!this._paused) + return; + const shouldReload = this._shouldReloadOnResume; + this._paused = false; + this._shouldReloadOnResume = false; + if (shouldReload) + this.reload(); + if (this.transform) + this.update(this.transform, this.terrain); + } + _loadTile(tile, id, state) { + return performance$1._(this, void 0, void 0, function* () { + try { + yield this._source.loadTile(tile); + this._tileLoaded(tile, id, state); + } + catch (err) { + tile.state = 'errored'; + if (err.status !== 404) { + this._source.fire(new performance$1.j(err, { tile })); + } + else { + // continue to try loading parent/children tiles if a tile doesn't exist (404) + this.update(this.transform, this.terrain); + } + } + }); + } + _unloadTile(tile) { + if (this._source.unloadTile) + this._source.unloadTile(tile); + } + _abortTile(tile) { + if (this._source.abortTile) + this._source.abortTile(tile); + this._source.fire(new performance$1.k('dataabort', { tile, coord: tile.tileID, dataType: 'source' })); + } + serialize() { + return this._source.serialize(); + } + prepare(context) { + if (this._source.prepare) { + this._source.prepare(); + } + this._state.coalesceChanges(this._tiles, this.map ? this.map.painter : null); + for (const i in this._tiles) { + const tile = this._tiles[i]; + tile.upload(context); + tile.prepare(this.map.style.imageManager); + } + } + /** + * Return all tile ids ordered with z-order, and cast to numbers + */ + getIds() { + return Object.values(this._tiles).map((tile) => tile.tileID).sort(compareTileId).map(id => id.key); + } + getRenderableIds(symbolLayer) { + const renderables = []; + for (const id in this._tiles) { + if (this._isIdRenderable(id, symbolLayer)) + renderables.push(this._tiles[id]); + } + if (symbolLayer) { + return renderables.sort((a_, b_) => { + const a = a_.tileID; + const b = b_.tileID; + const rotatedA = (new performance$1.P(a.canonical.x, a.canonical.y))._rotate(this.transform.angle); + const rotatedB = (new performance$1.P(b.canonical.x, b.canonical.y))._rotate(this.transform.angle); + return a.overscaledZ - b.overscaledZ || rotatedB.y - rotatedA.y || rotatedB.x - rotatedA.x; + }).map(tile => tile.tileID.key); + } + return renderables.map(tile => tile.tileID).sort(compareTileId).map(id => id.key); + } + hasRenderableParent(tileID) { + const parentTile = this.findLoadedParent(tileID, 0); + if (parentTile) { + return this._isIdRenderable(parentTile.tileID.key); + } + return false; + } + _isIdRenderable(id, symbolLayer) { + return this._tiles[id] && this._tiles[id].hasData() && + !this._coveredTiles[id] && (symbolLayer || !this._tiles[id].holdingForFade()); + } + reload() { + if (this._paused) { + this._shouldReloadOnResume = true; + return; + } + this._cache.reset(); + for (const i in this._tiles) { + if (this._tiles[i].state !== 'errored') + this._reloadTile(i, 'reloading'); + } + } + _reloadTile(id, state) { + return performance$1._(this, void 0, void 0, function* () { + const tile = this._tiles[id]; + // this potentially does not address all underlying + // issues https://github.com/mapbox/mapbox-gl-js/issues/4252 + // - hard to tell without repro steps + if (!tile) + return; + // The difference between "loading" tiles and "reloading" or "expired" + // tiles is that "reloading"/"expired" tiles are "renderable". + // Therefore, a "loading" tile cannot become a "reloading" tile without + // first becoming a "loaded" tile. + if (tile.state !== 'loading') { + tile.state = state; + } + yield this._loadTile(tile, id, state); + }); + } + _tileLoaded(tile, id, previousState) { + tile.timeAdded = browser.now(); + if (previousState === 'expired') + tile.refreshedUponExpiration = true; + this._setTileReloadTimer(id, tile); + if (this.getSource().type === 'raster-dem' && tile.dem) + this._backfillDEM(tile); + this._state.initializeTileState(tile, this.map ? this.map.painter : null); + if (!tile.aborted) { + this._source.fire(new performance$1.k('data', { dataType: 'source', tile, coord: tile.tileID })); + } + } + /** + * For raster terrain source, backfill DEM to eliminate visible tile boundaries + */ + _backfillDEM(tile) { + const renderables = this.getRenderableIds(); + for (let i = 0; i < renderables.length; i++) { + const borderId = renderables[i]; + if (tile.neighboringTiles && tile.neighboringTiles[borderId]) { + const borderTile = this.getTileByID(borderId); + fillBorder(tile, borderTile); + fillBorder(borderTile, tile); + } + } + function fillBorder(tile, borderTile) { + tile.needsHillshadePrepare = true; + tile.needsTerrainPrepare = true; + let dx = borderTile.tileID.canonical.x - tile.tileID.canonical.x; + const dy = borderTile.tileID.canonical.y - tile.tileID.canonical.y; + const dim = Math.pow(2, tile.tileID.canonical.z); + const borderId = borderTile.tileID.key; + if (dx === 0 && dy === 0) + return; + if (Math.abs(dy) > 1) { + return; + } + if (Math.abs(dx) > 1) { + // Adjust the delta coordinate for world wraparound. + if (Math.abs(dx + dim) === 1) { + dx += dim; + } + else if (Math.abs(dx - dim) === 1) { + dx -= dim; + } + } + if (!borderTile.dem || !tile.dem) + return; + tile.dem.backfillBorder(borderTile.dem, dx, dy); + if (tile.neighboringTiles && tile.neighboringTiles[borderId]) + tile.neighboringTiles[borderId].backfilled = true; + } + } + /** + * Get a specific tile by TileID + */ + getTile(tileID) { + return this.getTileByID(tileID.key); + } + /** + * Get a specific tile by id + */ + getTileByID(id) { + return this._tiles[id]; + } + /** + * For a given set of tiles, retain children that are loaded and have a zoom + * between `zoom` (exclusive) and `maxCoveringZoom` (inclusive) + */ + _retainLoadedChildren(idealTiles, zoom, maxCoveringZoom, retain) { + for (const id in this._tiles) { + let tile = this._tiles[id]; + // only consider renderable tiles up to maxCoveringZoom + if (retain[id] || + !tile.hasData() || + tile.tileID.overscaledZ <= zoom || + tile.tileID.overscaledZ > maxCoveringZoom) + continue; + // loop through parents and retain the topmost loaded one if found + let topmostLoadedID = tile.tileID; + while (tile && tile.tileID.overscaledZ > zoom + 1) { + const parentID = tile.tileID.scaledTo(tile.tileID.overscaledZ - 1); + tile = this._tiles[parentID.key]; + if (tile && tile.hasData()) { + topmostLoadedID = parentID; + } + } + // loop through ancestors of the topmost loaded child to see if there's one that needed it + let tileID = topmostLoadedID; + while (tileID.overscaledZ > zoom) { + tileID = tileID.scaledTo(tileID.overscaledZ - 1); + if (idealTiles[tileID.key]) { + // found a parent that needed a loaded child; retain that child + retain[topmostLoadedID.key] = topmostLoadedID; + break; + } + } + } + } + /** + * Find a loaded parent of the given tile (up to minCoveringZoom) + */ + findLoadedParent(tileID, minCoveringZoom) { + if (tileID.key in this._loadedParentTiles) { + const parent = this._loadedParentTiles[tileID.key]; + if (parent && parent.tileID.overscaledZ >= minCoveringZoom) { + return parent; + } + else { + return null; + } + } + for (let z = tileID.overscaledZ - 1; z >= minCoveringZoom; z--) { + const parentTileID = tileID.scaledTo(z); + const tile = this._getLoadedTile(parentTileID); + if (tile) { + return tile; + } + } + } + /** + * Find a loaded sibling of the given tile + */ + findLoadedSibling(tileID) { + // If a tile with this ID already exists, return it + return this._getLoadedTile(tileID); + } + _getLoadedTile(tileID) { + const tile = this._tiles[tileID.key]; + if (tile && tile.hasData()) { + return tile; + } + // TileCache ignores wrap in lookup. + const cachedTile = this._cache.getByKey(tileID.wrapped().key); + return cachedTile; + } + /** + * Resizes the tile cache based on the current viewport's size + * or the maxTileCacheSize option passed during map creation + * + * Larger viewports use more tiles and need larger caches. Larger viewports + * are more likely to be found on devices with more memory and on pages where + * the map is more important. + */ + updateCacheSize(transform) { + const widthInTiles = Math.ceil(transform.width / this._source.tileSize) + 1; + const heightInTiles = Math.ceil(transform.height / this._source.tileSize) + 1; + const approxTilesInView = widthInTiles * heightInTiles; + const commonZoomRange = this._maxTileCacheZoomLevels === null ? + performance$1.a.MAX_TILE_CACHE_ZOOM_LEVELS : this._maxTileCacheZoomLevels; + const viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange); + const maxSize = typeof this._maxTileCacheSize === 'number' ? + Math.min(this._maxTileCacheSize, viewDependentMaxSize) : viewDependentMaxSize; + this._cache.setMaxSize(maxSize); + } + handleWrapJump(lng) { + // On top of the regular z/x/y values, TileIDs have a `wrap` value that specify + // which cppy of the world the tile belongs to. For example, at `lng: 10` you + // might render z/x/y/0 while at `lng: 370` you would render z/x/y/1. + // + // When lng values get wrapped (going from `lng: 370` to `long: 10`) you expect + // to see the same thing on the screen (370 degrees and 10 degrees is the same + // place in the world) but all the TileIDs will have different wrap values. + // + // In order to make this transition seamless, we calculate the rounded difference of + // "worlds" between the last frame and the current frame. If the map panned by + // a world, then we can assign all the tiles new TileIDs with updated wrap values. + // For example, assign z/x/y/1 a new id: z/x/y/0. It is the same tile, just rendered + // in a different position. + // + // This enables us to reuse the tiles at more ideal locations and prevent flickering. + const prevLng = this._prevLng === undefined ? lng : this._prevLng; + const lngDifference = lng - prevLng; + const worldDifference = lngDifference / 360; + const wrapDelta = Math.round(worldDifference); + this._prevLng = lng; + if (wrapDelta) { + const tiles = {}; + for (const key in this._tiles) { + const tile = this._tiles[key]; + tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta); + tiles[tile.tileID.key] = tile; + } + this._tiles = tiles; + // Reset tile reload timers + for (const id in this._timers) { + clearTimeout(this._timers[id]); + delete this._timers[id]; + } + for (const id in this._tiles) { + const tile = this._tiles[id]; + this._setTileReloadTimer(id, tile); + } + } + } + _updateCoveredAndRetainedTiles(retain, minCoveringZoom, maxCoveringZoom, zoom, idealTileIDs, terrain) { + const tilesForFading = {}; + const fadingTiles = {}; + const ids = Object.keys(retain); + const now = browser.now(); + for (const id of ids) { + const tileID = retain[id]; + const tile = this._tiles[id]; + // when fadeEndTime is 0, the tile is created but registerFadeDuration + // has not been called, therefore must be kept in fadingTiles dictionary + // for next round of rendering + if (!tile || (tile.fadeEndTime !== 0 && tile.fadeEndTime <= now)) { + continue; + } + // if the tile is loaded but still fading in, find parents to cross-fade with it + const parentTile = this.findLoadedParent(tileID, minCoveringZoom); + const siblingTile = this.findLoadedSibling(tileID); + const fadeTileRef = parentTile || siblingTile || null; + if (fadeTileRef) { + this._addTile(fadeTileRef.tileID); + tilesForFading[fadeTileRef.tileID.key] = fadeTileRef.tileID; + } + fadingTiles[id] = tileID; + } + // for tiles that are still fading in, also find children to cross-fade with + this._retainLoadedChildren(fadingTiles, zoom, maxCoveringZoom, retain); + for (const id in tilesForFading) { + if (!retain[id]) { + // If a tile is only needed for fading, mark it as covered so that it isn't rendered on it's own. + this._coveredTiles[id] = true; + retain[id] = tilesForFading[id]; + } + } + // disable fading logic in terrain3D mode to avoid rendering two tiles on the same place + if (terrain) { + const idealRasterTileIDs = {}; + const missingTileIDs = {}; + for (const tileID of idealTileIDs) { + if (this._tiles[tileID.key].hasData()) + idealRasterTileIDs[tileID.key] = tileID; + else + missingTileIDs[tileID.key] = tileID; + } + // search for a complete set of children for each missing tile + for (const key in missingTileIDs) { + const children = missingTileIDs[key].children(this._source.maxzoom); + if (this._tiles[children[0].key] && this._tiles[children[1].key] && this._tiles[children[2].key] && this._tiles[children[3].key]) { + idealRasterTileIDs[children[0].key] = retain[children[0].key] = children[0]; + idealRasterTileIDs[children[1].key] = retain[children[1].key] = children[1]; + idealRasterTileIDs[children[2].key] = retain[children[2].key] = children[2]; + idealRasterTileIDs[children[3].key] = retain[children[3].key] = children[3]; + delete missingTileIDs[key]; + } + } + // search for parent or sibling for each missing tile + for (const key in missingTileIDs) { + const tileID = missingTileIDs[key]; + const parentTile = this.findLoadedParent(tileID, this._source.minzoom); + const siblingTile = this.findLoadedSibling(tileID); + const fadeTileRef = parentTile || siblingTile || null; + if (fadeTileRef) { + idealRasterTileIDs[fadeTileRef.tileID.key] = retain[fadeTileRef.tileID.key] = fadeTileRef.tileID; + // remove idealTiles which would be rendered twice + for (const key in idealRasterTileIDs) { + if (idealRasterTileIDs[key].isChildOf(fadeTileRef.tileID)) + delete idealRasterTileIDs[key]; + } + } + } + // cover all tiles which are not needed + for (const key in this._tiles) { + if (!idealRasterTileIDs[key]) + this._coveredTiles[key] = true; + } + } + } + /** + * Removes tiles that are outside the viewport and adds new tiles that + * are inside the viewport. + */ + update(transform, terrain) { + if (!this._sourceLoaded || this._paused) { + return; + } + this.transform = transform; + this.terrain = terrain; + this.updateCacheSize(transform); + this.handleWrapJump(this.transform.center.lng); + // Covered is a list of retained tiles who's areas are fully covered by other, + // better, retained tiles. They are not drawn separately. + this._coveredTiles = {}; + let idealTileIDs; + if (!this.used && !this.usedForTerrain) { + idealTileIDs = []; + } + else if (this._source.tileID) { + idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID) + .map((unwrapped) => new performance$1.S(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y)); + } + else { + idealTileIDs = transform.coveringTiles({ + tileSize: this.usedForTerrain ? this.tileSize : this._source.tileSize, + minzoom: this._source.minzoom, + maxzoom: this._source.maxzoom, + roundZoom: this.usedForTerrain ? false : this._source.roundZoom, + reparseOverscaled: this._source.reparseOverscaled, + terrain + }); + if (this._source.hasTile) { + idealTileIDs = idealTileIDs.filter((coord) => this._source.hasTile(coord)); + } + } + // Determine the overzooming/underzooming amounts. + const zoom = transform.coveringZoomLevel(this._source); + const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom); + const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom); + // When sourcecache is used for terrain also load parent tiles to avoid flickering when zooming out + if (this.usedForTerrain) { + const parents = {}; + for (const tileID of idealTileIDs) { + if (tileID.canonical.z > this._source.minzoom) { + const parent = tileID.scaledTo(tileID.canonical.z - 1); + parents[parent.key] = parent; + // load very low zoom to calculate tile visibility in transform.coveringTiles and high zoomlevels correct + const parent2 = tileID.scaledTo(Math.max(this._source.minzoom, Math.min(tileID.canonical.z, 5))); + parents[parent2.key] = parent2; + } + } + idealTileIDs = idealTileIDs.concat(Object.values(parents)); + } + const noPendingDataEmissions = idealTileIDs.length === 0 && !this._updated && this._didEmitContent; + this._updated = true; + // if we won't have any tiles to fetch and content is already emitted + // there will be no more data emissions, so we need to emit the event with isSourceLoaded = true + if (noPendingDataEmissions) { + this.fire(new performance$1.k('data', { sourceDataType: 'idle', dataType: 'source', sourceId: this.id })); + } + // Retain is a list of tiles that we shouldn't delete, even if they are not + // the most ideal tile for the current viewport. This may include tiles like + // parent or child tiles that are *already* loaded. + const retain = this._updateRetainedTiles(idealTileIDs, zoom); + if (isRasterType(this._source.type)) { + this._updateCoveredAndRetainedTiles(retain, minCoveringZoom, maxCoveringZoom, zoom, idealTileIDs, terrain); + } + for (const retainedId in retain) { + // Make sure retained tiles always clear any existing fade holds + // so that if they're removed again their fade timer starts fresh. + this._tiles[retainedId].clearFadeHold(); + } + // Remove the tiles we don't need anymore. + const remove = performance$1.ab(this._tiles, retain); + for (const tileID of remove) { + const tile = this._tiles[tileID]; + if (tile.hasSymbolBuckets && !tile.holdingForFade()) { + tile.setHoldDuration(this.map._fadeDuration); + } + else if (!tile.hasSymbolBuckets || tile.symbolFadeFinished()) { + this._removeTile(tileID); + } + } + // Construct caches of loaded parents & siblings + this._updateLoadedParentTileCache(); + this._updateLoadedSiblingTileCache(); + } + releaseSymbolFadeTiles() { + for (const id in this._tiles) { + if (this._tiles[id].holdingForFade()) { + this._removeTile(id); + } + } + } + _updateRetainedTiles(idealTileIDs, zoom) { + var _a; + const retain = {}; + const checked = {}; + const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom); + const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom); + const missingTiles = {}; + for (const tileID of idealTileIDs) { + const tile = this._addTile(tileID); + // retain the tile even if it's not loaded because it's an ideal tile. + retain[tileID.key] = tileID; + if (tile.hasData()) + continue; + if (zoom < this._source.maxzoom) { + // save missing tiles that potentially have loaded children + missingTiles[tileID.key] = tileID; + } + } + // retain any loaded children of ideal tiles up to maxCoveringZoom + this._retainLoadedChildren(missingTiles, zoom, maxCoveringZoom, retain); + for (const tileID of idealTileIDs) { + let tile = this._tiles[tileID.key]; + if (tile.hasData()) + continue; + // The tile we require is not yet loaded or does not exist; + // Attempt to find children that fully cover it. + if (zoom + 1 > this._source.maxzoom) { + // We're looking for an overzoomed child tile. + const childCoord = tileID.children(this._source.maxzoom)[0]; + const childTile = this.getTile(childCoord); + if (!!childTile && childTile.hasData()) { + retain[childCoord.key] = childCoord; + continue; // tile is covered by overzoomed child + } + } + else { + // check if all 4 immediate children are loaded (i.e. the missing ideal tile is covered) + const children = tileID.children(this._source.maxzoom); + if (retain[children[0].key] && + retain[children[1].key] && + retain[children[2].key] && + retain[children[3].key]) + continue; // tile is covered by children + } + // We couldn't find child tiles that entirely cover the ideal tile; look for parents now. + // As we ascend up the tile pyramid of the ideal tile, we check whether the parent + // tile has been previously requested (and errored because we only loop over tiles with no data) + // in order to determine if we need to request its parent. + let parentWasRequested = tile.wasRequested(); + for (let overscaledZ = tileID.overscaledZ - 1; overscaledZ >= minCoveringZoom; --overscaledZ) { + const parentId = tileID.scaledTo(overscaledZ); + // Break parent tile ascent if this route has been previously checked by another child. + if (checked[parentId.key]) + break; + checked[parentId.key] = true; + tile = this.getTile(parentId); + if (!tile && parentWasRequested) { + tile = this._addTile(parentId); + } + if (tile) { + const hasData = tile.hasData(); + if (hasData || !((_a = this.map) === null || _a === void 0 ? void 0 : _a.cancelPendingTileRequestsWhileZooming) || parentWasRequested) { + retain[parentId.key] = parentId; + } + // Save the current values, since they're the parent of the next iteration + // of the parent tile ascent loop. + parentWasRequested = tile.wasRequested(); + if (hasData) + break; + } + } + } + return retain; + } + _updateLoadedParentTileCache() { + this._loadedParentTiles = {}; + for (const tileKey in this._tiles) { + const path = []; + let parentTile; + let currentId = this._tiles[tileKey].tileID; + // Find the closest loaded ancestor by traversing the tile tree towards the root and + // caching results along the way + while (currentId.overscaledZ > 0) { + // Do we have a cached result from previous traversals? + if (currentId.key in this._loadedParentTiles) { + parentTile = this._loadedParentTiles[currentId.key]; + break; + } + path.push(currentId.key); + // Is the parent loaded? + const parentId = currentId.scaledTo(currentId.overscaledZ - 1); + parentTile = this._getLoadedTile(parentId); + if (parentTile) { + break; + } + currentId = parentId; + } + // Cache the result of this traversal to all newly visited tiles + for (const key of path) { + this._loadedParentTiles[key] = parentTile; + } + } + } + /** + * Update the cache of loaded sibling tiles + * + * Sibling tiles are tiles that share the same zoom level and + * x/y position but have different wrap values + * Maintaining sibling tile cache allows fading from old to new tiles + * of the same position and zoom level + */ + _updateLoadedSiblingTileCache() { + this._loadedSiblingTiles = {}; + for (const tileKey in this._tiles) { + const currentId = this._tiles[tileKey].tileID; + const siblingTile = this._getLoadedTile(currentId); + this._loadedSiblingTiles[currentId.key] = siblingTile; + } + } + /** + * Add a tile, given its coordinate, to the pyramid. + */ + _addTile(tileID) { + let tile = this._tiles[tileID.key]; + if (tile) + return tile; + tile = this._cache.getAndRemove(tileID); + if (tile) { + this._setTileReloadTimer(tileID.key, tile); + // set the tileID because the cached tile could have had a different wrap value + tile.tileID = tileID; + this._state.initializeTileState(tile, this.map ? this.map.painter : null); + if (this._cacheTimers[tileID.key]) { + clearTimeout(this._cacheTimers[tileID.key]); + delete this._cacheTimers[tileID.key]; + this._setTileReloadTimer(tileID.key, tile); + } + } + const cached = tile; + if (!tile) { + tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor()); + this._loadTile(tile, tileID.key, tile.state); + } + tile.uses++; + this._tiles[tileID.key] = tile; + if (!cached) { + this._source.fire(new performance$1.k('dataloading', { tile, coord: tile.tileID, dataType: 'source' })); + } + return tile; + } + _setTileReloadTimer(id, tile) { + if (id in this._timers) { + clearTimeout(this._timers[id]); + delete this._timers[id]; + } + const expiryTimeout = tile.getExpiryTimeout(); + if (expiryTimeout) { + this._timers[id] = setTimeout(() => { + this._reloadTile(id, 'expired'); + delete this._timers[id]; + }, expiryTimeout); + } + } + /** + * Remove a tile, given its id, from the pyramid + */ + _removeTile(id) { + const tile = this._tiles[id]; + if (!tile) + return; + tile.uses--; + delete this._tiles[id]; + if (this._timers[id]) { + clearTimeout(this._timers[id]); + delete this._timers[id]; + } + if (tile.uses > 0) + return; + if (tile.hasData() && tile.state !== 'reloading') { + this._cache.add(tile.tileID, tile, tile.getExpiryTimeout()); + } + else { + tile.aborted = true; + this._abortTile(tile); + this._unloadTile(tile); + } + } + /** @internal */ + _dataHandler(e) { + const eventSourceDataType = e.sourceDataType; + if (e.dataType === 'source' && eventSourceDataType === 'metadata') { + this._sourceLoaded = true; + } + // for sources with mutable data, this event fires when the underlying data + // to a source is changed. (i.e. GeoJSONSource#setData and ImageSource#serCoordinates) + if (this._sourceLoaded && !this._paused && e.dataType === 'source' && eventSourceDataType === 'content') { + this.reload(); + if (this.transform) { + this.update(this.transform, this.terrain); + } + this._didEmitContent = true; + } + } + /** + * Remove all tiles from this pyramid + */ + clearTiles() { + this._shouldReloadOnResume = false; + this._paused = false; + for (const id in this._tiles) + this._removeTile(id); + this._cache.reset(); + } + /** + * Search through our current tiles and attempt to find the tiles that + * cover the given bounds. + * @param pointQueryGeometry - coordinates of the corners of bounding rectangle + * @returns result items have `{tile, minX, maxX, minY, maxY}`, where min/max bounding values are the given bounds transformed in into the coordinate space of this tile. + */ + tilesIn(pointQueryGeometry, maxPitchScaleFactor, has3DLayer) { + const tileResults = []; + const transform = this.transform; + if (!transform) + return tileResults; + const cameraPointQueryGeometry = has3DLayer ? + transform.getCameraQueryGeometry(pointQueryGeometry) : + pointQueryGeometry; + const queryGeometry = pointQueryGeometry.map((p) => transform.pointCoordinate(p, this.terrain)); + const cameraQueryGeometry = cameraPointQueryGeometry.map((p) => transform.pointCoordinate(p, this.terrain)); + const ids = this.getIds(); + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const p of cameraQueryGeometry) { + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + for (let i = 0; i < ids.length; i++) { + const tile = this._tiles[ids[i]]; + if (tile.holdingForFade()) { + // Tiles held for fading are covered by tiles that are closer to ideal + continue; + } + const tileID = tile.tileID; + const scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ); + const queryPadding = maxPitchScaleFactor * tile.queryPadding * performance$1.X / tile.tileSize / scale; + const tileSpaceBounds = [ + tileID.getTilePoint(new performance$1.Z(minX, minY)), + tileID.getTilePoint(new performance$1.Z(maxX, maxY)) + ]; + if (tileSpaceBounds[0].x - queryPadding < performance$1.X && tileSpaceBounds[0].y - queryPadding < performance$1.X && + tileSpaceBounds[1].x + queryPadding >= 0 && tileSpaceBounds[1].y + queryPadding >= 0) { + const tileSpaceQueryGeometry = queryGeometry.map((c) => tileID.getTilePoint(c)); + const tileSpaceCameraQueryGeometry = cameraQueryGeometry.map((c) => tileID.getTilePoint(c)); + tileResults.push({ + tile, + tileID, + queryGeometry: tileSpaceQueryGeometry, + cameraQueryGeometry: tileSpaceCameraQueryGeometry, + scale + }); + } + } + return tileResults; + } + getVisibleCoordinates(symbolLayer) { + const coords = this.getRenderableIds(symbolLayer).map((id) => this._tiles[id].tileID); + for (const coord of coords) { + coord.posMatrix = this.transform.calculatePosMatrix(coord.toUnwrapped()); + } + return coords; + } + hasTransition() { + if (this._source.hasTransition()) { + return true; + } + if (isRasterType(this._source.type)) { + const now = browser.now(); + for (const id in this._tiles) { + const tile = this._tiles[id]; + if (tile.fadeEndTime >= now) { + return true; + } + } + } + return false; + } + /** + * Set the value of a particular state for a feature + */ + setFeatureState(sourceLayer, featureId, state) { + sourceLayer = sourceLayer || '_geojsonTileLayer'; + this._state.updateState(sourceLayer, featureId, state); + } + /** + * Resets the value of a particular state key for a feature + */ + removeFeatureState(sourceLayer, featureId, key) { + sourceLayer = sourceLayer || '_geojsonTileLayer'; + this._state.removeFeatureState(sourceLayer, featureId, key); + } + /** + * Get the entire state object for a feature + */ + getFeatureState(sourceLayer, featureId) { + sourceLayer = sourceLayer || '_geojsonTileLayer'; + return this._state.getState(sourceLayer, featureId); + } + /** + * Sets the set of keys that the tile depends on. This allows tiles to + * be reloaded when their dependencies change. + */ + setDependencies(tileKey, namespace, dependencies) { + const tile = this._tiles[tileKey]; + if (tile) { + tile.setDependencies(namespace, dependencies); + } + } + /** + * Reloads all tiles that depend on the given keys. + */ + reloadTilesForDependencies(namespaces, keys) { + for (const id in this._tiles) { + const tile = this._tiles[id]; + if (tile.hasDependency(namespaces, keys)) { + this._reloadTile(id, 'reloading'); + } + } + this._cache.filter(tile => !tile.hasDependency(namespaces, keys)); + } +} +SourceCache.maxOverzooming = 10; +SourceCache.maxUnderzooming = 3; +function compareTileId(a, b) { + // Different copies of the world are sorted based on their distance to the center. + // Wrap values are converted to unsigned distances by reserving odd number for copies + // with negative wrap and even numbers for copies with positive wrap. + const aWrap = Math.abs(a.wrap * 2) - +(a.wrap < 0); + const bWrap = Math.abs(b.wrap * 2) - +(b.wrap < 0); + return a.overscaledZ - b.overscaledZ || bWrap - aWrap || b.canonical.y - a.canonical.y || b.canonical.x - a.canonical.x; +} +function isRasterType(type) { + return type === 'raster' || type === 'image' || type === 'video'; +} + +class PathInterpolator { + constructor(points_, padding_) { + this.reset(points_, padding_); + } + reset(points_, padding_) { + this.points = points_ || []; + // Compute cumulative distance from first point to every other point in the segment. + // Last entry in the array is total length of the path + this._distances = [0.0]; + for (let i = 1; i < this.points.length; i++) { + this._distances[i] = this._distances[i - 1] + this.points[i].dist(this.points[i - 1]); + } + this.length = this._distances[this._distances.length - 1]; + this.padding = Math.min(padding_ || 0, this.length * 0.5); + this.paddedLength = this.length - this.padding * 2.0; + } + lerp(t) { + if (this.points.length === 1) { + return this.points[0]; + } + t = performance$1.ac(t, 0, 1); + // Find the correct segment [p0, p1] where p0 <= x < p1 + let currentIndex = 1; + let distOfCurrentIdx = this._distances[currentIndex]; + const distToTarget = t * this.paddedLength + this.padding; + while (distOfCurrentIdx < distToTarget && currentIndex < this._distances.length) { + distOfCurrentIdx = this._distances[++currentIndex]; + } + // Interpolate between the two points of the segment + const idxOfPrevPoint = currentIndex - 1; + const distOfPrevIdx = this._distances[idxOfPrevPoint]; + const segmentLength = distOfCurrentIdx - distOfPrevIdx; + const segmentT = segmentLength > 0 ? (distToTarget - distOfPrevIdx) / segmentLength : 0; + return this.points[idxOfPrevPoint].mult(1.0 - segmentT).add(this.points[currentIndex].mult(segmentT)); + } +} + +function overlapAllowed(overlapA, overlapB) { + let allowed = true; + if (overlapA === 'always') ; + else if (overlapA === 'never' || overlapB === 'never') { + // symbol A using 'never' overlap - can't overlap anything + // symbol A using 'cooperative' overlap - can overlap 'always' or 'cooperative' symbol; can't overlap 'never' + allowed = false; + } + return allowed; +} +/** + * @internal + * GridIndex is a data structure for testing the intersection of + * circles and rectangles in a 2d plane. + * It is optimized for rapid insertion and querying. + * GridIndex splits the plane into a set of "cells" and keeps track + * of which geometries intersect with each cell. At query time, + * full geometry comparisons are only done for items that share + * at least one cell. As long as the geometries are relatively + * uniformly distributed across the plane, this greatly reduces + * the number of comparisons necessary. + */ +class GridIndex { + constructor(width, height, cellSize) { + const boxCells = this.boxCells = []; + const circleCells = this.circleCells = []; + // More cells -> fewer geometries to check per cell, but items tend + // to be split across more cells. + // Sweet spot allows most small items to fit in one cell + this.xCellCount = Math.ceil(width / cellSize); + this.yCellCount = Math.ceil(height / cellSize); + for (let i = 0; i < this.xCellCount * this.yCellCount; i++) { + boxCells.push([]); + circleCells.push([]); + } + this.circleKeys = []; + this.boxKeys = []; + this.bboxes = []; + this.circles = []; + this.width = width; + this.height = height; + this.xScale = this.xCellCount / width; + this.yScale = this.yCellCount / height; + this.boxUid = 0; + this.circleUid = 0; + } + keysLength() { + return this.boxKeys.length + this.circleKeys.length; + } + insert(key, x1, y1, x2, y2) { + this._forEachCell(x1, y1, x2, y2, this._insertBoxCell, this.boxUid++); + this.boxKeys.push(key); + this.bboxes.push(x1); + this.bboxes.push(y1); + this.bboxes.push(x2); + this.bboxes.push(y2); + } + insertCircle(key, x, y, radius) { + // Insert circle into grid for all cells in the circumscribing square + // It's more than necessary (by a factor of 4/PI), but fast to insert + this._forEachCell(x - radius, y - radius, x + radius, y + radius, this._insertCircleCell, this.circleUid++); + this.circleKeys.push(key); + this.circles.push(x); + this.circles.push(y); + this.circles.push(radius); + } + _insertBoxCell(x1, y1, x2, y2, cellIndex, uid) { + this.boxCells[cellIndex].push(uid); + } + _insertCircleCell(x1, y1, x2, y2, cellIndex, uid) { + this.circleCells[cellIndex].push(uid); + } + _query(x1, y1, x2, y2, hitTest, overlapMode, predicate) { + if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) { + return []; + } + const result = []; + if (x1 <= 0 && y1 <= 0 && this.width <= x2 && this.height <= y2) { + if (hitTest) { + // Covers the entire grid, so collides with everything + return [{ + key: null, + x1, + y1, + x2, + y2 + }]; + } + for (let boxUid = 0; boxUid < this.boxKeys.length; boxUid++) { + result.push({ + key: this.boxKeys[boxUid], + x1: this.bboxes[boxUid * 4], + y1: this.bboxes[boxUid * 4 + 1], + x2: this.bboxes[boxUid * 4 + 2], + y2: this.bboxes[boxUid * 4 + 3] + }); + } + for (let circleUid = 0; circleUid < this.circleKeys.length; circleUid++) { + const x = this.circles[circleUid * 3]; + const y = this.circles[circleUid * 3 + 1]; + const radius = this.circles[circleUid * 3 + 2]; + result.push({ + key: this.circleKeys[circleUid], + x1: x - radius, + y1: y - radius, + x2: x + radius, + y2: y + radius + }); + } + } + else { + const queryArgs = { + hitTest, + overlapMode, + seenUids: { box: {}, circle: {} } + }; + this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate); + } + return result; + } + query(x1, y1, x2, y2) { + return this._query(x1, y1, x2, y2, false, null); + } + hitTest(x1, y1, x2, y2, overlapMode, predicate) { + return this._query(x1, y1, x2, y2, true, overlapMode, predicate).length > 0; + } + hitTestCircle(x, y, radius, overlapMode, predicate) { + // Insert circle into grid for all cells in the circumscribing square + // It's more than necessary (by a factor of 4/PI), but fast to insert + const x1 = x - radius; + const x2 = x + radius; + const y1 = y - radius; + const y2 = y + radius; + if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) { + return false; + } + // Box query early exits if the bounding box is larger than the grid, but we don't do + // the equivalent calculation for circle queries because early exit is less likely + // and the calculation is more expensive + const result = []; + const queryArgs = { + hitTest: true, + overlapMode, + circle: { x, y, radius }, + seenUids: { box: {}, circle: {} } + }; + this._forEachCell(x1, y1, x2, y2, this._queryCellCircle, result, queryArgs, predicate); + return result.length > 0; + } + _queryCell(x1, y1, x2, y2, cellIndex, result, queryArgs, predicate) { + const { seenUids, hitTest, overlapMode } = queryArgs; + const boxCell = this.boxCells[cellIndex]; + if (boxCell !== null) { + const bboxes = this.bboxes; + for (const boxUid of boxCell) { + if (!seenUids.box[boxUid]) { + seenUids.box[boxUid] = true; + const offset = boxUid * 4; + const key = this.boxKeys[boxUid]; + if ((x1 <= bboxes[offset + 2]) && + (y1 <= bboxes[offset + 3]) && + (x2 >= bboxes[offset + 0]) && + (y2 >= bboxes[offset + 1]) && + (!predicate || predicate(key))) { + if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) { + result.push({ + key, + x1: bboxes[offset], + y1: bboxes[offset + 1], + x2: bboxes[offset + 2], + y2: bboxes[offset + 3] + }); + if (hitTest) { + // true return value stops the query after first match + return true; + } + } + } + } + } + } + const circleCell = this.circleCells[cellIndex]; + if (circleCell !== null) { + const circles = this.circles; + for (const circleUid of circleCell) { + if (!seenUids.circle[circleUid]) { + seenUids.circle[circleUid] = true; + const offset = circleUid * 3; + const key = this.circleKeys[circleUid]; + if (this._circleAndRectCollide(circles[offset], circles[offset + 1], circles[offset + 2], x1, y1, x2, y2) && + (!predicate || predicate(key))) { + if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) { + const x = circles[offset]; + const y = circles[offset + 1]; + const radius = circles[offset + 2]; + result.push({ + key, + x1: x - radius, + y1: y - radius, + x2: x + radius, + y2: y + radius + }); + if (hitTest) { + // true return value stops the query after first match + return true; + } + } + } + } + } + } + // false return to continue query + return false; + } + _queryCellCircle(x1, y1, x2, y2, cellIndex, result, queryArgs, predicate) { + const { circle, seenUids, overlapMode } = queryArgs; + const boxCell = this.boxCells[cellIndex]; + if (boxCell !== null) { + const bboxes = this.bboxes; + for (const boxUid of boxCell) { + if (!seenUids.box[boxUid]) { + seenUids.box[boxUid] = true; + const offset = boxUid * 4; + const key = this.boxKeys[boxUid]; + if (this._circleAndRectCollide(circle.x, circle.y, circle.radius, bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) && + (!predicate || predicate(key)) && + !overlapAllowed(overlapMode, key.overlapMode)) { + result.push(true); + return true; + } + } + } + } + const circleCell = this.circleCells[cellIndex]; + if (circleCell !== null) { + const circles = this.circles; + for (const circleUid of circleCell) { + if (!seenUids.circle[circleUid]) { + seenUids.circle[circleUid] = true; + const offset = circleUid * 3; + const key = this.circleKeys[circleUid]; + if (this._circlesCollide(circles[offset], circles[offset + 1], circles[offset + 2], circle.x, circle.y, circle.radius) && + (!predicate || predicate(key)) && + !overlapAllowed(overlapMode, key.overlapMode)) { + result.push(true); + return true; + } + } + } + } + } + _forEachCell(x1, y1, x2, y2, fn, arg1, arg2, predicate) { + const cx1 = this._convertToXCellCoord(x1); + const cy1 = this._convertToYCellCoord(y1); + const cx2 = this._convertToXCellCoord(x2); + const cy2 = this._convertToYCellCoord(y2); + for (let x = cx1; x <= cx2; x++) { + for (let y = cy1; y <= cy2; y++) { + const cellIndex = this.xCellCount * y + x; + if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, predicate)) + return; + } + } + } + _convertToXCellCoord(x) { + return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(x * this.xScale))); + } + _convertToYCellCoord(y) { + return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(y * this.yScale))); + } + _circlesCollide(x1, y1, r1, x2, y2, r2) { + const dx = x2 - x1; + const dy = y2 - y1; + const bothRadii = r1 + r2; + return (bothRadii * bothRadii) > (dx * dx + dy * dy); + } + _circleAndRectCollide(circleX, circleY, radius, x1, y1, x2, y2) { + const halfRectWidth = (x2 - x1) / 2; + const distX = Math.abs(circleX - (x1 + halfRectWidth)); + if (distX > (halfRectWidth + radius)) { + return false; + } + const halfRectHeight = (y2 - y1) / 2; + const distY = Math.abs(circleY - (y1 + halfRectHeight)); + if (distY > (halfRectHeight + radius)) { + return false; + } + if (distX <= halfRectWidth || distY <= halfRectHeight) { + return true; + } + const dx = distX - halfRectWidth; + const dy = distY - halfRectHeight; + return (dx * dx + dy * dy <= (radius * radius)); + } +} + +/* + * # Overview of coordinate spaces + * + * ## Tile coordinate spaces + * Each label has an anchor. Some labels have corresponding line geometries. + * The points for both anchors and lines are stored in tile units. Each tile has it's own + * coordinate space going from (0, 0) at the top left to (EXTENT, EXTENT) at the bottom right. + * + * ## Clip space (GL coordinate space) + * At the end of everything, the vertex shader needs to produce a position in clip space, + * which is (-1, 1) at the top left and (1, -1) in the bottom right. + * In the depth buffer, values are between 0 (near plane) to 1 (far plane). + * + * ## Map pixel coordinate spaces + * Each tile has a pixel coordinate space. It's just the tile units scaled so that one unit is + * whatever counts as 1 pixel at the current zoom. + * This space is used for pitch-alignment=map, rotation-alignment=map + * + * ## Rotated map pixel coordinate spaces + * Like the above, but rotated so axis of the space are aligned with the viewport instead of the tile. + * This space is used for pitch-alignment=map, rotation-alignment=viewport + * + * ## Viewport pixel coordinate space + * (0, 0) is at the top left of the canvas and (pixelWidth, pixelHeight) is at the bottom right corner + * of the canvas. This space is used for pitch-alignment=viewport + * + * + * # Vertex projection + * It goes roughly like this: + * 1. project the anchor and line from tile units into the correct label coordinate space + * - map pixel space pitch-alignment=map rotation-alignment=map + * - rotated map pixel space pitch-alignment=map rotation-alignment=viewport + * - viewport pixel space pitch-alignment=viewport rotation-alignment=* + * 2. if the label follows a line, find the point along the line that is the correct distance from the anchor. + * 3. add the glyph's corner offset to the point from step 3 + * 4. convert from the label coordinate space to clip space + * + * For horizontal labels we want to do step 1 in the shader for performance reasons (no cpu work). + * This is what `u_label_plane_matrix` is used for. + * For labels aligned with lines we have to steps 1 and 2 on the cpu since we need access to the line geometry. + * This is what `updateLineLabels(...)` does. + * Since the conversion is handled on the cpu we just set `u_label_plane_matrix` to an identity matrix. + * + * Steps 3 and 4 are done in the shaders for all labels. + */ +/* + * Returns a matrix for converting from tile units to the correct label coordinate space. + */ +function getLabelPlaneMatrix(posMatrix, pitchWithMap, rotateWithMap, transform, pixelsToTileUnits) { + const m = performance$1.H(); + if (pitchWithMap) { + performance$1.K(m, m, [1 / pixelsToTileUnits, 1 / pixelsToTileUnits, 1]); + if (!rotateWithMap) { + performance$1.ad(m, m, transform.angle); + } + } + else { + performance$1.L(m, transform.labelPlaneMatrix, posMatrix); + } + return m; +} +/* + * Returns a matrix for converting from the correct label coordinate space to clip space. + */ +function getGlCoordMatrix(posMatrix, pitchWithMap, rotateWithMap, transform, pixelsToTileUnits) { + if (pitchWithMap) { + const m = performance$1.ae(posMatrix); + performance$1.K(m, m, [pixelsToTileUnits, pixelsToTileUnits, 1]); + if (!rotateWithMap) { + performance$1.ad(m, m, -transform.angle); + } + return m; + } + else { + return transform.glCoordMatrix; + } +} +function project(x, y, matrix, getElevation) { + let pos; + if (getElevation) { // slow because of handle z-index + pos = [x, y, getElevation(x, y), 1]; + performance$1.af(pos, pos, matrix); + } + else { // fast because of ignore z-index + pos = [x, y, 0, 1]; + xyTransformMat4(pos, pos, matrix); + } + const w = pos[3]; + return { + point: new performance$1.P(pos[0] / w, pos[1] / w), + signedDistanceFromCamera: w, + isOccluded: false + }; +} +function getPerspectiveRatio(cameraToCenterDistance, signedDistanceFromCamera) { + return 0.5 + 0.5 * (cameraToCenterDistance / signedDistanceFromCamera); +} +function isVisible(p, clippingBuffer) { + const inPaddedViewport = (p.x >= -clippingBuffer[0] && + p.x <= clippingBuffer[0] && + p.y >= -clippingBuffer[1] && + p.y <= clippingBuffer[1]); + return inPaddedViewport; +} +/* + * Update the `dynamicLayoutVertexBuffer` for the buffer with the correct glyph positions for the current map view. + * This is only run on labels that are aligned with lines. Horizontal labels are handled entirely in the shader. + */ +function updateLineLabels(bucket, posMatrix, painter, isText, labelPlaneMatrix, glCoordMatrix, pitchWithMap, keepUpright, rotateToLine, projection, unwrappedTileID, viewportWidth, viewportHeight, translation, getElevation) { + const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData; + const partiallyEvaluatedSize = performance$1.ag(sizeData, painter.transform.zoom); + const clippingBuffer = [256 / painter.width * 2 + 1, 256 / painter.height * 2 + 1]; + const dynamicLayoutVertexArray = isText ? + bucket.text.dynamicLayoutVertexArray : + bucket.icon.dynamicLayoutVertexArray; + dynamicLayoutVertexArray.clear(); + const lineVertexArray = bucket.lineVertexArray; + const placedSymbols = isText ? bucket.text.placedSymbolArray : bucket.icon.placedSymbolArray; + const aspectRatio = painter.transform.width / painter.transform.height; + let useVertical = false; + for (let s = 0; s < placedSymbols.length; s++) { + const symbol = placedSymbols.get(s); + // Don't do calculations for vertical glyphs unless the previous symbol was horizontal + // and we determined that vertical glyphs were necessary. + // Also don't do calculations for symbols that are collided and fully faded out + if (symbol.hidden || symbol.writingMode === performance$1.ah.vertical && !useVertical) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + continue; + } + // Awkward... but we're counting on the paired "vertical" symbol coming immediately after its horizontal counterpart + useVertical = false; + const anchorPos = project(symbol.anchorX, symbol.anchorY, posMatrix, getElevation); + // Don't bother calculating the correct point for invisible labels. + if (!isVisible(anchorPos.point, clippingBuffer)) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + continue; + } + const cameraToAnchorDistance = anchorPos.signedDistanceFromCamera; + const perspectiveRatio = getPerspectiveRatio(painter.transform.cameraToCenterDistance, cameraToAnchorDistance); + const fontSize = performance$1.ai(sizeData, partiallyEvaluatedSize, symbol); + const pitchScaledFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio; + const tileAnchorPoint = new performance$1.P(symbol.anchorX, symbol.anchorY); + const projectionCache = { projections: {}, offsets: {}, cachedAnchorPoint: undefined, anyProjectionOccluded: false }; + const projectionContext = { + getElevation, + labelPlaneMatrix, + lineVertexArray, + pitchWithMap, + projectionCache, + projection, + tileAnchorPoint, + unwrappedTileID, + width: viewportWidth, + height: viewportHeight, + translation + }; + const placeUnflipped = placeGlyphsAlongLine(projectionContext, symbol, pitchScaledFontSize, false /*unflipped*/, keepUpright, posMatrix, glCoordMatrix, bucket.glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine); + useVertical = placeUnflipped.useVertical; + if (placeUnflipped.notEnoughRoom || useVertical || + (placeUnflipped.needsFlipping && + placeGlyphsAlongLine(projectionContext, symbol, pitchScaledFontSize, true /*flipped*/, keepUpright, posMatrix, glCoordMatrix, bucket.glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine).notEnoughRoom)) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + } + } + if (isText) { + bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray); + } + else { + bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray); + } +} +/* + * Place the first and last glyph of a line label, projected to the label plane. + * This function is called both during collision detection (to determine the label's size) + * and during line label rendering (to make sure the label fits on the line geometry with + * the current camera position, which may differ from the position used during collision detection). + * + * Calling this function has the effect of populating the "projectionCache" with all projected + * vertex locations the label will need, making future calls to placeGlyphAlongLine (for all the + * intermediate glyphs) much cheaper. + * + * Returns null if the label can't fit on the geometry + */ +function placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, symbol, rotateToLine, projectionContext) { + const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs; + const lineStartIndex = symbol.lineStartIndex; + const lineEndIndex = symbol.lineStartIndex + symbol.lineLength; + const firstGlyphOffset = glyphOffsetArray.getoffsetX(symbol.glyphStartIndex); + const lastGlyphOffset = glyphOffsetArray.getoffsetX(glyphEndIndex - 1); + const firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, lineOffsetX, lineOffsetY, flip, symbol.segment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine); + if (!firstPlacedGlyph) + return null; + const lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, symbol.segment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine); + if (!lastPlacedGlyph) + return null; + if (projectionContext.projectionCache.anyProjectionOccluded) { + return null; + } + return { first: firstPlacedGlyph, last: lastPlacedGlyph }; +} +function requiresOrientationChange(writingMode, firstPoint, lastPoint, aspectRatio) { + if (writingMode === performance$1.ah.horizontal) { + // On top of choosing whether to flip, choose whether to render this version of the glyphs or the alternate + // vertical glyphs. We can't just filter out vertical glyphs in the horizontal range because the horizontal + // and vertical versions can have slightly different projections which could lead to angles where both or + // neither showed. + const rise = Math.abs(lastPoint.y - firstPoint.y); + const run = Math.abs(lastPoint.x - firstPoint.x) * aspectRatio; + if (rise > run) { + return { useVertical: true }; + } + } + if (writingMode === performance$1.ah.vertical ? firstPoint.y < lastPoint.y : firstPoint.x > lastPoint.x) { + // Includes "horizontalOnly" case for labels without vertical glyphs + return { needsFlipping: true }; + } + return null; +} +/* +* Place first and last glyph along the line projected to label plane, and if they fit +* iterate through all the intermediate glyphs, calculating their label plane positions +* from the projected line. +* +* Finally, add resulting glyph position calculations to dynamicLayoutVertexArray for +* upload to the GPU +*/ +function placeGlyphsAlongLine(projectionContext, symbol, fontSize, flip, keepUpright, posMatrix, glCoordMatrix, glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine) { + const fontScale = fontSize / 24; + const lineOffsetX = symbol.lineOffsetX * fontScale; + const lineOffsetY = symbol.lineOffsetY * fontScale; + let placedGlyphs; + if (symbol.numGlyphs > 1) { + const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs; + const lineStartIndex = symbol.lineStartIndex; + const lineEndIndex = symbol.lineStartIndex + symbol.lineLength; + // Place the first and the last glyph in the label first, so we can figure out + // the overall orientation of the label and determine whether it needs to be flipped in keepUpright mode + const firstAndLastGlyph = placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, symbol, rotateToLine, projectionContext); + if (!firstAndLastGlyph) { + return { notEnoughRoom: true }; + } + const firstPoint = project(firstAndLastGlyph.first.point.x, firstAndLastGlyph.first.point.y, glCoordMatrix, projectionContext.getElevation).point; + const lastPoint = project(firstAndLastGlyph.last.point.x, firstAndLastGlyph.last.point.y, glCoordMatrix, projectionContext.getElevation).point; + if (keepUpright && !flip) { + const orientationChange = requiresOrientationChange(symbol.writingMode, firstPoint, lastPoint, aspectRatio); + if (orientationChange) { + return orientationChange; + } + } + placedGlyphs = [firstAndLastGlyph.first]; + for (let glyphIndex = symbol.glyphStartIndex + 1; glyphIndex < glyphEndIndex - 1; glyphIndex++) { + // Since first and last glyph fit on the line, we're sure that the rest of the glyphs can be placed + placedGlyphs.push(placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphIndex), lineOffsetX, lineOffsetY, flip, symbol.segment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine)); + } + placedGlyphs.push(firstAndLastGlyph.last); + } + else { + // Only a single glyph to place + // So, determine whether to flip based on projected angle of the line segment it's on + if (keepUpright && !flip) { + const a = project(projectionContext.tileAnchorPoint.x, projectionContext.tileAnchorPoint.y, posMatrix, projectionContext.getElevation).point; + const tileVertexIndex = (symbol.lineStartIndex + symbol.segment + 1); + const tileSegmentEnd = new performance$1.P(projectionContext.lineVertexArray.getx(tileVertexIndex), projectionContext.lineVertexArray.gety(tileVertexIndex)); + const projectedVertex = project(tileSegmentEnd.x, tileSegmentEnd.y, posMatrix, projectionContext.getElevation); + // We know the anchor will be in the viewport, but the end of the line segment may be + // behind the plane of the camera, in which case we can use a point at any arbitrary (closer) + // point on the segment. + const b = (projectedVertex.signedDistanceFromCamera > 0) ? + projectedVertex.point : + projectTruncatedLineSegmentToLabelPlane(projectionContext.tileAnchorPoint, tileSegmentEnd, a, 1, posMatrix, projectionContext); + const orientationChange = requiresOrientationChange(symbol.writingMode, a, b, aspectRatio); + if (orientationChange) { + return orientationChange; + } + } + const singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(symbol.glyphStartIndex), lineOffsetX, lineOffsetY, flip, symbol.segment, symbol.lineStartIndex, symbol.lineStartIndex + symbol.lineLength, projectionContext, rotateToLine); + if (!singleGlyph || projectionContext.projectionCache.anyProjectionOccluded) + return { notEnoughRoom: true }; + placedGlyphs = [singleGlyph]; + } + for (const glyph of placedGlyphs) { + performance$1.aj(dynamicLayoutVertexArray, glyph.point, glyph.angle); + } + return {}; +} +/** + * Takes a line and direction from `previousTilePoint` to `currentTilePoint`, + * projects it to *label plane*, + * and returns a projected point along this projected line that is `minimumLength` distance away from `previousProjectedPoint`. + * @param previousTilePoint - Line start point, in tile coordinates. + * @param currentTilePoint - Line end point, in tile coordinates. + * @param previousProjectedPoint - Projection of `previousTilePoint` into *label plane*. + * @param minimumLength - Distance in the projected space along the line for the returned point. + * @param projectionMatrix - Matrix to use during projection. + * @param projectionContext - Projection context, used only for terrain's `getElevation`. + */ +function projectTruncatedLineSegmentToLabelPlane(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionMatrix, projectionContext) { + return _projectTruncatedLineSegment(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionMatrix, projectionContext); +} +/** + * Takes a line and direction from `previousTilePoint` to `currentTilePoint`, + * projects it to *viewport*, + * and returns a projected point along this projected line that is `minimumLength` distance away from `previousProjectedPoint`. + * @param previousTilePoint - Line start point, in tile coordinates. + * @param currentTilePoint - Line end point, in tile coordinates. + * @param previousProjectedPoint - Projection of `previousTilePoint` into *viewport*. + * @param minimumLength - Distance in the projected space along the line for the returned point. + * @param projectionContext - Projection context, used for terrain's `getElevation`, and either the `labelPlaneMatrix` or the map's special projection (mostly for globe). + */ +function projectTruncatedLineSegmentToViewport(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionContext) { + return _projectTruncatedLineSegment(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, undefined, projectionContext); +} +/** + * Do not use directly, use {@link projectTruncatedLineSegmentToLabelPlane} or {@link projectTruncatedLineSegmentToViewport} instead, + * depending on the target space. + * + * Projects a "virtual" vertex along a line segment. + * If `projectionMatrix` is not undefined, does a simple projection using this matrix. + * Otherwise, either projects to label plane using the `labelPlaneMatrix` + * or projects to viewport using the special map projection (mostly for globe) by calling {@link projectTileCoordinatesToViewport}. + */ +function _projectTruncatedLineSegment(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionMatrix, projectionContext) { + // We are assuming "previousTilePoint" won't project to a point within one unit of the camera plane + // If it did, that would mean our label extended all the way out from within the viewport to a (very distant) + // point near the plane of the camera. We wouldn't be able to render the label anyway once it crossed the + // plane of the camera. + const unitVertexToBeProjected = previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit()); + const projectedUnitVertex = projectionMatrix !== undefined ? + project(unitVertexToBeProjected.x, unitVertexToBeProjected.y, projectionMatrix, projectionContext.getElevation).point : + projectTileCoordinatesToViewport(unitVertexToBeProjected.x, unitVertexToBeProjected.y, projectionContext).point; + const projectedUnitSegment = previousProjectedPoint.sub(projectedUnitVertex); + return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength / projectedUnitSegment.mag())); +} +/** + * Transform a vertex from tile coordinates to label plane coordinates + * @param index - index of vertex to project + * @param projectionContext - necessary data to project a vertex + * @returns the vertex projected to the label plane + */ +function projectLineVertexToViewport(index, projectionContext, syntheticVertexArgs) { + const cache = projectionContext.projectionCache; + if (cache.projections[index]) { + return cache.projections[index]; + } + const currentVertex = new performance$1.P(projectionContext.lineVertexArray.getx(index), projectionContext.lineVertexArray.gety(index)); + const projection = projectTileCoordinatesToViewport(currentVertex.x, currentVertex.y, projectionContext); + if (projection.signedDistanceFromCamera > 0) { + cache.projections[index] = projection.point; + cache.anyProjectionOccluded = cache.anyProjectionOccluded || projection.isOccluded; + return projection.point; + } + // The vertex is behind the plane of the camera, so we can't project it + // Instead, we'll create a vertex along the line that's far enough to include the glyph + const previousLineVertexIndex = index - syntheticVertexArgs.direction; + const previousTilePoint = syntheticVertexArgs.distanceFromAnchor === 0 ? + projectionContext.tileAnchorPoint : + new performance$1.P(projectionContext.lineVertexArray.getx(previousLineVertexIndex), projectionContext.lineVertexArray.gety(previousLineVertexIndex)); + // Don't cache because the new vertex might not be far enough out for future glyphs on the same segment + const minimumLength = syntheticVertexArgs.absOffsetX - syntheticVertexArgs.distanceFromAnchor + 1; + return projectTruncatedLineSegmentToViewport(previousTilePoint, currentVertex, syntheticVertexArgs.previousVertex, minimumLength, projectionContext); +} +function projectTileCoordinatesToViewport(x, y, projectionContext) { + const translatedX = x + projectionContext.translation[0]; + const translatedY = y + projectionContext.translation[1]; + let projection; + if (!projectionContext.pitchWithMap && projectionContext.projection.useSpecialProjectionForSymbols) { + projection = projectionContext.projection.projectTileCoordinates(translatedX, translatedY, projectionContext.unwrappedTileID, projectionContext.getElevation); + projection.point.x = (projection.point.x * 0.5 + 0.5) * projectionContext.width; + projection.point.y = (-projection.point.y * 0.5 + 0.5) * projectionContext.height; + } + else { + projection = project(translatedX, translatedY, projectionContext.labelPlaneMatrix, projectionContext.getElevation); + projection.isOccluded = false; + } + return projection; +} +/** + * Calculate the normal vector for a line segment + * @param segmentVector - will be mutated as a tiny optimization + * @param offset - magnitude of resulting vector + * @param direction - direction of line traversal + * @returns a normal vector from the segment, with magnitude equal to offset amount + */ +function transformToOffsetNormal(segmentVector, offset, direction) { + return segmentVector._unit()._perp()._mult(offset * direction); +} +/** + * Construct offset line segments for the current segment and the next segment, then extend/shrink + * the segments until they intersect. If the segments are parallel, then they will touch with no modification. + * + * @param index - Index of the current vertex + * @param prevToCurrentOffsetNormal - Normal vector of the line segment from the previous vertex to the current vertex + * @param currentVertex - Current (non-offset) vertex projected to the label plane + * @param lineStartIndex - Beginning index for the line this label is on + * @param lineEndIndex - End index for the line this label is on + * @param offsetPreviousVertex - The previous vertex projected to the label plane, and then offset along the previous segments normal + * @param lineOffsetY - Magnitude of the offset + * @param projectionContext - Necessary data for tile-to-label-plane projection + * @returns The point at which the current and next line segments intersect, once offset and extended/shrunk to their meeting point + */ +function findOffsetIntersectionPoint(index, prevToCurrentOffsetNormal, currentVertex, lineStartIndex, lineEndIndex, offsetPreviousVertex, lineOffsetY, projectionContext, syntheticVertexArgs) { + if (projectionContext.projectionCache.offsets[index]) { + return projectionContext.projectionCache.offsets[index]; + } + const offsetCurrentVertex = currentVertex.add(prevToCurrentOffsetNormal); + if (index + syntheticVertexArgs.direction < lineStartIndex || index + syntheticVertexArgs.direction >= lineEndIndex) { + // This is the end of the line, no intersection to calculate + projectionContext.projectionCache.offsets[index] = offsetCurrentVertex; + return offsetCurrentVertex; + } + // Offset the vertices for the next segment + const nextVertex = projectLineVertexToViewport(index + syntheticVertexArgs.direction, projectionContext, syntheticVertexArgs); + const currentToNextOffsetNormal = transformToOffsetNormal(nextVertex.sub(currentVertex), lineOffsetY, syntheticVertexArgs.direction); + const offsetNextSegmentBegin = currentVertex.add(currentToNextOffsetNormal); + const offsetNextSegmentEnd = nextVertex.add(currentToNextOffsetNormal); + // find the intersection of these two lines + // if the lines are parallel, offsetCurrent/offsetNextBegin will touch + projectionContext.projectionCache.offsets[index] = performance$1.ak(offsetPreviousVertex, offsetCurrentVertex, offsetNextSegmentBegin, offsetNextSegmentEnd) || offsetCurrentVertex; + return projectionContext.projectionCache.offsets[index]; +} +/* + * Place a single glyph along its line, projected into the label plane, by iterating outward + * from the anchor point until the distance traversed in the label plane equals the glyph's + * offsetX. Returns null if the glyph can't fit on the line geometry. + */ +function placeGlyphAlongLine(offsetX, lineOffsetX, lineOffsetY, flip, anchorSegment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine) { + const combinedOffsetX = flip ? + offsetX - lineOffsetX : + offsetX + lineOffsetX; + let direction = combinedOffsetX > 0 ? 1 : -1; + let angle = 0; + if (flip) { + // The label needs to be flipped to keep text upright. + // Iterate in the reverse direction. + direction *= -1; + angle = Math.PI; + } + if (direction < 0) + angle += Math.PI; + let currentIndex = direction > 0 ? + lineStartIndex + anchorSegment : + lineStartIndex + anchorSegment + 1; + // Project anchor point to proper label plane and cache it + let anchorPoint; + if (projectionContext.projectionCache.cachedAnchorPoint) { + anchorPoint = projectionContext.projectionCache.cachedAnchorPoint; + } + else { + anchorPoint = projectTileCoordinatesToViewport(projectionContext.tileAnchorPoint.x, projectionContext.tileAnchorPoint.y, projectionContext).point; + projectionContext.projectionCache.cachedAnchorPoint = anchorPoint; + } + let currentVertex = anchorPoint; + let previousVertex = anchorPoint; + // offsetPrev and intersectionPoint are analogous to previousVertex and currentVertex + // but if there's a line offset they are calculated in parallel as projection happens + let offsetIntersectionPoint; + let offsetPreviousVertex; + let distanceFromAnchor = 0; + let currentSegmentDistance = 0; + const absOffsetX = Math.abs(combinedOffsetX); + const pathVertices = []; + let currentLineSegment; + while (distanceFromAnchor + currentSegmentDistance <= absOffsetX) { + currentIndex += direction; + // offset does not fit on the projected line + if (currentIndex < lineStartIndex || currentIndex >= lineEndIndex) + return null; + // accumulate values from last iteration + distanceFromAnchor += currentSegmentDistance; + previousVertex = currentVertex; + offsetPreviousVertex = offsetIntersectionPoint; + const syntheticVertexArgs = { + absOffsetX, + direction, + distanceFromAnchor, + previousVertex + }; + // find next vertex in viewport space + currentVertex = projectLineVertexToViewport(currentIndex, projectionContext, syntheticVertexArgs); + if (lineOffsetY === 0) { + // Store vertices for collision detection and update current segment geometry + pathVertices.push(previousVertex); + currentLineSegment = currentVertex.sub(previousVertex); + } + else { + // Calculate the offset for this section + let prevToCurrentOffsetNormal; + const prevToCurrent = currentVertex.sub(previousVertex); + if (prevToCurrent.mag() === 0) { + // We are starting with our anchor point directly on the vertex, so look one vertex ahead + // to calculate a normal + const nextVertex = projectLineVertexToViewport(currentIndex + direction, projectionContext, syntheticVertexArgs); + prevToCurrentOffsetNormal = transformToOffsetNormal(nextVertex.sub(currentVertex), lineOffsetY, direction); + } + else { + prevToCurrentOffsetNormal = transformToOffsetNormal(prevToCurrent, lineOffsetY, direction); + } + // Initialize offsetPrev on our first iteration, after that it will be pre-calculated + if (!offsetPreviousVertex) + offsetPreviousVertex = previousVertex.add(prevToCurrentOffsetNormal); + offsetIntersectionPoint = findOffsetIntersectionPoint(currentIndex, prevToCurrentOffsetNormal, currentVertex, lineStartIndex, lineEndIndex, offsetPreviousVertex, lineOffsetY, projectionContext, syntheticVertexArgs); + pathVertices.push(offsetPreviousVertex); + currentLineSegment = offsetIntersectionPoint.sub(offsetPreviousVertex); + } + currentSegmentDistance = currentLineSegment.mag(); + } + // The point is on the current segment. Interpolate to find it. + const segmentInterpolationT = (absOffsetX - distanceFromAnchor) / currentSegmentDistance; + const p = currentLineSegment._mult(segmentInterpolationT)._add(offsetPreviousVertex || previousVertex); + const segmentAngle = angle + Math.atan2(currentVertex.y - previousVertex.y, currentVertex.x - previousVertex.x); + pathVertices.push(p); + return { + point: p, + angle: rotateToLine ? segmentAngle : 0.0, + path: pathVertices + }; +} +const hiddenGlyphAttributes = new Float32Array([-Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0]); +// Hide them by moving them offscreen. We still need to add them to the buffer +// because the dynamic buffer is paired with a static buffer that doesn't get updated. +function hideGlyphs(num, dynamicLayoutVertexArray) { + for (let i = 0; i < num; i++) { + const offset = dynamicLayoutVertexArray.length; + dynamicLayoutVertexArray.resize(offset + 4); + // Since all hidden glyphs have the same attributes, we can build up the array faster with a single call to Float32Array.set + // for each set of four vertices, instead of calling addDynamicAttributes for each vertex. + dynamicLayoutVertexArray.float32.set(hiddenGlyphAttributes, offset * 3); + } +} +// For line label layout, we're not using z output and our w input is always 1 +// This custom matrix transformation ignores those components to make projection faster +function xyTransformMat4(out, a, m) { + const x = a[0], y = a[1]; + out[0] = m[0] * x + m[4] * y + m[12]; + out[1] = m[1] * x + m[5] * y + m[13]; + out[3] = m[3] * x + m[7] * y + m[15]; + return out; +} + +// When a symbol crosses the edge that causes it to be included in +// collision detection, it will cause changes in the symbols around +// it. This constant specifies how many pixels to pad the edge of +// the viewport for collision detection so that the bulk of the changes +// occur offscreen. Making this constant greater increases label +// stability, but it's expensive. +const viewportPadding = 100; +/** + * @internal + * A collision index used to prevent symbols from overlapping. It keep tracks of + * where previous symbols have been placed and is used to check if a new + * symbol overlaps with any previously added symbols. + * + * There are two steps to insertion: first placeCollisionBox/Circles checks if + * there's room for a symbol, then insertCollisionBox/Circles actually puts the + * symbol in the index. The two step process allows paired symbols to be inserted + * together even if they overlap. + */ +class CollisionIndex { + constructor(transform, projection, grid = new GridIndex(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25), ignoredGrid = new GridIndex(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25)) { + this.transform = transform; + this.mapProjection = projection; + this.grid = grid; + this.ignoredGrid = ignoredGrid; + this.pitchFactor = Math.cos(transform._pitch) * transform.cameraToCenterDistance; + this.screenRightBoundary = transform.width + viewportPadding; + this.screenBottomBoundary = transform.height + viewportPadding; + this.gridRightBoundary = transform.width + 2 * viewportPadding; + this.gridBottomBoundary = transform.height + 2 * viewportPadding; + this.perspectiveRatioCutoff = 0.6; + } + placeCollisionBox(collisionBox, overlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translation, collisionGroupPredicate, getElevation, shift) { + const x = collisionBox.anchorPointX + translation[0]; + const y = collisionBox.anchorPointY + translation[1]; + const projectedPoint = this.projectAndGetPerspectiveRatio(posMatrix, x, y, unwrappedTileID, getElevation); + const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio; + let projectedBox; + if (!pitchWithMap && !rotateWithMap) { + // Fast path for common symbols + const pointX = projectedPoint.point.x + (shift ? shift.x * tileToViewport : 0); + const pointY = projectedPoint.point.y + (shift ? shift.y * tileToViewport : 0); + projectedBox = { + allPointsOccluded: false, + box: [ + pointX + collisionBox.x1 * tileToViewport, + pointY + collisionBox.y1 * tileToViewport, + pointX + collisionBox.x2 * tileToViewport, + pointY + collisionBox.y2 * tileToViewport, + ] + }; + } + else { + projectedBox = this._projectCollisionBox(collisionBox, tileToViewport, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translation, projectedPoint, getElevation, shift); + } + const [tlX, tlY, brX, brY] = projectedBox.box; + const projectionOccluded = this.mapProjection.useSpecialProjectionForSymbols ? (pitchWithMap ? projectedBox.allPointsOccluded : this.mapProjection.isOccluded(x, y, unwrappedTileID)) : false; + if (projectionOccluded || projectedPoint.perspectiveRatio < this.perspectiveRatioCutoff || !this.isInsideGrid(tlX, tlY, brX, brY) || + (overlapMode !== 'always' && this.grid.hitTest(tlX, tlY, brX, brY, overlapMode, collisionGroupPredicate))) { + return { + box: [tlX, tlY, brX, brY], + placeable: false, + offscreen: false + }; + } + return { + box: [tlX, tlY, brX, brY], + placeable: true, + offscreen: this.isOffscreen(tlX, tlY, brX, brY) + }; + } + placeCollisionCircles(overlapMode, symbol, lineVertexArray, glyphOffsetArray, fontSize, posMatrix, unwrappedTileID, labelPlaneMatrix, labelToScreenMatrix, showCollisionCircles, pitchWithMap, collisionGroupPredicate, circlePixelDiameter, textPixelPadding, translation, getElevation) { + const placedCollisionCircles = []; + const tileUnitAnchorPoint = new performance$1.P(symbol.anchorX, symbol.anchorY); + const perspectiveRatio = this.getPerspectiveRatio(posMatrix, tileUnitAnchorPoint.x, tileUnitAnchorPoint.y, unwrappedTileID, getElevation); + const labelPlaneFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio; + const labelPlaneFontScale = labelPlaneFontSize / performance$1.ap; + const projectionCache = { projections: {}, offsets: {}, cachedAnchorPoint: undefined, anyProjectionOccluded: false }; + const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale; + const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale; + const projectionContext = { + getElevation, + labelPlaneMatrix, + lineVertexArray, + pitchWithMap, + projectionCache, + projection: this.mapProjection, + tileAnchorPoint: tileUnitAnchorPoint, + unwrappedTileID, + width: this.transform.width, + height: this.transform.height, + translation + }; + const firstAndLastGlyph = placeFirstAndLastGlyph(labelPlaneFontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, + /*flip*/ false, symbol, false, projectionContext); + let collisionDetected = false; + let inGrid = false; + let entirelyOffscreen = true; + if (firstAndLastGlyph) { + const radius = circlePixelDiameter * 0.5 * perspectiveRatio + textPixelPadding; + const screenPlaneMin = new performance$1.P(-viewportPadding, -viewportPadding); + const screenPlaneMax = new performance$1.P(this.screenRightBoundary, this.screenBottomBoundary); + const interpolator = new PathInterpolator(); + // Construct a projected path from projected line vertices. Anchor points are ignored and removed + const first = firstAndLastGlyph.first; + const last = firstAndLastGlyph.last; + let projectedPath = []; + for (let i = first.path.length - 1; i >= 1; i--) { + projectedPath.push(first.path[i]); + } + for (let i = 1; i < last.path.length; i++) { + projectedPath.push(last.path[i]); + } + // Tolerate a slightly longer distance than one diameter between two adjacent circles + const circleDist = radius * 2.5; + // The path might need to be converted into screen space if a pitched map is used as the label space + if (labelToScreenMatrix) { + const screenSpacePath = this.projectPathToScreenSpace(projectedPath, projectionContext, labelToScreenMatrix); + // Do not try to place collision circles if even one of the points is behind the camera. + // This is a plausible scenario with big camera pitch angles + if (screenSpacePath.some(point => point.signedDistanceFromCamera <= 0)) { + projectedPath = []; + } + else { + projectedPath = screenSpacePath.map(p => p.point); + } + } + let segments = []; + if (projectedPath.length > 0) { + // Quickly check if the path is fully inside or outside of the padded collision region. + // For overlapping paths we'll only create collision circles for the visible segments + const minPoint = projectedPath[0].clone(); + const maxPoint = projectedPath[0].clone(); + for (let i = 1; i < projectedPath.length; i++) { + minPoint.x = Math.min(minPoint.x, projectedPath[i].x); + minPoint.y = Math.min(minPoint.y, projectedPath[i].y); + maxPoint.x = Math.max(maxPoint.x, projectedPath[i].x); + maxPoint.y = Math.max(maxPoint.y, projectedPath[i].y); + } + if (minPoint.x >= screenPlaneMin.x && maxPoint.x <= screenPlaneMax.x && + minPoint.y >= screenPlaneMin.y && maxPoint.y <= screenPlaneMax.y) { + // Quad fully visible + segments = [projectedPath]; + } + else if (maxPoint.x < screenPlaneMin.x || minPoint.x > screenPlaneMax.x || + maxPoint.y < screenPlaneMin.y || minPoint.y > screenPlaneMax.y) { + // Not visible + segments = []; + } + else { + segments = performance$1.al([projectedPath], screenPlaneMin.x, screenPlaneMin.y, screenPlaneMax.x, screenPlaneMax.y); + } + } + for (const seg of segments) { + // interpolate positions for collision circles. Add a small padding to both ends of the segment + interpolator.reset(seg, radius * 0.25); + let numCircles = 0; + if (interpolator.length <= 0.5 * radius) { + numCircles = 1; + } + else { + numCircles = Math.ceil(interpolator.paddedLength / circleDist) + 1; + } + for (let i = 0; i < numCircles; i++) { + const t = i / Math.max(numCircles - 1, 1); + const circlePosition = interpolator.lerp(t); + // add viewport padding to the position and perform initial collision check + const centerX = circlePosition.x + viewportPadding; + const centerY = circlePosition.y + viewportPadding; + placedCollisionCircles.push(centerX, centerY, radius, 0); + const x1 = centerX - radius; + const y1 = centerY - radius; + const x2 = centerX + radius; + const y2 = centerY + radius; + entirelyOffscreen = entirelyOffscreen && this.isOffscreen(x1, y1, x2, y2); + inGrid = inGrid || this.isInsideGrid(x1, y1, x2, y2); + if (overlapMode !== 'always' && this.grid.hitTestCircle(centerX, centerY, radius, overlapMode, collisionGroupPredicate)) { + // Don't early exit if we're showing the debug circles because we still want to calculate + // which circles are in use + collisionDetected = true; + if (!showCollisionCircles) { + return { + circles: [], + offscreen: false, + collisionDetected + }; + } + } + } + } + } + return { + circles: ((!showCollisionCircles && collisionDetected) || !inGrid || perspectiveRatio < this.perspectiveRatioCutoff) ? [] : placedCollisionCircles, + offscreen: entirelyOffscreen, + collisionDetected + }; + } + projectPathToScreenSpace(projectedPath, projectionContext, labelToScreenMatrix) { + return projectedPath.map(p => project(p.x, p.y, labelToScreenMatrix, projectionContext.getElevation)); + } + /** + * Because the geometries in the CollisionIndex are an approximation of the shape of + * symbols on the map, we use the CollisionIndex to look up the symbol part of + * `queryRenderedFeatures`. + */ + queryRenderedSymbols(viewportQueryGeometry) { + if (viewportQueryGeometry.length === 0 || (this.grid.keysLength() === 0 && this.ignoredGrid.keysLength() === 0)) { + return {}; + } + const query = []; + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const point of viewportQueryGeometry) { + const gridPoint = new performance$1.P(point.x + viewportPadding, point.y + viewportPadding); + minX = Math.min(minX, gridPoint.x); + minY = Math.min(minY, gridPoint.y); + maxX = Math.max(maxX, gridPoint.x); + maxY = Math.max(maxY, gridPoint.y); + query.push(gridPoint); + } + const features = this.grid.query(minX, minY, maxX, maxY) + .concat(this.ignoredGrid.query(minX, minY, maxX, maxY)); + const seenFeatures = {}; + const result = {}; + for (const feature of features) { + const featureKey = feature.key; + // Skip already seen features. + if (seenFeatures[featureKey.bucketInstanceId] === undefined) { + seenFeatures[featureKey.bucketInstanceId] = {}; + } + if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) { + continue; + } + // Check if query intersects with the feature box + // "Collision Circles" for line labels are treated as boxes here + // Since there's no actual collision taking place, the circle vs. square + // distinction doesn't matter as much, and box geometry is easier + // to work with. + const bbox = [ + new performance$1.P(feature.x1, feature.y1), + new performance$1.P(feature.x2, feature.y1), + new performance$1.P(feature.x2, feature.y2), + new performance$1.P(feature.x1, feature.y2) + ]; + if (!performance$1.am(query, bbox)) { + continue; + } + seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true; + if (result[featureKey.bucketInstanceId] === undefined) { + result[featureKey.bucketInstanceId] = []; + } + result[featureKey.bucketInstanceId].push(featureKey.featureIndex); + } + return result; + } + insertCollisionBox(collisionBox, overlapMode, ignorePlacement, bucketInstanceId, featureIndex, collisionGroupID) { + const grid = ignorePlacement ? this.ignoredGrid : this.grid; + const key = { bucketInstanceId, featureIndex, collisionGroupID, overlapMode }; + grid.insert(key, collisionBox[0], collisionBox[1], collisionBox[2], collisionBox[3]); + } + insertCollisionCircles(collisionCircles, overlapMode, ignorePlacement, bucketInstanceId, featureIndex, collisionGroupID) { + const grid = ignorePlacement ? this.ignoredGrid : this.grid; + const key = { bucketInstanceId, featureIndex, collisionGroupID, overlapMode }; + for (let k = 0; k < collisionCircles.length; k += 4) { + grid.insertCircle(key, collisionCircles[k], collisionCircles[k + 1], collisionCircles[k + 2]); + } + } + projectAndGetPerspectiveRatio(posMatrix, x, y, _unwrappedTileID, getElevation) { + // The code here is duplicated from "projection.ts" for performance. + // Code here is subject to change once globe is merged. + let pos; + if (getElevation) { // slow because of handle z-index + pos = [x, y, getElevation(x, y), 1]; + performance$1.af(pos, pos, posMatrix); + } + else { // fast because of ignore z-index + pos = [x, y, 0, 1]; + xyTransformMat4(pos, pos, posMatrix); + } + const w = pos[3]; + return { + point: new performance$1.P((((pos[0] / w + 1) / 2) * this.transform.width) + viewportPadding, (((-pos[1] / w + 1) / 2) * this.transform.height) + viewportPadding), + // See perspective ratio comment in symbol_sdf.vertex + // We're doing collision detection in viewport space so we need + // to scale down boxes in the distance + perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / w), + isOccluded: false, + signedDistanceFromCamera: w + }; + } + getPerspectiveRatio(posMatrix, x, y, unwrappedTileID, getElevation) { + // We don't care about the actual projected point, just its W component. + const projected = this.mapProjection.useSpecialProjectionForSymbols ? + this.mapProjection.projectTileCoordinates(x, y, unwrappedTileID, getElevation) : + project(x, y, posMatrix, getElevation); + return 0.5 + 0.5 * (this.transform.cameraToCenterDistance / projected.signedDistanceFromCamera); + } + isOffscreen(x1, y1, x2, y2) { + return x2 < viewportPadding || x1 >= this.screenRightBoundary || y2 < viewportPadding || y1 > this.screenBottomBoundary; + } + isInsideGrid(x1, y1, x2, y2) { + return x2 >= 0 && x1 < this.gridRightBoundary && y2 >= 0 && y1 < this.gridBottomBoundary; + } + /* + * Returns a matrix for transforming collision shapes to viewport coordinate space. + * Use this function to render e.g. collision circles on the screen. + * example transformation: clipPos = glCoordMatrix * viewportMatrix * circle_pos + */ + getViewportMatrix() { + const m = performance$1.an([]); + performance$1.J(m, m, [-viewportPadding, -viewportPadding, 0.0]); + return m; + } + /** + * Applies all layout+paint properties of the given box in order to find as good approximation of its screen-space bounding box as possible. + */ + _projectCollisionBox(collisionBox, tileToViewport, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translation, projectedPoint, getElevation, shift) { + // These vectors are valid both for screen space viewport-rotation-aligned texts and for pitch-align: map texts that are map-rotation-aligned. + let vecEast = new performance$1.P(1, 0); + let vecSouth = new performance$1.P(0, 1); + const translatedAnchor = new performance$1.P(collisionBox.anchorPointX + translation[0], collisionBox.anchorPointY + translation[1]); + if (rotateWithMap && !pitchWithMap) { + // Handles screen space texts that are always aligned east-west. + const projectedEast = this.projectAndGetPerspectiveRatio(posMatrix, translatedAnchor.x + 1, translatedAnchor.y, unwrappedTileID, getElevation).point; + const toEast = projectedEast.sub(projectedPoint.point).unit(); + const angle = Math.atan(toEast.y / toEast.x) + (toEast.x < 0 ? Math.PI : 0); + const sin = Math.sin(angle); + const cos = Math.cos(angle); + vecEast = new performance$1.P(cos, sin); + vecSouth = new performance$1.P(-sin, cos); + } + else if (!rotateWithMap && pitchWithMap) { + // Handles pitch-align: map texts that are always aligned with the viewport's X axis. + const angle = -this.transform.angle; + const sin = Math.sin(angle); + const cos = Math.cos(angle); + vecEast = new performance$1.P(cos, sin); + vecSouth = new performance$1.P(-sin, cos); + } + // Configuration for screen space offsets + let basePoint = projectedPoint.point; + let distanceMultiplier = tileToViewport; + if (pitchWithMap) { + // Configuration for tile space (map-pitch-aligned) offsets + basePoint = translatedAnchor; + const zoomFraction = this.transform.zoom - Math.floor(this.transform.zoom); + distanceMultiplier = Math.pow(2, -zoomFraction); + distanceMultiplier *= this.mapProjection.getPitchedTextCorrection(this.transform, translatedAnchor, unwrappedTileID); + // This next correction can't be applied when variable anchors are in use. + if (!shift) { + // Shader applies a perspective size correction, we need to apply the same correction. + // For non-pitchWithMap texts, this is handled above by multiplying `textPixelRatio` with `projectedPoint.perspectiveRatio`, + // which is equivalent to the non-pitchWithMap branch of the GLSL code. + // Here, we compute and apply the pitchWithMap branch. + // See the computation of `perspective_ratio` in the symbol vertex shaders for the GLSL code. + const distanceRatio = projectedPoint.signedDistanceFromCamera / this.transform.cameraToCenterDistance; + const perspectiveRatio = performance$1.ac(0.5 + 0.5 * distanceRatio, 0.0, 4.0); // Same clamp as what is used in the shader. + distanceMultiplier *= perspectiveRatio; + } + } + if (shift) { + // Variable anchors are in use + basePoint = basePoint.add(vecEast.mult(shift.x * distanceMultiplier)).add(vecSouth.mult(shift.y * distanceMultiplier)); + } + const offsetXmin = collisionBox.x1 * distanceMultiplier; + const offsetXmax = collisionBox.x2 * distanceMultiplier; + const offsetXhalf = (offsetXmin + offsetXmax) / 2; + const offsetYmin = collisionBox.y1 * distanceMultiplier; + const offsetYmax = collisionBox.y2 * distanceMultiplier; + const offsetYhalf = (offsetYmin + offsetYmax) / 2; + // 0--1--2 + // | | + // 7 3 + // | | + // 6--5--4 + const offsetsArray = [ + { offsetX: offsetXmin, offsetY: offsetYmin }, + { offsetX: offsetXhalf, offsetY: offsetYmin }, + { offsetX: offsetXmax, offsetY: offsetYmin }, + { offsetX: offsetXmax, offsetY: offsetYhalf }, + { offsetX: offsetXmax, offsetY: offsetYmax }, + { offsetX: offsetXhalf, offsetY: offsetYmax }, + { offsetX: offsetXmin, offsetY: offsetYmax }, + { offsetX: offsetXmin, offsetY: offsetYhalf } + ]; + let points = []; + for (const { offsetX, offsetY } of offsetsArray) { + points.push(new performance$1.P(basePoint.x + vecEast.x * offsetX + vecSouth.x * offsetY, basePoint.y + vecEast.y * offsetX + vecSouth.y * offsetY)); + } + // Is any point of the collision shape visible on the globe (on beyond horizon)? + let anyPointVisible = false; + if (pitchWithMap) { + const projected = points.map(p => this.projectAndGetPerspectiveRatio(posMatrix, p.x, p.y, unwrappedTileID, getElevation)); + // Is at least one of the projected points NOT behind the horizon? + anyPointVisible = projected.some(p => !p.isOccluded); + points = projected.map(p => p.point); + } + else { + // Labels that are not pitchWithMap cannot ever hide behind the horizon. + anyPointVisible = true; + } + return { + box: performance$1.ao(points), + allPointsOccluded: !anyPointVisible + }; + } +} + +/** + * Converts a pixel value at a the given zoom level to tile units. + * + * The shaders mostly calculate everything in tile units so style + * properties need to be converted from pixels to tile units using this. + * + * For example, a translation by 30 pixels at zoom 6.5 will be a + * translation by pixelsToTileUnits(30, 6.5) tile units. + * + * @returns value in tile units + */ +function pixelsToTileUnits(tile, pixelValue, z) { + return pixelValue * (performance$1.X / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ))); +} + +class OpacityState { + constructor(prevState, increment, placed, skipFade) { + if (prevState) { + this.opacity = Math.max(0, Math.min(1, prevState.opacity + (prevState.placed ? increment : -increment))); + } + else { + this.opacity = (skipFade && placed) ? 1 : 0; + } + this.placed = placed; + } + isHidden() { + return this.opacity === 0 && !this.placed; + } +} +class JointOpacityState { + constructor(prevState, increment, placedText, placedIcon, skipFade) { + this.text = new OpacityState(prevState ? prevState.text : null, increment, placedText, skipFade); + this.icon = new OpacityState(prevState ? prevState.icon : null, increment, placedIcon, skipFade); + } + isHidden() { + return this.text.isHidden() && this.icon.isHidden(); + } +} +class JointPlacement { + constructor(text, icon, skipFade) { + this.text = text; + this.icon = icon; + this.skipFade = skipFade; + } +} +class CollisionCircleArray { + constructor() { + this.invProjMatrix = performance$1.H(); + this.viewportMatrix = performance$1.H(); + this.circles = []; + } +} +class RetainedQueryData { + constructor(bucketInstanceId, featureIndex, sourceLayerIndex, bucketIndex, tileID) { + this.bucketInstanceId = bucketInstanceId; + this.featureIndex = featureIndex; + this.sourceLayerIndex = sourceLayerIndex; + this.bucketIndex = bucketIndex; + this.tileID = tileID; + } +} +class CollisionGroups { + constructor(crossSourceCollisions) { + this.crossSourceCollisions = crossSourceCollisions; + this.maxGroupID = 0; + this.collisionGroups = {}; + } + get(sourceID) { + // The predicate/groupID mechanism allows for arbitrary grouping, + // but the current interface defines one source == one group when + // crossSourceCollisions == true. + if (!this.crossSourceCollisions) { + if (!this.collisionGroups[sourceID]) { + const nextGroupID = ++this.maxGroupID; + this.collisionGroups[sourceID] = { + ID: nextGroupID, + predicate: (key) => { + return key.collisionGroupID === nextGroupID; + } + }; + } + return this.collisionGroups[sourceID]; + } + else { + return { ID: 0, predicate: null }; + } + } +} +function calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale) { + const { horizontalAlign, verticalAlign } = performance$1.au(anchor); + const shiftX = -(horizontalAlign - 0.5) * width; + const shiftY = -(verticalAlign - 0.5) * height; + return new performance$1.P(shiftX + textOffset[0] * textBoxScale, shiftY + textOffset[1] * textBoxScale); +} +class Placement { + constructor(transform, projection, terrain, fadeDuration, crossSourceCollisions, prevPlacement) { + this.transform = transform.clone(); + this.terrain = terrain; + this.collisionIndex = new CollisionIndex(this.transform, projection); + this.placements = {}; + this.opacities = {}; + this.variableOffsets = {}; + this.stale = false; + this.commitTime = 0; + this.fadeDuration = fadeDuration; + this.retainedQueryData = {}; + this.collisionGroups = new CollisionGroups(crossSourceCollisions); + this.collisionCircleArrays = {}; + this.collisionBoxArrays = new Map(); + this.prevPlacement = prevPlacement; + if (prevPlacement) { + prevPlacement.prevPlacement = undefined; // Only hold on to one placement back + } + this.placedOrientations = {}; + } + _getTerrainElevationFunc(tileID) { + const terrain = this.terrain; + return terrain ? (x, y) => terrain.getElevation(tileID, x, y) : null; + } + getBucketParts(results, styleLayer, tile, sortAcrossTiles) { + const symbolBucket = tile.getBucket(styleLayer); + const bucketFeatureIndex = tile.latestFeatureIndex; + if (!symbolBucket || !bucketFeatureIndex || styleLayer.id !== symbolBucket.layerIds[0]) + return; + const collisionBoxArray = tile.collisionBoxArray; + const layout = symbolBucket.layers[0].layout; + const paint = symbolBucket.layers[0].paint; + const scale = Math.pow(2, this.transform.zoom - tile.tileID.overscaledZ); + const textPixelRatio = tile.tileSize / performance$1.X; + const unwrappedTileID = tile.tileID.toUnwrapped(); + const posMatrix = this.transform.calculatePosMatrix(unwrappedTileID); + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pixelsToTiles = pixelsToTileUnits(tile, 1, this.transform.zoom); + const translationText = this.collisionIndex.mapProjection.translatePosition(this.transform, tile, paint.get('text-translate'), paint.get('text-translate-anchor')); + const translationIcon = this.collisionIndex.mapProjection.translatePosition(this.transform, tile, paint.get('icon-translate'), paint.get('icon-translate-anchor')); + const textLabelPlaneMatrix = getLabelPlaneMatrix(posMatrix, pitchWithMap, rotateWithMap, this.transform, pixelsToTiles); + let labelToScreenMatrix = null; + if (pitchWithMap) { + const glMatrix = getGlCoordMatrix(posMatrix, pitchWithMap, rotateWithMap, this.transform, pixelsToTiles); + labelToScreenMatrix = performance$1.L([], this.transform.labelPlaneMatrix, glMatrix); + } + // As long as this placement lives, we have to hold onto this bucket's + // matching FeatureIndex/data for querying purposes + this.retainedQueryData[symbolBucket.bucketInstanceId] = new RetainedQueryData(symbolBucket.bucketInstanceId, bucketFeatureIndex, symbolBucket.sourceLayerIndex, symbolBucket.index, tile.tileID); + const parameters = { + bucket: symbolBucket, + layout, + translationText, + translationIcon, + posMatrix, + unwrappedTileID, + textLabelPlaneMatrix, + labelToScreenMatrix, + scale, + textPixelRatio, + holdingForFade: tile.holdingForFade(), + collisionBoxArray, + partiallyEvaluatedTextSize: performance$1.ag(symbolBucket.textSizeData, this.transform.zoom), + collisionGroup: this.collisionGroups.get(symbolBucket.sourceID) + }; + if (sortAcrossTiles) { + for (const range of symbolBucket.sortKeyRanges) { + const { sortKey, symbolInstanceStart, symbolInstanceEnd } = range; + results.push({ sortKey, symbolInstanceStart, symbolInstanceEnd, parameters }); + } + } + else { + results.push({ + symbolInstanceStart: 0, + symbolInstanceEnd: symbolBucket.symbolInstances.length, + parameters + }); + } + } + attemptAnchorPlacement(textAnchorOffset, textBox, width, height, textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix, unwrappedTileID, collisionGroup, textOverlapMode, symbolInstance, bucket, orientation, translationText, translationIcon, iconBox, getElevation) { + const anchor = performance$1.aq[textAnchorOffset.textAnchor]; + const textOffset = [textAnchorOffset.textOffset0, textAnchorOffset.textOffset1]; + const shift = calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale); + const placedGlyphBoxes = this.collisionIndex.placeCollisionBox(textBox, textOverlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation, shift); + if (iconBox) { + const placedIconBoxes = this.collisionIndex.placeCollisionBox(iconBox, textOverlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationIcon, collisionGroup.predicate, getElevation, shift); + if (!placedIconBoxes.placeable) + return; + } + if (placedGlyphBoxes.placeable) { + let prevAnchor; + // If this label was placed in the previous placement, record the anchor position + // to allow us to animate the transition + if (this.prevPlacement && + this.prevPlacement.variableOffsets[symbolInstance.crossTileID] && + this.prevPlacement.placements[symbolInstance.crossTileID] && + this.prevPlacement.placements[symbolInstance.crossTileID].text) { + prevAnchor = this.prevPlacement.variableOffsets[symbolInstance.crossTileID].anchor; + } + if (symbolInstance.crossTileID === 0) + throw new Error('symbolInstance.crossTileID can\'t be 0'); + this.variableOffsets[symbolInstance.crossTileID] = { + textOffset, + width, + height, + anchor, + textBoxScale, + prevAnchor + }; + this.markUsedJustification(bucket, anchor, symbolInstance, orientation); + if (bucket.allowVerticalPlacement) { + this.markUsedOrientation(bucket, orientation, symbolInstance); + this.placedOrientations[symbolInstance.crossTileID] = orientation; + } + return { shift, placedGlyphBoxes }; + } + } + placeLayerBucketPart(bucketPart, seenCrossTileIDs, showCollisionBoxes) { + const { bucket, layout, translationText, translationIcon, posMatrix, unwrappedTileID, textLabelPlaneMatrix, labelToScreenMatrix, textPixelRatio, holdingForFade, collisionBoxArray, partiallyEvaluatedTextSize, collisionGroup } = bucketPart.parameters; + const textOptional = layout.get('text-optional'); + const iconOptional = layout.get('icon-optional'); + const textOverlapMode = performance$1.ar(layout, 'text-overlap', 'text-allow-overlap'); + const textAlwaysOverlap = textOverlapMode === 'always'; + const iconOverlapMode = performance$1.ar(layout, 'icon-overlap', 'icon-allow-overlap'); + const iconAlwaysOverlap = iconOverlapMode === 'always'; + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const hasIconTextFit = layout.get('icon-text-fit') !== 'none'; + const zOrderByViewportY = layout.get('symbol-z-order') === 'viewport-y'; + // This logic is similar to the "defaultOpacityState" logic below in updateBucketOpacities + // If we know a symbol is always supposed to show, force it to be marked visible even if + // it wasn't placed into the collision index (because some or all of it was outside the range + // of the collision grid). + // There is a subtle edge case here we're accepting: + // Symbol A has text-allow-overlap: true, icon-allow-overlap: true, icon-optional: false + // A's icon is outside the grid, so doesn't get placed + // A's text would be inside grid, but doesn't get placed because of icon-optional: false + // We still show A because of the allow-overlap settings. + // Symbol B has allow-overlap: false, and gets placed where A's text would be + // On panning in, there is a short period when Symbol B and Symbol A will overlap + // This is the reverse of our normal policy of "fade in on pan", but should look like any other + // collision and hopefully not be too noticeable. + // See https://github.com/mapbox/mapbox-gl-js/issues/7172 + const alwaysShowText = textAlwaysOverlap && (iconAlwaysOverlap || !bucket.hasIconData() || iconOptional); + const alwaysShowIcon = iconAlwaysOverlap && (textAlwaysOverlap || !bucket.hasTextData() || textOptional); + if (!bucket.collisionArrays && collisionBoxArray) { + bucket.deserializeCollisionBoxes(collisionBoxArray); + } + const tileID = this.retainedQueryData[bucket.bucketInstanceId].tileID; + const getElevation = this._getTerrainElevationFunc(tileID); + const placeSymbol = (symbolInstance, collisionArrays, symbolIndex) => { + var _a, _b; + if (seenCrossTileIDs[symbolInstance.crossTileID]) + return; + if (holdingForFade) { + // Mark all symbols from this tile as "not placed", but don't add to seenCrossTileIDs, because we don't + // know yet if we have a duplicate in a parent tile that _should_ be placed. + this.placements[symbolInstance.crossTileID] = new JointPlacement(false, false, false); + return; + } + let placeText = false; + let placeIcon = false; + let offscreen = true; + let shift = null; + let placed = { box: null, placeable: false, offscreen: null }; + let placedVerticalText = { box: null, placeable: false, offscreen: null }; + let placedGlyphBoxes = null; + let placedGlyphCircles = null; + let placedIconBoxes = null; + let textFeatureIndex = 0; + let verticalTextFeatureIndex = 0; + let iconFeatureIndex = 0; + if (collisionArrays.textFeatureIndex) { + textFeatureIndex = collisionArrays.textFeatureIndex; + } + else if (symbolInstance.useRuntimeCollisionCircles) { + textFeatureIndex = symbolInstance.featureIndex; + } + if (collisionArrays.verticalTextFeatureIndex) { + verticalTextFeatureIndex = collisionArrays.verticalTextFeatureIndex; + } + const textBox = collisionArrays.textBox; + if (textBox) { + const updatePreviousOrientationIfNotPlaced = (isPlaced) => { + let previousOrientation = performance$1.ah.horizontal; + if (bucket.allowVerticalPlacement && !isPlaced && this.prevPlacement) { + const prevPlacedOrientation = this.prevPlacement.placedOrientations[symbolInstance.crossTileID]; + if (prevPlacedOrientation) { + this.placedOrientations[symbolInstance.crossTileID] = prevPlacedOrientation; + previousOrientation = prevPlacedOrientation; + this.markUsedOrientation(bucket, previousOrientation, symbolInstance); + } + } + return previousOrientation; + }; + const placeTextForPlacementModes = (placeHorizontalFn, placeVerticalFn) => { + if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && collisionArrays.verticalTextBox) { + for (const placementMode of bucket.writingModes) { + if (placementMode === performance$1.ah.vertical) { + placed = placeVerticalFn(); + placedVerticalText = placed; + } + else { + placed = placeHorizontalFn(); + } + if (placed && placed.placeable) + break; + } + } + else { + placed = placeHorizontalFn(); + } + }; + const textAnchorOffsetStart = symbolInstance.textAnchorOffsetStartIndex; + const textAnchorOffsetEnd = symbolInstance.textAnchorOffsetEndIndex; + // If start+end indices match, text-variable-anchor is not in play. + if (textAnchorOffsetEnd === textAnchorOffsetStart) { + const placeBox = (collisionTextBox, orientation) => { + const placedFeature = this.collisionIndex.placeCollisionBox(collisionTextBox, textOverlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation); + if (placedFeature && placedFeature.placeable) { + this.markUsedOrientation(bucket, orientation, symbolInstance); + this.placedOrientations[symbolInstance.crossTileID] = orientation; + } + return placedFeature; + }; + const placeHorizontal = () => { + return placeBox(textBox, performance$1.ah.horizontal); + }; + const placeVertical = () => { + const verticalTextBox = collisionArrays.verticalTextBox; + if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) { + return placeBox(verticalTextBox, performance$1.ah.vertical); + } + return { box: null, offscreen: null }; + }; + placeTextForPlacementModes(placeHorizontal, placeVertical); + updatePreviousOrientationIfNotPlaced(placed && placed.placeable); + } + else { + // If this symbol was in the last placement, prefer placement using same anchor, if it's still available + let prevAnchor = performance$1.aq[(_b = (_a = this.prevPlacement) === null || _a === void 0 ? void 0 : _a.variableOffsets[symbolInstance.crossTileID]) === null || _b === void 0 ? void 0 : _b.anchor]; + const placeBoxForVariableAnchors = (collisionTextBox, collisionIconBox, orientation) => { + const width = collisionTextBox.x2 - collisionTextBox.x1; + const height = collisionTextBox.y2 - collisionTextBox.y1; + const textBoxScale = symbolInstance.textBoxScale; + const variableIconBox = hasIconTextFit && (iconOverlapMode === 'never') ? collisionIconBox : null; + let placedBox = null; + let placementPasses = (textOverlapMode === 'never') ? 1 : 2; + let overlapMode = 'never'; + if (prevAnchor) { + placementPasses++; + } + for (let pass = 0; pass < placementPasses; pass++) { + for (let i = textAnchorOffsetStart; i < textAnchorOffsetEnd; i++) { + const textAnchorOffset = bucket.textAnchorOffsets.get(i); + if (prevAnchor && textAnchorOffset.textAnchor !== prevAnchor) { + continue; + } + const result = this.attemptAnchorPlacement(textAnchorOffset, collisionTextBox, width, height, textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix, unwrappedTileID, collisionGroup, overlapMode, symbolInstance, bucket, orientation, translationText, translationIcon, variableIconBox, getElevation); + if (result) { + placedBox = result.placedGlyphBoxes; + if (placedBox && placedBox.placeable) { + placeText = true; + shift = result.shift; + return placedBox; + } + } + } + if (prevAnchor) { + prevAnchor = null; + } + else { + overlapMode = textOverlapMode; + } + } + if (showCollisionBoxes && !placedBox) { + // No box was successfully placed + // Generate bounds for a fake centered box, so that we can at least display something for collision debug. + const placedFakeGlyphBox = this.collisionIndex.placeCollisionBox(textBox, 'always', // Skips expensive collision check with already placed boxes + textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation, new performance$1.P(0, 0)); + placedBox = { + box: placedFakeGlyphBox.box, + offscreen: false, + placeable: false + }; + } + return placedBox; + }; + const placeHorizontal = () => { + return placeBoxForVariableAnchors(textBox, collisionArrays.iconBox, performance$1.ah.horizontal); + }; + const placeVertical = () => { + const verticalTextBox = collisionArrays.verticalTextBox; + const wasPlaced = placed && placed.placeable; + if (bucket.allowVerticalPlacement && !wasPlaced && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) { + return placeBoxForVariableAnchors(verticalTextBox, collisionArrays.verticalIconBox, performance$1.ah.vertical); + } + return { box: null, occluded: true, offscreen: null }; + }; + placeTextForPlacementModes(placeHorizontal, placeVertical); + if (placed) { + placeText = placed.placeable; + offscreen = placed.offscreen; + } + const prevOrientation = updatePreviousOrientationIfNotPlaced(placed && placed.placeable); + // If we didn't get placed, we still need to copy our position from the last placement for + // fade animations + if (!placeText && this.prevPlacement) { + const prevOffset = this.prevPlacement.variableOffsets[symbolInstance.crossTileID]; + if (prevOffset) { + this.variableOffsets[symbolInstance.crossTileID] = prevOffset; + this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, prevOrientation); + } + } + } + } + placedGlyphBoxes = placed; + placeText = placedGlyphBoxes && placedGlyphBoxes.placeable; + offscreen = placedGlyphBoxes && placedGlyphBoxes.offscreen; + if (symbolInstance.useRuntimeCollisionCircles) { + const placedSymbol = bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex); + const fontSize = performance$1.ai(bucket.textSizeData, partiallyEvaluatedTextSize, placedSymbol); + const textPixelPadding = layout.get('text-padding'); + const circlePixelDiameter = symbolInstance.collisionCircleDiameter; + placedGlyphCircles = this.collisionIndex.placeCollisionCircles(textOverlapMode, placedSymbol, bucket.lineVertexArray, bucket.glyphOffsetArray, fontSize, posMatrix, unwrappedTileID, textLabelPlaneMatrix, labelToScreenMatrix, showCollisionBoxes, pitchWithMap, collisionGroup.predicate, circlePixelDiameter, textPixelPadding, translationText, getElevation); + if (placedGlyphCircles.circles.length && placedGlyphCircles.collisionDetected && !showCollisionBoxes) { + performance$1.w('Collisions detected, but collision boxes are not shown'); + } + // If text-overlap is set to 'always', force "placedCircles" to true + // In theory there should always be at least one circle placed + // in this case, but for now quirks in text-anchor + // and text-offset may prevent that from being true. + placeText = textAlwaysOverlap || (placedGlyphCircles.circles.length > 0 && !placedGlyphCircles.collisionDetected); + offscreen = offscreen && placedGlyphCircles.offscreen; + } + if (collisionArrays.iconFeatureIndex) { + iconFeatureIndex = collisionArrays.iconFeatureIndex; + } + if (collisionArrays.iconBox) { + const placeIconFeature = iconBox => { + return this.collisionIndex.placeCollisionBox(iconBox, iconOverlapMode, textPixelRatio, posMatrix, unwrappedTileID, pitchWithMap, rotateWithMap, translationIcon, collisionGroup.predicate, getElevation, (hasIconTextFit && shift) ? shift : undefined); + }; + if (placedVerticalText && placedVerticalText.placeable && collisionArrays.verticalIconBox) { + placedIconBoxes = placeIconFeature(collisionArrays.verticalIconBox); + placeIcon = placedIconBoxes.placeable; + } + else { + placedIconBoxes = placeIconFeature(collisionArrays.iconBox); + placeIcon = placedIconBoxes.placeable; + } + offscreen = offscreen && placedIconBoxes.offscreen; + } + const iconWithoutText = textOptional || + (symbolInstance.numHorizontalGlyphVertices === 0 && symbolInstance.numVerticalGlyphVertices === 0); + const textWithoutIcon = iconOptional || symbolInstance.numIconVertices === 0; + // Combine the scales for icons and text. + if (!iconWithoutText && !textWithoutIcon) { + placeIcon = placeText = placeIcon && placeText; + } + else if (!textWithoutIcon) { + placeText = placeIcon && placeText; + } + else if (!iconWithoutText) { + placeIcon = placeIcon && placeText; + } + const hasTextBox = placeText && placedGlyphBoxes.placeable; + const hasIconBox = placeIcon && placedIconBoxes.placeable; + if (hasTextBox) { + if (placedVerticalText && placedVerticalText.placeable && verticalTextFeatureIndex) { + this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, textOverlapMode, layout.get('text-ignore-placement'), bucket.bucketInstanceId, verticalTextFeatureIndex, collisionGroup.ID); + } + else { + this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, textOverlapMode, layout.get('text-ignore-placement'), bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID); + } + } + if (hasIconBox) { + this.collisionIndex.insertCollisionBox(placedIconBoxes.box, iconOverlapMode, layout.get('icon-ignore-placement'), bucket.bucketInstanceId, iconFeatureIndex, collisionGroup.ID); + } + if (placedGlyphCircles) { + if (placeText) { + this.collisionIndex.insertCollisionCircles(placedGlyphCircles.circles, textOverlapMode, layout.get('text-ignore-placement'), bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID); + } + } + if (showCollisionBoxes) { + this.storeCollisionData(bucket.bucketInstanceId, symbolIndex, collisionArrays, placedGlyphBoxes, placedIconBoxes, placedGlyphCircles); + } + if (symbolInstance.crossTileID === 0) + throw new Error('symbolInstance.crossTileID can\'t be 0'); + if (bucket.bucketInstanceId === 0) + throw new Error('bucket.bucketInstanceId can\'t be 0'); + this.placements[symbolInstance.crossTileID] = new JointPlacement(placeText || alwaysShowText, placeIcon || alwaysShowIcon, offscreen || bucket.justReloaded); + seenCrossTileIDs[symbolInstance.crossTileID] = true; + }; + if (zOrderByViewportY) { + if (bucketPart.symbolInstanceStart !== 0) + throw new Error('bucket.bucketInstanceId should be 0'); + const symbolIndexes = bucket.getSortedSymbolIndexes(this.transform.angle); + for (let i = symbolIndexes.length - 1; i >= 0; --i) { + const symbolIndex = symbolIndexes[i]; + placeSymbol(bucket.symbolInstances.get(symbolIndex), bucket.collisionArrays[symbolIndex], symbolIndex); + } + } + else { + for (let i = bucketPart.symbolInstanceStart; i < bucketPart.symbolInstanceEnd; i++) { + placeSymbol(bucket.symbolInstances.get(i), bucket.collisionArrays[i], i); + } + } + if (showCollisionBoxes && bucket.bucketInstanceId in this.collisionCircleArrays) { + const circleArray = this.collisionCircleArrays[bucket.bucketInstanceId]; + // Store viewport and inverse projection matrices per bucket + performance$1.as(circleArray.invProjMatrix, posMatrix); + circleArray.viewportMatrix = this.collisionIndex.getViewportMatrix(); + } + bucket.justReloaded = false; + } + storeCollisionData(bucketInstanceId, symbolIndex, collisionArrays, placedGlyphBoxes, placedIconBoxes, placedGlyphCircles) { + if (collisionArrays.textBox || collisionArrays.iconBox) { + // Store the actually used collision box for debug draw + let boxArray; + if (this.collisionBoxArrays.has(bucketInstanceId)) { + boxArray = this.collisionBoxArrays.get(bucketInstanceId); + } + else { + boxArray = new Map(); + this.collisionBoxArrays.set(bucketInstanceId, boxArray); + } + let realCollisionBox; + if (boxArray.has(symbolIndex)) { + realCollisionBox = boxArray.get(symbolIndex); + } + else { + realCollisionBox = { + text: null, + icon: null + }; + boxArray.set(symbolIndex, realCollisionBox); + } + if (collisionArrays.textBox) { + realCollisionBox.text = placedGlyphBoxes.box; + } + if (collisionArrays.iconBox) { + realCollisionBox.icon = placedIconBoxes.box; + } + } + if (placedGlyphCircles) { + let circleArray = this.collisionCircleArrays[bucketInstanceId]; + // Group collision circles together by bucket. Circles can't be pushed forward for rendering yet as the symbol placement + // for a bucket is not guaranteed to be complete before the commit-function has been called + if (circleArray === undefined) + circleArray = this.collisionCircleArrays[bucketInstanceId] = new CollisionCircleArray(); + for (let i = 0; i < placedGlyphCircles.circles.length; i += 4) { + circleArray.circles.push(placedGlyphCircles.circles[i + 0]); // x + circleArray.circles.push(placedGlyphCircles.circles[i + 1]); // y + circleArray.circles.push(placedGlyphCircles.circles[i + 2]); // radius + circleArray.circles.push(placedGlyphCircles.collisionDetected ? 1 : 0); // collisionDetected-flag + } + } + } + markUsedJustification(bucket, placedAnchor, symbolInstance, orientation) { + const justifications = { + 'left': symbolInstance.leftJustifiedTextSymbolIndex, + 'center': symbolInstance.centerJustifiedTextSymbolIndex, + 'right': symbolInstance.rightJustifiedTextSymbolIndex + }; + let autoIndex; + if (orientation === performance$1.ah.vertical) { + autoIndex = symbolInstance.verticalPlacedTextSymbolIndex; + } + else { + autoIndex = justifications[performance$1.at(placedAnchor)]; + } + const indexes = [ + symbolInstance.leftJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.verticalPlacedTextSymbolIndex + ]; + for (const index of indexes) { + if (index >= 0) { + if (autoIndex >= 0 && index !== autoIndex) { + // There are multiple justifications and this one isn't it: shift offscreen + bucket.text.placedSymbolArray.get(index).crossTileID = 0; + } + else { + // Either this is the chosen justification or the justification is hardwired: use this one + bucket.text.placedSymbolArray.get(index).crossTileID = symbolInstance.crossTileID; + } + } + } + } + markUsedOrientation(bucket, orientation, symbolInstance) { + const horizontal = (orientation === performance$1.ah.horizontal || orientation === performance$1.ah.horizontalOnly) ? orientation : 0; + const vertical = orientation === performance$1.ah.vertical ? orientation : 0; + const horizontalIndexes = [ + symbolInstance.leftJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.rightJustifiedTextSymbolIndex + ]; + for (const index of horizontalIndexes) { + bucket.text.placedSymbolArray.get(index).placedOrientation = horizontal; + } + if (symbolInstance.verticalPlacedTextSymbolIndex) { + bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).placedOrientation = vertical; + } + } + commit(now) { + this.commitTime = now; + this.zoomAtLastRecencyCheck = this.transform.zoom; + const prevPlacement = this.prevPlacement; + let placementChanged = false; + this.prevZoomAdjustment = prevPlacement ? prevPlacement.zoomAdjustment(this.transform.zoom) : 0; + const increment = prevPlacement ? prevPlacement.symbolFadeChange(now) : 1; + const prevOpacities = prevPlacement ? prevPlacement.opacities : {}; + const prevOffsets = prevPlacement ? prevPlacement.variableOffsets : {}; + const prevOrientations = prevPlacement ? prevPlacement.placedOrientations : {}; + // add the opacities from the current placement, and copy their current values from the previous placement + for (const crossTileID in this.placements) { + const jointPlacement = this.placements[crossTileID]; + const prevOpacity = prevOpacities[crossTileID]; + if (prevOpacity) { + this.opacities[crossTileID] = new JointOpacityState(prevOpacity, increment, jointPlacement.text, jointPlacement.icon); + placementChanged = placementChanged || + jointPlacement.text !== prevOpacity.text.placed || + jointPlacement.icon !== prevOpacity.icon.placed; + } + else { + this.opacities[crossTileID] = new JointOpacityState(null, increment, jointPlacement.text, jointPlacement.icon, jointPlacement.skipFade); + placementChanged = placementChanged || jointPlacement.text || jointPlacement.icon; + } + } + // copy and update values from the previous placement that aren't in the current placement but haven't finished fading + for (const crossTileID in prevOpacities) { + const prevOpacity = prevOpacities[crossTileID]; + if (!this.opacities[crossTileID]) { + const jointOpacity = new JointOpacityState(prevOpacity, increment, false, false); + if (!jointOpacity.isHidden()) { + this.opacities[crossTileID] = jointOpacity; + placementChanged = placementChanged || prevOpacity.text.placed || prevOpacity.icon.placed; + } + } + } + for (const crossTileID in prevOffsets) { + if (!this.variableOffsets[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) { + this.variableOffsets[crossTileID] = prevOffsets[crossTileID]; + } + } + for (const crossTileID in prevOrientations) { + if (!this.placedOrientations[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) { + this.placedOrientations[crossTileID] = prevOrientations[crossTileID]; + } + } + // this.lastPlacementChangeTime is the time of the last commit() that + // resulted in a placement change -- in other words, the start time of + // the last symbol fade animation + if (prevPlacement && prevPlacement.lastPlacementChangeTime === undefined) { + throw new Error('Last placement time for previous placement is not defined'); + } + if (placementChanged) { + this.lastPlacementChangeTime = now; + } + else if (typeof this.lastPlacementChangeTime !== 'number') { + this.lastPlacementChangeTime = prevPlacement ? prevPlacement.lastPlacementChangeTime : now; + } + } + updateLayerOpacities(styleLayer, tiles) { + const seenCrossTileIDs = {}; + for (const tile of tiles) { + const symbolBucket = tile.getBucket(styleLayer); + if (symbolBucket && tile.latestFeatureIndex && styleLayer.id === symbolBucket.layerIds[0]) { + this.updateBucketOpacities(symbolBucket, tile.tileID, seenCrossTileIDs, tile.collisionBoxArray); + } + } + } + updateBucketOpacities(bucket, tileID, seenCrossTileIDs, collisionBoxArray) { + if (bucket.hasTextData()) { + bucket.text.opacityVertexArray.clear(); + bucket.text.hasVisibleVertices = false; + } + if (bucket.hasIconData()) { + bucket.icon.opacityVertexArray.clear(); + bucket.icon.hasVisibleVertices = false; + } + if (bucket.hasIconCollisionBoxData()) + bucket.iconCollisionBox.collisionVertexArray.clear(); + if (bucket.hasTextCollisionBoxData()) + bucket.textCollisionBox.collisionVertexArray.clear(); + const layer = bucket.layers[0]; + const layout = layer.layout; + const duplicateOpacityState = new JointOpacityState(null, 0, false, false, true); + const textAllowOverlap = layout.get('text-allow-overlap'); + const iconAllowOverlap = layout.get('icon-allow-overlap'); + const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset'); + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const hasIconTextFit = layout.get('icon-text-fit') !== 'none'; + // If allow-overlap is true, we can show symbols before placement runs on them + // But we have to wait for placement if we potentially depend on a paired icon/text + // with allow-overlap: false. + // See https://github.com/mapbox/mapbox-gl-js/issues/7032 + const defaultOpacityState = new JointOpacityState(null, 0, textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || layout.get('icon-optional')), iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || layout.get('text-optional')), true); + if (!bucket.collisionArrays && collisionBoxArray && ((bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()))) { + bucket.deserializeCollisionBoxes(collisionBoxArray); + } + const addOpacities = (iconOrText, numVertices, opacity) => { + for (let i = 0; i < numVertices / 4; i++) { + iconOrText.opacityVertexArray.emplaceBack(opacity); + } + iconOrText.hasVisibleVertices = iconOrText.hasVisibleVertices || (opacity !== PACKED_HIDDEN_OPACITY); + }; + const boxArrays = this.collisionBoxArrays.get(bucket.bucketInstanceId); + for (let s = 0; s < bucket.symbolInstances.length; s++) { + const symbolInstance = bucket.symbolInstances.get(s); + const { numHorizontalGlyphVertices, numVerticalGlyphVertices, crossTileID } = symbolInstance; + const isDuplicate = seenCrossTileIDs[crossTileID]; + let opacityState = this.opacities[crossTileID]; + if (isDuplicate) { + opacityState = duplicateOpacityState; + } + else if (!opacityState) { + opacityState = defaultOpacityState; + // store the state so that future placements use it as a starting point + this.opacities[crossTileID] = opacityState; + } + seenCrossTileIDs[crossTileID] = true; + const hasText = numHorizontalGlyphVertices > 0 || numVerticalGlyphVertices > 0; + const hasIcon = symbolInstance.numIconVertices > 0; + const placedOrientation = this.placedOrientations[symbolInstance.crossTileID]; + const horizontalHidden = placedOrientation === performance$1.ah.vertical; + const verticalHidden = placedOrientation === performance$1.ah.horizontal || placedOrientation === performance$1.ah.horizontalOnly; + if (hasText) { + const packedOpacity = packOpacity(opacityState.text); + // Vertical text fades in/out on collision the same way as corresponding + // horizontal text. Switch between vertical/horizontal should be instantaneous + const horizontalOpacity = horizontalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity; + addOpacities(bucket.text, numHorizontalGlyphVertices, horizontalOpacity); + const verticalOpacity = verticalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity; + addOpacities(bucket.text, numVerticalGlyphVertices, verticalOpacity); + // If this label is completely faded, mark it so that we don't have to calculate + // its position at render time. If this layer has variable placement, shift the various + // symbol instances appropriately so that symbols from buckets that have yet to be placed + // offset appropriately. + const symbolHidden = opacityState.text.isHidden(); + [ + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.leftJustifiedTextSymbolIndex + ].forEach(index => { + if (index >= 0) { + bucket.text.placedSymbolArray.get(index).hidden = symbolHidden || horizontalHidden ? 1 : 0; + } + }); + if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) { + bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).hidden = symbolHidden || verticalHidden ? 1 : 0; + } + const prevOffset = this.variableOffsets[symbolInstance.crossTileID]; + if (prevOffset) { + this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, placedOrientation); + } + const prevOrientation = this.placedOrientations[symbolInstance.crossTileID]; + if (prevOrientation) { + this.markUsedJustification(bucket, 'left', symbolInstance, prevOrientation); + this.markUsedOrientation(bucket, prevOrientation, symbolInstance); + } + } + if (hasIcon) { + const packedOpacity = packOpacity(opacityState.icon); + const useHorizontal = !(hasIconTextFit && symbolInstance.verticalPlacedIconSymbolIndex && horizontalHidden); + if (symbolInstance.placedIconSymbolIndex >= 0) { + const horizontalOpacity = useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY; + addOpacities(bucket.icon, symbolInstance.numIconVertices, horizontalOpacity); + bucket.icon.placedSymbolArray.get(symbolInstance.placedIconSymbolIndex).hidden = + opacityState.icon.isHidden(); + } + if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) { + const verticalOpacity = !useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY; + addOpacities(bucket.icon, symbolInstance.numVerticalIconVertices, verticalOpacity); + bucket.icon.placedSymbolArray.get(symbolInstance.verticalPlacedIconSymbolIndex).hidden = + opacityState.icon.isHidden(); + } + } + const realBoxes = (boxArrays && boxArrays.has(s)) ? boxArrays.get(s) : { + text: null, + icon: null + }; + if (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()) { + const collisionArrays = bucket.collisionArrays[s]; + if (collisionArrays) { + let shift = new performance$1.P(0, 0); + if (collisionArrays.textBox || collisionArrays.verticalTextBox) { + let used = true; + if (hasVariablePlacement) { + const variableOffset = this.variableOffsets[crossTileID]; + if (variableOffset) { + // This will show either the currently placed position or the last + // successfully placed position (so you can visualize what collision + // just made the symbol disappear, and the most likely place for the + // symbol to come back) + shift = calculateVariableLayoutShift(variableOffset.anchor, variableOffset.width, variableOffset.height, variableOffset.textOffset, variableOffset.textBoxScale); + if (rotateWithMap) { + shift._rotate(pitchWithMap ? this.transform.angle : -this.transform.angle); + } + } + else { + // No offset -> this symbol hasn't been placed since coming on-screen + // No single box is particularly meaningful and all of them would be too noisy + // Use the center box just to show something's there, but mark it "not used" + used = false; + } + } + if (collisionArrays.textBox || collisionArrays.verticalTextBox) { + let hidden; + if (collisionArrays.textBox) { + hidden = horizontalHidden; + } + if (collisionArrays.verticalTextBox) { + hidden = verticalHidden; + } + updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || hidden, realBoxes.text, shift.x, shift.y); + } + } + if (collisionArrays.iconBox || collisionArrays.verticalIconBox) { + const verticalIconUsed = Boolean(!verticalHidden && collisionArrays.verticalIconBox); + let hidden; + if (collisionArrays.iconBox) { + hidden = verticalIconUsed; + } + if (collisionArrays.verticalIconBox) { + hidden = !verticalIconUsed; + } + updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, hidden, realBoxes.icon, hasIconTextFit ? shift.x : 0, hasIconTextFit ? shift.y : 0); + } + } + } + } + bucket.sortFeatures(this.transform.angle); + if (this.retainedQueryData[bucket.bucketInstanceId]) { + this.retainedQueryData[bucket.bucketInstanceId].featureSortOrder = bucket.featureSortOrder; + } + if (bucket.hasTextData() && bucket.text.opacityVertexBuffer) { + bucket.text.opacityVertexBuffer.updateData(bucket.text.opacityVertexArray); + } + if (bucket.hasIconData() && bucket.icon.opacityVertexBuffer) { + bucket.icon.opacityVertexBuffer.updateData(bucket.icon.opacityVertexArray); + } + if (bucket.hasIconCollisionBoxData() && bucket.iconCollisionBox.collisionVertexBuffer) { + bucket.iconCollisionBox.collisionVertexBuffer.updateData(bucket.iconCollisionBox.collisionVertexArray); + } + if (bucket.hasTextCollisionBoxData() && bucket.textCollisionBox.collisionVertexBuffer) { + bucket.textCollisionBox.collisionVertexBuffer.updateData(bucket.textCollisionBox.collisionVertexArray); + } + if (bucket.text.opacityVertexArray.length !== bucket.text.layoutVertexArray.length / 4) + throw new Error(`bucket.text.opacityVertexArray.length (= ${bucket.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${bucket.text.layoutVertexArray.length}) / 4`); + if (bucket.icon.opacityVertexArray.length !== bucket.icon.layoutVertexArray.length / 4) + throw new Error(`bucket.icon.opacityVertexArray.length (= ${bucket.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${bucket.icon.layoutVertexArray.length}) / 4`); + // Push generated collision circles to the bucket for debug rendering + if (bucket.bucketInstanceId in this.collisionCircleArrays) { + const instance = this.collisionCircleArrays[bucket.bucketInstanceId]; + bucket.placementInvProjMatrix = instance.invProjMatrix; + bucket.placementViewportMatrix = instance.viewportMatrix; + bucket.collisionCircleArray = instance.circles; + delete this.collisionCircleArrays[bucket.bucketInstanceId]; + } + } + symbolFadeChange(now) { + return this.fadeDuration === 0 ? + 1 : + ((now - this.commitTime) / this.fadeDuration + this.prevZoomAdjustment); + } + zoomAdjustment(zoom) { + // When zooming out quickly, labels can overlap each other. This + // adjustment is used to reduce the interval between placement calculations + // and to reduce the fade duration when zooming out quickly. Discovering the + // collisions more quickly and fading them more quickly reduces the unwanted effect. + return Math.max(0, (this.transform.zoom - zoom) / 1.5); + } + hasTransitions(now) { + return this.stale || + now - this.lastPlacementChangeTime < this.fadeDuration; + } + stillRecent(now, zoom) { + // The adjustment makes placement more frequent when zooming. + // This condition applies the adjustment only after the map has + // stopped zooming. This avoids adding extra jank while zooming. + const durationAdjustment = this.zoomAtLastRecencyCheck === zoom ? + (1 - this.zoomAdjustment(zoom)) : + 1; + this.zoomAtLastRecencyCheck = zoom; + return this.commitTime + this.fadeDuration * durationAdjustment > now; + } + setStale() { + this.stale = true; + } +} +function updateCollisionVertices(collisionVertexArray, placed, notUsed, realBox, shiftX, shiftY) { + if (!realBox || realBox.length === 0) { + realBox = [0, 0, 0, 0]; + } + const tlX = realBox[0] - viewportPadding; + const tlY = realBox[1] - viewportPadding; + const brX = realBox[2] - viewportPadding; + const brY = realBox[3] - viewportPadding; + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, tlX, tlY); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, brX, tlY); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, brX, brY); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, tlX, brY); +} +// All four vertices for a glyph will have the same opacity state +// So we pack the opacity into a uint8, and then repeat it four times +// to make a single uint32 that we can upload for each glyph in the +// label. +const shift25 = Math.pow(2, 25); +const shift24 = Math.pow(2, 24); +const shift17 = Math.pow(2, 17); +const shift16 = Math.pow(2, 16); +const shift9 = Math.pow(2, 9); +const shift8 = Math.pow(2, 8); +const shift1 = Math.pow(2, 1); +function packOpacity(opacityState) { + if (opacityState.opacity === 0 && !opacityState.placed) { + return 0; + } + else if (opacityState.opacity === 1 && opacityState.placed) { + return 4294967295; + } + const targetBit = opacityState.placed ? 1 : 0; + const opacityBits = Math.floor(opacityState.opacity * 127); + return opacityBits * shift25 + targetBit * shift24 + + opacityBits * shift17 + targetBit * shift16 + + opacityBits * shift9 + targetBit * shift8 + + opacityBits * shift1 + targetBit; +} +const PACKED_HIDDEN_OPACITY = 0; + +function createProjection() { + return { + isOccluded(_x, _y, _t) { + return false; + }, + getPitchedTextCorrection(_transform, _anchor, _tile) { + return 1.0; + }, + get useSpecialProjectionForSymbols() { return false; }, + projectTileCoordinates(_x, _y, _t, _ele) { + // This function should only be used when useSpecialProjectionForSymbols is set to true. + throw new Error('Not implemented.'); + }, + translatePosition(transform, tile, translate, translateAnchor) { + return translatePosition(transform, tile, translate, translateAnchor); + }, + getCircleRadiusCorrection(_) { + return 1.0; + } + }; +} +/** + * Returns a translation in tile units that correctly incorporates the view angle and the *-translate and *-translate-anchor properties. + * @param inViewportPixelUnitsUnits - True when the units accepted by the matrix are in viewport pixels instead of tile units. + * + * Temporarily imported from globe branch. + */ +function translatePosition(transform, tile, translate, translateAnchor, inViewportPixelUnitsUnits = false) { + if (!translate[0] && !translate[1]) + return [0, 0]; + const angle = inViewportPixelUnitsUnits ? + (translateAnchor === 'map' ? transform.angle : 0) : + (translateAnchor === 'viewport' ? -transform.angle : 0); + if (angle) { + const sinA = Math.sin(angle); + const cosA = Math.cos(angle); + translate = [ + translate[0] * cosA - translate[1] * sinA, + translate[0] * sinA + translate[1] * cosA + ]; + } + return [ + inViewportPixelUnitsUnits ? translate[0] : pixelsToTileUnits(tile, translate[0], transform.zoom), + inViewportPixelUnitsUnits ? translate[1] : pixelsToTileUnits(tile, translate[1], transform.zoom) + ]; +} + +class LayerPlacement { + constructor(styleLayer) { + this._sortAcrossTiles = styleLayer.layout.get('symbol-z-order') !== 'viewport-y' && + !styleLayer.layout.get('symbol-sort-key').isConstant(); + this._currentTileIndex = 0; + this._currentPartIndex = 0; + this._seenCrossTileIDs = {}; + this._bucketParts = []; + } + continuePlacement(tiles, placement, showCollisionBoxes, styleLayer, shouldPausePlacement) { + const bucketParts = this._bucketParts; + while (this._currentTileIndex < tiles.length) { + const tile = tiles[this._currentTileIndex]; + placement.getBucketParts(bucketParts, styleLayer, tile, this._sortAcrossTiles); + this._currentTileIndex++; + if (shouldPausePlacement()) { + return true; + } + } + if (this._sortAcrossTiles) { + this._sortAcrossTiles = false; + bucketParts.sort((a, b) => a.sortKey - b.sortKey); + } + while (this._currentPartIndex < bucketParts.length) { + const bucketPart = bucketParts[this._currentPartIndex]; + placement.placeLayerBucketPart(bucketPart, this._seenCrossTileIDs, showCollisionBoxes); + this._currentPartIndex++; + if (shouldPausePlacement()) { + return true; + } + } + return false; + } +} +class PauseablePlacement { + constructor(transform, terrain, order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, prevPlacement) { + this.placement = new Placement(transform, createProjection(), terrain, fadeDuration, crossSourceCollisions, prevPlacement); + this._currentPlacementIndex = order.length - 1; + this._forceFullPlacement = forceFullPlacement; + this._showCollisionBoxes = showCollisionBoxes; + this._done = false; + } + isDone() { + return this._done; + } + continuePlacement(order, layers, layerTiles) { + const startTime = browser.now(); + const shouldPausePlacement = () => { + return this._forceFullPlacement ? false : (browser.now() - startTime) > 2; + }; + while (this._currentPlacementIndex >= 0) { + const layerId = order[this._currentPlacementIndex]; + const layer = layers[layerId]; + const placementZoom = this.placement.collisionIndex.transform.zoom; + if (layer.type === 'symbol' && + (!layer.minzoom || layer.minzoom <= placementZoom) && + (!layer.maxzoom || layer.maxzoom > placementZoom)) { + if (!this._inProgressLayer) { + this._inProgressLayer = new LayerPlacement(layer); + } + const pausePlacement = this._inProgressLayer.continuePlacement(layerTiles[layer.source], this.placement, this._showCollisionBoxes, layer, shouldPausePlacement); + if (pausePlacement) { + // We didn't finish placing all layers within 2ms, + // but we can keep rendering with a partial placement + // We'll resume here on the next frame + return; + } + delete this._inProgressLayer; + } + this._currentPlacementIndex--; + } + this._done = true; + } + commit(now) { + this.placement.commit(now); + return this.placement; + } +} + +/* + The CrossTileSymbolIndex generally works on the assumption that + a conceptual "unique symbol" can be identified by the text of + the label combined with the anchor point. The goal is to assign + these conceptual "unique symbols" a shared crossTileID that can be + used by Placement to keep fading opacity states consistent and to + deduplicate labels. + + The CrossTileSymbolIndex indexes all the current symbol instances and + their crossTileIDs. When a symbol bucket gets added or updated, the + index assigns a crossTileID to each of it's symbol instances by either + matching it with an existing id or assigning a new one. +*/ +// Round anchor positions to roughly 4 pixel grid +const roundingFactor = 512 / performance$1.X / 2; +const KDBUSH_THRESHHOLD = 128; +class TileLayerIndex { + constructor(tileID, symbolInstances, bucketInstanceId) { + this.tileID = tileID; + this.bucketInstanceId = bucketInstanceId; + this._symbolsByKey = {}; + // group the symbolInstances by key + const symbolInstancesByKey = new Map(); + for (let i = 0; i < symbolInstances.length; i++) { + const symbolInstance = symbolInstances.get(i); + const key = symbolInstance.key; + const instances = symbolInstancesByKey.get(key); + if (instances) { + // This tile may have multiple symbol instances with the same key + // Store each one along with its coordinates + instances.push(symbolInstance); + } + else { + symbolInstancesByKey.set(key, [symbolInstance]); + } + } + // index the SymbolInstances in this each bucket + for (const [key, symbols] of symbolInstancesByKey) { + const positions = symbols.map(symbolInstance => ({ x: Math.floor(symbolInstance.anchorX * roundingFactor), y: Math.floor(symbolInstance.anchorY * roundingFactor) })); + const crossTileIDs = symbols.map(v => v.crossTileID); + const entry = { positions, crossTileIDs }; + // once we get too many symbols for a given key, it becomes much faster to index it before queries + if (entry.positions.length > KDBUSH_THRESHHOLD) { + const index = new performance$1.av(entry.positions.length, 16, Uint16Array); + for (const { x, y } of entry.positions) + index.add(x, y); + index.finish(); + // clear all references to the original positions data + delete entry.positions; + entry.index = index; + } + this._symbolsByKey[key] = entry; + } + } + // Converts the coordinates of the input symbol instance into coordinates that be can compared + // against other symbols in this index. Coordinates are: + // (1) local-tile-based (so after correction we get x,y values relative to our local anchorX/Y) + // (2) converted to the z-scale of this TileLayerIndex + // (3) down-sampled by "roundingFactor" from tile coordinate precision in order to be + // more tolerant of small differences between tiles. + getScaledCoordinates(symbolInstance, childTileID) { + const { x: localX, y: localY, z: localZ } = this.tileID.canonical; + const { x, y, z } = childTileID.canonical; + const zDifference = z - localZ; + const scale = roundingFactor / Math.pow(2, zDifference); + const xWorld = (x * performance$1.X + symbolInstance.anchorX) * scale; + const yWorld = (y * performance$1.X + symbolInstance.anchorY) * scale; + const xOffset = localX * performance$1.X * roundingFactor; + const yOffset = localY * performance$1.X * roundingFactor; + const result = { + x: Math.floor(xWorld - xOffset), + y: Math.floor(yWorld - yOffset) + }; + return result; + } + findMatches(symbolInstances, newTileID, zoomCrossTileIDs) { + const tolerance = this.tileID.canonical.z < newTileID.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - newTileID.canonical.z); + for (let i = 0; i < symbolInstances.length; i++) { + const symbolInstance = symbolInstances.get(i); + if (symbolInstance.crossTileID) { + // already has a match, skip + continue; + } + const entry = this._symbolsByKey[symbolInstance.key]; + if (!entry) { + // No symbol with this key in this bucket + continue; + } + const scaledSymbolCoord = this.getScaledCoordinates(symbolInstance, newTileID); + if (entry.index) { + // Return any symbol with the same keys whose coordinates are within 1 + // grid unit. (with a 4px grid, this covers a 12px by 12px area) + const indexes = entry.index.range(scaledSymbolCoord.x - tolerance, scaledSymbolCoord.y - tolerance, scaledSymbolCoord.x + tolerance, scaledSymbolCoord.y + tolerance).sort(); + for (const i of indexes) { + const crossTileID = entry.crossTileIDs[i]; + if (!zoomCrossTileIDs[crossTileID]) { + // Once we've marked ourselves duplicate against this parent symbol, + // don't let any other symbols at the same zoom level duplicate against + // the same parent (see issue #5993) + zoomCrossTileIDs[crossTileID] = true; + symbolInstance.crossTileID = crossTileID; + break; + } + } + } + else if (entry.positions) { + for (let i = 0; i < entry.positions.length; i++) { + const thisTileSymbol = entry.positions[i]; + const crossTileID = entry.crossTileIDs[i]; + // Return any symbol with the same keys whose coordinates are within 1 + // grid unit. (with a 4px grid, this covers a 12px by 12px area) + if (Math.abs(thisTileSymbol.x - scaledSymbolCoord.x) <= tolerance && + Math.abs(thisTileSymbol.y - scaledSymbolCoord.y) <= tolerance && + !zoomCrossTileIDs[crossTileID]) { + // Once we've marked ourselves duplicate against this parent symbol, + // don't let any other symbols at the same zoom level duplicate against + // the same parent (see issue #5993) + zoomCrossTileIDs[crossTileID] = true; + symbolInstance.crossTileID = crossTileID; + break; + } + } + } + } + } + getCrossTileIDsLists() { + return Object.values(this._symbolsByKey).map(({ crossTileIDs }) => crossTileIDs); + } +} +class CrossTileIDs { + constructor() { + this.maxCrossTileID = 0; + } + generate() { + return ++this.maxCrossTileID; + } +} +class CrossTileSymbolLayerIndex { + constructor() { + this.indexes = {}; + this.usedCrossTileIDs = {}; + this.lng = 0; + } + /* + * Sometimes when a user pans across the antimeridian the longitude value gets wrapped. + * To prevent labels from flashing out and in we adjust the tileID values in the indexes + * so that they match the new wrapped version of the map. + */ + handleWrapJump(lng) { + const wrapDelta = Math.round((lng - this.lng) / 360); + if (wrapDelta !== 0) { + for (const zoom in this.indexes) { + const zoomIndexes = this.indexes[zoom]; + const newZoomIndex = {}; + for (const key in zoomIndexes) { + // change the tileID's wrap and add it to a new index + const index = zoomIndexes[key]; + index.tileID = index.tileID.unwrapTo(index.tileID.wrap + wrapDelta); + newZoomIndex[index.tileID.key] = index; + } + this.indexes[zoom] = newZoomIndex; + } + } + this.lng = lng; + } + addBucket(tileID, bucket, crossTileIDs) { + if (this.indexes[tileID.overscaledZ] && + this.indexes[tileID.overscaledZ][tileID.key]) { + if (this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId === + bucket.bucketInstanceId) { + return false; + } + else { + // We're replacing this bucket with an updated version + // Remove the old bucket's "used crossTileIDs" now so that + // the new bucket can claim them. + // The old index entries themselves stick around until + // 'removeStaleBuckets' is called. + this.removeBucketCrossTileIDs(tileID.overscaledZ, this.indexes[tileID.overscaledZ][tileID.key]); + } + } + for (let i = 0; i < bucket.symbolInstances.length; i++) { + const symbolInstance = bucket.symbolInstances.get(i); + symbolInstance.crossTileID = 0; + } + if (!this.usedCrossTileIDs[tileID.overscaledZ]) { + this.usedCrossTileIDs[tileID.overscaledZ] = {}; + } + const zoomCrossTileIDs = this.usedCrossTileIDs[tileID.overscaledZ]; + for (const zoom in this.indexes) { + const zoomIndexes = this.indexes[zoom]; + if (Number(zoom) > tileID.overscaledZ) { + for (const id in zoomIndexes) { + const childIndex = zoomIndexes[id]; + if (childIndex.tileID.isChildOf(tileID)) { + childIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs); + } + } + } + else { + const parentCoord = tileID.scaledTo(Number(zoom)); + const parentIndex = zoomIndexes[parentCoord.key]; + if (parentIndex) { + parentIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs); + } + } + } + for (let i = 0; i < bucket.symbolInstances.length; i++) { + const symbolInstance = bucket.symbolInstances.get(i); + if (!symbolInstance.crossTileID) { + // symbol did not match any known symbol, assign a new id + symbolInstance.crossTileID = crossTileIDs.generate(); + zoomCrossTileIDs[symbolInstance.crossTileID] = true; + } + } + if (this.indexes[tileID.overscaledZ] === undefined) { + this.indexes[tileID.overscaledZ] = {}; + } + this.indexes[tileID.overscaledZ][tileID.key] = new TileLayerIndex(tileID, bucket.symbolInstances, bucket.bucketInstanceId); + return true; + } + removeBucketCrossTileIDs(zoom, removedBucket) { + for (const crossTileIDs of removedBucket.getCrossTileIDsLists()) { + for (const crossTileID of crossTileIDs) { + delete this.usedCrossTileIDs[zoom][crossTileID]; + } + } + } + removeStaleBuckets(currentIDs) { + let tilesChanged = false; + for (const z in this.indexes) { + const zoomIndexes = this.indexes[z]; + for (const tileKey in zoomIndexes) { + if (!currentIDs[zoomIndexes[tileKey].bucketInstanceId]) { + this.removeBucketCrossTileIDs(z, zoomIndexes[tileKey]); + delete zoomIndexes[tileKey]; + tilesChanged = true; + } + } + } + return tilesChanged; + } +} +class CrossTileSymbolIndex { + constructor() { + this.layerIndexes = {}; + this.crossTileIDs = new CrossTileIDs(); + this.maxBucketInstanceId = 0; + this.bucketsInCurrentPlacement = {}; + } + addLayer(styleLayer, tiles, lng) { + let layerIndex = this.layerIndexes[styleLayer.id]; + if (layerIndex === undefined) { + layerIndex = this.layerIndexes[styleLayer.id] = new CrossTileSymbolLayerIndex(); + } + let symbolBucketsChanged = false; + const currentBucketIDs = {}; + layerIndex.handleWrapJump(lng); + for (const tile of tiles) { + const symbolBucket = tile.getBucket(styleLayer); + if (!symbolBucket || styleLayer.id !== symbolBucket.layerIds[0]) + continue; + if (!symbolBucket.bucketInstanceId) { + symbolBucket.bucketInstanceId = ++this.maxBucketInstanceId; + } + if (layerIndex.addBucket(tile.tileID, symbolBucket, this.crossTileIDs)) { + symbolBucketsChanged = true; + } + currentBucketIDs[symbolBucket.bucketInstanceId] = true; + } + if (layerIndex.removeStaleBuckets(currentBucketIDs)) { + symbolBucketsChanged = true; + } + return symbolBucketsChanged; + } + pruneUnusedLayers(usedLayers) { + const usedLayerMap = {}; + usedLayers.forEach((usedLayer) => { + usedLayerMap[usedLayer] = true; + }); + for (const layerId in this.layerIndexes) { + if (!usedLayerMap[layerId]) { + delete this.layerIndexes[layerId]; + } + } + } +} + +// We're skipping validation errors with the `source.canvas` identifier in order +// to continue to allow canvas sources to be added at runtime/updated in +// smart setStyle (see https://github.com/mapbox/mapbox-gl-js/pull/6424): +const emitValidationErrors = (evented, errors) => performance$1.t(evented, errors && errors.filter(error => error.identifier !== 'source.canvas')); +const empty = performance$1.aw(); +/** + * The Style base class + */ +class Style extends performance$1.E { + constructor(map, options = {}) { + super(); + this._rtlPluginLoaded = () => { + for (const id in this.sourceCaches) { + const sourceType = this.sourceCaches[id].getSource().type; + if (sourceType === 'vector' || sourceType === 'geojson') { + // Non-vector sources don't have any symbols buckets to reload when the RTL text plugin loads + // They also load more quickly, so they're more likely to have already displaying tiles + // that would be unnecessarily booted by the plugin load event + this.sourceCaches[id].reload(); // Should be a no-op if the plugin loads before any tiles load + } + } + }; + this.map = map; + this.dispatcher = new Dispatcher(getGlobalWorkerPool(), map._getMapId()); + this.dispatcher.registerMessageHandler("GG" /* MessageType.getGlyphs */, (mapId, params) => { + return this.getGlyphs(mapId, params); + }); + this.dispatcher.registerMessageHandler("GI" /* MessageType.getImages */, (mapId, params) => { + return this.getImages(mapId, params); + }); + this.imageManager = new ImageManager(); + this.imageManager.setEventedParent(this); + this.glyphManager = new GlyphManager(map._requestManager, options.localIdeographFontFamily); + this.lineAtlas = new LineAtlas(256, 512); + this.crossTileSymbolIndex = new CrossTileSymbolIndex(); + this._spritesImagesIds = {}; + this._layers = {}; + this._order = []; + this.sourceCaches = {}; + this.zoomHistory = new performance$1.ax(); + this._loaded = false; + this._availableImages = []; + this._resetUpdates(); + this.dispatcher.broadcast("SR" /* MessageType.setReferrer */, performance$1.ay()); + rtlMainThreadPluginFactory().on(RTLPluginLoadedEventName, this._rtlPluginLoaded); + this.on('data', (event) => { + if (event.dataType !== 'source' || event.sourceDataType !== 'metadata') { + return; + } + const sourceCache = this.sourceCaches[event.sourceId]; + if (!sourceCache) { + return; + } + const source = sourceCache.getSource(); + if (!source || !source.vectorLayerIds) { + return; + } + for (const layerId in this._layers) { + const layer = this._layers[layerId]; + if (layer.source === source.id) { + this._validateLayer(layer); + } + } + }); + } + loadURL(url, options = {}, previousStyle) { + this.fire(new performance$1.k('dataloading', { dataType: 'style' })); + options.validate = typeof options.validate === 'boolean' ? + options.validate : true; + const request = this.map._requestManager.transformRequest(url, "Style" /* ResourceType.Style */); + this._loadStyleRequest = new AbortController(); + const abortController = this._loadStyleRequest; + performance$1.h(request, this._loadStyleRequest).then((response) => { + this._loadStyleRequest = null; + this._load(response.data, options, previousStyle); + }).catch((error) => { + this._loadStyleRequest = null; + if (error && !abortController.signal.aborted) { // ignore abort + this.fire(new performance$1.j(error)); + } + }); + } + loadJSON(json, options = {}, previousStyle) { + this.fire(new performance$1.k('dataloading', { dataType: 'style' })); + this._frameRequest = new AbortController(); + browser.frameAsync(this._frameRequest).then(() => { + this._frameRequest = null; + options.validate = options.validate !== false; + this._load(json, options, previousStyle); + }).catch(() => { }); // ignore abort + } + loadEmpty() { + this.fire(new performance$1.k('dataloading', { dataType: 'style' })); + this._load(empty, { validate: false }); + } + _load(json, options, previousStyle) { + var _a; + const nextState = options.transformStyle ? options.transformStyle(previousStyle, json) : json; + if (options.validate && emitValidationErrors(this, performance$1.u(nextState))) { + return; + } + this._loaded = true; + this.stylesheet = nextState; + for (const id in nextState.sources) { + this.addSource(id, nextState.sources[id], { validate: false }); + } + if (nextState.sprite) { + this._loadSprite(nextState.sprite); + } + else { + this.imageManager.setLoaded(true); + } + this.glyphManager.setURL(nextState.glyphs); + this._createLayers(); + this.light = new Light(this.stylesheet.light); + this.sky = new Sky(this.stylesheet.sky); + this.map.setTerrain((_a = this.stylesheet.terrain) !== null && _a !== void 0 ? _a : null); + this.fire(new performance$1.k('data', { dataType: 'style' })); + this.fire(new performance$1.k('style.load')); + } + _createLayers() { + const dereferencedLayers = performance$1.az(this.stylesheet.layers); + // Broadcast layers to workers first, so that expensive style processing (createStyleLayer) + // can happen in parallel on both main and worker threads. + this.dispatcher.broadcast("SL" /* MessageType.setLayers */, dereferencedLayers); + this._order = dereferencedLayers.map((layer) => layer.id); + this._layers = {}; + // reset serialization field, to be populated only when needed + this._serializedLayers = null; + for (const layer of dereferencedLayers) { + const styledLayer = performance$1.aA(layer); + styledLayer.setEventedParent(this, { layer: { id: layer.id } }); + this._layers[layer.id] = styledLayer; + } + } + _loadSprite(sprite, isUpdate = false, completion = undefined) { + this.imageManager.setLoaded(false); + this._spriteRequest = new AbortController(); + let err; + loadSprite(sprite, this.map._requestManager, this.map.getPixelRatio(), this._spriteRequest).then((images) => { + this._spriteRequest = null; + if (images) { + for (const spriteId in images) { + this._spritesImagesIds[spriteId] = []; + // remove old sprite's loaded images (for the same sprite id) that are not in new sprite + const imagesToRemove = this._spritesImagesIds[spriteId] ? this._spritesImagesIds[spriteId].filter(id => !(id in images)) : []; + for (const id of imagesToRemove) { + this.imageManager.removeImage(id); + this._changedImages[id] = true; + } + for (const id in images[spriteId]) { + // don't prefix images of the "default" sprite + const imageId = spriteId === 'default' ? id : `${spriteId}:${id}`; + // save all the sprite's images' ids to be able to delete them in `removeSprite` + this._spritesImagesIds[spriteId].push(imageId); + if (imageId in this.imageManager.images) { + this.imageManager.updateImage(imageId, images[spriteId][id], false); + } + else { + this.imageManager.addImage(imageId, images[spriteId][id]); + } + if (isUpdate) { + this._changedImages[imageId] = true; + } + } + } + } + }).catch((error) => { + this._spriteRequest = null; + err = error; + this.fire(new performance$1.j(err)); + }).finally(() => { + this.imageManager.setLoaded(true); + this._availableImages = this.imageManager.listImages(); + if (isUpdate) { + this._changed = true; + } + this.dispatcher.broadcast("SI" /* MessageType.setImages */, this._availableImages); + this.fire(new performance$1.k('data', { dataType: 'style' })); + if (completion) { + completion(err); + } + }); + } + _unloadSprite() { + for (const id of Object.values(this._spritesImagesIds).flat()) { + this.imageManager.removeImage(id); + this._changedImages[id] = true; + } + this._spritesImagesIds = {}; + this._availableImages = this.imageManager.listImages(); + this._changed = true; + this.dispatcher.broadcast("SI" /* MessageType.setImages */, this._availableImages); + this.fire(new performance$1.k('data', { dataType: 'style' })); + } + _validateLayer(layer) { + const sourceCache = this.sourceCaches[layer.source]; + if (!sourceCache) { + return; + } + const sourceLayer = layer.sourceLayer; + if (!sourceLayer) { + return; + } + const source = sourceCache.getSource(); + if (source.type === 'geojson' || (source.vectorLayerIds && source.vectorLayerIds.indexOf(sourceLayer) === -1)) { + this.fire(new performance$1.j(new Error(`Source layer "${sourceLayer}" ` + + `does not exist on source "${source.id}" ` + + `as specified by style layer "${layer.id}".`))); + } + } + loaded() { + if (!this._loaded) + return false; + if (Object.keys(this._updatedSources).length) + return false; + for (const id in this.sourceCaches) + if (!this.sourceCaches[id].loaded()) + return false; + if (!this.imageManager.isLoaded()) + return false; + return true; + } + /** + * @hidden + * take an array of string IDs, and based on this._layers, generate an array of LayerSpecification + * @param ids - an array of string IDs, for which serialized layers will be generated. If omitted, all serialized layers will be returned + * @param returnClose - if true, return a clone of the layer object + * @returns generated result + */ + _serializeByIds(ids, returnClone = false) { + const serializedLayersDictionary = this._serializedAllLayers(); + if (!ids || ids.length === 0) { + return returnClone ? Object.values(performance$1.aB(serializedLayersDictionary)) : Object.values(serializedLayersDictionary); + } + const serializedLayers = []; + for (const id of ids) { + // this check will skip all custom layers + if (serializedLayersDictionary[id]) { + const toPush = returnClone ? performance$1.aB(serializedLayersDictionary[id]) : serializedLayersDictionary[id]; + serializedLayers.push(toPush); + } + } + return serializedLayers; + } + /** + * @hidden + * Lazy initialization of this._serializedLayers dictionary and return it + * @returns this._serializedLayers dictionary + */ + _serializedAllLayers() { + let serializedLayers = this._serializedLayers; + if (serializedLayers) { + return serializedLayers; + } + serializedLayers = this._serializedLayers = {}; + const allLayerIds = Object.keys(this._layers); + for (const layerId of allLayerIds) { + const layer = this._layers[layerId]; + if (layer.type !== 'custom') { + serializedLayers[layerId] = layer.serialize(); + } + } + return serializedLayers; + } + hasTransitions() { + if (this.light && this.light.hasTransition()) { + return true; + } + if (this.sky && this.sky.hasTransition()) { + return true; + } + for (const id in this.sourceCaches) { + if (this.sourceCaches[id].hasTransition()) { + return true; + } + } + for (const id in this._layers) { + if (this._layers[id].hasTransition()) { + return true; + } + } + return false; + } + _checkLoaded() { + if (!this._loaded) { + throw new Error('Style is not done loading.'); + } + } + /** + * @internal + * Apply queued style updates in a batch and recalculate zoom-dependent paint properties. + */ + update(parameters) { + if (!this._loaded) { + return; + } + const changed = this._changed; + if (changed) { + const updatedIds = Object.keys(this._updatedLayers); + const removedIds = Object.keys(this._removedLayers); + if (updatedIds.length || removedIds.length) { + this._updateWorkerLayers(updatedIds, removedIds); + } + for (const id in this._updatedSources) { + const action = this._updatedSources[id]; + if (action === 'reload') { + this._reloadSource(id); + } + else if (action === 'clear') { + this._clearSource(id); + } + else { + throw new Error(`Invalid action ${action}`); + } + } + this._updateTilesForChangedImages(); + this._updateTilesForChangedGlyphs(); + for (const id in this._updatedPaintProps) { + this._layers[id].updateTransitions(parameters); + } + this.light.updateTransitions(parameters); + this.sky.updateTransitions(parameters); + this._resetUpdates(); + } + const sourcesUsedBefore = {}; + // save 'used' status to sourcesUsedBefore object and reset all sourceCaches 'used' field to false + for (const sourceCacheId in this.sourceCaches) { + const sourceCache = this.sourceCaches[sourceCacheId]; + // sourceCache.used could be undefined, and sourcesUsedBefore[sourceCacheId] is also 'undefined' + sourcesUsedBefore[sourceCacheId] = sourceCache.used; + sourceCache.used = false; + } + // loop all layers and find layers that are not hidden at parameters.zoom + // and set used to true in sourceCaches dictionary for the sources of these layers + for (const layerId of this._order) { + const layer = this._layers[layerId]; + layer.recalculate(parameters, this._availableImages); + if (!layer.isHidden(parameters.zoom) && layer.source) { + this.sourceCaches[layer.source].used = true; + } + } + // cross check sourcesUsedBefore against updated this.sourceCaches dictionary + // if "used" field is different fire visibility event + for (const sourcesUsedBeforeId in sourcesUsedBefore) { + const sourceCache = this.sourceCaches[sourcesUsedBeforeId]; + // (undefine !== false) will evaluate to true and fire an useless visibility event + // need force "falsy" values to boolean to avoid the case above + if (!!sourcesUsedBefore[sourcesUsedBeforeId] !== !!sourceCache.used) { + sourceCache.fire(new performance$1.k('data', { + sourceDataType: 'visibility', + dataType: 'source', + sourceId: sourcesUsedBeforeId + })); + } + } + this.light.recalculate(parameters); + this.sky.recalculate(parameters); + this.z = parameters.zoom; + if (changed) { + this.fire(new performance$1.k('data', { dataType: 'style' })); + } + } + /* + * Apply any queued image changes. + */ + _updateTilesForChangedImages() { + const changedImages = Object.keys(this._changedImages); + if (changedImages.length) { + for (const name in this.sourceCaches) { + this.sourceCaches[name].reloadTilesForDependencies(['icons', 'patterns'], changedImages); + } + this._changedImages = {}; + } + } + _updateTilesForChangedGlyphs() { + if (this._glyphsDidChange) { + for (const name in this.sourceCaches) { + this.sourceCaches[name].reloadTilesForDependencies(['glyphs'], ['']); + } + this._glyphsDidChange = false; + } + } + _updateWorkerLayers(updatedIds, removedIds) { + this.dispatcher.broadcast("UL" /* MessageType.updateLayers */, { + layers: this._serializeByIds(updatedIds, false), + removedIds + }); + } + _resetUpdates() { + this._changed = false; + this._updatedLayers = {}; + this._removedLayers = {}; + this._updatedSources = {}; + this._updatedPaintProps = {}; + this._changedImages = {}; + this._glyphsDidChange = false; + } + /** + * Update this style's state to match the given style JSON, performing only + * the necessary mutations. + * + * May throw an Error ('Unimplemented: METHOD') if the mapbox-gl-style-spec + * diff algorithm produces an operation that is not supported. + * + * @returns true if any changes were made; false otherwise + */ + setState(nextState, options = {}) { + var _a; + this._checkLoaded(); + const serializedStyle = this.serialize(); + nextState = options.transformStyle ? options.transformStyle(serializedStyle, nextState) : nextState; + const validate = (_a = options.validate) !== null && _a !== void 0 ? _a : true; + if (validate && emitValidationErrors(this, performance$1.u(nextState))) + return false; + nextState = performance$1.aB(nextState); + nextState.layers = performance$1.az(nextState.layers); + const changes = performance$1.aC(serializedStyle, nextState); + const operations = this._getOperationsToPerform(changes); + if (operations.unimplemented.length > 0) { + throw new Error(`Unimplemented: ${operations.unimplemented.join(', ')}.`); + } + if (operations.operations.length === 0) { + return false; + } + for (const styleChangeOperation of operations.operations) { + styleChangeOperation(); + } + this.stylesheet = nextState; + // reset serialization field, to be populated only when needed + this._serializedLayers = null; + return true; + } + _getOperationsToPerform(diff) { + const operations = []; + const unimplemented = []; + for (const op of diff) { + switch (op.command) { + case 'setCenter': + case 'setZoom': + case 'setBearing': + case 'setPitch': + continue; + case 'addLayer': + operations.push(() => this.addLayer.apply(this, op.args)); + break; + case 'removeLayer': + operations.push(() => this.removeLayer.apply(this, op.args)); + break; + case 'setPaintProperty': + operations.push(() => this.setPaintProperty.apply(this, op.args)); + break; + case 'setLayoutProperty': + operations.push(() => this.setLayoutProperty.apply(this, op.args)); + break; + case 'setFilter': + operations.push(() => this.setFilter.apply(this, op.args)); + break; + case 'addSource': + operations.push(() => this.addSource.apply(this, op.args)); + break; + case 'removeSource': + operations.push(() => this.removeSource.apply(this, op.args)); + break; + case 'setLayerZoomRange': + operations.push(() => this.setLayerZoomRange.apply(this, op.args)); + break; + case 'setLight': + operations.push(() => this.setLight.apply(this, op.args)); + break; + case 'setGeoJSONSourceData': + operations.push(() => this.setGeoJSONSourceData.apply(this, op.args)); + break; + case 'setGlyphs': + operations.push(() => this.setGlyphs.apply(this, op.args)); + break; + case 'setSprite': + operations.push(() => this.setSprite.apply(this, op.args)); + break; + case 'setSky': + operations.push(() => this.setSky.apply(this, op.args)); + break; + case 'setTerrain': + operations.push(() => this.map.setTerrain.apply(this, op.args)); + break; + case 'setTransition': + operations.push(() => { }); + break; + default: + unimplemented.push(op.command); + break; + } + } + return { + operations, + unimplemented + }; + } + addImage(id, image) { + if (this.getImage(id)) { + return this.fire(new performance$1.j(new Error(`An image named "${id}" already exists.`))); + } + this.imageManager.addImage(id, image); + this._afterImageUpdated(id); + } + updateImage(id, image) { + this.imageManager.updateImage(id, image); + } + getImage(id) { + return this.imageManager.getImage(id); + } + removeImage(id) { + if (!this.getImage(id)) { + return this.fire(new performance$1.j(new Error(`An image named "${id}" does not exist.`))); + } + this.imageManager.removeImage(id); + this._afterImageUpdated(id); + } + _afterImageUpdated(id) { + this._availableImages = this.imageManager.listImages(); + this._changedImages[id] = true; + this._changed = true; + this.dispatcher.broadcast("SI" /* MessageType.setImages */, this._availableImages); + this.fire(new performance$1.k('data', { dataType: 'style' })); + } + listImages() { + this._checkLoaded(); + return this.imageManager.listImages(); + } + addSource(id, source, options = {}) { + this._checkLoaded(); + if (this.sourceCaches[id] !== undefined) { + throw new Error(`Source "${id}" already exists.`); + } + if (!source.type) { + throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(source).join(', ')}.`); + } + const builtIns = ['vector', 'raster', 'geojson', 'video', 'image']; + const shouldValidate = builtIns.indexOf(source.type) >= 0; + if (shouldValidate && this._validate(performance$1.u.source, `sources.${id}`, source, null, options)) + return; + if (this.map && this.map._collectResourceTiming) + source.collectResourceTiming = true; + const sourceCache = this.sourceCaches[id] = new SourceCache(id, source, this.dispatcher); + sourceCache.style = this; + sourceCache.setEventedParent(this, () => ({ + isSourceLoaded: sourceCache.loaded(), + source: sourceCache.serialize(), + sourceId: id + })); + sourceCache.onAdd(this.map); + this._changed = true; + } + /** + * Remove a source from this stylesheet, given its id. + * @param id - id of the source to remove + * @throws if no source is found with the given ID + */ + removeSource(id) { + this._checkLoaded(); + if (this.sourceCaches[id] === undefined) { + throw new Error('There is no source with this ID'); + } + for (const layerId in this._layers) { + if (this._layers[layerId].source === id) { + return this.fire(new performance$1.j(new Error(`Source "${id}" cannot be removed while layer "${layerId}" is using it.`))); + } + } + const sourceCache = this.sourceCaches[id]; + delete this.sourceCaches[id]; + delete this._updatedSources[id]; + sourceCache.fire(new performance$1.k('data', { sourceDataType: 'metadata', dataType: 'source', sourceId: id })); + sourceCache.setEventedParent(null); + sourceCache.onRemove(this.map); + this._changed = true; + } + /** + * Set the data of a GeoJSON source, given its id. + * @param id - id of the source + * @param data - GeoJSON source + */ + setGeoJSONSourceData(id, data) { + this._checkLoaded(); + if (this.sourceCaches[id] === undefined) + throw new Error(`There is no source with this ID=${id}`); + const geojsonSource = this.sourceCaches[id].getSource(); + if (geojsonSource.type !== 'geojson') + throw new Error(`geojsonSource.type is ${geojsonSource.type}, which is !== 'geojson`); + geojsonSource.setData(data); + this._changed = true; + } + /** + * Get a source by ID. + * @param id - ID of the desired source + * @returns source + */ + getSource(id) { + return this.sourceCaches[id] && this.sourceCaches[id].getSource(); + } + /** + * Add a layer to the map style. The layer will be inserted before the layer with + * ID `before`, or appended if `before` is omitted. + * @param layerObject - The style layer to add. + * @param before - ID of an existing layer to insert before + * @param options - Style setter options. + */ + addLayer(layerObject, before, options = {}) { + this._checkLoaded(); + const id = layerObject.id; + if (this.getLayer(id)) { + this.fire(new performance$1.j(new Error(`Layer "${id}" already exists on this map.`))); + return; + } + let layer; + if (layerObject.type === 'custom') { + if (emitValidationErrors(this, performance$1.aD(layerObject))) + return; + layer = performance$1.aA(layerObject); + } + else { + if ('source' in layerObject && typeof layerObject.source === 'object') { + this.addSource(id, layerObject.source); + layerObject = performance$1.aB(layerObject); + layerObject = performance$1.e(layerObject, { source: id }); + } + // this layer is not in the style.layers array, so we pass an impossible array index + if (this._validate(performance$1.u.layer, `layers.${id}`, layerObject, { arrayIndex: -1 }, options)) + return; + layer = performance$1.aA(layerObject); + this._validateLayer(layer); + layer.setEventedParent(this, { layer: { id } }); + } + const index = before ? this._order.indexOf(before) : this._order.length; + if (before && index === -1) { + this.fire(new performance$1.j(new Error(`Cannot add layer "${id}" before non-existing layer "${before}".`))); + return; + } + this._order.splice(index, 0, id); + this._layerOrderChanged = true; + this._layers[id] = layer; + if (this._removedLayers[id] && layer.source && layer.type !== 'custom') { + // If, in the current batch, we have already removed this layer + // and we are now re-adding it with a different `type`, then we + // need to clear (rather than just reload) the underlying source's + // tiles. Otherwise, tiles marked 'reloading' will have buckets / + // buffers that are set up for the _previous_ version of this + // layer, causing, e.g.: + // https://github.com/mapbox/mapbox-gl-js/issues/3633 + const removed = this._removedLayers[id]; + delete this._removedLayers[id]; + if (removed.type !== layer.type) { + this._updatedSources[layer.source] = 'clear'; + } + else { + this._updatedSources[layer.source] = 'reload'; + this.sourceCaches[layer.source].pause(); + } + } + this._updateLayer(layer); + if (layer.onAdd) { + layer.onAdd(this.map); + } + } + /** + * Moves a layer to a different z-position. The layer will be inserted before the layer with + * ID `before`, or appended if `before` is omitted. + * @param id - ID of the layer to move + * @param before - ID of an existing layer to insert before + */ + moveLayer(id, before) { + this._checkLoaded(); + this._changed = true; + const layer = this._layers[id]; + if (!layer) { + this.fire(new performance$1.j(new Error(`The layer '${id}' does not exist in the map's style and cannot be moved.`))); + return; + } + if (id === before) { + return; + } + const index = this._order.indexOf(id); + this._order.splice(index, 1); + const newIndex = before ? this._order.indexOf(before) : this._order.length; + if (before && newIndex === -1) { + this.fire(new performance$1.j(new Error(`Cannot move layer "${id}" before non-existing layer "${before}".`))); + return; + } + this._order.splice(newIndex, 0, id); + this._layerOrderChanged = true; + } + /** + * Remove the layer with the given id from the style. + * A {@link ErrorEvent} event will be fired if no such layer exists. + * + * @param id - id of the layer to remove + */ + removeLayer(id) { + this._checkLoaded(); + const layer = this._layers[id]; + if (!layer) { + this.fire(new performance$1.j(new Error(`Cannot remove non-existing layer "${id}".`))); + return; + } + layer.setEventedParent(null); + const index = this._order.indexOf(id); + this._order.splice(index, 1); + this._layerOrderChanged = true; + this._changed = true; + this._removedLayers[id] = layer; + delete this._layers[id]; + if (this._serializedLayers) { + delete this._serializedLayers[id]; + } + delete this._updatedLayers[id]; + delete this._updatedPaintProps[id]; + if (layer.onRemove) { + layer.onRemove(this.map); + } + } + /** + * Return the style layer object with the given `id`. + * + * @param id - id of the desired layer + * @returns a layer, if one with the given `id` exists + */ + getLayer(id) { + return this._layers[id]; + } + /** + * Return the ids of all layers currently in the style, including custom layers, in order. + * + * @returns ids of layers, in order + */ + getLayersOrder() { + return [...this._order]; + } + /** + * Checks if a specific layer is present within the style. + * + * @param id - the id of the desired layer + * @returns a boolean specifying if the given layer is present + */ + hasLayer(id) { + return id in this._layers; + } + setLayerZoomRange(layerId, minzoom, maxzoom) { + this._checkLoaded(); + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new performance$1.j(new Error(`Cannot set the zoom range of non-existing layer "${layerId}".`))); + return; + } + if (layer.minzoom === minzoom && layer.maxzoom === maxzoom) + return; + if (minzoom != null) { + layer.minzoom = minzoom; + } + if (maxzoom != null) { + layer.maxzoom = maxzoom; + } + this._updateLayer(layer); + } + setFilter(layerId, filter, options = {}) { + this._checkLoaded(); + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new performance$1.j(new Error(`Cannot filter non-existing layer "${layerId}".`))); + return; + } + if (performance$1.aE(layer.filter, filter)) { + return; + } + if (filter === null || filter === undefined) { + layer.filter = undefined; + this._updateLayer(layer); + return; + } + if (this._validate(performance$1.u.filter, `layers.${layer.id}.filter`, filter, null, options)) { + return; + } + layer.filter = performance$1.aB(filter); + this._updateLayer(layer); + } + /** + * Get a layer's filter object + * @param layer - the layer to inspect + * @returns the layer's filter, if any + */ + getFilter(layer) { + return performance$1.aB(this.getLayer(layer).filter); + } + setLayoutProperty(layerId, name, value, options = {}) { + this._checkLoaded(); + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new performance$1.j(new Error(`Cannot style non-existing layer "${layerId}".`))); + return; + } + if (performance$1.aE(layer.getLayoutProperty(name), value)) + return; + layer.setLayoutProperty(name, value, options); + this._updateLayer(layer); + } + /** + * Get a layout property's value from a given layer + * @param layerId - the layer to inspect + * @param name - the name of the layout property + * @returns the property value + */ + getLayoutProperty(layerId, name) { + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new performance$1.j(new Error(`Cannot get style of non-existing layer "${layerId}".`))); + return; + } + return layer.getLayoutProperty(name); + } + setPaintProperty(layerId, name, value, options = {}) { + this._checkLoaded(); + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new performance$1.j(new Error(`Cannot style non-existing layer "${layerId}".`))); + return; + } + if (performance$1.aE(layer.getPaintProperty(name), value)) + return; + const requiresRelayout = layer.setPaintProperty(name, value, options); + if (requiresRelayout) { + this._updateLayer(layer); + } + this._changed = true; + this._updatedPaintProps[layerId] = true; + // reset serialization field, to be populated only when needed + this._serializedLayers = null; + } + getPaintProperty(layer, name) { + return this.getLayer(layer).getPaintProperty(name); + } + setFeatureState(target, state) { + this._checkLoaded(); + const sourceId = target.source; + const sourceLayer = target.sourceLayer; + const sourceCache = this.sourceCaches[sourceId]; + if (sourceCache === undefined) { + this.fire(new performance$1.j(new Error(`The source '${sourceId}' does not exist in the map's style.`))); + return; + } + const sourceType = sourceCache.getSource().type; + if (sourceType === 'geojson' && sourceLayer) { + this.fire(new performance$1.j(new Error('GeoJSON sources cannot have a sourceLayer parameter.'))); + return; + } + if (sourceType === 'vector' && !sourceLayer) { + this.fire(new performance$1.j(new Error('The sourceLayer parameter must be provided for vector source types.'))); + return; + } + if (target.id === undefined) { + this.fire(new performance$1.j(new Error('The feature id parameter must be provided.'))); + } + sourceCache.setFeatureState(sourceLayer, target.id, state); + } + removeFeatureState(target, key) { + this._checkLoaded(); + const sourceId = target.source; + const sourceCache = this.sourceCaches[sourceId]; + if (sourceCache === undefined) { + this.fire(new performance$1.j(new Error(`The source '${sourceId}' does not exist in the map's style.`))); + return; + } + const sourceType = sourceCache.getSource().type; + const sourceLayer = sourceType === 'vector' ? target.sourceLayer : undefined; + if (sourceType === 'vector' && !sourceLayer) { + this.fire(new performance$1.j(new Error('The sourceLayer parameter must be provided for vector source types.'))); + return; + } + if (key && (typeof target.id !== 'string' && typeof target.id !== 'number')) { + this.fire(new performance$1.j(new Error('A feature id is required to remove its specific state property.'))); + return; + } + sourceCache.removeFeatureState(sourceLayer, target.id, key); + } + getFeatureState(target) { + this._checkLoaded(); + const sourceId = target.source; + const sourceLayer = target.sourceLayer; + const sourceCache = this.sourceCaches[sourceId]; + if (sourceCache === undefined) { + this.fire(new performance$1.j(new Error(`The source '${sourceId}' does not exist in the map's style.`))); + return; + } + const sourceType = sourceCache.getSource().type; + if (sourceType === 'vector' && !sourceLayer) { + this.fire(new performance$1.j(new Error('The sourceLayer parameter must be provided for vector source types.'))); + return; + } + if (target.id === undefined) { + this.fire(new performance$1.j(new Error('The feature id parameter must be provided.'))); + } + return sourceCache.getFeatureState(sourceLayer, target.id); + } + getTransition() { + return performance$1.e({ duration: 300, delay: 0 }, this.stylesheet && this.stylesheet.transition); + } + serialize() { + // We return undefined before we're loaded, following the pattern of Map.getStyle() before + // the Style object is initialized. + // Internally, Style._validate() calls Style.serialize() but callers are responsible for + // calling Style._checkLoaded() first if their validation requires the style to be loaded. + if (!this._loaded) + return; + const sources = performance$1.aF(this.sourceCaches, (source) => source.serialize()); + const layers = this._serializeByIds(this._order, true); + const terrain = this.map.getTerrain() || undefined; + const myStyleSheet = this.stylesheet; + return performance$1.aG({ + version: myStyleSheet.version, + name: myStyleSheet.name, + metadata: myStyleSheet.metadata, + light: myStyleSheet.light, + sky: myStyleSheet.sky, + center: myStyleSheet.center, + zoom: myStyleSheet.zoom, + bearing: myStyleSheet.bearing, + pitch: myStyleSheet.pitch, + sprite: myStyleSheet.sprite, + glyphs: myStyleSheet.glyphs, + transition: myStyleSheet.transition, + sources, + layers, + terrain + }, (value) => { return value !== undefined; }); + } + _updateLayer(layer) { + this._updatedLayers[layer.id] = true; + if (layer.source && !this._updatedSources[layer.source] && + //Skip for raster layers (https://github.com/mapbox/mapbox-gl-js/issues/7865) + this.sourceCaches[layer.source].getSource().type !== 'raster') { + this._updatedSources[layer.source] = 'reload'; + this.sourceCaches[layer.source].pause(); + } + // upon updating, serialized layer dictionary should be reset. + // When needed, it will be populated with the correct copy again. + this._serializedLayers = null; + this._changed = true; + } + _flattenAndSortRenderedFeatures(sourceResults) { + // Feature order is complicated. + // The order between features in two 2D layers is always determined by layer order. + // The order between features in two 3D layers is always determined by depth. + // The order between a feature in a 2D layer and a 3D layer is tricky: + // Most often layer order determines the feature order in this case. If + // a line layer is above a extrusion layer the line feature will be rendered + // above the extrusion. If the line layer is below the extrusion layer, + // it will be rendered below it. + // + // There is a weird case though. + // You have layers in this order: extrusion_layer_a, line_layer, extrusion_layer_b + // Each layer has a feature that overlaps the other features. + // The feature in extrusion_layer_a is closer than the feature in extrusion_layer_b so it is rendered above. + // The feature in line_layer is rendered above extrusion_layer_a. + // This means that that the line_layer feature is above the extrusion_layer_b feature despite + // it being in an earlier layer. + const isLayer3D = layerId => this._layers[layerId].type === 'fill-extrusion'; + const layerIndex = {}; + const features3D = []; + for (let l = this._order.length - 1; l >= 0; l--) { + const layerId = this._order[l]; + if (isLayer3D(layerId)) { + layerIndex[layerId] = l; + for (const sourceResult of sourceResults) { + const layerFeatures = sourceResult[layerId]; + if (layerFeatures) { + for (const featureWrapper of layerFeatures) { + features3D.push(featureWrapper); + } + } + } + } + } + features3D.sort((a, b) => { + return b.intersectionZ - a.intersectionZ; + }); + const features = []; + for (let l = this._order.length - 1; l >= 0; l--) { + const layerId = this._order[l]; + if (isLayer3D(layerId)) { + // add all 3D features that are in or above the current layer + for (let i = features3D.length - 1; i >= 0; i--) { + const topmost3D = features3D[i].feature; + if (layerIndex[topmost3D.layer.id] < l) + break; + features.push(topmost3D); + features3D.pop(); + } + } + else { + for (const sourceResult of sourceResults) { + const layerFeatures = sourceResult[layerId]; + if (layerFeatures) { + for (const featureWrapper of layerFeatures) { + features.push(featureWrapper.feature); + } + } + } + } + } + return features; + } + queryRenderedFeatures(queryGeometry, params, transform) { + if (params && params.filter) { + this._validate(performance$1.u.filter, 'queryRenderedFeatures.filter', params.filter, null, params); + } + const includedSources = {}; + if (params && params.layers) { + if (!Array.isArray(params.layers)) { + this.fire(new performance$1.j(new Error('parameters.layers must be an Array.'))); + return []; + } + for (const layerId of params.layers) { + const layer = this._layers[layerId]; + if (!layer) { + // this layer is not in the style.layers array + this.fire(new performance$1.j(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be queried for features.`))); + return []; + } + includedSources[layer.source] = true; + } + } + const sourceResults = []; + params.availableImages = this._availableImages; + // LayerSpecification is serialized StyleLayer, and this casting is safe. + const serializedLayers = this._serializedAllLayers(); + for (const id in this.sourceCaches) { + if (params.layers && !includedSources[id]) + continue; + sourceResults.push(queryRenderedFeatures(this.sourceCaches[id], this._layers, serializedLayers, queryGeometry, params, transform)); + } + if (this.placement) { + // If a placement has run, query against its CollisionIndex + // for symbol results, and treat it as an extra source to merge + sourceResults.push(queryRenderedSymbols(this._layers, serializedLayers, this.sourceCaches, queryGeometry, params, this.placement.collisionIndex, this.placement.retainedQueryData)); + } + return this._flattenAndSortRenderedFeatures(sourceResults); + } + querySourceFeatures(sourceID, params) { + if (params && params.filter) { + this._validate(performance$1.u.filter, 'querySourceFeatures.filter', params.filter, null, params); + } + const sourceCache = this.sourceCaches[sourceID]; + return sourceCache ? querySourceFeatures(sourceCache, params) : []; + } + getLight() { + return this.light.getLight(); + } + setLight(lightOptions, options = {}) { + this._checkLoaded(); + const light = this.light.getLight(); + let _update = false; + for (const key in lightOptions) { + if (!performance$1.aE(lightOptions[key], light[key])) { + _update = true; + break; + } + } + if (!_update) + return; + const parameters = { + now: browser.now(), + transition: performance$1.e({ + duration: 300, + delay: 0 + }, this.stylesheet.transition) + }; + this.light.setLight(lightOptions, options); + this.light.updateTransitions(parameters); + } + getSky() { + var _a; + return (_a = this.stylesheet) === null || _a === void 0 ? void 0 : _a.sky; + } + setSky(skyOptions, options = {}) { + const sky = this.getSky(); + let update = false; + if (!skyOptions && !sky) + return; + if (skyOptions && !sky) { + update = true; + } + else if (!skyOptions && sky) { + update = true; + } + else { + for (const key in skyOptions) { + if (!performance$1.aE(skyOptions[key], sky[key])) { + update = true; + break; + } + } + } + if (!update) + return; + const parameters = { + now: browser.now(), + transition: performance$1.e({ + duration: 300, + delay: 0 + }, this.stylesheet.transition) + }; + this.stylesheet.sky = skyOptions; + this.sky.setSky(skyOptions, options); + this.sky.updateTransitions(parameters); + } + _validate(validate, key, value, props, options = {}) { + if (options && options.validate === false) { + return false; + } + return emitValidationErrors(this, validate.call(performance$1.u, performance$1.e({ + key, + style: this.serialize(), + value, + styleSpec: performance$1.v + }, props))); + } + _remove(mapRemoved = true) { + if (this._frameRequest) { + this._frameRequest.abort(); + this._frameRequest = null; + } + if (this._loadStyleRequest) { + this._loadStyleRequest.abort(); + this._loadStyleRequest = null; + } + if (this._spriteRequest) { + this._spriteRequest.abort(); + this._spriteRequest = null; + } + rtlMainThreadPluginFactory().off(RTLPluginLoadedEventName, this._rtlPluginLoaded); + for (const layerId in this._layers) { + const layer = this._layers[layerId]; + layer.setEventedParent(null); + } + for (const id in this.sourceCaches) { + const sourceCache = this.sourceCaches[id]; + sourceCache.setEventedParent(null); + sourceCache.onRemove(this.map); + } + this.imageManager.setEventedParent(null); + this.setEventedParent(null); + if (mapRemoved) { + this.dispatcher.broadcast("RM" /* MessageType.removeMap */, undefined); + } + this.dispatcher.remove(mapRemoved); + } + _clearSource(id) { + this.sourceCaches[id].clearTiles(); + } + _reloadSource(id) { + this.sourceCaches[id].resume(); + this.sourceCaches[id].reload(); + } + _updateSources(transform) { + for (const id in this.sourceCaches) { + this.sourceCaches[id].update(transform, this.map.terrain); + } + } + _generateCollisionBoxes() { + for (const id in this.sourceCaches) { + this._reloadSource(id); + } + } + _updatePlacement(transform, showCollisionBoxes, fadeDuration, crossSourceCollisions, forceFullPlacement = false) { + let symbolBucketsChanged = false; + let placementCommitted = false; + const layerTiles = {}; + for (const layerID of this._order) { + const styleLayer = this._layers[layerID]; + if (styleLayer.type !== 'symbol') + continue; + if (!layerTiles[styleLayer.source]) { + const sourceCache = this.sourceCaches[styleLayer.source]; + layerTiles[styleLayer.source] = sourceCache.getRenderableIds(true) + .map((id) => sourceCache.getTileByID(id)) + .sort((a, b) => (b.tileID.overscaledZ - a.tileID.overscaledZ) || (a.tileID.isLessThan(b.tileID) ? -1 : 1)); + } + const layerBucketsChanged = this.crossTileSymbolIndex.addLayer(styleLayer, layerTiles[styleLayer.source], transform.center.lng); + symbolBucketsChanged = symbolBucketsChanged || layerBucketsChanged; + } + this.crossTileSymbolIndex.pruneUnusedLayers(this._order); + // Anything that changes our "in progress" layer and tile indices requires us + // to start over. When we start over, we do a full placement instead of incremental + // to prevent starvation. + // We need to restart placement to keep layer indices in sync. + // Also force full placement when fadeDuration === 0 to ensure that newly loaded + // tiles will fully display symbols in their first frame + forceFullPlacement = forceFullPlacement || this._layerOrderChanged || fadeDuration === 0; + if (forceFullPlacement || !this.pauseablePlacement || (this.pauseablePlacement.isDone() && !this.placement.stillRecent(browser.now(), transform.zoom))) { + this.pauseablePlacement = new PauseablePlacement(transform, this.map.terrain, this._order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, this.placement); + this._layerOrderChanged = false; + } + if (this.pauseablePlacement.isDone()) { + // the last placement finished running, but the next one hasn’t + // started yet because of the `stillRecent` check immediately + // above, so mark it stale to ensure that we request another + // render frame + this.placement.setStale(); + } + else { + this.pauseablePlacement.continuePlacement(this._order, this._layers, layerTiles); + if (this.pauseablePlacement.isDone()) { + this.placement = this.pauseablePlacement.commit(browser.now()); + placementCommitted = true; + } + if (symbolBucketsChanged) { + // since the placement gets split over multiple frames it is possible + // these buckets were processed before they were changed and so the + // placement is already stale while it is in progress + this.pauseablePlacement.placement.setStale(); + } + } + if (placementCommitted || symbolBucketsChanged) { + for (const layerID of this._order) { + const styleLayer = this._layers[layerID]; + if (styleLayer.type !== 'symbol') + continue; + this.placement.updateLayerOpacities(styleLayer, layerTiles[styleLayer.source]); + } + } + // needsRender is false when we have just finished a placement that didn't change the visibility of any symbols + const needsRerender = !this.pauseablePlacement.isDone() || this.placement.hasTransitions(browser.now()); + return needsRerender; + } + _releaseSymbolFadeTiles() { + for (const id in this.sourceCaches) { + this.sourceCaches[id].releaseSymbolFadeTiles(); + } + } + // Callbacks from web workers + getImages(mapId, params) { + return performance$1._(this, void 0, void 0, function* () { + const images = yield this.imageManager.getImages(params.icons); + // Apply queued image changes before setting the tile's dependencies so that the tile + // is not reloaded unnecessarily. Without this forced update the reload could happen in cases + // like this one: + // - icons contains "my-image" + // - imageManager.getImages(...) triggers `onstyleimagemissing` + // - the user adds "my-image" within the callback + // - addImage adds "my-image" to this._changedImages + // - the next frame triggers a reload of this tile even though it already has the latest version + this._updateTilesForChangedImages(); + const sourceCache = this.sourceCaches[params.source]; + if (sourceCache) { + sourceCache.setDependencies(params.tileID.key, params.type, params.icons); + } + return images; + }); + } + getGlyphs(mapId, params) { + return performance$1._(this, void 0, void 0, function* () { + const glypgs = yield this.glyphManager.getGlyphs(params.stacks); + const sourceCache = this.sourceCaches[params.source]; + if (sourceCache) { + // we are not setting stacks as dependencies since for now + // we just need to know which tiles have glyph dependencies + sourceCache.setDependencies(params.tileID.key, params.type, ['']); + } + return glypgs; + }); + } + getGlyphsUrl() { + return this.stylesheet.glyphs || null; + } + setGlyphs(glyphsUrl, options = {}) { + this._checkLoaded(); + if (glyphsUrl && this._validate(performance$1.u.glyphs, 'glyphs', glyphsUrl, null, options)) { + return; + } + this._glyphsDidChange = true; + this.stylesheet.glyphs = glyphsUrl; + this.glyphManager.entries = {}; + this.glyphManager.setURL(glyphsUrl); + } + /** + * Add a sprite. + * + * @param id - The id of the desired sprite + * @param url - The url to load the desired sprite from + * @param options - The style setter options + * @param completion - The completion handler + */ + addSprite(id, url, options = {}, completion) { + this._checkLoaded(); + const spriteToAdd = [{ id, url }]; + const updatedSprite = [ + ...coerceSpriteToArray(this.stylesheet.sprite), + ...spriteToAdd + ]; + if (this._validate(performance$1.u.sprite, 'sprite', updatedSprite, null, options)) + return; + this.stylesheet.sprite = updatedSprite; + this._loadSprite(spriteToAdd, true, completion); + } + /** + * Remove a sprite by its id. When the last sprite is removed, the whole `this.stylesheet.sprite` object becomes + * `undefined`. This falsy `undefined` value later prevents attempts to load the sprite when it's absent. + * + * @param id - the id of the sprite to remove + */ + removeSprite(id) { + this._checkLoaded(); + const internalSpriteRepresentation = coerceSpriteToArray(this.stylesheet.sprite); + if (!internalSpriteRepresentation.find(sprite => sprite.id === id)) { + this.fire(new performance$1.j(new Error(`Sprite "${id}" doesn't exists on this map.`))); + return; + } + if (this._spritesImagesIds[id]) { + for (const imageId of this._spritesImagesIds[id]) { + this.imageManager.removeImage(imageId); + this._changedImages[imageId] = true; + } + } + internalSpriteRepresentation.splice(internalSpriteRepresentation.findIndex(sprite => sprite.id === id), 1); + this.stylesheet.sprite = internalSpriteRepresentation.length > 0 ? internalSpriteRepresentation : undefined; + delete this._spritesImagesIds[id]; + this._availableImages = this.imageManager.listImages(); + this._changed = true; + this.dispatcher.broadcast("SI" /* MessageType.setImages */, this._availableImages); + this.fire(new performance$1.k('data', { dataType: 'style' })); + } + /** + * Get the current sprite value. + * + * @returns empty array when no sprite is set; id-url pairs otherwise + */ + getSprite() { + return coerceSpriteToArray(this.stylesheet.sprite); + } + /** + * Set a new value for the style's sprite. + * + * @param sprite - new sprite value + * @param options - style setter options + * @param completion - the completion handler + */ + setSprite(sprite, options = {}, completion) { + this._checkLoaded(); + if (sprite && this._validate(performance$1.u.sprite, 'sprite', sprite, null, options)) { + return; + } + this.stylesheet.sprite = sprite; + if (sprite) { + this._loadSprite(sprite, true, completion); + } + else { + this._unloadSprite(); + if (completion) { + completion(null); + } + } + } +} + +var posAttributes = performance$1.Y([ + { name: 'a_pos', type: 'Int16', components: 2 } +]); + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var preludeFrag = '#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\n'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var preludeVert = '#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture2D(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture2D(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var backgroundFrag = 'uniform vec4 u_color;uniform float u_opacity;void main() {gl_FragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var backgroundVert = 'attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var backgroundPatternFrag = 'uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var backgroundPatternVert = 'uniform mat4 u_matrix;uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var circleFrag = 'varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);lowp float antialiasblur=v_data.z;float antialiased_blur=-max(blur,antialiasblur);float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));gl_FragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var circleVert = 'uniform mat4 u_matrix;uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);float ele=get_elevation(circle_center);v_visibility=calculate_visibility(u_matrix*vec4(circle_center,ele,1.0));if (u_pitch_with_map) {vec2 corner_position=circle_center;if (u_scale_with_map) {corner_position+=extrude*(radius+stroke_width)*u_extrude_scale;} else {vec4 projected_center=u_matrix*vec4(circle_center,0,1);corner_position+=extrude*(radius+stroke_width)*u_extrude_scale*(projected_center.w/u_camera_to_center_distance);}gl_Position=u_matrix*vec4(corner_position,ele,1);} else {gl_Position=u_matrix*vec4(circle_center,ele,1);if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var clippingMaskFrag = 'void main() {gl_FragColor=vec4(1.0);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var clippingMaskVert = 'attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var heatmapFrag = 'uniform highp float u_intensity;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);gl_FragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var heatmapVert = 'uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec4 pos=vec4(floor(a_pos*0.5)+extrude,get_elevation(floor(a_pos*0.5)),1);gl_Position=u_matrix*pos;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var heatmapTextureFrag = 'uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(0.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var heatmapTextureVert = 'uniform mat4 u_matrix;uniform vec2 u_world;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var collisionBoxFrag = 'varying float v_placed;varying float v_notUsed;void main() {float alpha=0.5;gl_FragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var collisionBoxVert = 'attribute vec2 a_anchor_pos;attribute vec2 a_placed;attribute vec2 a_box_real;uniform mat4 u_matrix;uniform vec2 u_pixel_extrude_scale;varying float v_placed;varying float v_notUsed;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var collisionCircleFrag = 'varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var collisionCircleVert = 'attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var debugFrag = 'uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var debugVert = 'attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,get_elevation(a_pos),1);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillFrag = '#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillVert = 'attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillOutlineFrag = 'varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillOutlineVert = 'attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillOutlinePatternFrag = 'uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillOutlinePatternVert = 'uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillPatternFrag = '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillPatternVert = 'uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillExtrusionFrag = 'varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillExtrusionVert = 'uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillExtrusionPatternFrag = 'uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var fillExtrusionPatternVert = 'uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var hillshadePrepareFrag = '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var hillshadePrepareVert = 'uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var hillshadeFrag = 'uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var hillshadeVert = 'uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineFrag = 'uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineVert = '\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineGradientFrag = 'uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,v_uv);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineGradientVert = '\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;attribute float a_uv_x;attribute float a_split_index;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var linePatternFrag = '#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var linePatternVert = '\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineSDFFrag = 'uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var lineSDFVert = '\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var rasterFrag = 'uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var rasterVert = 'uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolIconFrag = 'uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolIconVert = 'attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_tex;varying float v_fade_opacity;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolSDFFrag = '#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_2;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nfloat median(vec3 values) {return max(min(values.r,values.g),min(max(values.r,values.g),values.b));}float screenPxRange(float fontScale) {return fontScale*SDF_PX;}vec4 renderText(vec4 fill_color,vec4 halo_color,float opacity,float halo_width,float halo_blur,float EDGE_GAMMA,vec2 tex,float gamma_scale,float size,float fade_opacity) {float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}return color*(alpha*opacity*fade_opacity);}vec4 renderMSDFIcon(vec4 fill_color,vec4 halo_color,float opacity,float EDGE_GAMMA,vec2 tex,float gamma_scale,float size,float fade_opacity) {float fontScale=size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;vec3 s=texture2D(u_texture,tex).rgb;float sd=median(s);float dist=sd-0.5;if (u_is_halo) {color=halo_color;s=texture2D(u_texture_2,tex).rgb;sd=median(s);dist=sd-0.5;}float clampedDistance=clamp(dist*screenPxRange(fontScale)+0.5,0.0,1.0);highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,clampedDistance);return color*(alpha*opacity*fade_opacity);}void main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];gl_FragColor=u_is_text ? renderText(fill_color,halo_color,opacity,halo_width,halo_blur,EDGE_GAMMA,tex,gamma_scale,size,fade_opacity) : renderMSDFIcon(fill_color,halo_color,opacity,EDGE_GAMMA,tex,gamma_scale,size,fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolSDFVert = 'attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_data0;varying vec3 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolTextAndIconFrag = '#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var symbolTextAndIconVert = 'attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec4 v_data0;varying vec4 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainDepthFrag = 'varying float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {gl_FragColor=pack(v_depth);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainCoordsFrag = 'precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;varying vec2 v_texture_pos;void main() {vec4 rgba=texture2D(u_texture,v_texture_pos);gl_FragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainFrag = 'uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;varying vec2 v_texture_pos;varying float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture2D(u_texture,v_texture_pos);if (v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);gl_FragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {gl_FragColor=surface_color;}}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainDepthVert = 'attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);v_depth=gl_Position.z/gl_Position.w;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainCoordsVert = 'attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var terrainVert = 'attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform mat4 u_fog_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;varying float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var skyFrag = 'uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform float u_horizon;uniform float u_sky_horizon_blend;void main() {float y=gl_FragCoord.y;if (y > u_horizon) {float blend=y-u_horizon;if (blend < u_sky_horizon_blend) {gl_FragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {gl_FragColor=u_sky_color;}}}'; + +// This file is generated. Edit build/generate-shaders.ts, then run `npm run codegen`. +var skyVert = 'attribute vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}'; + +// Disable Flow annotations here because Flow doesn't support importing GLSL files +const shaders = { + prelude: compile(preludeFrag, preludeVert), + background: compile(backgroundFrag, backgroundVert), + backgroundPattern: compile(backgroundPatternFrag, backgroundPatternVert), + circle: compile(circleFrag, circleVert), + clippingMask: compile(clippingMaskFrag, clippingMaskVert), + heatmap: compile(heatmapFrag, heatmapVert), + heatmapTexture: compile(heatmapTextureFrag, heatmapTextureVert), + collisionBox: compile(collisionBoxFrag, collisionBoxVert), + collisionCircle: compile(collisionCircleFrag, collisionCircleVert), + debug: compile(debugFrag, debugVert), + fill: compile(fillFrag, fillVert), + fillOutline: compile(fillOutlineFrag, fillOutlineVert), + fillOutlinePattern: compile(fillOutlinePatternFrag, fillOutlinePatternVert), + fillPattern: compile(fillPatternFrag, fillPatternVert), + fillExtrusion: compile(fillExtrusionFrag, fillExtrusionVert), + fillExtrusionPattern: compile(fillExtrusionPatternFrag, fillExtrusionPatternVert), + hillshadePrepare: compile(hillshadePrepareFrag, hillshadePrepareVert), + hillshade: compile(hillshadeFrag, hillshadeVert), + line: compile(lineFrag, lineVert), + lineGradient: compile(lineGradientFrag, lineGradientVert), + linePattern: compile(linePatternFrag, linePatternVert), + lineSDF: compile(lineSDFFrag, lineSDFVert), + raster: compile(rasterFrag, rasterVert), + symbolIcon: compile(symbolIconFrag, symbolIconVert), + symbolSDF: compile(symbolSDFFrag, symbolSDFVert), + symbolTextAndIcon: compile(symbolTextAndIconFrag, symbolTextAndIconVert), + terrain: compile(terrainFrag, terrainVert), + terrainDepth: compile(terrainDepthFrag, terrainDepthVert), + terrainCoords: compile(terrainCoordsFrag, terrainCoordsVert), + sky: compile(skyFrag, skyVert) +}; +// Expand #pragmas to #ifdefs. +function compile(fragmentSource, vertexSource) { + const re = /#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g; + const staticAttributes = vertexSource.match(/attribute ([\w]+) ([\w]+)/g); + const fragmentUniforms = fragmentSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g); + const vertexUniforms = vertexSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g); + const staticUniforms = vertexUniforms ? vertexUniforms.concat(fragmentUniforms) : fragmentUniforms; + const fragmentPragmas = {}; + fragmentSource = fragmentSource.replace(re, (match, operation, precision, type, name) => { + fragmentPragmas[name] = true; + if (operation === 'define') { + return ` +#ifndef HAS_UNIFORM_u_${name} +varying ${precision} ${type} ${name}; +#else +uniform ${precision} ${type} u_${name}; +#endif +`; + } + else /* if (operation === 'initialize') */ { + return ` +#ifdef HAS_UNIFORM_u_${name} + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + }); + vertexSource = vertexSource.replace(re, (match, operation, precision, type, name) => { + const attrType = type === 'float' ? 'vec2' : 'vec4'; + const unpackType = name.match(/color/) ? 'color' : attrType; + if (fragmentPragmas[name]) { + if (operation === 'define') { + return ` +#ifndef HAS_UNIFORM_u_${name} +uniform lowp float u_${name}_t; +attribute ${precision} ${attrType} a_${name}; +varying ${precision} ${type} ${name}; +#else +uniform ${precision} ${type} u_${name}; +#endif +`; + } + else /* if (operation === 'initialize') */ { + if (unpackType === 'vec4') { + // vec4 attributes are only used for cross-faded properties, and are not packed + return ` +#ifndef HAS_UNIFORM_u_${name} + ${name} = a_${name}; +#else + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + else { + return ` +#ifndef HAS_UNIFORM_u_${name} + ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t); +#else + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + } + } + else { + if (operation === 'define') { + return ` +#ifndef HAS_UNIFORM_u_${name} +uniform lowp float u_${name}_t; +attribute ${precision} ${attrType} a_${name}; +#else +uniform ${precision} ${type} u_${name}; +#endif +`; + } + else /* if (operation === 'initialize') */ { + if (unpackType === 'vec4') { + // vec4 attributes are only used for cross-faded properties, and are not packed + return ` +#ifndef HAS_UNIFORM_u_${name} + ${precision} ${type} ${name} = a_${name}; +#else + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + else /* */ { + return ` +#ifndef HAS_UNIFORM_u_${name} + ${precision} ${type} ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t); +#else + ${precision} ${type} ${name} = u_${name}; +#endif +`; + } + } + } + }); + return { fragmentSource, vertexSource, staticAttributes, staticUniforms }; +} + +/** + * @internal + * A vertex array object used to pass data to the webgl code + */ +class VertexArrayObject { + constructor() { + this.boundProgram = null; + this.boundLayoutVertexBuffer = null; + this.boundPaintVertexBuffers = []; + this.boundIndexBuffer = null; + this.boundVertexOffset = null; + this.boundDynamicVertexBuffer = null; + this.vao = null; + } + bind(context, program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3) { + this.context = context; + let paintBuffersDiffer = this.boundPaintVertexBuffers.length !== paintVertexBuffers.length; + for (let i = 0; !paintBuffersDiffer && i < paintVertexBuffers.length; i++) { + if (this.boundPaintVertexBuffers[i] !== paintVertexBuffers[i]) { + paintBuffersDiffer = true; + } + } + const isFreshBindRequired = (!this.vao || + this.boundProgram !== program || + this.boundLayoutVertexBuffer !== layoutVertexBuffer || + paintBuffersDiffer || + this.boundIndexBuffer !== indexBuffer || + this.boundVertexOffset !== vertexOffset || + this.boundDynamicVertexBuffer !== dynamicVertexBuffer || + this.boundDynamicVertexBuffer2 !== dynamicVertexBuffer2 || + this.boundDynamicVertexBuffer3 !== dynamicVertexBuffer3); + if (isFreshBindRequired) { + this.freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3); + } + else { + context.bindVertexArray.set(this.vao); + if (dynamicVertexBuffer) { + // The buffer may have been updated. Rebind to upload data. + dynamicVertexBuffer.bind(); + } + if (indexBuffer && indexBuffer.dynamicDraw) { + indexBuffer.bind(); + } + if (dynamicVertexBuffer2) { + dynamicVertexBuffer2.bind(); + } + if (dynamicVertexBuffer3) { + dynamicVertexBuffer3.bind(); + } + } + } + freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3) { + const numNextAttributes = program.numAttributes; + const context = this.context; + const gl = context.gl; + if (this.vao) + this.destroy(); + this.vao = context.createVertexArray(); + context.bindVertexArray.set(this.vao); + // store the arguments so that we can verify them when the vao is bound again + this.boundProgram = program; + this.boundLayoutVertexBuffer = layoutVertexBuffer; + this.boundPaintVertexBuffers = paintVertexBuffers; + this.boundIndexBuffer = indexBuffer; + this.boundVertexOffset = vertexOffset; + this.boundDynamicVertexBuffer = dynamicVertexBuffer; + this.boundDynamicVertexBuffer2 = dynamicVertexBuffer2; + this.boundDynamicVertexBuffer3 = dynamicVertexBuffer3; + layoutVertexBuffer.enableAttributes(gl, program); + for (const vertexBuffer of paintVertexBuffers) { + vertexBuffer.enableAttributes(gl, program); + } + if (dynamicVertexBuffer) { + dynamicVertexBuffer.enableAttributes(gl, program); + } + if (dynamicVertexBuffer2) { + dynamicVertexBuffer2.enableAttributes(gl, program); + } + if (dynamicVertexBuffer3) { + dynamicVertexBuffer3.enableAttributes(gl, program); + } + layoutVertexBuffer.bind(); + layoutVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset); + for (const vertexBuffer of paintVertexBuffers) { + vertexBuffer.bind(); + vertexBuffer.setVertexAttribPointers(gl, program, vertexOffset); + } + if (dynamicVertexBuffer) { + dynamicVertexBuffer.bind(); + dynamicVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset); + } + if (indexBuffer) { + indexBuffer.bind(); + } + if (dynamicVertexBuffer2) { + dynamicVertexBuffer2.bind(); + dynamicVertexBuffer2.setVertexAttribPointers(gl, program, vertexOffset); + } + if (dynamicVertexBuffer3) { + dynamicVertexBuffer3.bind(); + dynamicVertexBuffer3.setVertexAttribPointers(gl, program, vertexOffset); + } + context.currentNumAttributes = numNextAttributes; + } + destroy() { + if (this.vao) { + this.context.deleteVertexArray(this.vao); + this.vao = null; + } + } +} + +const terrainPreludeUniforms = (context, locations) => ({ + 'u_depth': new performance$1.aH(context, locations.u_depth), + 'u_terrain': new performance$1.aH(context, locations.u_terrain), + 'u_terrain_dim': new performance$1.aI(context, locations.u_terrain_dim), + 'u_terrain_matrix': new performance$1.aJ(context, locations.u_terrain_matrix), + 'u_terrain_unpack': new performance$1.aK(context, locations.u_terrain_unpack), + 'u_terrain_exaggeration': new performance$1.aI(context, locations.u_terrain_exaggeration) +}); +const terrainUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_texture': new performance$1.aH(context, locations.u_texture), + 'u_ele_delta': new performance$1.aI(context, locations.u_ele_delta), + 'u_fog_matrix': new performance$1.aJ(context, locations.u_fog_matrix), + 'u_fog_color': new performance$1.aL(context, locations.u_fog_color), + 'u_fog_ground_blend': new performance$1.aI(context, locations.u_fog_ground_blend), + 'u_fog_ground_blend_opacity': new performance$1.aI(context, locations.u_fog_ground_blend_opacity), + 'u_horizon_color': new performance$1.aL(context, locations.u_horizon_color), + 'u_horizon_fog_blend': new performance$1.aI(context, locations.u_horizon_fog_blend) +}); +const terrainDepthUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_ele_delta': new performance$1.aI(context, locations.u_ele_delta) +}); +const terrainCoordsUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_texture': new performance$1.aH(context, locations.u_texture), + 'u_terrain_coords_id': new performance$1.aI(context, locations.u_terrain_coords_id), + 'u_ele_delta': new performance$1.aI(context, locations.u_ele_delta) +}); +const terrainUniformValues = (matrix, eleDelta, fogMatrix, sky, pitch) => ({ + 'u_matrix': matrix, + 'u_texture': 0, + 'u_ele_delta': eleDelta, + 'u_fog_matrix': fogMatrix, + 'u_fog_color': sky ? sky.properties.get('fog-color') : performance$1.aM.white, + 'u_fog_ground_blend': sky ? sky.properties.get('fog-ground-blend') : 1, + 'u_fog_ground_blend_opacity': sky ? sky.calculateFogBlendOpacity(pitch) : 0, + 'u_horizon_color': sky ? sky.properties.get('horizon-color') : performance$1.aM.white, + 'u_horizon_fog_blend': sky ? sky.properties.get('horizon-fog-blend') : 1 +}); +const terrainDepthUniformValues = (matrix, eleDelta) => ({ + 'u_matrix': matrix, + 'u_ele_delta': eleDelta +}); +const terrainCoordsUniformValues = (matrix, coordsId, eleDelta) => ({ + 'u_matrix': matrix, + 'u_terrain_coords_id': coordsId / 255, + 'u_texture': 0, + 'u_ele_delta': eleDelta +}); + +function getTokenizedAttributesAndUniforms(array) { + const result = []; + for (let i = 0; i < array.length; i++) { + if (array[i] === null) + continue; + const token = array[i].split(' '); + result.push(token.pop()); + } + return result; +} +/** + * @internal + * A webgl program to execute in the GPU space + */ +class Program { + constructor(context, source, configuration, fixedUniforms, showOverdrawInspector, terrain) { + const gl = context.gl; + this.program = gl.createProgram(); + const staticAttrInfo = getTokenizedAttributesAndUniforms(source.staticAttributes); + const dynamicAttrInfo = configuration ? configuration.getBinderAttributes() : []; + const allAttrInfo = staticAttrInfo.concat(dynamicAttrInfo); + const preludeUniformsInfo = shaders.prelude.staticUniforms ? getTokenizedAttributesAndUniforms(shaders.prelude.staticUniforms) : []; + const staticUniformsInfo = source.staticUniforms ? getTokenizedAttributesAndUniforms(source.staticUniforms) : []; + const dynamicUniformsInfo = configuration ? configuration.getBinderUniforms() : []; + // remove duplicate uniforms + const uniformList = preludeUniformsInfo.concat(staticUniformsInfo).concat(dynamicUniformsInfo); + const allUniformsInfo = []; + for (const uniform of uniformList) { + if (allUniformsInfo.indexOf(uniform) < 0) + allUniformsInfo.push(uniform); + } + const defines = configuration ? configuration.defines() : []; + if (showOverdrawInspector) { + defines.push('#define OVERDRAW_INSPECTOR;'); + } + if (terrain) { + defines.push('#define TERRAIN3D;'); + } + const fragmentSource = defines.concat(shaders.prelude.fragmentSource, source.fragmentSource).join('\n'); + const vertexSource = defines.concat(shaders.prelude.vertexSource, source.vertexSource).join('\n'); + const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); + if (gl.isContextLost()) { + this.failedToCreate = true; + return; + } + gl.shaderSource(fragmentShader, fragmentSource); + gl.compileShader(fragmentShader); + if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) { + console.log(gl.getShaderInfoLog(fragmentShader)); + throw new Error(`Could not compile fragment shader:`); + } + gl.attachShader(this.program, fragmentShader); + const vertexShader = gl.createShader(gl.VERTEX_SHADER); + if (gl.isContextLost()) { + this.failedToCreate = true; + return; + } + gl.shaderSource(vertexShader, vertexSource); + gl.compileShader(vertexShader); + if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) { + throw new Error(`Could not compile vertex shader: ${gl.getShaderInfoLog(vertexShader)}`); + } + gl.attachShader(this.program, vertexShader); + this.attributes = {}; + const uniformLocations = {}; + this.numAttributes = allAttrInfo.length; + for (let i = 0; i < this.numAttributes; i++) { + if (allAttrInfo[i]) { + gl.bindAttribLocation(this.program, i, allAttrInfo[i]); + this.attributes[allAttrInfo[i]] = i; + } + } + gl.linkProgram(this.program); + if (!gl.getProgramParameter(this.program, gl.LINK_STATUS)) { + console.log(gl.getProgramInfoLog(this.program)); + throw new Error(`Program failed to link:`); + } + gl.deleteShader(vertexShader); + gl.deleteShader(fragmentShader); + for (let it = 0; it < allUniformsInfo.length; it++) { + const uniform = allUniformsInfo[it]; + if (uniform && !uniformLocations[uniform]) { + const uniformLocation = gl.getUniformLocation(this.program, uniform); + if (uniformLocation) { + uniformLocations[uniform] = uniformLocation; + } + } + } + this.fixedUniforms = fixedUniforms(context, uniformLocations); + this.terrainUniforms = terrainPreludeUniforms(context, uniformLocations); + this.binderUniforms = configuration ? configuration.getUniforms(context, uniformLocations) : []; + } + draw(context, drawMode, depthMode, stencilMode, colorMode, cullFaceMode, uniformValues, terrain, layerID, layoutVertexBuffer, indexBuffer, segments, currentProperties, zoom, configuration, dynamicLayoutBuffer, dynamicLayoutBuffer2, dynamicLayoutBuffer3) { + const gl = context.gl; + if (this.failedToCreate) + return; + context.program.set(this.program); + context.setDepthMode(depthMode); + context.setStencilMode(stencilMode); + context.setColorMode(colorMode); + context.setCullFace(cullFaceMode); + // set variables used by the 3d functions defined in _prelude.vertex.glsl + if (terrain) { + context.activeTexture.set(gl.TEXTURE2); + gl.bindTexture(gl.TEXTURE_2D, terrain.depthTexture); + context.activeTexture.set(gl.TEXTURE3); + gl.bindTexture(gl.TEXTURE_2D, terrain.texture); + for (const name in this.terrainUniforms) { + this.terrainUniforms[name].set(terrain[name]); + } + } + for (const name in this.fixedUniforms) { + this.fixedUniforms[name].set(uniformValues[name]); + } + if (configuration) { + configuration.setUniforms(context, this.binderUniforms, currentProperties, { zoom: zoom }); + } + let primitiveSize = 0; + switch (drawMode) { + case gl.LINES: + primitiveSize = 2; + break; + case gl.TRIANGLES: + primitiveSize = 3; + break; + case gl.LINE_STRIP: + primitiveSize = 1; + break; + } + for (const segment of segments.get()) { + const vaos = segment.vaos || (segment.vaos = {}); + const vao = vaos[layerID] || (vaos[layerID] = new VertexArrayObject()); + vao.bind(context, this, layoutVertexBuffer, configuration ? configuration.getPaintVertexBuffers() : [], indexBuffer, segment.vertexOffset, dynamicLayoutBuffer, dynamicLayoutBuffer2, dynamicLayoutBuffer3); + gl.drawElements(drawMode, segment.primitiveLength * primitiveSize, gl.UNSIGNED_SHORT, segment.primitiveOffset * primitiveSize * 2); + } + } +} + +function patternUniformValues(crossfade, painter, tile) { + const tileRatio = 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom); + const numTiles = Math.pow(2, tile.tileID.overscaledZ); + const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles; + const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles); + const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y; + return { + 'u_image': 0, + 'u_texsize': tile.imageAtlasTexture.size, + 'u_scale': [tileRatio, crossfade.fromScale, crossfade.toScale], + 'u_fade': crossfade.t, + // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision. + 'u_pixel_coord_upper': [pixelX >> 16, pixelY >> 16], + 'u_pixel_coord_lower': [pixelX & 0xFFFF, pixelY & 0xFFFF] + }; +} +function bgPatternUniformValues(image, crossfade, painter, tile) { + const imagePosA = painter.imageManager.getPattern(image.from.toString()); + const imagePosB = painter.imageManager.getPattern(image.to.toString()); + const { width, height } = painter.imageManager.getPixelSize(); + const numTiles = Math.pow(2, tile.tileID.overscaledZ); + const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles; + const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles); + const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y; + return { + 'u_image': 0, + 'u_pattern_tl_a': imagePosA.tl, + 'u_pattern_br_a': imagePosA.br, + 'u_pattern_tl_b': imagePosB.tl, + 'u_pattern_br_b': imagePosB.br, + 'u_texsize': [width, height], + 'u_mix': crossfade.t, + 'u_pattern_size_a': imagePosA.displaySize, + 'u_pattern_size_b': imagePosB.displaySize, + 'u_scale_a': crossfade.fromScale, + 'u_scale_b': crossfade.toScale, + 'u_tile_units_to_pixels': 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom), + // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision. + 'u_pixel_coord_upper': [pixelX >> 16, pixelY >> 16], + 'u_pixel_coord_lower': [pixelX & 0xFFFF, pixelY & 0xFFFF] + }; +} + +const fillExtrusionUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_lightpos': new performance$1.aN(context, locations.u_lightpos), + 'u_lightintensity': new performance$1.aI(context, locations.u_lightintensity), + 'u_lightcolor': new performance$1.aN(context, locations.u_lightcolor), + 'u_vertical_gradient': new performance$1.aI(context, locations.u_vertical_gradient), + 'u_opacity': new performance$1.aI(context, locations.u_opacity) +}); +const fillExtrusionPatternUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_lightpos': new performance$1.aN(context, locations.u_lightpos), + 'u_lightintensity': new performance$1.aI(context, locations.u_lightintensity), + 'u_lightcolor': new performance$1.aN(context, locations.u_lightcolor), + 'u_vertical_gradient': new performance$1.aI(context, locations.u_vertical_gradient), + 'u_height_factor': new performance$1.aI(context, locations.u_height_factor), + // pattern uniforms + 'u_image': new performance$1.aH(context, locations.u_image), + 'u_texsize': new performance$1.aO(context, locations.u_texsize), + 'u_pixel_coord_upper': new performance$1.aO(context, locations.u_pixel_coord_upper), + 'u_pixel_coord_lower': new performance$1.aO(context, locations.u_pixel_coord_lower), + 'u_scale': new performance$1.aN(context, locations.u_scale), + 'u_fade': new performance$1.aI(context, locations.u_fade), + 'u_opacity': new performance$1.aI(context, locations.u_opacity) +}); +const fillExtrusionUniformValues = (matrix, painter, shouldUseVerticalGradient, opacity) => { + const light = painter.style.light; + const _lp = light.properties.get('position'); + const lightPos = [_lp.x, _lp.y, _lp.z]; + const lightMat = create$3(); + if (light.properties.get('anchor') === 'viewport') { + fromRotation(lightMat, -painter.transform.angle); + } + transformMat3(lightPos, lightPos, lightMat); + const lightColor = light.properties.get('color'); + return { + 'u_matrix': matrix, + 'u_lightpos': lightPos, + 'u_lightintensity': light.properties.get('intensity'), + 'u_lightcolor': [lightColor.r, lightColor.g, lightColor.b], + 'u_vertical_gradient': +shouldUseVerticalGradient, + 'u_opacity': opacity + }; +}; +const fillExtrusionPatternUniformValues = (matrix, painter, shouldUseVerticalGradient, opacity, coord, crossfade, tile) => { + return performance$1.e(fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity), patternUniformValues(crossfade, painter, tile), { + 'u_height_factor': -Math.pow(2, coord.overscaledZ) / tile.tileSize / 8 + }); +}; + +const fillUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix) +}); +const fillPatternUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_image': new performance$1.aH(context, locations.u_image), + 'u_texsize': new performance$1.aO(context, locations.u_texsize), + 'u_pixel_coord_upper': new performance$1.aO(context, locations.u_pixel_coord_upper), + 'u_pixel_coord_lower': new performance$1.aO(context, locations.u_pixel_coord_lower), + 'u_scale': new performance$1.aN(context, locations.u_scale), + 'u_fade': new performance$1.aI(context, locations.u_fade) +}); +const fillOutlineUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_world': new performance$1.aO(context, locations.u_world) +}); +const fillOutlinePatternUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_world': new performance$1.aO(context, locations.u_world), + 'u_image': new performance$1.aH(context, locations.u_image), + 'u_texsize': new performance$1.aO(context, locations.u_texsize), + 'u_pixel_coord_upper': new performance$1.aO(context, locations.u_pixel_coord_upper), + 'u_pixel_coord_lower': new performance$1.aO(context, locations.u_pixel_coord_lower), + 'u_scale': new performance$1.aN(context, locations.u_scale), + 'u_fade': new performance$1.aI(context, locations.u_fade) +}); +const fillUniformValues = (matrix) => ({ + 'u_matrix': matrix +}); +const fillPatternUniformValues = (matrix, painter, crossfade, tile) => performance$1.e(fillUniformValues(matrix), patternUniformValues(crossfade, painter, tile)); +const fillOutlineUniformValues = (matrix, drawingBufferSize) => ({ + 'u_matrix': matrix, + 'u_world': drawingBufferSize +}); +const fillOutlinePatternUniformValues = (matrix, painter, crossfade, tile, drawingBufferSize) => performance$1.e(fillPatternUniformValues(matrix, painter, crossfade, tile), { + 'u_world': drawingBufferSize +}); + +const circleUniforms = (context, locations) => ({ + 'u_camera_to_center_distance': new performance$1.aI(context, locations.u_camera_to_center_distance), + 'u_scale_with_map': new performance$1.aH(context, locations.u_scale_with_map), + 'u_pitch_with_map': new performance$1.aH(context, locations.u_pitch_with_map), + 'u_extrude_scale': new performance$1.aO(context, locations.u_extrude_scale), + 'u_device_pixel_ratio': new performance$1.aI(context, locations.u_device_pixel_ratio), + 'u_matrix': new performance$1.aJ(context, locations.u_matrix) +}); +const circleUniformValues = (painter, coord, tile, layer) => { + const transform = painter.transform; + let pitchWithMap, extrudeScale; + if (layer.paint.get('circle-pitch-alignment') === 'map') { + const pixelRatio = pixelsToTileUnits(tile, 1, transform.zoom); + pitchWithMap = true; + extrudeScale = [pixelRatio, pixelRatio]; + } + else { + pitchWithMap = false; + extrudeScale = transform.pixelsToGLUnits; + } + return { + 'u_camera_to_center_distance': transform.cameraToCenterDistance, + 'u_scale_with_map': +(layer.paint.get('circle-pitch-scale') === 'map'), + 'u_matrix': painter.translatePosMatrix(coord.posMatrix, tile, layer.paint.get('circle-translate'), layer.paint.get('circle-translate-anchor')), + 'u_pitch_with_map': +(pitchWithMap), + 'u_device_pixel_ratio': painter.pixelRatio, + 'u_extrude_scale': extrudeScale + }; +}; + +const collisionUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_pixel_extrude_scale': new performance$1.aO(context, locations.u_pixel_extrude_scale) +}); +const collisionCircleUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_inv_matrix': new performance$1.aJ(context, locations.u_inv_matrix), + 'u_camera_to_center_distance': new performance$1.aI(context, locations.u_camera_to_center_distance), + 'u_viewport_size': new performance$1.aO(context, locations.u_viewport_size) +}); +const collisionUniformValues = (transform, matrix) => { + return { + 'u_matrix': matrix, + 'u_pixel_extrude_scale': [1.0 / transform.width, 1.0 / transform.height], + }; +}; +const collisionCircleUniformValues = (matrix, invMatrix, transform) => { + return { + 'u_matrix': matrix, + 'u_inv_matrix': invMatrix, + 'u_camera_to_center_distance': transform.cameraToCenterDistance, + 'u_viewport_size': [transform.width, transform.height] + }; +}; + +const debugUniforms = (context, locations) => ({ + 'u_color': new performance$1.aL(context, locations.u_color), + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_overlay': new performance$1.aH(context, locations.u_overlay), + 'u_overlay_scale': new performance$1.aI(context, locations.u_overlay_scale) +}); +const debugUniformValues = (matrix, color, scaleRatio = 1) => ({ + 'u_matrix': matrix, + 'u_color': color, + 'u_overlay': 0, + 'u_overlay_scale': scaleRatio +}); + +const clippingMaskUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix) +}); +const clippingMaskUniformValues = (matrix) => ({ + 'u_matrix': matrix +}); + +const heatmapUniforms = (context, locations) => ({ + 'u_extrude_scale': new performance$1.aI(context, locations.u_extrude_scale), + 'u_intensity': new performance$1.aI(context, locations.u_intensity), + 'u_matrix': new performance$1.aJ(context, locations.u_matrix) +}); +const heatmapTextureUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_world': new performance$1.aO(context, locations.u_world), + 'u_image': new performance$1.aH(context, locations.u_image), + 'u_color_ramp': new performance$1.aH(context, locations.u_color_ramp), + 'u_opacity': new performance$1.aI(context, locations.u_opacity) +}); +const heatmapUniformValues = (matrix, tile, zoom, intensity) => ({ + 'u_matrix': matrix, + 'u_extrude_scale': pixelsToTileUnits(tile, 1, zoom), + 'u_intensity': intensity +}); +const heatmapTextureUniformValues = (painter, layer, textureUnit, colorRampUnit) => { + const matrix = performance$1.H(); + performance$1.aP(matrix, 0, painter.width, painter.height, 0, 0, 1); + const gl = painter.context.gl; + return { + 'u_matrix': matrix, + 'u_world': [gl.drawingBufferWidth, gl.drawingBufferHeight], + 'u_image': textureUnit, + 'u_color_ramp': colorRampUnit, + 'u_opacity': layer.paint.get('heatmap-opacity') + }; +}; + +const hillshadeUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_image': new performance$1.aH(context, locations.u_image), + 'u_latrange': new performance$1.aO(context, locations.u_latrange), + 'u_light': new performance$1.aO(context, locations.u_light), + 'u_shadow': new performance$1.aL(context, locations.u_shadow), + 'u_highlight': new performance$1.aL(context, locations.u_highlight), + 'u_accent': new performance$1.aL(context, locations.u_accent) +}); +const hillshadePrepareUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_image': new performance$1.aH(context, locations.u_image), + 'u_dimension': new performance$1.aO(context, locations.u_dimension), + 'u_zoom': new performance$1.aI(context, locations.u_zoom), + 'u_unpack': new performance$1.aK(context, locations.u_unpack) +}); +const hillshadeUniformValues = (painter, tile, layer, coord) => { + const shadow = layer.paint.get('hillshade-shadow-color'); + const highlight = layer.paint.get('hillshade-highlight-color'); + const accent = layer.paint.get('hillshade-accent-color'); + let azimuthal = layer.paint.get('hillshade-illumination-direction') * (Math.PI / 180); + // modify azimuthal angle by map rotation if light is anchored at the viewport + if (layer.paint.get('hillshade-illumination-anchor') === 'viewport') { + azimuthal -= painter.transform.angle; + } + const align = !painter.options.moving; + return { + 'u_matrix': coord ? coord.posMatrix : painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped(), align), + 'u_image': 0, + 'u_latrange': getTileLatRange(painter, tile.tileID), + 'u_light': [layer.paint.get('hillshade-exaggeration'), azimuthal], + 'u_shadow': shadow, + 'u_highlight': highlight, + 'u_accent': accent + }; +}; +const hillshadeUniformPrepareValues = (tileID, dem) => { + const stride = dem.stride; + const matrix = performance$1.H(); + // Flip rendering at y axis. + performance$1.aP(matrix, 0, performance$1.X, -performance$1.X, 0, 0, 1); + performance$1.J(matrix, matrix, [0, -performance$1.X, 0]); + return { + 'u_matrix': matrix, + 'u_image': 1, + 'u_dimension': [stride, stride], + 'u_zoom': tileID.overscaledZ, + 'u_unpack': dem.getUnpackVector() + }; +}; +function getTileLatRange(painter, tileID) { + // for scaling the magnitude of a points slope by its latitude + const tilesAtZoom = Math.pow(2, tileID.canonical.z); + const y = tileID.canonical.y; + return [ + new performance$1.Z(0, y / tilesAtZoom).toLngLat().lat, + new performance$1.Z(0, (y + 1) / tilesAtZoom).toLngLat().lat + ]; +} + +const lineUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_ratio': new performance$1.aI(context, locations.u_ratio), + 'u_device_pixel_ratio': new performance$1.aI(context, locations.u_device_pixel_ratio), + 'u_units_to_pixels': new performance$1.aO(context, locations.u_units_to_pixels) +}); +const lineGradientUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_ratio': new performance$1.aI(context, locations.u_ratio), + 'u_device_pixel_ratio': new performance$1.aI(context, locations.u_device_pixel_ratio), + 'u_units_to_pixels': new performance$1.aO(context, locations.u_units_to_pixels), + 'u_image': new performance$1.aH(context, locations.u_image), + 'u_image_height': new performance$1.aI(context, locations.u_image_height) +}); +const linePatternUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_texsize': new performance$1.aO(context, locations.u_texsize), + 'u_ratio': new performance$1.aI(context, locations.u_ratio), + 'u_device_pixel_ratio': new performance$1.aI(context, locations.u_device_pixel_ratio), + 'u_image': new performance$1.aH(context, locations.u_image), + 'u_units_to_pixels': new performance$1.aO(context, locations.u_units_to_pixels), + 'u_scale': new performance$1.aN(context, locations.u_scale), + 'u_fade': new performance$1.aI(context, locations.u_fade) +}); +const lineSDFUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_ratio': new performance$1.aI(context, locations.u_ratio), + 'u_device_pixel_ratio': new performance$1.aI(context, locations.u_device_pixel_ratio), + 'u_units_to_pixels': new performance$1.aO(context, locations.u_units_to_pixels), + 'u_patternscale_a': new performance$1.aO(context, locations.u_patternscale_a), + 'u_patternscale_b': new performance$1.aO(context, locations.u_patternscale_b), + 'u_sdfgamma': new performance$1.aI(context, locations.u_sdfgamma), + 'u_image': new performance$1.aH(context, locations.u_image), + 'u_tex_y_a': new performance$1.aI(context, locations.u_tex_y_a), + 'u_tex_y_b': new performance$1.aI(context, locations.u_tex_y_b), + 'u_mix': new performance$1.aI(context, locations.u_mix) +}); +const lineUniformValues = (painter, tile, layer, coord) => { + const transform = painter.transform; + return { + 'u_matrix': calculateMatrix(painter, tile, layer, coord), + 'u_ratio': 1 / pixelsToTileUnits(tile, 1, transform.zoom), + 'u_device_pixel_ratio': painter.pixelRatio, + 'u_units_to_pixels': [ + 1 / transform.pixelsToGLUnits[0], + 1 / transform.pixelsToGLUnits[1] + ] + }; +}; +const lineGradientUniformValues = (painter, tile, layer, imageHeight, coord) => { + return performance$1.e(lineUniformValues(painter, tile, layer, coord), { + 'u_image': 0, + 'u_image_height': imageHeight, + }); +}; +const linePatternUniformValues = (painter, tile, layer, crossfade, coord) => { + const transform = painter.transform; + const tileZoomRatio = calculateTileRatio(tile, transform); + return { + 'u_matrix': calculateMatrix(painter, tile, layer, coord), + 'u_texsize': tile.imageAtlasTexture.size, + // camera zoom ratio + 'u_ratio': 1 / pixelsToTileUnits(tile, 1, transform.zoom), + 'u_device_pixel_ratio': painter.pixelRatio, + 'u_image': 0, + 'u_scale': [tileZoomRatio, crossfade.fromScale, crossfade.toScale], + 'u_fade': crossfade.t, + 'u_units_to_pixels': [ + 1 / transform.pixelsToGLUnits[0], + 1 / transform.pixelsToGLUnits[1] + ] + }; +}; +const lineSDFUniformValues = (painter, tile, layer, dasharray, crossfade, coord) => { + const transform = painter.transform; + const lineAtlas = painter.lineAtlas; + const tileRatio = calculateTileRatio(tile, transform); + const round = layer.layout.get('line-cap') === 'round'; + const posA = lineAtlas.getDash(dasharray.from, round); + const posB = lineAtlas.getDash(dasharray.to, round); + const widthA = posA.width * crossfade.fromScale; + const widthB = posB.width * crossfade.toScale; + return performance$1.e(lineUniformValues(painter, tile, layer, coord), { + 'u_patternscale_a': [tileRatio / widthA, -posA.height / 2], + 'u_patternscale_b': [tileRatio / widthB, -posB.height / 2], + 'u_sdfgamma': lineAtlas.width / (Math.min(widthA, widthB) * 256 * painter.pixelRatio) / 2, + 'u_image': 0, + 'u_tex_y_a': posA.y, + 'u_tex_y_b': posB.y, + 'u_mix': crossfade.t + }); +}; +function calculateTileRatio(tile, transform) { + return 1 / pixelsToTileUnits(tile, 1, transform.tileZoom); +} +function calculateMatrix(painter, tile, layer, coord) { + return painter.translatePosMatrix(coord ? coord.posMatrix : tile.tileID.posMatrix, tile, layer.paint.get('line-translate'), layer.paint.get('line-translate-anchor')); +} + +const rasterUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_tl_parent': new performance$1.aO(context, locations.u_tl_parent), + 'u_scale_parent': new performance$1.aI(context, locations.u_scale_parent), + 'u_buffer_scale': new performance$1.aI(context, locations.u_buffer_scale), + 'u_fade_t': new performance$1.aI(context, locations.u_fade_t), + 'u_opacity': new performance$1.aI(context, locations.u_opacity), + 'u_image0': new performance$1.aH(context, locations.u_image0), + 'u_image1': new performance$1.aH(context, locations.u_image1), + 'u_brightness_low': new performance$1.aI(context, locations.u_brightness_low), + 'u_brightness_high': new performance$1.aI(context, locations.u_brightness_high), + 'u_saturation_factor': new performance$1.aI(context, locations.u_saturation_factor), + 'u_contrast_factor': new performance$1.aI(context, locations.u_contrast_factor), + 'u_spin_weights': new performance$1.aN(context, locations.u_spin_weights) +}); +const rasterUniformValues = (matrix, parentTL, parentScaleBy, fade, layer) => ({ + 'u_matrix': matrix, + 'u_tl_parent': parentTL, + 'u_scale_parent': parentScaleBy, + 'u_buffer_scale': 1, + 'u_fade_t': fade.mix, + 'u_opacity': fade.opacity * layer.paint.get('raster-opacity'), + 'u_image0': 0, + 'u_image1': 1, + 'u_brightness_low': layer.paint.get('raster-brightness-min'), + 'u_brightness_high': layer.paint.get('raster-brightness-max'), + 'u_saturation_factor': saturationFactor(layer.paint.get('raster-saturation')), + 'u_contrast_factor': contrastFactor(layer.paint.get('raster-contrast')), + 'u_spin_weights': spinWeights(layer.paint.get('raster-hue-rotate')) +}); +function spinWeights(angle) { + angle *= Math.PI / 180; + const s = Math.sin(angle); + const c = Math.cos(angle); + return [ + (2 * c + 1) / 3, + (-Math.sqrt(3) * s - c + 1) / 3, + (Math.sqrt(3) * s - c + 1) / 3 + ]; +} +function contrastFactor(contrast) { + return contrast > 0 ? + 1 / (1 - contrast) : + 1 + contrast; +} +function saturationFactor(saturation) { + return saturation > 0 ? + 1 - 1 / (1.001 - saturation) : + -saturation; +} + +const symbolIconUniforms = (context, locations) => ({ + 'u_is_size_zoom_constant': new performance$1.aH(context, locations.u_is_size_zoom_constant), + 'u_is_size_feature_constant': new performance$1.aH(context, locations.u_is_size_feature_constant), + 'u_size_t': new performance$1.aI(context, locations.u_size_t), + 'u_size': new performance$1.aI(context, locations.u_size), + 'u_camera_to_center_distance': new performance$1.aI(context, locations.u_camera_to_center_distance), + 'u_pitch': new performance$1.aI(context, locations.u_pitch), + 'u_rotate_symbol': new performance$1.aH(context, locations.u_rotate_symbol), + 'u_aspect_ratio': new performance$1.aI(context, locations.u_aspect_ratio), + 'u_fade_change': new performance$1.aI(context, locations.u_fade_change), + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_label_plane_matrix': new performance$1.aJ(context, locations.u_label_plane_matrix), + 'u_coord_matrix': new performance$1.aJ(context, locations.u_coord_matrix), + 'u_is_text': new performance$1.aH(context, locations.u_is_text), + 'u_pitch_with_map': new performance$1.aH(context, locations.u_pitch_with_map), + 'u_is_along_line': new performance$1.aH(context, locations.u_is_along_line), + 'u_is_variable_anchor': new performance$1.aH(context, locations.u_is_variable_anchor), + 'u_texsize': new performance$1.aO(context, locations.u_texsize), + 'u_texture': new performance$1.aH(context, locations.u_texture), + 'u_translation': new performance$1.aO(context, locations.u_translation), + 'u_pitched_scale': new performance$1.aI(context, locations.u_pitched_scale), +}); +const symbolSDFUniforms = (context, locations) => ({ + 'u_is_size_zoom_constant': new performance$1.aH(context, locations.u_is_size_zoom_constant), + 'u_is_size_feature_constant': new performance$1.aH(context, locations.u_is_size_feature_constant), + 'u_size_t': new performance$1.aI(context, locations.u_size_t), + 'u_size': new performance$1.aI(context, locations.u_size), + 'u_camera_to_center_distance': new performance$1.aI(context, locations.u_camera_to_center_distance), + 'u_pitch': new performance$1.aI(context, locations.u_pitch), + 'u_rotate_symbol': new performance$1.aH(context, locations.u_rotate_symbol), + 'u_aspect_ratio': new performance$1.aI(context, locations.u_aspect_ratio), + 'u_fade_change': new performance$1.aI(context, locations.u_fade_change), + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_label_plane_matrix': new performance$1.aJ(context, locations.u_label_plane_matrix), + 'u_coord_matrix': new performance$1.aJ(context, locations.u_coord_matrix), + 'u_is_text': new performance$1.aH(context, locations.u_is_text), + 'u_pitch_with_map': new performance$1.aH(context, locations.u_pitch_with_map), + 'u_is_along_line': new performance$1.aH(context, locations.u_is_along_line), + 'u_is_variable_anchor': new performance$1.aH(context, locations.u_is_variable_anchor), + 'u_texsize': new performance$1.aO(context, locations.u_texsize), + 'u_texture': new performance$1.aH(context, locations.u_texture), + 'u_texture_2': new performance$1.aH(context, locations.u_texture_2), + 'u_gamma_scale': new performance$1.aI(context, locations.u_gamma_scale), + 'u_device_pixel_ratio': new performance$1.aI(context, locations.u_device_pixel_ratio), + 'u_is_halo': new performance$1.aH(context, locations.u_is_halo), + 'u_translation': new performance$1.aO(context, locations.u_translation), + 'u_pitched_scale': new performance$1.aI(context, locations.u_pitched_scale), +}); +const symbolTextAndIconUniforms = (context, locations) => ({ + 'u_is_size_zoom_constant': new performance$1.aH(context, locations.u_is_size_zoom_constant), + 'u_is_size_feature_constant': new performance$1.aH(context, locations.u_is_size_feature_constant), + 'u_size_t': new performance$1.aI(context, locations.u_size_t), + 'u_size': new performance$1.aI(context, locations.u_size), + 'u_camera_to_center_distance': new performance$1.aI(context, locations.u_camera_to_center_distance), + 'u_pitch': new performance$1.aI(context, locations.u_pitch), + 'u_rotate_symbol': new performance$1.aH(context, locations.u_rotate_symbol), + 'u_aspect_ratio': new performance$1.aI(context, locations.u_aspect_ratio), + 'u_fade_change': new performance$1.aI(context, locations.u_fade_change), + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_label_plane_matrix': new performance$1.aJ(context, locations.u_label_plane_matrix), + 'u_coord_matrix': new performance$1.aJ(context, locations.u_coord_matrix), + 'u_is_text': new performance$1.aH(context, locations.u_is_text), + 'u_pitch_with_map': new performance$1.aH(context, locations.u_pitch_with_map), + 'u_is_along_line': new performance$1.aH(context, locations.u_is_along_line), + 'u_is_variable_anchor': new performance$1.aH(context, locations.u_is_variable_anchor), + 'u_texsize': new performance$1.aO(context, locations.u_texsize), + 'u_texsize_icon': new performance$1.aO(context, locations.u_texsize_icon), + 'u_texture': new performance$1.aH(context, locations.u_texture), + 'u_texture_icon': new performance$1.aH(context, locations.u_texture_icon), + 'u_gamma_scale': new performance$1.aI(context, locations.u_gamma_scale), + 'u_device_pixel_ratio': new performance$1.aI(context, locations.u_device_pixel_ratio), + 'u_is_halo': new performance$1.aH(context, locations.u_is_halo), + 'u_translation': new performance$1.aO(context, locations.u_translation), + 'u_pitched_scale': new performance$1.aI(context, locations.u_pitched_scale), +}); +const symbolIconUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, pitchedScale) => { + const transform = painter.transform; + return { + 'u_is_size_zoom_constant': +(functionType === 'constant' || functionType === 'source'), + 'u_is_size_feature_constant': +(functionType === 'constant' || functionType === 'camera'), + 'u_size_t': size ? size.uSizeT : 0, + 'u_size': size ? size.uSize : 0, + 'u_camera_to_center_distance': transform.cameraToCenterDistance, + 'u_pitch': transform.pitch / 360 * 2 * Math.PI, + 'u_rotate_symbol': +rotateInShader, + 'u_aspect_ratio': transform.width / transform.height, + 'u_fade_change': painter.options.fadeDuration ? painter.symbolFadeChange : 1, + 'u_matrix': matrix, + 'u_label_plane_matrix': labelPlaneMatrix, + 'u_coord_matrix': glCoordMatrix, + 'u_is_text': +isText, + 'u_pitch_with_map': +pitchWithMap, + 'u_is_along_line': isAlongLine, + 'u_is_variable_anchor': isVariableAnchor, + 'u_texsize': texSize, + 'u_texture': 0, + 'u_translation': translation, + 'u_pitched_scale': pitchedScale + }; +}; +const symbolSDFUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, isHalo, pitchedScale) => { + const transform = painter.transform; + return performance$1.e(symbolIconUniformValues(functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, pitchedScale), { + 'u_gamma_scale': (pitchWithMap ? Math.cos(transform._pitch) * transform.cameraToCenterDistance : 1), + 'u_device_pixel_ratio': painter.pixelRatio, + 'u_is_halo': +isHalo, + 'u_texture_2': 1 + }); +}; +const symbolTextAndIconUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, texSizeSDF, texSizeIcon, pitchedScale) => { + return performance$1.e(symbolSDFUniformValues(functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, matrix, labelPlaneMatrix, glCoordMatrix, translation, true, texSizeSDF, true, pitchedScale), { + 'u_texsize_icon': texSizeIcon, + 'u_texture_icon': 1 + }); +}; + +const backgroundUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_opacity': new performance$1.aI(context, locations.u_opacity), + 'u_color': new performance$1.aL(context, locations.u_color) +}); +const backgroundPatternUniforms = (context, locations) => ({ + 'u_matrix': new performance$1.aJ(context, locations.u_matrix), + 'u_opacity': new performance$1.aI(context, locations.u_opacity), + 'u_image': new performance$1.aH(context, locations.u_image), + 'u_pattern_tl_a': new performance$1.aO(context, locations.u_pattern_tl_a), + 'u_pattern_br_a': new performance$1.aO(context, locations.u_pattern_br_a), + 'u_pattern_tl_b': new performance$1.aO(context, locations.u_pattern_tl_b), + 'u_pattern_br_b': new performance$1.aO(context, locations.u_pattern_br_b), + 'u_texsize': new performance$1.aO(context, locations.u_texsize), + 'u_mix': new performance$1.aI(context, locations.u_mix), + 'u_pattern_size_a': new performance$1.aO(context, locations.u_pattern_size_a), + 'u_pattern_size_b': new performance$1.aO(context, locations.u_pattern_size_b), + 'u_scale_a': new performance$1.aI(context, locations.u_scale_a), + 'u_scale_b': new performance$1.aI(context, locations.u_scale_b), + 'u_pixel_coord_upper': new performance$1.aO(context, locations.u_pixel_coord_upper), + 'u_pixel_coord_lower': new performance$1.aO(context, locations.u_pixel_coord_lower), + 'u_tile_units_to_pixels': new performance$1.aI(context, locations.u_tile_units_to_pixels) +}); +const backgroundUniformValues = (matrix, opacity, color) => ({ + 'u_matrix': matrix, + 'u_opacity': opacity, + 'u_color': color +}); +const backgroundPatternUniformValues = (matrix, opacity, painter, image, tile, crossfade) => performance$1.e(bgPatternUniformValues(image, crossfade, painter, tile), { + 'u_matrix': matrix, + 'u_opacity': opacity +}); + +const skyUniforms = (context, locations) => ({ + 'u_sky_color': new performance$1.aL(context, locations.u_sky_color), + 'u_horizon_color': new performance$1.aL(context, locations.u_horizon_color), + 'u_horizon': new performance$1.aI(context, locations.u_horizon), + 'u_sky_horizon_blend': new performance$1.aI(context, locations.u_sky_horizon_blend), +}); +const skyUniformValues = (sky, transform, pixelRatio) => ({ + 'u_sky_color': sky.properties.get('sky-color'), + 'u_horizon_color': sky.properties.get('horizon-color'), + 'u_horizon': (transform.height / 2 + transform.getHorizon()) * pixelRatio, + 'u_sky_horizon_blend': (sky.properties.get('sky-horizon-blend') * transform.height / 2) * pixelRatio, +}); + +const programUniforms = { + fillExtrusion: fillExtrusionUniforms, + fillExtrusionPattern: fillExtrusionPatternUniforms, + fill: fillUniforms, + fillPattern: fillPatternUniforms, + fillOutline: fillOutlineUniforms, + fillOutlinePattern: fillOutlinePatternUniforms, + circle: circleUniforms, + collisionBox: collisionUniforms, + collisionCircle: collisionCircleUniforms, + debug: debugUniforms, + clippingMask: clippingMaskUniforms, + heatmap: heatmapUniforms, + heatmapTexture: heatmapTextureUniforms, + hillshade: hillshadeUniforms, + hillshadePrepare: hillshadePrepareUniforms, + line: lineUniforms, + lineGradient: lineGradientUniforms, + linePattern: linePatternUniforms, + lineSDF: lineSDFUniforms, + raster: rasterUniforms, + symbolIcon: symbolIconUniforms, + symbolSDF: symbolSDFUniforms, + symbolTextAndIcon: symbolTextAndIconUniforms, + background: backgroundUniforms, + backgroundPattern: backgroundPatternUniforms, + terrain: terrainUniforms, + terrainDepth: terrainDepthUniforms, + terrainCoords: terrainCoordsUniforms, + sky: skyUniforms +}; + +/** + * @internal + * an index buffer class + */ +class IndexBuffer { + constructor(context, array, dynamicDraw) { + this.context = context; + const gl = context.gl; + this.buffer = gl.createBuffer(); + this.dynamicDraw = Boolean(dynamicDraw); + // The bound index buffer is part of vertex array object state. We don't want to + // modify whatever VAO happens to be currently bound, so make sure the default + // vertex array provided by the context is bound instead. + this.context.unbindVAO(); + context.bindElementBuffer.set(this.buffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW); + if (!this.dynamicDraw) { + delete array.arrayBuffer; + } + } + bind() { + this.context.bindElementBuffer.set(this.buffer); + } + updateData(array) { + const gl = this.context.gl; + if (!this.dynamicDraw) + throw new Error('Attempted to update data while not in dynamic mode.'); + // The right VAO will get this buffer re-bound later in VertexArrayObject#bind + // See https://github.com/mapbox/mapbox-gl-js/issues/5620 + this.context.unbindVAO(); + this.bind(); + gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, array.arrayBuffer); + } + destroy() { + const gl = this.context.gl; + if (this.buffer) { + gl.deleteBuffer(this.buffer); + delete this.buffer; + } + } +} + +/** + * An Enum for AttributeType + */ +const AttributeType = { + Int8: 'BYTE', + Uint8: 'UNSIGNED_BYTE', + Int16: 'SHORT', + Uint16: 'UNSIGNED_SHORT', + Int32: 'INT', + Uint32: 'UNSIGNED_INT', + Float32: 'FLOAT' +}; +/** + * @internal + * The `VertexBuffer` class turns a `StructArray` into a WebGL buffer. Each member of the StructArray's + * Struct type is converted to a WebGL attribute. + */ +class VertexBuffer { + /** + * @param dynamicDraw - Whether this buffer will be repeatedly updated. + */ + constructor(context, array, attributes, dynamicDraw) { + this.length = array.length; + this.attributes = attributes; + this.itemSize = array.bytesPerElement; + this.dynamicDraw = dynamicDraw; + this.context = context; + const gl = context.gl; + this.buffer = gl.createBuffer(); + context.bindVertexBuffer.set(this.buffer); + gl.bufferData(gl.ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW); + if (!this.dynamicDraw) { + delete array.arrayBuffer; + } + } + bind() { + this.context.bindVertexBuffer.set(this.buffer); + } + updateData(array) { + if (array.length !== this.length) + throw new Error(`Length of new data is ${array.length}, which doesn't match current length of ${this.length}`); + const gl = this.context.gl; + this.bind(); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, array.arrayBuffer); + } + enableAttributes(gl, program) { + for (let j = 0; j < this.attributes.length; j++) { + const member = this.attributes[j]; + const attribIndex = program.attributes[member.name]; + if (attribIndex !== undefined) { + gl.enableVertexAttribArray(attribIndex); + } + } + } + /** + * Set the attribute pointers in a WebGL context + * @param gl - The WebGL context + * @param program - The active WebGL program + * @param vertexOffset - Index of the starting vertex of the segment + */ + setVertexAttribPointers(gl, program, vertexOffset) { + for (let j = 0; j < this.attributes.length; j++) { + const member = this.attributes[j]; + const attribIndex = program.attributes[member.name]; + if (attribIndex !== undefined) { + gl.vertexAttribPointer(attribIndex, member.components, gl[AttributeType[member.type]], false, this.itemSize, member.offset + (this.itemSize * (vertexOffset || 0))); + } + } + } + /** + * Destroy the GL buffer bound to the given WebGL context + */ + destroy() { + const gl = this.context.gl; + if (this.buffer) { + gl.deleteBuffer(this.buffer); + delete this.buffer; + } + } +} + +const cache = new WeakMap(); +function isWebGL2(gl) { + var _a; + if (cache.has(gl)) { + return cache.get(gl); + } + else { + const value = (_a = gl.getParameter(gl.VERSION)) === null || _a === void 0 ? void 0 : _a.startsWith('WebGL 2.0'); + cache.set(gl, value); + return value; + } +} + +class BaseValue { + constructor(context) { + this.gl = context.gl; + this.default = this.getDefault(); + this.current = this.default; + this.dirty = false; + } + get() { + return this.current; + } + set(value) { + // overridden in child classes; + } + getDefault() { + return this.default; // overridden in child classes + } + setDefault() { + this.set(this.default); + } +} +class ClearColor extends BaseValue { + getDefault() { + return performance$1.aM.transparent; + } + set(v) { + const c = this.current; + if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) + return; + this.gl.clearColor(v.r, v.g, v.b, v.a); + this.current = v; + this.dirty = false; + } +} +class ClearDepth extends BaseValue { + getDefault() { + return 1; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.clearDepth(v); + this.current = v; + this.dirty = false; + } +} +class ClearStencil extends BaseValue { + getDefault() { + return 0; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.clearStencil(v); + this.current = v; + this.dirty = false; + } +} +class ColorMask extends BaseValue { + getDefault() { + return [true, true, true, true]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) + return; + this.gl.colorMask(v[0], v[1], v[2], v[3]); + this.current = v; + this.dirty = false; + } +} +class DepthMask extends BaseValue { + getDefault() { + return true; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.depthMask(v); + this.current = v; + this.dirty = false; + } +} +class StencilMask extends BaseValue { + getDefault() { + return 0xFF; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.stencilMask(v); + this.current = v; + this.dirty = false; + } +} +class StencilFunc extends BaseValue { + getDefault() { + return { + func: this.gl.ALWAYS, + ref: 0, + mask: 0xFF + }; + } + set(v) { + const c = this.current; + if (v.func === c.func && v.ref === c.ref && v.mask === c.mask && !this.dirty) + return; + this.gl.stencilFunc(v.func, v.ref, v.mask); + this.current = v; + this.dirty = false; + } +} +class StencilOp extends BaseValue { + getDefault() { + const gl = this.gl; + return [gl.KEEP, gl.KEEP, gl.KEEP]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && !this.dirty) + return; + this.gl.stencilOp(v[0], v[1], v[2]); + this.current = v; + this.dirty = false; + } +} +class StencilTest extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (v) { + gl.enable(gl.STENCIL_TEST); + } + else { + gl.disable(gl.STENCIL_TEST); + } + this.current = v; + this.dirty = false; + } +} +class DepthRange extends BaseValue { + getDefault() { + return [0, 1]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && !this.dirty) + return; + this.gl.depthRange(v[0], v[1]); + this.current = v; + this.dirty = false; + } +} +class DepthTest extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (v) { + gl.enable(gl.DEPTH_TEST); + } + else { + gl.disable(gl.DEPTH_TEST); + } + this.current = v; + this.dirty = false; + } +} +class DepthFunc extends BaseValue { + getDefault() { + return this.gl.LESS; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.depthFunc(v); + this.current = v; + this.dirty = false; + } +} +class Blend extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (v) { + gl.enable(gl.BLEND); + } + else { + gl.disable(gl.BLEND); + } + this.current = v; + this.dirty = false; + } +} +class BlendFunc extends BaseValue { + getDefault() { + const gl = this.gl; + return [gl.ONE, gl.ZERO]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && !this.dirty) + return; + this.gl.blendFunc(v[0], v[1]); + this.current = v; + this.dirty = false; + } +} +class BlendColor extends BaseValue { + getDefault() { + return performance$1.aM.transparent; + } + set(v) { + const c = this.current; + if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) + return; + this.gl.blendColor(v.r, v.g, v.b, v.a); + this.current = v; + this.dirty = false; + } +} +class BlendEquation extends BaseValue { + getDefault() { + return this.gl.FUNC_ADD; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.blendEquation(v); + this.current = v; + this.dirty = false; + } +} +class CullFace extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (v) { + gl.enable(gl.CULL_FACE); + } + else { + gl.disable(gl.CULL_FACE); + } + this.current = v; + this.dirty = false; + } +} +class CullFaceSide extends BaseValue { + getDefault() { + return this.gl.BACK; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.cullFace(v); + this.current = v; + this.dirty = false; + } +} +class FrontFace extends BaseValue { + getDefault() { + return this.gl.CCW; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.frontFace(v); + this.current = v; + this.dirty = false; + } +} +class ProgramValue extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.useProgram(v); + this.current = v; + this.dirty = false; + } +} +class ActiveTextureUnit extends BaseValue { + getDefault() { + return this.gl.TEXTURE0; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.gl.activeTexture(v); + this.current = v; + this.dirty = false; + } +} +class Viewport extends BaseValue { + getDefault() { + const gl = this.gl; + return [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight]; + } + set(v) { + const c = this.current; + if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) + return; + this.gl.viewport(v[0], v[1], v[2], v[3]); + this.current = v; + this.dirty = false; + } +} +class BindFramebuffer extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, v); + this.current = v; + this.dirty = false; + } +} +class BindRenderbuffer extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.bindRenderbuffer(gl.RENDERBUFFER, v); + this.current = v; + this.dirty = false; + } +} +class BindTexture extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, v); + this.current = v; + this.dirty = false; + } +} +class BindVertexBuffer extends BaseValue { + getDefault() { + return null; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.bindBuffer(gl.ARRAY_BUFFER, v); + this.current = v; + this.dirty = false; + } +} +class BindElementBuffer extends BaseValue { + getDefault() { + return null; + } + set(v) { + // Always rebind + const gl = this.gl; + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, v); + this.current = v; + this.dirty = false; + } +} +class BindVertexArray extends BaseValue { + getDefault() { + return null; + } + set(v) { + var _a; + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + if (isWebGL2(gl)) { + gl.bindVertexArray(v); + } + else { + (_a = gl.getExtension('OES_vertex_array_object')) === null || _a === void 0 ? void 0 : _a.bindVertexArrayOES(v); + } + this.current = v; + this.dirty = false; + } +} +class PixelStoreUnpack extends BaseValue { + getDefault() { + return 4; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_ALIGNMENT, v); + this.current = v; + this.dirty = false; + } +} +class PixelStoreUnpackPremultiplyAlpha extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, v); + this.current = v; + this.dirty = false; + } +} +class PixelStoreUnpackFlipY extends BaseValue { + getDefault() { + return false; + } + set(v) { + if (v === this.current && !this.dirty) + return; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, v); + this.current = v; + this.dirty = false; + } +} +class FramebufferAttachment extends BaseValue { + constructor(context, parent) { + super(context); + this.context = context; + this.parent = parent; + } + getDefault() { + return null; + } +} +class ColorAttachment extends FramebufferAttachment { + setDirty() { + this.dirty = true; + } + set(v) { + if (v === this.current && !this.dirty) + return; + this.context.bindFramebuffer.set(this.parent); + // note: it's possible to attach a renderbuffer to the color + // attachment point, but thus far MBGL only uses textures for color + const gl = this.gl; + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, v, 0); + this.current = v; + this.dirty = false; + } +} +class DepthAttachment extends FramebufferAttachment { + set(v) { + if (v === this.current && !this.dirty) + return; + this.context.bindFramebuffer.set(this.parent); + // note: it's possible to attach a texture to the depth attachment + // point, but thus far MBGL only uses renderbuffers for depth + const gl = this.gl; + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, v); + this.current = v; + this.dirty = false; + } +} +class DepthStencilAttachment extends FramebufferAttachment { + set(v) { + if (v === this.current && !this.dirty) + return; + this.context.bindFramebuffer.set(this.parent); + // note: it's possible to attach a texture to the depth attachment + // point, but thus far MBGL only uses renderbuffers for depth + const gl = this.gl; + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, v); + this.current = v; + this.dirty = false; + } +} + +/** + * @internal + * A framebuffer holder object + */ +class Framebuffer { + constructor(context, width, height, hasDepth, hasStencil) { + this.context = context; + this.width = width; + this.height = height; + const gl = context.gl; + const fbo = this.framebuffer = gl.createFramebuffer(); + this.colorAttachment = new ColorAttachment(context, fbo); + if (hasDepth) { + this.depthAttachment = hasStencil ? new DepthStencilAttachment(context, fbo) : new DepthAttachment(context, fbo); + } + else if (hasStencil) { + throw new Error('Stencil cannot be set without depth'); + } + if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) { + throw new Error('Framebuffer is not complete'); + } + } + destroy() { + const gl = this.context.gl; + const texture = this.colorAttachment.get(); + if (texture) + gl.deleteTexture(texture); + if (this.depthAttachment) { + const renderbuffer = this.depthAttachment.get(); + if (renderbuffer) + gl.deleteRenderbuffer(renderbuffer); + } + gl.deleteFramebuffer(this.framebuffer); + } +} + +const ZERO = 0x0000; +const ONE = 0x0001; +const ONE_MINUS_SRC_ALPHA = 0x0303; +class ColorMode { + constructor(blendFunction, blendColor, mask) { + this.blendFunction = blendFunction; + this.blendColor = blendColor; + this.mask = mask; + } +} +ColorMode.Replace = [ONE, ZERO]; +ColorMode.disabled = new ColorMode(ColorMode.Replace, performance$1.aM.transparent, [false, false, false, false]); +ColorMode.unblended = new ColorMode(ColorMode.Replace, performance$1.aM.transparent, [true, true, true, true]); +ColorMode.alphaBlended = new ColorMode([ONE, ONE_MINUS_SRC_ALPHA], performance$1.aM.transparent, [true, true, true, true]); + +/** + * @internal + * A webgl wrapper class to allow injection, mocking and abstaction + */ +class Context { + constructor(gl) { + var _a, _b; + this.gl = gl; + this.clearColor = new ClearColor(this); + this.clearDepth = new ClearDepth(this); + this.clearStencil = new ClearStencil(this); + this.colorMask = new ColorMask(this); + this.depthMask = new DepthMask(this); + this.stencilMask = new StencilMask(this); + this.stencilFunc = new StencilFunc(this); + this.stencilOp = new StencilOp(this); + this.stencilTest = new StencilTest(this); + this.depthRange = new DepthRange(this); + this.depthTest = new DepthTest(this); + this.depthFunc = new DepthFunc(this); + this.blend = new Blend(this); + this.blendFunc = new BlendFunc(this); + this.blendColor = new BlendColor(this); + this.blendEquation = new BlendEquation(this); + this.cullFace = new CullFace(this); + this.cullFaceSide = new CullFaceSide(this); + this.frontFace = new FrontFace(this); + this.program = new ProgramValue(this); + this.activeTexture = new ActiveTextureUnit(this); + this.viewport = new Viewport(this); + this.bindFramebuffer = new BindFramebuffer(this); + this.bindRenderbuffer = new BindRenderbuffer(this); + this.bindTexture = new BindTexture(this); + this.bindVertexBuffer = new BindVertexBuffer(this); + this.bindElementBuffer = new BindElementBuffer(this); + this.bindVertexArray = new BindVertexArray(this); + this.pixelStoreUnpack = new PixelStoreUnpack(this); + this.pixelStoreUnpackPremultiplyAlpha = new PixelStoreUnpackPremultiplyAlpha(this); + this.pixelStoreUnpackFlipY = new PixelStoreUnpackFlipY(this); + this.extTextureFilterAnisotropic = (gl.getExtension('EXT_texture_filter_anisotropic') || + gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || + gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic')); + if (this.extTextureFilterAnisotropic) { + this.extTextureFilterAnisotropicMax = gl.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } + this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + if (isWebGL2(gl)) { + this.HALF_FLOAT = gl.HALF_FLOAT; + const extColorBufferHalfFloat = gl.getExtension('EXT_color_buffer_half_float'); + this.RGBA16F = (_a = gl.RGBA16F) !== null && _a !== void 0 ? _a : extColorBufferHalfFloat === null || extColorBufferHalfFloat === void 0 ? void 0 : extColorBufferHalfFloat.RGBA16F_EXT; + this.RGB16F = (_b = gl.RGB16F) !== null && _b !== void 0 ? _b : extColorBufferHalfFloat === null || extColorBufferHalfFloat === void 0 ? void 0 : extColorBufferHalfFloat.RGB16F_EXT; + gl.getExtension('EXT_color_buffer_float'); + } + else { + gl.getExtension('EXT_color_buffer_half_float'); + gl.getExtension('OES_texture_half_float_linear'); + const extTextureHalfFloat = gl.getExtension('OES_texture_half_float'); + this.HALF_FLOAT = extTextureHalfFloat === null || extTextureHalfFloat === void 0 ? void 0 : extTextureHalfFloat.HALF_FLOAT_OES; + } + } + setDefault() { + this.unbindVAO(); + this.clearColor.setDefault(); + this.clearDepth.setDefault(); + this.clearStencil.setDefault(); + this.colorMask.setDefault(); + this.depthMask.setDefault(); + this.stencilMask.setDefault(); + this.stencilFunc.setDefault(); + this.stencilOp.setDefault(); + this.stencilTest.setDefault(); + this.depthRange.setDefault(); + this.depthTest.setDefault(); + this.depthFunc.setDefault(); + this.blend.setDefault(); + this.blendFunc.setDefault(); + this.blendColor.setDefault(); + this.blendEquation.setDefault(); + this.cullFace.setDefault(); + this.cullFaceSide.setDefault(); + this.frontFace.setDefault(); + this.program.setDefault(); + this.activeTexture.setDefault(); + this.bindFramebuffer.setDefault(); + this.pixelStoreUnpack.setDefault(); + this.pixelStoreUnpackPremultiplyAlpha.setDefault(); + this.pixelStoreUnpackFlipY.setDefault(); + } + setDirty() { + this.clearColor.dirty = true; + this.clearDepth.dirty = true; + this.clearStencil.dirty = true; + this.colorMask.dirty = true; + this.depthMask.dirty = true; + this.stencilMask.dirty = true; + this.stencilFunc.dirty = true; + this.stencilOp.dirty = true; + this.stencilTest.dirty = true; + this.depthRange.dirty = true; + this.depthTest.dirty = true; + this.depthFunc.dirty = true; + this.blend.dirty = true; + this.blendFunc.dirty = true; + this.blendColor.dirty = true; + this.blendEquation.dirty = true; + this.cullFace.dirty = true; + this.cullFaceSide.dirty = true; + this.frontFace.dirty = true; + this.program.dirty = true; + this.activeTexture.dirty = true; + this.viewport.dirty = true; + this.bindFramebuffer.dirty = true; + this.bindRenderbuffer.dirty = true; + this.bindTexture.dirty = true; + this.bindVertexBuffer.dirty = true; + this.bindElementBuffer.dirty = true; + this.bindVertexArray.dirty = true; + this.pixelStoreUnpack.dirty = true; + this.pixelStoreUnpackPremultiplyAlpha.dirty = true; + this.pixelStoreUnpackFlipY.dirty = true; + } + createIndexBuffer(array, dynamicDraw) { + return new IndexBuffer(this, array, dynamicDraw); + } + createVertexBuffer(array, attributes, dynamicDraw) { + return new VertexBuffer(this, array, attributes, dynamicDraw); + } + createRenderbuffer(storageFormat, width, height) { + const gl = this.gl; + const rbo = gl.createRenderbuffer(); + this.bindRenderbuffer.set(rbo); + gl.renderbufferStorage(gl.RENDERBUFFER, storageFormat, width, height); + this.bindRenderbuffer.set(null); + return rbo; + } + createFramebuffer(width, height, hasDepth, hasStencil) { + return new Framebuffer(this, width, height, hasDepth, hasStencil); + } + clear({ color, depth, stencil }) { + const gl = this.gl; + let mask = 0; + if (color) { + mask |= gl.COLOR_BUFFER_BIT; + this.clearColor.set(color); + this.colorMask.set([true, true, true, true]); + } + if (typeof depth !== 'undefined') { + mask |= gl.DEPTH_BUFFER_BIT; + // Workaround for platforms where clearDepth doesn't seem to work + // without resetting the depthRange. See https://github.com/mapbox/mapbox-gl-js/issues/3437 + this.depthRange.set([0, 1]); + this.clearDepth.set(depth); + this.depthMask.set(true); + } + if (typeof stencil !== 'undefined') { + mask |= gl.STENCIL_BUFFER_BIT; + this.clearStencil.set(stencil); + this.stencilMask.set(0xFF); + } + gl.clear(mask); + } + setCullFace(cullFaceMode) { + if (cullFaceMode.enable === false) { + this.cullFace.set(false); + } + else { + this.cullFace.set(true); + this.cullFaceSide.set(cullFaceMode.mode); + this.frontFace.set(cullFaceMode.frontFace); + } + } + setDepthMode(depthMode) { + if (depthMode.func === this.gl.ALWAYS && !depthMode.mask) { + this.depthTest.set(false); + } + else { + this.depthTest.set(true); + this.depthFunc.set(depthMode.func); + this.depthMask.set(depthMode.mask); + this.depthRange.set(depthMode.range); + } + } + setStencilMode(stencilMode) { + if (stencilMode.test.func === this.gl.ALWAYS && !stencilMode.mask) { + this.stencilTest.set(false); + } + else { + this.stencilTest.set(true); + this.stencilMask.set(stencilMode.mask); + this.stencilOp.set([stencilMode.fail, stencilMode.depthFail, stencilMode.pass]); + this.stencilFunc.set({ + func: stencilMode.test.func, + ref: stencilMode.ref, + mask: stencilMode.test.mask + }); + } + } + setColorMode(colorMode) { + if (performance$1.aE(colorMode.blendFunction, ColorMode.Replace)) { + this.blend.set(false); + } + else { + this.blend.set(true); + this.blendFunc.set(colorMode.blendFunction); + this.blendColor.set(colorMode.blendColor); + } + this.colorMask.set(colorMode.mask); + } + createVertexArray() { + var _a; + if (isWebGL2(this.gl)) + return this.gl.createVertexArray(); + return (_a = this.gl.getExtension('OES_vertex_array_object')) === null || _a === void 0 ? void 0 : _a.createVertexArrayOES(); + } + deleteVertexArray(x) { + var _a; + if (isWebGL2(this.gl)) + return this.gl.deleteVertexArray(x); + return (_a = this.gl.getExtension('OES_vertex_array_object')) === null || _a === void 0 ? void 0 : _a.deleteVertexArrayOES(x); + } + unbindVAO() { + // Unbinding the VAO prevents other things (custom layers, new buffer creation) from + // unintentionally changing the state of the last VAO used. + this.bindVertexArray.set(null); + } +} + +const ALWAYS$1 = 0x0207; +class DepthMode { + constructor(depthFunc, depthMask, depthRange) { + this.func = depthFunc; + this.mask = depthMask; + this.range = depthRange; + } +} +DepthMode.ReadOnly = false; +DepthMode.ReadWrite = true; +DepthMode.disabled = new DepthMode(ALWAYS$1, DepthMode.ReadOnly, [0, 1]); + +const ALWAYS = 0x0207; +const KEEP = 0x1E00; +class StencilMode { + constructor(test, ref, mask, fail, depthFail, pass) { + this.test = test; + this.ref = ref; + this.mask = mask; + this.fail = fail; + this.depthFail = depthFail; + this.pass = pass; + } +} +StencilMode.disabled = new StencilMode({ func: ALWAYS, mask: 0 }, 0, 0, KEEP, KEEP, KEEP); + +const BACK = 0x0405; +const CCW = 0x0901; +class CullFaceMode { + constructor(enable, mode, frontFace) { + this.enable = enable; + this.mode = mode; + this.frontFace = frontFace; + } +} +CullFaceMode.disabled = new CullFaceMode(false, BACK, CCW); +CullFaceMode.backCCW = new CullFaceMode(true, BACK, CCW); + +let quadTriangles; +function drawCollisionDebug(painter, sourceCache, layer, coords, isText) { + const context = painter.context; + const gl = context.gl; + const program = painter.useProgram('collisionBox'); + const tileBatches = []; + let circleCount = 0; + let circleOffset = 0; + for (let i = 0; i < coords.length; i++) { + const coord = coords[i]; + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const buffers = isText ? bucket.textCollisionBox : bucket.iconCollisionBox; + // Get collision circle data of this bucket + const circleArray = bucket.collisionCircleArray; + if (circleArray.length > 0) { + // We need to know the projection matrix that was used for projecting collision circles to the screen. + // This might vary between buckets as the symbol placement is a continuous process. This matrix is + // required for transforming points from previous screen space to the current one + const invTransform = performance$1.H(); + performance$1.aQ(invTransform, bucket.placementInvProjMatrix, painter.transform.glCoordMatrix); + performance$1.aQ(invTransform, invTransform, bucket.placementViewportMatrix); + tileBatches.push({ + circleArray, + circleOffset, + transform: coord.posMatrix, // Ignore translation + invTransform, + coord + }); + circleCount += circleArray.length / 4; // 4 values per circle + circleOffset = circleCount; + } + // Draw collision boxes + if (!buffers) { + continue; + } + program.draw(context, gl.LINES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, collisionUniformValues(painter.transform, coord.posMatrix), painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord), layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer, buffers.segments, null, painter.transform.zoom, null, null, buffers.collisionVertexBuffer); + } + if (!isText || !tileBatches.length) { + return; + } + // Render collision circles + const circleProgram = painter.useProgram('collisionCircle'); + // Construct vertex data + const vertexData = new performance$1.aR(); + vertexData.resize(circleCount * 4); + vertexData._trim(); + let vertexOffset = 0; + for (const batch of tileBatches) { + for (let i = 0; i < batch.circleArray.length / 4; i++) { + const circleIdx = i * 4; + const x = batch.circleArray[circleIdx + 0]; + const y = batch.circleArray[circleIdx + 1]; + const radius = batch.circleArray[circleIdx + 2]; + const collision = batch.circleArray[circleIdx + 3]; + // 4 floats per vertex, 4 vertices per quad + vertexData.emplace(vertexOffset++, x, y, radius, collision, 0); + vertexData.emplace(vertexOffset++, x, y, radius, collision, 1); + vertexData.emplace(vertexOffset++, x, y, radius, collision, 2); + vertexData.emplace(vertexOffset++, x, y, radius, collision, 3); + } + } + if (!quadTriangles || quadTriangles.length < circleCount * 2) { + quadTriangles = createQuadTriangles(circleCount); + } + const indexBuffer = context.createIndexBuffer(quadTriangles, true); + const vertexBuffer = context.createVertexBuffer(vertexData, performance$1.aS.members, true); + // Render batches + for (const batch of tileBatches) { + const uniforms = collisionCircleUniformValues(batch.transform, batch.invTransform, painter.transform); + circleProgram.draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, uniforms, painter.style.map.terrain && painter.style.map.terrain.getTerrainData(batch.coord), layer.id, vertexBuffer, indexBuffer, performance$1.a0.simpleSegment(0, batch.circleOffset * 2, batch.circleArray.length, batch.circleArray.length / 2), null, painter.transform.zoom, null, null, null); + } + vertexBuffer.destroy(); + indexBuffer.destroy(); +} +function createQuadTriangles(quadCount) { + const triCount = quadCount * 2; + const array = new performance$1.aT(); + array.resize(triCount); + array._trim(); + // Two triangles and 4 vertices per quad. + for (let i = 0; i < triCount; i++) { + const idx = i * 6; + array.uint16[idx + 0] = i * 4 + 0; + array.uint16[idx + 1] = i * 4 + 1; + array.uint16[idx + 2] = i * 4 + 2; + array.uint16[idx + 3] = i * 4 + 2; + array.uint16[idx + 4] = i * 4 + 3; + array.uint16[idx + 5] = i * 4 + 0; + } + return array; +} + +const identityMat4 = performance$1.an(new Float32Array(16)); +function drawSymbols(painter, sourceCache, layer, coords, variableOffsets) { + if (painter.renderPass !== 'translucent') + return; + // Disable the stencil test so that labels aren't clipped to tile boundaries. + const stencilMode = StencilMode.disabled; + const colorMode = painter.colorModeForRenderPass(); + const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset'); + //Compute variable-offsets before painting since icons and text data positioning + //depend on each other in this case. + if (hasVariablePlacement) { + updateVariableAnchors(coords, painter, layer, sourceCache, layer.layout.get('text-rotation-alignment'), layer.layout.get('text-pitch-alignment'), layer.paint.get('text-translate'), layer.paint.get('text-translate-anchor'), variableOffsets); + } + if (layer.paint.get('icon-opacity').constantOr(1) !== 0) { + drawLayerSymbols(painter, sourceCache, layer, coords, false, layer.paint.get('icon-translate'), layer.paint.get('icon-translate-anchor'), layer.layout.get('icon-rotation-alignment'), layer.layout.get('icon-pitch-alignment'), layer.layout.get('icon-keep-upright'), stencilMode, colorMode); + } + if (layer.paint.get('text-opacity').constantOr(1) !== 0) { + drawLayerSymbols(painter, sourceCache, layer, coords, true, layer.paint.get('text-translate'), layer.paint.get('text-translate-anchor'), layer.layout.get('text-rotation-alignment'), layer.layout.get('text-pitch-alignment'), layer.layout.get('text-keep-upright'), stencilMode, colorMode); + } + if (sourceCache.map.showCollisionBoxes) { + drawCollisionDebug(painter, sourceCache, layer, coords, true); + drawCollisionDebug(painter, sourceCache, layer, coords, false); + } +} +function calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize) { + const { horizontalAlign, verticalAlign } = performance$1.au(anchor); + const shiftX = -(horizontalAlign - 0.5) * width; + const shiftY = -(verticalAlign - 0.5) * height; + return new performance$1.P((shiftX / textBoxScale + textOffset[0]) * renderTextSize, (shiftY / textBoxScale + textOffset[1]) * renderTextSize); +} +function updateVariableAnchors(coords, painter, layer, sourceCache, rotationAlignment, pitchAlignment, translate, translateAnchor, variableOffsets) { + const transform = painter.transform; + const projection = createProjection(); + const rotateWithMap = rotationAlignment === 'map'; + const pitchWithMap = pitchAlignment === 'map'; + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket || !bucket.text || !bucket.text.segments.get().length) + continue; + const sizeData = bucket.textSizeData; + const size = performance$1.ag(sizeData, transform.zoom); + const pixelToTileScale = pixelsToTileUnits(tile, 1, painter.transform.zoom); + const labelPlaneMatrix = getLabelPlaneMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, pixelToTileScale); + const updateTextFitIcon = layer.layout.get('icon-text-fit') !== 'none' && bucket.hasIconData(); + if (size) { + const tileScale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ); + const getElevation = painter.style.map.terrain ? (x, y) => painter.style.map.terrain.getElevation(coord, x, y) : null; + const translation = projection.translatePosition(transform, tile, translate, translateAnchor); + updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, transform, labelPlaneMatrix, coord.posMatrix, tileScale, size, updateTextFitIcon, projection, translation, coord.toUnwrapped(), getElevation); + } + } +} +function getShiftedAnchor(projectedAnchorPoint, projectionContext, rotateWithMap, shift, transformAngle, pitchedTextShiftCorrection) { + // Usual case is that we take the projected anchor and add the pixel-based shift + // calculated earlier. In the (somewhat weird) case of pitch-aligned text, we add an equivalent + // tile-unit based shift to the anchor before projecting to the label plane. + const translatedAnchor = projectionContext.tileAnchorPoint.add(new performance$1.P(projectionContext.translation[0], projectionContext.translation[1])); + if (projectionContext.pitchWithMap) { + let adjustedShift = shift.mult(pitchedTextShiftCorrection); + if (!rotateWithMap) { + adjustedShift = adjustedShift.rotate(-transformAngle); + } + const tileAnchorShifted = translatedAnchor.add(adjustedShift); + return project(tileAnchorShifted.x, tileAnchorShifted.y, projectionContext.labelPlaneMatrix, projectionContext.getElevation).point; + } + else { + if (rotateWithMap) { + // Compute the angle with which to rotate the anchor, so that it is aligned with + // the map's actual east-west axis. Very similar to what is done in the shader. + const projectedAnchorRight = projectTileCoordinatesToViewport(projectionContext.tileAnchorPoint.x + 1, projectionContext.tileAnchorPoint.y, projectionContext); + const east = projectedAnchorRight.point.sub(projectedAnchorPoint); + const angle = Math.atan(east.y / east.x) + (east.x < 0 ? Math.PI : 0); + return projectedAnchorPoint.add(shift.rotate(angle)); + } + else { + return projectedAnchorPoint.add(shift); + } + } +} +function updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, transform, labelPlaneMatrix, posMatrix, tileScale, size, updateTextFitIcon, projection, translation, unwrappedTileID, getElevation) { + const placedSymbols = bucket.text.placedSymbolArray; + const dynamicTextLayoutVertexArray = bucket.text.dynamicLayoutVertexArray; + const dynamicIconLayoutVertexArray = bucket.icon.dynamicLayoutVertexArray; + const placedTextShifts = {}; + dynamicTextLayoutVertexArray.clear(); + for (let s = 0; s < placedSymbols.length; s++) { + const symbol = placedSymbols.get(s); + const skipOrientation = bucket.allowVerticalPlacement && !symbol.placedOrientation; + const variableOffset = (!symbol.hidden && symbol.crossTileID && !skipOrientation) ? variableOffsets[symbol.crossTileID] : null; + if (!variableOffset) { + // These symbols are from a justification that is not being used, or a label that wasn't placed + // so we don't need to do the extra math to figure out what incremental shift to apply. + hideGlyphs(symbol.numGlyphs, dynamicTextLayoutVertexArray); + } + else { + const tileAnchor = new performance$1.P(symbol.anchorX, symbol.anchorY); + const projectionContext = { + getElevation, + width: transform.width, + height: transform.height, + labelPlaneMatrix, + lineVertexArray: null, + pitchWithMap, + projection, + projectionCache: null, + tileAnchorPoint: tileAnchor, + translation, + unwrappedTileID + }; + const projectedAnchor = pitchWithMap ? + project(tileAnchor.x, tileAnchor.y, posMatrix, getElevation) : + projectTileCoordinatesToViewport(tileAnchor.x, tileAnchor.y, projectionContext); + const perspectiveRatio = getPerspectiveRatio(transform.cameraToCenterDistance, projectedAnchor.signedDistanceFromCamera); + let renderTextSize = performance$1.ai(bucket.textSizeData, size, symbol) * perspectiveRatio / performance$1.ap; + if (pitchWithMap) { + // Go from size in pixels to equivalent size in tile units + renderTextSize *= bucket.tilePixelRatio / tileScale; + } + const { width, height, anchor, textOffset, textBoxScale } = variableOffset; + const shift = calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize); + const pitchedTextCorrection = projection.getPitchedTextCorrection(transform, tileAnchor.add(new performance$1.P(translation[0], translation[1])), unwrappedTileID); + const shiftedAnchor = getShiftedAnchor(projectedAnchor.point, projectionContext, rotateWithMap, shift, transform.angle, pitchedTextCorrection); + const angle = (bucket.allowVerticalPlacement && symbol.placedOrientation === performance$1.ah.vertical) ? Math.PI / 2 : 0; + for (let g = 0; g < symbol.numGlyphs; g++) { + performance$1.aj(dynamicTextLayoutVertexArray, shiftedAnchor, angle); + } + //Only offset horizontal text icons + if (updateTextFitIcon && symbol.associatedIconIndex >= 0) { + placedTextShifts[symbol.associatedIconIndex] = { shiftedAnchor, angle }; + } + } + } + if (updateTextFitIcon) { + dynamicIconLayoutVertexArray.clear(); + const placedIcons = bucket.icon.placedSymbolArray; + for (let i = 0; i < placedIcons.length; i++) { + const placedIcon = placedIcons.get(i); + if (placedIcon.hidden) { + hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray); + } + else { + const shift = placedTextShifts[i]; + if (!shift) { + hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray); + } + else { + for (let g = 0; g < placedIcon.numGlyphs; g++) { + performance$1.aj(dynamicIconLayoutVertexArray, shift.shiftedAnchor, shift.angle); + } + } + } + } + bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicIconLayoutVertexArray); + } + bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicTextLayoutVertexArray); +} +function getSymbolProgramName(isSDF, isText, bucket) { + if (bucket.iconsInText && isText) { + return 'symbolTextAndIcon'; + } + else if (isSDF) { + return 'symbolSDF'; + } + else { + return 'symbolIcon'; + } +} +function drawLayerSymbols(painter, sourceCache, layer, coords, isText, translate, translateAnchor, rotationAlignment, pitchAlignment, keepUpright, stencilMode, colorMode) { + const context = painter.context; + const gl = context.gl; + const tr = painter.transform; + const projection = createProjection(); + const rotateWithMap = rotationAlignment === 'map'; + const pitchWithMap = pitchAlignment === 'map'; + const alongLine = rotationAlignment !== 'viewport' && layer.layout.get('symbol-placement') !== 'point'; + // Line label rotation happens in `updateLineLabels` + // Pitched point labels are automatically rotated by the labelPlaneMatrix projection + // Unpitched point labels need to have their rotation applied after projection + const rotateInShader = rotateWithMap && !pitchWithMap && !alongLine; + const isViewportLine = !pitchWithMap && alongLine; + const hasSortKey = !layer.layout.get('symbol-sort-key').isConstant(); + let sortFeaturesByKey = false; + const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly); + const hasVariablePlacement = layer._unevaluatedLayout.hasValue('text-variable-anchor') || layer._unevaluatedLayout.hasValue('text-variable-anchor-offset'); + const tileRenderState = []; + const pitchedTextRescaling = projection.getCircleRadiusCorrection(tr); + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const buffers = isText ? bucket.text : bucket.icon; + if (!buffers || !buffers.segments.get().length || !buffers.hasVisibleVertices) + continue; + const programConfiguration = buffers.programConfigurations.get(layer.id); + const isSDF = isText || bucket.sdfIcons; + const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData; + const transformed = pitchWithMap || tr.pitch !== 0; + const program = painter.useProgram(getSymbolProgramName(isSDF, isText, bucket), programConfiguration); + const size = performance$1.ag(sizeData, tr.zoom); + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + let texSize; + let texSizeIcon = [0, 0]; + let atlasTexture; + let atlasInterpolation; + let atlasTextureIcon = null; + let atlasInterpolationIcon; + let atlasBackgroundTexture; + if (isText) { + atlasTexture = tile.glyphAtlasTexture; + atlasInterpolation = gl.LINEAR; + texSize = tile.glyphAtlasTexture.size; + if (bucket.iconsInText) { + texSizeIcon = tile.imageAtlasTexture.size; + atlasTextureIcon = tile.imageAtlasTexture; + const zoomDependentSize = sizeData.kind === 'composite' || sizeData.kind === 'camera'; + atlasInterpolationIcon = transformed || painter.options.rotating || painter.options.zooming || zoomDependentSize ? gl.LINEAR : gl.NEAREST; + } + } + else { + const iconScaled = layer.layout.get('icon-size').constantOr(0) !== 1 || bucket.iconsNeedLinear; + atlasTexture = tile.imageAtlasTexture; + atlasBackgroundTexture = tile.imageBackgroundsAtlasTexture; + atlasInterpolation = isSDF || painter.options.rotating || painter.options.zooming || iconScaled || transformed ? + gl.LINEAR : + gl.NEAREST; + texSize = tile.imageAtlasTexture.size; + } + const s = pixelsToTileUnits(tile, 1, painter.transform.zoom); + const baseMatrix = isViewportLine ? coord.posMatrix : identityMat4; + const labelPlaneMatrix = getLabelPlaneMatrix(baseMatrix, pitchWithMap, rotateWithMap, painter.transform, s); + const glCoordMatrixForShader = getGlCoordMatrix(baseMatrix, pitchWithMap, rotateWithMap, painter.transform, s); + const glCoordMatrixForSymbolPlacement = getGlCoordMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, s); + const translation = projection.translatePosition(painter.transform, tile, translate, translateAnchor); + const hasVariableAnchors = hasVariablePlacement && bucket.hasTextData(); + const updateTextFitIcon = layer.layout.get('icon-text-fit') !== 'none' && + hasVariableAnchors && + bucket.hasIconData(); + if (alongLine) { + const getElevation = painter.style.map.terrain ? (x, y) => painter.style.map.terrain.getElevation(coord, x, y) : null; + const rotateToLine = layer.layout.get('text-rotation-alignment') === 'map'; + updateLineLabels(bucket, coord.posMatrix, painter, isText, labelPlaneMatrix, glCoordMatrixForSymbolPlacement, pitchWithMap, keepUpright, rotateToLine, projection, coord.toUnwrapped(), tr.width, tr.height, translation, getElevation); + } + const matrix = coord.posMatrix; // formerly also incorporated translate and translate-anchor + const shaderVariableAnchor = (isText && hasVariablePlacement) || updateTextFitIcon; + const noLabelPlane = (alongLine || shaderVariableAnchor); + const uLabelPlaneMatrix = noLabelPlane ? identityMat4 : labelPlaneMatrix; + const uglCoordMatrix = glCoordMatrixForShader; // formerly also incorporated translate and translate-anchor + const hasHalo = isSDF && layer.paint.get(isText ? 'text-halo-width' : 'icon-halo-width').constantOr(1) !== 0; + let uniformValues; + if (isSDF) { + if (!bucket.iconsInText) { + uniformValues = symbolSDFUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, translation, isText, texSize, true, pitchedTextRescaling); + } + else { + uniformValues = symbolTextAndIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, translation, texSize, texSizeIcon, pitchedTextRescaling); + } + } + else { + uniformValues = symbolIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, translation, isText, texSize, pitchedTextRescaling); + } + const state = { + program, + buffers, + uniformValues, + atlasTexture, + atlasBackgroundTexture, + atlasTextureIcon, + atlasInterpolation, + atlasInterpolationIcon, + isSDF, + hasHalo + }; + if (hasSortKey && bucket.canOverlap) { + sortFeaturesByKey = true; + const oldSegments = buffers.segments.get(); + for (const segment of oldSegments) { + tileRenderState.push({ + segments: new performance$1.a0([segment]), + sortKey: segment.sortKey, + state, + terrainData + }); + } + } + else { + tileRenderState.push({ + segments: buffers.segments, + sortKey: 0, + state, + terrainData + }); + } + } + if (sortFeaturesByKey) { + tileRenderState.sort((a, b) => a.sortKey - b.sortKey); + } + for (const segmentState of tileRenderState) { + const state = segmentState.state; + context.activeTexture.set(gl.TEXTURE0); + state.atlasTexture.bind(state.atlasInterpolation, gl.CLAMP_TO_EDGE); + if (state.atlasTextureIcon || state.atlasBackgroundTexture) { + context.activeTexture.set(gl.TEXTURE1); + if (state.atlasTextureIcon) { + state.atlasTextureIcon.bind(state.atlasInterpolationIcon, gl.CLAMP_TO_EDGE); + } + if (state.atlasBackgroundTexture) { + state.atlasBackgroundTexture.bind(state.atlasInterpolation, gl.CLAMP_TO_EDGE); + } + } + if (state.isSDF) { + const uniformValues = state.uniformValues; + if (state.hasHalo) { + uniformValues['u_is_halo'] = 1; + drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, uniformValues, segmentState.terrainData); + } + uniformValues['u_is_halo'] = 0; + } + drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, state.uniformValues, segmentState.terrainData); + } +} +function drawSymbolElements(buffers, segments, layer, painter, program, depthMode, stencilMode, colorMode, uniformValues, terrainData) { + const context = painter.context; + const gl = context.gl; + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer, segments, layer.paint, painter.transform.zoom, buffers.programConfigurations.get(layer.id), buffers.dynamicLayoutVertexBuffer, buffers.opacityVertexBuffer); +} + +function drawCircles(painter, sourceCache, layer, coords) { + if (painter.renderPass !== 'translucent') + return; + const opacity = layer.paint.get('circle-opacity'); + const strokeWidth = layer.paint.get('circle-stroke-width'); + const strokeOpacity = layer.paint.get('circle-stroke-opacity'); + const sortFeaturesByKey = !layer.layout.get('circle-sort-key').isConstant(); + if (opacity.constantOr(1) === 0 && (strokeWidth.constantOr(1) === 0 || strokeOpacity.constantOr(1) === 0)) { + return; + } + const context = painter.context; + const gl = context.gl; + const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly); + // Turn off stencil testing to allow circles to be drawn across boundaries, + // so that large circles are not clipped to tiles + const stencilMode = StencilMode.disabled; + const colorMode = painter.colorModeForRenderPass(); + const segmentsRenderStates = []; + for (let i = 0; i < coords.length; i++) { + const coord = coords[i]; + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram('circle', programConfiguration); + const layoutVertexBuffer = bucket.layoutVertexBuffer; + const indexBuffer = bucket.indexBuffer; + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + const uniformValues = circleUniformValues(painter, coord, tile, layer); + const state = { + programConfiguration, + program, + layoutVertexBuffer, + indexBuffer, + uniformValues, + terrainData + }; + if (sortFeaturesByKey) { + const oldSegments = bucket.segments.get(); + for (const segment of oldSegments) { + segmentsRenderStates.push({ + segments: new performance$1.a0([segment]), + sortKey: segment.sortKey, + state + }); + } + } + else { + segmentsRenderStates.push({ + segments: bucket.segments, + sortKey: 0, + state + }); + } + } + if (sortFeaturesByKey) { + segmentsRenderStates.sort((a, b) => a.sortKey - b.sortKey); + } + for (const segmentsState of segmentsRenderStates) { + const { programConfiguration, program, layoutVertexBuffer, indexBuffer, uniformValues, terrainData } = segmentsState.state; + const segments = segmentsState.segments; + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, layoutVertexBuffer, indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration); + } +} + +function drawHeatmap(painter, sourceCache, layer, tileIDs) { + if (layer.paint.get('heatmap-opacity') === 0) { + return; + } + const context = painter.context; + if (painter.style.map.terrain) { + for (const coord of tileIDs) { + const tile = sourceCache.getTile(coord); + // Skip tiles that have uncovered parents to avoid flickering; we don't need + // to use complex tile masking here because the change between zoom levels is subtle, + // so it's fine to simply render the parent until all its 4 children are loaded + if (sourceCache.hasRenderableParent(coord)) + continue; + if (painter.renderPass === 'offscreen') { + prepareHeatmapTerrain(painter, tile, layer, coord); + } + else if (painter.renderPass === 'translucent') { + renderHeatmapTerrain(painter, layer, coord); + } + } + context.viewport.set([0, 0, painter.width, painter.height]); + } + else { + if (painter.renderPass === 'offscreen') { + prepareHeatmapFlat(painter, sourceCache, layer, tileIDs); + } + else if (painter.renderPass === 'translucent') { + renderHeatmapFlat(painter, layer); + } + } +} +function prepareHeatmapFlat(painter, sourceCache, layer, coords) { + const context = painter.context; + const gl = context.gl; + // Allow kernels to be drawn across boundaries, so that + // large kernels are not clipped to tiles + const stencilMode = StencilMode.disabled; + // Turn on additive blending for kernels, which is a key aspect of kernel density estimation formula + const colorMode = new ColorMode([gl.ONE, gl.ONE], performance$1.aM.transparent, [true, true, true, true]); + bindFramebuffer(context, painter, layer); + context.clear({ color: performance$1.aM.transparent }); + for (let i = 0; i < coords.length; i++) { + const coord = coords[i]; + // Skip tiles that have uncovered parents to avoid flickering; we don't need + // to use complex tile masking here because the change between zoom levels is subtle, + // so it's fine to simply render the parent until all its 4 children are loaded + if (sourceCache.hasRenderableParent(coord)) + continue; + const tile = sourceCache.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram('heatmap', programConfiguration); + const { zoom } = painter.transform; + program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.disabled, heatmapUniformValues(coord.posMatrix, tile, zoom, layer.paint.get('heatmap-intensity')), null, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration); + } + context.viewport.set([0, 0, painter.width, painter.height]); +} +function renderHeatmapFlat(painter, layer) { + const context = painter.context; + const gl = context.gl; + context.setColorMode(painter.colorModeForRenderPass()); + // Here we bind two different textures from which we'll sample in drawing + // heatmaps: the kernel texture, prepared in the offscreen pass, and a + // color ramp texture. + const fbo = layer.heatmapFbos.get(performance$1.aU); + if (!fbo) + return; + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get()); + context.activeTexture.set(gl.TEXTURE1); + const colorRampTexture = getColorRampTexture(context, layer); + colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + painter.useProgram('heatmapTexture').draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, heatmapTextureUniformValues(painter, layer, 0, 1), null, layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer, painter.viewportSegments, layer.paint, painter.transform.zoom); +} +function prepareHeatmapTerrain(painter, tile, layer, coord) { + const context = painter.context; + const gl = context.gl; + const stencilMode = StencilMode.disabled; + // Turn on additive blending for kernels, which is a key aspect of kernel density estimation formula + const colorMode = new ColorMode([gl.ONE, gl.ONE], performance$1.aM.transparent, [true, true, true, true]); + const bucket = tile.getBucket(layer); + if (!bucket) + return; + const tileKey = coord.key; + let fbo = layer.heatmapFbos.get(tileKey); + if (!fbo) { + fbo = createHeatmapFbo(context, tile.tileSize, tile.tileSize); + layer.heatmapFbos.set(tileKey, fbo); + } + context.bindFramebuffer.set(fbo.framebuffer); + context.viewport.set([0, 0, tile.tileSize, tile.tileSize]); + context.clear({ color: performance$1.aM.transparent }); + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram('heatmap', programConfiguration); + const terrainData = painter.style.map.terrain.getTerrainData(coord); + program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.disabled, heatmapUniformValues(coord.posMatrix, tile, painter.transform.zoom, layer.paint.get('heatmap-intensity')), terrainData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration); +} +function renderHeatmapTerrain(painter, layer, coord) { + const context = painter.context; + const gl = context.gl; + context.setColorMode(painter.colorModeForRenderPass()); + const colorRampTexture = getColorRampTexture(context, layer); + // Here we bind two different textures from which we'll sample in drawing + // heatmaps: the kernel texture, prepared in the offscreen pass, and a + // color ramp texture. + const tileKey = coord.key; + const fbo = layer.heatmapFbos.get(tileKey); + if (!fbo) + return; + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get()); + context.activeTexture.set(gl.TEXTURE1); + colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + painter.useProgram('heatmapTexture').draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, heatmapTextureUniformValues(painter, layer, 0, 1), null, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments, layer.paint, painter.transform.zoom); + // destroy the FBO after rendering + fbo.destroy(); + layer.heatmapFbos.delete(tileKey); +} +function bindFramebuffer(context, painter, layer) { + const gl = context.gl; + context.activeTexture.set(gl.TEXTURE1); + // Use a 4x downscaled screen texture for better performance + context.viewport.set([0, 0, painter.width / 4, painter.height / 4]); + let fbo = layer.heatmapFbos.get(performance$1.aU); + if (!fbo) { + fbo = createHeatmapFbo(context, painter.width / 4, painter.height / 4); + layer.heatmapFbos.set(performance$1.aU, fbo); + } + else { + gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get()); + context.bindFramebuffer.set(fbo.framebuffer); + } +} +function createHeatmapFbo(context, width, height) { + var _a, _b; + const gl = context.gl; + const texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + // Use the higher precision half-float texture where available (producing much smoother looking heatmaps); + // Otherwise, fall back to a low precision texture + const numType = (_a = context.HALF_FLOAT) !== null && _a !== void 0 ? _a : gl.UNSIGNED_BYTE; + const internalFormat = (_b = context.RGBA16F) !== null && _b !== void 0 ? _b : gl.RGBA; + gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, width, height, 0, gl.RGBA, numType, null); + const fbo = context.createFramebuffer(width, height, false, false); + fbo.colorAttachment.set(texture); + return fbo; +} +function getColorRampTexture(context, layer) { + if (!layer.colorRampTexture) { + layer.colorRampTexture = new Texture(context, layer.colorRamp, context.gl.RGBA); + } + return layer.colorRampTexture; +} + +function drawLine(painter, sourceCache, layer, coords) { + if (painter.renderPass !== 'translucent') + return; + const opacity = layer.paint.get('line-opacity'); + const width = layer.paint.get('line-width'); + if (opacity.constantOr(1) === 0 || width.constantOr(1) === 0) + return; + const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly); + const colorMode = painter.colorModeForRenderPass(); + const dasharray = layer.paint.get('line-dasharray'); + const patternProperty = layer.paint.get('line-pattern'); + const image = patternProperty.constantOr(1); + const gradient = layer.paint.get('line-gradient'); + const crossfade = layer.getCrossfadeParameters(); + const programId = image ? 'linePattern' : + dasharray ? 'lineSDF' : + gradient ? 'lineGradient' : 'line'; + const context = painter.context; + const gl = context.gl; + let firstTile = true; + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + if (image && !tile.patternsLoaded()) + continue; + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const programConfiguration = bucket.programConfigurations.get(layer.id); + const prevProgram = painter.context.program.get(); + const program = painter.useProgram(programId, programConfiguration); + const programChanged = firstTile || program.program !== prevProgram; + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + const constantPattern = patternProperty.constantOr(null); + if (constantPattern && tile.imageAtlas) { + const atlas = tile.imageAtlas; + const posTo = atlas.patternPositions[constantPattern.to.toString()]; + const posFrom = atlas.patternPositions[constantPattern.from.toString()]; + if (posTo && posFrom) + programConfiguration.setConstantPatternPositions(posTo, posFrom); + } + const terrainCoord = terrainData ? coord : null; + const uniformValues = image ? linePatternUniformValues(painter, tile, layer, crossfade, terrainCoord) : + dasharray ? lineSDFUniformValues(painter, tile, layer, dasharray, crossfade, terrainCoord) : + gradient ? lineGradientUniformValues(painter, tile, layer, bucket.lineClipsArray.length, terrainCoord) : + lineUniformValues(painter, tile, layer, terrainCoord); + if (image) { + context.activeTexture.set(gl.TEXTURE0); + tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + programConfiguration.updatePaintBuffers(crossfade); + } + else if (dasharray && (programChanged || painter.lineAtlas.dirty)) { + context.activeTexture.set(gl.TEXTURE0); + painter.lineAtlas.bind(context); + } + else if (gradient) { + const layerGradient = bucket.gradients[layer.id]; + let gradientTexture = layerGradient.texture; + if (layer.gradientVersion !== layerGradient.version) { + let textureResolution = 256; + if (layer.stepInterpolant) { + const sourceMaxZoom = sourceCache.getSource().maxzoom; + const potentialOverzoom = coord.canonical.z === sourceMaxZoom ? + Math.ceil(1 << (painter.transform.maxZoom - coord.canonical.z)) : 1; + const lineLength = bucket.maxLineLength / performance$1.X; + // Logical pixel tile size is 512px, and 1024px right before current zoom + 1 + const maxTilePixelSize = 1024; + // Maximum possible texture coverage heuristic, bound by hardware max texture size + const maxTextureCoverage = lineLength * maxTilePixelSize * potentialOverzoom; + textureResolution = performance$1.ac(performance$1.aV(maxTextureCoverage), 256, context.maxTextureSize); + } + layerGradient.gradient = performance$1.aW({ + expression: layer.gradientExpression(), + evaluationKey: 'lineProgress', + resolution: textureResolution, + image: layerGradient.gradient || undefined, + clips: bucket.lineClipsArray + }); + if (layerGradient.texture) { + layerGradient.texture.update(layerGradient.gradient); + } + else { + layerGradient.texture = new Texture(context, layerGradient.gradient, gl.RGBA); + } + layerGradient.version = layer.gradientVersion; + gradientTexture = layerGradient.texture; + } + context.activeTexture.set(gl.TEXTURE0); + gradientTexture.bind(layer.stepInterpolant ? gl.NEAREST : gl.LINEAR, gl.CLAMP_TO_EDGE); + } + program.draw(context, gl.TRIANGLES, depthMode, painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration, bucket.layoutVertexBuffer2); + firstTile = false; + // once refactored so that bound texture state is managed, we'll also be able to remove this firstTile/programChanged logic + } +} + +/** + * A simple helper shared by draw_fill and draw_fill_extrusions to find the correct pattern positions AND update program. + * For transitionable properties, especially 'fill-pattern' and 'fill-extrusion-pattern', while rendering certain frames + * tile.imageAtlas has been updated by worker to hold the new pattern only, but rendering code is still looking for the previous image. + * The mismatch was causing setConstantPatternPositions method not being called and pixelRatio was always the + * default of 1, instead of actual values set by original map.addImage. + * + * @param programConfiguration - to be used to set pattern position and device pixel ratio. + * @param propertyName - 'fill-pattern' or 'fill-extrusion-pattern' property key + * @param constantPattern - either 'fill-pattern' or 'fill-extrusion-pattern' property value + * @param tile - current tile being drawn + * @param layer - current layer being rendered + */ +function updatePatternPositionsInProgram(programConfiguration, propertyName, constantPattern, tile, layer) { + if (!constantPattern || !tile || !tile.imageAtlas) { + return; + } + const patternPositions = tile.imageAtlas.patternPositions; + let posTo = patternPositions[constantPattern.to.toString()]; + let posFrom = patternPositions[constantPattern.from.toString()]; + // https://github.com/maplibre/maplibre-gl-js/issues/3377 + if (!posTo && posFrom) + posTo = posFrom; + if (!posFrom && posTo) + posFrom = posTo; + // try again in case patternPositions has been updated by worker + if (!posTo || !posFrom) { + const transitioned = layer.getPaintProperty(propertyName); + posTo = patternPositions[transitioned]; + posFrom = patternPositions[transitioned]; + } + if (posTo && posFrom) { + programConfiguration.setConstantPatternPositions(posTo, posFrom); + } +} + +function drawFill(painter, sourceCache, layer, coords) { + const color = layer.paint.get('fill-color'); + const opacity = layer.paint.get('fill-opacity'); + if (opacity.constantOr(1) === 0) { + return; + } + const colorMode = painter.colorModeForRenderPass(); + const pattern = layer.paint.get('fill-pattern'); + const pass = painter.opaquePassEnabledForLayer() && + (!pattern.constantOr(1) && + color.constantOr(performance$1.aM.transparent).a === 1 && + opacity.constantOr(0) === 1) ? 'opaque' : 'translucent'; + // Draw fill + if (painter.renderPass === pass) { + const depthMode = painter.depthModeForSublayer(1, painter.renderPass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly); + drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, false); + } + // Draw stroke + if (painter.renderPass === 'translucent' && layer.paint.get('fill-antialias')) { + // If we defined a different color for the fill outline, we are + // going to ignore the bits in 0x07 and just care about the global + // clipping mask. + // Otherwise, we only want to drawFill the antialiased parts that are + // *outside* the current shape. This is important in case the fill + // or stroke color is translucent. If we wouldn't clip to outside + // the current shape, some pixels from the outline stroke overlapped + // the (non-antialiased) fill. + const depthMode = painter.depthModeForSublayer(layer.getPaintProperty('fill-outline-color') ? 2 : 0, DepthMode.ReadOnly); + drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, true); + } +} +function drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, isOutline) { + const gl = painter.context.gl; + const fillPropertyName = 'fill-pattern'; + const patternProperty = layer.paint.get(fillPropertyName); + const image = patternProperty && patternProperty.constantOr(1); + const crossfade = layer.getCrossfadeParameters(); + let drawMode, programName, uniformValues, indexBuffer, segments; + if (!isOutline) { + programName = image ? 'fillPattern' : 'fill'; + drawMode = gl.TRIANGLES; + } + else { + programName = image && !layer.getPaintProperty('fill-outline-color') ? 'fillOutlinePattern' : 'fillOutline'; + drawMode = gl.LINES; + } + const constantPattern = patternProperty.constantOr(null); + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + if (image && !tile.patternsLoaded()) + continue; + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram(programName, programConfiguration); + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + if (image) { + painter.context.activeTexture.set(gl.TEXTURE0); + tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + programConfiguration.updatePaintBuffers(crossfade); + } + updatePatternPositionsInProgram(programConfiguration, fillPropertyName, constantPattern, tile, layer); + const terrainCoord = terrainData ? coord : null; + const posMatrix = terrainCoord ? terrainCoord.posMatrix : coord.posMatrix; + const tileMatrix = painter.translatePosMatrix(posMatrix, tile, layer.paint.get('fill-translate'), layer.paint.get('fill-translate-anchor')); + if (!isOutline) { + indexBuffer = bucket.indexBuffer; + segments = bucket.segments; + uniformValues = image ? + fillPatternUniformValues(tileMatrix, painter, crossfade, tile) : + fillUniformValues(tileMatrix); + } + else { + indexBuffer = bucket.indexBuffer2; + segments = bucket.segments2; + const drawingBufferSize = [gl.drawingBufferWidth, gl.drawingBufferHeight]; + uniformValues = (programName === 'fillOutlinePattern' && image) ? + fillOutlinePatternUniformValues(tileMatrix, painter, crossfade, tile, drawingBufferSize) : + fillOutlineUniformValues(tileMatrix, drawingBufferSize); + } + program.draw(painter.context, drawMode, depthMode, painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, bucket.layoutVertexBuffer, indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration); + } +} + +function drawFillExtrusion(painter, source, layer, coords) { + const opacity = layer.paint.get('fill-extrusion-opacity'); + if (opacity === 0) { + return; + } + if (painter.renderPass === 'translucent') { + const depthMode = new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D); + if (opacity === 1 && !layer.paint.get('fill-extrusion-pattern').constantOr(1)) { + const colorMode = painter.colorModeForRenderPass(); + drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, colorMode); + } + else { + // Draw transparent buildings in two passes so that only the closest surface is drawn. + // First draw all the extrusions into only the depth buffer. No colors are drawn. + drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, ColorMode.disabled); + // Then draw all the extrusions a second type, only coloring fragments if they have the + // same depth value as the closest fragment in the previous pass. Use the stencil buffer + // to prevent the second draw in cases where we have coincident polygons. + drawExtrusionTiles(painter, source, layer, coords, depthMode, painter.stencilModeFor3D(), painter.colorModeForRenderPass()); + } + } +} +function drawExtrusionTiles(painter, source, layer, coords, depthMode, stencilMode, colorMode) { + const context = painter.context; + const gl = context.gl; + const fillPropertyName = 'fill-extrusion-pattern'; + const patternProperty = layer.paint.get(fillPropertyName); + const image = patternProperty.constantOr(1); + const crossfade = layer.getCrossfadeParameters(); + const opacity = layer.paint.get('fill-extrusion-opacity'); + const constantPattern = patternProperty.constantOr(null); + for (const coord of coords) { + const tile = source.getTile(coord); + const bucket = tile.getBucket(layer); + if (!bucket) + continue; + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + const programConfiguration = bucket.programConfigurations.get(layer.id); + const program = painter.useProgram(image ? 'fillExtrusionPattern' : 'fillExtrusion', programConfiguration); + if (image) { + painter.context.activeTexture.set(gl.TEXTURE0); + tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + programConfiguration.updatePaintBuffers(crossfade); + } + updatePatternPositionsInProgram(programConfiguration, fillPropertyName, constantPattern, tile, layer); + const matrix = painter.translatePosMatrix(coord.posMatrix, tile, layer.paint.get('fill-extrusion-translate'), layer.paint.get('fill-extrusion-translate-anchor')); + const shouldUseVerticalGradient = layer.paint.get('fill-extrusion-vertical-gradient'); + const uniformValues = image ? + fillExtrusionPatternUniformValues(matrix, painter, shouldUseVerticalGradient, opacity, coord, crossfade, tile) : + fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity); + program.draw(context, context.gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration, painter.style.map.terrain && bucket.centroidVertexBuffer); + } +} + +function drawHillshade(painter, sourceCache, layer, tileIDs) { + if (painter.renderPass !== 'offscreen' && painter.renderPass !== 'translucent') + return; + const context = painter.context; + const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly); + const colorMode = painter.colorModeForRenderPass(); + const [stencilModes, coords] = painter.renderPass === 'translucent' ? + painter.stencilConfigForOverlap(tileIDs) : [{}, tileIDs]; + for (const coord of coords) { + const tile = sourceCache.getTile(coord); + if (typeof tile.needsHillshadePrepare !== 'undefined' && tile.needsHillshadePrepare && painter.renderPass === 'offscreen') { + prepareHillshade(painter, tile, layer, depthMode, StencilMode.disabled, colorMode); + } + else if (painter.renderPass === 'translucent') { + renderHillshade(painter, coord, tile, layer, depthMode, stencilModes[coord.overscaledZ], colorMode); + } + } + context.viewport.set([0, 0, painter.width, painter.height]); +} +function renderHillshade(painter, coord, tile, layer, depthMode, stencilMode, colorMode) { + const context = painter.context; + const gl = context.gl; + const fbo = tile.fbo; + if (!fbo) + return; + const program = painter.useProgram('hillshade'); + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get()); + const terrainCoord = terrainData ? coord : null; + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, hillshadeUniformValues(painter, tile, layer, terrainCoord), terrainData, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments); +} +// hillshade rendering is done in two steps. the prepare step first calculates the slope of the terrain in the x and y +// directions for each pixel, and saves those values to a framebuffer texture in the r and g channels. +function prepareHillshade(painter, tile, layer, depthMode, stencilMode, colorMode) { + const context = painter.context; + const gl = context.gl; + const dem = tile.dem; + if (dem && dem.data) { + const tileSize = dem.dim; + const textureStride = dem.stride; + const pixelData = dem.getPixels(); + context.activeTexture.set(gl.TEXTURE1); + context.pixelStoreUnpackPremultiplyAlpha.set(false); + tile.demTexture = tile.demTexture || painter.getTileTexture(textureStride); + if (tile.demTexture) { + const demTexture = tile.demTexture; + demTexture.update(pixelData, { premultiply: false }); + demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE); + } + else { + tile.demTexture = new Texture(context, pixelData, gl.RGBA, { premultiply: false }); + tile.demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE); + } + context.activeTexture.set(gl.TEXTURE0); + let fbo = tile.fbo; + if (!fbo) { + const renderTexture = new Texture(context, { width: tileSize, height: tileSize, data: null }, gl.RGBA); + renderTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + fbo = tile.fbo = context.createFramebuffer(tileSize, tileSize, true, false); + fbo.colorAttachment.set(renderTexture.texture); + } + context.bindFramebuffer.set(fbo.framebuffer); + context.viewport.set([0, 0, tileSize, tileSize]); + painter.useProgram('hillshadePrepare').draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, hillshadeUniformPrepareValues(tile.tileID, dem), null, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments); + tile.needsHillshadePrepare = false; + } +} + +function drawRaster(painter, sourceCache, layer, tileIDs) { + if (painter.renderPass !== 'translucent') + return; + if (layer.paint.get('raster-opacity') === 0) + return; + if (!tileIDs.length) + return; + const context = painter.context; + const gl = context.gl; + const source = sourceCache.getSource(); + const program = painter.useProgram('raster'); + const colorMode = painter.colorModeForRenderPass(); + const [stencilModes, coords] = source instanceof ImageSource ? [{}, tileIDs] : + painter.stencilConfigForOverlap(tileIDs); + const minTileZ = coords[coords.length - 1].overscaledZ; + const align = !painter.options.moving; + for (const coord of coords) { + // Set the lower zoom level to sublayer 0, and higher zoom levels to higher sublayers + // Use gl.LESS to prevent double drawing in areas where tiles overlap. + const depthMode = painter.depthModeForSublayer(coord.overscaledZ - minTileZ, layer.paint.get('raster-opacity') === 1 ? DepthMode.ReadWrite : DepthMode.ReadOnly, gl.LESS); + const tile = sourceCache.getTile(coord); + tile.registerFadeDuration(layer.paint.get('raster-fade-duration')); + const parentTile = sourceCache.findLoadedParent(coord, 0); + const siblingTile = sourceCache.findLoadedSibling(coord); + // Prefer parent tile if present + const fadeTileReference = parentTile || siblingTile || null; + const fade = getFadeValues(tile, fadeTileReference, sourceCache, layer, painter.transform, painter.style.map.terrain); + let parentScaleBy, parentTL; + const textureFilter = layer.paint.get('raster-resampling') === 'nearest' ? gl.NEAREST : gl.LINEAR; + context.activeTexture.set(gl.TEXTURE0); + tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST); + context.activeTexture.set(gl.TEXTURE1); + if (parentTile) { + parentTile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST); + parentScaleBy = Math.pow(2, parentTile.tileID.overscaledZ - tile.tileID.overscaledZ); + parentTL = [tile.tileID.canonical.x * parentScaleBy % 1, tile.tileID.canonical.y * parentScaleBy % 1]; + } + else { + tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST); + } + // Enable anisotropic filtering only when the pitch is greater than 20 degrees + // to preserve image sharpness on flat or slightly tilted maps. + if (tile.texture.useMipmap && context.extTextureFilterAnisotropic && painter.transform.pitch > 20) { + gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax); + } + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + const terrainCoord = terrainData ? coord : null; + const posMatrix = terrainCoord ? terrainCoord.posMatrix : painter.transform.calculatePosMatrix(coord.toUnwrapped(), align); + const uniformValues = rasterUniformValues(posMatrix, parentTL || [0, 0], parentScaleBy || 1, fade, layer); + if (source instanceof ImageSource) { + program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, source.boundsBuffer, painter.quadTriangleIndexBuffer, source.boundsSegments); + } + else { + program.draw(context, gl.TRIANGLES, depthMode, stencilModes[coord.overscaledZ], colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments); + } + } +} +function getFadeValues(tile, parentTile, sourceCache, layer, transform, terrain) { + const fadeDuration = layer.paint.get('raster-fade-duration'); + if (!terrain && fadeDuration > 0) { + const now = browser.now(); + const sinceTile = (now - tile.timeAdded) / fadeDuration; + const sinceParent = parentTile ? (now - parentTile.timeAdded) / fadeDuration : -1; + const source = sourceCache.getSource(); + const idealZ = transform.coveringZoomLevel({ + tileSize: source.tileSize, + roundZoom: source.roundZoom + }); + // if no parent or parent is older, fade in; if parent is younger, fade out + const fadeIn = !parentTile || Math.abs(parentTile.tileID.overscaledZ - idealZ) > Math.abs(tile.tileID.overscaledZ - idealZ); + const childOpacity = (fadeIn && tile.refreshedUponExpiration) ? 1 : performance$1.ac(fadeIn ? sinceTile : 1 - sinceParent, 0, 1); + // we don't crossfade tiles that were just refreshed upon expiring: + // once they're old enough to pass the crossfading threshold + // (fadeDuration), unset the `refreshedUponExpiration` flag so we don't + // incorrectly fail to crossfade them when zooming + if (tile.refreshedUponExpiration && sinceTile >= 1) + tile.refreshedUponExpiration = false; + if (parentTile) { + return { + opacity: 1, + mix: 1 - childOpacity + }; + } + else { + return { + opacity: childOpacity, + mix: 0 + }; + } + } + else { + return { + opacity: 1, + mix: 0 + }; + } +} + +function drawBackground(painter, sourceCache, layer, coords) { + const color = layer.paint.get('background-color'); + const opacity = layer.paint.get('background-opacity'); + if (opacity === 0) + return; + const context = painter.context; + const gl = context.gl; + const transform = painter.transform; + const tileSize = transform.tileSize; + const image = layer.paint.get('background-pattern'); + if (painter.isPatternMissing(image)) + return; + const pass = (!image && color.a === 1 && opacity === 1 && painter.opaquePassEnabledForLayer()) ? 'opaque' : 'translucent'; + if (painter.renderPass !== pass) + return; + const stencilMode = StencilMode.disabled; + const depthMode = painter.depthModeForSublayer(0, pass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly); + const colorMode = painter.colorModeForRenderPass(); + const program = painter.useProgram(image ? 'backgroundPattern' : 'background'); + const tileIDs = coords ? coords : transform.coveringTiles({ tileSize, terrain: painter.style.map.terrain }); + if (image) { + context.activeTexture.set(gl.TEXTURE0); + painter.imageManager.bind(painter.context); + } + const crossfade = layer.getCrossfadeParameters(); + for (const tileID of tileIDs) { + const matrix = coords ? tileID.posMatrix : painter.transform.calculatePosMatrix(tileID.toUnwrapped()); + const uniformValues = image ? + backgroundPatternUniformValues(matrix, opacity, painter, image, { tileID, tileSize }, crossfade) : + backgroundUniformValues(matrix, opacity, color); + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(tileID); + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, terrainData, layer.id, painter.tileExtentBuffer, painter.quadTriangleIndexBuffer, painter.tileExtentSegments); + } +} + +const topColor = new performance$1.aM(1, 0, 0, 1); +const btmColor = new performance$1.aM(0, 1, 0, 1); +const leftColor = new performance$1.aM(0, 0, 1, 1); +const rightColor = new performance$1.aM(1, 0, 1, 1); +const centerColor = new performance$1.aM(0, 1, 1, 1); +function drawDebugPadding(painter) { + const padding = painter.transform.padding; + const lineWidth = 3; + // Top + drawHorizontalLine(painter, painter.transform.height - (padding.top || 0), lineWidth, topColor); + // Bottom + drawHorizontalLine(painter, padding.bottom || 0, lineWidth, btmColor); + // Left + drawVerticalLine(painter, padding.left || 0, lineWidth, leftColor); + // Right + drawVerticalLine(painter, painter.transform.width - (padding.right || 0), lineWidth, rightColor); + // Center + const center = painter.transform.centerPoint; + drawCrosshair(painter, center.x, painter.transform.height - center.y, centerColor); +} +function drawCrosshair(painter, x, y, color) { + const size = 20; + const lineWidth = 2; + //Vertical line + drawDebugSSRect(painter, x - lineWidth / 2, y - size / 2, lineWidth, size, color); + //Horizontal line + drawDebugSSRect(painter, x - size / 2, y - lineWidth / 2, size, lineWidth, color); +} +function drawHorizontalLine(painter, y, lineWidth, color) { + drawDebugSSRect(painter, 0, y + lineWidth / 2, painter.transform.width, lineWidth, color); +} +function drawVerticalLine(painter, x, lineWidth, color) { + drawDebugSSRect(painter, x - lineWidth / 2, 0, lineWidth, painter.transform.height, color); +} +function drawDebugSSRect(painter, x, y, width, height, color) { + const context = painter.context; + const gl = context.gl; + gl.enable(gl.SCISSOR_TEST); + gl.scissor(x * painter.pixelRatio, y * painter.pixelRatio, width * painter.pixelRatio, height * painter.pixelRatio); + context.clear({ color }); + gl.disable(gl.SCISSOR_TEST); +} +function drawDebug(painter, sourceCache, coords) { + for (let i = 0; i < coords.length; i++) { + drawDebugTile(painter, sourceCache, coords[i]); + } +} +function drawDebugTile(painter, sourceCache, coord) { + const context = painter.context; + const gl = context.gl; + const posMatrix = coord.posMatrix; + const program = painter.useProgram('debug'); + const depthMode = DepthMode.disabled; + const stencilMode = StencilMode.disabled; + const colorMode = painter.colorModeForRenderPass(); + const id = '$debug'; + const terrainData = painter.style.map.terrain && painter.style.map.terrain.getTerrainData(coord); + context.activeTexture.set(gl.TEXTURE0); + const tileRawData = sourceCache.getTileByID(coord.key).latestRawTileData; + const tileByteLength = (tileRawData && tileRawData.byteLength) || 0; + const tileSizeKb = Math.floor(tileByteLength / 1024); + const tileSize = sourceCache.getTile(coord).tileSize; + const scaleRatio = (512 / Math.min(tileSize, 512) * (coord.overscaledZ / painter.transform.zoom)) * 0.5; + let tileIdText = coord.canonical.toString(); + if (coord.overscaledZ !== coord.canonical.z) { + tileIdText += ` => ${coord.overscaledZ}`; + } + const tileLabel = `${tileIdText} ${tileSizeKb}kB`; + drawTextToOverlay(painter, tileLabel); + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, ColorMode.alphaBlended, CullFaceMode.disabled, debugUniformValues(posMatrix, performance$1.aM.transparent, scaleRatio), null, id, painter.debugBuffer, painter.quadTriangleIndexBuffer, painter.debugSegments); + program.draw(context, gl.LINE_STRIP, depthMode, stencilMode, colorMode, CullFaceMode.disabled, debugUniformValues(posMatrix, performance$1.aM.red), terrainData, id, painter.debugBuffer, painter.tileBorderIndexBuffer, painter.debugSegments); +} +function drawTextToOverlay(painter, text) { + painter.initDebugOverlayCanvas(); + const canvas = painter.debugOverlayCanvas; + const gl = painter.context.gl; + const ctx2d = painter.debugOverlayCanvas.getContext('2d'); + ctx2d.clearRect(0, 0, canvas.width, canvas.height); + ctx2d.shadowColor = 'white'; + ctx2d.shadowBlur = 2; + ctx2d.lineWidth = 1.5; + ctx2d.strokeStyle = 'white'; + ctx2d.textBaseline = 'top'; + ctx2d.font = `bold ${36}px Open Sans, sans-serif`; + ctx2d.fillText(text, 5, 5); + ctx2d.strokeText(text, 5, 5); + painter.debugOverlayTexture.update(canvas); + painter.debugOverlayTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); +} +function selectDebugSource(style, zoom) { + // Use vector source with highest maxzoom + // Else use source with highest maxzoom of any type + let selectedSource = null; + const layers = Object.values(style._layers); + const sources = layers.flatMap((layer) => { + if (layer.source && !layer.isHidden(zoom)) { + const sourceCache = style.sourceCaches[layer.source]; + return [sourceCache]; + } + else { + return []; + } + }); + const vectorSources = sources.filter((source) => source.getSource().type === 'vector'); + const otherSources = sources.filter((source) => source.getSource().type !== 'vector'); + const considerSource = (source) => { + if (!selectedSource || (selectedSource.getSource().maxzoom < source.getSource().maxzoom)) { + selectedSource = source; + } + }; + vectorSources.forEach((source) => considerSource(source)); + if (!selectedSource) { + otherSources.forEach((source) => considerSource(source)); + } + return selectedSource; +} + +function drawCustom(painter, sourceCache, layer) { + const context = painter.context; + const implementation = layer.implementation; + if (painter.renderPass === 'offscreen') { + const prerender = implementation.prerender; + if (prerender) { + painter.setCustomLayerDefaults(); + context.setColorMode(painter.colorModeForRenderPass()); + prerender.call(implementation, context.gl, painter.transform.customLayerMatrix()); + context.setDirty(); + painter.setBaseState(); + } + } + else if (painter.renderPass === 'translucent') { + painter.setCustomLayerDefaults(); + context.setColorMode(painter.colorModeForRenderPass()); + context.setStencilMode(StencilMode.disabled); + const depthMode = implementation.renderingMode === '3d' ? + new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D) : + painter.depthModeForSublayer(0, DepthMode.ReadOnly); + context.setDepthMode(depthMode); + implementation.render(context.gl, painter.transform.customLayerMatrix(), { farZ: painter.transform.farZ, nearZ: painter.transform.nearZ, fov: painter.transform._fov, modelViewProjectionMatrix: painter.transform.modelViewProjectionMatrix, projectionMatrix: painter.transform.projectionMatrix }); + context.setDirty(); + painter.setBaseState(); + context.bindFramebuffer.set(null); + } +} + +/** + * Redraw the Depth Framebuffer + * @param painter - the painter + * @param terrain - the terrain + */ +function drawDepth(painter, terrain) { + const context = painter.context; + const gl = context.gl; + const colorMode = ColorMode.unblended; + const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]); + const mesh = terrain.getTerrainMesh(); + const tiles = terrain.sourceCache.getRenderableTiles(); + const program = painter.useProgram('terrainDepth'); + context.bindFramebuffer.set(terrain.getFramebuffer('depth').framebuffer); + context.viewport.set([0, 0, painter.width / devicePixelRatio, painter.height / devicePixelRatio]); + context.clear({ color: performance$1.aM.transparent, depth: 1 }); + for (const tile of tiles) { + const terrainData = terrain.getTerrainData(tile.tileID); + const posMatrix = painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped()); + const uniformValues = terrainDepthUniformValues(posMatrix, terrain.getMeshFrameDelta(painter.transform.zoom)); + program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments); + } + context.bindFramebuffer.set(null); + context.viewport.set([0, 0, painter.width, painter.height]); +} +/** + * Redraw the Coords Framebuffers + * @param painter - the painter + * @param terrain - the terrain + */ +function drawCoords(painter, terrain) { + const context = painter.context; + const gl = context.gl; + const colorMode = ColorMode.unblended; + const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]); + const mesh = terrain.getTerrainMesh(); + const coords = terrain.getCoordsTexture(); + const tiles = terrain.sourceCache.getRenderableTiles(); + // draw tile-coords into framebuffer + const program = painter.useProgram('terrainCoords'); + context.bindFramebuffer.set(terrain.getFramebuffer('coords').framebuffer); + context.viewport.set([0, 0, painter.width / devicePixelRatio, painter.height / devicePixelRatio]); + context.clear({ color: performance$1.aM.transparent, depth: 1 }); + terrain.coordsIndex = []; + for (const tile of tiles) { + const terrainData = terrain.getTerrainData(tile.tileID); + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, coords.texture); + const posMatrix = painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped()); + const uniformValues = terrainCoordsUniformValues(posMatrix, 255 - terrain.coordsIndex.length, terrain.getMeshFrameDelta(painter.transform.zoom)); + program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments); + terrain.coordsIndex.push(tile.tileID.key); + } + context.bindFramebuffer.set(null); + context.viewport.set([0, 0, painter.width, painter.height]); +} +function drawTerrain(painter, terrain, tiles) { + const context = painter.context; + const gl = context.gl; + const colorMode = painter.colorModeForRenderPass(); + const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D); + const program = painter.useProgram('terrain'); + const mesh = terrain.getTerrainMesh(); + context.bindFramebuffer.set(null); + context.viewport.set([0, 0, painter.width, painter.height]); + for (const tile of tiles) { + const texture = painter.renderToTexture.getTexture(tile); + const terrainData = terrain.getTerrainData(tile.tileID); + context.activeTexture.set(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, texture.texture); + const posMatrix = painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped()); + const eleDelta = terrain.getMeshFrameDelta(painter.transform.zoom); + const fogMatrix = painter.transform.calculateFogMatrix(tile.tileID.toUnwrapped()); + const uniformValues = terrainUniformValues(posMatrix, eleDelta, fogMatrix, painter.style.sky, painter.transform.pitch); + program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, 'terrain', mesh.vertexBuffer, mesh.indexBuffer, mesh.segments); + } +} + +class Mesh { + constructor(vertexBuffer, indexBuffer, segments) { + this.vertexBuffer = vertexBuffer; + this.indexBuffer = indexBuffer; + this.segments = segments; + } + destroy() { + this.vertexBuffer.destroy(); + this.indexBuffer.destroy(); + this.segments.destroy(); + this.vertexBuffer = null; + this.indexBuffer = null; + this.segments = null; + } +} + +function drawSky(painter, sky) { + const context = painter.context; + const gl = context.gl; + const skyUniforms = skyUniformValues(sky, painter.style.map.transform, painter.pixelRatio); + const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]); + const stencilMode = StencilMode.disabled; + const colorMode = painter.colorModeForRenderPass(); + const program = painter.useProgram('sky'); + if (!sky.mesh) { + const vertexArray = new performance$1.aX(); + vertexArray.emplaceBack(-1, -1); + vertexArray.emplaceBack(1, -1); + vertexArray.emplaceBack(1, 1); + vertexArray.emplaceBack(-1, 1); + const indexArray = new performance$1.aY(); + indexArray.emplaceBack(0, 1, 2); + indexArray.emplaceBack(0, 2, 3); + sky.mesh = new Mesh(context.createVertexBuffer(vertexArray, posAttributes.members), context.createIndexBuffer(indexArray), performance$1.a0.simpleSegment(0, 0, vertexArray.length, indexArray.length)); + } + program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, skyUniforms, undefined, 'sky', sky.mesh.vertexBuffer, sky.mesh.indexBuffer, sky.mesh.segments); +} + +/** + * @internal + * Initialize a new painter object. + */ +class Painter { + constructor(gl, transform) { + this.context = new Context(gl); + this.transform = transform; + this._tileTextures = {}; + this.terrainFacilitator = { dirty: true, matrix: performance$1.an(new Float64Array(16)), renderTime: 0 }; + this.setup(); + // Within each layer there are multiple distinct z-planes that can be drawn to. + // This is implemented using the WebGL depth buffer. + this.numSublayers = SourceCache.maxUnderzooming + SourceCache.maxOverzooming + 1; + this.depthEpsilon = 1 / Math.pow(2, 16); + this.crossTileSymbolIndex = new CrossTileSymbolIndex(); + } + /* + * Update the GL viewport, projection matrix, and transforms to compensate + * for a new width and height value. + */ + resize(width, height, pixelRatio) { + this.width = Math.floor(width * pixelRatio); + this.height = Math.floor(height * pixelRatio); + this.pixelRatio = pixelRatio; + this.context.viewport.set([0, 0, this.width, this.height]); + if (this.style) { + for (const layerId of this.style._order) { + this.style._layers[layerId].resize(); + } + } + } + setup() { + const context = this.context; + const tileExtentArray = new performance$1.aX(); + tileExtentArray.emplaceBack(0, 0); + tileExtentArray.emplaceBack(performance$1.X, 0); + tileExtentArray.emplaceBack(0, performance$1.X); + tileExtentArray.emplaceBack(performance$1.X, performance$1.X); + this.tileExtentBuffer = context.createVertexBuffer(tileExtentArray, posAttributes.members); + this.tileExtentSegments = performance$1.a0.simpleSegment(0, 0, 4, 2); + const debugArray = new performance$1.aX(); + debugArray.emplaceBack(0, 0); + debugArray.emplaceBack(performance$1.X, 0); + debugArray.emplaceBack(0, performance$1.X); + debugArray.emplaceBack(performance$1.X, performance$1.X); + this.debugBuffer = context.createVertexBuffer(debugArray, posAttributes.members); + this.debugSegments = performance$1.a0.simpleSegment(0, 0, 4, 5); + const rasterBoundsArray = new performance$1.$(); + rasterBoundsArray.emplaceBack(0, 0, 0, 0); + rasterBoundsArray.emplaceBack(performance$1.X, 0, performance$1.X, 0); + rasterBoundsArray.emplaceBack(0, performance$1.X, 0, performance$1.X); + rasterBoundsArray.emplaceBack(performance$1.X, performance$1.X, performance$1.X, performance$1.X); + this.rasterBoundsBuffer = context.createVertexBuffer(rasterBoundsArray, rasterBoundsAttributes.members); + this.rasterBoundsSegments = performance$1.a0.simpleSegment(0, 0, 4, 2); + const viewportArray = new performance$1.aX(); + viewportArray.emplaceBack(0, 0); + viewportArray.emplaceBack(1, 0); + viewportArray.emplaceBack(0, 1); + viewportArray.emplaceBack(1, 1); + this.viewportBuffer = context.createVertexBuffer(viewportArray, posAttributes.members); + this.viewportSegments = performance$1.a0.simpleSegment(0, 0, 4, 2); + const tileLineStripIndices = new performance$1.aZ(); + tileLineStripIndices.emplaceBack(0); + tileLineStripIndices.emplaceBack(1); + tileLineStripIndices.emplaceBack(3); + tileLineStripIndices.emplaceBack(2); + tileLineStripIndices.emplaceBack(0); + this.tileBorderIndexBuffer = context.createIndexBuffer(tileLineStripIndices); + const quadTriangleIndices = new performance$1.aY(); + quadTriangleIndices.emplaceBack(0, 1, 2); + quadTriangleIndices.emplaceBack(2, 1, 3); + this.quadTriangleIndexBuffer = context.createIndexBuffer(quadTriangleIndices); + const gl = this.context.gl; + this.stencilClearMode = new StencilMode({ func: gl.ALWAYS, mask: 0 }, 0x0, 0xFF, gl.ZERO, gl.ZERO, gl.ZERO); + } + /* + * Reset the drawing canvas by clearing the stencil buffer so that we can draw + * new tiles at the same location, while retaining previously drawn pixels. + */ + clearStencil() { + const context = this.context; + const gl = context.gl; + this.nextStencilID = 1; + this.currentStencilSource = undefined; + // As a temporary workaround for https://github.com/mapbox/mapbox-gl-js/issues/5490, + // pending an upstream fix, we draw a fullscreen stencil=0 clipping mask here, + // effectively clearing the stencil buffer: once an upstream patch lands, remove + // this function in favor of context.clear({ stencil: 0x0 }) + const matrix = performance$1.H(); + performance$1.aP(matrix, 0, this.width, this.height, 0, 0, 1); + performance$1.K(matrix, matrix, [gl.drawingBufferWidth, gl.drawingBufferHeight, 0]); + this.useProgram('clippingMask').draw(context, gl.TRIANGLES, DepthMode.disabled, this.stencilClearMode, ColorMode.disabled, CullFaceMode.disabled, clippingMaskUniformValues(matrix), null, '$clipping', this.viewportBuffer, this.quadTriangleIndexBuffer, this.viewportSegments); + } + _renderTileClippingMasks(layer, tileIDs) { + if (this.currentStencilSource === layer.source || !layer.isTileClipped() || !tileIDs || !tileIDs.length) + return; + this.currentStencilSource = layer.source; + const context = this.context; + const gl = context.gl; + if (this.nextStencilID + tileIDs.length > 256) { + // we'll run out of fresh IDs so we need to clear and start from scratch + this.clearStencil(); + } + context.setColorMode(ColorMode.disabled); + context.setDepthMode(DepthMode.disabled); + const program = this.useProgram('clippingMask'); + this._tileClippingMaskIDs = {}; + for (const tileID of tileIDs) { + const id = this._tileClippingMaskIDs[tileID.key] = this.nextStencilID++; + const terrainData = this.style.map.terrain && this.style.map.terrain.getTerrainData(tileID); + program.draw(context, gl.TRIANGLES, DepthMode.disabled, + // Tests will always pass, and ref value will be written to stencil buffer. + new StencilMode({ func: gl.ALWAYS, mask: 0 }, id, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE), ColorMode.disabled, CullFaceMode.disabled, clippingMaskUniformValues(tileID.posMatrix), terrainData, '$clipping', this.tileExtentBuffer, this.quadTriangleIndexBuffer, this.tileExtentSegments); + } + } + stencilModeFor3D() { + this.currentStencilSource = undefined; + if (this.nextStencilID + 1 > 256) { + this.clearStencil(); + } + const id = this.nextStencilID++; + const gl = this.context.gl; + return new StencilMode({ func: gl.NOTEQUAL, mask: 0xFF }, id, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE); + } + stencilModeForClipping(tileID) { + const gl = this.context.gl; + return new StencilMode({ func: gl.EQUAL, mask: 0xFF }, this._tileClippingMaskIDs[tileID.key], 0x00, gl.KEEP, gl.KEEP, gl.REPLACE); + } + /* + * Sort coordinates by Z as drawing tiles is done in Z-descending order. + * All children with the same Z write the same stencil value. Children + * stencil values are greater than parent's. This is used only for raster + * and raster-dem tiles, which are already clipped to tile boundaries, to + * mask area of tile overlapped by children tiles. + * Stencil ref values continue range used in _tileClippingMaskIDs. + * + * Returns [StencilMode for tile overscaleZ map, sortedCoords]. + */ + stencilConfigForOverlap(tileIDs) { + const gl = this.context.gl; + const coords = tileIDs.sort((a, b) => b.overscaledZ - a.overscaledZ); + const minTileZ = coords[coords.length - 1].overscaledZ; + const stencilValues = coords[0].overscaledZ - minTileZ + 1; + if (stencilValues > 1) { + this.currentStencilSource = undefined; + if (this.nextStencilID + stencilValues > 256) { + this.clearStencil(); + } + const zToStencilMode = {}; + for (let i = 0; i < stencilValues; i++) { + zToStencilMode[i + minTileZ] = new StencilMode({ func: gl.GEQUAL, mask: 0xFF }, i + this.nextStencilID, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE); + } + this.nextStencilID += stencilValues; + return [zToStencilMode, coords]; + } + return [{ [minTileZ]: StencilMode.disabled }, coords]; + } + colorModeForRenderPass() { + const gl = this.context.gl; + if (this._showOverdrawInspector) { + const numOverdrawSteps = 8; + const a = 1 / numOverdrawSteps; + return new ColorMode([gl.CONSTANT_COLOR, gl.ONE], new performance$1.aM(a, a, a, 0), [true, true, true, true]); + } + else if (this.renderPass === 'opaque') { + return ColorMode.unblended; + } + else { + return ColorMode.alphaBlended; + } + } + depthModeForSublayer(n, mask, func) { + if (!this.opaquePassEnabledForLayer()) + return DepthMode.disabled; + const depth = 1 - ((1 + this.currentLayer) * this.numSublayers + n) * this.depthEpsilon; + return new DepthMode(func || this.context.gl.LEQUAL, mask, [depth, depth]); + } + /* + * The opaque pass and 3D layers both use the depth buffer. + * Layers drawn above 3D layers need to be drawn using the + * painter's algorithm so that they appear above 3D features. + * This returns true for layers that can be drawn using the + * opaque pass. + */ + opaquePassEnabledForLayer() { + return this.currentLayer < this.opaquePassCutoff; + } + render(style, options) { + this.style = style; + this.options = options; + this.lineAtlas = style.lineAtlas; + this.imageManager = style.imageManager; + this.glyphManager = style.glyphManager; + this.symbolFadeChange = style.placement.symbolFadeChange(browser.now()); + this.imageManager.beginFrame(); + const layerIds = this.style._order; + const sourceCaches = this.style.sourceCaches; + const coordsAscending = {}; + const coordsDescending = {}; + const coordsDescendingSymbol = {}; + for (const id in sourceCaches) { + const sourceCache = sourceCaches[id]; + if (sourceCache.used) { + sourceCache.prepare(this.context); + } + coordsAscending[id] = sourceCache.getVisibleCoordinates(); + coordsDescending[id] = coordsAscending[id].slice().reverse(); + coordsDescendingSymbol[id] = sourceCache.getVisibleCoordinates(true).reverse(); + } + this.opaquePassCutoff = Infinity; + for (let i = 0; i < layerIds.length; i++) { + const layerId = layerIds[i]; + if (this.style._layers[layerId].is3D()) { + this.opaquePassCutoff = i; + break; + } + } + this.maybeDrawDepthAndCoords(false); + if (this.renderToTexture) { + this.renderToTexture.prepareForRender(this.style, this.transform.zoom); + // this is disabled, because render-to-texture is rendering all layers from bottom to top. + this.opaquePassCutoff = 0; + } + // Offscreen pass =============================================== + // We first do all rendering that requires rendering to a separate + // framebuffer, and then save those for rendering back to the map + // later: in doing this we avoid doing expensive framebuffer restores. + this.renderPass = 'offscreen'; + for (const layerId of layerIds) { + const layer = this.style._layers[layerId]; + if (!layer.hasOffscreenPass() || layer.isHidden(this.transform.zoom)) + continue; + const coords = coordsDescending[layer.source]; + if (layer.type !== 'custom' && !coords.length) + continue; + this.renderLayer(this, sourceCaches[layer.source], layer, coords); + } + // Rebind the main framebuffer now that all offscreen layers have been rendered: + this.context.bindFramebuffer.set(null); + // Clear buffers in preparation for drawing to the main framebuffer + this.context.clear({ color: options.showOverdrawInspector ? performance$1.aM.black : performance$1.aM.transparent, depth: 1 }); + this.clearStencil(); + // draw sky first to not overwrite symbols + if (this.style.sky) + drawSky(this, this.style.sky); + this._showOverdrawInspector = options.showOverdrawInspector; + this.depthRangeFor3D = [0, 1 - ((style._order.length + 2) * this.numSublayers * this.depthEpsilon)]; + // Opaque pass =============================================== + // Draw opaque layers top-to-bottom first. + if (!this.renderToTexture) { + this.renderPass = 'opaque'; + for (this.currentLayer = layerIds.length - 1; this.currentLayer >= 0; this.currentLayer--) { + const layer = this.style._layers[layerIds[this.currentLayer]]; + const sourceCache = sourceCaches[layer.source]; + const coords = coordsAscending[layer.source]; + this._renderTileClippingMasks(layer, coords); + this.renderLayer(this, sourceCache, layer, coords); + } + } + // Translucent pass =============================================== + // Draw all other layers bottom-to-top. + this.renderPass = 'translucent'; + for (this.currentLayer = 0; this.currentLayer < layerIds.length; this.currentLayer++) { + const layer = this.style._layers[layerIds[this.currentLayer]]; + const sourceCache = sourceCaches[layer.source]; + if (this.renderToTexture && this.renderToTexture.renderLayer(layer)) + continue; + // For symbol layers in the translucent pass, we add extra tiles to the renderable set + // for cross-tile symbol fading. Symbol layers don't use tile clipping, so no need to render + // separate clipping masks + const coords = (layer.type === 'symbol' ? coordsDescendingSymbol : coordsDescending)[layer.source]; + this._renderTileClippingMasks(layer, coordsAscending[layer.source]); + this.renderLayer(this, sourceCache, layer, coords); + } + if (this.options.showTileBoundaries) { + const selectedSource = selectDebugSource(this.style, this.transform.zoom); + if (selectedSource) { + drawDebug(this, selectedSource, selectedSource.getVisibleCoordinates()); + } + } + if (this.options.showPadding) { + drawDebugPadding(this); + } + // Set defaults for most GL values so that anyone using the state after the render + // encounters more expected values. + this.context.setDefault(); + } + /** + * Update the depth and coords framebuffers, if the contents of those frame buffers is out of date. + * If requireExact is false, then the contents of those frame buffers is not updated if it is close + * to accurate (that is, the camera has not moved much since it was updated last). + */ + maybeDrawDepthAndCoords(requireExact) { + if (!this.style || !this.style.map || !this.style.map.terrain) { + return; + } + const prevMatrix = this.terrainFacilitator.matrix; + const currMatrix = this.transform.modelViewProjectionMatrix; + // Update coords/depth-framebuffer on camera movement, or tile reloading + let doUpdate = this.terrainFacilitator.dirty; + doUpdate || (doUpdate = requireExact ? !performance$1.a_(prevMatrix, currMatrix) : !performance$1.a$(prevMatrix, currMatrix)); + doUpdate || (doUpdate = this.style.map.terrain.sourceCache.tilesAfterTime(this.terrainFacilitator.renderTime).length > 0); + if (!doUpdate) { + return; + } + performance$1.b0(prevMatrix, currMatrix); + this.terrainFacilitator.renderTime = Date.now(); + this.terrainFacilitator.dirty = false; + drawDepth(this, this.style.map.terrain); + drawCoords(this, this.style.map.terrain); + } + renderLayer(painter, sourceCache, layer, coords) { + if (layer.isHidden(this.transform.zoom)) + return; + if (layer.type !== 'background' && layer.type !== 'custom' && !(coords || []).length) + return; + this.id = layer.id; + switch (layer.type) { + case 'symbol': + drawSymbols(painter, sourceCache, layer, coords, this.style.placement.variableOffsets); + break; + case 'circle': + drawCircles(painter, sourceCache, layer, coords); + break; + case 'heatmap': + drawHeatmap(painter, sourceCache, layer, coords); + break; + case 'line': + drawLine(painter, sourceCache, layer, coords); + break; + case 'fill': + drawFill(painter, sourceCache, layer, coords); + break; + case 'fill-extrusion': + drawFillExtrusion(painter, sourceCache, layer, coords); + break; + case 'hillshade': + drawHillshade(painter, sourceCache, layer, coords); + break; + case 'raster': + drawRaster(painter, sourceCache, layer, coords); + break; + case 'background': + drawBackground(painter, sourceCache, layer, coords); + break; + case 'custom': + drawCustom(painter, sourceCache, layer); + break; + } + } + /** + * Transform a matrix to incorporate the *-translate and *-translate-anchor properties into it. + * @param inViewportPixelUnitsUnits - True when the units accepted by the matrix are in viewport pixels instead of tile units. + * @returns matrix + */ + translatePosMatrix(matrix, tile, translate, translateAnchor, inViewportPixelUnitsUnits) { + if (!translate[0] && !translate[1]) + return matrix; + const angle = inViewportPixelUnitsUnits ? + (translateAnchor === 'map' ? this.transform.angle : 0) : + (translateAnchor === 'viewport' ? -this.transform.angle : 0); + if (angle) { + const sinA = Math.sin(angle); + const cosA = Math.cos(angle); + translate = [ + translate[0] * cosA - translate[1] * sinA, + translate[0] * sinA + translate[1] * cosA + ]; + } + const translation = [ + inViewportPixelUnitsUnits ? translate[0] : pixelsToTileUnits(tile, translate[0], this.transform.zoom), + inViewportPixelUnitsUnits ? translate[1] : pixelsToTileUnits(tile, translate[1], this.transform.zoom), + 0 + ]; + const translatedMatrix = new Float32Array(16); + performance$1.J(translatedMatrix, matrix, translation); + return translatedMatrix; + } + saveTileTexture(texture) { + const textures = this._tileTextures[texture.size[0]]; + if (!textures) { + this._tileTextures[texture.size[0]] = [texture]; + } + else { + textures.push(texture); + } + } + getTileTexture(size) { + const textures = this._tileTextures[size]; + return textures && textures.length > 0 ? textures.pop() : null; + } + /** + * Checks whether a pattern image is needed, and if it is, whether it is not loaded. + * + * @returns true if a needed image is missing and rendering needs to be skipped. + */ + isPatternMissing(image) { + if (!image) + return false; + if (!image.from || !image.to) + return true; + const imagePosA = this.imageManager.getPattern(image.from.toString()); + const imagePosB = this.imageManager.getPattern(image.to.toString()); + return !imagePosA || !imagePosB; + } + useProgram(name, programConfiguration) { + this.cache = this.cache || {}; + const key = name + + (programConfiguration ? programConfiguration.cacheKey : '') + + (this._showOverdrawInspector ? '/overdraw' : '') + + (this.style.map.terrain ? '/terrain' : ''); + if (!this.cache[key]) { + this.cache[key] = new Program(this.context, shaders[name], programConfiguration, programUniforms[name], this._showOverdrawInspector, this.style.map.terrain); + } + return this.cache[key]; + } + /* + * Reset some GL state to default values to avoid hard-to-debug bugs + * in custom layers. + */ + setCustomLayerDefaults() { + // Prevent custom layers from unintentionally modify the last VAO used. + // All other state is state is restored on it's own, but for VAOs it's + // simpler to unbind so that we don't have to track the state of VAOs. + this.context.unbindVAO(); + // The default values for this state is meaningful and often expected. + // Leaving this state dirty could cause a lot of confusion for users. + this.context.cullFace.setDefault(); + this.context.activeTexture.setDefault(); + this.context.pixelStoreUnpack.setDefault(); + this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(); + this.context.pixelStoreUnpackFlipY.setDefault(); + } + /* + * Set GL state that is shared by all layers. + */ + setBaseState() { + const gl = this.context.gl; + this.context.cullFace.set(false); + this.context.viewport.set([0, 0, this.width, this.height]); + this.context.blendEquation.set(gl.FUNC_ADD); + } + initDebugOverlayCanvas() { + if (this.debugOverlayCanvas == null) { + this.debugOverlayCanvas = document.createElement('canvas'); + this.debugOverlayCanvas.width = 512; + this.debugOverlayCanvas.height = 512; + const gl = this.context.gl; + this.debugOverlayTexture = new Texture(this.context, this.debugOverlayCanvas, gl.RGBA); + } + } + destroy() { + if (this.debugOverlayTexture) { + this.debugOverlayTexture.destroy(); + } + } + /* + * Return true if drawing buffer size is != from requested size. + * That means that we've reached GL limits somehow. + * Note: drawing buffer size changes only when canvas size changes + */ + overLimit() { + const { drawingBufferWidth, drawingBufferHeight } = this.context.gl; + return this.width !== drawingBufferWidth || this.height !== drawingBufferHeight; + } +} + +class Frustum { + constructor(points, planes) { + this.points = points; + this.planes = planes; + } + static fromInvProjectionMatrix(invProj, worldSize, zoom) { + const clipSpaceCorners = [ + [-1, 1, -1, 1], + [1, 1, -1, 1], + [1, -1, -1, 1], + [-1, -1, -1, 1], + [-1, 1, 1, 1], + [1, 1, 1, 1], + [1, -1, 1, 1], + [-1, -1, 1, 1] + ]; + const scale = Math.pow(2, zoom); + // Transform frustum corner points from clip space to tile space, Z to meters + const frustumCoords = clipSpaceCorners.map(v => { + v = performance$1.af([], v, invProj); + const s = 1.0 / v[3] / worldSize * scale; + return performance$1.b1(v, v, [s, s, 1.0 / v[3], s]); + }); + const frustumPlanePointIndices = [ + [0, 1, 2], // near + [6, 5, 4], // far + [0, 3, 7], // left + [2, 1, 5], // right + [3, 2, 6], // bottom + [0, 4, 5] // top + ]; + const frustumPlanes = frustumPlanePointIndices.map((p) => { + const a = sub([], frustumCoords[p[0]], frustumCoords[p[1]]); + const b = sub([], frustumCoords[p[2]], frustumCoords[p[1]]); + const n = normalize([], cross([], a, b)); + const d = -dot(n, frustumCoords[p[1]]); + return n.concat(d); + }); + return new Frustum(frustumCoords, frustumPlanes); + } +} +class Aabb { + constructor(min_, max_) { + this.min = min_; + this.max = max_; + this.center = scale([], add([], this.min, this.max), 0.5); + } + quadrant(index) { + const split = [(index % 2) === 0, index < 2]; + const qMin = clone(this.min); + const qMax = clone(this.max); + for (let axis = 0; axis < split.length; axis++) { + qMin[axis] = split[axis] ? this.min[axis] : this.center[axis]; + qMax[axis] = split[axis] ? this.center[axis] : this.max[axis]; + } + // Elevation is always constant, hence quadrant.max.z = this.max.z + qMax[2] = this.max[2]; + return new Aabb(qMin, qMax); + } + distanceX(point) { + const pointOnAabb = Math.max(Math.min(this.max[0], point[0]), this.min[0]); + return pointOnAabb - point[0]; + } + distanceY(point) { + const pointOnAabb = Math.max(Math.min(this.max[1], point[1]), this.min[1]); + return pointOnAabb - point[1]; + } + // Performs a frustum-aabb intersection test. Returns 0 if there's no intersection, + // 1 if shapes are intersecting and 2 if the aabb if fully inside the frustum. + intersects(frustum) { + // Execute separating axis test between two convex objects to find intersections + // Each frustum plane together with 3 major axes define the separating axes + const aabbPoints = [ + [this.min[0], this.min[1], this.min[2], 1], + [this.max[0], this.min[1], this.min[2], 1], + [this.max[0], this.max[1], this.min[2], 1], + [this.min[0], this.max[1], this.min[2], 1], + [this.min[0], this.min[1], this.max[2], 1], + [this.max[0], this.min[1], this.max[2], 1], + [this.max[0], this.max[1], this.max[2], 1], + [this.min[0], this.max[1], this.max[2], 1] + ]; + let fullyInside = true; + for (let p = 0; p < frustum.planes.length; p++) { + const plane = frustum.planes[p]; + let pointsInside = 0; + for (let i = 0; i < aabbPoints.length; i++) { + if (performance$1.b2(plane, aabbPoints[i]) >= 0) { + pointsInside++; + } + } + if (pointsInside === 0) + return 0; + if (pointsInside !== aabbPoints.length) + fullyInside = false; + } + if (fullyInside) + return 2; + for (let axis = 0; axis < 3; axis++) { + let projMin = Number.MAX_VALUE; + let projMax = -Number.MAX_VALUE; + for (let p = 0; p < frustum.points.length; p++) { + const projectedPoint = frustum.points[p][axis] - this.min[axis]; + projMin = Math.min(projMin, projectedPoint); + projMax = Math.max(projMax, projectedPoint); + } + if (projMax < 0 || projMin > this.max[axis] - this.min[axis]) + return 0; + } + return 1; + } +} + +/** + * An `EdgeInset` object represents screen space padding applied to the edges of the viewport. + * This shifts the apprent center or the vanishing point of the map. This is useful for adding floating UI elements + * on top of the map and having the vanishing point shift as UI elements resize. + * + * @group Geography and Geometry + */ +class EdgeInsets { + constructor(top = 0, bottom = 0, left = 0, right = 0) { + if (isNaN(top) || top < 0 || + isNaN(bottom) || bottom < 0 || + isNaN(left) || left < 0 || + isNaN(right) || right < 0) { + throw new Error('Invalid value for edge-insets, top, bottom, left and right must all be numbers'); + } + this.top = top; + this.bottom = bottom; + this.left = left; + this.right = right; + } + /** + * Interpolates the inset in-place. + * This maintains the current inset value for any inset not present in `target`. + * @param start - interpolation start + * @param target - interpolation target + * @param t - interpolation step/weight + * @returns the insets + */ + interpolate(start, target, t) { + if (target.top != null && start.top != null) + this.top = performance$1.y.number(start.top, target.top, t); + if (target.bottom != null && start.bottom != null) + this.bottom = performance$1.y.number(start.bottom, target.bottom, t); + if (target.left != null && start.left != null) + this.left = performance$1.y.number(start.left, target.left, t); + if (target.right != null && start.right != null) + this.right = performance$1.y.number(start.right, target.right, t); + return this; + } + /** + * Utility method that computes the new apprent center or vanishing point after applying insets. + * This is in pixels and with the top left being (0.0) and +y being downwards. + * + * @param width - the width + * @param height - the height + * @returns the point + */ + getCenter(width, height) { + // Clamp insets so they never overflow width/height and always calculate a valid center + const x = performance$1.ac((this.left + width - this.right) / 2, 0, width); + const y = performance$1.ac((this.top + height - this.bottom) / 2, 0, height); + return new performance$1.P(x, y); + } + equals(other) { + return this.top === other.top && + this.bottom === other.bottom && + this.left === other.left && + this.right === other.right; + } + clone() { + return new EdgeInsets(this.top, this.bottom, this.left, this.right); + } + /** + * Returns the current state as json, useful when you want to have a + * read-only representation of the inset. + * + * @returns state as json + */ + toJSON() { + return { + top: this.top, + bottom: this.bottom, + left: this.left, + right: this.right + }; + } +} + +const MAX_VALID_LATITUDE = 85.051129; +/** + * @internal + * A single transform, generally used for a single tile to be + * scaled, rotated, and zoomed. + */ +class Transform { + constructor(minZoom, maxZoom, minPitch, maxPitch, renderWorldCopies) { + this.tileSize = 512; // constant + this._renderWorldCopies = renderWorldCopies === undefined ? true : !!renderWorldCopies; + this._minZoom = minZoom || 0; + this._maxZoom = maxZoom || 22; + this._minPitch = (minPitch === undefined || minPitch === null) ? 0 : minPitch; + this._maxPitch = (maxPitch === undefined || maxPitch === null) ? 60 : maxPitch; + this.setMaxBounds(); + this.width = 0; + this.height = 0; + this._center = new performance$1.N(0, 0); + this._elevation = 0; + this.zoom = 0; + this.angle = 0; + this._fov = 0.6435011087932844; + this._pitch = 0; + this._unmodified = true; + this._edgeInsets = new EdgeInsets(); + this._posMatrixCache = {}; + this._alignedPosMatrixCache = {}; + this._fogMatrixCache = {}; + this.minElevationForCurrentTile = 0; + } + clone() { + const clone = new Transform(this._minZoom, this._maxZoom, this._minPitch, this.maxPitch, this._renderWorldCopies); + clone.apply(this); + return clone; + } + apply(that) { + this.tileSize = that.tileSize; + this.latRange = that.latRange; + this.lngRange = that.lngRange; + this.width = that.width; + this.height = that.height; + this._center = that._center; + this._elevation = that._elevation; + this.minElevationForCurrentTile = that.minElevationForCurrentTile; + this.zoom = that.zoom; + this.angle = that.angle; + this._fov = that._fov; + this._pitch = that._pitch; + this._unmodified = that._unmodified; + this._edgeInsets = that._edgeInsets.clone(); + this._calcMatrices(); + } + get minZoom() { return this._minZoom; } + set minZoom(zoom) { + if (this._minZoom === zoom) + return; + this._minZoom = zoom; + this.zoom = Math.max(this.zoom, zoom); + } + get maxZoom() { return this._maxZoom; } + set maxZoom(zoom) { + if (this._maxZoom === zoom) + return; + this._maxZoom = zoom; + this.zoom = Math.min(this.zoom, zoom); + } + get minPitch() { return this._minPitch; } + set minPitch(pitch) { + if (this._minPitch === pitch) + return; + this._minPitch = pitch; + this.pitch = Math.max(this.pitch, pitch); + } + get maxPitch() { return this._maxPitch; } + set maxPitch(pitch) { + if (this._maxPitch === pitch) + return; + this._maxPitch = pitch; + this.pitch = Math.min(this.pitch, pitch); + } + get renderWorldCopies() { return this._renderWorldCopies; } + set renderWorldCopies(renderWorldCopies) { + if (renderWorldCopies === undefined) { + renderWorldCopies = true; + } + else if (renderWorldCopies === null) { + renderWorldCopies = false; + } + this._renderWorldCopies = renderWorldCopies; + } + get worldSize() { + return this.tileSize * this.scale; + } + get centerOffset() { + return this.centerPoint._sub(this.size._div(2)); + } + get size() { + return new performance$1.P(this.width, this.height); + } + get bearing() { + return -this.angle / Math.PI * 180; + } + set bearing(bearing) { + const b = -performance$1.b3(bearing, -180, 180) * Math.PI / 180; + if (this.angle === b) + return; + this._unmodified = false; + this.angle = b; + this._calcMatrices(); + // 2x2 matrix for rotating points + this.rotationMatrix = create$4(); + rotate(this.rotationMatrix, this.rotationMatrix, this.angle); + } + get pitch() { + return this._pitch / Math.PI * 180; + } + set pitch(pitch) { + const p = performance$1.ac(pitch, this.minPitch, this.maxPitch) / 180 * Math.PI; + if (this._pitch === p) + return; + this._unmodified = false; + this._pitch = p; + this._calcMatrices(); + } + get fov() { + return this._fov / Math.PI * 180; + } + set fov(fov) { + fov = Math.max(0.01, Math.min(60, fov)); + if (this._fov === fov) + return; + this._unmodified = false; + this._fov = fov / 180 * Math.PI; + this._calcMatrices(); + } + get zoom() { return this._zoom; } + set zoom(zoom) { + const constrainedZoom = Math.min(Math.max(zoom, this.minZoom), this.maxZoom); + if (this._zoom === constrainedZoom) + return; + this._unmodified = false; + this._zoom = constrainedZoom; + this.tileZoom = Math.max(0, Math.floor(constrainedZoom)); + this.scale = this.zoomScale(constrainedZoom); + this._constrain(); + this._calcMatrices(); + } + get center() { return this._center; } + set center(center) { + if (center.lat === this._center.lat && center.lng === this._center.lng) + return; + this._unmodified = false; + this._center = center; + this._constrain(); + this._calcMatrices(); + } + /** + * Elevation at current center point, meters above sea level + */ + get elevation() { return this._elevation; } + set elevation(elevation) { + if (elevation === this._elevation) + return; + this._elevation = elevation; + this._constrain(); + this._calcMatrices(); + } + get padding() { return this._edgeInsets.toJSON(); } + set padding(padding) { + if (this._edgeInsets.equals(padding)) + return; + this._unmodified = false; + //Update edge-insets in place + this._edgeInsets.interpolate(this._edgeInsets, padding, 1); + this._calcMatrices(); + } + /** + * The center of the screen in pixels with the top-left corner being (0,0) + * and +y axis pointing downwards. This accounts for padding. + */ + get centerPoint() { + return this._edgeInsets.getCenter(this.width, this.height); + } + /** + * Returns if the padding params match + * + * @param padding - the padding to check against + * @returns true if they are equal, false otherwise + */ + isPaddingEqual(padding) { + return this._edgeInsets.equals(padding); + } + /** + * Helper method to update edge-insets in place + * + * @param start - the starting padding + * @param target - the target padding + * @param t - the step/weight + */ + interpolatePadding(start, target, t) { + this._unmodified = false; + this._edgeInsets.interpolate(start, target, t); + this._constrain(); + this._calcMatrices(); + } + /** + * Return a zoom level that will cover all tiles the transform + * @param options - the options + * @returns zoom level An integer zoom level at which all tiles will be visible. + */ + coveringZoomLevel(options) { + const z = (options.roundZoom ? Math.round : Math.floor)(this.zoom + this.scaleZoom(this.tileSize / options.tileSize)); + // At negative zoom levels load tiles from z0 because negative tile zoom levels don't exist. + return Math.max(0, z); + } + /** + * Return any "wrapped" copies of a given tile coordinate that are visible + * in the current view. + */ + getVisibleUnwrappedCoordinates(tileID) { + const result = [new performance$1.b4(0, tileID)]; + if (this._renderWorldCopies) { + const utl = this.pointCoordinate(new performance$1.P(0, 0)); + const utr = this.pointCoordinate(new performance$1.P(this.width, 0)); + const ubl = this.pointCoordinate(new performance$1.P(this.width, this.height)); + const ubr = this.pointCoordinate(new performance$1.P(0, this.height)); + const w0 = Math.floor(Math.min(utl.x, utr.x, ubl.x, ubr.x)); + const w1 = Math.floor(Math.max(utl.x, utr.x, ubl.x, ubr.x)); + // Add an extra copy of the world on each side to properly render ImageSources and CanvasSources. + // Both sources draw outside the tile boundaries of the tile that "contains them" so we need + // to add extra copies on both sides in case offscreen tiles need to draw into on-screen ones. + const extraWorldCopy = 1; + for (let w = w0 - extraWorldCopy; w <= w1 + extraWorldCopy; w++) { + if (w === 0) + continue; + result.push(new performance$1.b4(w, tileID)); + } + } + return result; + } + /** + * Return all coordinates that could cover this transform for a covering + * zoom level. + * @param options - the options + * @returns OverscaledTileIDs + */ + coveringTiles(options) { + var _a, _b; + let z = this.coveringZoomLevel(options); + const actualZ = z; + if (options.minzoom !== undefined && z < options.minzoom) + return []; + if (options.maxzoom !== undefined && z > options.maxzoom) + z = options.maxzoom; + const cameraCoord = this.pointCoordinate(this.getCameraPoint()); + const centerCoord = performance$1.Z.fromLngLat(this.center); + const numTiles = Math.pow(2, z); + const cameraPoint = [numTiles * cameraCoord.x, numTiles * cameraCoord.y, 0]; + const centerPoint = [numTiles * centerCoord.x, numTiles * centerCoord.y, 0]; + const cameraFrustum = Frustum.fromInvProjectionMatrix(this.invModelViewProjectionMatrix, this.worldSize, z); + // 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 + let minZoom = options.minzoom || 0; + // Use 0.1 as an epsilon to avoid for explicit == 0.0 floating point checks + if (!options.terrain && this.pitch <= 60.0 && this._edgeInsets.top < 0.1) + minZoom = z; + // There should always be a certain number of maximum zoom level tiles surrounding the center location in 2D or in front of the camera in 3D + const radiusOfMaxLvlLodInTiles = options.terrain ? 2 / Math.min(this.tileSize, options.tileSize) * this.tileSize : 3; + const newRootTile = (wrap) => { + return { + aabb: new Aabb([wrap * numTiles, 0, 0], [(wrap + 1) * numTiles, numTiles, 0]), + zoom: 0, + x: 0, + y: 0, + wrap, + fullyVisible: false + }; + }; + // Do a depth-first traversal to find visible tiles and proper levels of detail + const stack = []; + const result = []; + const maxZoom = z; + const overscaledZ = options.reparseOverscaled ? actualZ : z; + if (this._renderWorldCopies) { + // Render copy of the globe thrice on both sides + for (let i = 1; i <= 3; i++) { + stack.push(newRootTile(-i)); + stack.push(newRootTile(i)); + } + } + stack.push(newRootTile(0)); + while (stack.length > 0) { + const it = stack.pop(); + const x = it.x; + const y = it.y; + let fullyVisible = it.fullyVisible; + // Visibility of a tile is not required if any of its ancestor if fully inside the frustum + if (!fullyVisible) { + const intersectResult = it.aabb.intersects(cameraFrustum); + if (intersectResult === 0) + continue; + fullyVisible = intersectResult === 2; + } + const refPoint = options.terrain ? cameraPoint : centerPoint; + const distanceX = it.aabb.distanceX(refPoint); + const distanceY = it.aabb.distanceY(refPoint); + const longestDim = Math.max(Math.abs(distanceX), Math.abs(distanceY)); + // We're using distance based heuristics to determine if a tile should be split into quadrants or not. + // radiusOfMaxLvlLodInTiles defines that there's always a certain number of maxLevel tiles next to the map center. + // Using the fact that a parent node in quadtree is twice the size of its children (per dimension) + // we can define distance thresholds for each relative level: + // f(k) = offset + 2 + 4 + 8 + 16 + ... + 2^k. This is the same as "offset+2^(k+1)-2" + const distToSplit = radiusOfMaxLvlLodInTiles + (1 << (maxZoom - it.zoom)) - 2; + // Have we reached the target depth or is the tile too far away to be any split further? + if (it.zoom === maxZoom || (longestDim > distToSplit && it.zoom >= minZoom)) { + const dz = maxZoom - it.zoom, dx = cameraPoint[0] - 0.5 - (x << dz), dy = cameraPoint[1] - 0.5 - (y << dz); + result.push({ + tileID: new performance$1.S(it.zoom === maxZoom ? overscaledZ : it.zoom, it.wrap, it.zoom, x, y), + distanceSq: sqrLen([centerPoint[0] - 0.5 - x, centerPoint[1] - 0.5 - y]), + // this variable is currently not used, but may be important to reduce the amount of loaded tiles + tileDistanceToCamera: Math.sqrt(dx * dx + dy * dy) + }); + continue; + } + for (let i = 0; i < 4; i++) { + const childX = (x << 1) + (i % 2); + const childY = (y << 1) + (i >> 1); + const childZ = it.zoom + 1; + let quadrant = it.aabb.quadrant(i); + if (options.terrain) { + const tileID = new performance$1.S(childZ, it.wrap, childZ, childX, childY); + const minMax = options.terrain.getMinMaxElevation(tileID); + const minElevation = (_a = minMax.minElevation) !== null && _a !== void 0 ? _a : this.elevation; + const maxElevation = (_b = minMax.maxElevation) !== null && _b !== void 0 ? _b : this.elevation; + quadrant = new Aabb([quadrant.min[0], quadrant.min[1], minElevation], [quadrant.max[0], quadrant.max[1], maxElevation]); + } + stack.push({ aabb: quadrant, zoom: childZ, x: childX, y: childY, wrap: it.wrap, fullyVisible }); + } + } + return result.sort((a, b) => a.distanceSq - b.distanceSq).map(a => a.tileID); + } + resize(width, height) { + this.width = width; + this.height = height; + this.pixelsToGLUnits = [2 / width, -2 / height]; + this._constrain(); + this._calcMatrices(); + } + get unmodified() { return this._unmodified; } + zoomScale(zoom) { return Math.pow(2, zoom); } + scaleZoom(scale) { return Math.log(scale) / Math.LN2; } + /** + * Convert from LngLat to world coordinates (Mercator coordinates scaled by 512) + * @param lnglat - the lngLat + * @returns Point + */ + project(lnglat) { + const lat = performance$1.ac(lnglat.lat, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE); + return new performance$1.P(performance$1.O(lnglat.lng) * this.worldSize, performance$1.Q(lat) * this.worldSize); + } + /** + * Convert from world coordinates ([0, 512],[0, 512]) to LngLat ([-180, 180], [-90, 90]) + * @param point - world coordinate + * @returns LngLat + */ + unproject(point) { + return new performance$1.Z(point.x / this.worldSize, point.y / this.worldSize).toLngLat(); + } + get point() { return this.project(this.center); } + /** + * get the camera position in LngLat and altitudes in meter + * @returns An object with lngLat & altitude. + */ + getCameraPosition() { + const lngLat = this.pointLocation(this.getCameraPoint()); + const altitude = Math.cos(this._pitch) * this.cameraToCenterDistance / this._pixelPerMeter; + return { lngLat, altitude: altitude + this.elevation }; + } + /** + * This method works in combination with freezeElevation activated. + * freezeElevation is enabled during map-panning because during this the camera should sit in constant height. + * After panning finished, call this method to recalculate the zoomlevel for the current camera-height in current terrain. + * @param terrain - the terrain + */ + recalculateZoom(terrain) { + const origElevation = this.elevation; + const origAltitude = Math.cos(this._pitch) * this.cameraToCenterDistance / this._pixelPerMeter; + // find position the camera is looking on + const center = this.pointLocation(this.centerPoint, terrain); + const elevation = terrain.getElevationForLngLatZoom(center, this.tileZoom); + const deltaElevation = this.elevation - elevation; + if (!deltaElevation) + return; + // The camera's altitude off the ground + the ground's elevation = a constant: + // this means the camera stays at the same total height. + const requiredAltitude = origAltitude + origElevation - elevation; + // Since altitude = Math.cos(this._pitch) * this.cameraToCenterDistance / pixelPerMeter: + const requiredPixelPerMeter = Math.cos(this._pitch) * this.cameraToCenterDistance / requiredAltitude; + // Since pixelPerMeter = mercatorZfromAltitude(1, center.lat) * worldSize: + const requiredWorldSize = requiredPixelPerMeter / performance$1.b5(1, center.lat); + // Since worldSize = this.tileSize * scale: + const requiredScale = requiredWorldSize / this.tileSize; + const zoom = this.scaleZoom(requiredScale); + // update matrices + this._elevation = elevation; + this._center = center; + this.zoom = zoom; + } + setLocationAtPoint(lnglat, point) { + const a = this.pointCoordinate(point); + const b = this.pointCoordinate(this.centerPoint); + const loc = this.locationCoordinate(lnglat); + const newCenter = new performance$1.Z(loc.x - (a.x - b.x), loc.y - (a.y - b.y)); + this.center = this.coordinateLocation(newCenter); + if (this._renderWorldCopies) { + this.center = this.center.wrap(); + } + } + /** + * Given a LngLat location, return the screen point that corresponds to it + * @param lnglat - location + * @param terrain - optional terrain + * @returns screen point + */ + locationPoint(lnglat, terrain) { + return terrain ? + this.coordinatePoint(this.locationCoordinate(lnglat), terrain.getElevationForLngLatZoom(lnglat, this.tileZoom), this.pixelMatrix3D) : + this.coordinatePoint(this.locationCoordinate(lnglat)); + } + /** + * Given a point on screen, return its lnglat + * @param p - screen point + * @param terrain - optional terrain + * @returns lnglat location + */ + pointLocation(p, terrain) { + return this.coordinateLocation(this.pointCoordinate(p, terrain)); + } + /** + * Given a geographical lnglat, return an unrounded + * coordinate that represents it at low zoom level. + * @param lnglat - the location + * @returns The mercator coordinate + */ + locationCoordinate(lnglat) { + return performance$1.Z.fromLngLat(lnglat); + } + /** + * Given a Coordinate, return its geographical position. + * @param coord - mercator coordinates + * @returns lng and lat + */ + coordinateLocation(coord) { + return coord && coord.toLngLat(); + } + /** + * Given a Point, return its mercator coordinate. + * @param p - the point + * @param terrain - optional terrain + * @returns lnglat + */ + pointCoordinate(p, terrain) { + // get point-coordinate from terrain coordinates framebuffer + if (terrain) { + const coordinate = terrain.pointCoordinate(p); + if (coordinate != null) { + return coordinate; + } + } + // calculate point-coordinate on flat earth + const targetZ = 0; + // since we don't know the correct projected z value for the point, + // unproject two points to get a line and then find the point on that + // line with z=0 + const coord0 = [p.x, p.y, 0, 1]; + const coord1 = [p.x, p.y, 1, 1]; + performance$1.af(coord0, coord0, this.pixelMatrixInverse); + performance$1.af(coord1, coord1, this.pixelMatrixInverse); + const w0 = coord0[3]; + const w1 = coord1[3]; + const x0 = coord0[0] / w0; + const x1 = coord1[0] / w1; + const y0 = coord0[1] / w0; + const y1 = coord1[1] / w1; + const z0 = coord0[2] / w0; + const z1 = coord1[2] / w1; + const t = z0 === z1 ? 0 : (targetZ - z0) / (z1 - z0); + return new performance$1.Z(performance$1.y.number(x0, x1, t) / this.worldSize, performance$1.y.number(y0, y1, t) / this.worldSize); + } + /** + * Given a coordinate, return the screen point that corresponds to it + * @param coord - the coordinates + * @param elevation - the elevation + * @param pixelMatrix - the pixel matrix + * @returns screen point + */ + coordinatePoint(coord, elevation = 0, pixelMatrix = this.pixelMatrix) { + const p = [coord.x * this.worldSize, coord.y * this.worldSize, elevation, 1]; + performance$1.af(p, p, pixelMatrix); + return new performance$1.P(p[0] / p[3], p[1] / p[3]); + } + /** + * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not + * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region. + * @returns Returns a {@link LngLatBounds} object describing the map's geographical bounds. + */ + getBounds() { + const top = Math.max(0, this.height / 2 - this.getHorizon()); + return new LngLatBounds() + .extend(this.pointLocation(new performance$1.P(0, top))) + .extend(this.pointLocation(new performance$1.P(this.width, top))) + .extend(this.pointLocation(new performance$1.P(this.width, this.height))) + .extend(this.pointLocation(new performance$1.P(0, this.height))); + } + /** + * Returns the maximum geographical bounds the map is constrained to, or `null` if none set. + * @returns max bounds + */ + getMaxBounds() { + if (!this.latRange || this.latRange.length !== 2 || + !this.lngRange || this.lngRange.length !== 2) + return null; + return new LngLatBounds([this.lngRange[0], this.latRange[0]], [this.lngRange[1], this.latRange[1]]); + } + /** + * Calculate pixel height of the visible horizon in relation to map-center (e.g. height/2), + * multiplied by a static factor to simulate the earth-radius. + * The calculated value is the horizontal line from the camera-height to sea-level. + * @returns Horizon above center in pixels. + */ + getHorizon() { + return Math.tan(Math.PI / 2 - this._pitch) * this.cameraToCenterDistance * 0.85; + } + /** + * Sets or clears the map's geographical constraints. + * @param bounds - A {@link LngLatBounds} object describing the new geographic boundaries of the map. + */ + setMaxBounds(bounds) { + if (bounds) { + this.lngRange = [bounds.getWest(), bounds.getEast()]; + this.latRange = [bounds.getSouth(), bounds.getNorth()]; + this._constrain(); + } + else { + this.lngRange = null; + this.latRange = [-MAX_VALID_LATITUDE, MAX_VALID_LATITUDE]; + } + } + calculateTileMatrix(unwrappedTileID) { + const canonical = unwrappedTileID.canonical; + const scale = this.worldSize / this.zoomScale(canonical.z); + const unwrappedX = canonical.x + Math.pow(2, canonical.z) * unwrappedTileID.wrap; + const worldMatrix = performance$1.an(new Float64Array(16)); + performance$1.J(worldMatrix, worldMatrix, [unwrappedX * scale, canonical.y * scale, 0]); + performance$1.K(worldMatrix, worldMatrix, [scale / performance$1.X, scale / performance$1.X, 1]); + return worldMatrix; + } + /** + * Calculate the posMatrix that, given a tile coordinate, would be used to display the tile on a map. + * @param unwrappedTileID - the tile ID + */ + calculatePosMatrix(unwrappedTileID, aligned = false) { + const posMatrixKey = unwrappedTileID.key; + const cache = aligned ? this._alignedPosMatrixCache : this._posMatrixCache; + if (cache[posMatrixKey]) { + return cache[posMatrixKey]; + } + const posMatrix = this.calculateTileMatrix(unwrappedTileID); + performance$1.L(posMatrix, aligned ? this.alignedModelViewProjectionMatrix : this.modelViewProjectionMatrix, posMatrix); + cache[posMatrixKey] = new Float32Array(posMatrix); + return cache[posMatrixKey]; + } + /** + * Calculate the fogMatrix that, given a tile coordinate, would be used to calculate fog on the map. + * @param unwrappedTileID - the tile ID + * @private + */ + calculateFogMatrix(unwrappedTileID) { + const posMatrixKey = unwrappedTileID.key; + const cache = this._fogMatrixCache; + if (cache[posMatrixKey]) { + return cache[posMatrixKey]; + } + const fogMatrix = this.calculateTileMatrix(unwrappedTileID); + performance$1.L(fogMatrix, this.fogMatrix, fogMatrix); + cache[posMatrixKey] = new Float32Array(fogMatrix); + return cache[posMatrixKey]; + } + customLayerMatrix() { + return this.mercatorMatrix.slice(); + } + /** + * Get center lngLat and zoom to ensure that + * 1) everything beyond the bounds is excluded + * 2) a given lngLat is as near the center as possible + * Bounds are those set by maxBounds or North & South "Poles" and, if only 1 globe is displayed, antimeridian. + */ + getConstrained(lngLat, zoom) { + zoom = performance$1.ac(+zoom, this.minZoom, this.maxZoom); + const result = { + center: new performance$1.N(lngLat.lng, lngLat.lat), + zoom + }; + let lngRange = this.lngRange; + if (!this._renderWorldCopies && lngRange === null) { + const almost180 = 180 - 1e-10; + lngRange = [-almost180, almost180]; + } + const worldSize = this.tileSize * this.zoomScale(result.zoom); // A world size for the requested zoom level, not the current world size + let minY = 0; + let maxY = worldSize; + let minX = 0; + let maxX = worldSize; + let scaleY = 0; + let scaleX = 0; + const { x: screenWidth, y: screenHeight } = this.size; + if (this.latRange) { + const latRange = this.latRange; + minY = performance$1.Q(latRange[1]) * worldSize; + maxY = performance$1.Q(latRange[0]) * worldSize; + const shouldZoomIn = maxY - minY < screenHeight; + if (shouldZoomIn) + scaleY = screenHeight / (maxY - minY); + } + if (lngRange) { + minX = performance$1.b3(performance$1.O(lngRange[0]) * worldSize, 0, worldSize); + maxX = performance$1.b3(performance$1.O(lngRange[1]) * worldSize, 0, worldSize); + if (maxX < minX) + maxX += worldSize; + const shouldZoomIn = maxX - minX < screenWidth; + if (shouldZoomIn) + scaleX = screenWidth / (maxX - minX); + } + const { x: originalX, y: originalY } = this.project.call({ worldSize }, lngLat); + let modifiedX, modifiedY; + const scale = Math.max(scaleX || 0, scaleY || 0); + if (scale) { + // zoom in to exclude all beyond the given lng/lat ranges + const newPoint = new performance$1.P(scaleX ? (maxX + minX) / 2 : originalX, scaleY ? (maxY + minY) / 2 : originalY); + result.center = this.unproject.call({ worldSize }, newPoint).wrap(); + result.zoom += this.scaleZoom(scale); + return result; + } + if (this.latRange) { + const h2 = screenHeight / 2; + if (originalY - h2 < minY) + modifiedY = minY + h2; + if (originalY + h2 > maxY) + modifiedY = maxY - h2; + } + if (lngRange) { + const centerX = (minX + maxX) / 2; + let wrappedX = originalX; + if (this._renderWorldCopies) { + wrappedX = performance$1.b3(originalX, centerX - worldSize / 2, centerX + worldSize / 2); + } + const w2 = screenWidth / 2; + if (wrappedX - w2 < minX) + modifiedX = minX + w2; + if (wrappedX + w2 > maxX) + modifiedX = maxX - w2; + } + // pan the map if the screen goes off the range + if (modifiedX !== undefined || modifiedY !== undefined) { + const newPoint = new performance$1.P(modifiedX !== null && modifiedX !== void 0 ? modifiedX : originalX, modifiedY !== null && modifiedY !== void 0 ? modifiedY : originalY); + result.center = this.unproject.call({ worldSize }, newPoint).wrap(); + } + return result; + } + _constrain() { + if (!this.center || !this.width || !this.height || this._constraining) + return; + this._constraining = true; + const unmodified = this._unmodified; + const { center, zoom } = this.getConstrained(this.center, this.zoom); + this.center = center; + this.zoom = zoom; + this._unmodified = unmodified; + this._constraining = false; + } + _calcMatrices() { + if (!this.height) + return; + const halfFov = this._fov / 2; + const offset = this.centerOffset; + const x = this.point.x, y = this.point.y; + this.cameraToCenterDistance = 0.5 / Math.tan(halfFov) * this.height; + this._pixelPerMeter = performance$1.b5(1, this.center.lat) * this.worldSize; + let m = performance$1.an(new Float64Array(16)); + performance$1.K(m, m, [this.width / 2, -this.height / 2, 1]); + performance$1.J(m, m, [1, -1, 0]); + this.labelPlaneMatrix = m; + m = performance$1.an(new Float64Array(16)); + performance$1.K(m, m, [1, -1, 1]); + performance$1.J(m, m, [-1, -1, 0]); + performance$1.K(m, m, [2 / this.width, 2 / this.height, 1]); + this.glCoordMatrix = m; + // Calculate the camera to sea-level distance in pixel in respect of terrain + const cameraToSeaLevelDistance = this.cameraToCenterDistance + this._elevation * this._pixelPerMeter / Math.cos(this._pitch); + // In case of negative minimum elevation (e.g. the dead see, under the sea maps) use a lower plane for calculation + const minElevation = Math.min(this.elevation, this.minElevationForCurrentTile); + const cameraToLowestPointDistance = cameraToSeaLevelDistance - minElevation * this._pixelPerMeter / Math.cos(this._pitch); + const lowestPlane = minElevation < 0 ? cameraToLowestPointDistance : cameraToSeaLevelDistance; + // Find the distance from the center point [width/2 + offset.x, height/2 + offset.y] to the + // center top point [width/2 + offset.x, 0] in Z units, using the law of sines. + // 1 Z unit is equivalent to 1 horizontal px at the center of the map + // (the distance between[width/2, height/2] and [width/2 + 1, height/2]) + const groundAngle = Math.PI / 2 + this._pitch; + const fovAboveCenter = this._fov * (0.5 + offset.y / this.height); + const topHalfSurfaceDistance = Math.sin(fovAboveCenter) * lowestPlane / Math.sin(performance$1.ac(Math.PI - groundAngle - fovAboveCenter, 0.01, Math.PI - 0.01)); + // Find the distance from the center point to the horizon + const horizon = this.getHorizon(); + const horizonAngle = Math.atan(horizon / this.cameraToCenterDistance); + const fovCenterToHorizon = 2 * horizonAngle * (0.5 + offset.y / (horizon * 2)); + const topHalfSurfaceDistanceHorizon = Math.sin(fovCenterToHorizon) * lowestPlane / Math.sin(performance$1.ac(Math.PI - groundAngle - fovCenterToHorizon, 0.01, Math.PI - 0.01)); + // Calculate z distance of the farthest fragment that should be rendered. + // Add a bit extra to avoid precision problems when a fragment's distance is exactly `furthestDistance` + const topHalfMinDistance = Math.min(topHalfSurfaceDistance, topHalfSurfaceDistanceHorizon); + this.farZ = (Math.cos(Math.PI / 2 - this._pitch) * topHalfMinDistance + lowestPlane) * 1.01; + // The larger the value of nearZ is + // - the more depth precision is available for features (good) + // - clipping starts appearing sooner when the camera is close to 3d features (bad) + // + // Other values work for mapbox-gl-js but deck.gl was encountering precision issues + // when rendering custom layers. This value was experimentally chosen and + // seems to solve z-fighting issues in deck.gl while not clipping buildings too close to the camera. + this.nearZ = this.height / 50; + // matrix for conversion from location to clip space(-1 .. 1) + m = new Float64Array(16); + performance$1.b6(m, this._fov, this.width / this.height, this.nearZ, this.farZ); + // Apply center of perspective offset + m[8] = -offset.x * 2 / this.width; + m[9] = offset.y * 2 / this.height; + this.projectionMatrix = performance$1.ae(m); + performance$1.K(m, m, [1, -1, 1]); + performance$1.J(m, m, [0, 0, -this.cameraToCenterDistance]); + performance$1.b7(m, m, this._pitch); + performance$1.ad(m, m, this.angle); + performance$1.J(m, m, [-x, -y, 0]); + // The mercatorMatrix can be used to transform points from mercator coordinates + // ([0, 0] nw, [1, 1] se) to clip space. + this.mercatorMatrix = performance$1.K([], m, [this.worldSize, this.worldSize, this.worldSize]); + // scale vertically to meters per pixel (inverse of ground resolution): + performance$1.K(m, m, [1, 1, this._pixelPerMeter]); + // matrix for conversion from world space to screen coordinates in 2D + this.pixelMatrix = performance$1.L(new Float64Array(16), this.labelPlaneMatrix, m); + // matrix for conversion from world space to clip space (-1 .. 1) + performance$1.J(m, m, [0, 0, -this.elevation]); // elevate camera over terrain + this.modelViewProjectionMatrix = m; + this.invModelViewProjectionMatrix = performance$1.as([], m); + // create a fog matrix, same es proj-matrix but with near clipping-plane in mapcenter + // needed to calculate a correct z-value for fog calculation, because projMatrix z value is not + this.fogMatrix = new Float64Array(16); + performance$1.b6(this.fogMatrix, this._fov, this.width / this.height, cameraToSeaLevelDistance, this.farZ); + this.fogMatrix[8] = -offset.x * 2 / this.width; + this.fogMatrix[9] = offset.y * 2 / this.height; + performance$1.K(this.fogMatrix, this.fogMatrix, [1, -1, 1]); + performance$1.J(this.fogMatrix, this.fogMatrix, [0, 0, -this.cameraToCenterDistance]); + performance$1.b7(this.fogMatrix, this.fogMatrix, this._pitch); + performance$1.ad(this.fogMatrix, this.fogMatrix, this.angle); + performance$1.J(this.fogMatrix, this.fogMatrix, [-x, -y, 0]); + performance$1.K(this.fogMatrix, this.fogMatrix, [1, 1, this._pixelPerMeter]); + performance$1.J(this.fogMatrix, this.fogMatrix, [0, 0, -this.elevation]); // elevate camera over terrain + // matrix for conversion from world space to screen coordinates in 3D + this.pixelMatrix3D = performance$1.L(new Float64Array(16), this.labelPlaneMatrix, m); + // Make a second projection matrix that is aligned to a pixel grid for rendering raster tiles. + // We're rounding the (floating point) x/y values to achieve to avoid rendering raster images to fractional + // coordinates. Additionally, we adjust by half a pixel in either direction in case that viewport dimension + // is an odd integer to preserve rendering to the pixel grid. We're rotating this shift based on the angle + // of the transformation so that 0°, 90°, 180°, and 270° rasters are crisp, and adjust the shift so that + // it is always <= 0.5 pixels. + const xShift = (this.width % 2) / 2, yShift = (this.height % 2) / 2, angleCos = Math.cos(this.angle), angleSin = Math.sin(this.angle), dx = x - Math.round(x) + angleCos * xShift + angleSin * yShift, dy = y - Math.round(y) + angleCos * yShift + angleSin * xShift; + const alignedM = new Float64Array(m); + performance$1.J(alignedM, alignedM, [dx > 0.5 ? dx - 1 : dx, dy > 0.5 ? dy - 1 : dy, 0]); + this.alignedModelViewProjectionMatrix = alignedM; + // inverse matrix for conversion from screen coordinates to location + m = performance$1.as(new Float64Array(16), this.pixelMatrix); + if (!m) + throw new Error('failed to invert matrix'); + this.pixelMatrixInverse = m; + this._posMatrixCache = {}; + this._alignedPosMatrixCache = {}; + this._fogMatrixCache = {}; + } + maxPitchScaleFactor() { + // calcMatrices hasn't run yet + if (!this.pixelMatrixInverse) + return 1; + const coord = this.pointCoordinate(new performance$1.P(0, 0)); + const p = [coord.x * this.worldSize, coord.y * this.worldSize, 0, 1]; + const topPoint = performance$1.af(p, p, this.pixelMatrix); + return topPoint[3] / this.cameraToCenterDistance; + } + /** + * The camera looks at the map from a 3D (lng, lat, altitude) location. Let's use `cameraLocation` + * as the name for the location under the camera and on the surface of the earth (lng, lat, 0). + * `cameraPoint` is the projected position of the `cameraLocation`. + * + * This point is useful to us because only fill-extrusions that are between `cameraPoint` and + * the query point on the surface of the earth can extend and intersect the query. + * + * When the map is not pitched the `cameraPoint` is equivalent to the center of the map because + * the camera is right above the center of the map. + */ + getCameraPoint() { + const pitch = this._pitch; + const yOffset = Math.tan(pitch) * (this.cameraToCenterDistance || 1); + return this.centerPoint.add(new performance$1.P(0, yOffset)); + } + /** + * When the map is pitched, some of the 3D features that intersect a query will not intersect + * the query at the surface of the earth. Instead the feature may be closer and only intersect + * the query because it extrudes into the air. + * @param queryGeometry - For point queries, the line from the query point to the "camera point", + * for other geometries, the envelope of the query geometry and the "camera point" + * @returns a geometry that includes all of the original query as well as all possible ares of the + * screen where the *base* of a visible extrusion could be. + * + */ + getCameraQueryGeometry(queryGeometry) { + const c = this.getCameraPoint(); + if (queryGeometry.length === 1) { + return [queryGeometry[0], c]; + } + else { + let minX = c.x; + let minY = c.y; + let maxX = c.x; + let maxY = c.y; + for (const p of queryGeometry) { + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + return [ + new performance$1.P(minX, minY), + new performance$1.P(maxX, minY), + new performance$1.P(maxX, maxY), + new performance$1.P(minX, maxY), + new performance$1.P(minX, minY) + ]; + } + } + /** + * Return the distance to the camera in clip space from a LngLat. + * This can be compared to the value from the depth buffer (terrain.depthAtPoint) + * to determine whether a point is occluded. + * @param lngLat - the point + * @param elevation - the point's elevation + * @returns depth value in clip space (between 0 and 1) + */ + lngLatToCameraDepth(lngLat, elevation) { + const coord = this.locationCoordinate(lngLat); + const p = [coord.x * this.worldSize, coord.y * this.worldSize, elevation, 1]; + performance$1.af(p, p, this.modelViewProjectionMatrix); + return (p[2] / p[3]); + } +} + +/** + * Throttle the given function to run at most every `period` milliseconds. + */ +function throttle(fn, time) { + let pending = false; + let timerId = null; + let lastCallContext = null; + let lastCallArgs; + const later = () => { + timerId = null; + if (pending) { + fn.apply(lastCallContext, lastCallArgs); + timerId = setTimeout(later, time); + pending = false; + } + }; + return (...args) => { + pending = true; + lastCallContext = this; + lastCallArgs = args; + if (!timerId) { + later(); + } + return timerId; + }; +} + +/** + * Adds the map's position to its page's location hash. + * Passed as an option to the map object. + * + * @group Markers and Controls + */ +class Hash { + constructor(hashName) { + this._getCurrentHash = () => { + // Get the current hash from location, stripped from its number sign + const hash = window.location.hash.replace('#', ''); + if (this._hashName) { + // Split the parameter-styled hash into parts and find the value we need + let keyval; + hash.split('&').map(part => part.split('=')).forEach(part => { + if (part[0] === this._hashName) { + keyval = part; + } + }); + return (keyval ? keyval[1] || '' : '').split('/'); + } + return hash.split('/'); + }; + this._onHashChange = () => { + const loc = this._getCurrentHash(); + if (loc.length >= 3 && !loc.some(v => isNaN(v))) { + const bearing = this._map.dragRotate.isEnabled() && this._map.touchZoomRotate.isEnabled() ? +(loc[3] || 0) : this._map.getBearing(); + this._map.jumpTo({ + center: [+loc[2], +loc[1]], + zoom: +loc[0], + bearing, + pitch: +(loc[4] || 0) + }); + return true; + } + return false; + }; + this._updateHashUnthrottled = () => { + // Replace if already present, else append the updated hash string + const location = window.location.href.replace(/(#.+)?$/, this.getHashString()); + window.history.replaceState(window.history.state, null, location); + }; + this._removeHash = () => { + const currentHash = this._getCurrentHash(); + if (currentHash.length === 0) { + return; + } + const baseHash = currentHash.join('/'); + let targetHash = baseHash; + if (targetHash.split('&').length > 0) { + targetHash = targetHash.split('&')[0]; // #3/1/2&foo=bar -> #3/1/2 + } + if (this._hashName) { + targetHash = `${this._hashName}=${baseHash}`; + } + let replaceString = window.location.hash.replace(targetHash, ''); + if (replaceString.startsWith('#&')) { + replaceString = replaceString.slice(0, 1) + replaceString.slice(2); + } + else if (replaceString === '#') { + replaceString = ''; + } + let location = window.location.href.replace(/(#.+)?$/, replaceString); + location = location.replace('&&', '&'); + window.history.replaceState(window.history.state, null, location); + }; + /** + * Mobile Safari doesn't allow updating the hash more than 100 times per 30 seconds. + */ + this._updateHash = throttle(this._updateHashUnthrottled, 30 * 1000 / 100); + this._hashName = hashName && encodeURIComponent(hashName); + } + /** + * Map element to listen for coordinate changes + * + * @param map - The map object + */ + addTo(map) { + this._map = map; + addEventListener('hashchange', this._onHashChange, false); + this._map.on('moveend', this._updateHash); + return this; + } + /** + * Removes hash + */ + remove() { + removeEventListener('hashchange', this._onHashChange, false); + this._map.off('moveend', this._updateHash); + clearTimeout(this._updateHash()); + this._removeHash(); + delete this._map; + return this; + } + getHashString(mapFeedback) { + const center = this._map.getCenter(), zoom = Math.round(this._map.getZoom() * 100) / 100, + // derived from equation: 512px * 2^z / 360 / 10^d < 0.5px + precision = Math.ceil((zoom * Math.LN2 + Math.log(512 / 360 / 0.5)) / Math.LN10), m = Math.pow(10, precision), lng = Math.round(center.lng * m) / m, lat = Math.round(center.lat * m) / m, bearing = this._map.getBearing(), pitch = this._map.getPitch(); + let hash = ''; + if (mapFeedback) { + // new map feedback site has some constraints that don't allow + // us to use the same hash format as we do for the Map hash option. + hash += `/${lng}/${lat}/${zoom}`; + } + else { + hash += `${zoom}/${lat}/${lng}`; + } + if (bearing || pitch) + hash += (`/${Math.round(bearing * 10) / 10}`); + if (pitch) + hash += (`/${Math.round(pitch)}`); + if (this._hashName) { + const hashName = this._hashName; + let found = false; + const parts = window.location.hash.slice(1).split('&').map(part => { + const key = part.split('=')[0]; + if (key === hashName) { + found = true; + return `${key}=${hash}`; + } + return part; + }).filter(a => a); + if (!found) { + parts.push(`${hashName}=${hash}`); + } + return `#${parts.join('&')}`; + } + return `#${hash}`; + } +} + +const defaultInertiaOptions = { + linearity: 0.3, + easing: performance$1.b8(0, 0, 0.3, 1), +}; +const defaultPanInertiaOptions = performance$1.e({ + deceleration: 2500, + maxSpeed: 1400 +}, defaultInertiaOptions); +const defaultZoomInertiaOptions = performance$1.e({ + deceleration: 20, + maxSpeed: 1400 +}, defaultInertiaOptions); +const defaultBearingInertiaOptions = performance$1.e({ + deceleration: 1000, + maxSpeed: 360 +}, defaultInertiaOptions); +const defaultPitchInertiaOptions = performance$1.e({ + deceleration: 1000, + maxSpeed: 90 +}, defaultInertiaOptions); +class HandlerInertia { + constructor(map) { + this._map = map; + this.clear(); + } + clear() { + this._inertiaBuffer = []; + } + record(settings) { + this._drainInertiaBuffer(); + this._inertiaBuffer.push({ time: browser.now(), settings }); + } + _drainInertiaBuffer() { + const inertia = this._inertiaBuffer, now = browser.now(), cutoff = 160; //msec + while (inertia.length > 0 && now - inertia[0].time > cutoff) + inertia.shift(); + } + _onMoveEnd(panInertiaOptions) { + this._drainInertiaBuffer(); + if (this._inertiaBuffer.length < 2) { + return; + } + const deltas = { + zoom: 0, + bearing: 0, + pitch: 0, + pan: new performance$1.P(0, 0), + pinchAround: undefined, + around: undefined + }; + for (const { settings } of this._inertiaBuffer) { + deltas.zoom += settings.zoomDelta || 0; + deltas.bearing += settings.bearingDelta || 0; + deltas.pitch += settings.pitchDelta || 0; + if (settings.panDelta) + deltas.pan._add(settings.panDelta); + if (settings.around) + deltas.around = settings.around; + if (settings.pinchAround) + deltas.pinchAround = settings.pinchAround; + } + const lastEntry = this._inertiaBuffer[this._inertiaBuffer.length - 1]; + const duration = (lastEntry.time - this._inertiaBuffer[0].time); + const easeOptions = {}; + if (deltas.pan.mag()) { + const result = calculateEasing(deltas.pan.mag(), duration, performance$1.e({}, defaultPanInertiaOptions, panInertiaOptions || {})); + easeOptions.offset = deltas.pan.mult(result.amount / deltas.pan.mag()); + easeOptions.center = this._map.transform.center; + extendDuration(easeOptions, result); + } + if (deltas.zoom) { + const result = calculateEasing(deltas.zoom, duration, defaultZoomInertiaOptions); + easeOptions.zoom = this._map.transform.zoom + result.amount; + extendDuration(easeOptions, result); + } + if (deltas.bearing) { + const result = calculateEasing(deltas.bearing, duration, defaultBearingInertiaOptions); + easeOptions.bearing = this._map.transform.bearing + performance$1.ac(result.amount, -179, 179); + extendDuration(easeOptions, result); + } + if (deltas.pitch) { + const result = calculateEasing(deltas.pitch, duration, defaultPitchInertiaOptions); + easeOptions.pitch = this._map.transform.pitch + result.amount; + extendDuration(easeOptions, result); + } + if (easeOptions.zoom || easeOptions.bearing) { + const last = deltas.pinchAround === undefined ? deltas.around : deltas.pinchAround; + easeOptions.around = last ? this._map.unproject(last) : this._map.getCenter(); + } + this.clear(); + return performance$1.e(easeOptions, { + noMoveStart: true + }); + } +} +// Unfortunately zoom, bearing, etc can't have different durations and easings so +// we need to choose one. We use the longest duration and it's corresponding easing. +function extendDuration(easeOptions, result) { + if (!easeOptions.duration || easeOptions.duration < result.duration) { + easeOptions.duration = result.duration; + easeOptions.easing = result.easing; + } +} +function calculateEasing(amount, inertiaDuration, inertiaOptions) { + const { maxSpeed, linearity, deceleration } = inertiaOptions; + const speed = performance$1.ac(amount * linearity / (inertiaDuration / 1000), -maxSpeed, maxSpeed); + const duration = Math.abs(speed) / (deceleration * linearity); + return { + easing: inertiaOptions.easing, + duration: duration * 1000, + amount: speed * (duration / 2) + }; +} + +/** + * `MapMouseEvent` is the event type for mouse-related map events. + * + * @group Event Related + * + * @example + * ```ts + * // The `click` event is an example of a `MapMouseEvent`. + * // Set up an event listener on the map. + * map.on('click', (e) => { + * // The event object (e) contains information like the + * // coordinates of the point on the map that was clicked. + * console.log('A click event has occurred at ' + e.lngLat); + * }); + * ``` + */ +class MapMouseEvent extends performance$1.k { + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the following default map behaviors: + * + * * On `mousedown` events, the behavior of {@link DragPanHandler} + * * On `mousedown` events, the behavior of {@link DragRotateHandler} + * * On `mousedown` events, the behavior of {@link BoxZoomHandler} + * * On `dblclick` events, the behavior of {@link DoubleClickZoomHandler} + * + */ + preventDefault() { + this._defaultPrevented = true; + } + /** + * `true` if `preventDefault` has been called. + */ + get defaultPrevented() { + return this._defaultPrevented; + } + constructor(type, map, originalEvent, data = {}) { + const point = DOM.mousePos(map.getCanvas(), originalEvent); + const lngLat = map.unproject(point); + super(type, performance$1.e({ point, lngLat, originalEvent }, data)); + this._defaultPrevented = false; + this.target = map; + } +} +/** + * `MapTouchEvent` is the event type for touch-related map events. + * + * @group Event Related + */ +class MapTouchEvent extends performance$1.k { + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the following default map behaviors: + * + * * On `touchstart` events, the behavior of {@link DragPanHandler} + * * On `touchstart` events, the behavior of {@link TwoFingersTouchZoomRotateHandler} + * + */ + preventDefault() { + this._defaultPrevented = true; + } + /** + * `true` if `preventDefault` has been called. + */ + get defaultPrevented() { + return this._defaultPrevented; + } + constructor(type, map, originalEvent) { + const touches = type === 'touchend' ? originalEvent.changedTouches : originalEvent.touches; + const points = DOM.touchPos(map.getCanvasContainer(), touches); + const lngLats = points.map((t) => map.unproject(t)); + const point = points.reduce((prev, curr, i, arr) => { + return prev.add(curr.div(arr.length)); + }, new performance$1.P(0, 0)); + const lngLat = map.unproject(point); + super(type, { points, point, lngLats, lngLat, originalEvent }); + this._defaultPrevented = false; + } +} +/** + * `MapWheelEvent` is the event type for the `wheel` map event. + * + * @group Event Related + */ +class MapWheelEvent extends performance$1.k { + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the behavior of {@link ScrollZoomHandler}. + */ + preventDefault() { + this._defaultPrevented = true; + } + /** + * `true` if `preventDefault` has been called. + */ + get defaultPrevented() { + return this._defaultPrevented; + } + /** */ + constructor(type, map, originalEvent) { + super(type, { originalEvent }); + this._defaultPrevented = false; + } +} + +class MapEventHandler { + constructor(map, options) { + this._map = map; + this._clickTolerance = options.clickTolerance; + } + reset() { + delete this._mousedownPos; + } + wheel(e) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - ScrollZoom + return this._firePreventable(new MapWheelEvent(e.type, this._map, e)); + } + mousedown(e, point) { + this._mousedownPos = point; + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - MousePan + // - MouseRotate + // - MousePitch + // - DblclickHandler + return this._firePreventable(new MapMouseEvent(e.type, this._map, e)); + } + mouseup(e) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + click(e, point) { + if (this._mousedownPos && this._mousedownPos.dist(point) >= this._clickTolerance) + return; + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + dblclick(e) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - DblClickZoom + return this._firePreventable(new MapMouseEvent(e.type, this._map, e)); + } + mouseover(e) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + mouseout(e) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + touchstart(e) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - TouchPan + // - TouchZoom + // - TouchRotate + // - TouchPitch + // - TapZoom + // - SwipeZoom + return this._firePreventable(new MapTouchEvent(e.type, this._map, e)); + } + touchmove(e) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + touchend(e) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + touchcancel(e) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + _firePreventable(mapEvent) { + this._map.fire(mapEvent); + if (mapEvent.defaultPrevented) { + // returning an object marks the handler as active and resets other handlers + return {}; + } + } + isEnabled() { + return true; + } + isActive() { + return false; + } + enable() { } + disable() { } +} +class BlockableMapEventHandler { + constructor(map) { + this._map = map; + } + reset() { + this._delayContextMenu = false; + this._ignoreContextMenu = true; + delete this._contextMenuEvent; + } + mousemove(e) { + // mousemove map events should not be fired when interaction handlers (pan, rotate, etc) are active + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + mousedown() { + this._delayContextMenu = true; + this._ignoreContextMenu = false; + } + mouseup() { + this._delayContextMenu = false; + if (this._contextMenuEvent) { + this._map.fire(new MapMouseEvent('contextmenu', this._map, this._contextMenuEvent)); + delete this._contextMenuEvent; + } + } + contextmenu(e) { + if (this._delayContextMenu) { + // Mac: contextmenu fired on mousedown; we save it until mouseup for consistency's sake + this._contextMenuEvent = e; + } + else if (!this._ignoreContextMenu) { + // Windows: contextmenu fired on mouseup, so fire event now + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + // prevent browser context menu when necessary + if (this._map.listens('contextmenu')) { + e.preventDefault(); + } + } + isEnabled() { + return true; + } + isActive() { + return false; + } + enable() { } + disable() { } +} + +/** + * @internal + * Shared utilities for the Handler classes to access the correct camera state. + * If Camera.transformCameraUpdate is specified or terrain is enabled, the + * "desired state" of camera may differ from the state used for rendering. The + * handlers need the "desired state" to track accumulated changes. + */ +class TransformProvider { + constructor(map) { + this._map = map; + } + get transform() { + return this._map._requestedCameraState || this._map.transform; + } + get center() { + return { lng: this.transform.center.lng, lat: this.transform.center.lat }; + } + get zoom() { + return this.transform.zoom; + } + get pitch() { + return this.transform.pitch; + } + get bearing() { + return this.transform.bearing; + } + unproject(point) { + return this.transform.pointLocation(performance$1.P.convert(point), this._map.terrain); + } +} + +/** + * The `BoxZoomHandler` allows the user to zoom the map to fit within a bounding box. + * The bounding box is defined by clicking and holding `shift` while dragging the cursor. + * + * @group Handlers + */ +class BoxZoomHandler { + /** @internal */ + constructor(map, options) { + this._map = map; + this._tr = new TransformProvider(map); + this._el = map.getCanvasContainer(); + this._container = map.getContainer(); + this._clickTolerance = options.clickTolerance || 1; + } + /** + * Returns a Boolean indicating whether the "box zoom" interaction is enabled. + * + * @returns `true` if the "box zoom" interaction is enabled. + */ + isEnabled() { + return !!this._enabled; + } + /** + * Returns a Boolean indicating whether the "box zoom" interaction is active, i.e. currently being used. + * + * @returns `true` if the "box zoom" interaction is active. + */ + isActive() { + return !!this._active; + } + /** + * Enables the "box zoom" interaction. + * + * @example + * ```ts + * map.boxZoom.enable(); + * ``` + */ + enable() { + if (this.isEnabled()) + return; + this._enabled = true; + } + /** + * Disables the "box zoom" interaction. + * + * @example + * ```ts + * map.boxZoom.disable(); + * ``` + */ + disable() { + if (!this.isEnabled()) + return; + this._enabled = false; + } + mousedown(e, point) { + if (!this.isEnabled()) + return; + if (!(e.shiftKey && e.button === 0)) + return; + DOM.disableDrag(); + this._startPos = this._lastPos = point; + this._active = true; + } + mousemoveWindow(e, point) { + if (!this._active) + return; + const pos = point; + if (this._lastPos.equals(pos) || (!this._box && pos.dist(this._startPos) < this._clickTolerance)) { + return; + } + const p0 = this._startPos; + this._lastPos = pos; + if (!this._box) { + this._box = DOM.create('div', 'maplibregl-boxzoom', this._container); + this._container.classList.add('maplibregl-crosshair'); + this._fireEvent('boxzoomstart', e); + } + const minX = Math.min(p0.x, pos.x), maxX = Math.max(p0.x, pos.x), minY = Math.min(p0.y, pos.y), maxY = Math.max(p0.y, pos.y); + DOM.setTransform(this._box, `translate(${minX}px,${minY}px)`); + this._box.style.width = `${maxX - minX}px`; + this._box.style.height = `${maxY - minY}px`; + } + mouseupWindow(e, point) { + if (!this._active) + return; + if (e.button !== 0) + return; + const p0 = this._startPos, p1 = point; + this.reset(); + DOM.suppressClick(); + if (p0.x === p1.x && p0.y === p1.y) { + this._fireEvent('boxzoomcancel', e); + } + else { + this._map.fire(new performance$1.k('boxzoomend', { originalEvent: e })); + return { + cameraAnimation: map => map.fitScreenCoordinates(p0, p1, this._tr.bearing, { linear: true }) + }; + } + } + keydown(e) { + if (!this._active) + return; + if (e.keyCode === 27) { + this.reset(); + this._fireEvent('boxzoomcancel', e); + } + } + reset() { + this._active = false; + this._container.classList.remove('maplibregl-crosshair'); + if (this._box) { + DOM.remove(this._box); + this._box = null; + } + DOM.enableDrag(); + delete this._startPos; + delete this._lastPos; + } + _fireEvent(type, e) { + return this._map.fire(new performance$1.k(type, { originalEvent: e })); + } +} + +function indexTouches(touches, points) { + if (touches.length !== points.length) + throw new Error(`The number of touches and points are not equal - touches ${touches.length}, points ${points.length}`); + const obj = {}; + for (let i = 0; i < touches.length; i++) { + obj[touches[i].identifier] = points[i]; + } + return obj; +} + +function getCentroid(points) { + const sum = new performance$1.P(0, 0); + for (const point of points) { + sum._add(point); + } + return sum.div(points.length); +} +const MAX_TAP_INTERVAL = 500; +const MAX_TOUCH_TIME = 500; +const MAX_DIST = 30; +class SingleTapRecognizer { + constructor(options) { + this.reset(); + this.numTouches = options.numTouches; + } + reset() { + delete this.centroid; + delete this.startTime; + delete this.touches; + this.aborted = false; + } + touchstart(e, points, mapTouches) { + if (this.centroid || mapTouches.length > this.numTouches) { + this.aborted = true; + } + if (this.aborted) { + return; + } + if (this.startTime === undefined) { + this.startTime = e.timeStamp; + } + if (mapTouches.length === this.numTouches) { + this.centroid = getCentroid(points); + this.touches = indexTouches(mapTouches, points); + } + } + touchmove(e, points, mapTouches) { + if (this.aborted || !this.centroid) + return; + const newTouches = indexTouches(mapTouches, points); + for (const id in this.touches) { + const prevPos = this.touches[id]; + const pos = newTouches[id]; + if (!pos || pos.dist(prevPos) > MAX_DIST) { + this.aborted = true; + } + } + } + touchend(e, points, mapTouches) { + if (!this.centroid || e.timeStamp - this.startTime > MAX_TOUCH_TIME) { + this.aborted = true; + } + if (mapTouches.length === 0) { + const centroid = !this.aborted && this.centroid; + this.reset(); + if (centroid) + return centroid; + } + } +} +class TapRecognizer { + constructor(options) { + this.singleTap = new SingleTapRecognizer(options); + this.numTaps = options.numTaps; + this.reset(); + } + reset() { + this.lastTime = Infinity; + delete this.lastTap; + this.count = 0; + this.singleTap.reset(); + } + touchstart(e, points, mapTouches) { + this.singleTap.touchstart(e, points, mapTouches); + } + touchmove(e, points, mapTouches) { + this.singleTap.touchmove(e, points, mapTouches); + } + touchend(e, points, mapTouches) { + const tap = this.singleTap.touchend(e, points, mapTouches); + if (tap) { + const soonEnough = e.timeStamp - this.lastTime < MAX_TAP_INTERVAL; + const closeEnough = !this.lastTap || this.lastTap.dist(tap) < MAX_DIST; + if (!soonEnough || !closeEnough) { + this.reset(); + } + this.count++; + this.lastTime = e.timeStamp; + this.lastTap = tap; + if (this.count === this.numTaps) { + this.reset(); + return tap; + } + } + } +} + +/** + * A `TapZoomHandler` allows the user to zoom the map at a point by double tapping + */ +class TapZoomHandler { + constructor(map) { + this._tr = new TransformProvider(map); + this._zoomIn = new TapRecognizer({ + numTouches: 1, + numTaps: 2 + }); + this._zoomOut = new TapRecognizer({ + numTouches: 2, + numTaps: 1 + }); + this.reset(); + } + reset() { + this._active = false; + this._zoomIn.reset(); + this._zoomOut.reset(); + } + touchstart(e, points, mapTouches) { + this._zoomIn.touchstart(e, points, mapTouches); + this._zoomOut.touchstart(e, points, mapTouches); + } + touchmove(e, points, mapTouches) { + this._zoomIn.touchmove(e, points, mapTouches); + this._zoomOut.touchmove(e, points, mapTouches); + } + touchend(e, points, mapTouches) { + const zoomInPoint = this._zoomIn.touchend(e, points, mapTouches); + const zoomOutPoint = this._zoomOut.touchend(e, points, mapTouches); + const tr = this._tr; + if (zoomInPoint) { + this._active = true; + e.preventDefault(); + setTimeout(() => this.reset(), 0); + return { + cameraAnimation: (map) => map.easeTo({ + duration: 300, + zoom: tr.zoom + 1, + around: tr.unproject(zoomInPoint) + }, { originalEvent: e }) + }; + } + else if (zoomOutPoint) { + this._active = true; + e.preventDefault(); + setTimeout(() => this.reset(), 0); + return { + cameraAnimation: (map) => map.easeTo({ + duration: 300, + zoom: tr.zoom - 1, + around: tr.unproject(zoomOutPoint) + }, { originalEvent: e }) + }; + } + } + touchcancel() { + this.reset(); + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } +} + +/** + * A generic class to create handlers for drag events, from both mouse and touch events. + */ +class DragHandler { + constructor(options) { + this._enabled = !!options.enable; + this._moveStateManager = options.moveStateManager; + this._clickTolerance = options.clickTolerance || 1; + this._moveFunction = options.move; + this._activateOnStart = !!options.activateOnStart; + options.assignEvents(this); + this.reset(); + } + reset(e) { + this._active = false; + this._moved = false; + delete this._lastPoint; + this._moveStateManager.endMove(e); + } + _move(...params) { + const move = this._moveFunction(...params); + if (move.bearingDelta || move.pitchDelta || move.around || move.panDelta) { + this._active = true; + return move; + } + } + dragStart(e, point) { + if (!this.isEnabled() || this._lastPoint) + return; + if (!this._moveStateManager.isValidStartEvent(e)) + return; + this._moveStateManager.startMove(e); + this._lastPoint = point['length'] ? point[0] : point; + if (this._activateOnStart && this._lastPoint) + this._active = true; + } + dragMove(e, point) { + if (!this.isEnabled()) + return; + const lastPoint = this._lastPoint; + if (!lastPoint) + return; + e.preventDefault(); + if (!this._moveStateManager.isValidMoveEvent(e)) { + this.reset(e); + return; + } + const movePoint = point['length'] ? point[0] : point; + if (!this._moved && movePoint.dist(lastPoint) < this._clickTolerance) + return; + this._moved = true; + this._lastPoint = movePoint; + return this._move(lastPoint, movePoint); + } + dragEnd(e) { + if (!this.isEnabled() || !this._lastPoint) + return; + if (!this._moveStateManager.isValidEndEvent(e)) + return; + if (this._moved) + DOM.suppressClick(); + this.reset(e); + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } + getClickTolerance() { + return this._clickTolerance; + } +} + +const LEFT_BUTTON$1 = 0; +const RIGHT_BUTTON$1 = 2; +// the values for each button in MouseEvent.buttons +const BUTTONS_FLAGS = { + [LEFT_BUTTON$1]: 1, + [RIGHT_BUTTON$1]: 2 +}; +function buttonNoLongerPressed(e, button) { + const flag = BUTTONS_FLAGS[button]; + return e.buttons === undefined || (e.buttons & flag) !== flag; +} +class MouseMoveStateManager { + constructor(options) { + this._correctEvent = options.checkCorrectEvent; + } + startMove(e) { + const eventButton = DOM.mouseButton(e); + this._eventButton = eventButton; + } + endMove(_e) { + delete this._eventButton; + } + isValidStartEvent(e) { + return this._correctEvent(e); + } + isValidMoveEvent(e) { + // Some browsers don't fire a `mouseup` when the mouseup occurs outside + // the window or iframe: + // https://github.com/mapbox/mapbox-gl-js/issues/4622 + // + // If the button is no longer pressed during this `mousemove` it may have + // been released outside of the window or iframe. + return !buttonNoLongerPressed(e, this._eventButton); + } + isValidEndEvent(e) { + const eventButton = DOM.mouseButton(e); + return eventButton === this._eventButton; + } +} +class OneFingerTouchMoveStateManager { + constructor() { + this._firstTouch = undefined; + } + _isOneFingerTouch(e) { + return e.targetTouches.length === 1; + } + _isSameTouchEvent(e) { + return e.targetTouches[0].identifier === this._firstTouch; + } + startMove(e) { + const firstTouch = e.targetTouches[0].identifier; + this._firstTouch = firstTouch; + } + endMove(_e) { + delete this._firstTouch; + } + isValidStartEvent(e) { + return this._isOneFingerTouch(e); + } + isValidMoveEvent(e) { + return this._isOneFingerTouch(e) && this._isSameTouchEvent(e); + } + isValidEndEvent(e) { + return this._isOneFingerTouch(e) && this._isSameTouchEvent(e); + } +} + +const LEFT_BUTTON = 0; +const RIGHT_BUTTON = 2; +const assignEvents$1 = (handler) => { + handler.mousedown = handler.dragStart; + handler.mousemoveWindow = handler.dragMove; + handler.mouseup = handler.dragEnd; + handler.contextmenu = (e) => { + e.preventDefault(); + }; +}; +const generateMousePanHandler = ({ enable, clickTolerance, }) => { + const mouseMoveStateManager = new MouseMoveStateManager({ + checkCorrectEvent: (e) => DOM.mouseButton(e) === LEFT_BUTTON && !e.ctrlKey, + }); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ around: point, panDelta: point.sub(lastPoint) }), + activateOnStart: true, + moveStateManager: mouseMoveStateManager, + enable, + assignEvents: assignEvents$1, + }); +}; +const generateMouseRotationHandler = ({ enable, clickTolerance, bearingDegreesPerPixelMoved = 0.8 }) => { + const mouseMoveStateManager = new MouseMoveStateManager({ + checkCorrectEvent: (e) => (DOM.mouseButton(e) === LEFT_BUTTON && e.ctrlKey) || + (DOM.mouseButton(e) === RIGHT_BUTTON), + }); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ bearingDelta: (point.x - lastPoint.x) * bearingDegreesPerPixelMoved }), + // prevent browser context menu when necessary; we don't allow it with rotation + // because we can't discern rotation gesture start from contextmenu on Mac + moveStateManager: mouseMoveStateManager, + enable, + assignEvents: assignEvents$1, + }); +}; +const generateMousePitchHandler = ({ enable, clickTolerance, pitchDegreesPerPixelMoved = -0.5 }) => { + const mouseMoveStateManager = new MouseMoveStateManager({ + checkCorrectEvent: (e) => (DOM.mouseButton(e) === LEFT_BUTTON && e.ctrlKey) || + (DOM.mouseButton(e) === RIGHT_BUTTON), + }); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ pitchDelta: (point.y - lastPoint.y) * pitchDegreesPerPixelMoved }), + // prevent browser context menu when necessary; we don't allow it with rotation + // because we can't discern rotation gesture start from contextmenu on Mac + moveStateManager: mouseMoveStateManager, + enable, + assignEvents: assignEvents$1, + }); +}; + +/** + * A `TouchPanHandler` allows the user to pan the map using touch gestures. + */ +class TouchPanHandler { + constructor(options, map) { + this._clickTolerance = options.clickTolerance || 1; + this._map = map; + this.reset(); + } + reset() { + this._active = false; + this._touches = {}; + this._sum = new performance$1.P(0, 0); + } + _shouldBePrevented(touchesCount) { + const minTouches = this._map.cooperativeGestures.isEnabled() ? 2 : 1; + return touchesCount < minTouches; + } + touchstart(e, points, mapTouches) { + return this._calculateTransform(e, points, mapTouches); + } + touchmove(e, points, mapTouches) { + if (!this._active) + return; + if (this._shouldBePrevented(mapTouches.length)) { + this._map.cooperativeGestures.notifyGestureBlocked('touch_pan', e); + return; + } + e.preventDefault(); + return this._calculateTransform(e, points, mapTouches); + } + touchend(e, points, mapTouches) { + this._calculateTransform(e, points, mapTouches); + if (this._active && this._shouldBePrevented(mapTouches.length)) { + this.reset(); + } + } + touchcancel() { + this.reset(); + } + _calculateTransform(e, points, mapTouches) { + if (mapTouches.length > 0) + this._active = true; + const touches = indexTouches(mapTouches, points); + const touchPointSum = new performance$1.P(0, 0); + const touchDeltaSum = new performance$1.P(0, 0); + let touchDeltaCount = 0; + for (const identifier in touches) { + const point = touches[identifier]; + const prevPoint = this._touches[identifier]; + if (prevPoint) { + touchPointSum._add(point); + touchDeltaSum._add(point.sub(prevPoint)); + touchDeltaCount++; + touches[identifier] = point; + } + } + this._touches = touches; + if (this._shouldBePrevented(touchDeltaCount) || !touchDeltaSum.mag()) + return; + const panDelta = touchDeltaSum.div(touchDeltaCount); + this._sum._add(panDelta); + if (this._sum.mag() < this._clickTolerance) + return; + const around = touchPointSum.div(touchDeltaCount); + return { + around, + panDelta + }; + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } +} + +/** + * The `TwoFingersTouchHandler`s allows the user to zoom, pitch and rotate the map using two fingers + * + */ +class TwoFingersTouchHandler { + /** @internal */ + constructor() { + this.reset(); + } + reset() { + this._active = false; + delete this._firstTwoTouches; + } + touchstart(e, points, mapTouches) { + //log('touchstart', points, e.target.innerHTML, e.targetTouches.length ? e.targetTouches[0].target.innerHTML: undefined); + if (this._firstTwoTouches || mapTouches.length < 2) + return; + this._firstTwoTouches = [ + mapTouches[0].identifier, + mapTouches[1].identifier + ]; + // implemented by child classes + this._start([points[0], points[1]]); + } + touchmove(e, points, mapTouches) { + if (!this._firstTwoTouches) + return; + e.preventDefault(); + const [idA, idB] = this._firstTwoTouches; + const a = getTouchById(mapTouches, points, idA); + const b = getTouchById(mapTouches, points, idB); + if (!a || !b) + return; + const pinchAround = this._aroundCenter ? null : a.add(b).div(2); + // implemented by child classes + return this._move([a, b], pinchAround, e); + } + touchend(e, points, mapTouches) { + if (!this._firstTwoTouches) + return; + const [idA, idB] = this._firstTwoTouches; + const a = getTouchById(mapTouches, points, idA); + const b = getTouchById(mapTouches, points, idB); + if (a && b) + return; + if (this._active) + DOM.suppressClick(); + this.reset(); + } + touchcancel() { + this.reset(); + } + /** + * Enables the "drag to pitch" interaction. + * + * @example + * ```ts + * map.touchPitch.enable(); + * ``` + */ + enable(options) { + this._enabled = true; + this._aroundCenter = !!options && options.around === 'center'; + } + /** + * Disables the "drag to pitch" interaction. + * + * @example + * ```ts + * map.touchPitch.disable(); + * ``` + */ + disable() { + this._enabled = false; + this.reset(); + } + /** + * Returns a Boolean indicating whether the "drag to pitch" interaction is enabled. + * + * @returns `true` if the "drag to pitch" interaction is enabled. + */ + isEnabled() { + return !!this._enabled; + } + /** + * Returns a Boolean indicating whether the "drag to pitch" interaction is active, i.e. currently being used. + * + * @returns `true` if the "drag to pitch" interaction is active. + */ + isActive() { + return !!this._active; + } +} +function getTouchById(mapTouches, points, identifier) { + for (let i = 0; i < mapTouches.length; i++) { + if (mapTouches[i].identifier === identifier) + return points[i]; + } + return undefined; +} +/* ZOOM */ +const ZOOM_THRESHOLD = 0.1; +function getZoomDelta(distance, lastDistance) { + return Math.log(distance / lastDistance) / Math.LN2; +} +/** + * The `TwoFingersTouchHandler`s allows the user to zoom the map two fingers + * + * @group Handlers + */ +class TwoFingersTouchZoomHandler extends TwoFingersTouchHandler { + reset() { + super.reset(); + delete this._distance; + delete this._startDistance; + } + _start(points) { + this._startDistance = this._distance = points[0].dist(points[1]); + } + _move(points, pinchAround) { + const lastDistance = this._distance; + this._distance = points[0].dist(points[1]); + if (!this._active && Math.abs(getZoomDelta(this._distance, this._startDistance)) < ZOOM_THRESHOLD) + return; + this._active = true; + return { + zoomDelta: getZoomDelta(this._distance, lastDistance), + pinchAround + }; + } +} +/* ROTATE */ +const ROTATION_THRESHOLD = 25; // pixels along circumference of touch circle +function getBearingDelta(a, b) { + return a.angleWith(b) * 180 / Math.PI; +} +/** + * The `TwoFingersTouchHandler`s allows the user to rotate the map two fingers + * + * @group Handlers + */ +class TwoFingersTouchRotateHandler extends TwoFingersTouchHandler { + reset() { + super.reset(); + delete this._minDiameter; + delete this._startVector; + delete this._vector; + } + _start(points) { + this._startVector = this._vector = points[0].sub(points[1]); + this._minDiameter = points[0].dist(points[1]); + } + _move(points, pinchAround, _e) { + const lastVector = this._vector; + this._vector = points[0].sub(points[1]); + if (!this._active && this._isBelowThreshold(this._vector)) + return; + this._active = true; + return { + bearingDelta: getBearingDelta(this._vector, lastVector), + pinchAround + }; + } + _isBelowThreshold(vector) { + /* + * The threshold before a rotation actually happens is configured in + * pixels along the circumference of the circle formed by the two fingers. + * This makes the threshold in degrees larger when the fingers are close + * together and smaller when the fingers are far apart. + * + * Use the smallest diameter from the whole gesture to reduce sensitivity + * when pinching in and out. + */ + this._minDiameter = Math.min(this._minDiameter, vector.mag()); + const circumference = Math.PI * this._minDiameter; + const threshold = ROTATION_THRESHOLD / circumference * 360; + const bearingDeltaSinceStart = getBearingDelta(vector, this._startVector); + return Math.abs(bearingDeltaSinceStart) < threshold; + } +} +/* PITCH */ +function isVertical(vector) { + return Math.abs(vector.y) > Math.abs(vector.x); +} +const ALLOWED_SINGLE_TOUCH_TIME = 100; +/** + * The `TwoFingersTouchPitchHandler` allows the user to pitch the map by dragging up and down with two fingers. + * + * @group Handlers + */ +class TwoFingersTouchPitchHandler extends TwoFingersTouchHandler { + constructor(map) { + super(); + this._currentTouchCount = 0; + this._map = map; + } + reset() { + super.reset(); + this._valid = undefined; + delete this._firstMove; + delete this._lastPoints; + } + touchstart(e, points, mapTouches) { + super.touchstart(e, points, mapTouches); + this._currentTouchCount = mapTouches.length; + } + _start(points) { + this._lastPoints = points; + if (isVertical(points[0].sub(points[1]))) { + // fingers are more horizontal than vertical + this._valid = false; + } + } + _move(points, center, e) { + // If cooperative gestures is enabled, we need a 3-finger minimum for this gesture to register + if (this._map.cooperativeGestures.isEnabled() && this._currentTouchCount < 3) { + return; + } + const vectorA = points[0].sub(this._lastPoints[0]); + const vectorB = points[1].sub(this._lastPoints[1]); + this._valid = this.gestureBeginsVertically(vectorA, vectorB, e.timeStamp); + if (!this._valid) + return; + this._lastPoints = points; + this._active = true; + const yDeltaAverage = (vectorA.y + vectorB.y) / 2; + const degreesPerPixelMoved = -0.5; + return { + pitchDelta: yDeltaAverage * degreesPerPixelMoved + }; + } + gestureBeginsVertically(vectorA, vectorB, timeStamp) { + if (this._valid !== undefined) + return this._valid; + const threshold = 2; + const movedA = vectorA.mag() >= threshold; + const movedB = vectorB.mag() >= threshold; + // neither finger has moved a meaningful amount, wait + if (!movedA && !movedB) + return; + // One finger has moved and the other has not. + // If enough time has passed, decide it is not a pitch. + if (!movedA || !movedB) { + if (this._firstMove === undefined) { + this._firstMove = timeStamp; + } + if (timeStamp - this._firstMove < ALLOWED_SINGLE_TOUCH_TIME) { + // still waiting for a movement from the second finger + return undefined; + } + else { + return false; + } + } + const isSameDirection = vectorA.y > 0 === vectorB.y > 0; + return isVertical(vectorA) && isVertical(vectorB) && isSameDirection; + } +} + +const defaultOptions$5 = { + panStep: 100, + bearingStep: 15, + pitchStep: 10 +}; +/** + * The `KeyboardHandler` allows the user to zoom, rotate, and pan the map using + * the following keyboard shortcuts: + * + * - `=` / `+`: Increase the zoom level by 1. + * - `Shift-=` / `Shift-+`: Increase the zoom level by 2. + * - `-`: Decrease the zoom level by 1. + * - `Shift--`: Decrease the zoom level by 2. + * - Arrow keys: Pan by 100 pixels. + * - `Shift+⇢`: Increase the rotation by 15 degrees. + * - `Shift+⇠`: Decrease the rotation by 15 degrees. + * - `Shift+⇡`: Increase the pitch by 10 degrees. + * - `Shift+⇣`: Decrease the pitch by 10 degrees. + * + * @group Handlers + */ +class KeyboardHandler { + /** @internal */ + constructor(map) { + this._tr = new TransformProvider(map); + const stepOptions = defaultOptions$5; + this._panStep = stepOptions.panStep; + this._bearingStep = stepOptions.bearingStep; + this._pitchStep = stepOptions.pitchStep; + this._rotationDisabled = false; + } + reset() { + this._active = false; + } + keydown(e) { + if (e.altKey || e.ctrlKey || e.metaKey) + return; + let zoomDir = 0; + let bearingDir = 0; + let pitchDir = 0; + let xDir = 0; + let yDir = 0; + switch (e.keyCode) { + case 61: + case 107: + case 171: + case 187: + zoomDir = 1; + break; + case 189: + case 109: + case 173: + zoomDir = -1; + break; + case 37: + if (e.shiftKey) { + bearingDir = -1; + } + else { + e.preventDefault(); + xDir = -1; + } + break; + case 39: + if (e.shiftKey) { + bearingDir = 1; + } + else { + e.preventDefault(); + xDir = 1; + } + break; + case 38: + if (e.shiftKey) { + pitchDir = 1; + } + else { + e.preventDefault(); + yDir = -1; + } + break; + case 40: + if (e.shiftKey) { + pitchDir = -1; + } + else { + e.preventDefault(); + yDir = 1; + } + break; + default: + return; + } + if (this._rotationDisabled) { + bearingDir = 0; + pitchDir = 0; + } + return { + cameraAnimation: (map) => { + const tr = this._tr; + map.easeTo({ + duration: 300, + easeId: 'keyboardHandler', + easing: easeOut, + zoom: zoomDir ? Math.round(tr.zoom) + zoomDir * (e.shiftKey ? 2 : 1) : tr.zoom, + bearing: tr.bearing + bearingDir * this._bearingStep, + pitch: tr.pitch + pitchDir * this._pitchStep, + offset: [-xDir * this._panStep, -yDir * this._panStep], + center: tr.center + }, { originalEvent: e }); + } + }; + } + /** + * Enables the "keyboard rotate and zoom" interaction. + * + * @example + * ```ts + * map.keyboard.enable(); + * ``` + */ + enable() { + this._enabled = true; + } + /** + * Disables the "keyboard rotate and zoom" interaction. + * + * @example + * ```ts + * map.keyboard.disable(); + * ``` + */ + disable() { + this._enabled = false; + this.reset(); + } + /** + * Returns a Boolean indicating whether the "keyboard rotate and zoom" + * interaction is enabled. + * + * @returns `true` if the "keyboard rotate and zoom" + * interaction is enabled. + */ + isEnabled() { + return this._enabled; + } + /** + * Returns true if the handler is enabled and has detected the start of a + * zoom/rotate gesture. + * + * @returns `true` if the handler is enabled and has detected the + * start of a zoom/rotate gesture. + */ + isActive() { + return this._active; + } + /** + * Disables the "keyboard pan/rotate" interaction, leaving the + * "keyboard zoom" interaction enabled. + * + * @example + * ```ts + * map.keyboard.disableRotation(); + * ``` + */ + disableRotation() { + this._rotationDisabled = true; + } + /** + * Enables the "keyboard pan/rotate" interaction. + * + * @example + * ```ts + * map.keyboard.enable(); + * map.keyboard.enableRotation(); + * ``` + */ + enableRotation() { + this._rotationDisabled = false; + } +} +function easeOut(t) { + return t * (2 - t); +} + +// deltaY value for mouse scroll wheel identification +const wheelZoomDelta = 4.000244140625; +// These magic numbers control the rate of zoom. Trackpad events fire at a greater +// frequency than mouse scroll wheel, so reduce the zoom rate per wheel tick +const defaultZoomRate = 1 / 100; +const wheelZoomRate = 1 / 450; +// upper bound on how much we scale the map in any single render frame; this +// is used to limit zoom rate in the case of very fast scrolling +const maxScalePerFrame = 2; +/** + * The `ScrollZoomHandler` allows the user to zoom the map by scrolling. + * + * @group Handlers + */ +class ScrollZoomHandler { + /** @internal */ + constructor(map, triggerRenderFrame) { + this._onTimeout = (initialEvent) => { + this._type = 'wheel'; + this._delta -= this._lastValue; + if (!this._active) { + this._start(initialEvent); + } + }; + this._map = map; + this._tr = new TransformProvider(map); + this._triggerRenderFrame = triggerRenderFrame; + this._delta = 0; + this._defaultZoomRate = defaultZoomRate; + this._wheelZoomRate = wheelZoomRate; + } + /** + * Set the zoom rate of a trackpad + * @param zoomRate - 1/100 The rate used to scale trackpad movement to a zoom value. + * @example + * Speed up trackpad zoom + * ```ts + * map.scrollZoom.setZoomRate(1/25); + * ``` + */ + setZoomRate(zoomRate) { + this._defaultZoomRate = zoomRate; + } + /** + * Set the zoom rate of a mouse wheel + * @param wheelZoomRate - 1/450 The rate used to scale mouse wheel movement to a zoom value. + * @example + * Slow down zoom of mouse wheel + * ```ts + * map.scrollZoom.setWheelZoomRate(1/600); + * ``` + */ + setWheelZoomRate(wheelZoomRate) { + this._wheelZoomRate = wheelZoomRate; + } + /** + * Returns a Boolean indicating whether the "scroll to zoom" interaction is enabled. + * @returns `true` if the "scroll to zoom" interaction is enabled. + */ + isEnabled() { + return !!this._enabled; + } + /* + * Active state is turned on and off with every scroll wheel event and is set back to false before the map + * render is called, so _active is not a good candidate for determining if a scroll zoom animation is in + * progress. + */ + isActive() { + return !!this._active || this._finishTimeout !== undefined; + } + isZooming() { + return !!this._zooming; + } + /** + * Enables the "scroll to zoom" interaction. + * + * @param options - Options object. + * @example + * ```ts + * map.scrollZoom.enable(); + * map.scrollZoom.enable({ around: 'center' }) + * ``` + */ + enable(options) { + if (this.isEnabled()) + return; + this._enabled = true; + this._aroundCenter = !!options && options.around === 'center'; + } + /** + * Disables the "scroll to zoom" interaction. + * + * @example + * ```ts + * map.scrollZoom.disable(); + * ``` + */ + disable() { + if (!this.isEnabled()) + return; + this._enabled = false; + } + /** + * Determines whether or not the gesture is blocked due to cooperativeGestures. + */ + _shouldBePrevented(e) { + if (!this._map.cooperativeGestures.isEnabled()) { + return false; + } + const isTrackpadPinch = e.ctrlKey; + const isBypassed = isTrackpadPinch || this._map.cooperativeGestures.isBypassed(e); + return !isBypassed; + } + wheel(e) { + if (!this.isEnabled()) + return; + if (this._shouldBePrevented(e)) { + this._map.cooperativeGestures.notifyGestureBlocked('wheel_zoom', e); + return; + } + let value = e.deltaMode === WheelEvent.DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY; + const now = browser.now(), timeDelta = now - (this._lastWheelEventTime || 0); + this._lastWheelEventTime = now; + if (value !== 0 && (value % wheelZoomDelta) === 0) { + // This one is definitely a mouse wheel event. + this._type = 'wheel'; + } + else if (value !== 0 && Math.abs(value) < 4) { + // This one is definitely a trackpad event because it is so small. + this._type = 'trackpad'; + } + else if (timeDelta > 400) { + // This is likely a new scroll action. + this._type = null; + this._lastValue = value; + // Start a timeout in case this was a singular event, and delay it by up to 40ms. + this._timeout = setTimeout(this._onTimeout, 40, e); + } + else if (!this._type) { + // This is a repeating event, but we don't know the type of event just yet. + // If the delta per time is small, we assume it's a fast trackpad; otherwise we switch into wheel mode. + this._type = (Math.abs(timeDelta * value) < 200) ? 'trackpad' : 'wheel'; + // Make sure our delayed event isn't fired again, because we accumulate + // the previous event (which was less than 40ms ago) into this event. + if (this._timeout) { + clearTimeout(this._timeout); + this._timeout = null; + value += this._lastValue; + } + } + // Slow down zoom if shift key is held for more precise zooming + if (e.shiftKey && value) + value = value / 4; + // Only fire the callback if we actually know what type of scrolling device the user uses. + if (this._type) { + this._lastWheelEvent = e; + this._delta -= value; + if (!this._active) { + this._start(e); + } + } + e.preventDefault(); + } + _start(e) { + if (!this._delta) + return; + if (this._frameId) { + this._frameId = null; + } + this._active = true; + if (!this.isZooming()) { + this._zooming = true; + } + if (this._finishTimeout) { + clearTimeout(this._finishTimeout); + delete this._finishTimeout; + } + const pos = DOM.mousePos(this._map.getCanvas(), e); + const tr = this._tr; + if (pos.y > tr.transform.height / 2 - tr.transform.getHorizon()) { + this._around = performance$1.N.convert(this._aroundCenter ? tr.center : tr.unproject(pos)); + } + else { + // Do not use current cursor position if above the horizon to avoid 'unproject' this point + // as it is not mapped into 'coords' framebuffer or inversible with 'pixelMatrixInverse'. + this._around = performance$1.N.convert(tr.center); + } + this._aroundPoint = tr.transform.locationPoint(this._around); + if (!this._frameId) { + this._frameId = true; + this._triggerRenderFrame(); + } + } + renderFrame() { + if (!this._frameId) + return; + this._frameId = null; + if (!this.isActive()) + return; + const tr = this._tr.transform; + // if we've had scroll events since the last render frame, consume the + // accumulated delta, and update the target zoom level accordingly + if (this._delta !== 0) { + // For trackpad events and single mouse wheel ticks, use the default zoom rate + const zoomRate = (this._type === 'wheel' && Math.abs(this._delta) > wheelZoomDelta) ? this._wheelZoomRate : this._defaultZoomRate; + // Scale by sigmoid of scroll wheel delta. + let scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * zoomRate))); + if (this._delta < 0 && scale !== 0) { + scale = 1 / scale; + } + const fromScale = typeof this._targetZoom === 'number' ? tr.zoomScale(this._targetZoom) : tr.scale; + this._targetZoom = Math.min(tr.maxZoom, Math.max(tr.minZoom, tr.scaleZoom(fromScale * scale))); + // if this is a mouse wheel, refresh the starting zoom and easing + // function we're using to smooth out the zooming between wheel + // events + if (this._type === 'wheel') { + this._startZoom = tr.zoom; + this._easing = this._smoothOutEasing(200); + } + this._delta = 0; + } + const targetZoom = typeof this._targetZoom === 'number' ? + this._targetZoom : tr.zoom; + const startZoom = this._startZoom; + const easing = this._easing; + let finished = false; + let zoom; + const lastWheelEventTimeDiff = browser.now() - this._lastWheelEventTime; + if (this._type === 'wheel' && startZoom && easing && lastWheelEventTimeDiff) { + const t = Math.min(lastWheelEventTimeDiff / 200, 1); + const k = easing(t); + zoom = performance$1.y.number(startZoom, targetZoom, k); + if (t < 1) { + if (!this._frameId) { + this._frameId = true; + } + } + else { + finished = true; + } + } + else { + zoom = targetZoom; + finished = true; + } + this._active = true; + if (finished) { + this._active = false; + this._finishTimeout = setTimeout(() => { + this._zooming = false; + this._triggerRenderFrame(); + delete this._targetZoom; + delete this._finishTimeout; + }, 200); + } + return { + noInertia: true, + needsRenderFrame: !finished, + zoomDelta: zoom - tr.zoom, + around: this._aroundPoint, + originalEvent: this._lastWheelEvent + }; + } + _smoothOutEasing(duration) { + let easing = performance$1.b9; + if (this._prevEase) { + const currentEase = this._prevEase; + const t = (browser.now() - currentEase.start) / currentEase.duration; + const speed = currentEase.easing(t + 0.01) - currentEase.easing(t); + // Quick hack to make new bezier that is continuous with last + const x = 0.27 / Math.sqrt(speed * speed + 0.0001) * 0.01; + const y = Math.sqrt(0.27 * 0.27 - x * x); + easing = performance$1.b8(x, y, 0.25, 1); + } + this._prevEase = { + start: browser.now(), + duration, + easing + }; + return easing; + } + reset() { + this._active = false; + this._zooming = false; + delete this._targetZoom; + if (this._finishTimeout) { + clearTimeout(this._finishTimeout); + delete this._finishTimeout; + } + } +} + +/** + * The `DoubleClickZoomHandler` allows the user to zoom the map at a point by + * double clicking or double tapping. + * + * @group Handlers + */ +class DoubleClickZoomHandler { + /** @internal */ + constructor(clickZoom, TapZoom) { + this._clickZoom = clickZoom; + this._tapZoom = TapZoom; + } + /** + * Enables the "double click to zoom" interaction. + * + * @example + * ```ts + * map.doubleClickZoom.enable(); + * ``` + */ + enable() { + this._clickZoom.enable(); + this._tapZoom.enable(); + } + /** + * Disables the "double click to zoom" interaction. + * + * @example + * ```ts + * map.doubleClickZoom.disable(); + * ``` + */ + disable() { + this._clickZoom.disable(); + this._tapZoom.disable(); + } + /** + * Returns a Boolean indicating whether the "double click to zoom" interaction is enabled. + * + * @returns `true` if the "double click to zoom" interaction is enabled. + */ + isEnabled() { + return this._clickZoom.isEnabled() && this._tapZoom.isEnabled(); + } + /** + * Returns a Boolean indicating whether the "double click to zoom" interaction is active, i.e. currently being used. + * + * @returns `true` if the "double click to zoom" interaction is active. + */ + isActive() { + return this._clickZoom.isActive() || this._tapZoom.isActive(); + } +} + +/** + * The `ClickZoomHandler` allows the user to zoom the map at a point by double clicking + * It is used by other handlers + */ +class ClickZoomHandler { + /** @internal */ + constructor(map) { + this._tr = new TransformProvider(map); + this.reset(); + } + reset() { + this._active = false; + } + dblclick(e, point) { + e.preventDefault(); + return { + cameraAnimation: (map) => { + map.easeTo({ + duration: 300, + zoom: this._tr.zoom + (e.shiftKey ? -1 : 1), + around: this._tr.unproject(point) + }, { originalEvent: e }); + } + }; + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } +} + +/** + * A `TapDragZoomHandler` allows the user to zoom the map at a point by double tapping. It also allows the user pan the map by dragging. + */ +class TapDragZoomHandler { + constructor() { + this._tap = new TapRecognizer({ + numTouches: 1, + numTaps: 1 + }); + this.reset(); + } + reset() { + this._active = false; + delete this._swipePoint; + delete this._swipeTouch; + delete this._tapTime; + delete this._tapPoint; + this._tap.reset(); + } + touchstart(e, points, mapTouches) { + if (this._swipePoint) + return; + if (!this._tapTime) { + this._tap.touchstart(e, points, mapTouches); + } + else { + const swipePoint = points[0]; + const soonEnough = e.timeStamp - this._tapTime < MAX_TAP_INTERVAL; + const closeEnough = this._tapPoint.dist(swipePoint) < MAX_DIST; + if (!soonEnough || !closeEnough) { + this.reset(); + } + else if (mapTouches.length > 0) { + this._swipePoint = swipePoint; + this._swipeTouch = mapTouches[0].identifier; + } + } + } + touchmove(e, points, mapTouches) { + if (!this._tapTime) { + this._tap.touchmove(e, points, mapTouches); + } + else if (this._swipePoint) { + if (mapTouches[0].identifier !== this._swipeTouch) { + return; + } + const newSwipePoint = points[0]; + const dist = newSwipePoint.y - this._swipePoint.y; + this._swipePoint = newSwipePoint; + e.preventDefault(); + this._active = true; + return { + zoomDelta: dist / 128 + }; + } + } + touchend(e, points, mapTouches) { + if (!this._tapTime) { + const point = this._tap.touchend(e, points, mapTouches); + if (point) { + this._tapTime = e.timeStamp; + this._tapPoint = point; + } + } + else if (this._swipePoint) { + if (mapTouches.length === 0) { + this.reset(); + } + } + } + touchcancel() { + this.reset(); + } + enable() { + this._enabled = true; + } + disable() { + this._enabled = false; + this.reset(); + } + isEnabled() { + return this._enabled; + } + isActive() { + return this._active; + } +} + +/** + * The `DragPanHandler` allows the user to pan the map by clicking and dragging + * the cursor. + * + * @group Handlers + */ +class DragPanHandler { + /** @internal */ + constructor(el, mousePan, touchPan) { + this._el = el; + this._mousePan = mousePan; + this._touchPan = touchPan; + } + /** + * Enables the "drag to pan" interaction. + * + * @param options - Options object + * @example + * ```ts + * map.dragPan.enable(); + * map.dragPan.enable({ + * linearity: 0.3, + * easing: bezier(0, 0, 0.3, 1), + * maxSpeed: 1400, + * deceleration: 2500, + * }); + * ``` + */ + enable(options) { + this._inertiaOptions = options || {}; + this._mousePan.enable(); + this._touchPan.enable(); + this._el.classList.add('maplibregl-touch-drag-pan'); + } + /** + * Disables the "drag to pan" interaction. + * + * @example + * ```ts + * map.dragPan.disable(); + * ``` + */ + disable() { + this._mousePan.disable(); + this._touchPan.disable(); + this._el.classList.remove('maplibregl-touch-drag-pan'); + } + /** + * Returns a Boolean indicating whether the "drag to pan" interaction is enabled. + * + * @returns `true` if the "drag to pan" interaction is enabled. + */ + isEnabled() { + return this._mousePan.isEnabled() && this._touchPan.isEnabled(); + } + /** + * Returns a Boolean indicating whether the "drag to pan" interaction is active, i.e. currently being used. + * + * @returns `true` if the "drag to pan" interaction is active. + */ + isActive() { + return this._mousePan.isActive() || this._touchPan.isActive(); + } +} + +/** + * The `DragRotateHandler` allows the user to rotate the map by clicking and + * dragging the cursor while holding the right mouse button or `ctrl` key. + * + * @group Handlers + */ +class DragRotateHandler { + /** @internal */ + constructor(options, mouseRotate, mousePitch) { + this._pitchWithRotate = options.pitchWithRotate; + this._mouseRotate = mouseRotate; + this._mousePitch = mousePitch; + } + /** + * Enables the "drag to rotate" interaction. + * + * @example + * ```ts + * map.dragRotate.enable(); + * ``` + */ + enable() { + this._mouseRotate.enable(); + if (this._pitchWithRotate) + this._mousePitch.enable(); + } + /** + * Disables the "drag to rotate" interaction. + * + * @example + * ```ts + * map.dragRotate.disable(); + * ``` + */ + disable() { + this._mouseRotate.disable(); + this._mousePitch.disable(); + } + /** + * Returns a Boolean indicating whether the "drag to rotate" interaction is enabled. + * + * @returns `true` if the "drag to rotate" interaction is enabled. + */ + isEnabled() { + return this._mouseRotate.isEnabled() && (!this._pitchWithRotate || this._mousePitch.isEnabled()); + } + /** + * Returns a Boolean indicating whether the "drag to rotate" interaction is active, i.e. currently being used. + * + * @returns `true` if the "drag to rotate" interaction is active. + */ + isActive() { + return this._mouseRotate.isActive() || this._mousePitch.isActive(); + } +} + +/** + * The `TwoFingersTouchZoomRotateHandler` allows the user to zoom and rotate the map by + * pinching on a touchscreen. + * + * They can zoom with one finger by double tapping and dragging. On the second tap, + * hold the finger down and drag up or down to zoom in or out. + * + * @group Handlers + */ +class TwoFingersTouchZoomRotateHandler { + /** @internal */ + constructor(el, touchZoom, touchRotate, tapDragZoom) { + this._el = el; + this._touchZoom = touchZoom; + this._touchRotate = touchRotate; + this._tapDragZoom = tapDragZoom; + this._rotationDisabled = false; + this._enabled = true; + } + /** + * Enables the "pinch to rotate and zoom" interaction. + * + * @param options - Options object. + * + * @example + * ```ts + * map.touchZoomRotate.enable(); + * map.touchZoomRotate.enable({ around: 'center' }); + * ``` + */ + enable(options) { + this._touchZoom.enable(options); + if (!this._rotationDisabled) + this._touchRotate.enable(options); + this._tapDragZoom.enable(); + this._el.classList.add('maplibregl-touch-zoom-rotate'); + } + /** + * Disables the "pinch to rotate and zoom" interaction. + * + * @example + * ```ts + * map.touchZoomRotate.disable(); + * ``` + */ + disable() { + this._touchZoom.disable(); + this._touchRotate.disable(); + this._tapDragZoom.disable(); + this._el.classList.remove('maplibregl-touch-zoom-rotate'); + } + /** + * Returns a Boolean indicating whether the "pinch to rotate and zoom" interaction is enabled. + * + * @returns `true` if the "pinch to rotate and zoom" interaction is enabled. + */ + isEnabled() { + return this._touchZoom.isEnabled() && + (this._rotationDisabled || this._touchRotate.isEnabled()) && + this._tapDragZoom.isEnabled(); + } + /** + * Returns true if the handler is enabled and has detected the start of a zoom/rotate gesture. + * + * @returns `true` if the handler is active, `false` otherwise + */ + isActive() { + return this._touchZoom.isActive() || this._touchRotate.isActive() || this._tapDragZoom.isActive(); + } + /** + * Disables the "pinch to rotate" interaction, leaving the "pinch to zoom" + * interaction enabled. + * + * @example + * ```ts + * map.touchZoomRotate.disableRotation(); + * ``` + */ + disableRotation() { + this._rotationDisabled = true; + this._touchRotate.disable(); + } + /** + * Enables the "pinch to rotate" interaction. + * + * @example + * ```ts + * map.touchZoomRotate.enable(); + * map.touchZoomRotate.enableRotation(); + * ``` + */ + enableRotation() { + this._rotationDisabled = false; + if (this._touchZoom.isEnabled()) + this._touchRotate.enable(); + } +} + +/** + * A `CooperativeGestureHandler` is a control that adds cooperative gesture info when user tries to zoom in/out. + * + * When the CooperativeGestureHandler blocks a gesture, it will emit a `cooperativegestureprevented` event. + * + * @group Handlers + * + * @example + * ```ts + * const map = new Map({ + * cooperativeGestures: true + * }); + * ``` + * @see [Example: cooperative gestures](https://maplibre.org/maplibre-gl-js/docs/examples/cooperative-gestures/) + **/ +class CooperativeGesturesHandler { + constructor(map, options) { + /** + * This is the key that will allow to bypass the cooperative gesture protection + */ + this._bypassKey = navigator.userAgent.indexOf('Mac') !== -1 ? 'metaKey' : 'ctrlKey'; + this._map = map; + this._options = options; + this._enabled = false; + } + isActive() { + return false; + } + reset() { } + _setupUI() { + if (this._container) + return; + const mapCanvasContainer = this._map.getCanvasContainer(); + // Add a cooperative gestures class (enable touch-action: pan-x pan-y;) + mapCanvasContainer.classList.add('maplibregl-cooperative-gestures'); + this._container = DOM.create('div', 'maplibregl-cooperative-gesture-screen', mapCanvasContainer); + let desktopMessage = this._map._getUIString('CooperativeGesturesHandler.WindowsHelpText'); + if (this._bypassKey === 'metaKey') { + desktopMessage = this._map._getUIString('CooperativeGesturesHandler.MacHelpText'); + } + const mobileMessage = this._map._getUIString('CooperativeGesturesHandler.MobileHelpText'); + // Create and append the desktop message div + const desktopDiv = document.createElement('div'); + desktopDiv.className = 'maplibregl-desktop-message'; + desktopDiv.textContent = desktopMessage; + this._container.appendChild(desktopDiv); + // Create and append the mobile message div + const mobileDiv = document.createElement('div'); + mobileDiv.className = 'maplibregl-mobile-message'; + mobileDiv.textContent = mobileMessage; + this._container.appendChild(mobileDiv); + // Remove cooperative gesture screen from the accessibility tree since screenreaders cannot interact with the map using gestures + this._container.setAttribute('aria-hidden', 'true'); + } + _destroyUI() { + if (this._container) { + DOM.remove(this._container); + const mapCanvasContainer = this._map.getCanvasContainer(); + mapCanvasContainer.classList.remove('maplibregl-cooperative-gestures'); + } + delete this._container; + } + enable() { + this._setupUI(); + this._enabled = true; + } + disable() { + this._enabled = false; + this._destroyUI(); + } + isEnabled() { + return this._enabled; + } + isBypassed(event) { + return event[this._bypassKey]; + } + notifyGestureBlocked(gestureType, originalEvent) { + if (!this._enabled) + return; + // notify subscribers that a cooperative gesture was prevented + this._map.fire(new performance$1.k('cooperativegestureprevented', { gestureType, originalEvent })); + // Alert user how to scroll/pan + this._container.classList.add('maplibregl-show'); + setTimeout(() => { + this._container.classList.remove('maplibregl-show'); + }, 100); + } +} + +const isMoving = (p) => p.zoom || p.drag || p.pitch || p.rotate; +class RenderFrameEvent extends performance$1.k { +} +function hasChange(result) { + return (result.panDelta && result.panDelta.mag()) || result.zoomDelta || result.bearingDelta || result.pitchDelta; +} +class HandlerManager { + constructor(map, options) { + this.handleWindowEvent = (e) => { + this.handleEvent(e, `${e.type}Window`); + }; + this.handleEvent = (e, eventName) => { + if (e.type === 'blur') { + this.stop(true); + return; + } + this._updatingCamera = true; + const inputEvent = e.type === 'renderFrame' ? undefined : e; + /* + * We don't call e.preventDefault() for any events by default. + * Handlers are responsible for calling it where necessary. + */ + const mergedHandlerResult = { needsRenderFrame: false }; + const eventsInProgress = {}; + const activeHandlers = {}; + const eventTouches = e.touches; + const mapTouches = eventTouches ? this._getMapTouches(eventTouches) : undefined; + const points = mapTouches ? + DOM.touchPos(this._map.getCanvas(), mapTouches) : + DOM.mousePos(this._map.getCanvas(), e); + for (const { handlerName, handler, allowed } of this._handlers) { + if (!handler.isEnabled()) + continue; + let data; + if (this._blockedByActive(activeHandlers, allowed, handlerName)) { + handler.reset(); + } + else { + if (handler[eventName || e.type]) { + data = handler[eventName || e.type](e, points, mapTouches); + this.mergeHandlerResult(mergedHandlerResult, eventsInProgress, data, handlerName, inputEvent); + if (data && data.needsRenderFrame) { + this._triggerRenderFrame(); + } + } + } + if (data || handler.isActive()) { + activeHandlers[handlerName] = handler; + } + } + const deactivatedHandlers = {}; + for (const name in this._previousActiveHandlers) { + if (!activeHandlers[name]) { + deactivatedHandlers[name] = inputEvent; + } + } + this._previousActiveHandlers = activeHandlers; + if (Object.keys(deactivatedHandlers).length || hasChange(mergedHandlerResult)) { + this._changes.push([mergedHandlerResult, eventsInProgress, deactivatedHandlers]); + this._triggerRenderFrame(); + } + if (Object.keys(activeHandlers).length || hasChange(mergedHandlerResult)) { + this._map._stop(true); + } + this._updatingCamera = false; + const { cameraAnimation } = mergedHandlerResult; + if (cameraAnimation) { + this._inertia.clear(); + this._fireEvents({}, {}, true); + this._changes = []; + cameraAnimation(this._map); + } + }; + this._map = map; + this._el = this._map.getCanvasContainer(); + this._handlers = []; + this._handlersById = {}; + this._changes = []; + this._inertia = new HandlerInertia(map); + this._bearingSnap = options.bearingSnap; + this._previousActiveHandlers = {}; + // Track whether map is currently moving, to compute start/move/end events + this._eventsInProgress = {}; + this._addDefaultHandlers(options); + const el = this._el; + this._listeners = [ + // This needs to be `passive: true` so that a double tap fires two + // pairs of touchstart/end events in iOS Safari 13. If this is set to + // `passive: false` then the second pair of events is only fired if + // preventDefault() is called on the first touchstart. Calling preventDefault() + // undesirably prevents click events. + [el, 'touchstart', { passive: true }], + // This needs to be `passive: false` so that scrolls and pinches can be + // prevented in browsers that don't support `touch-actions: none`, for example iOS Safari 12. + [el, 'touchmove', { passive: false }], + [el, 'touchend', undefined], + [el, 'touchcancel', undefined], + [el, 'mousedown', undefined], + [el, 'mousemove', undefined], + [el, 'mouseup', undefined], + // Bind window-level event listeners for move and up/end events. In the absence of + // the pointer capture API, which is not supported by all necessary platforms, + // window-level event listeners give us the best shot at capturing events that + // fall outside the map canvas element. Use `{capture: true}` for the move event + // to prevent map move events from being fired during a drag. + [document, 'mousemove', { capture: true }], + [document, 'mouseup', undefined], + [el, 'mouseover', undefined], + [el, 'mouseout', undefined], + [el, 'dblclick', undefined], + [el, 'click', undefined], + [el, 'keydown', { capture: false }], + [el, 'keyup', undefined], + [el, 'wheel', { passive: false }], + [el, 'contextmenu', undefined], + [window, 'blur', undefined] + ]; + for (const [target, type, listenerOptions] of this._listeners) { + DOM.addEventListener(target, type, target === document ? this.handleWindowEvent : this.handleEvent, listenerOptions); + } + } + destroy() { + for (const [target, type, listenerOptions] of this._listeners) { + DOM.removeEventListener(target, type, target === document ? this.handleWindowEvent : this.handleEvent, listenerOptions); + } + } + _addDefaultHandlers(options) { + const map = this._map; + const el = map.getCanvasContainer(); + this._add('mapEvent', new MapEventHandler(map, options)); + const boxZoom = map.boxZoom = new BoxZoomHandler(map, options); + this._add('boxZoom', boxZoom); + if (options.interactive && options.boxZoom) { + boxZoom.enable(); + } + const cooperativeGestures = map.cooperativeGestures = new CooperativeGesturesHandler(map, options.cooperativeGestures); + this._add('cooperativeGestures', cooperativeGestures); + if (options.cooperativeGestures) { + cooperativeGestures.enable(); + } + const tapZoom = new TapZoomHandler(map); + const clickZoom = new ClickZoomHandler(map); + map.doubleClickZoom = new DoubleClickZoomHandler(clickZoom, tapZoom); + this._add('tapZoom', tapZoom); + this._add('clickZoom', clickZoom); + if (options.interactive && options.doubleClickZoom) { + map.doubleClickZoom.enable(); + } + const tapDragZoom = new TapDragZoomHandler(); + this._add('tapDragZoom', tapDragZoom); + const touchPitch = map.touchPitch = new TwoFingersTouchPitchHandler(map); + this._add('touchPitch', touchPitch); + if (options.interactive && options.touchPitch) { + map.touchPitch.enable(options.touchPitch); + } + const mouseRotate = generateMouseRotationHandler(options); + const mousePitch = generateMousePitchHandler(options); + map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch); + this._add('mouseRotate', mouseRotate, ['mousePitch']); + this._add('mousePitch', mousePitch, ['mouseRotate']); + if (options.interactive && options.dragRotate) { + map.dragRotate.enable(); + } + const mousePan = generateMousePanHandler(options); + const touchPan = new TouchPanHandler(options, map); + map.dragPan = new DragPanHandler(el, mousePan, touchPan); + this._add('mousePan', mousePan); + this._add('touchPan', touchPan, ['touchZoom', 'touchRotate']); + if (options.interactive && options.dragPan) { + map.dragPan.enable(options.dragPan); + } + const touchRotate = new TwoFingersTouchRotateHandler(); + const touchZoom = new TwoFingersTouchZoomHandler(); + map.touchZoomRotate = new TwoFingersTouchZoomRotateHandler(el, touchZoom, touchRotate, tapDragZoom); + this._add('touchRotate', touchRotate, ['touchPan', 'touchZoom']); + this._add('touchZoom', touchZoom, ['touchPan', 'touchRotate']); + if (options.interactive && options.touchZoomRotate) { + map.touchZoomRotate.enable(options.touchZoomRotate); + } + const scrollZoom = map.scrollZoom = new ScrollZoomHandler(map, () => this._triggerRenderFrame()); + this._add('scrollZoom', scrollZoom, ['mousePan']); + if (options.interactive && options.scrollZoom) { + map.scrollZoom.enable(options.scrollZoom); + } + const keyboard = map.keyboard = new KeyboardHandler(map); + this._add('keyboard', keyboard); + if (options.interactive && options.keyboard) { + map.keyboard.enable(); + } + this._add('blockableMapEvent', new BlockableMapEventHandler(map)); + } + _add(handlerName, handler, allowed) { + this._handlers.push({ handlerName, handler, allowed }); + this._handlersById[handlerName] = handler; + } + stop(allowEndAnimation) { + // do nothing if this method was triggered by a gesture update + if (this._updatingCamera) + return; + for (const { handler } of this._handlers) { + handler.reset(); + } + this._inertia.clear(); + this._fireEvents({}, {}, allowEndAnimation); + this._changes = []; + } + isActive() { + for (const { handler } of this._handlers) { + if (handler.isActive()) + return true; + } + return false; + } + isZooming() { + return !!this._eventsInProgress.zoom || this._map.scrollZoom.isZooming(); + } + isRotating() { + return !!this._eventsInProgress.rotate; + } + isMoving() { + return Boolean(isMoving(this._eventsInProgress)) || this.isZooming(); + } + _blockedByActive(activeHandlers, allowed, myName) { + for (const name in activeHandlers) { + if (name === myName) + continue; + if (!allowed || allowed.indexOf(name) < 0) { + return true; + } + } + return false; + } + _getMapTouches(touches) { + const mapTouches = []; + for (const t of touches) { + const target = t.target; + if (this._el.contains(target)) { + mapTouches.push(t); + } + } + return mapTouches; + } + mergeHandlerResult(mergedHandlerResult, eventsInProgress, handlerResult, name, e) { + if (!handlerResult) + return; + performance$1.e(mergedHandlerResult, handlerResult); + const eventData = { handlerName: name, originalEvent: handlerResult.originalEvent || e }; + // track which handler changed which camera property + if (handlerResult.zoomDelta !== undefined) { + eventsInProgress.zoom = eventData; + } + if (handlerResult.panDelta !== undefined) { + eventsInProgress.drag = eventData; + } + if (handlerResult.pitchDelta !== undefined) { + eventsInProgress.pitch = eventData; + } + if (handlerResult.bearingDelta !== undefined) { + eventsInProgress.rotate = eventData; + } + } + _applyChanges() { + const combined = {}; + const combinedEventsInProgress = {}; + const combinedDeactivatedHandlers = {}; + for (const [change, eventsInProgress, deactivatedHandlers] of this._changes) { + if (change.panDelta) + combined.panDelta = (combined.panDelta || new performance$1.P(0, 0))._add(change.panDelta); + if (change.zoomDelta) + combined.zoomDelta = (combined.zoomDelta || 0) + change.zoomDelta; + if (change.bearingDelta) + combined.bearingDelta = (combined.bearingDelta || 0) + change.bearingDelta; + if (change.pitchDelta) + combined.pitchDelta = (combined.pitchDelta || 0) + change.pitchDelta; + if (change.around !== undefined) + combined.around = change.around; + if (change.pinchAround !== undefined) + combined.pinchAround = change.pinchAround; + if (change.noInertia) + combined.noInertia = change.noInertia; + performance$1.e(combinedEventsInProgress, eventsInProgress); + performance$1.e(combinedDeactivatedHandlers, deactivatedHandlers); + } + this._updateMapTransform(combined, combinedEventsInProgress, combinedDeactivatedHandlers); + this._changes = []; + } + _updateMapTransform(combinedResult, combinedEventsInProgress, deactivatedHandlers) { + const map = this._map; + const tr = map._getTransformForUpdate(); + const terrain = map.terrain; + if (!hasChange(combinedResult) && !(terrain && this._terrainMovement)) { + return this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true); + } + let { panDelta, zoomDelta, bearingDelta, pitchDelta, around, pinchAround } = combinedResult; + if (pinchAround !== undefined) { + around = pinchAround; + } + // stop any ongoing camera animations (easeTo, flyTo) + map._stop(true); + around = around || map.transform.centerPoint; + const loc = tr.pointLocation(panDelta ? around.sub(panDelta) : around); + if (bearingDelta) + tr.bearing += bearingDelta; + if (pitchDelta) + tr.pitch += pitchDelta; + if (zoomDelta) + tr.zoom += zoomDelta; + if (!terrain) { + tr.setLocationAtPoint(loc, around); + } + else { + // when 3d-terrain is enabled act a little different: + // - dragging do not drag the picked point itself, instead it drags the map by pixel-delta. + // With this approach it is no longer possible to pick a point from somewhere near + // the horizon to the center in one move. + // So this logic avoids the problem, that in such cases you easily loose orientation. + if (!this._terrainMovement && + (combinedEventsInProgress.drag || combinedEventsInProgress.zoom)) { + // When starting to drag or move, flag it and register moveend to clear flagging + this._terrainMovement = true; + this._map._elevationFreeze = true; + tr.setLocationAtPoint(loc, around); + } + else if (combinedEventsInProgress.drag && this._terrainMovement) { + // drag map + tr.center = tr.pointLocation(tr.centerPoint.sub(panDelta)); + } + else { + tr.setLocationAtPoint(loc, around); + } + } + map._applyUpdatedTransform(tr); + this._map._update(); + if (!combinedResult.noInertia) + this._inertia.record(combinedResult); + this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true); + } + _fireEvents(newEventsInProgress, deactivatedHandlers, allowEndAnimation) { + const wasMoving = isMoving(this._eventsInProgress); + const nowMoving = isMoving(newEventsInProgress); + const startEvents = {}; + for (const eventName in newEventsInProgress) { + const { originalEvent } = newEventsInProgress[eventName]; + if (!this._eventsInProgress[eventName]) { + startEvents[`${eventName}start`] = originalEvent; + } + this._eventsInProgress[eventName] = newEventsInProgress[eventName]; + } + // fire start events only after this._eventsInProgress has been updated + if (!wasMoving && nowMoving) { + this._fireEvent('movestart', nowMoving.originalEvent); + } + for (const name in startEvents) { + this._fireEvent(name, startEvents[name]); + } + if (nowMoving) { + this._fireEvent('move', nowMoving.originalEvent); + } + for (const eventName in newEventsInProgress) { + const { originalEvent } = newEventsInProgress[eventName]; + this._fireEvent(eventName, originalEvent); + } + const endEvents = {}; + let originalEndEvent; + for (const eventName in this._eventsInProgress) { + const { handlerName, originalEvent } = this._eventsInProgress[eventName]; + if (!this._handlersById[handlerName].isActive()) { + delete this._eventsInProgress[eventName]; + originalEndEvent = deactivatedHandlers[handlerName] || originalEvent; + endEvents[`${eventName}end`] = originalEndEvent; + } + } + for (const name in endEvents) { + this._fireEvent(name, endEvents[name]); + } + const stillMoving = isMoving(this._eventsInProgress); + const finishedMoving = (wasMoving || nowMoving) && !stillMoving; + if (finishedMoving && this._terrainMovement) { + this._map._elevationFreeze = false; + this._terrainMovement = false; + const tr = this._map._getTransformForUpdate(); + tr.recalculateZoom(this._map.terrain); + this._map._applyUpdatedTransform(tr); + } + if (allowEndAnimation && finishedMoving) { + this._updatingCamera = true; + const inertialEase = this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions); + const shouldSnapToNorth = bearing => bearing !== 0 && -this._bearingSnap < bearing && bearing < this._bearingSnap; + if (inertialEase && (inertialEase.essential || !browser.prefersReducedMotion)) { + if (shouldSnapToNorth(inertialEase.bearing || this._map.getBearing())) { + inertialEase.bearing = 0; + } + inertialEase.freezeElevation = true; + this._map.easeTo(inertialEase, { originalEvent: originalEndEvent }); + } + else { + this._map.fire(new performance$1.k('moveend', { originalEvent: originalEndEvent })); + if (shouldSnapToNorth(this._map.getBearing())) { + this._map.resetNorth(); + } + } + this._updatingCamera = false; + } + } + _fireEvent(type, e) { + this._map.fire(new performance$1.k(type, e ? { originalEvent: e } : {})); + } + _requestFrame() { + this._map.triggerRepaint(); + return this._map._renderTaskQueue.add(timeStamp => { + delete this._frameId; + this.handleEvent(new RenderFrameEvent('renderFrame', { timeStamp })); + this._applyChanges(); + }); + } + _triggerRenderFrame() { + if (this._frameId === undefined) { + this._frameId = this._requestFrame(); + } + } +} + +class Camera extends performance$1.E { + constructor(transform, options) { + super(); + // Callback for map._requestRenderFrame + this._renderFrameCallback = () => { + const t = Math.min((browser.now() - this._easeStart) / this._easeOptions.duration, 1); + this._onEaseFrame(this._easeOptions.easing(t)); + // if _stop is called during _onEaseFrame from _fireMoveEvents we should avoid a new _requestRenderFrame, checking it by ensuring _easeFrameId was not deleted + if (t < 1 && this._easeFrameId) { + this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback); + } + else { + this.stop(); + } + }; + this._moving = false; + this._zooming = false; + this.transform = transform; + this._bearingSnap = options.bearingSnap; + this.on('moveend', () => { + delete this._requestedCameraState; + }); + } + /** + * Returns the map's geographical centerpoint. + * + * @returns The map's geographical centerpoint. + * @example + * Return a LngLat object such as `{lng: 0, lat: 0}` + * ```ts + * let center = map.getCenter(); + * // access longitude and latitude values directly + * let {lng, lat} = map.getCenter(); + * ``` + */ + getCenter() { return new performance$1.N(this.transform.center.lng, this.transform.center.lat); } + /** + * Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param center - The centerpoint to set. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * map.setCenter([-74, 38]); + * ``` + */ + setCenter(center, eventData) { + return this.jumpTo({ center }, eventData); + } + /** + * Pans the map by the specified offset. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param offset - `x` and `y` coordinates by which to pan the map. + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/) + */ + panBy(offset, options, eventData) { + offset = performance$1.P.convert(offset).mult(-1); + return this.panTo(this.transform.center, performance$1.e({ offset }, options), eventData); + } + /** + * Pans the map to the specified location with an animated transition. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param lnglat - The location to pan the map to. + * @param options - Options describing the destination and animation of the transition. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * map.panTo([-74, 38]); + * // Specify that the panTo animation should last 5000 milliseconds. + * map.panTo([-74, 38], {duration: 5000}); + * ``` + * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/live-update-feature/) + */ + panTo(lnglat, options, eventData) { + return this.easeTo(performance$1.e({ + center: lnglat + }, options), eventData); + } + /** + * Returns the map's current zoom level. + * + * @returns The map's current zoom level. + * @example + * ```ts + * map.getZoom(); + * ``` + */ + getZoom() { return this.transform.zoom; } + /** + * Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param zoom - The zoom level to set (0-20). + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Zoom to the zoom level 5 without an animated transition + * ```ts + * map.setZoom(5); + * ``` + */ + setZoom(zoom, eventData) { + this.jumpTo({ zoom }, eventData); + return this; + } + /** + * Zooms the map to the specified zoom level, with an animated transition. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param zoom - The zoom level to transition to. + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * // Zoom to the zoom level 5 without an animated transition + * map.zoomTo(5); + * // Zoom to the zoom level 8 with an animated transition + * map.zoomTo(8, { + * duration: 2000, + * offset: [100, 50] + * }); + * ``` + */ + zoomTo(zoom, options, eventData) { + return this.easeTo(performance$1.e({ + zoom + }, options), eventData); + } + /** + * Increases the map's zoom level by 1. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Zoom the map in one level with a custom animation duration + * ```ts + * map.zoomIn({duration: 1000}); + * ``` + */ + zoomIn(options, eventData) { + this.zoomTo(this.getZoom() + 1, options, eventData); + return this; + } + /** + * Decreases the map's zoom level by 1. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Zoom the map out one level with a custom animation offset + * ```ts + * map.zoomOut({offset: [80, 60]}); + * ``` + */ + zoomOut(options, eventData) { + this.zoomTo(this.getZoom() - 1, options, eventData); + return this; + } + /** + * Returns the map's current bearing. The bearing is the compass direction that is "up"; for example, a bearing + * of 90° orients the map so that east is up. + * + * @returns The map's current bearing. + * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/) + */ + getBearing() { return this.transform.bearing; } + /** + * Sets the map's bearing (rotation). The bearing is the compass direction that is "up"; for example, a bearing + * of 90° orients the map so that east is up. + * + * Equivalent to `jumpTo({bearing: bearing})`. + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param bearing - The desired bearing. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Rotate the map to 90 degrees + * ```ts + * map.setBearing(90); + * ``` + */ + setBearing(bearing, eventData) { + this.jumpTo({ bearing }, eventData); + return this; + } + /** + * Returns the current padding applied around the map viewport. + * + * @returns The current padding around the map viewport. + */ + getPadding() { return this.transform.padding; } + /** + * Sets the padding in pixels around the viewport. + * + * Equivalent to `jumpTo({padding: padding})`. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param padding - The desired padding. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Sets a left padding of 300px, and a top padding of 50px + * ```ts + * map.setPadding({ left: 300, top: 50 }); + * ``` + */ + setPadding(padding, eventData) { + this.jumpTo({ padding }, eventData); + return this; + } + /** + * Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction + * that is "up"; for example, a bearing of 90° orients the map so that east is up. + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param bearing - The desired bearing. + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + rotateTo(bearing, options, eventData) { + return this.easeTo(performance$1.e({ + bearing + }, options), eventData); + } + /** + * Rotates the map so that north is up (0° bearing), with an animated transition. + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + resetNorth(options, eventData) { + this.rotateTo(0, performance$1.e({ duration: 1000 }, options), eventData); + return this; + } + /** + * Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + resetNorthPitch(options, eventData) { + this.easeTo(performance$1.e({ + bearing: 0, + pitch: 0, + duration: 1000 + }, options), eventData); + return this; + } + /** + * Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the + * `bearingSnap` threshold). + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + snapToNorth(options, eventData) { + if (Math.abs(this.getBearing()) < this._bearingSnap) { + return this.resetNorth(options, eventData); + } + return this; + } + /** + * Returns the map's current pitch (tilt). + * + * @returns The map's current pitch, measured in degrees away from the plane of the screen. + */ + getPitch() { return this.transform.pitch; } + /** + * Sets the map's pitch (tilt). Equivalent to `jumpTo({pitch: pitch})`. + * + * Triggers the following events: `movestart`, `moveend`, `pitchstart`, and `pitchend`. + * + * @param pitch - The pitch to set, measured in degrees away from the plane of the screen (0-60). + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + setPitch(pitch, eventData) { + this.jumpTo({ pitch }, eventData); + return this; + } + /** + * @param bounds - Calculate the center for these bounds in the viewport and use + * the highest zoom level up to and including `Map#getMaxZoom()` that fits + * in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0. + * Bounds will be taken in [sw, ne] order. Southwest point will always be to the left of the northeast point. + * @param options - Options object + * @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`. + * If map is unable to fit, method will warn and return undefined. + * @example + * ```ts + * let bbox = [[-79, 43], [-73, 45]]; + * let newCameraTransform = map.cameraForBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + */ + cameraForBounds(bounds, options) { + bounds = LngLatBounds.convert(bounds).adjustAntiMeridian(); + const bearing = options && options.bearing || 0; + return this._cameraForBoxAndBearing(bounds.getNorthWest(), bounds.getSouthEast(), bearing, options); + } + /** + * @internal + * Calculate the center of these two points in the viewport and use + * the highest zoom level up to and including `Map#getMaxZoom()` that fits + * the points in the viewport at the specified bearing. + * @param p0 - First point + * @param p1 - Second point + * @param bearing - Desired map bearing at end of animation, in degrees + * @param options - the camera options + * @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`. + * If map is unable to fit, method will warn and return undefined. + * @example + * ```ts + * let p0 = [-79, 43]; + * let p1 = [-73, 45]; + * let bearing = 90; + * let newCameraTransform = map._cameraForBoxAndBearing(p0, p1, bearing, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + */ + _cameraForBoxAndBearing(p0, p1, bearing, options) { + const defaultPadding = { + top: 0, + bottom: 0, + right: 0, + left: 0 + }; + options = performance$1.e({ + padding: defaultPadding, + offset: [0, 0], + maxZoom: this.transform.maxZoom + }, options); + if (typeof options.padding === 'number') { + const p = options.padding; + options.padding = { + top: p, + bottom: p, + right: p, + left: p + }; + } + options.padding = performance$1.e(defaultPadding, options.padding); + const tr = this.transform; + const edgePadding = tr.padding; + // Consider all corners of the rotated bounding box derived from the given points + // when find the camera position that fits the given points. + const bounds = new LngLatBounds(p0, p1); + const nwWorld = tr.project(bounds.getNorthWest()); + const neWorld = tr.project(bounds.getNorthEast()); + const seWorld = tr.project(bounds.getSouthEast()); + const swWorld = tr.project(bounds.getSouthWest()); + const bearingRadians = performance$1.ba(-bearing); + const nwRotatedWorld = nwWorld.rotate(bearingRadians); + const neRotatedWorld = neWorld.rotate(bearingRadians); + const seRotatedWorld = seWorld.rotate(bearingRadians); + const swRotatedWorld = swWorld.rotate(bearingRadians); + const upperRight = new performance$1.P(Math.max(nwRotatedWorld.x, neRotatedWorld.x, swRotatedWorld.x, seRotatedWorld.x), Math.max(nwRotatedWorld.y, neRotatedWorld.y, swRotatedWorld.y, seRotatedWorld.y)); + const lowerLeft = new performance$1.P(Math.min(nwRotatedWorld.x, neRotatedWorld.x, swRotatedWorld.x, seRotatedWorld.x), Math.min(nwRotatedWorld.y, neRotatedWorld.y, swRotatedWorld.y, seRotatedWorld.y)); + // Calculate zoom: consider the original bbox and padding. + const size = upperRight.sub(lowerLeft); + const scaleX = (tr.width - (edgePadding.left + edgePadding.right + options.padding.left + options.padding.right)) / size.x; + const scaleY = (tr.height - (edgePadding.top + edgePadding.bottom + options.padding.top + options.padding.bottom)) / size.y; + if (scaleY < 0 || scaleX < 0) { + performance$1.w('Map cannot fit within canvas with the given bounds, padding, and/or offset.'); + return undefined; + } + const zoom = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom); + // Calculate center: apply the zoom, the configured offset, as well as offset that exists as a result of padding. + const offset = performance$1.P.convert(options.offset); + const paddingOffsetX = (options.padding.left - options.padding.right) / 2; + const paddingOffsetY = (options.padding.top - options.padding.bottom) / 2; + const paddingOffset = new performance$1.P(paddingOffsetX, paddingOffsetY); + const rotatedPaddingOffset = paddingOffset.rotate(performance$1.ba(bearing)); + const offsetAtInitialZoom = offset.add(rotatedPaddingOffset); + const offsetAtFinalZoom = offsetAtInitialZoom.mult(tr.scale / tr.zoomScale(zoom)); + const center = tr.unproject( + // either world diagonal can be used (NW-SE or NE-SW) + nwWorld.add(seWorld).div(2).sub(offsetAtFinalZoom)); + return { + center, + zoom, + bearing + }; + } + /** + * Pans and zooms the map to contain its visible area within the specified geographical bounds. + * This function will also reset the map's bearing to 0 if bearing is nonzero. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param bounds - Center these bounds in the viewport and use the highest + * zoom level up to and including `Map#getMaxZoom()` that fits them in the viewport. + * Bounds will be taken in [sw, ne] order. Southwest point will always be to the left of the northeast point. + * @param options - Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * let bbox = [[-79, 43], [-73, 45]]; + * map.fitBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + * @see [Fit a map to a bounding box](https://maplibre.org/maplibre-gl-js/docs/examples/fitbounds/) + */ + fitBounds(bounds, options, eventData) { + return this._fitInternal(this.cameraForBounds(bounds, options), options, eventData); + } + /** + * Pans, rotates and zooms the map to to fit the box made by points p0 and p1 + * once the map is rotated to the specified bearing. To zoom without rotating, + * pass in the current map bearing. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend` and `rotate`. + * + * @param p0 - First point on screen, in pixel coordinates + * @param p1 - Second point on screen, in pixel coordinates + * @param bearing - Desired map bearing at end of animation, in degrees + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * let p0 = [220, 400]; + * let p1 = [500, 900]; + * map.fitScreenCoordinates(p0, p1, map.getBearing(), { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + * @see Used by {@link BoxZoomHandler} + */ + fitScreenCoordinates(p0, p1, bearing, options, eventData) { + return this._fitInternal(this._cameraForBoxAndBearing(this.transform.pointLocation(performance$1.P.convert(p0)), this.transform.pointLocation(performance$1.P.convert(p1)), bearing, options), options, eventData); + } + _fitInternal(calculatedOptions, options, eventData) { + // cameraForBounds warns + returns undefined if unable to fit: + if (!calculatedOptions) + return this; + options = performance$1.e(calculatedOptions, options); + // Explicitly remove the padding field because, calculatedOptions already accounts for padding by setting zoom and center accordingly. + delete options.padding; + return options.linear ? + this.easeTo(options, eventData) : + this.flyTo(options, eventData); + } + /** + * Changes any combination of center, zoom, bearing, and pitch, without + * an animated transition. The map will retain its current values for any + * details not specified in `options`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`, + * `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * // jump to coordinates at current zoom + * map.jumpTo({center: [0, 0]}); + * // jump with zoom, pitch, and bearing options + * map.jumpTo({ + * center: [0, 0], + * zoom: 8, + * pitch: 45, + * bearing: 90 + * }); + * ``` + * @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js/docs/examples/jump-to/) + * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/live-update-feature/) + */ + jumpTo(options, eventData) { + this.stop(); + const tr = this._getTransformForUpdate(); + let zoomChanged = false, bearingChanged = false, pitchChanged = false; + if ('zoom' in options && tr.zoom !== +options.zoom) { + zoomChanged = true; + tr.zoom = +options.zoom; + } + if (options.center !== undefined) { + tr.center = performance$1.N.convert(options.center); + } + if ('bearing' in options && tr.bearing !== +options.bearing) { + bearingChanged = true; + tr.bearing = +options.bearing; + } + if ('pitch' in options && tr.pitch !== +options.pitch) { + pitchChanged = true; + tr.pitch = +options.pitch; + } + if (options.padding != null && !tr.isPaddingEqual(options.padding)) { + tr.padding = options.padding; + } + this._applyUpdatedTransform(tr); + this.fire(new performance$1.k('movestart', eventData)) + .fire(new performance$1.k('move', eventData)); + if (zoomChanged) { + this.fire(new performance$1.k('zoomstart', eventData)) + .fire(new performance$1.k('zoom', eventData)) + .fire(new performance$1.k('zoomend', eventData)); + } + if (bearingChanged) { + this.fire(new performance$1.k('rotatestart', eventData)) + .fire(new performance$1.k('rotate', eventData)) + .fire(new performance$1.k('rotateend', eventData)); + } + if (pitchChanged) { + this.fire(new performance$1.k('pitchstart', eventData)) + .fire(new performance$1.k('pitch', eventData)) + .fire(new performance$1.k('pitchend', eventData)); + } + return this.fire(new performance$1.k('moveend', eventData)); + } + /** + * Calculates pitch, zoom and bearing for looking at `newCenter` with the camera position being `newCenter` + * and returns them as {@link CameraOptions}. + * @param from - The camera to look from + * @param altitudeFrom - The altitude of the camera to look from + * @param to - The center to look at + * @param altitudeTo - Optional altitude of the center to look at. If none given the ground height will be used. + * @returns the calculated camera options + */ + calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo = 0) { + const fromMerc = performance$1.Z.fromLngLat(from, altitudeFrom); + const toMerc = performance$1.Z.fromLngLat(to, altitudeTo); + const dx = toMerc.x - fromMerc.x; + const dy = toMerc.y - fromMerc.y; + const dz = toMerc.z - fromMerc.z; + const distance3D = Math.hypot(dx, dy, dz); + if (distance3D === 0) + throw new Error('Can\'t calculate camera options with same From and To'); + const groundDistance = Math.hypot(dx, dy); + const zoom = this.transform.scaleZoom(this.transform.cameraToCenterDistance / distance3D / this.transform.tileSize); + const bearing = (Math.atan2(dx, -dy) * 180) / Math.PI; + let pitch = (Math.acos(groundDistance / distance3D) * 180) / Math.PI; + pitch = dz < 0 ? 90 - pitch : 90 + pitch; + return { + center: toMerc.toLngLat(), + zoom, + pitch, + bearing + }; + } + /** + * Changes any combination of `center`, `zoom`, `bearing`, `pitch`, and `padding` with an animated transition + * between old and new values. The map will retain its current values for any + * details not specified in `options`. + * + * Note: The transition will happen instantly if the user has enabled + * the `reduced motion` accessibility feature enabled in their operating system, + * unless `options` includes `essential: true`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`, + * `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options describing the destination and animation of the transition. + * Accepts {@link CameraOptions} and {@link AnimationOptions}. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/) + */ + easeTo(options, eventData) { + var _a; + this._stop(false, options.easeId); + options = performance$1.e({ + offset: [0, 0], + duration: 500, + easing: performance$1.b9 + }, options); + if (options.animate === false || (!options.essential && browser.prefersReducedMotion)) + options.duration = 0; + const tr = this._getTransformForUpdate(), startZoom = tr.zoom, startBearing = tr.bearing, startPitch = tr.pitch, startPadding = tr.padding, bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing, pitch = 'pitch' in options ? +options.pitch : startPitch, padding = 'padding' in options ? options.padding : tr.padding; + const offsetAsPoint = performance$1.P.convert(options.offset); + let pointAtOffset = tr.centerPoint.add(offsetAsPoint); + const locationAtOffset = tr.pointLocation(pointAtOffset); + const { center, zoom } = tr.getConstrained(performance$1.N.convert(options.center || locationAtOffset), (_a = options.zoom) !== null && _a !== void 0 ? _a : startZoom); + this._normalizeCenter(center, tr); + const from = tr.project(locationAtOffset); + const delta = tr.project(center).sub(from); + const finalScale = tr.zoomScale(zoom - startZoom); + let around, aroundPoint; + if (options.around) { + around = performance$1.N.convert(options.around); + aroundPoint = tr.locationPoint(around); + } + const currently = { + moving: this._moving, + zooming: this._zooming, + rotating: this._rotating, + pitching: this._pitching + }; + this._zooming = this._zooming || (zoom !== startZoom); + this._rotating = this._rotating || (startBearing !== bearing); + this._pitching = this._pitching || (pitch !== startPitch); + this._padding = !tr.isPaddingEqual(padding); + this._easeId = options.easeId; + this._prepareEase(eventData, options.noMoveStart, currently); + if (this.terrain) + this._prepareElevation(center); + this._ease((k) => { + if (this._zooming) { + tr.zoom = performance$1.y.number(startZoom, zoom, k); + } + if (this._rotating) { + tr.bearing = performance$1.y.number(startBearing, bearing, k); + } + if (this._pitching) { + tr.pitch = performance$1.y.number(startPitch, pitch, k); + } + if (this._padding) { + tr.interpolatePadding(startPadding, padding, k); + // When padding is being applied, Transform#centerPoint is changing continuously, + // thus we need to recalculate offsetPoint every frame + pointAtOffset = tr.centerPoint.add(offsetAsPoint); + } + if (this.terrain && !options.freezeElevation) + this._updateElevation(k); + if (around) { + tr.setLocationAtPoint(around, aroundPoint); + } + else { + const scale = tr.zoomScale(tr.zoom - startZoom); + const base = zoom > startZoom ? + Math.min(2, finalScale) : + Math.max(0.5, finalScale); + const speedup = Math.pow(base, 1 - k); + const newCenter = tr.unproject(from.add(delta.mult(k * speedup)).mult(scale)); + tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset); + } + this._applyUpdatedTransform(tr); + this._fireMoveEvents(eventData); + }, (interruptingEaseId) => { + if (this.terrain && options.freezeElevation) + this._finalizeElevation(); + this._afterEase(eventData, interruptingEaseId); + }, options); + return this; + } + _prepareEase(eventData, noMoveStart, currently = {}) { + this._moving = true; + if (!noMoveStart && !currently.moving) { + this.fire(new performance$1.k('movestart', eventData)); + } + if (this._zooming && !currently.zooming) { + this.fire(new performance$1.k('zoomstart', eventData)); + } + if (this._rotating && !currently.rotating) { + this.fire(new performance$1.k('rotatestart', eventData)); + } + if (this._pitching && !currently.pitching) { + this.fire(new performance$1.k('pitchstart', eventData)); + } + } + _prepareElevation(center) { + this._elevationCenter = center; + this._elevationStart = this.transform.elevation; + this._elevationTarget = this.terrain.getElevationForLngLatZoom(center, this.transform.tileZoom); + this._elevationFreeze = true; + } + _updateElevation(k) { + this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter, this.transform.tileZoom); + const elevation = this.terrain.getElevationForLngLatZoom(this._elevationCenter, this.transform.tileZoom); + // target terrain updated during flight, slowly move camera to new height + if (k < 1 && elevation !== this._elevationTarget) { + const pitch1 = this._elevationTarget - this._elevationStart; + const pitch2 = (elevation - (pitch1 * k + this._elevationStart)) / (1 - k); + this._elevationStart += k * (pitch1 - pitch2); + this._elevationTarget = elevation; + } + this.transform.elevation = performance$1.y.number(this._elevationStart, this._elevationTarget, k); + } + _finalizeElevation() { + this._elevationFreeze = false; + this.transform.recalculateZoom(this.terrain); + } + /** + * @internal + * Called when the camera is about to be manipulated. + * If `transformCameraUpdate` is specified or terrain is enabled, a copy of + * the current transform is created to track the accumulated changes. + * This underlying transform represents the "desired state" proposed by input handlers / animations / UI controls. + * It may differ from the state used for rendering (`this.transform`). + * @returns Transform to apply changes to + */ + _getTransformForUpdate() { + if (!this.transformCameraUpdate && !this.terrain) + return this.transform; + if (!this._requestedCameraState) { + this._requestedCameraState = this.transform.clone(); + } + return this._requestedCameraState; + } + /** + * @internal + * Checks the given transform for the camera being below terrain surface and + * returns new pitch and zoom to fix that. + * + * With the new pitch and zoom, the camera will be at the same ground + * position but at higher altitude. It will still point to the same spot on + * the map. + * + * @param tr - The transform to check. + */ + _elevateCameraIfInsideTerrain(tr) { + const camera = tr.getCameraPosition(); + const minAltitude = this.terrain.getElevationForLngLatZoom(camera.lngLat, tr.zoom); + if (camera.altitude < minAltitude) { + const newCamera = this.calculateCameraOptionsFromTo(camera.lngLat, minAltitude, tr.center, tr.elevation); + return { + pitch: newCamera.pitch, + zoom: newCamera.zoom, + }; + } + return {}; + } + /** + * @internal + * Called after the camera is done being manipulated. + * @param tr - the requested camera end state + * If the camera is inside terrain, it gets elevated. + * Call `transformCameraUpdate` if present, and then apply the "approved" changes. + */ + _applyUpdatedTransform(tr) { + const modifiers = []; + if (this.terrain) { + modifiers.push(tr => this._elevateCameraIfInsideTerrain(tr)); + } + if (this.transformCameraUpdate) { + modifiers.push(tr => this.transformCameraUpdate(tr)); + } + if (!modifiers.length) { + return; + } + const finalTransform = tr.clone(); + for (const modifier of modifiers) { + const nextTransform = finalTransform.clone(); + const { center, zoom, pitch, bearing, elevation } = modifier(nextTransform); + if (center) + nextTransform.center = center; + if (zoom !== undefined) + nextTransform.zoom = zoom; + if (pitch !== undefined) + nextTransform.pitch = pitch; + if (bearing !== undefined) + nextTransform.bearing = bearing; + if (elevation !== undefined) + nextTransform.elevation = elevation; + finalTransform.apply(nextTransform); + } + this.transform.apply(finalTransform); + } + _fireMoveEvents(eventData) { + this.fire(new performance$1.k('move', eventData)); + if (this._zooming) { + this.fire(new performance$1.k('zoom', eventData)); + } + if (this._rotating) { + this.fire(new performance$1.k('rotate', eventData)); + } + if (this._pitching) { + this.fire(new performance$1.k('pitch', eventData)); + } + } + _afterEase(eventData, easeId) { + // if this easing is being stopped to start another easing with + // the same id then don't fire any events to avoid extra start/stop events + if (this._easeId && easeId && this._easeId === easeId) { + return; + } + delete this._easeId; + const wasZooming = this._zooming; + const wasRotating = this._rotating; + const wasPitching = this._pitching; + this._moving = false; + this._zooming = false; + this._rotating = false; + this._pitching = false; + this._padding = false; + if (wasZooming) { + this.fire(new performance$1.k('zoomend', eventData)); + } + if (wasRotating) { + this.fire(new performance$1.k('rotateend', eventData)); + } + if (wasPitching) { + this.fire(new performance$1.k('pitchend', eventData)); + } + this.fire(new performance$1.k('moveend', eventData)); + } + /** + * Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that + * evokes flight. The animation seamlessly incorporates zooming and panning to help + * the user maintain her bearings even after traversing a great distance. + * + * Note: The animation will be skipped, and this will behave equivalently to `jumpTo` + * if the user has the `reduced motion` accessibility feature enabled in their operating system, + * unless 'options' includes `essential: true`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`, + * `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options describing the destination and animation of the transition. + * Accepts {@link CameraOptions}, {@link AnimationOptions}, + * and the following additional options. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * // fly with default options to null island + * map.flyTo({center: [0, 0], zoom: 9}); + * // using flyTo options + * map.flyTo({ + * center: [0, 0], + * zoom: 9, + * speed: 0.2, + * curve: 1, + * easing(t) { + * return t; + * } + * }); + * ``` + * @see [Fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/flyto/) + * @see [Slowly fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/flyto-options/) + * @see [Fly to a location based on scroll position](https://maplibre.org/maplibre-gl-js/docs/examples/scroll-fly-to/) + */ + flyTo(options, eventData) { + var _a; + // Fall through to jumpTo if user has set prefers-reduced-motion + if (!options.essential && browser.prefersReducedMotion) { + const coercedOptions = performance$1.M(options, ['center', 'zoom', 'bearing', 'pitch', 'around']); + return this.jumpTo(coercedOptions, eventData); + } + // This method implements an “optimal path” animation, as detailed in: + // + // Van Wijk, Jarke J.; Nuij, Wim A. A. “Smooth and efficient zooming and panning.” INFOVIS + // ’03. pp. 15–22. . + // + // Where applicable, local variable documentation begins with the associated variable or + // function in van Wijk (2003). + this.stop(); + options = performance$1.e({ + offset: [0, 0], + speed: 1.2, + curve: 1.42, + easing: performance$1.b9 + }, options); + const tr = this._getTransformForUpdate(), startZoom = tr.zoom, startBearing = tr.bearing, startPitch = tr.pitch, startPadding = tr.padding; + const bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing; + const pitch = 'pitch' in options ? +options.pitch : startPitch; + const padding = 'padding' in options ? options.padding : tr.padding; + const offsetAsPoint = performance$1.P.convert(options.offset); + let pointAtOffset = tr.centerPoint.add(offsetAsPoint); + const locationAtOffset = tr.pointLocation(pointAtOffset); + const { center, zoom } = tr.getConstrained(performance$1.N.convert(options.center || locationAtOffset), (_a = options.zoom) !== null && _a !== void 0 ? _a : startZoom); + this._normalizeCenter(center, tr); + const scale = tr.zoomScale(zoom - startZoom); + const from = tr.project(locationAtOffset); + const delta = tr.project(center).sub(from); + let rho = options.curve; + // w₀: Initial visible span, measured in pixels at the initial scale. + const w0 = Math.max(tr.width, tr.height), + // w₁: Final visible span, measured in pixels with respect to the initial scale. + w1 = w0 / scale, + // Length of the flight path as projected onto the ground plane, measured in pixels from + // the world image origin at the initial scale. + u1 = delta.mag(); + if ('minZoom' in options) { + const minZoom = performance$1.ac(Math.min(options.minZoom, startZoom, zoom), tr.minZoom, tr.maxZoom); + // wm: Maximum visible span, measured in pixels with respect to the initial + // scale. + const wMax = w0 / tr.zoomScale(minZoom - startZoom); + rho = Math.sqrt(wMax / u1 * 2); + } + // ρ² + const rho2 = rho * rho; + /** + * rᵢ: Returns the zoom-out factor at one end of the animation. + * + * @param descent - `true` for the descent, `false` for the ascent + */ + function zoomOutFactor(descent) { + const b = (w1 * w1 - w0 * w0 + (descent ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (descent ? w1 : w0) * rho2 * u1); + return Math.log(Math.sqrt(b * b + 1) - b); + } + function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; } + function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; } + function tanh(n) { return sinh(n) / cosh(n); } + // r₀: Zoom-out factor during ascent. + const r0 = zoomOutFactor(false); + // w(s): Returns the visible span on the ground, measured in pixels with respect to the + // initial scale. Assumes an angular field of view of 2 arctan ½ ≈ 53°. + let w = function (s) { + return (cosh(r0) / cosh(r0 + rho * s)); + }; + // u(s): Returns the distance along the flight path as projected onto the ground plane, + // measured in pixels from the world image origin at the initial scale. + let u = function (s) { + return w0 * ((cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2) / u1; + }; + // S: Total length of the flight path, measured in ρ-screenfuls. + let S = (zoomOutFactor(true) - r0) / rho; + // When u₀ = u₁, the optimal path doesn’t require both ascent and descent. + if (Math.abs(u1) < 0.000001 || !isFinite(S)) { + // Perform a more or less instantaneous transition if the path is too short. + if (Math.abs(w0 - w1) < 0.000001) + return this.easeTo(options, eventData); + const k = w1 < w0 ? -1 : 1; + S = Math.abs(Math.log(w1 / w0)) / rho; + u = () => 0; + w = (s) => Math.exp(k * rho * s); + } + if ('duration' in options) { + options.duration = +options.duration; + } + else { + const V = 'screenSpeed' in options ? +options.screenSpeed / rho : +options.speed; + options.duration = 1000 * S / V; + } + if (options.maxDuration && options.duration > options.maxDuration) { + options.duration = 0; + } + this._zooming = true; + this._rotating = (startBearing !== bearing); + this._pitching = (pitch !== startPitch); + this._padding = !tr.isPaddingEqual(padding); + this._prepareEase(eventData, false); + if (this.terrain) + this._prepareElevation(center); + this._ease((k) => { + // s: The distance traveled along the flight path, measured in ρ-screenfuls. + const s = k * S; + const scale = 1 / w(s); + tr.zoom = k === 1 ? zoom : startZoom + tr.scaleZoom(scale); + if (this._rotating) { + tr.bearing = performance$1.y.number(startBearing, bearing, k); + } + if (this._pitching) { + tr.pitch = performance$1.y.number(startPitch, pitch, k); + } + if (this._padding) { + tr.interpolatePadding(startPadding, padding, k); + // When padding is being applied, Transform#centerPoint is changing continuously, + // thus we need to recalculate offsetPoint every frame + pointAtOffset = tr.centerPoint.add(offsetAsPoint); + } + if (this.terrain && !options.freezeElevation) + this._updateElevation(k); + const newCenter = k === 1 ? center : tr.unproject(from.add(delta.mult(u(s))).mult(scale)); + tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset); + this._applyUpdatedTransform(tr); + this._fireMoveEvents(eventData); + }, () => { + if (this.terrain && options.freezeElevation) + this._finalizeElevation(); + this._afterEase(eventData); + }, options); + return this; + } + isEasing() { + return !!this._easeFrameId; + } + /** + * Stops any animated transition underway. + */ + stop() { + return this._stop(); + } + _stop(allowGestures, easeId) { + var _a; + if (this._easeFrameId) { + this._cancelRenderFrame(this._easeFrameId); + delete this._easeFrameId; + delete this._onEaseFrame; + } + if (this._onEaseEnd) { + // The _onEaseEnd function might emit events which trigger new + // animation, which sets a new _onEaseEnd. Ensure we don't delete + // it unintentionally. + const onEaseEnd = this._onEaseEnd; + delete this._onEaseEnd; + onEaseEnd.call(this, easeId); + } + if (!allowGestures) { + (_a = this.handlers) === null || _a === void 0 ? void 0 : _a.stop(false); + } + return this; + } + _ease(frame, finish, options) { + if (options.animate === false || options.duration === 0) { + frame(1); + finish(); + } + else { + this._easeStart = browser.now(); + this._easeOptions = options; + this._onEaseFrame = frame; + this._onEaseEnd = finish; + this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback); + } + } + // convert bearing so that it's numerically close to the current one so that it interpolates properly + _normalizeBearing(bearing, currentBearing) { + bearing = performance$1.b3(bearing, -180, 180); + const diff = Math.abs(bearing - currentBearing); + if (Math.abs(bearing - 360 - currentBearing) < diff) + bearing -= 360; + if (Math.abs(bearing + 360 - currentBearing) < diff) + bearing += 360; + return bearing; + } + // If a path crossing the antimeridian would be shorter, extend the final coordinate so that + // interpolating between the two endpoints will cross it. + _normalizeCenter(center, tr) { + if (!tr.renderWorldCopies || tr.lngRange) + return; + const delta = center.lng - tr.center.lng; + center.lng += + delta > 180 ? -360 : + delta < -180 ? 360 : 0; + } + /** + * Get the elevation difference between a given point + * and a point that is currently in the middle of the screen. + * This method should be used for proper positioning of custom 3d objects, as explained [here](https://maplibre.org/maplibre-gl-js/docs/examples/add-3d-model-with-terrain/) + * Returns null if terrain is not enabled. + * This method is subject to change in Maplibre GL JS v5. + * @param lngLatLike - [x,y] or LngLat coordinates of the location + * @returns elevation offset in meters + */ + queryTerrainElevation(lngLatLike) { + if (!this.terrain) { + return null; + } + const elevation = this.terrain.getElevationForLngLatZoom(performance$1.N.convert(lngLatLike), this.transform.tileZoom); + return elevation - this.transform.elevation; + } +} + +const defaultAttributionControlOptions = { + compact: true, + customAttribution: 'MapLibre' +}; +/** + * An `AttributionControl` control presents the map's attribution information. By default, the attribution control is expanded (regardless of map width). + * @group Markers and Controls + * @example + * ```ts + * let map = new Map({attributionControl: false}) + * .addControl(new AttributionControl({ + * compact: true + * })); + * ``` + */ +class AttributionControl { + /** + * @param options - the attribution options + */ + constructor(options = defaultAttributionControlOptions) { + this._toggleAttribution = () => { + if (this._container.classList.contains('maplibregl-compact')) { + if (this._container.classList.contains('maplibregl-compact-show')) { + this._container.setAttribute('open', ''); + this._container.classList.remove('maplibregl-compact-show'); + } + else { + this._container.classList.add('maplibregl-compact-show'); + this._container.removeAttribute('open'); + } + } + }; + this._updateData = (e) => { + if (e && (e.sourceDataType === 'metadata' || e.sourceDataType === 'visibility' || e.dataType === 'style' || e.type === 'terrain')) { + this._updateAttributions(); + } + }; + this._updateCompact = () => { + if (this._map.getCanvasContainer().offsetWidth <= 640 || this._compact) { + if (this._compact === false) { + this._container.setAttribute('open', ''); + } + else if (!this._container.classList.contains('maplibregl-compact') && !this._container.classList.contains('maplibregl-attrib-empty')) { + this._container.setAttribute('open', ''); + this._container.classList.add('maplibregl-compact', 'maplibregl-compact-show'); + } + } + else { + this._container.setAttribute('open', ''); + if (this._container.classList.contains('maplibregl-compact')) { + this._container.classList.remove('maplibregl-compact', 'maplibregl-compact-show'); + } + } + }; + this._updateCompactMinimize = () => { + if (this._container.classList.contains('maplibregl-compact')) { + if (this._container.classList.contains('maplibregl-compact-show')) { + this._container.classList.remove('maplibregl-compact-show'); + } + } + }; + this.options = options; + } + getDefaultPosition() { + return 'bottom-right'; + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._compact = this.options.compact; + this._container = DOM.create('details', 'maplibregl-ctrl maplibregl-ctrl-attrib'); + this._compactButton = DOM.create('summary', 'maplibregl-ctrl-attrib-button', this._container); + this._compactButton.addEventListener('click', this._toggleAttribution); + this._setElementTitle(this._compactButton, 'ToggleAttribution'); + this._innerContainer = DOM.create('div', 'maplibregl-ctrl-attrib-inner', this._container); + this._updateAttributions(); + this._updateCompact(); + this._map.on('styledata', this._updateData); + this._map.on('sourcedata', this._updateData); + this._map.on('terrain', this._updateData); + this._map.on('resize', this._updateCompact); + this._map.on('drag', this._updateCompactMinimize); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + this._map.off('styledata', this._updateData); + this._map.off('sourcedata', this._updateData); + this._map.off('terrain', this._updateData); + this._map.off('resize', this._updateCompact); + this._map.off('drag', this._updateCompactMinimize); + this._map = undefined; + this._compact = undefined; + this._attribHTML = undefined; + } + _setElementTitle(element, title) { + const str = this._map._getUIString(`AttributionControl.${title}`); + element.title = str; + element.setAttribute('aria-label', str); + } + _updateAttributions() { + if (!this._map.style) + return; + let attributions = []; + if (this.options.customAttribution) { + if (Array.isArray(this.options.customAttribution)) { + attributions = attributions.concat(this.options.customAttribution.map(attribution => { + if (typeof attribution !== 'string') + return ''; + return attribution; + })); + } + else if (typeof this.options.customAttribution === 'string') { + attributions.push(this.options.customAttribution); + } + } + if (this._map.style.stylesheet) { + const stylesheet = this._map.style.stylesheet; + this.styleOwner = stylesheet.owner; + this.styleId = stylesheet.id; + } + const sourceCaches = this._map.style.sourceCaches; + for (const id in sourceCaches) { + const sourceCache = sourceCaches[id]; + if (sourceCache.used || sourceCache.usedForTerrain) { + const source = sourceCache.getSource(); + if (source.attribution && attributions.indexOf(source.attribution) < 0) { + attributions.push(source.attribution); + } + } + } + // remove any entries that are whitespace + attributions = attributions.filter(e => String(e).trim()); + // remove any entries that are substrings of another entry. + // first sort by length so that substrings come first + attributions.sort((a, b) => a.length - b.length); + attributions = attributions.filter((attrib, i) => { + for (let j = i + 1; j < attributions.length; j++) { + if (attributions[j].indexOf(attrib) >= 0) { + return false; + } + } + return true; + }); + // check if attribution string is different to minimize DOM changes + const attribHTML = attributions.join(' | '); + if (attribHTML === this._attribHTML) + return; + this._attribHTML = attribHTML; + if (attributions.length) { + this._innerContainer.innerHTML = attribHTML; + this._container.classList.remove('maplibregl-attrib-empty'); + } + else { + this._container.classList.add('maplibregl-attrib-empty'); + } + this._updateCompact(); + // remove old DOM node from _editLink + this._editLink = null; + } +} + +/** + * A `LogoControl` is a control that adds the watermark. + * + * @group Markers and Controls + * + * @example + * ```ts + * map.addControl(new LogoControl({compact: false})); + * ``` + **/ +class LogoControl { + /** + * @param options - the control's options + */ + constructor(options = {}) { + this._updateCompact = () => { + const containerChildren = this._container.children; + if (containerChildren.length) { + const anchor = containerChildren[0]; + if (this._map.getCanvasContainer().offsetWidth <= 640 || this._compact) { + if (this._compact !== false) { + anchor.classList.add('maplibregl-compact'); + } + } + else { + anchor.classList.remove('maplibregl-compact'); + } + } + }; + this.options = options; + } + getDefaultPosition() { + return 'bottom-left'; + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._compact = this.options && this.options.compact; + this._container = DOM.create('div', 'maplibregl-ctrl'); + const anchor = DOM.create('a', 'maplibregl-ctrl-logo'); + anchor.target = '_blank'; + anchor.rel = 'noopener nofollow'; + anchor.href = 'https://maplibre.org/'; + anchor.setAttribute('aria-label', this._map._getUIString('LogoControl.Title')); + anchor.setAttribute('rel', 'noopener nofollow'); + this._container.appendChild(anchor); + this._container.style.display = 'block'; + this._map.on('resize', this._updateCompact); + this._updateCompact(); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + this._map.off('resize', this._updateCompact); + this._map = undefined; + this._compact = undefined; + } +} + +class TaskQueue { + constructor() { + this._queue = []; + this._id = 0; + this._cleared = false; + this._currentlyRunning = false; + } + add(callback) { + const id = ++this._id; + const queue = this._queue; + queue.push({ callback, id, cancelled: false }); + return id; + } + remove(id) { + const running = this._currentlyRunning; + const queue = running ? this._queue.concat(running) : this._queue; + for (const task of queue) { + if (task.id === id) { + task.cancelled = true; + return; + } + } + } + run(timeStamp = 0) { + if (this._currentlyRunning) + throw new Error('Attempting to run(), but is already running.'); + const queue = this._currentlyRunning = this._queue; + // Tasks queued by callbacks in the current queue should be executed + // on the next run, not the current run. + this._queue = []; + for (const task of queue) { + if (task.cancelled) + continue; + task.callback(timeStamp); + if (this._cleared) + break; + } + this._cleared = false; + this._currentlyRunning = false; + } + clear() { + if (this._currentlyRunning) { + this._cleared = true; + } + this._queue = []; + } +} + +var pos3dAttributes = performance$1.Y([ + { name: 'a_pos3d', type: 'Int16', components: 3 } +]); + +/** + * @internal + * This class is a helper for the Terrain-class, it: + * + * - loads raster-dem tiles + * - manages all renderToTexture tiles. + * - caches previous rendered tiles. + * - finds all necessary renderToTexture tiles for a OverscaledTileID area + * - finds the corresponding raster-dem tile for OverscaledTileID + */ +class TerrainSourceCache extends performance$1.E { + constructor(sourceCache) { + super(); + this.sourceCache = sourceCache; + this._tiles = {}; + this._renderableTilesKeys = []; + this._sourceTileCache = {}; + this.minzoom = 0; + this.maxzoom = 22; + this.tileSize = 512; + this.deltaZoom = 1; + sourceCache.usedForTerrain = true; + sourceCache.tileSize = this.tileSize * 2 ** this.deltaZoom; + } + destruct() { + this.sourceCache.usedForTerrain = false; + this.sourceCache.tileSize = null; + } + /** + * Load Terrain Tiles, create internal render-to-texture tiles, free GPU memory. + * @param transform - the operation to do + * @param terrain - the terrain + */ + update(transform, terrain) { + // load raster-dem tiles for the current scene. + this.sourceCache.update(transform, terrain); + // create internal render-to-texture tiles for the current scene. + this._renderableTilesKeys = []; + const keys = {}; + for (const tileID of transform.coveringTiles({ + tileSize: this.tileSize, + minzoom: this.minzoom, + maxzoom: this.maxzoom, + reparseOverscaled: false, + terrain + })) { + keys[tileID.key] = true; + this._renderableTilesKeys.push(tileID.key); + if (!this._tiles[tileID.key]) { + tileID.posMatrix = new Float64Array(16); + performance$1.aP(tileID.posMatrix, 0, performance$1.X, 0, performance$1.X, 0, 1); + this._tiles[tileID.key] = new Tile(tileID, this.tileSize); + } + } + // free unused tiles + for (const key in this._tiles) { + if (!keys[key]) + delete this._tiles[key]; + } + } + /** + * Free render to texture cache + * @param tileID - optional, free only corresponding to tileID. + */ + freeRtt(tileID) { + for (const key in this._tiles) { + const tile = this._tiles[key]; + if (!tileID || tile.tileID.equals(tileID) || tile.tileID.isChildOf(tileID) || tileID.isChildOf(tile.tileID)) + tile.rtt = []; + } + } + /** + * get a list of tiles, which are loaded and should be rendered in the current scene + * @returns the renderable tiles + */ + getRenderableTiles() { + return this._renderableTilesKeys.map(key => this.getTileByID(key)); + } + /** + * get terrain tile by the TileID key + * @param id - the tile id + * @returns the tile + */ + getTileByID(id) { + return this._tiles[id]; + } + /** + * Searches for the corresponding current renderable terrain-tiles + * @param tileID - the tile to look for + * @returns the tiles that were found + */ + getTerrainCoords(tileID) { + const coords = {}; + for (const key of this._renderableTilesKeys) { + const _tileID = this._tiles[key].tileID; + if (_tileID.canonical.equals(tileID.canonical)) { + const coord = tileID.clone(); + coord.posMatrix = new Float64Array(16); + performance$1.aP(coord.posMatrix, 0, performance$1.X, 0, performance$1.X, 0, 1); + coords[key] = coord; + } + else if (_tileID.canonical.isChildOf(tileID.canonical)) { + const coord = tileID.clone(); + coord.posMatrix = new Float64Array(16); + const dz = _tileID.canonical.z - tileID.canonical.z; + const dx = _tileID.canonical.x - (_tileID.canonical.x >> dz << dz); + const dy = _tileID.canonical.y - (_tileID.canonical.y >> dz << dz); + const size = performance$1.X >> dz; + performance$1.aP(coord.posMatrix, 0, size, 0, size, 0, 1); + performance$1.J(coord.posMatrix, coord.posMatrix, [-dx * size, -dy * size, 0]); + coords[key] = coord; + } + else if (tileID.canonical.isChildOf(_tileID.canonical)) { + const coord = tileID.clone(); + coord.posMatrix = new Float64Array(16); + const dz = tileID.canonical.z - _tileID.canonical.z; + const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz); + const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz); + const size = performance$1.X >> dz; + performance$1.aP(coord.posMatrix, 0, performance$1.X, 0, performance$1.X, 0, 1); + performance$1.J(coord.posMatrix, coord.posMatrix, [dx * size, dy * size, 0]); + performance$1.K(coord.posMatrix, coord.posMatrix, [1 / (2 ** dz), 1 / (2 ** dz), 0]); + coords[key] = coord; + } + } + return coords; + } + /** + * find the covering raster-dem tile + * @param tileID - the tile to look for + * @param searchForDEM - Optional parameter to search for (parent) sourcetiles with loaded dem. + * @returns the tile + */ + getSourceTile(tileID, searchForDEM) { + const source = this.sourceCache._source; + let z = tileID.overscaledZ - this.deltaZoom; + if (z > source.maxzoom) + z = source.maxzoom; + if (z < source.minzoom) + return null; + // cache for tileID to terrain-tileID + if (!this._sourceTileCache[tileID.key]) + this._sourceTileCache[tileID.key] = tileID.scaledTo(z).key; + let tile = this.sourceCache.getTileByID(this._sourceTileCache[tileID.key]); + // during tile-loading phase look if parent tiles (with loaded dem) are available. + if (!(tile && tile.dem) && searchForDEM) + while (z >= source.minzoom && !(tile && tile.dem)) + tile = this.sourceCache.getTileByID(tileID.scaledTo(z--).key); + return tile; + } + /** + * get a list of tiles, loaded after a specific time. This is used to update depth & coords framebuffers. + * @param time - the time + * @returns the relevant tiles + */ + tilesAfterTime(time = Date.now()) { + return Object.values(this._tiles).filter(t => t.timeAdded >= time); + } +} + +/** + * @internal + * This is the main class which handles most of the 3D Terrain logic. It has the following topics: + * + * 1. loads raster-dem tiles via the internal sourceCache this.sourceCache + * 2. creates a depth-framebuffer, which is used to calculate the visibility of coordinates + * 3. creates a coords-framebuffer, which is used the get to tile-coordinate for a screen-pixel + * 4. stores all render-to-texture tiles in the this.sourceCache._tiles + * 5. calculates the elevation for a specific tile-coordinate + * 6. creates a terrain-mesh + * + * A note about the GPU resource-usage: + * + * Framebuffers: + * + * - one for the depth & coords framebuffer with the size of the map-div. + * - one for rendering a tile to texture with the size of tileSize (= 512x512). + * + * Textures: + * + * - one texture for an empty raster-dem tile with size 1x1 + * - one texture for an empty depth-buffer, when terrain is disabled with size 1x1 + * - one texture for an each loaded raster-dem with size of the source.tileSize + * - one texture for the coords-framebuffer with the size of the map-div. + * - one texture for the depth-framebuffer with the size of the map-div. + * - one texture for the encoded tile-coords with the size 2*tileSize (=1024x1024) + * - finally for each render-to-texture tile (= this._tiles) a set of textures + * for each render stack (The stack-concept is documented in painter.ts). + * + * Normally there exists 1-3 Textures per tile, depending on the stylesheet. + * Each Textures has the size 2*tileSize (= 1024x1024). Also there exists a + * cache of the last 150 newest rendered tiles. + * + */ +class Terrain { + constructor(painter, sourceCache, options) { + this.painter = painter; + this.sourceCache = new TerrainSourceCache(sourceCache); + this.options = options; + this.exaggeration = typeof options.exaggeration === 'number' ? options.exaggeration : 1.0; + this.qualityFactor = 2; + this.meshSize = 128; + this._demMatrixCache = {}; + this.coordsIndex = []; + this._coordsTextureSize = 1024; + } + /** + * get the elevation-value from original dem-data for a given tile-coordinate + * @param tileID - the tile to get elevation for + * @param x - between 0 .. EXTENT + * @param y - between 0 .. EXTENT + * @param extent - optional, default 8192 + * @returns the elevation + */ + getDEMElevation(tileID, x, y, extent = performance$1.X) { + var _a; + if (!(x >= 0 && x < extent && y >= 0 && y < extent)) + return 0; + const terrain = this.getTerrainData(tileID); + const dem = (_a = terrain.tile) === null || _a === void 0 ? void 0 : _a.dem; + if (!dem) + return 0; + const pos = transformMat4([], [x / extent * performance$1.X, y / extent * performance$1.X], terrain.u_terrain_matrix); + const coord = [pos[0] * dem.dim, pos[1] * dem.dim]; + // bilinear interpolation + const cx = Math.floor(coord[0]), cy = Math.floor(coord[1]), tx = coord[0] - cx, ty = coord[1] - cy; + return (dem.get(cx, cy) * (1 - tx) * (1 - ty) + + dem.get(cx + 1, cy) * (tx) * (1 - ty) + + dem.get(cx, cy + 1) * (1 - tx) * (ty) + + dem.get(cx + 1, cy + 1) * (tx) * (ty)); + } + /** + * Get the elevation for given {@link LngLat} in respect of exaggeration. + * @param lnglat - the location + * @param zoom - the zoom + * @returns the elevation + */ + getElevationForLngLatZoom(lnglat, zoom) { + if (!performance$1.bb(zoom, lnglat.wrap())) + return 0; + const { tileID, mercatorX, mercatorY } = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom); + return this.getElevation(tileID, mercatorX % performance$1.X, mercatorY % performance$1.X, performance$1.X); + } + /** + * Get the elevation for given coordinate in respect of exaggeration. + * @param tileID - the tile id + * @param x - between 0 .. EXTENT + * @param y - between 0 .. EXTENT + * @param extent - optional, default 8192 + * @returns the elevation + */ + getElevation(tileID, x, y, extent = performance$1.X) { + return this.getDEMElevation(tileID, x, y, extent) * this.exaggeration; + } + /** + * returns a Terrain Object for a tile. Unless the tile corresponds to data (e.g. tile is loading), return a flat dem object + * @param tileID - the tile to get the terrain for + * @returns the terrain data to use in the program + */ + getTerrainData(tileID) { + // create empty DEM Objects, which will used while raster-dem tiles are loading. + // creates an empty depth-buffer texture which is needed, during the initialization process of the 3d mesh.. + if (!this._emptyDemTexture) { + const context = this.painter.context; + const image = new performance$1.R({ width: 1, height: 1 }, new Uint8Array(1 * 4)); + this._emptyDepthTexture = new Texture(context, image, context.gl.RGBA, { premultiply: false }); + this._emptyDemUnpack = [0, 0, 0, 0]; + this._emptyDemTexture = new Texture(context, new performance$1.R({ width: 1, height: 1 }), context.gl.RGBA, { premultiply: false }); + this._emptyDemTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE); + this._emptyDemMatrix = performance$1.an([]); + } + // find covering dem tile and prepare demTexture + const sourceTile = this.sourceCache.getSourceTile(tileID, true); + if (sourceTile && sourceTile.dem && (!sourceTile.demTexture || sourceTile.needsTerrainPrepare)) { + const context = this.painter.context; + sourceTile.demTexture = this.painter.getTileTexture(sourceTile.dem.stride); + if (sourceTile.demTexture) + sourceTile.demTexture.update(sourceTile.dem.getPixels(), { premultiply: false }); + else + sourceTile.demTexture = new Texture(context, sourceTile.dem.getPixels(), context.gl.RGBA, { premultiply: false }); + sourceTile.demTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE); + sourceTile.needsTerrainPrepare = false; + } + // create matrix for lookup in dem data + const matrixKey = sourceTile && (sourceTile + sourceTile.tileID.key) + tileID.key; + if (matrixKey && !this._demMatrixCache[matrixKey]) { + const maxzoom = this.sourceCache.sourceCache._source.maxzoom; + let dz = tileID.canonical.z - sourceTile.tileID.canonical.z; + if (tileID.overscaledZ > tileID.canonical.z) { + if (tileID.canonical.z >= maxzoom) + dz = tileID.canonical.z - maxzoom; + else + performance$1.w('cannot calculate elevation if elevation maxzoom > source.maxzoom'); + } + const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz); + const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz); + const demMatrix = performance$1.bc(new Float64Array(16), [1 / (performance$1.X << dz), 1 / (performance$1.X << dz), 0]); + performance$1.J(demMatrix, demMatrix, [dx * performance$1.X, dy * performance$1.X, 0]); + this._demMatrixCache[tileID.key] = { matrix: demMatrix, coord: tileID }; + } + // return uniform values & textures + return { + 'u_depth': 2, + 'u_terrain': 3, + 'u_terrain_dim': sourceTile && sourceTile.dem && sourceTile.dem.dim || 1, + 'u_terrain_matrix': matrixKey ? this._demMatrixCache[tileID.key].matrix : this._emptyDemMatrix, + 'u_terrain_unpack': sourceTile && sourceTile.dem && sourceTile.dem.getUnpackVector() || this._emptyDemUnpack, + 'u_terrain_exaggeration': this.exaggeration, + texture: (sourceTile && sourceTile.demTexture || this._emptyDemTexture).texture, + depthTexture: (this._fboDepthTexture || this._emptyDepthTexture).texture, + tile: sourceTile + }; + } + /** + * get a framebuffer as big as the map-div, which will be used to render depth & coords into a texture + * @param texture - the texture + * @returns the frame buffer + */ + getFramebuffer(texture) { + const painter = this.painter; + const width = painter.width / devicePixelRatio; + const height = painter.height / devicePixelRatio; + if (this._fbo && (this._fbo.width !== width || this._fbo.height !== height)) { + this._fbo.destroy(); + this._fboCoordsTexture.destroy(); + this._fboDepthTexture.destroy(); + delete this._fbo; + delete this._fboDepthTexture; + delete this._fboCoordsTexture; + } + if (!this._fboCoordsTexture) { + this._fboCoordsTexture = new Texture(painter.context, { width, height, data: null }, painter.context.gl.RGBA, { premultiply: false }); + this._fboCoordsTexture.bind(painter.context.gl.NEAREST, painter.context.gl.CLAMP_TO_EDGE); + } + if (!this._fboDepthTexture) { + this._fboDepthTexture = new Texture(painter.context, { width, height, data: null }, painter.context.gl.RGBA, { premultiply: false }); + this._fboDepthTexture.bind(painter.context.gl.NEAREST, painter.context.gl.CLAMP_TO_EDGE); + } + if (!this._fbo) { + this._fbo = painter.context.createFramebuffer(width, height, true, false); + this._fbo.depthAttachment.set(painter.context.createRenderbuffer(painter.context.gl.DEPTH_COMPONENT16, width, height)); + } + this._fbo.colorAttachment.set(texture === 'coords' ? this._fboCoordsTexture.texture : this._fboDepthTexture.texture); + return this._fbo; + } + /** + * create coords texture, needed to grab coordinates from canvas + * encode coords coordinate into 4 bytes: + * - 8 lower bits for x + * - 8 lower bits for y + * - 4 higher bits for x + * - 4 higher bits for y + * - 8 bits for coordsIndex (1 .. 255) (= number of terraintile), is later setted in draw_terrain uniform value + * @returns the texture + */ + getCoordsTexture() { + const context = this.painter.context; + if (this._coordsTexture) + return this._coordsTexture; + const data = new Uint8Array(this._coordsTextureSize * this._coordsTextureSize * 4); + for (let y = 0, i = 0; y < this._coordsTextureSize; y++) + for (let x = 0; x < this._coordsTextureSize; x++, i += 4) { + data[i + 0] = x & 255; + data[i + 1] = y & 255; + data[i + 2] = ((x >> 8) << 4) | (y >> 8); + data[i + 3] = 0; + } + const image = new performance$1.R({ width: this._coordsTextureSize, height: this._coordsTextureSize }, new Uint8Array(data.buffer)); + const texture = new Texture(context, image, context.gl.RGBA, { premultiply: false }); + texture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE); + this._coordsTexture = texture; + return texture; + } + /** + * Reads a pixel from the coords-framebuffer and translate this to mercator. + * @param p - Screen-Coordinate + * @returns mercator coordinate for a screen pixel + */ + pointCoordinate(p) { + // First, ensure the coords framebuffer is up to date. + this.painter.maybeDrawDepthAndCoords(true); + const rgba = new Uint8Array(4); + const context = this.painter.context, gl = context.gl; + const px = Math.round(p.x * this.painter.pixelRatio / devicePixelRatio); + const py = Math.round(p.y * this.painter.pixelRatio / devicePixelRatio); + const fbHeight = Math.round(this.painter.height / devicePixelRatio); + // grab coordinate pixel from coordinates framebuffer + context.bindFramebuffer.set(this.getFramebuffer('coords').framebuffer); + gl.readPixels(px, fbHeight - py - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rgba); + context.bindFramebuffer.set(null); + // decode coordinates (encoding see getCoordsTexture) + const x = rgba[0] + ((rgba[2] >> 4) << 8); + const y = rgba[1] + ((rgba[2] & 15) << 8); + const tileID = this.coordsIndex[255 - rgba[3]]; + const tile = tileID && this.sourceCache.getTileByID(tileID); + if (!tile) + return null; + const coordsSize = this._coordsTextureSize; + const worldSize = (1 << tile.tileID.canonical.z) * coordsSize; + return new performance$1.Z((tile.tileID.canonical.x * coordsSize + x) / worldSize + tile.tileID.wrap, (tile.tileID.canonical.y * coordsSize + y) / worldSize, this.getElevation(tile.tileID, x, y, coordsSize)); + } + /** + * Reads the depth value from the depth-framebuffer at a given screen pixel + * @param p - Screen coordinate + * @returns depth value in clip space (between 0 and 1) + */ + depthAtPoint(p) { + const rgba = new Uint8Array(4); + const context = this.painter.context, gl = context.gl; + context.bindFramebuffer.set(this.getFramebuffer('depth').framebuffer); + gl.readPixels(p.x, this.painter.height / devicePixelRatio - p.y - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rgba); + context.bindFramebuffer.set(null); + // decode coordinates (encoding see terran_depth.fragment.glsl) + const depthValue = (rgba[0] / (256 * 256 * 256) + rgba[1] / (256 * 256) + rgba[2] / 256 + rgba[3]) / 256; + return depthValue; + } + /** + * create a regular mesh which will be used by all terrain-tiles + * @returns the created regular mesh + */ + getTerrainMesh() { + if (this._mesh) + return this._mesh; + const context = this.painter.context; + const vertexArray = new performance$1.bd(); + const indexArray = new performance$1.aY(); + const meshSize = this.meshSize; + const delta = performance$1.X / meshSize; + const meshSize2 = meshSize * meshSize; + for (let y = 0; y <= meshSize; y++) + for (let x = 0; x <= meshSize; x++) + vertexArray.emplaceBack(x * delta, y * delta, 0); + for (let y = 0; y < meshSize2; y += meshSize + 1) + for (let x = 0; x < meshSize; x++) { + indexArray.emplaceBack(x + y, meshSize + x + y + 1, meshSize + x + y + 2); + indexArray.emplaceBack(x + y, meshSize + x + y + 2, x + y + 1); + } + // add an extra frame around the mesh to avoid stiching on tile boundaries with different zoomlevels + // first code-block is for top-bottom frame and second for left-right frame + const offsetTop = vertexArray.length, offsetBottom = offsetTop + (meshSize + 1) * 2; + for (const y of [0, 1]) + for (let x = 0; x <= meshSize; x++) + for (const z of [0, 1]) + vertexArray.emplaceBack(x * delta, y * performance$1.X, z); + for (let x = 0; x < meshSize * 2; x += 2) { + indexArray.emplaceBack(offsetBottom + x, offsetBottom + x + 1, offsetBottom + x + 3); + indexArray.emplaceBack(offsetBottom + x, offsetBottom + x + 3, offsetBottom + x + 2); + indexArray.emplaceBack(offsetTop + x, offsetTop + x + 3, offsetTop + x + 1); + indexArray.emplaceBack(offsetTop + x, offsetTop + x + 2, offsetTop + x + 3); + } + const offsetLeft = vertexArray.length, offsetRight = offsetLeft + (meshSize + 1) * 2; + for (const x of [0, 1]) + for (let y = 0; y <= meshSize; y++) + for (const z of [0, 1]) + vertexArray.emplaceBack(x * performance$1.X, y * delta, z); + for (let y = 0; y < meshSize * 2; y += 2) { + indexArray.emplaceBack(offsetLeft + y, offsetLeft + y + 1, offsetLeft + y + 3); + indexArray.emplaceBack(offsetLeft + y, offsetLeft + y + 3, offsetLeft + y + 2); + indexArray.emplaceBack(offsetRight + y, offsetRight + y + 3, offsetRight + y + 1); + indexArray.emplaceBack(offsetRight + y, offsetRight + y + 2, offsetRight + y + 3); + } + this._mesh = new Mesh(context.createVertexBuffer(vertexArray, pos3dAttributes.members), context.createIndexBuffer(indexArray), performance$1.a0.simpleSegment(0, 0, vertexArray.length, indexArray.length)); + return this._mesh; + } + /** + * Calculates a height of the frame around the terrain-mesh to avoid stiching between + * tile boundaries in different zoomlevels. + * @param zoom - current zoomlevel + * @returns the elevation delta in meters + */ + getMeshFrameDelta(zoom) { + // divide by 5 is evaluated by trial & error to get a frame in the right height + return 2 * Math.PI * performance$1.be / Math.pow(2, zoom) / 5; + } + getMinTileElevationForLngLatZoom(lnglat, zoom) { + var _a; + const { tileID } = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom); + return (_a = this.getMinMaxElevation(tileID).minElevation) !== null && _a !== void 0 ? _a : 0; + } + /** + * Get the minimum and maximum elevation contained in a tile. This includes any + * exaggeration included in the terrain. + * + * @param tileID - ID of the tile to be used as a source for the min/max elevation + * @returns the minimum and maximum elevation found in the tile, including the terrain's + * exaggeration + */ + getMinMaxElevation(tileID) { + const tile = this.getTerrainData(tileID).tile; + const minMax = { minElevation: null, maxElevation: null }; + if (tile && tile.dem) { + minMax.minElevation = tile.dem.min * this.exaggeration; + minMax.maxElevation = tile.dem.max * this.exaggeration; + } + return minMax; + } + _getOverscaledTileIDFromLngLatZoom(lnglat, zoom) { + const mercatorCoordinate = performance$1.Z.fromLngLat(lnglat.wrap()); + const worldSize = (1 << zoom) * performance$1.X; + const mercatorX = mercatorCoordinate.x * worldSize; + const mercatorY = mercatorCoordinate.y * worldSize; + const tileX = Math.floor(mercatorX / performance$1.X), tileY = Math.floor(mercatorY / performance$1.X); + const tileID = new performance$1.S(zoom, 0, zoom, tileX, tileY); + return { + tileID, + mercatorX, + mercatorY + }; + } +} + +/** + * @internal + * `RenderPool` is a resource pool for textures and framebuffers + */ +class RenderPool { + constructor(_context, _size, _tileSize) { + this._context = _context; + this._size = _size; + this._tileSize = _tileSize; + this._objects = []; + this._recentlyUsed = []; + this._stamp = 0; + } + destruct() { + for (const obj of this._objects) { + obj.texture.destroy(); + obj.fbo.destroy(); + } + } + _createObject(id) { + const fbo = this._context.createFramebuffer(this._tileSize, this._tileSize, true, true); + const texture = new Texture(this._context, { width: this._tileSize, height: this._tileSize, data: null }, this._context.gl.RGBA); + texture.bind(this._context.gl.LINEAR, this._context.gl.CLAMP_TO_EDGE); + fbo.depthAttachment.set(this._context.createRenderbuffer(this._context.gl.DEPTH_STENCIL, this._tileSize, this._tileSize)); + fbo.colorAttachment.set(texture.texture); + return { id, fbo, texture, stamp: -1, inUse: false }; + } + getObjectForId(id) { + return this._objects[id]; + } + useObject(obj) { + obj.inUse = true; + this._recentlyUsed = this._recentlyUsed.filter(id => obj.id !== id); + this._recentlyUsed.push(obj.id); + } + stampObject(obj) { + obj.stamp = ++this._stamp; + } + getOrCreateFreeObject() { + // check for free existing object + for (const id of this._recentlyUsed) { + if (!this._objects[id].inUse) + return this._objects[id]; + } + if (this._objects.length >= this._size) + throw new Error('No free RenderPool available, call freeAllObjects() required!'); + // create new object + const obj = this._createObject(this._objects.length); + this._objects.push(obj); + return obj; + } + freeObject(obj) { + obj.inUse = false; + } + freeAllObjects() { + for (const obj of this._objects) + this.freeObject(obj); + } + isFull() { + if (this._objects.length < this._size) { + return false; + } + return this._objects.some(o => !o.inUse) === false; + } +} + +/** + * lookup table which layers should rendered to texture + */ +const LAYERS = { + background: true, + fill: true, + line: true, + raster: true, + hillshade: true +}; +/** + * @internal + * A helper class to help define what should be rendered to texture and how + */ +class RenderToTexture { + constructor(painter, terrain) { + this.painter = painter; + this.terrain = terrain; + this.pool = new RenderPool(painter.context, 30, terrain.sourceCache.tileSize * terrain.qualityFactor); + } + destruct() { + this.pool.destruct(); + } + getTexture(tile) { + return this.pool.getObjectForId(tile.rtt[this._stacks.length - 1].id).texture; + } + prepareForRender(style, zoom) { + this._stacks = []; + this._prevType = null; + this._rttTiles = []; + this._renderableTiles = this.terrain.sourceCache.getRenderableTiles(); + this._renderableLayerIds = style._order.filter(id => !style._layers[id].isHidden(zoom)); + this._coordsDescendingInv = {}; + for (const id in style.sourceCaches) { + this._coordsDescendingInv[id] = {}; + const tileIDs = style.sourceCaches[id].getVisibleCoordinates(); + for (const tileID of tileIDs) { + const keys = this.terrain.sourceCache.getTerrainCoords(tileID); + for (const key in keys) { + if (!this._coordsDescendingInv[id][key]) + this._coordsDescendingInv[id][key] = []; + this._coordsDescendingInv[id][key].push(keys[key]); + } + } + } + this._coordsDescendingInvStr = {}; + for (const id of style._order) { + const layer = style._layers[id], source = layer.source; + if (LAYERS[layer.type]) { + if (!this._coordsDescendingInvStr[source]) { + this._coordsDescendingInvStr[source] = {}; + for (const key in this._coordsDescendingInv[source]) + this._coordsDescendingInvStr[source][key] = this._coordsDescendingInv[source][key].map(c => c.key).sort().join(); + } + } + } + // check tiles to render + for (const tile of this._renderableTiles) { + for (const source in this._coordsDescendingInvStr) { + // rerender if there are more coords to render than in the last rendering + const coords = this._coordsDescendingInvStr[source][tile.tileID.key]; + if (coords && coords !== tile.rttCoords[source]) + tile.rtt = []; + } + } + } + /** + * due that switching textures is relatively slow, the render + * layer-by-layer context is not practicable. To bypass this problem + * this lines of code stack all layers and later render all at once. + * Because of the stylesheet possibility to mixing render-to-texture layers + * and 'live'-layers (f.e. symbols) it is necessary to create more stacks. For example + * a symbol-layer is in between of fill-layers. + * @param layer - the layer to render + * @returns if true layer is rendered to texture, otherwise false + */ + renderLayer(layer) { + if (layer.isHidden(this.painter.transform.zoom)) + return false; + const type = layer.type; + const painter = this.painter; + const isLastLayer = this._renderableLayerIds[this._renderableLayerIds.length - 1] === layer.id; + // remember background, fill, line & raster layer to render into a stack + if (LAYERS[type]) { + // create a new stack if previous layer was not rendered to texture (f.e. symbols) + if (!this._prevType || !LAYERS[this._prevType]) + this._stacks.push([]); + // push current render-to-texture layer to render-stack + this._prevType = type; + this._stacks[this._stacks.length - 1].push(layer.id); + // rendering is done later, all in once + if (!isLastLayer) + return true; + } + // in case a stack is finished render all collected stack-layers into a texture + if (LAYERS[this._prevType] || (LAYERS[type] && isLastLayer)) { + this._prevType = type; + const stack = this._stacks.length - 1, layers = this._stacks[stack] || []; + for (const tile of this._renderableTiles) { + // if render pool is full draw current tiles to screen and free pool + if (this.pool.isFull()) { + drawTerrain(this.painter, this.terrain, this._rttTiles); + this._rttTiles = []; + this.pool.freeAllObjects(); + } + this._rttTiles.push(tile); + // check for cached PoolObject + if (tile.rtt[stack]) { + const obj = this.pool.getObjectForId(tile.rtt[stack].id); + if (obj.stamp === tile.rtt[stack].stamp) { + this.pool.useObject(obj); + continue; + } + } + // get free PoolObject + const obj = this.pool.getOrCreateFreeObject(); + this.pool.useObject(obj); + this.pool.stampObject(obj); + tile.rtt[stack] = { id: obj.id, stamp: obj.stamp }; + // prepare PoolObject for rendering + painter.context.bindFramebuffer.set(obj.fbo.framebuffer); + painter.context.clear({ color: performance$1.aM.transparent, stencil: 0 }); + painter.currentStencilSource = undefined; + for (let l = 0; l < layers.length; l++) { + const layer = painter.style._layers[layers[l]]; + const coords = layer.source ? this._coordsDescendingInv[layer.source][tile.tileID.key] : [tile.tileID]; + painter.context.viewport.set([0, 0, obj.fbo.width, obj.fbo.height]); + painter._renderTileClippingMasks(layer, coords); + painter.renderLayer(painter, painter.style.sourceCaches[layer.source], layer, coords); + if (layer.source) + tile.rttCoords[layer.source] = this._coordsDescendingInvStr[layer.source][tile.tileID.key]; + } + } + drawTerrain(this.painter, this.terrain, this._rttTiles); + this._rttTiles = []; + this.pool.freeAllObjects(); + return LAYERS[type]; + } + return false; + } +} + +const defaultLocale = { + 'AttributionControl.ToggleAttribution': 'Toggle attribution', + 'AttributionControl.MapFeedback': 'Map feedback', + 'FullscreenControl.Enter': 'Enter fullscreen', + 'FullscreenControl.Exit': 'Exit fullscreen', + 'GeolocateControl.FindMyLocation': 'Find my location', + 'GeolocateControl.LocationNotAvailable': 'Location not available', + 'LogoControl.Title': 'MapLibre logo', + 'Map.Title': 'Map', + 'Marker.Title': 'Map marker', + 'NavigationControl.ResetBearing': 'Reset bearing to north', + 'NavigationControl.ZoomIn': 'Zoom in', + 'NavigationControl.ZoomOut': 'Zoom out', + 'Popup.Close': 'Close popup', + 'ScaleControl.Feet': 'ft', + 'ScaleControl.Meters': 'm', + 'ScaleControl.Kilometers': 'km', + 'ScaleControl.Miles': 'mi', + 'ScaleControl.NauticalMiles': 'nm', + 'TerrainControl.Enable': 'Enable terrain', + 'TerrainControl.Disable': 'Disable terrain', + 'CooperativeGesturesHandler.WindowsHelpText': 'Use Ctrl + scroll to zoom the map', + 'CooperativeGesturesHandler.MacHelpText': 'Use ⌘ + scroll to zoom the map', + 'CooperativeGesturesHandler.MobileHelpText': 'Use two fingers to move the map', +}; + +const version$1 = packageJSON.version; +const defaultMinZoom = -2; +const defaultMaxZoom = 22; +// the default values, but also the valid range +const defaultMinPitch = 0; +const defaultMaxPitch = 60; +// use this variable to check maxPitch for validity +const maxPitchThreshold = 85; +const defaultOptions$4 = { + hash: false, + interactive: true, + bearingSnap: 7, + attributionControl: defaultAttributionControlOptions, + maplibreLogo: false, + failIfMajorPerformanceCaveat: false, + preserveDrawingBuffer: false, + refreshExpiredTiles: true, + scrollZoom: true, + minZoom: defaultMinZoom, + maxZoom: defaultMaxZoom, + minPitch: defaultMinPitch, + maxPitch: defaultMaxPitch, + boxZoom: true, + dragRotate: true, + dragPan: true, + keyboard: true, + doubleClickZoom: true, + touchZoomRotate: true, + touchPitch: true, + cooperativeGestures: false, + trackResize: true, + center: [0, 0], + zoom: 0, + bearing: 0, + pitch: 0, + renderWorldCopies: true, + maxTileCacheSize: null, + maxTileCacheZoomLevels: performance$1.a.MAX_TILE_CACHE_ZOOM_LEVELS, + transformRequest: null, + transformCameraUpdate: null, + fadeDuration: 300, + crossSourceCollisions: true, + clickTolerance: 3, + localIdeographFontFamily: 'sans-serif', + pitchWithRotate: true, + validateStyle: true, + /**Because GL MAX_TEXTURE_SIZE is usually at least 4096px. */ + maxCanvasSize: [4096, 4096], + cancelPendingTileRequestsWhileZooming: true +}; +/** + * The `Map` object represents the map on your page. It exposes methods + * and properties that enable you to programmatically change the map, + * and fires events as users interact with it. + * + * You create a `Map` by specifying a `container` and other options, see {@link MapOptions} for the full list. + * Then MapLibre GL JS initializes the map on the page and returns your `Map` object. + * + * @group Main + * + * @example + * ```ts + * let map = new Map({ + * container: 'map', + * center: [-122.420679, 37.772537], + * zoom: 13, + * style: style_object, + * hash: true, + * transformRequest: (url, resourceType)=> { + * if(resourceType === 'Source' && url.startsWith('http://myHost')) { + * return { + * url: url.replace('http', 'https'), + * headers: { 'my-custom-header': true}, + * credentials: 'include' // Include cookies for cross-origin requests + * } + * } + * } + * }); + * ``` + * @see [Display a map](https://maplibre.org/maplibre-gl-js/docs/examples/simple-map/) + */ +let Map$1 = class Map extends Camera { + constructor(options) { + performance$1.bf.mark(performance$1.bg.create); + const resolvedOptions = Object.assign(Object.assign({}, defaultOptions$4), options); + if (resolvedOptions.minZoom != null && resolvedOptions.maxZoom != null && resolvedOptions.minZoom > resolvedOptions.maxZoom) { + throw new Error('maxZoom must be greater than or equal to minZoom'); + } + if (resolvedOptions.minPitch != null && resolvedOptions.maxPitch != null && resolvedOptions.minPitch > resolvedOptions.maxPitch) { + throw new Error('maxPitch must be greater than or equal to minPitch'); + } + if (resolvedOptions.minPitch != null && resolvedOptions.minPitch < defaultMinPitch) { + throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`); + } + if (resolvedOptions.maxPitch != null && resolvedOptions.maxPitch > maxPitchThreshold) { + throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`); + } + const transform = new Transform(resolvedOptions.minZoom, resolvedOptions.maxZoom, resolvedOptions.minPitch, resolvedOptions.maxPitch, resolvedOptions.renderWorldCopies); + super(transform, { bearingSnap: resolvedOptions.bearingSnap }); + this._idleTriggered = false; + this._crossFadingFactor = 1; + this._renderTaskQueue = new TaskQueue(); + this._controls = []; + this._mapId = performance$1.a4(); + this._contextLost = (event) => { + event.preventDefault(); + if (this._frameRequest) { + this._frameRequest.abort(); + this._frameRequest = null; + } + this.fire(new performance$1.k('webglcontextlost', { originalEvent: event })); + }; + this._contextRestored = (event) => { + this._setupPainter(); + this.resize(); + this._update(); + this.fire(new performance$1.k('webglcontextrestored', { originalEvent: event })); + }; + this._onMapScroll = (event) => { + if (event.target !== this._container) + return; + // Revert any scroll which would move the canvas outside of the view + this._container.scrollTop = 0; + this._container.scrollLeft = 0; + return false; + }; + this._onWindowOnline = () => { + this._update(); + }; + this._interactive = resolvedOptions.interactive; + this._maxTileCacheSize = resolvedOptions.maxTileCacheSize; + this._maxTileCacheZoomLevels = resolvedOptions.maxTileCacheZoomLevels; + this._failIfMajorPerformanceCaveat = resolvedOptions.failIfMajorPerformanceCaveat === true; + this._preserveDrawingBuffer = resolvedOptions.preserveDrawingBuffer === true; + this._antialias = resolvedOptions.antialias === true; + this._trackResize = resolvedOptions.trackResize === true; + this._bearingSnap = resolvedOptions.bearingSnap; + this._refreshExpiredTiles = resolvedOptions.refreshExpiredTiles === true; + this._fadeDuration = resolvedOptions.fadeDuration; + this._crossSourceCollisions = resolvedOptions.crossSourceCollisions === true; + this._collectResourceTiming = resolvedOptions.collectResourceTiming === true; + this._locale = Object.assign(Object.assign({}, defaultLocale), resolvedOptions.locale); + this._clickTolerance = resolvedOptions.clickTolerance; + this._overridePixelRatio = resolvedOptions.pixelRatio; + this._maxCanvasSize = resolvedOptions.maxCanvasSize; + this.transformCameraUpdate = resolvedOptions.transformCameraUpdate; + this.cancelPendingTileRequestsWhileZooming = resolvedOptions.cancelPendingTileRequestsWhileZooming === true; + this._imageQueueHandle = ImageRequest.addThrottleControl(() => this.isMoving()); + this._requestManager = new RequestManager(resolvedOptions.transformRequest); + if (typeof resolvedOptions.container === 'string') { + this._container = document.getElementById(resolvedOptions.container); + if (!this._container) { + throw new Error(`Container '${resolvedOptions.container}' not found.`); + } + } + else if (resolvedOptions.container instanceof HTMLElement) { + this._container = resolvedOptions.container; + } + else { + throw new Error('Invalid type: \'container\' must be a String or HTMLElement.'); + } + if (resolvedOptions.maxBounds) { + this.setMaxBounds(resolvedOptions.maxBounds); + } + this._setupContainer(); + this._setupPainter(); + this.on('move', () => this._update(false)) + .on('moveend', () => this._update(false)) + .on('zoom', () => this._update(true)) + .on('terrain', () => { + this.painter.terrainFacilitator.dirty = true; + this._update(true); + }) + .once('idle', () => { this._idleTriggered = true; }); + if (typeof window !== 'undefined') { + addEventListener('online', this._onWindowOnline, false); + let initialResizeEventCaptured = false; + const throttledResizeCallback = throttle((entries) => { + if (this._trackResize && !this._removed) { + this.resize(entries); + this.redraw(); + } + }, 50); + this._resizeObserver = new ResizeObserver((entries) => { + if (!initialResizeEventCaptured) { + initialResizeEventCaptured = true; + return; + } + throttledResizeCallback(entries); + }); + this._resizeObserver.observe(this._container); + } + this.handlers = new HandlerManager(this, resolvedOptions); + const hashName = (typeof resolvedOptions.hash === 'string' && resolvedOptions.hash) || undefined; + this._hash = resolvedOptions.hash && (new Hash(hashName)).addTo(this); + // don't set position from options if set through hash + if (!this._hash || !this._hash._onHashChange()) { + this.jumpTo({ + center: resolvedOptions.center, + zoom: resolvedOptions.zoom, + bearing: resolvedOptions.bearing, + pitch: resolvedOptions.pitch + }); + if (resolvedOptions.bounds) { + this.resize(); + this.fitBounds(resolvedOptions.bounds, performance$1.e({}, resolvedOptions.fitBoundsOptions, { duration: 0 })); + } + } + this.resize(); + this._localIdeographFontFamily = resolvedOptions.localIdeographFontFamily; + this._validateStyle = resolvedOptions.validateStyle; + if (resolvedOptions.style) + this.setStyle(resolvedOptions.style, { localIdeographFontFamily: resolvedOptions.localIdeographFontFamily }); + if (resolvedOptions.attributionControl) + this.addControl(new AttributionControl(typeof resolvedOptions.attributionControl === 'boolean' ? undefined : resolvedOptions.attributionControl)); + if (resolvedOptions.maplibreLogo) + this.addControl(new LogoControl(), resolvedOptions.logoPosition); + this.on('style.load', () => { + if (this.transform.unmodified) { + this.jumpTo(this.style.stylesheet); + } + }); + this.on('data', (event) => { + this._update(event.dataType === 'style'); + this.fire(new performance$1.k(`${event.dataType}data`, event)); + }); + this.on('dataloading', (event) => { + this.fire(new performance$1.k(`${event.dataType}dataloading`, event)); + }); + this.on('dataabort', (event) => { + this.fire(new performance$1.k('sourcedataabort', event)); + }); + } + /** + * @internal + * Returns a unique number for this map instance which is used for the MapLoadEvent + * to make sure we only fire one event per instantiated map object. + * @returns the uniq map ID + */ + _getMapId() { + return this._mapId; + } + /** + * Adds an {@link IControl} to the map, calling `control.onAdd(this)`. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param control - The {@link IControl} to add. + * @param position - position on the map to which the control will be added. + * Valid values are `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. Defaults to `'top-right'`. + * @example + * Add zoom and rotation controls to the map. + * ```ts + * map.addControl(new NavigationControl()); + * ``` + * @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigation/) + */ + addControl(control, position) { + if (position === undefined) { + if (control.getDefaultPosition) { + position = control.getDefaultPosition(); + } + else { + position = 'top-right'; + } + } + if (!control || !control.onAdd) { + return this.fire(new performance$1.j(new Error('Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.'))); + } + const controlElement = control.onAdd(this); + this._controls.push(control); + const positionContainer = this._controlPositions[position]; + if (position.indexOf('bottom') !== -1) { + positionContainer.insertBefore(controlElement, positionContainer.firstChild); + } + else { + positionContainer.appendChild(controlElement); + } + return this; + } + /** + * Removes the control from the map. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param control - The {@link IControl} to remove. + * @example + * ```ts + * // Define a new navigation control. + * let navigation = new NavigationControl(); + * // Add zoom and rotation controls to the map. + * map.addControl(navigation); + * // Remove zoom and rotation controls from the map. + * map.removeControl(navigation); + * ``` + */ + removeControl(control) { + if (!control || !control.onRemove) { + return this.fire(new performance$1.j(new Error('Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.'))); + } + const ci = this._controls.indexOf(control); + if (ci > -1) + this._controls.splice(ci, 1); + control.onRemove(this); + return this; + } + /** + * Checks if a control exists on the map. + * + * @param control - The {@link IControl} to check. + * @returns true if map contains control. + * @example + * ```ts + * // Define a new navigation control. + * let navigation = new NavigationControl(); + * // Add zoom and rotation controls to the map. + * map.addControl(navigation); + * // Check that the navigation control exists on the map. + * map.hasControl(navigation); + * ``` + */ + hasControl(control) { + return this._controls.indexOf(control) > -1; + } + calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo) { + if (altitudeTo == null && this.terrain) { + altitudeTo = this.terrain.getElevationForLngLatZoom(to, this.transform.tileZoom); + } + return super.calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo); + } + /** + * Resizes the map according to the dimensions of its + * `container` element. + * + * Checks if the map container size changed and updates the map if it has changed. + * This method must be called after the map's `container` is resized programmatically + * or when the map is shown after being initially hidden with CSS. + * + * Triggers the following events: `movestart`, `move`, `moveend`, and `resize`. + * + * @param eventData - Additional properties to be passed to `movestart`, `move`, `resize`, and `moveend` + * events that get triggered as a result of resize. This can be useful for differentiating the + * source of an event (for example, user-initiated or programmatically-triggered events). + * @example + * Resize the map when the map container is shown after being initially hidden with CSS. + * ```ts + * let mapDiv = document.getElementById('map'); + * if (mapDiv.style.visibility === true) map.resize(); + * ``` + */ + resize(eventData) { + var _a; + const dimensions = this._containerDimensions(); + const width = dimensions[0]; + const height = dimensions[1]; + const clampedPixelRatio = this._getClampedPixelRatio(width, height); + this._resizeCanvas(width, height, clampedPixelRatio); + this.painter.resize(width, height, clampedPixelRatio); + // check if we've reached GL limits, in that case further clamps pixelRatio + if (this.painter.overLimit()) { + const gl = this.painter.context.gl; + // store updated _maxCanvasSize value + this._maxCanvasSize = [gl.drawingBufferWidth, gl.drawingBufferHeight]; + const clampedPixelRatio = this._getClampedPixelRatio(width, height); + this._resizeCanvas(width, height, clampedPixelRatio); + this.painter.resize(width, height, clampedPixelRatio); + } + this.transform.resize(width, height); + (_a = this._requestedCameraState) === null || _a === void 0 ? void 0 : _a.resize(width, height); + const fireMoving = !this._moving; + if (fireMoving) { + this.stop(); + this.fire(new performance$1.k('movestart', eventData)) + .fire(new performance$1.k('move', eventData)); + } + this.fire(new performance$1.k('resize', eventData)); + if (fireMoving) + this.fire(new performance$1.k('moveend', eventData)); + return this; + } + /** + * @internal + * Return the map's pixel ratio eventually scaled down to respect maxCanvasSize. + * Internally you should use this and not getPixelRatio(). + */ + _getClampedPixelRatio(width, height) { + const { 0: maxCanvasWidth, 1: maxCanvasHeight } = this._maxCanvasSize; + const pixelRatio = this.getPixelRatio(); + const canvasWidth = width * pixelRatio; + const canvasHeight = height * pixelRatio; + const widthScaleFactor = canvasWidth > maxCanvasWidth ? (maxCanvasWidth / canvasWidth) : 1; + const heightScaleFactor = canvasHeight > maxCanvasHeight ? (maxCanvasHeight / canvasHeight) : 1; + return Math.min(widthScaleFactor, heightScaleFactor) * pixelRatio; + } + /** + * Returns the map's pixel ratio. + * Note that the pixel ratio actually applied may be lower to respect maxCanvasSize. + * @returns The pixel ratio. + */ + getPixelRatio() { + var _a; + return (_a = this._overridePixelRatio) !== null && _a !== void 0 ? _a : devicePixelRatio; + } + /** + * Sets the map's pixel ratio. This allows to override `devicePixelRatio`. + * After this call, the canvas' `width` attribute will be `container.clientWidth * pixelRatio` + * and its height attribute will be `container.clientHeight * pixelRatio`. + * Set this to null to disable `devicePixelRatio` override. + * Note that the pixel ratio actually applied may be lower to respect maxCanvasSize. + * @param pixelRatio - The pixel ratio. + */ + setPixelRatio(pixelRatio) { + this._overridePixelRatio = pixelRatio; + this.resize(); + } + /** + * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not + * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region. + * @returns The geographical bounds of the map as {@link LngLatBounds}. + * @example + * ```ts + * let bounds = map.getBounds(); + * ``` + */ + getBounds() { + return this.transform.getBounds(); + } + /** + * Returns the maximum geographical bounds the map is constrained to, or `null` if none set. + * @returns The map object. + * @example + * ```ts + * let maxBounds = map.getMaxBounds(); + * ``` + */ + getMaxBounds() { + return this.transform.getMaxBounds(); + } + /** + * Sets or clears the map's geographical bounds. + * + * Pan and zoom operations are constrained within these bounds. + * If a pan or zoom is performed that would + * display regions outside these bounds, the map will + * instead display a position and zoom level + * as close as possible to the operation's request while still + * remaining within the bounds. + * + * @param bounds - The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds. + * @example + * Define bounds that conform to the `LngLatBoundsLike` object as set the max bounds. + * ```ts + * let bounds = [ + * [-74.04728, 40.68392], // [west, south] + * [-73.91058, 40.87764] // [east, north] + * ]; + * map.setMaxBounds(bounds); + * ``` + */ + setMaxBounds(bounds) { + this.transform.setMaxBounds(LngLatBounds.convert(bounds)); + return this._update(); + } + /** + * Sets or clears the map's minimum zoom level. + * If the map's current zoom level is lower than the new minimum, + * the map will zoom to the new minimum. + * + * It is not always possible to zoom out and reach the set `minZoom`. + * Other factors such as map height may restrict zooming. For example, + * if the map is 512px tall it will not be possible to zoom below zoom 0 + * no matter what the `minZoom` is set to. + * + * A {@link ErrorEvent} event will be fired if minZoom is out of bounds. + * + * @param minZoom - The minimum zoom level to set (-2 - 24). + * If `null` or `undefined` is provided, the function removes the current minimum zoom (i.e. sets it to -2). + * @example + * ```ts + * map.setMinZoom(12.25); + * ``` + */ + setMinZoom(minZoom) { + minZoom = minZoom === null || minZoom === undefined ? defaultMinZoom : minZoom; + if (minZoom >= defaultMinZoom && minZoom <= this.transform.maxZoom) { + this.transform.minZoom = minZoom; + this._update(); + if (this.getZoom() < minZoom) + this.setZoom(minZoom); + return this; + } + else + throw new Error(`minZoom must be between ${defaultMinZoom} and the current maxZoom, inclusive`); + } + /** + * Returns the map's minimum allowable zoom level. + * + * @returns minZoom + * @example + * ```ts + * let minZoom = map.getMinZoom(); + * ``` + */ + getMinZoom() { return this.transform.minZoom; } + /** + * Sets or clears the map's maximum zoom level. + * If the map's current zoom level is higher than the new maximum, + * the map will zoom to the new maximum. + * + * A {@link ErrorEvent} event will be fired if minZoom is out of bounds. + * + * @param maxZoom - The maximum zoom level to set. + * If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22). + * @example + * ```ts + * map.setMaxZoom(18.75); + * ``` + */ + setMaxZoom(maxZoom) { + maxZoom = maxZoom === null || maxZoom === undefined ? defaultMaxZoom : maxZoom; + if (maxZoom >= this.transform.minZoom) { + this.transform.maxZoom = maxZoom; + this._update(); + if (this.getZoom() > maxZoom) + this.setZoom(maxZoom); + return this; + } + else + throw new Error('maxZoom must be greater than the current minZoom'); + } + /** + * Returns the map's maximum allowable zoom level. + * + * @returns The maxZoom + * @example + * ```ts + * let maxZoom = map.getMaxZoom(); + * ``` + */ + getMaxZoom() { return this.transform.maxZoom; } + /** + * Sets or clears the map's minimum pitch. + * If the map's current pitch is lower than the new minimum, + * the map will pitch to the new minimum. + * + * A {@link ErrorEvent} event will be fired if minPitch is out of bounds. + * + * @param minPitch - The minimum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. + * If `null` or `undefined` is provided, the function removes the current minimum pitch (i.e. sets it to 0). + */ + setMinPitch(minPitch) { + minPitch = minPitch === null || minPitch === undefined ? defaultMinPitch : minPitch; + if (minPitch < defaultMinPitch) { + throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`); + } + if (minPitch >= defaultMinPitch && minPitch <= this.transform.maxPitch) { + this.transform.minPitch = minPitch; + this._update(); + if (this.getPitch() < minPitch) + this.setPitch(minPitch); + return this; + } + else + throw new Error(`minPitch must be between ${defaultMinPitch} and the current maxPitch, inclusive`); + } + /** + * Returns the map's minimum allowable pitch. + * + * @returns The minPitch + */ + getMinPitch() { return this.transform.minPitch; } + /** + * Sets or clears the map's maximum pitch. + * If the map's current pitch is higher than the new maximum, + * the map will pitch to the new maximum. + * + * A {@link ErrorEvent} event will be fired if maxPitch is out of bounds. + * + * @param maxPitch - The maximum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. + * If `null` or `undefined` is provided, the function removes the current maximum pitch (sets it to 60). + */ + setMaxPitch(maxPitch) { + maxPitch = maxPitch === null || maxPitch === undefined ? defaultMaxPitch : maxPitch; + if (maxPitch > maxPitchThreshold) { + throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`); + } + if (maxPitch >= this.transform.minPitch) { + this.transform.maxPitch = maxPitch; + this._update(); + if (this.getPitch() > maxPitch) + this.setPitch(maxPitch); + return this; + } + else + throw new Error('maxPitch must be greater than the current minPitch'); + } + /** + * Returns the map's maximum allowable pitch. + * + * @returns The maxPitch + */ + getMaxPitch() { return this.transform.maxPitch; } + /** + * 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`: + * + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * @returns The renderWorldCopies + * @example + * ```ts + * let worldCopiesRendered = map.getRenderWorldCopies(); + * ``` + * @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/) + */ + getRenderWorldCopies() { return this.transform.renderWorldCopies; } + /** + * Sets the state of `renderWorldCopies`. + * + * @param renderWorldCopies - If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`: + * + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * + * `undefined` is treated as `true`, `null` is treated as `false`. + * @example + * ```ts + * map.setRenderWorldCopies(true); + * ``` + * @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/) + */ + setRenderWorldCopies(renderWorldCopies) { + this.transform.renderWorldCopies = renderWorldCopies; + return this._update(); + } + /** + * Returns a [Point](https://github.com/mapbox/point-geometry) representing pixel coordinates, relative to the map's `container`, + * that correspond to the specified geographical location. + * + * @param lnglat - The geographical location to project. + * @returns The [Point](https://github.com/mapbox/point-geometry) corresponding to `lnglat`, relative to the map's `container`. + * @example + * ```ts + * let coordinate = [-122.420679, 37.772537]; + * let point = map.project(coordinate); + * ``` + */ + project(lnglat) { + return this.transform.locationPoint(performance$1.N.convert(lnglat), this.style && this.terrain); + } + /** + * Returns a {@link LngLat} representing geographical coordinates that correspond + * to the specified pixel coordinates. + * + * @param point - The pixel coordinates to unproject. + * @returns The {@link LngLat} corresponding to `point`. + * @example + * ```ts + * map.on('click', (e) => { + * // When the map is clicked, get the geographic coordinate. + * let coordinate = map.unproject(e.point); + * }); + * ``` + */ + unproject(point) { + return this.transform.pointLocation(performance$1.P.convert(point), this.terrain); + } + /** + * Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture. + * @returns true if the map is moving. + * @example + * ```ts + * let isMoving = map.isMoving(); + * ``` + */ + isMoving() { + var _a; + return this._moving || ((_a = this.handlers) === null || _a === void 0 ? void 0 : _a.isMoving()); + } + /** + * Returns true if the map is zooming due to a camera animation or user gesture. + * @returns true if the map is zooming. + * @example + * ```ts + * let isZooming = map.isZooming(); + * ``` + */ + isZooming() { + var _a; + return this._zooming || ((_a = this.handlers) === null || _a === void 0 ? void 0 : _a.isZooming()); + } + /** + * Returns true if the map is rotating due to a camera animation or user gesture. + * @returns true if the map is rotating. + * @example + * ```ts + * map.isRotating(); + * ``` + */ + isRotating() { + var _a; + return this._rotating || ((_a = this.handlers) === null || _a === void 0 ? void 0 : _a.isRotating()); + } + _createDelegatedListener(type, layerIds, listener) { + if (type === 'mouseenter' || type === 'mouseover') { + let mousein = false; + const mousemove = (e) => { + const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId)); + const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, { layers: existingLayers }) : []; + if (!features.length) { + mousein = false; + } + else if (!mousein) { + mousein = true; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent, { features })); + } + }; + const mouseout = () => { + mousein = false; + }; + return { layers: layerIds, listener, delegates: { mousemove, mouseout } }; + } + else if (type === 'mouseleave' || type === 'mouseout') { + let mousein = false; + const mousemove = (e) => { + const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId)); + const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, { layers: existingLayers }) : []; + if (features.length) { + mousein = true; + } + else if (mousein) { + mousein = false; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent)); + } + }; + const mouseout = (e) => { + if (mousein) { + mousein = false; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent)); + } + }; + return { layers: layerIds, listener, delegates: { mousemove, mouseout } }; + } + else { + const delegate = (e) => { + const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId)); + const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, { layers: existingLayers }) : []; + if (features.length) { + // Here we need to mutate the original event, so that preventDefault works as expected. + e.features = features; + listener.call(this, e); + delete e.features; + } + }; + return { layers: layerIds, listener, delegates: { [type]: delegate } }; + } + } + _saveDelegatedListener(type, delegatedListener) { + this._delegatedListeners = this._delegatedListeners || {}; + this._delegatedListeners[type] = this._delegatedListeners[type] || []; + this._delegatedListeners[type].push(delegatedListener); + } + _removeDelegatedListener(type, layerIds, listener) { + if (!this._delegatedListeners || !this._delegatedListeners[type]) { + return; + } + const listeners = this._delegatedListeners[type]; + for (let i = 0; i < listeners.length; i++) { + const delegatedListener = listeners[i]; + if (delegatedListener.listener === listener && + delegatedListener.layers.length === layerIds.length && + delegatedListener.layers.every((layerId) => layerIds.includes(layerId))) { + for (const event in delegatedListener.delegates) { + this.off(event, delegatedListener.delegates[event]); + } + listeners.splice(i, 1); + return; + } + } + } + on(type, layerIdsOrListener, listener) { + if (listener === undefined) { + return super.on(type, layerIdsOrListener); + } + const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener; + const delegatedListener = this._createDelegatedListener(type, layerIds, listener); + this._saveDelegatedListener(type, delegatedListener); + for (const event in delegatedListener.delegates) { + this.on(event, delegatedListener.delegates[event]); + } + return this; + } + once(type, layerIdsOrListener, listener) { + if (listener === undefined) { + return super.once(type, layerIdsOrListener); + } + const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener; + const delegatedListener = this._createDelegatedListener(type, layerIds, listener); + for (const key in delegatedListener.delegates) { + const delegate = delegatedListener.delegates[key]; + delegatedListener.delegates[key] = (...args) => { + this._removeDelegatedListener(type, layerIds, listener); + delegate(...args); + }; + } + this._saveDelegatedListener(type, delegatedListener); + for (const event in delegatedListener.delegates) { + this.once(event, delegatedListener.delegates[event]); + } + return this; + } + off(type, layerIdsOrListener, listener) { + if (listener === undefined) { + return super.off(type, layerIdsOrListener); + } + const layerIds = typeof layerIdsOrListener === 'string' ? [layerIdsOrListener] : layerIdsOrListener; + this._removeDelegatedListener(type, layerIds, listener); + return this; + } + /** + * Returns an array of MapGeoJSONFeature objects + * representing visible features that satisfy the query parameters. + * + * @param geometryOrOptions - (optional) The geometry of the query region: + * either a single point or southwest and northeast points describing a bounding box. + * Omitting this parameter (i.e. calling {@link Map#queryRenderedFeatures} with zero arguments, + * or with only a `options` argument) is equivalent to passing a bounding box encompassing the entire + * map viewport. + * The geometryOrOptions can receive a {@link QueryRenderedFeaturesOptions} only to support a situation where the function receives only one parameter which is the options parameter. + * @param options - (optional) Options object. + * + * @returns An array of MapGeoJSONFeature objects. + * + * The `properties` value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only + * string and numeric property values are supported (i.e. `null`, `Array`, and `Object` values are not supported). + * + * Each feature includes top-level `layer`, `source`, and `sourceLayer` properties. The `layer` property is an object + * representing the style layer to which the feature belongs. Layout and paint properties in this object contain values + * which are fully evaluated for the given zoom level and feature. + * + * Only features that are currently rendered are included. Some features will **not** be included, like: + * + * - Features from layers whose `visibility` property is `"none"`. + * - Features from layers whose zoom range excludes the current zoom level. + * - Symbol features that have been hidden due to text or icon collision. + * + * Features from all other layers are included, including features that may have no visible + * contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to + * 0. + * + * The topmost rendered feature appears first in the returned array, and subsequent features are sorted by + * descending z-order. Features that are rendered multiple times (due to wrapping across the antemeridian at low + * zoom levels) are returned only once (though subject to the following caveat). + * + * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature + * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple + * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. + * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding + * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile + * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple + * tiles due to tile buffering. + * + * @example + * Find all features at a point + * ```ts + * let features = map.queryRenderedFeatures( + * [20, 35], + * { layers: ['my-layer-name'] } + * ); + * ``` + * + * @example + * Find all features within a static bounding box + * ```ts + * let features = map.queryRenderedFeatures( + * [[10, 20], [30, 50]], + * { layers: ['my-layer-name'] } + * ); + * ``` + * + * @example + * Find all features within a bounding box around a point + * ```ts + * let width = 10; + * let height = 20; + * let features = map.queryRenderedFeatures([ + * [point.x - width / 2, point.y - height / 2], + * [point.x + width / 2, point.y + height / 2] + * ], { layers: ['my-layer-name'] }); + * ``` + * + * @example + * Query all rendered features from a single layer + * ```ts + * let features = map.queryRenderedFeatures({ layers: ['my-layer-name'] }); + * ``` + * @see [Get features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/queryrenderedfeatures/) + */ + queryRenderedFeatures(geometryOrOptions, options) { + if (!this.style) { + return []; + } + let queryGeometry; + const isGeometry = geometryOrOptions instanceof performance$1.P || Array.isArray(geometryOrOptions); + const geometry = isGeometry ? geometryOrOptions : [[0, 0], [this.transform.width, this.transform.height]]; + options = options || (isGeometry ? {} : geometryOrOptions) || {}; + if (geometry instanceof performance$1.P || typeof geometry[0] === 'number') { + queryGeometry = [performance$1.P.convert(geometry)]; + } + else { + const tl = performance$1.P.convert(geometry[0]); + const br = performance$1.P.convert(geometry[1]); + queryGeometry = [tl, new performance$1.P(br.x, tl.y), br, new performance$1.P(tl.x, br.y), tl]; + } + return this.style.queryRenderedFeatures(queryGeometry, options, this.transform); + } + /** + * Returns an array of MapGeoJSONFeature objects + * representing features within the specified vector tile or GeoJSON source that satisfy the query parameters. + * + * @param sourceId - The ID of the vector tile or GeoJSON source to query. + * @param parameters - The options object. + * @returns An array of MapGeoJSONFeature objects. + * + * In contrast to {@link Map#queryRenderedFeatures}, this function returns all features matching the query parameters, + * whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded + * vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently + * visible viewport. + * + * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature + * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple + * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. + * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding + * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile + * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple + * tiles due to tile buffering. + * + * @example + * Find all features in one source layer in a vector source + * ```ts + * let features = map.querySourceFeatures('your-source-id', { + * sourceLayer: 'your-source-layer' + * }); + * ``` + * + */ + querySourceFeatures(sourceId, parameters) { + return this.style.querySourceFeatures(sourceId, parameters); + } + /** + * Updates the map's MapLibre style object with a new value. + * + * 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 + * against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites + * (images used for icons and patterns) and glyphs (fonts for label text) **cannot** be diffed. If the sprites or fonts used in the current + * style and the given style are different in any way, the map renderer will force a full update, removing the current style and building + * the given one from scratch. + * + * + * @param style - A JSON object conforming to the schema described in the + * [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/), or a URL to such JSON. + * @param options - The options object. + * + * @example + * ```ts + * map.setStyle("https://demotiles.maplibre.org/style.json"); + * + * map.setStyle('https://demotiles.maplibre.org/style.json', { + * transformStyle: (previousStyle, nextStyle) => ({ + * ...nextStyle, + * sources: { + * ...nextStyle.sources, + * // copy a source from previous style + * 'osm': previousStyle.sources.osm + * }, + * layers: [ + * // background layer + * nextStyle.layers[0], + * // copy a layer from previous style + * previousStyle.layers[0], + * // other layers from the next style + * ...nextStyle.layers.slice(1).map(layer => { + * // hide the layers we don't need from demotiles style + * if (layer.id.startsWith('geolines')) { + * layer.layout = {...layer.layout || {}, visibility: 'none'}; + * // filter out US polygons + * } else if (layer.id.startsWith('coastline') || layer.id.startsWith('countries')) { + * layer.filter = ['!=', ['get', 'ADM0_A3'], 'USA']; + * } + * return layer; + * }) + * ] + * }) + * }); + * ``` + */ + setStyle(style, options) { + options = performance$1.e({}, { + localIdeographFontFamily: this._localIdeographFontFamily, + validate: this._validateStyle + }, options); + if ((options.diff !== false && options.localIdeographFontFamily === this._localIdeographFontFamily) && this.style && style) { + this._diffStyle(style, options); + return this; + } + else { + this._localIdeographFontFamily = options.localIdeographFontFamily; + return this._updateStyle(style, options); + } + } + /** + * Updates the requestManager's transform request with a new function + * + * @param transformRequest - 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. + * Expected to return an object with a `url` property and optionally `headers` and `credentials` properties + * + * @example + * ```ts + * map.setTransformRequest((url: string, resourceType: string) => {}); + * ``` + */ + setTransformRequest(transformRequest) { + this._requestManager.setTransformRequest(transformRequest); + return this; + } + _getUIString(key) { + const str = this._locale[key]; + if (str == null) { + throw new Error(`Missing UI string '${key}'`); + } + return str; + } + _updateStyle(style, options) { + // transformStyle relies on having previous style serialized, if it is not loaded yet, delay _updateStyle until previous style is loaded + if (options.transformStyle && this.style && !this.style._loaded) { + this.style.once('style.load', () => this._updateStyle(style, options)); + return; + } + const previousStyle = this.style && options.transformStyle ? this.style.serialize() : undefined; + if (this.style) { + this.style.setEventedParent(null); + // Only release workers when map is getting disposed + this.style._remove(!style); + } + if (!style) { + delete this.style; + return this; + } + else { + this.style = new Style(this, options || {}); + } + this.style.setEventedParent(this, { style: this.style }); + if (typeof style === 'string') { + this.style.loadURL(style, options, previousStyle); + } + else { + this.style.loadJSON(style, options, previousStyle); + } + return this; + } + _lazyInitEmptyStyle() { + if (!this.style) { + this.style = new Style(this, {}); + this.style.setEventedParent(this, { style: this.style }); + this.style.loadEmpty(); + } + } + _diffStyle(style, options) { + if (typeof style === 'string') { + const url = style; + const request = this._requestManager.transformRequest(url, "Style" /* ResourceType.Style */); + performance$1.h(request, new AbortController()).then((response) => { + this._updateDiff(response.data, options); + }).catch((error) => { + if (error) { + this.fire(new performance$1.j(error)); + } + }); + } + else if (typeof style === 'object') { + this._updateDiff(style, options); + } + } + _updateDiff(style, options) { + try { + if (this.style.setState(style, options)) { + this._update(true); + } + } + catch (e) { + performance$1.w(`Unable to perform style diff: ${e.message || e.error || e}. Rebuilding the style from scratch.`); + this._updateStyle(style, options); + } + } + /** + * Returns the map's MapLibre style object, a JSON object which can be used to recreate the map's style. + * + * @returns The map's style JSON object. + * + * @example + * ```ts + * let styleJson = map.getStyle(); + * ``` + * + */ + getStyle() { + if (this.style) { + return this.style.serialize(); + } + } + /** + * Returns a Boolean indicating whether the map's style is fully loaded. + * + * @returns A Boolean indicating whether the style is fully loaded. + * + * @example + * ```ts + * let styleLoadStatus = map.isStyleLoaded(); + * ``` + */ + isStyleLoaded() { + if (!this.style) + return performance$1.w('There is no style added to the map.'); + return this.style.loaded(); + } + /** + * Adds a source to the map's style. + * + * Events triggered: + * + * Triggers the `source.add` event. + * + * @param id - The ID of the source to add. Must not conflict with existing sources. + * @param source - The source object, conforming to the + * MapLibre Style Specification's [source definition](https://maplibre.org/maplibre-style-spec/sources) or + * {@link CanvasSourceSpecification}. + * @example + * ```ts + * map.addSource('my-data', { + * type: 'vector', + * url: 'https://demotiles.maplibre.org/tiles/tiles.json' + * }); + * ``` + * @example + * ```ts + * map.addSource('my-data', { + * "type": "geojson", + * "data": { + * "type": "Feature", + * "geometry": { + * "type": "Point", + * "coordinates": [-77.0323, 38.9131] + * }, + * "properties": { + * "title": "Mapbox DC", + * "marker-symbol": "monument" + * } + * } + * }); + * ``` + * @see GeoJSON source: [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/live-geojson/) + */ + addSource(id, source) { + this._lazyInitEmptyStyle(); + this.style.addSource(id, source); + return this._update(true); + } + /** + * Returns a Boolean indicating whether the source is loaded. Returns `true` if the source with + * the given ID in the map's style has no outstanding network requests, otherwise `false`. + * + * A {@link ErrorEvent} event will be fired if there is no source wit the specified ID. + * + * @param id - The ID of the source to be checked. + * @returns A Boolean indicating whether the source is loaded. + * @example + * ```ts + * let sourceLoaded = map.isSourceLoaded('bathymetry-data'); + * ``` + */ + isSourceLoaded(id) { + const source = this.style && this.style.sourceCaches[id]; + if (source === undefined) { + this.fire(new performance$1.j(new Error(`There is no source with ID '${id}'`))); + return; + } + return source.loaded(); + } + /** + * Loads a 3D terrain mesh, based on a "raster-dem" source. + * + * Triggers the `terrain` event. + * + * @param options - Options object. + * @example + * ```ts + * map.setTerrain({ source: 'terrain' }); + * ``` + */ + setTerrain(options) { + this.style._checkLoaded(); + // clear event handlers + if (this._terrainDataCallback) + this.style.off('data', this._terrainDataCallback); + if (!options) { + // remove terrain + if (this.terrain) + this.terrain.sourceCache.destruct(); + this.terrain = null; + if (this.painter.renderToTexture) + this.painter.renderToTexture.destruct(); + this.painter.renderToTexture = null; + this.transform.minElevationForCurrentTile = 0; + this.transform.elevation = 0; + } + else { + // add terrain + const sourceCache = this.style.sourceCaches[options.source]; + if (!sourceCache) + throw new Error(`cannot load terrain, because there exists no source with ID: ${options.source}`); + // Update terrain tiles when adding new terrain + if (this.terrain === null) + sourceCache.reload(); + // Warn once if user is using the same source for hillshade and terrain + for (const index in this.style._layers) { + const thisLayer = this.style._layers[index]; + if (thisLayer.type === 'hillshade' && thisLayer.source === options.source) { + performance$1.w('You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.'); + } + } + this.terrain = new Terrain(this.painter, sourceCache, options); + this.painter.renderToTexture = new RenderToTexture(this.painter, this.terrain); + this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + this._terrainDataCallback = e => { + if (e.dataType === 'style') { + this.terrain.sourceCache.freeRtt(); + } + else if (e.dataType === 'source' && e.tile) { + if (e.sourceId === options.source && !this._elevationFreeze) { + this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + } + this.terrain.sourceCache.freeRtt(e.tile.tileID); + } + }; + this.style.on('data', this._terrainDataCallback); + } + this.fire(new performance$1.k('terrain', { terrain: options })); + return this; + } + /** + * Get the terrain-options if terrain is loaded + * @returns the TerrainSpecification passed to setTerrain + * @example + * ```ts + * map.getTerrain(); // { source: 'terrain' }; + * ``` + */ + getTerrain() { + var _a, _b; + return (_b = (_a = this.terrain) === null || _a === void 0 ? void 0 : _a.options) !== null && _b !== void 0 ? _b : null; + } + /** + * Returns a Boolean indicating whether all tiles in the viewport from all sources on + * the style are loaded. + * + * @returns A Boolean indicating whether all tiles are loaded. + * @example + * ```ts + * let tilesLoaded = map.areTilesLoaded(); + * ``` + */ + areTilesLoaded() { + const sources = this.style && this.style.sourceCaches; + for (const id in sources) { + const source = sources[id]; + const tiles = source._tiles; + for (const t in tiles) { + const tile = tiles[t]; + if (!(tile.state === 'loaded' || tile.state === 'errored')) + return false; + } + } + return true; + } + /** + * Removes a source from the map's style. + * + * @param id - The ID of the source to remove. + * @example + * ```ts + * map.removeSource('bathymetry-data'); + * ``` + */ + removeSource(id) { + this.style.removeSource(id); + return this._update(true); + } + /** + * Returns the source with the specified ID in the map's style. + * + * This method is often used to update a source using the instance members for the relevant + * source type as defined in classes that derive from {@link Source}. + * For example, setting the `data` for a GeoJSON source or updating the `url` and `coordinates` + * of an image source. + * + * @param id - The ID of the source to get. + * @returns The style source with the specified ID or `undefined` if the ID + * corresponds to no existing sources. + * The shape of the object varies by source type. + * A list of options for each source type is available on the MapLibre Style Specification's + * [Sources](https://maplibre.org/maplibre-style-spec/sources/) page. + * @example + * ```ts + * let sourceObject = map.getSource('points'); + * ``` + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + * @see [Animate a point](https://maplibre.org/maplibre-gl-js/docs/examples/animate-point-along-line/) + * @see [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/live-geojson/) + */ + getSource(id) { + return this.style.getSource(id); + } + /** + * Add an image to the style. This image can be displayed on the map like any other icon in the style's + * sprite using the image's ID with + * [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image), + * [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern), + * [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern), + * or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern). + * + * A {@link ErrorEvent} event will be fired if the image parameter is invalid or there is not enough space in the sprite to add this image. + * + * @param id - The ID of the image. + * @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data` + * properties with the same format as `ImageData`. + * @param options - Options object. + * @example + * ```ts + * // If the style's sprite does not already contain an image with ID 'cat', + * // add the image 'cat-icon.png' to the style's sprite with the ID 'cat'. + * const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png'); + * if (!map.hasImage('cat')) map.addImage('cat', image.data); + * + * // Add a stretchable image that can be used with `icon-text-fit` + * // In this example, the image is 600px wide by 400px high. + * const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png'); + * if (map.hasImage('border-image')) return; + * map.addImage('border-image', image.data, { + * content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border + * stretchX: [[16, 584]], // stretch everything horizontally except the 16px border + * stretchY: [[16, 384]], // stretch everything vertically except the 16px border + * }); + * ``` + * @see Use `HTMLImageElement`: [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image/) + * @see Use `ImageData`: [Add a generated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-generated/) + */ + addImage(id, image, options = {}) { + const { pixelRatio = 1, sdf = false, stretchX, stretchY, content, textFitWidth, textFitHeight } = options; + this._lazyInitEmptyStyle(); + const version = 0; + if (image instanceof HTMLImageElement || performance$1.b(image)) { + const { width, height, data } = browser.getImageData(image); + this.style.addImage(id, { data: new performance$1.R({ width, height }, data), pixelRatio, stretchX, stretchY, content, textFitWidth, textFitHeight, sdf, version }); + } + else if (image.width === undefined || image.height === undefined) { + return this.fire(new performance$1.j(new Error('Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' + + 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`'))); + } + else { + const { width, height, data } = image; + const userImage = image; + this.style.addImage(id, { + data: new performance$1.R({ width, height }, new Uint8Array(data)), + pixelRatio, + stretchX, + stretchY, + content, + textFitWidth, + textFitHeight, + sdf, + version, + userImage + }); + if (userImage.onAdd) { + userImage.onAdd(this, id); + } + return this; + } + } + /** + * Update an existing image in a style. This image can be displayed on the map like any other icon in the style's + * sprite using the image's ID with + * [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image), + * [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern), + * [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern), + * or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern). + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param id - The ID of the image. + * @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data` + * properties with the same format as `ImageData`. + * @example + * ```ts + * // If an image with the ID 'cat' already exists in the style's sprite, + * // replace that image with a new image, 'other-cat-icon.png'. + * if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png'); + * ``` + */ + updateImage(id, image) { + const existingImage = this.style.getImage(id); + if (!existingImage) { + return this.fire(new performance$1.j(new Error('The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.'))); + } + const imageData = (image instanceof HTMLImageElement || performance$1.b(image)) ? + browser.getImageData(image) : + image; + const { width, height, data } = imageData; + if (width === undefined || height === undefined) { + return this.fire(new performance$1.j(new Error('Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' + + 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`'))); + } + if (width !== existingImage.data.width || height !== existingImage.data.height) { + return this.fire(new performance$1.j(new Error('The width and height of the updated image must be that same as the previous version of the image'))); + } + const copy = !(image instanceof HTMLImageElement || performance$1.b(image)); + existingImage.data.replace(data, copy); + this.style.updateImage(id, existingImage); + return this; + } + /** + * Returns an image, specified by ID, currently available in the map. + * This includes both images from the style's original sprite + * and any images that have been added at runtime using {@link Map#addImage}. + * + * @param id - The ID of the image. + * @returns An image in the map with the specified ID. + * + * @example + * ```ts + * let coffeeShopIcon = map.getImage("coffee_cup"); + * ``` + */ + getImage(id) { + return this.style.getImage(id); + } + /** + * Check whether or not an image with a specific ID exists in the style. This checks both images + * in the style's original sprite and any images + * that have been added at runtime using {@link Map#addImage}. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param id - The ID of the image. + * + * @returns A Boolean indicating whether the image exists. + * @example + * Check if an image with the ID 'cat' exists in the style's sprite. + * ```ts + * let catIconExists = map.hasImage('cat'); + * ``` + */ + hasImage(id) { + if (!id) { + this.fire(new performance$1.j(new Error('Missing required image id'))); + return false; + } + return !!this.style.getImage(id); + } + /** + * Remove an image from a style. This can be an image from the style's original + * sprite or any images + * that have been added at runtime using {@link Map#addImage}. + * + * @param id - The ID of the image. + * + * @example + * ```ts + * // If an image with the ID 'cat' exists in + * // the style's sprite, remove it. + * if (map.hasImage('cat')) map.removeImage('cat'); + * ``` + */ + removeImage(id) { + this.style.removeImage(id); + } + /** + * Load an image from an external URL to be used with {@link Map#addImage}. External + * domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS). + * + * @param url - The URL of the image file. Image file must be in png, webp, or jpg format. + * @returns a promise that is resolved when the image is loaded + * + * @example + * Load an image from an external URL. + * ```ts + * const response = await map.loadImage('https://picsum.photos/50/50'); + * // Add the loaded image to the style's sprite with the ID 'photo'. + * map.addImage('photo', response.data); + * ``` + * @see [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image/) + */ + loadImage(url) { + return ImageRequest.getImage(this._requestManager.transformRequest(url, "Image" /* ResourceType.Image */), new AbortController()); + } + /** + * Returns an Array of strings containing the IDs of all images currently available in the map. + * This includes both images from the style's original sprite + * and any images that have been added at runtime using {@link Map#addImage}. + * + * @returns An Array of strings containing the names of all sprites/images currently available in the map. + * + * @example + * ```ts + * let allImages = map.listImages(); + * ``` + */ + listImages() { + return this.style.listImages(); + } + /** + * Adds a [MapLibre style layer](https://maplibre.org/maplibre-style-spec/layers) + * to the map's style. + * + * A layer defines how data from a specified source will be styled. Read more about layer types + * and available paint and layout properties in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/layers). + * + * @param layer - The layer to add, + * conforming to either the MapLibre Style Specification's [layer definition](https://maplibre.org/maplibre-style-spec/layers) or, + * less commonly, the {@link CustomLayerInterface} specification. Can also be a layer definition with an embedded source definition. + * The MapLibre Style Specification's layer definition is appropriate for most layers. + * + * @param beforeId - The ID of an existing layer to insert the new layer before, + * resulting in the new layer appearing visually beneath the existing layer. + * If this argument is not specified, the layer will be appended to the end of the layers array + * and appear visually above all other layers. + * + * @example + * Add a circle layer with a vector source + * ```ts + * map.addLayer({ + * id: 'points-of-interest', + * source: { + * type: 'vector', + * url: 'https://demotiles.maplibre.org/tiles/tiles.json' + * }, + * 'source-layer': 'poi_label', + * type: 'circle', + * paint: { + * // MapLibre Style Specification paint properties + * }, + * layout: { + * // MapLibre Style Specification layout properties + * } + * }); + * ``` + * + * @example + * Define a source before using it to create a new layer + * ```ts + * map.addSource('state-data', { + * type: 'geojson', + * data: 'path/to/data.geojson' + * }); + * + * map.addLayer({ + * id: 'states', + * // References the GeoJSON source defined above + * // and does not require a `source-layer` + * source: 'state-data', + * type: 'symbol', + * layout: { + * // Set the label content to the + * // feature's `name` property + * text-field: ['get', 'name'] + * } + * }); + * ``` + * + * @example + * Add a new symbol layer before an existing layer + * ```ts + * map.addLayer({ + * id: 'states', + * // References a source that's already been defined + * source: 'state-data', + * type: 'symbol', + * layout: { + * // Set the label content to the + * // feature's `name` property + * text-field: ['get', 'name'] + * } + * // Add the layer before the existing `cities` layer + * }, 'cities'); + * ``` + * @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/cluster/) + * @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/vector-source/) + * @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/wms/) + */ + addLayer(layer, beforeId) { + this._lazyInitEmptyStyle(); + this.style.addLayer(layer, beforeId); + return this._update(true); + } + /** + * Moves a layer to a different z-position. + * + * @param id - The ID of the layer to move. + * @param 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. + * + * @example + * 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. + * ```ts + * map.moveLayer('polygon', 'country-label'); + * ``` + */ + moveLayer(id, beforeId) { + this.style.moveLayer(id, beforeId); + return this._update(true); + } + /** + * Removes the layer with the given ID from the map's style. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param id - The ID of the layer to remove + * + * @example + * If a layer with ID 'state-data' exists, remove it. + * ```ts + * if (map.getLayer('state-data')) map.removeLayer('state-data'); + * ``` + */ + removeLayer(id) { + this.style.removeLayer(id); + return this._update(true); + } + /** + * Returns the layer with the specified ID in the map's style. + * + * @param id - The ID of the layer to get. + * @returns The layer with the specified ID, or `undefined` + * if the ID corresponds to no existing layers. + * + * @example + * ```ts + * let stateDataLayer = map.getLayer('state-data'); + * ``` + * @see [Filter symbols by toggling a list](https://maplibre.org/maplibre-gl-js/docs/examples/filter-markers/) + * @see [Filter symbols by text input](https://maplibre.org/maplibre-gl-js/docs/examples/filter-markers-by-input/) + */ + getLayer(id) { + return this.style.getLayer(id); + } + /** + * Return the ids of all layers currently in the style, including custom layers, in order. + * + * @returns ids of layers, in order + * + * @example + * ```ts + * const orderedLayerIds = map.getLayersOrder(); + * ``` + */ + getLayersOrder() { + return this.style.getLayersOrder(); + } + /** + * Sets the zoom extent for the specified style layer. The zoom extent includes the + * [minimum zoom level](https://maplibre.org/maplibre-style-spec/layers/#minzoom) + * and [maximum zoom level](https://maplibre.org/maplibre-style-spec/layers/#maxzoom)) + * at which the layer will be rendered. + * + * Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the + * minimum zoom level of the _source layer_ because the data does not exist at those zoom levels. If the minimum + * zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style + * layer will not be rendered at all zoom levels in the zoom range. + * + * @param layerId - The ID of the layer to which the zoom extent will be applied. + * @param minzoom - The minimum zoom to set (0-24). + * @param maxzoom - The maximum zoom to set (0-24). + * + * @example + * ```ts + * map.setLayerZoomRange('my-layer', 2, 5); + * ``` + */ + setLayerZoomRange(layerId, minzoom, maxzoom) { + this.style.setLayerZoomRange(layerId, minzoom, maxzoom); + return this._update(true); + } + /** + * Sets the filter for the specified style layer. + * + * Filters control which features a style layer renders from its source. + * Any feature for which the filter expression evaluates to `true` will be + * rendered on the map. Those that are false will be hidden. + * + * Use `setFilter` to show a subset of your source data. + * + * To clear the filter, pass `null` or `undefined` as the second parameter. + * + * @param layerId - The ID of the layer to which the filter will be applied. + * @param filter - The filter, conforming to the MapLibre Style Specification's + * [filter definition](https://maplibre.org/maplibre-style-spec/layers/#filter). If `null` or `undefined` is provided, the function removes any existing filter from the layer. + * @param options - Options object. + * + * @example + * Display only features with the 'name' property 'USA' + * ```ts + * map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']); + * ``` + * @example + * Display only features with five or more 'available-spots' + * ```ts + * map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]); + * ``` + * @example + * Remove the filter for the 'bike-docks' style layer + * ```ts + * map.setFilter('bike-docks', null); + * ``` + * @see [Create a timeline animation](https://maplibre.org/maplibre-gl-js/docs/examples/timeline-animation/) + */ + setFilter(layerId, filter, options = {}) { + this.style.setFilter(layerId, filter, options); + return this._update(true); + } + /** + * Returns the filter applied to the specified style layer. + * + * @param layerId - The ID of the style layer whose filter to get. + * @returns The layer's filter. + */ + getFilter(layerId) { + return this.style.getFilter(layerId); + } + /** + * Sets the value of a paint property in the specified style layer. + * + * @param layerId - The ID of the layer to set the paint property in. + * @param name - The name of the paint property to set. + * @param value - The value of the paint property to set. + * Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/). + * Pass `null` to unset the existing value. + * @param options - Options object. + * @example + * ```ts + * map.setPaintProperty('my-layer', 'fill-color', '#faafee'); + * ``` + * @see [Change a layer's color with buttons](https://maplibre.org/maplibre-gl-js/docs/examples/color-switcher/) + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + setPaintProperty(layerId, name, value, options = {}) { + this.style.setPaintProperty(layerId, name, value, options); + return this._update(true); + } + /** + * Returns the value of a paint property in the specified style layer. + * + * @param layerId - The ID of the layer to get the paint property from. + * @param name - The name of a paint property to get. + * @returns The value of the specified paint property. + */ + getPaintProperty(layerId, name) { + return this.style.getPaintProperty(layerId, name); + } + /** + * Sets the value of a layout property in the specified style layer. + * + * @param layerId - The ID of the layer to set the layout property in. + * @param name - The name of the layout property to set. + * @param value - The value of the layout property. Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/). + * @param options - The options object. + * @example + * ```ts + * map.setLayoutProperty('my-layer', 'visibility', 'none'); + * ``` + */ + setLayoutProperty(layerId, name, value, options = {}) { + this.style.setLayoutProperty(layerId, name, value, options); + return this._update(true); + } + /** + * Returns the value of a layout property in the specified style layer. + * + * @param layerId - The ID of the layer to get the layout property from. + * @param name - The name of the layout property to get. + * @returns The value of the specified layout property. + */ + getLayoutProperty(layerId, name) { + return this.style.getLayoutProperty(layerId, name); + } + /** + * Sets the value of the style's glyphs property. + * + * @param glyphsUrl - Glyph URL to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/glyphs/). + * @param options - Options object. + * @example + * ```ts + * map.setGlyphs('https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf'); + * ``` + */ + setGlyphs(glyphsUrl, options = {}) { + this._lazyInitEmptyStyle(); + this.style.setGlyphs(glyphsUrl, options); + return this._update(true); + } + /** + * Returns the value of the style's glyphs URL + * + * @returns glyphs Style's glyphs url + */ + getGlyphs() { + return this.style.getGlyphsUrl(); + } + /** + * Adds a sprite to the map's style. Fires the `style` event. + * + * @param id - The ID of the sprite to add. Must not conflict with existing sprites. + * @param url - The URL to load the sprite from + * @param options - Options object. + * @example + * ```ts + * map.addSprite('sprite-two', 'http://example.com/sprite-two'); + * ``` + */ + addSprite(id, url, options = {}) { + this._lazyInitEmptyStyle(); + this.style.addSprite(id, url, options, (err) => { + if (!err) { + this._update(true); + } + }); + return this; + } + /** + * Removes the sprite from the map's style. Fires the `style` event. + * + * @param id - The ID of the sprite to remove. If the sprite is declared as a single URL, the ID must be "default". + * @example + * ```ts + * map.removeSprite('sprite-two'); + * map.removeSprite('default'); + * ``` + */ + removeSprite(id) { + this._lazyInitEmptyStyle(); + this.style.removeSprite(id); + return this._update(true); + } + /** + * Returns the as-is value of the style's sprite. + * + * @returns style's sprite list of id-url pairs + */ + getSprite() { + return this.style.getSprite(); + } + /** + * Sets the value of the style's sprite property. + * + * @param spriteUrl - Sprite URL to set. + * @param options - Options object. + * @example + * ```ts + * map.setSprite('YOUR_SPRITE_URL'); + * ``` + */ + setSprite(spriteUrl, options = {}) { + this._lazyInitEmptyStyle(); + this.style.setSprite(spriteUrl, options, (err) => { + if (!err) { + this._update(true); + } + }); + return this; + } + /** + * Sets the any combination of light values. + * + * @param light - Light properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/light). + * @param options - Options object. + * + * @example + * ```ts + * let layerVisibility = map.getLayoutProperty('my-layer', 'visibility'); + * ``` + */ + setLight(light, options = {}) { + this._lazyInitEmptyStyle(); + this.style.setLight(light, options); + return this._update(true); + } + /** + * Returns the value of the light object. + * + * @returns light Light properties of the style. + */ + getLight() { + return this.style.getLight(); + } + /** + * Loads sky and fog defined by {@link SkySpecification} onto the map. + * Note: The fog only shows when using the terrain 3D feature. + * @param sky - Sky properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/sky/). + * @returns `this` + * @example + * ```ts + * map.setSky({ 'sky-color': '#00f' }); + * ``` + */ + setSky(sky) { + this._lazyInitEmptyStyle(); + this.style.setSky(sky); + return this._update(true); + } + /** + * Returns the value of the sky object. + * + * @returns the sky properties of the style. + * @example + * ```ts + * map.getSky(); + * ``` + */ + getSky() { + return this.style.getSky(); + } + /** + * Sets the `state` of a feature. + * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime. + * When using this method, the `state` object is merged with any existing key-value pairs in the feature's state. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * This method can only be used with sources that have a `feature.id` attribute. The `feature.id` attribute can be defined in three ways: + * + * - For vector or GeoJSON sources, including an `id` attribute in the original data file. + * - For vector or GeoJSON sources, using the [`promoteId`](https://maplibre.org/maplibre-style-spec/sources/#vector-promoteId) option at the time the source is defined. + * - For GeoJSON sources, using the [`generateId`](https://maplibre.org/maplibre-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. + * + * _Note: You can use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state) to access the values in a feature's state object for the purposes of styling._ + * + * @param feature - Feature identifier. Feature objects returned from + * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param state - A set of key-value pairs. The values should be valid JSON types. + * + * @example + * ```ts + * // When the mouse moves over the `my-layer` layer, update + * // the feature state for the feature under the mouse + * map.on('mousemove', 'my-layer', (e) => { + * if (e.features.length > 0) { + * map.setFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id, + * }, { + * hover: true + * }); + * } + * }); + * ``` + * @see [Create a hover effect](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/) + */ + setFeatureState(feature, state) { + this.style.setFeatureState(feature, state); + return this._update(); + } + /** + * Removes the `state` of a feature, setting it back to the default behavior. + * If only a `target.source` is specified, it will remove the state for all features from that source. + * If `target.id` is also specified, it will remove all keys for that feature's state. + * If `key` is also specified, it removes only that key from that feature's state. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * @param target - Identifier of where to remove state. It can be a source, a feature, or a specific key of feature. + * Feature objects returned from {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param key - (optional) The key in the feature state to reset. + * @example + * Reset the entire state object for all features in the `my-source` source + * ```ts + * map.removeFeatureState({ + * source: 'my-source' + * }); + * ``` + * + * @example + * When the mouse leaves the `my-layer` layer, + * reset the entire state object for the + * feature under the mouse + * ```ts + * map.on('mouseleave', 'my-layer', (e) => { + * map.removeFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }); + * }); + * ``` + * + * @example + * When the mouse leaves the `my-layer` layer, + * reset only the `hover` key-value pair in the + * state for the feature under the mouse + * ```ts + * map.on('mouseleave', 'my-layer', (e) => { + * map.removeFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }, 'hover'); + * }); + * ``` + */ + removeFeatureState(target, key) { + this.style.removeFeatureState(target, key); + return this._update(); + } + /** + * Gets the `state` of a feature. + * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * _Note: To access the values in a feature's state object for the purposes of styling the feature, use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state)._ + * + * @param feature - Feature identifier. Feature objects returned from + * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @returns The state of the feature: a set of key-value pairs that was assigned to the feature at runtime. + * + * @example + * When the mouse moves over the `my-layer` layer, + * get the feature state for the feature under the mouse + * ```ts + * map.on('mousemove', 'my-layer', (e) => { + * if (e.features.length > 0) { + * map.getFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }); + * } + * }); + * ``` + */ + getFeatureState(feature) { + return this.style.getFeatureState(feature); + } + /** + * Returns the map's containing HTML element. + * + * @returns The map's container. + */ + getContainer() { + return this._container; + } + /** + * Returns the HTML element containing the map's `` element. + * + * If you want to add non-GL overlays to the map, you should append them to this element. + * + * This is the element to which event bindings for map interactivity (such as panning and zooming) are + * attached. It will receive bubbled events from child elements such as the ``, but not from + * map controls. + * + * @returns The container of the map's ``. + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + getCanvasContainer() { + return this._canvasContainer; + } + /** + * Returns the map's `` element. + * + * @returns The map's `` element. + * @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-on-symbol/) + */ + getCanvas() { + return this._canvas; + } + _containerDimensions() { + let width = 0; + let height = 0; + if (this._container) { + width = this._container.clientWidth || 400; + height = this._container.clientHeight || 300; + } + return [width, height]; + } + _setupContainer() { + const container = this._container; + container.classList.add('maplibregl-map'); + const canvasContainer = this._canvasContainer = DOM.create('div', 'maplibregl-canvas-container', container); + if (this._interactive) { + canvasContainer.classList.add('maplibregl-interactive'); + } + this._canvas = DOM.create('canvas', 'maplibregl-canvas', canvasContainer); + this._canvas.addEventListener('webglcontextlost', this._contextLost, false); + this._canvas.addEventListener('webglcontextrestored', this._contextRestored, false); + this._canvas.setAttribute('tabindex', this._interactive ? '0' : '-1'); + this._canvas.setAttribute('aria-label', this._getUIString('Map.Title')); + this._canvas.setAttribute('role', 'region'); + const dimensions = this._containerDimensions(); + const clampedPixelRatio = this._getClampedPixelRatio(dimensions[0], dimensions[1]); + this._resizeCanvas(dimensions[0], dimensions[1], clampedPixelRatio); + const controlContainer = this._controlContainer = DOM.create('div', 'maplibregl-control-container', container); + const positions = this._controlPositions = {}; + ['top-left', 'top-right', 'bottom-left', 'bottom-right'].forEach((positionName) => { + positions[positionName] = DOM.create('div', `maplibregl-ctrl-${positionName} `, controlContainer); + }); + this._container.addEventListener('scroll', this._onMapScroll, false); + } + _resizeCanvas(width, height, pixelRatio) { + // Request the required canvas size taking the pixelratio into account. + this._canvas.width = Math.floor(pixelRatio * width); + this._canvas.height = Math.floor(pixelRatio * height); + // Maintain the same canvas size, potentially downscaling it for HiDPI displays + this._canvas.style.width = `${width}px`; + this._canvas.style.height = `${height}px`; + } + _setupPainter() { + const attributes = { + alpha: true, + stencil: true, + depth: true, + failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat, + preserveDrawingBuffer: this._preserveDrawingBuffer, + antialias: this._antialias || false + }; + let webglcontextcreationerrorDetailObject = null; + this._canvas.addEventListener('webglcontextcreationerror', (args) => { + webglcontextcreationerrorDetailObject = { requestedAttributes: attributes }; + if (args) { + webglcontextcreationerrorDetailObject.statusMessage = args.statusMessage; + webglcontextcreationerrorDetailObject.type = args.type; + } + }, { once: true }); + const gl = this._canvas.getContext('webgl2', attributes) || + this._canvas.getContext('webgl', attributes); + if (!gl) { + const msg = 'Failed to initialize WebGL'; + if (webglcontextcreationerrorDetailObject) { + webglcontextcreationerrorDetailObject.message = msg; + throw new Error(JSON.stringify(webglcontextcreationerrorDetailObject)); + } + else { + throw new Error(msg); + } + } + this.painter = new Painter(gl, this.transform); + webpSupported.testSupport(gl); + } + /** + * Returns a Boolean indicating whether the map is fully loaded. + * + * Returns `false` if the style is not yet fully loaded, + * or if there has been a change to the sources or style that + * has not yet fully loaded. + * + * @returns A Boolean indicating whether the map is fully loaded. + */ + loaded() { + return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded(); + } + /** + * @internal + * Update this map's style and sources, and re-render the map. + * + * @param updateStyle - mark the map's style for reprocessing as + * well as its sources + */ + _update(updateStyle) { + if (!this.style || !this.style._loaded) + return this; + this._styleDirty = this._styleDirty || updateStyle; + this._sourcesDirty = true; + this.triggerRepaint(); + return this; + } + /** + * @internal + * Request that the given callback be executed during the next render + * frame. Schedule a render frame if one is not already scheduled. + * + * @returns An id that can be used to cancel the callback + */ + _requestRenderFrame(callback) { + this._update(); + return this._renderTaskQueue.add(callback); + } + _cancelRenderFrame(id) { + this._renderTaskQueue.remove(id); + } + /** + * @internal + * Call when a (re-)render of the map is required: + * + * - The style has changed (`setPaintProperty()`, etc.) + * - Source data has changed (e.g. tiles have finished loading) + * - The map has is moving (or just finished moving) + * - A transition is in progress + * + * @param paintStartTimeStamp - The time when the animation frame began executing. + */ + _render(paintStartTimeStamp) { + const fadeDuration = this._idleTriggered ? this._fadeDuration : 0; + // A custom layer may have used the context asynchronously. Mark the state as dirty. + this.painter.context.setDirty(); + this.painter.setBaseState(); + this._renderTaskQueue.run(paintStartTimeStamp); + // A task queue callback may have fired a user event which may have removed the map + if (this._removed) + return; + let crossFading = false; + // If the style has changed, the map is being zoomed, or a transition or fade is in progress: + // - Apply style changes (in a batch) + // - Recalculate paint properties. + if (this.style && this._styleDirty) { + this._styleDirty = false; + const zoom = this.transform.zoom; + const now = browser.now(); + this.style.zoomHistory.update(zoom, now); + const parameters = new performance$1.z(zoom, { + now, + fadeDuration, + zoomHistory: this.style.zoomHistory, + transition: this.style.getTransition() + }); + const factor = parameters.crossFadingFactor(); + if (factor !== 1 || factor !== this._crossFadingFactor) { + crossFading = true; + this._crossFadingFactor = factor; + } + this.style.update(parameters); + } + // If we are in _render for any reason other than an in-progress paint + // transition, update source caches to check for and load any tiles we + // need for the current transform + if (this.style && this._sourcesDirty) { + this._sourcesDirty = false; + this.style._updateSources(this.transform); + } + // update terrain stuff + if (this.terrain) { + this.terrain.sourceCache.update(this.transform, this.terrain); + this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + if (!this._elevationFreeze) { + this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom); + } + } + else { + this.transform.minElevationForCurrentTile = 0; + this.transform.elevation = 0; + } + this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, fadeDuration, this._crossSourceCollisions); + // Actually draw + this.painter.render(this.style, { + showTileBoundaries: this.showTileBoundaries, + showOverdrawInspector: this._showOverdrawInspector, + rotating: this.isRotating(), + zooming: this.isZooming(), + moving: this.isMoving(), + fadeDuration, + showPadding: this.showPadding, + }); + this.fire(new performance$1.k('render')); + if (this.loaded() && !this._loaded) { + this._loaded = true; + performance$1.bf.mark(performance$1.bg.load); + this.fire(new performance$1.k('load')); + } + if (this.style && (this.style.hasTransitions() || crossFading)) { + this._styleDirty = true; + } + if (this.style && !this._placementDirty) { + // Since no fade operations are in progress, we can release + // all tiles held for fading. If we didn't do this, the tiles + // would just sit in the SourceCaches until the next render + this.style._releaseSymbolFadeTiles(); + } + // Schedule another render frame if it's needed. + // + // Even though `_styleDirty` and `_sourcesDirty` are reset in this + // method, synchronous events fired during Style#update or + // Style#_updateSources could have caused them to be set again. + const somethingDirty = this._sourcesDirty || this._styleDirty || this._placementDirty; + if (somethingDirty || this._repaint) { + this.triggerRepaint(); + } + else if (!this.isMoving() && this.loaded()) { + this.fire(new performance$1.k('idle')); + } + if (this._loaded && !this._fullyLoaded && !somethingDirty) { + this._fullyLoaded = true; + performance$1.bf.mark(performance$1.bg.fullLoad); + } + return this; + } + /** + * Force a synchronous redraw of the map. + * @example + * ```ts + * map.redraw(); + * ``` + */ + redraw() { + if (this.style) { + // cancel the scheduled update + if (this._frameRequest) { + this._frameRequest.abort(); + this._frameRequest = null; + } + this._render(0); + } + return this; + } + /** + * Clean up and release all internal resources associated with this map. + * + * This includes DOM elements, event bindings, web workers, and WebGL resources. + * + * Use this method when you are done using the map and wish to ensure that it no + * longer consumes browser resources. Afterwards, you must not call any other + * methods on the map. + */ + remove() { + var _a; + if (this._hash) + this._hash.remove(); + for (const control of this._controls) + control.onRemove(this); + this._controls = []; + if (this._frameRequest) { + this._frameRequest.abort(); + this._frameRequest = null; + } + this._renderTaskQueue.clear(); + this.painter.destroy(); + this.handlers.destroy(); + delete this.handlers; + this.setStyle(null); + if (typeof window !== 'undefined') { + removeEventListener('online', this._onWindowOnline, false); + } + ImageRequest.removeThrottleControl(this._imageQueueHandle); + (_a = this._resizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect(); + const extension = this.painter.context.gl.getExtension('WEBGL_lose_context'); + if (extension === null || extension === void 0 ? void 0 : extension.loseContext) + extension.loseContext(); + this._canvas.removeEventListener('webglcontextrestored', this._contextRestored, false); + this._canvas.removeEventListener('webglcontextlost', this._contextLost, false); + DOM.remove(this._canvasContainer); + DOM.remove(this._controlContainer); + this._container.classList.remove('maplibregl-map'); + performance$1.bf.clearMetrics(); + this._removed = true; + this.fire(new performance$1.k('remove')); + } + /** + * Trigger the rendering of a single frame. Use this method with custom layers to + * repaint the map when the layer changes. Calling this multiple times before the + * next frame is rendered will still result in only a single frame being rendered. + * @example + * ```ts + * map.triggerRepaint(); + * ``` + * @see [Add a 3D model](https://maplibre.org/maplibre-gl-js/docs/examples/add-3d-model/) + * @see [Add an animated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-animated/) + */ + triggerRepaint() { + if (this.style && !this._frameRequest) { + this._frameRequest = new AbortController(); + browser.frameAsync(this._frameRequest).then((paintStartTimeStamp) => { + performance$1.bf.frame(paintStartTimeStamp); + this._frameRequest = null; + this._render(paintStartTimeStamp); + }).catch(() => { }); // ignore abort error + } + } + /** + * Gets and sets a Boolean indicating whether the map will render an outline + * around each tile and the tile ID. These tile boundaries are useful for + * debugging. + * + * The uncompressed file size of the first vector source is drawn in the top left + * corner of each tile, next to the tile ID. + * + * @example + * ```ts + * map.showTileBoundaries = true; + * ``` + */ + get showTileBoundaries() { return !!this._showTileBoundaries; } + set showTileBoundaries(value) { + if (this._showTileBoundaries === value) + return; + this._showTileBoundaries = value; + this._update(); + } + /** + * Gets and sets a Boolean indicating whether the map will visualize + * the padding offsets. + */ + get showPadding() { return !!this._showPadding; } + set showPadding(value) { + if (this._showPadding === value) + return; + this._showPadding = value; + this._update(); + } + /** + * Gets and sets a Boolean indicating whether the map will render boxes + * around all symbols in the data source, revealing which symbols + * were rendered or which were hidden due to collisions. + * This information is useful for debugging. + */ + get showCollisionBoxes() { return !!this._showCollisionBoxes; } + set showCollisionBoxes(value) { + if (this._showCollisionBoxes === value) + return; + this._showCollisionBoxes = value; + if (value) { + // When we turn collision boxes on we have to generate them for existing tiles + // When we turn them off, there's no cost to leaving existing boxes in place + this.style._generateCollisionBoxes(); + } + else { + // Otherwise, call an update to remove collision boxes + this._update(); + } + } + /** + * Gets and sets a Boolean indicating whether the map should color-code + * each fragment to show how many times it has been shaded. + * White fragments have been shaded 8 or more times. + * Black fragments have been shaded 0 times. + * This information is useful for debugging. + */ + get showOverdrawInspector() { return !!this._showOverdrawInspector; } + set showOverdrawInspector(value) { + if (this._showOverdrawInspector === value) + return; + this._showOverdrawInspector = value; + this._update(); + } + /** + * Gets and sets a Boolean indicating whether the map will + * continuously repaint. This information is useful for analyzing performance. + */ + get repaint() { return !!this._repaint; } + set repaint(value) { + if (this._repaint !== value) { + this._repaint = value; + this.triggerRepaint(); + } + } + // show vertices + get vertices() { return !!this._vertices; } + set vertices(value) { this._vertices = value; this._update(); } + /** + * Returns the package version of the library + * @returns Package version of the library + */ + get version() { + return version$1; + } + /** + * Returns the elevation for the point where the camera is looking. + * This value corresponds to: + * "meters above sea level" * "exaggeration" + * @returns The elevation. + */ + getCameraTargetElevation() { + return this.transform.elevation; + } +}; + +const assignEvents = (handler) => { + handler.touchstart = handler.dragStart; + handler.touchmoveWindow = handler.dragMove; + handler.touchend = handler.dragEnd; +}; +const generateOneFingerTouchRotationHandler = ({ enable, clickTolerance, bearingDegreesPerPixelMoved = 0.8 }) => { + const touchMoveStateManager = new OneFingerTouchMoveStateManager(); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ bearingDelta: (point.x - lastPoint.x) * bearingDegreesPerPixelMoved }), + moveStateManager: touchMoveStateManager, + enable, + assignEvents, + }); +}; +const generateOneFingerTouchPitchHandler = ({ enable, clickTolerance, pitchDegreesPerPixelMoved = -0.5 }) => { + const touchMoveStateManager = new OneFingerTouchMoveStateManager(); + return new DragHandler({ + clickTolerance, + move: (lastPoint, point) => ({ pitchDelta: (point.y - lastPoint.y) * pitchDegreesPerPixelMoved }), + moveStateManager: touchMoveStateManager, + enable, + assignEvents, + }); +}; + +const defaultOptions$3 = { + showCompass: true, + showZoom: true, + visualizePitch: false +}; +/** + * A `NavigationControl` control contains zoom buttons and a compass. + * + * @group Markers and Controls + * + * @example + * ```ts + * let nav = new NavigationControl(); + * map.addControl(nav, 'top-left'); + * ``` + * @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigation/) + */ +class NavigationControl { + /** + * @param options - the control's options + */ + constructor(options) { + this._updateZoomButtons = () => { + const zoom = this._map.getZoom(); + const isMax = zoom === this._map.getMaxZoom(); + const isMin = zoom === this._map.getMinZoom(); + this._zoomInButton.disabled = isMax; + this._zoomOutButton.disabled = isMin; + this._zoomInButton.setAttribute('aria-disabled', isMax.toString()); + this._zoomOutButton.setAttribute('aria-disabled', isMin.toString()); + }; + this._rotateCompassArrow = () => { + const rotate = this.options.visualizePitch ? + `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)` : + `rotate(${this._map.transform.angle * (180 / Math.PI)}deg)`; + this._compassIcon.style.transform = rotate; + }; + this._setButtonTitle = (button, title) => { + const str = this._map._getUIString(`NavigationControl.${title}`); + button.title = str; + button.setAttribute('aria-label', str); + }; + this.options = performance$1.e({}, defaultOptions$3, options); + this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group'); + this._container.addEventListener('contextmenu', (e) => e.preventDefault()); + if (this.options.showZoom) { + this._zoomInButton = this._createButton('maplibregl-ctrl-zoom-in', (e) => this._map.zoomIn({}, { originalEvent: e })); + DOM.create('span', 'maplibregl-ctrl-icon', this._zoomInButton).setAttribute('aria-hidden', 'true'); + this._zoomOutButton = this._createButton('maplibregl-ctrl-zoom-out', (e) => this._map.zoomOut({}, { originalEvent: e })); + DOM.create('span', 'maplibregl-ctrl-icon', this._zoomOutButton).setAttribute('aria-hidden', 'true'); + } + if (this.options.showCompass) { + this._compass = this._createButton('maplibregl-ctrl-compass', (e) => { + if (this.options.visualizePitch) { + this._map.resetNorthPitch({}, { originalEvent: e }); + } + else { + this._map.resetNorth({}, { originalEvent: e }); + } + }); + this._compassIcon = DOM.create('span', 'maplibregl-ctrl-icon', this._compass); + this._compassIcon.setAttribute('aria-hidden', 'true'); + } + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + if (this.options.showZoom) { + this._setButtonTitle(this._zoomInButton, 'ZoomIn'); + this._setButtonTitle(this._zoomOutButton, 'ZoomOut'); + this._map.on('zoom', this._updateZoomButtons); + this._updateZoomButtons(); + } + if (this.options.showCompass) { + this._setButtonTitle(this._compass, 'ResetBearing'); + if (this.options.visualizePitch) { + this._map.on('pitch', this._rotateCompassArrow); + } + this._map.on('rotate', this._rotateCompassArrow); + this._rotateCompassArrow(); + this._handler = new MouseRotateWrapper(this._map, this._compass, this.options.visualizePitch); + } + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + if (this.options.showZoom) { + this._map.off('zoom', this._updateZoomButtons); + } + if (this.options.showCompass) { + if (this.options.visualizePitch) { + this._map.off('pitch', this._rotateCompassArrow); + } + this._map.off('rotate', this._rotateCompassArrow); + this._handler.off(); + delete this._handler; + } + delete this._map; + } + _createButton(className, fn) { + const a = DOM.create('button', className, this._container); + a.type = 'button'; + a.addEventListener('click', fn); + return a; + } +} +class MouseRotateWrapper { + constructor(map, element, pitch = false) { + this.mousedown = (e) => { + this.startMouse(performance$1.e({}, e, { ctrlKey: true, preventDefault: () => e.preventDefault() }), DOM.mousePos(this.element, e)); + DOM.addEventListener(window, 'mousemove', this.mousemove); + DOM.addEventListener(window, 'mouseup', this.mouseup); + }; + this.mousemove = (e) => { + this.moveMouse(e, DOM.mousePos(this.element, e)); + }; + this.mouseup = (e) => { + this.mouseRotate.dragEnd(e); + if (this.mousePitch) + this.mousePitch.dragEnd(e); + this.offTemp(); + }; + this.touchstart = (e) => { + if (e.targetTouches.length !== 1) { + this.reset(); + } + else { + this._startPos = this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0]; + this.startTouch(e, this._startPos); + DOM.addEventListener(window, 'touchmove', this.touchmove, { passive: false }); + DOM.addEventListener(window, 'touchend', this.touchend); + } + }; + this.touchmove = (e) => { + if (e.targetTouches.length !== 1) { + this.reset(); + } + else { + this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0]; + this.moveTouch(e, this._lastPos); + } + }; + this.touchend = (e) => { + if (e.targetTouches.length === 0 && + this._startPos && + this._lastPos && + this._startPos.dist(this._lastPos) < this._clickTolerance) { + this.element.click(); + } + delete this._startPos; + delete this._lastPos; + this.offTemp(); + }; + this.reset = () => { + this.mouseRotate.reset(); + if (this.mousePitch) + this.mousePitch.reset(); + this.touchRotate.reset(); + if (this.touchPitch) + this.touchPitch.reset(); + delete this._startPos; + delete this._lastPos; + this.offTemp(); + }; + this._clickTolerance = 10; + const mapRotateTolerance = map.dragRotate._mouseRotate.getClickTolerance(); + const mapPitchTolerance = map.dragRotate._mousePitch.getClickTolerance(); + this.element = element; + this.mouseRotate = generateMouseRotationHandler({ clickTolerance: mapRotateTolerance, enable: true }); + this.touchRotate = generateOneFingerTouchRotationHandler({ clickTolerance: mapRotateTolerance, enable: true }); + this.map = map; + if (pitch) { + this.mousePitch = generateMousePitchHandler({ clickTolerance: mapPitchTolerance, enable: true }); + this.touchPitch = generateOneFingerTouchPitchHandler({ clickTolerance: mapPitchTolerance, enable: true }); + } + DOM.addEventListener(element, 'mousedown', this.mousedown); + DOM.addEventListener(element, 'touchstart', this.touchstart, { passive: false }); + DOM.addEventListener(element, 'touchcancel', this.reset); + } + startMouse(e, point) { + this.mouseRotate.dragStart(e, point); + if (this.mousePitch) + this.mousePitch.dragStart(e, point); + DOM.disableDrag(); + } + startTouch(e, point) { + this.touchRotate.dragStart(e, point); + if (this.touchPitch) + this.touchPitch.dragStart(e, point); + DOM.disableDrag(); + } + moveMouse(e, point) { + const map = this.map; + const { bearingDelta } = this.mouseRotate.dragMove(e, point) || {}; + if (bearingDelta) + map.setBearing(map.getBearing() + bearingDelta); + if (this.mousePitch) { + const { pitchDelta } = this.mousePitch.dragMove(e, point) || {}; + if (pitchDelta) + map.setPitch(map.getPitch() + pitchDelta); + } + } + moveTouch(e, point) { + const map = this.map; + const { bearingDelta } = this.touchRotate.dragMove(e, point) || {}; + if (bearingDelta) + map.setBearing(map.getBearing() + bearingDelta); + if (this.touchPitch) { + const { pitchDelta } = this.touchPitch.dragMove(e, point) || {}; + if (pitchDelta) + map.setPitch(map.getPitch() + pitchDelta); + } + } + off() { + const element = this.element; + DOM.removeEventListener(element, 'mousedown', this.mousedown); + DOM.removeEventListener(element, 'touchstart', this.touchstart, { passive: false }); + DOM.removeEventListener(window, 'touchmove', this.touchmove, { passive: false }); + DOM.removeEventListener(window, 'touchend', this.touchend); + DOM.removeEventListener(element, 'touchcancel', this.reset); + this.offTemp(); + } + offTemp() { + DOM.enableDrag(); + DOM.removeEventListener(window, 'mousemove', this.mousemove); + DOM.removeEventListener(window, 'mouseup', this.mouseup); + DOM.removeEventListener(window, 'touchmove', this.touchmove, { passive: false }); + DOM.removeEventListener(window, 'touchend', this.touchend); + } +} + +let supportsGeolocation; +function checkGeolocationSupport() { + return performance$1._(this, arguments, void 0, function* (forceRecalculation = false) { + if (supportsGeolocation !== undefined && !forceRecalculation) { + return supportsGeolocation; + } + if (window.navigator.permissions === undefined) { + supportsGeolocation = !!window.navigator.geolocation; + return supportsGeolocation; + } + // navigator.permissions has incomplete browser support + // https://caniuse.com/#feat=permissions-api + // Test for the case where a browser disables Geolocation because of an + // insecure origin + try { + const permissions = yield window.navigator.permissions.query({ name: 'geolocation' }); + supportsGeolocation = permissions.state !== 'denied'; // eslint-disable-line require-atomic-updates + } + catch (_a) { + // Fix for iOS16 which rejects query but still supports geolocation + supportsGeolocation = !!window.navigator.geolocation; // eslint-disable-line require-atomic-updates + } + return supportsGeolocation; + }); +} + +/** + * Given a LngLat, prior projected position, and a transform, return a new LngLat shifted + * n × 360° east or west for some n ≥ 0 such that: + * + * * the projected location of the result is on screen, if possible, and secondarily: + * * the difference between the projected location of the result and the prior position + * is minimized. + * + * The object is to preserve perceived object constancy for Popups and Markers as much as + * possible; they should avoid shifting large distances across the screen, even when the + * map center changes by ±360° due to automatic wrapping, and when about to go off screen, + * should wrap just enough to avoid doing so. + */ +function smartWrap(lngLat, priorPos, transform) { + const originalLngLat = new performance$1.N(lngLat.lng, lngLat.lat); + lngLat = new performance$1.N(lngLat.lng, lngLat.lat); + // First, try shifting one world in either direction, and see if either is closer to the + // prior position. This preserves object constancy when the map center is auto-wrapped + // during animations. + if (priorPos) { + const left = new performance$1.N(lngLat.lng - 360, lngLat.lat); + const right = new performance$1.N(lngLat.lng + 360, lngLat.lat); + const delta = transform.locationPoint(lngLat).distSqr(priorPos); + if (transform.locationPoint(left).distSqr(priorPos) < delta) { + lngLat = left; + } + else if (transform.locationPoint(right).distSqr(priorPos) < delta) { + lngLat = right; + } + } + // Second, wrap toward the center until the new position is on screen, or we can't get + // any closer. + while (Math.abs(lngLat.lng - transform.center.lng) > 180) { + const pos = transform.locationPoint(lngLat); + if (pos.x >= 0 && pos.y >= 0 && pos.x <= transform.width && pos.y <= transform.height) { + break; + } + if (lngLat.lng > transform.center.lng) { + lngLat.lng -= 360; + } + else { + lngLat.lng += 360; + } + } + // Apply the change only if new coord is below horizon + if (lngLat.lng !== originalLngLat.lng && + transform.locationPoint(lngLat).y > (transform.height / 2 - transform.getHorizon())) { + return lngLat; + } + return originalLngLat; +} + +const anchorTranslate = { + 'center': 'translate(-50%,-50%)', + 'top': 'translate(-50%,0)', + 'top-left': 'translate(0,0)', + 'top-right': 'translate(-100%,0)', + 'bottom': 'translate(-50%,-100%)', + 'bottom-left': 'translate(0,-100%)', + 'bottom-right': 'translate(-100%,-100%)', + 'left': 'translate(0,-50%)', + 'right': 'translate(-100%,-50%)' +}; +function applyAnchorClass(element, anchor, prefix) { + const classList = element.classList; + for (const key in anchorTranslate) { + classList.remove(`maplibregl-${prefix}-anchor-${key}`); + } + classList.add(`maplibregl-${prefix}-anchor-${anchor}`); +} + +/** + * Creates a marker component + * + * @group Markers and Controls + * + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([30.5, 50.5]) + * .addTo(map); + * ``` + * + * @example + * Set options + * ```ts + * let marker = new Marker({ + * color: "#FFFFFF", + * draggable: true + * }).setLngLat([30.5, 50.5]) + * .addTo(map); + * ``` + * @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/custom-marker-icons/) + * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/) + * + * ## Events + * + * **Event** `dragstart` of type {@link Event} will be fired when dragging starts. + * + * **Event** `drag` of type {@link Event} will be fired while dragging. + * + * **Event** `dragend` of type {@link Event} will be fired when the marker is finished being dragged. + */ +class Marker extends performance$1.E { + /** + * @param options - the options + */ + constructor(options) { + super(); + this._onKeyPress = (e) => { + const code = e.code; + const legacyCode = e.charCode || e.keyCode; + if ((code === 'Space') || (code === 'Enter') || + (legacyCode === 32) || (legacyCode === 13) // space or enter + ) { + this.togglePopup(); + } + }; + this._onMapClick = (e) => { + const targetElement = e.originalEvent.target; + const element = this._element; + if (this._popup && (targetElement === element || element.contains(targetElement))) { + this.togglePopup(); + } + }; + this._update = (e) => { + var _a; + if (!this._map) + return; + const isFullyLoaded = this._map.loaded() && !this._map.isMoving(); + if ((e === null || e === void 0 ? void 0 : e.type) === 'terrain' || ((e === null || e === void 0 ? void 0 : e.type) === 'render' && !isFullyLoaded)) { + this._map.once('render', this._update); + } + if (this._map.transform.renderWorldCopies) { + this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map.transform); + } + else { + this._lngLat = (_a = this._lngLat) === null || _a === void 0 ? void 0 : _a.wrap(); + } + this._flatPos = this._pos = this._map.project(this._lngLat)._add(this._offset); + if (this._map.terrain) { + // flat position is saved because smartWrap needs non-elevated points + this._flatPos = this._map.transform.locationPoint(this._lngLat)._add(this._offset); + } + let rotation = ''; + if (this._rotationAlignment === 'viewport' || this._rotationAlignment === 'auto') { + rotation = `rotateZ(${this._rotation}deg)`; + } + else if (this._rotationAlignment === 'map') { + rotation = `rotateZ(${this._rotation - this._map.getBearing()}deg)`; + } + let pitch = ''; + if (this._pitchAlignment === 'viewport' || this._pitchAlignment === 'auto') { + pitch = 'rotateX(0deg)'; + } + else if (this._pitchAlignment === 'map') { + pitch = `rotateX(${this._map.getPitch()}deg)`; + } + // because rounding the coordinates at every `move` event causes stuttered zooming + // we only round them when _update is called with `moveend` or when its called with + // no arguments (when the Marker is initialized or Marker#setLngLat is invoked). + if (!this._subpixelPositioning && (!e || e.type === 'moveend')) { + this._pos = this._pos.round(); + } + DOM.setTransform(this._element, `${anchorTranslate[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${pitch} ${rotation}`); + browser.frameAsync(new AbortController()).then(() => { + this._updateOpacity(e && e.type === 'moveend'); + }).catch(() => { }); + }; + this._onMove = (e) => { + if (!this._isDragging) { + const clickTolerance = this._clickTolerance || this._map._clickTolerance; + this._isDragging = e.point.dist(this._pointerdownPos) >= clickTolerance; + } + if (!this._isDragging) + return; + this._pos = e.point.sub(this._positionDelta); + this._lngLat = this._map.unproject(this._pos); + this.setLngLat(this._lngLat); + // suppress click event so that popups don't toggle on drag + this._element.style.pointerEvents = 'none'; + // make sure dragstart only fires on the first move event after mousedown. + // this can't be on mousedown because that event doesn't necessarily + // imply that a drag is about to happen. + if (this._state === 'pending') { + this._state = 'active'; + this.fire(new performance$1.k('dragstart')); + } + this.fire(new performance$1.k('drag')); + }; + this._onUp = () => { + // revert to normal pointer event handling + this._element.style.pointerEvents = 'auto'; + this._positionDelta = null; + this._pointerdownPos = null; + this._isDragging = false; + this._map.off('mousemove', this._onMove); + this._map.off('touchmove', this._onMove); + // only fire dragend if it was preceded by at least one drag event + if (this._state === 'active') { + this.fire(new performance$1.k('dragend')); + } + this._state = 'inactive'; + }; + this._addDragHandler = (e) => { + if (this._element.contains(e.originalEvent.target)) { + e.preventDefault(); + // We need to calculate the pixel distance between the click point + // and the marker position, with the offset accounted for. Then we + // can subtract this distance from the mousemove event's position + // to calculate the new marker position. + // If we don't do this, the marker 'jumps' to the click position + // creating a jarring UX effect. + this._positionDelta = e.point.sub(this._pos).add(this._offset); + this._pointerdownPos = e.point; + this._state = 'pending'; + this._map.on('mousemove', this._onMove); + this._map.on('touchmove', this._onMove); + this._map.once('mouseup', this._onUp); + this._map.once('touchend', this._onUp); + } + }; + this._anchor = options && options.anchor || 'center'; + this._color = options && options.color || '#3FB1CE'; + this._scale = options && options.scale || 1; + this._draggable = options && options.draggable || false; + this._clickTolerance = options && options.clickTolerance || 0; + this._subpixelPositioning = options && options.subpixelPositioning || false; + this._isDragging = false; + this._state = 'inactive'; + this._rotation = options && options.rotation || 0; + this._rotationAlignment = options && options.rotationAlignment || 'auto'; + this._pitchAlignment = options && options.pitchAlignment && options.pitchAlignment !== 'auto' ? options.pitchAlignment : this._rotationAlignment; + this.setOpacity(); // set default opacity + this.setOpacity(options === null || options === void 0 ? void 0 : options.opacity, options === null || options === void 0 ? void 0 : options.opacityWhenCovered); + if (!options || !options.element) { + this._defaultMarker = true; + this._element = DOM.create('div'); + // create default map marker SVG + const svg = DOM.createNS('http://www.w3.org/2000/svg', 'svg'); + const defaultHeight = 41; + const defaultWidth = 27; + svg.setAttributeNS(null, 'display', 'block'); + svg.setAttributeNS(null, 'height', `${defaultHeight}px`); + svg.setAttributeNS(null, 'width', `${defaultWidth}px`); + svg.setAttributeNS(null, 'viewBox', `0 0 ${defaultWidth} ${defaultHeight}`); + const markerLarge = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + markerLarge.setAttributeNS(null, 'stroke', 'none'); + markerLarge.setAttributeNS(null, 'stroke-width', '1'); + markerLarge.setAttributeNS(null, 'fill', 'none'); + markerLarge.setAttributeNS(null, 'fill-rule', 'evenodd'); + const page1 = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + page1.setAttributeNS(null, 'fill-rule', 'nonzero'); + const shadow = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + shadow.setAttributeNS(null, 'transform', 'translate(3.0, 29.0)'); + shadow.setAttributeNS(null, 'fill', '#000000'); + const ellipses = [ + { 'rx': '10.5', 'ry': '5.25002273' }, + { 'rx': '10.5', 'ry': '5.25002273' }, + { 'rx': '9.5', 'ry': '4.77275007' }, + { 'rx': '8.5', 'ry': '4.29549936' }, + { 'rx': '7.5', 'ry': '3.81822308' }, + { 'rx': '6.5', 'ry': '3.34094679' }, + { 'rx': '5.5', 'ry': '2.86367051' }, + { 'rx': '4.5', 'ry': '2.38636864' } + ]; + for (const data of ellipses) { + const ellipse = DOM.createNS('http://www.w3.org/2000/svg', 'ellipse'); + ellipse.setAttributeNS(null, 'opacity', '0.04'); + ellipse.setAttributeNS(null, 'cx', '10.5'); + ellipse.setAttributeNS(null, 'cy', '5.80029008'); + ellipse.setAttributeNS(null, 'rx', data['rx']); + ellipse.setAttributeNS(null, 'ry', data['ry']); + shadow.appendChild(ellipse); + } + const background = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + background.setAttributeNS(null, 'fill', this._color); + const bgPath = DOM.createNS('http://www.w3.org/2000/svg', 'path'); + 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'); + background.appendChild(bgPath); + const border = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + border.setAttributeNS(null, 'opacity', '0.25'); + border.setAttributeNS(null, 'fill', '#000000'); + const borderPath = DOM.createNS('http://www.w3.org/2000/svg', 'path'); + 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'); + border.appendChild(borderPath); + const maki = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + maki.setAttributeNS(null, 'transform', 'translate(6.0, 7.0)'); + maki.setAttributeNS(null, 'fill', '#FFFFFF'); + const circleContainer = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + circleContainer.setAttributeNS(null, 'transform', 'translate(8.0, 8.0)'); + const circle1 = DOM.createNS('http://www.w3.org/2000/svg', 'circle'); + circle1.setAttributeNS(null, 'fill', '#000000'); + circle1.setAttributeNS(null, 'opacity', '0.25'); + circle1.setAttributeNS(null, 'cx', '5.5'); + circle1.setAttributeNS(null, 'cy', '5.5'); + circle1.setAttributeNS(null, 'r', '5.4999962'); + const circle2 = DOM.createNS('http://www.w3.org/2000/svg', 'circle'); + circle2.setAttributeNS(null, 'fill', '#FFFFFF'); + circle2.setAttributeNS(null, 'cx', '5.5'); + circle2.setAttributeNS(null, 'cy', '5.5'); + circle2.setAttributeNS(null, 'r', '5.4999962'); + circleContainer.appendChild(circle1); + circleContainer.appendChild(circle2); + page1.appendChild(shadow); + page1.appendChild(background); + page1.appendChild(border); + page1.appendChild(maki); + page1.appendChild(circleContainer); + svg.appendChild(page1); + svg.setAttributeNS(null, 'height', `${defaultHeight * this._scale}px`); + svg.setAttributeNS(null, 'width', `${defaultWidth * this._scale}px`); + this._element.appendChild(svg); + // if no element and no offset option given apply an offset for the default marker + // the -14 as the y value of the default marker offset was determined as follows + // + // the marker tip is at the center of the shadow ellipse from the default svg + // 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)" + // offset to the svg center "height (41 / 2)" gives (29.0 + 5.80029008) - (41 / 2) and rounded for an integer pixel offset gives 14 + // negative is used to move the marker up from the center so the tip is at the Marker lngLat + this._offset = performance$1.P.convert(options && options.offset || [0, -14]); + } + else { + this._element = options.element; + this._offset = performance$1.P.convert(options && options.offset || [0, 0]); + } + this._element.classList.add('maplibregl-marker'); + this._element.addEventListener('dragstart', (e) => { + e.preventDefault(); + }); + this._element.addEventListener('mousedown', (e) => { + // prevent focusing on click + e.preventDefault(); + }); + applyAnchorClass(this._element, this._anchor, 'marker'); + if (options && options.className) { + for (const name of options.className.split(' ')) { + this._element.classList.add(name); + } + } + this._popup = null; + } + /** + * Attaches the `Marker` to a `Map` object. + * @param map - The MapLibre GL JS map to add the marker to. + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([30.5, 50.5]) + * .addTo(map); // add the marker to the map + * ``` + */ + addTo(map) { + this.remove(); + this._map = map; + this._element.setAttribute('aria-label', map._getUIString('Marker.Title')); + map.getCanvasContainer().appendChild(this._element); + map.on('move', this._update); + map.on('moveend', this._update); + map.on('terrain', this._update); + this.setDraggable(this._draggable); + this._update(); + // If we attached the `click` listener to the marker element, the popup + // would close once the event propagated to `map` due to the + // `Popup#_onClickClose` listener. + this._map.on('click', this._onMapClick); + return this; + } + /** + * Removes the marker from a map + * @example + * ```ts + * let marker = new Marker().addTo(map); + * marker.remove(); + * ``` + */ + remove() { + if (this._opacityTimeout) { + clearTimeout(this._opacityTimeout); + delete this._opacityTimeout; + } + if (this._map) { + this._map.off('click', this._onMapClick); + this._map.off('move', this._update); + this._map.off('moveend', this._update); + this._map.off('terrain', this._update); + this._map.off('mousedown', this._addDragHandler); + this._map.off('touchstart', this._addDragHandler); + this._map.off('mouseup', this._onUp); + this._map.off('touchend', this._onUp); + this._map.off('mousemove', this._onMove); + this._map.off('touchmove', this._onMove); + delete this._map; + } + DOM.remove(this._element); + if (this._popup) + this._popup.remove(); + return this; + } + /** + * Get the marker's geographical location. + * + * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously + * set by `setLngLat` because `Marker` wraps the anchor longitude across copies of the world to keep + * the marker on screen. + * + * @returns A {@link LngLat} describing the marker's location. + * @example + * ```ts + * // Store the marker's longitude and latitude coordinates in a variable + * let lngLat = marker.getLngLat(); + * // Print the marker's longitude and latitude values in the console + * console.log('Longitude: ' + lngLat.lng + ', Latitude: ' + lngLat.lat ) + * ``` + * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/) + */ + getLngLat() { + return this._lngLat; + } + /** + * Set the marker's geographical position and move it. + * @param lnglat - A {@link LngLat} describing where the marker should be located. + * @example + * Create a new marker, set the longitude and latitude, and add it to the map + * ```ts + * new Marker() + * .setLngLat([-65.017, -16.457]) + * .addTo(map); + * ``` + * @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/custom-marker-icons/) + * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/) + */ + setLngLat(lnglat) { + this._lngLat = performance$1.N.convert(lnglat); + this._pos = null; + if (this._popup) + this._popup.setLngLat(this._lngLat); + this._update(); + return this; + } + /** + * Returns the `Marker`'s HTML element. + * @returns element + */ + getElement() { + return this._element; + } + /** + * Binds a {@link Popup} to the {@link Marker}. + * @param popup - An instance of the {@link Popup} class. If undefined or null, any popup + * set on this {@link Marker} instance is unset. + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([0, 0]) + * .setPopup(new Popup().setHTML("

Hello World!

")) // add popup + * .addTo(map); + * ``` + * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/) + */ + setPopup(popup) { + if (this._popup) { + this._popup.remove(); + this._popup = null; + this._element.removeEventListener('keypress', this._onKeyPress); + if (!this._originalTabIndex) { + this._element.removeAttribute('tabindex'); + } + } + if (popup) { + if (!('offset' in popup.options)) { + const markerHeight = 41 - (5.8 / 2); + const markerRadius = 13.5; + const linearOffset = Math.abs(markerRadius) / Math.SQRT2; + popup.options.offset = this._defaultMarker ? { + 'top': [0, 0], + 'top-left': [0, 0], + 'top-right': [0, 0], + 'bottom': [0, -markerHeight], + 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + 'left': [markerRadius, (markerHeight - markerRadius) * -1], + 'right': [-markerRadius, (markerHeight - markerRadius) * -1] + } : this._offset; + } + this._popup = popup; + this._originalTabIndex = this._element.getAttribute('tabindex'); + if (!this._originalTabIndex) { + this._element.setAttribute('tabindex', '0'); + } + this._element.addEventListener('keypress', this._onKeyPress); + } + return this; + } + /** + * Set the option to allow subpixel positioning of the marker by passing a boolean + * + * @param value - when set to `true`, subpixel positioning is enabled for the marker. + * + * @example + * ```ts + * let marker = new Marker() + * marker.setSubpixelPositioning(true); + * ``` + */ + setSubpixelPositioning(value) { + this._subpixelPositioning = value; + return this; + } + /** + * Returns the {@link Popup} instance that is bound to the {@link Marker}. + * @returns popup + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([0, 0]) + * .setPopup(new Popup().setHTML("

Hello World!

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

Hello World!

")) + * .addTo(map); + * + * marker.togglePopup(); // toggle popup open or closed + * ``` + */ + togglePopup() { + const popup = this._popup; + if (this._element.style.opacity === this._opacityWhenCovered) + return this; + if (!popup) + return this; + else if (popup.isOpen()) + popup.remove(); + else { + popup.setLngLat(this._lngLat); + popup.addTo(this._map); + } + return this; + } + _updateOpacity(force = false) { + var _a, _b; + const terrain = (_a = this._map) === null || _a === void 0 ? void 0 : _a.terrain; + if (!terrain) { + if (this._element.style.opacity !== this._opacity) { + this._element.style.opacity = this._opacity; + } + return; + } + if (force) { + this._opacityTimeout = null; + } + else { + if (this._opacityTimeout) { + return; + } + this._opacityTimeout = setTimeout(() => { + this._opacityTimeout = null; + }, 100); + } + const map = this._map; + // Read depth framebuffer, getting position of terrain in line of sight to marker + const terrainDistance = map.terrain.depthAtPoint(this._pos); + // Transform marker position to clip space + const elevation = map.terrain.getElevationForLngLatZoom(this._lngLat, map.transform.tileZoom); + const markerDistance = map.transform.lngLatToCameraDepth(this._lngLat, elevation); + const forgiveness = .006; + if (markerDistance - terrainDistance < forgiveness) { + this._element.style.opacity = this._opacity; + return; + } + // If the base is obscured, use the offset to check if the marker's center is obscured. + const metersToCenter = -this._offset.y / map.transform._pixelPerMeter; + const elevationToCenter = Math.sin(map.getPitch() * Math.PI / 180) * metersToCenter; + const terrainDistanceCenter = map.terrain.depthAtPoint(new performance$1.P(this._pos.x, this._pos.y - this._offset.y)); + const markerDistanceCenter = map.transform.lngLatToCameraDepth(this._lngLat, elevation + elevationToCenter); + // Display at full opacity if center is visible. + const centerIsInvisible = markerDistanceCenter - terrainDistanceCenter > forgiveness; + if (((_b = this._popup) === null || _b === void 0 ? void 0 : _b.isOpen()) && centerIsInvisible) + this._popup.remove(); + this._element.style.opacity = centerIsInvisible ? this._opacityWhenCovered : this._opacity; + } + /** + * Get the marker's offset. + * @returns The marker's screen coordinates in pixels. + */ + getOffset() { + return this._offset; + } + /** + * Sets the offset of the marker + * @param offset - The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up. + */ + setOffset(offset) { + this._offset = performance$1.P.convert(offset); + this._update(); + return this; + } + /** + * Adds a CSS class to the marker element. + * + * @param className - on-empty string with CSS class name to add to marker element + * + * @example + * ``` + * let marker = new Marker() + * marker.addClassName('some-class') + * ``` + */ + addClassName(className) { + this._element.classList.add(className); + } + /** + * Removes a CSS class from the marker element. + * + * @param className - Non-empty string with CSS class name to remove from marker element + * + * @example + * ```ts + * let marker = new Marker() + * marker.removeClassName('some-class') + * ``` + */ + removeClassName(className) { + this._element.classList.remove(className); + } + /** + * Add or remove the given CSS class on the marker element, depending on whether the element currently has that class. + * + * @param className - Non-empty string with CSS class name to add/remove + * + * @returns if the class was removed return false, if class was added, then return true + * + * @example + * ```ts + * let marker = new Marker() + * marker.toggleClassName('toggleClass') + * ``` + */ + toggleClassName(className) { + return this._element.classList.toggle(className); + } + /** + * Sets the `draggable` property and functionality of the marker + * @param shouldBeDraggable - Turns drag functionality on/off + */ + setDraggable(shouldBeDraggable) { + this._draggable = !!shouldBeDraggable; // convert possible undefined value to false + // handle case where map may not exist yet + // e.g. when setDraggable is called before addTo + if (this._map) { + if (shouldBeDraggable) { + this._map.on('mousedown', this._addDragHandler); + this._map.on('touchstart', this._addDragHandler); + } + else { + this._map.off('mousedown', this._addDragHandler); + this._map.off('touchstart', this._addDragHandler); + } + } + return this; + } + /** + * Returns true if the marker can be dragged + * @returns True if the marker is draggable. + */ + isDraggable() { + return this._draggable; + } + /** + * Sets the `rotation` property of the marker. + * @param rotation - The rotation angle of the marker (clockwise, in degrees), relative to its respective {@link Marker#setRotationAlignment} setting. + */ + setRotation(rotation) { + this._rotation = rotation || 0; + this._update(); + return this; + } + /** + * Returns the current rotation angle of the marker (in degrees). + * @returns The current rotation angle of the marker. + */ + getRotation() { + return this._rotation; + } + /** + * Sets the `rotationAlignment` property of the marker. + * @param alignment - Sets the `rotationAlignment` property of the marker. defaults to 'auto' + */ + setRotationAlignment(alignment) { + this._rotationAlignment = alignment || 'auto'; + this._update(); + return this; + } + /** + * Returns the current `rotationAlignment` property of the marker. + * @returns The current rotational alignment of the marker. + */ + getRotationAlignment() { + return this._rotationAlignment; + } + /** + * Sets the `pitchAlignment` property of the marker. + * @param alignment - Sets the `pitchAlignment` property of the marker. If alignment is 'auto', it will automatically match `rotationAlignment`. + */ + setPitchAlignment(alignment) { + this._pitchAlignment = alignment && alignment !== 'auto' ? alignment : this._rotationAlignment; + this._update(); + return this; + } + /** + * Returns the current `pitchAlignment` property of the marker. + * @returns The current pitch alignment of the marker in degrees. + */ + getPitchAlignment() { + return this._pitchAlignment; + } + /** + * Sets the `opacity` and `opacityWhenCovered` properties of the marker. + * When called without arguments, resets opacity and opacityWhenCovered to defaults + * @param opacity - Sets the `opacity` property of the marker. + * @param opacityWhenCovered - Sets the `opacityWhenCovered` property of the marker. + */ + setOpacity(opacity, opacityWhenCovered) { + if (opacity === undefined && opacityWhenCovered === undefined) { + this._opacity = '1'; + this._opacityWhenCovered = '0.2'; + } + if (opacity !== undefined) { + this._opacity = opacity; + } + if (opacityWhenCovered !== undefined) { + this._opacityWhenCovered = opacityWhenCovered; + } + if (this._map) { + this._updateOpacity(true); + } + return this; + } +} + +const defaultOptions$2 = { + positionOptions: { + enableHighAccuracy: false, + maximumAge: 0, + timeout: 6000 /* 6 sec */ + }, + fitBoundsOptions: { + maxZoom: 15 + }, + trackUserLocation: false, + showAccuracyCircle: true, + showUserLocation: true +}; +let numberOfWatches = 0; +let noTimeout = false; +/** + * A `GeolocateControl` control provides a button that uses the browser's geolocation + * API to locate the user on the map. + * + * Not all browsers support geolocation, + * and some users may disable the feature. Geolocation support for modern + * browsers including Chrome requires sites to be served over HTTPS. If + * geolocation support is not available, the `GeolocateControl` will show + * as disabled. + * + * The zoom level applied will depend on the accuracy of the geolocation provided by the device. + * + * 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: + * * 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. + * * passive - the user's location dot automatically updates, but the map's camera does not. Occurs upon the user initiating a map movement. + * * disabled - occurs if Geolocation is not available, disabled or denied. + * + * These interaction states can't be controlled programmatically, rather they are set based on user interactions. + * + * ## State Diagram + * ![GeolocateControl state diagram](https://github.com/maplibre/maplibre-gl-js/assets/3269297/78e720e5-d781-4da8-9803-a7a0e6aaaa9f) + * + * @group Markers and Controls + * + * @example + * ```ts + * map.addControl(new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * })); + * ``` + * @see [Locate the user](https://maplibre.org/maplibre-gl-js/docs/examples/locate-user/) + * + * ## Events + * + * **Event** `trackuserlocationend` of type {@link Event} will be fired when the `GeolocateControl` 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. + * + * **Event** `trackuserlocationstart` of type {@link Event} will be fired when the `GeolocateControl` 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). + * + * **Event** `userlocationlostfocus` of type {@link Event} will be fired when the `GeolocateControl` 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. + * + * **Event** `userlocationfocus` of type {@link Event} will be fired when the `GeolocateControl` changes to the active lock state, which happens upon 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. + * + * **Event** `geolocate` of type {@link Event} will be fired on each Geolocation API position update which returned as success. + * `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). + * + * **Event** `error` of type {@link Event} will be fired on each Geolocation API position update which returned as an error. + * `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). + * + * **Event** `outofmaxbounds` of type {@link Event} will be fired on each Geolocation API position update which returned as success but user position is out of map `maxBounds`. + * `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). + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a trackuserlocationend event occurs. + * geolocate.on('trackuserlocationend', () => { + * console.log('A trackuserlocationend event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a trackuserlocationstart event occurs. + * geolocate.on('trackuserlocationstart', () => { + * console.log('A trackuserlocationstart event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an userlocationlostfocus event occurs. + * geolocate.on('userlocationlostfocus', function() { + * console.log('An userlocationlostfocus event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an userlocationfocus event occurs. + * geolocate.on('userlocationfocus', function() { + * console.log('An userlocationfocus event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a geolocate event occurs. + * geolocate.on('geolocate', () => { + * console.log('A geolocate event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an error event occurs. + * geolocate.on('error', () => { + * console.log('An error event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an outofmaxbounds event occurs. + * geolocate.on('outofmaxbounds', () => { + * console.log('An outofmaxbounds event has occurred.') + * }); + * ``` + */ +class GeolocateControl extends performance$1.E { + /** + * @param options - the control's options + */ + constructor(options) { + super(); + /** + * When the Geolocation API returns a new location, update the `GeolocateControl`. + * + * @param position - the Geolocation API Position + */ + this._onSuccess = (position) => { + if (!this._map) { + // control has since been removed + return; + } + if (this._isOutOfMapMaxBounds(position)) { + this._setErrorState(); + this.fire(new performance$1.k('outofmaxbounds', position)); + this._updateMarker(); + this._finish(); + return; + } + if (this.options.trackUserLocation) { + // keep a record of the position so that if the state is BACKGROUND and the user + // clicks the button, we can move to ACTIVE_LOCK immediately without waiting for + // watchPosition to trigger _onSuccess + this._lastKnownPosition = position; + switch (this._watchState) { + case 'WAITING_ACTIVE': + case 'ACTIVE_LOCK': + case 'ACTIVE_ERROR': + this._watchState = 'ACTIVE_LOCK'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active'); + break; + case 'BACKGROUND': + case 'BACKGROUND_ERROR': + this._watchState = 'BACKGROUND'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background'); + break; + default: + throw new Error(`Unexpected watchState ${this._watchState}`); + } + } + // if showUserLocation and the watch state isn't off then update the marker location + if (this.options.showUserLocation && this._watchState !== 'OFF') { + this._updateMarker(position); + } + // if in normal mode (not watch mode), or if in watch mode and the state is active watch + // then update the camera + if (!this.options.trackUserLocation || this._watchState === 'ACTIVE_LOCK') { + this._updateCamera(position); + } + if (this.options.showUserLocation) { + this._dotElement.classList.remove('maplibregl-user-location-dot-stale'); + } + this.fire(new performance$1.k('geolocate', position)); + this._finish(); + }; + /** + * Update the camera location to center on the current position + * + * @param position - the Geolocation API Position + */ + this._updateCamera = (position) => { + const center = new performance$1.N(position.coords.longitude, position.coords.latitude); + const radius = position.coords.accuracy; + const bearing = this._map.getBearing(); + const options = performance$1.e({ bearing }, this.options.fitBoundsOptions); + const newBounds = LngLatBounds.fromLngLat(center, radius); + this._map.fitBounds(newBounds, options, { + geolocateSource: true // tag this camera change so it won't cause the control to change to background state + }); + }; + /** + * Update the user location dot Marker to the current position + * + * @param position - the Geolocation API Position + */ + this._updateMarker = (position) => { + if (position) { + const center = new performance$1.N(position.coords.longitude, position.coords.latitude); + this._accuracyCircleMarker.setLngLat(center).addTo(this._map); + this._userLocationDotMarker.setLngLat(center).addTo(this._map); + this._accuracy = position.coords.accuracy; + if (this.options.showUserLocation && this.options.showAccuracyCircle) { + this._updateCircleRadius(); + } + } + else { + this._userLocationDotMarker.remove(); + this._accuracyCircleMarker.remove(); + } + }; + this._onZoom = () => { + if (this.options.showUserLocation && this.options.showAccuracyCircle) { + this._updateCircleRadius(); + } + }; + this._onError = (error) => { + if (!this._map) { + // control has since been removed + return; + } + if (this.options.trackUserLocation) { + if (error.code === 1) { + // PERMISSION_DENIED + this._watchState = 'OFF'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error'); + this._geolocateButton.disabled = true; + const title = this._map._getUIString('GeolocateControl.LocationNotAvailable'); + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + if (this._geolocationWatchID !== undefined) { + this._clearWatch(); + } + } + else if (error.code === 3 && noTimeout) { + // this represents a forced error state + // this was triggered to force immediate geolocation when a watch is already present + // see https://github.com/mapbox/mapbox-gl-js/issues/8214 + // and https://w3c.github.io/geolocation-api/#example-5-forcing-the-user-agent-to-return-a-fresh-cached-position + return; + } + else { + this._setErrorState(); + } + } + if (this._watchState !== 'OFF' && this.options.showUserLocation) { + this._dotElement.classList.add('maplibregl-user-location-dot-stale'); + } + this.fire(new performance$1.k('error', error)); + this._finish(); + }; + this._finish = () => { + if (this._timeoutId) { + clearTimeout(this._timeoutId); + } + this._timeoutId = undefined; + }; + this._setupUI = () => { + // the control could have been removed before reaching here + if (!this._map) { + return; + } + this._container.addEventListener('contextmenu', (e) => e.preventDefault()); + this._geolocateButton = DOM.create('button', 'maplibregl-ctrl-geolocate', this._container); + DOM.create('span', 'maplibregl-ctrl-icon', this._geolocateButton).setAttribute('aria-hidden', 'true'); + this._geolocateButton.type = 'button'; + this._geolocateButton.disabled = true; + }; + this._finishSetupUI = (supported) => { + // this method is called asynchronously during onAdd + if (!this._map) { + // control has since been removed + return; + } + if (supported === false) { + performance$1.w('Geolocation support is not available so the GeolocateControl will be disabled.'); + const title = this._map._getUIString('GeolocateControl.LocationNotAvailable'); + this._geolocateButton.disabled = true; + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + } + else { + const title = this._map._getUIString('GeolocateControl.FindMyLocation'); + this._geolocateButton.disabled = false; + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + } + if (this.options.trackUserLocation) { + this._geolocateButton.setAttribute('aria-pressed', 'false'); + this._watchState = 'OFF'; + } + // when showUserLocation is enabled, keep the Geolocate button disabled until the device location marker is setup on the map + if (this.options.showUserLocation) { + this._dotElement = DOM.create('div', 'maplibregl-user-location-dot'); + this._userLocationDotMarker = new Marker({ element: this._dotElement }); + this._circleElement = DOM.create('div', 'maplibregl-user-location-accuracy-circle'); + this._accuracyCircleMarker = new Marker({ element: this._circleElement, pitchAlignment: 'map' }); + if (this.options.trackUserLocation) + this._watchState = 'OFF'; + this._map.on('zoom', this._onZoom); + } + this._geolocateButton.addEventListener('click', () => this.trigger()); + this._setup = true; + // when the camera is changed (and it's not as a result of the Geolocation Control) change + // the watch mode to background watch, so that the marker is updated but not the camera. + if (this.options.trackUserLocation) { + this._map.on('movestart', (event) => { + const fromResize = event.originalEvent && event.originalEvent.type === 'resize'; + if (!event.geolocateSource && this._watchState === 'ACTIVE_LOCK' && !fromResize) { + this._watchState = 'BACKGROUND'; + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this.fire(new performance$1.k('trackuserlocationend')); + this.fire(new performance$1.k('userlocationlostfocus')); + } + }); + } + }; + this.options = performance$1.e({}, defaultOptions$2, options); + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group'); + this._setupUI(); + checkGeolocationSupport().then((supported) => this._finishSetupUI(supported)); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + // clear the geolocation watch if exists + if (this._geolocationWatchID !== undefined) { + window.navigator.geolocation.clearWatch(this._geolocationWatchID); + this._geolocationWatchID = undefined; + } + // clear the markers from the map + if (this.options.showUserLocation && this._userLocationDotMarker) { + this._userLocationDotMarker.remove(); + } + if (this.options.showAccuracyCircle && this._accuracyCircleMarker) { + this._accuracyCircleMarker.remove(); + } + DOM.remove(this._container); + this._map.off('zoom', this._onZoom); + this._map = undefined; + numberOfWatches = 0; + noTimeout = false; + } + /** + * Check if the Geolocation API Position is outside the map's `maxBounds`. + * + * @param position - the Geolocation API Position + * @returns `true` if position is outside the map's `maxBounds`, otherwise returns `false`. + */ + _isOutOfMapMaxBounds(position) { + const bounds = this._map.getMaxBounds(); + const coordinates = position.coords; + return bounds && (coordinates.longitude < bounds.getWest() || + coordinates.longitude > bounds.getEast() || + coordinates.latitude < bounds.getSouth() || + coordinates.latitude > bounds.getNorth()); + } + _setErrorState() { + switch (this._watchState) { + case 'WAITING_ACTIVE': + this._watchState = 'ACTIVE_ERROR'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active-error'); + break; + case 'ACTIVE_LOCK': + this._watchState = 'ACTIVE_ERROR'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting'); + // turn marker grey + break; + case 'BACKGROUND': + this._watchState = 'BACKGROUND_ERROR'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background-error'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting'); + // turn marker grey + break; + case 'ACTIVE_ERROR': + break; + default: + throw new Error(`Unexpected watchState ${this._watchState}`); + } + } + _updateCircleRadius() { + const bounds = this._map.getBounds(); + const southEastPoint = bounds.getSouthEast(); + const northEastPoint = bounds.getNorthEast(); + const mapHeightInMeters = southEastPoint.distanceTo(northEastPoint); + const mapHeightInPixels = this._map._container.clientHeight; + const circleDiameter = Math.ceil(2 * (this._accuracy / (mapHeightInMeters / mapHeightInPixels))); + this._circleElement.style.width = `${circleDiameter}px`; + this._circleElement.style.height = `${circleDiameter}px`; + } + /** + * Programmatically request and move the map to the user's location. + * + * @returns `false` if called before control was added to a map, otherwise returns `true`. + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * map.on('load', () => { + * geolocate.trigger(); + * }); + * ``` + */ + trigger() { + if (!this._setup) { + performance$1.w('Geolocate control triggered before added to a map'); + return false; + } + if (this.options.trackUserLocation) { + // update watchState and do any outgoing state cleanup + switch (this._watchState) { + case 'OFF': + // turn on the Geolocate Control + this._watchState = 'WAITING_ACTIVE'; + this.fire(new performance$1.k('trackuserlocationstart')); + break; + case 'WAITING_ACTIVE': + case 'ACTIVE_LOCK': + case 'ACTIVE_ERROR': + case 'BACKGROUND_ERROR': + // turn off the Geolocate Control + numberOfWatches--; + noTimeout = false; + this._watchState = 'OFF'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background'); + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error'); + this.fire(new performance$1.k('trackuserlocationend')); + break; + case 'BACKGROUND': + this._watchState = 'ACTIVE_LOCK'; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background'); + // set camera to last known location + if (this._lastKnownPosition) + this._updateCamera(this._lastKnownPosition); + this.fire(new performance$1.k('trackuserlocationstart')); + this.fire(new performance$1.k('userlocationfocus')); + break; + default: + throw new Error(`Unexpected watchState ${this._watchState}`); + } + // incoming state setup + switch (this._watchState) { + case 'WAITING_ACTIVE': + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active'); + break; + case 'ACTIVE_LOCK': + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active'); + break; + case 'OFF': + break; + default: + throw new Error(`Unexpected watchState ${this._watchState}`); + } + // manage geolocation.watchPosition / geolocation.clearWatch + if (this._watchState === 'OFF' && this._geolocationWatchID !== undefined) { + // clear watchPosition as we've changed to an OFF state + this._clearWatch(); + } + else if (this._geolocationWatchID === undefined) { + // enable watchPosition since watchState is not OFF and there is no watchPosition already running + this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.setAttribute('aria-pressed', 'true'); + numberOfWatches++; + let positionOptions; + if (numberOfWatches > 1) { + positionOptions = { maximumAge: 600000, timeout: 0 }; + noTimeout = true; + } + else { + positionOptions = this.options.positionOptions; + noTimeout = false; + } + this._geolocationWatchID = window.navigator.geolocation.watchPosition(this._onSuccess, this._onError, positionOptions); + } + } + else { + window.navigator.geolocation.getCurrentPosition(this._onSuccess, this._onError, this.options.positionOptions); + // This timeout ensures that we still call finish() even if + // the user declines to share their location in Firefox + this._timeoutId = setTimeout(this._finish, 10000 /* 10sec */); + } + return true; + } + _clearWatch() { + window.navigator.geolocation.clearWatch(this._geolocationWatchID); + this._geolocationWatchID = undefined; + this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting'); + this._geolocateButton.setAttribute('aria-pressed', 'false'); + if (this.options.showUserLocation) { + this._updateMarker(null); + } + } +} + +const defaultOptions$1 = { + maxWidth: 100, + unit: 'metric' +}; +/** + * A `ScaleControl` control displays the ratio of a distance on the map to the corresponding distance on the ground. + * + * @group Markers and Controls + * + * @example + * ```ts + * let scale = new ScaleControl({ + * maxWidth: 80, + * unit: 'imperial' + * }); + * map.addControl(scale); + * + * scale.setUnit('metric'); + * ``` + */ +class ScaleControl { + /** + * @param options - the control's options + */ + constructor(options) { + this._onMove = () => { + updateScale(this._map, this._container, this.options); + }; + /** + * Set the scale's unit of the distance + * + * @param unit - Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`). + */ + this.setUnit = (unit) => { + this.options.unit = unit; + updateScale(this._map, this._container, this.options); + }; + this.options = Object.assign(Object.assign({}, defaultOptions$1), options); + } + getDefaultPosition() { + return 'bottom-left'; + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-scale', map.getContainer()); + this._map.on('move', this._onMove); + this._onMove(); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + this._map.off('move', this._onMove); + this._map = undefined; + } +} +function updateScale(map, container, options) { + // A horizontal scale is imagined to be present at center of the map + // container with maximum length (Default) as 100px. + // Using spherical law of cosines approximation, the real distance is + // found between the two coordinates. + const maxWidth = options && options.maxWidth || 100; + const y = map._container.clientHeight / 2; + const left = map.unproject([0, y]); + const right = map.unproject([maxWidth, y]); + const maxMeters = left.distanceTo(right); + // The real distance corresponding to 100px scale length is rounded off to + // near pretty number and the scale length for the same is found out. + // Default unit of the scale is based on User's locale. + if (options && options.unit === 'imperial') { + const maxFeet = 3.2808 * maxMeters; + if (maxFeet > 5280) { + const maxMiles = maxFeet / 5280; + setScale(container, maxWidth, maxMiles, map._getUIString('ScaleControl.Miles')); + } + else { + setScale(container, maxWidth, maxFeet, map._getUIString('ScaleControl.Feet')); + } + } + else if (options && options.unit === 'nautical') { + const maxNauticals = maxMeters / 1852; + setScale(container, maxWidth, maxNauticals, map._getUIString('ScaleControl.NauticalMiles')); + } + else if (maxMeters >= 1000) { + setScale(container, maxWidth, maxMeters / 1000, map._getUIString('ScaleControl.Kilometers')); + } + else { + setScale(container, maxWidth, maxMeters, map._getUIString('ScaleControl.Meters')); + } +} +function setScale(container, maxWidth, maxDistance, unit) { + const distance = getRoundNum(maxDistance); + const ratio = distance / maxDistance; + container.style.width = `${maxWidth * ratio}px`; + container.innerHTML = `${distance} ${unit}`; +} +function getDecimalRoundNum(d) { + const multiplier = Math.pow(10, Math.ceil(-Math.log(d) / Math.LN10)); + return Math.round(d * multiplier) / multiplier; +} +function getRoundNum(num) { + const pow10 = Math.pow(10, (`${Math.floor(num)}`).length - 1); + let d = num / pow10; + d = d >= 10 ? 10 : + d >= 5 ? 5 : + d >= 3 ? 3 : + d >= 2 ? 2 : + d >= 1 ? 1 : getDecimalRoundNum(d); + return pow10 * d; +} + +/** + * A `FullscreenControl` control contains a button for toggling the map in and out of fullscreen mode. + * When [requestFullscreen](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen) is not supported, fullscreen is handled via CSS properties. + * The map's `cooperativeGestures` option is temporarily disabled while the map + * is in fullscreen mode, and is restored when the map exist fullscreen mode. + * + * @group Markers and Controls + * @param options - the full screen control options + * + * @example + * ```ts + * map.addControl(new FullscreenControl({container: document.querySelector('body')})); + * ``` + * @see [View a fullscreen map](https://maplibre.org/maplibre-gl-js/docs/examples/fullscreen/) + * + * ## Events + * + * **Event** `fullscreenstart` of type {@link Event} will be fired when fullscreen mode has started. + * + * **Event** `fullscreenend` of type {@link Event} will be fired when fullscreen mode has ended. + */ +class FullscreenControl extends performance$1.E { + /** + * @param options - the control's options + */ + constructor(options = {}) { + super(); + this._onFullscreenChange = () => { + var _a; + let fullscreenElement = window.document.fullscreenElement || + window.document.mozFullScreenElement || + window.document.webkitFullscreenElement || + window.document.msFullscreenElement; + while ((_a = fullscreenElement === null || fullscreenElement === void 0 ? void 0 : fullscreenElement.shadowRoot) === null || _a === void 0 ? void 0 : _a.fullscreenElement) { + fullscreenElement = fullscreenElement.shadowRoot.fullscreenElement; + } + if ((fullscreenElement === this._container) !== this._fullscreen) { + this._handleFullscreenChange(); + } + }; + this._onClickFullscreen = () => { + if (this._isFullscreen()) { + this._exitFullscreen(); + } + else { + this._requestFullscreen(); + } + }; + this._fullscreen = false; + if (options && options.container) { + if (options.container instanceof HTMLElement) { + this._container = options.container; + } + else { + performance$1.w('Full screen control \'container\' must be a DOM element.'); + } + } + if ('onfullscreenchange' in document) { + this._fullscreenchange = 'fullscreenchange'; + } + else if ('onmozfullscreenchange' in document) { + this._fullscreenchange = 'mozfullscreenchange'; + } + else if ('onwebkitfullscreenchange' in document) { + this._fullscreenchange = 'webkitfullscreenchange'; + } + else if ('onmsfullscreenchange' in document) { + this._fullscreenchange = 'MSFullscreenChange'; + } + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + if (!this._container) + this._container = this._map.getContainer(); + this._controlContainer = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group'); + this._setupUI(); + return this._controlContainer; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._controlContainer); + this._map = null; + window.document.removeEventListener(this._fullscreenchange, this._onFullscreenChange); + } + _setupUI() { + const button = this._fullscreenButton = DOM.create('button', (('maplibregl-ctrl-fullscreen')), this._controlContainer); + DOM.create('span', 'maplibregl-ctrl-icon', button).setAttribute('aria-hidden', 'true'); + button.type = 'button'; + this._updateTitle(); + this._fullscreenButton.addEventListener('click', this._onClickFullscreen); + window.document.addEventListener(this._fullscreenchange, this._onFullscreenChange); + } + _updateTitle() { + const title = this._getTitle(); + this._fullscreenButton.setAttribute('aria-label', title); + this._fullscreenButton.title = title; + } + _getTitle() { + return this._map._getUIString(this._isFullscreen() ? 'FullscreenControl.Exit' : 'FullscreenControl.Enter'); + } + _isFullscreen() { + return this._fullscreen; + } + _handleFullscreenChange() { + this._fullscreen = !this._fullscreen; + this._fullscreenButton.classList.toggle('maplibregl-ctrl-shrink'); + this._fullscreenButton.classList.toggle('maplibregl-ctrl-fullscreen'); + this._updateTitle(); + if (this._fullscreen) { + this.fire(new performance$1.k('fullscreenstart')); + this._prevCooperativeGesturesEnabled = this._map.cooperativeGestures.isEnabled(); + this._map.cooperativeGestures.disable(); + } + else { + this.fire(new performance$1.k('fullscreenend')); + if (this._prevCooperativeGesturesEnabled) { + this._map.cooperativeGestures.enable(); + } + } + } + _exitFullscreen() { + if (window.document.exitFullscreen) { + window.document.exitFullscreen(); + } + else if (window.document.mozCancelFullScreen) { + window.document.mozCancelFullScreen(); + } + else if (window.document.msExitFullscreen) { + window.document.msExitFullscreen(); + } + else if (window.document.webkitCancelFullScreen) { + window.document.webkitCancelFullScreen(); + } + else { + this._togglePseudoFullScreen(); + } + } + _requestFullscreen() { + if (this._container.requestFullscreen) { + this._container.requestFullscreen(); + } + else if (this._container.mozRequestFullScreen) { + this._container.mozRequestFullScreen(); + } + else if (this._container.msRequestFullscreen) { + this._container.msRequestFullscreen(); + } + else if (this._container.webkitRequestFullscreen) { + this._container.webkitRequestFullscreen(); + } + else { + this._togglePseudoFullScreen(); + } + } + _togglePseudoFullScreen() { + this._container.classList.toggle('maplibregl-pseudo-fullscreen'); + this._handleFullscreenChange(); + this._map.resize(); + } +} + +/** + * A `TerrainControl` control contains a button for turning the terrain on and off. + * + * @group Markers and Controls + * + * @example + * ```ts + * let map = new Map({TerrainControl: false}) + * .addControl(new TerrainControl({ + * source: "terrain" + * })); + * ``` + */ +class TerrainControl { + /** + * @param options - the control's options + */ + constructor(options) { + this._toggleTerrain = () => { + if (this._map.getTerrain()) { + this._map.setTerrain(null); + } + else { + this._map.setTerrain(this.options); + } + this._updateTerrainIcon(); + }; + this._updateTerrainIcon = () => { + this._terrainButton.classList.remove('maplibregl-ctrl-terrain'); + this._terrainButton.classList.remove('maplibregl-ctrl-terrain-enabled'); + if (this._map.terrain) { + this._terrainButton.classList.add('maplibregl-ctrl-terrain-enabled'); + this._terrainButton.title = this._map._getUIString('TerrainControl.Disable'); + } + else { + this._terrainButton.classList.add('maplibregl-ctrl-terrain'); + this._terrainButton.title = this._map._getUIString('TerrainControl.Enable'); + } + }; + this.options = options; + } + /** {@inheritDoc IControl.onAdd} */ + onAdd(map) { + this._map = map; + this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group'); + this._terrainButton = DOM.create('button', 'maplibregl-ctrl-terrain', this._container); + DOM.create('span', 'maplibregl-ctrl-icon', this._terrainButton).setAttribute('aria-hidden', 'true'); + this._terrainButton.type = 'button'; + this._terrainButton.addEventListener('click', this._toggleTerrain); + this._updateTerrainIcon(); + this._map.on('terrain', this._updateTerrainIcon); + return this._container; + } + /** {@inheritDoc IControl.onRemove} */ + onRemove() { + DOM.remove(this._container); + this._map.off('terrain', this._updateTerrainIcon); + this._map = undefined; + } +} + +const defaultOptions = { + closeButton: true, + closeOnClick: true, + focusAfterOpen: true, + className: '', + maxWidth: '240px', + subpixelPositioning: false +}; +const focusQuerySelector = [ + 'a[href]', + '[tabindex]:not([tabindex=\'-1\'])', + '[contenteditable]:not([contenteditable=\'false\'])', + 'button:not([disabled])', + 'input:not([disabled])', + 'select:not([disabled])', + 'textarea:not([disabled])', +].join(', '); +/** + * A popup component. + * + * @group Markers and Controls + * + * + * @example + * Create a popup + * ```ts + * let popup = new Popup(); + * // Set an event listener that will fire + * // any time the popup is opened + * popup.on('open', () => { + * console.log('popup was opened'); + * }); + * ``` + * + * @example + * Create a popup + * ```ts + * let popup = new Popup(); + * // Set an event listener that will fire + * // any time the popup is closed + * popup.on('close', () => { + * console.log('popup was closed'); + * }); + * ``` + * + * @example + * ```ts + * let markerHeight = 50, markerRadius = 10, linearOffset = 25; + * let popupOffsets = { + * 'top': [0, 0], + * 'top-left': [0,0], + * 'top-right': [0,0], + * 'bottom': [0, -markerHeight], + * 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + * 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + * 'left': [markerRadius, (markerHeight - markerRadius) * -1], + * 'right': [-markerRadius, (markerHeight - markerRadius) * -1] + * }; + * let popup = new Popup({offset: popupOffsets, className: 'my-class'}) + * .setLngLat(e.lngLat) + * .setHTML("

Hello World!

") + * .setMaxWidth("300px") + * .addTo(map); + * ``` + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/) + * + * ## Events + * + * **Event** `open` of type {@link Event} will be fired when the popup is opened manually or programmatically. + * + * **Event** `close` of type {@link Event} will be fired when the popup is closed manually or programmatically. + */ +class Popup extends performance$1.E { + /** + * @param options - the options + */ + constructor(options) { + super(); + /** + * Removes the popup from the map it has been added to. + * + * @example + * ```ts + * let popup = new Popup().addTo(map); + * popup.remove(); + * ``` + */ + this.remove = () => { + if (this._content) { + DOM.remove(this._content); + } + if (this._container) { + DOM.remove(this._container); + delete this._container; + } + if (this._map) { + this._map.off('move', this._update); + this._map.off('move', this._onClose); + this._map.off('click', this._onClose); + this._map.off('remove', this.remove); + this._map.off('mousemove', this._onMouseMove); + this._map.off('mouseup', this._onMouseUp); + this._map.off('drag', this._onDrag); + this._map._canvasContainer.classList.remove('maplibregl-track-pointer'); + delete this._map; + this.fire(new performance$1.k('close')); + } + return this; + }; + this._onMouseUp = (event) => { + this._update(event.point); + }; + this._onMouseMove = (event) => { + this._update(event.point); + }; + this._onDrag = (event) => { + this._update(event.point); + }; + this._update = (cursor) => { + var _a; + const hasPosition = this._lngLat || this._trackPointer; + if (!this._map || !hasPosition || !this._content) { + return; + } + if (!this._container) { + this._container = DOM.create('div', 'maplibregl-popup', this._map.getContainer()); + this._tip = DOM.create('div', 'maplibregl-popup-tip', this._container); + this._container.appendChild(this._content); + if (this.options.className) { + for (const name of this.options.className.split(' ')) { + this._container.classList.add(name); + } + } + if (this._closeButton) { + this._closeButton.setAttribute('aria-label', this._map._getUIString('Popup.Close')); + } + if (this._trackPointer) { + this._container.classList.add('maplibregl-popup-track-pointer'); + } + } + if (this.options.maxWidth && this._container.style.maxWidth !== this.options.maxWidth) { + this._container.style.maxWidth = this.options.maxWidth; + } + if (this._map.transform.renderWorldCopies && !this._trackPointer) { + this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map.transform); + } + else { + this._lngLat = (_a = this._lngLat) === null || _a === void 0 ? void 0 : _a.wrap(); + } + if (this._trackPointer && !cursor) + return; + const pos = this._flatPos = this._pos = this._trackPointer && cursor ? cursor : this._map.project(this._lngLat); + if (this._map.terrain) { + // flat position is saved because smartWrap needs non-elevated points + this._flatPos = this._trackPointer && cursor ? cursor : this._map.transform.locationPoint(this._lngLat); + } + let anchor = this.options.anchor; + const offset = normalizeOffset(this.options.offset); + if (!anchor) { + const width = this._container.offsetWidth; + const height = this._container.offsetHeight; + let anchorComponents; + if (pos.y + offset.bottom.y < height) { + anchorComponents = ['top']; + } + else if (pos.y > this._map.transform.height - height) { + anchorComponents = ['bottom']; + } + else { + anchorComponents = []; + } + if (pos.x < width / 2) { + anchorComponents.push('left'); + } + else if (pos.x > this._map.transform.width - width / 2) { + anchorComponents.push('right'); + } + if (anchorComponents.length === 0) { + anchor = 'bottom'; + } + else { + anchor = anchorComponents.join('-'); + } + } + let offsetedPos = pos.add(offset[anchor]); + if (!this.options.subpixelPositioning) { + offsetedPos = offsetedPos.round(); + } + DOM.setTransform(this._container, `${anchorTranslate[anchor]} translate(${offsetedPos.x}px,${offsetedPos.y}px)`); + applyAnchorClass(this._container, anchor, 'popup'); + }; + this._onClose = () => { + this.remove(); + }; + this.options = performance$1.e(Object.create(defaultOptions), options); + } + /** + * Adds the popup to a map. + * + * @param map - The MapLibre GL JS map to add the popup to. + * @example + * ```ts + * new Popup() + * .setLngLat([0, 0]) + * .setHTML("

Null Island

") + * .addTo(map); + * ``` + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + * @see [Show polygon information on click](https://maplibre.org/maplibre-gl-js/docs/examples/polygon-popup-on-click/) + */ + addTo(map) { + if (this._map) + this.remove(); + this._map = map; + if (this.options.closeOnClick) { + this._map.on('click', this._onClose); + } + if (this.options.closeOnMove) { + this._map.on('move', this._onClose); + } + this._map.on('remove', this.remove); + this._update(); + this._focusFirstElement(); + if (this._trackPointer) { + this._map.on('mousemove', this._onMouseMove); + this._map.on('mouseup', this._onMouseUp); + if (this._container) { + this._container.classList.add('maplibregl-popup-track-pointer'); + } + this._map._canvasContainer.classList.add('maplibregl-track-pointer'); + } + else { + this._map.on('move', this._update); + } + this.fire(new performance$1.k('open')); + return this; + } + /** + * @returns `true` if the popup is open, `false` if it is closed. + */ + isOpen() { + return !!this._map; + } + /** + * Returns the geographical location of the popup's anchor. + * + * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously + * set by `setLngLat` because `Popup` wraps the anchor longitude across copies of the world to keep + * the popup on screen. + * + * @returns The geographical location of the popup's anchor. + */ + getLngLat() { + return this._lngLat; + } + /** + * Sets the geographical location of the popup's anchor, and moves the popup to it. Replaces trackPointer() behavior. + * + * @param lnglat - The geographical location to set as the popup's anchor. + */ + setLngLat(lnglat) { + this._lngLat = performance$1.N.convert(lnglat); + this._pos = null; + this._flatPos = null; + this._trackPointer = false; + this._update(); + if (this._map) { + this._map.on('move', this._update); + this._map.off('mousemove', this._onMouseMove); + if (this._container) { + this._container.classList.remove('maplibregl-popup-track-pointer'); + } + this._map._canvasContainer.classList.remove('maplibregl-track-pointer'); + } + return this; + } + /** + * Tracks the popup anchor to the cursor position on screens with a pointer device (it will be hidden on touchscreens). Replaces the `setLngLat` behavior. + * For most use cases, set `closeOnClick` and `closeButton` to `false`. + * @example + * ```ts + * let popup = new Popup({ closeOnClick: false, closeButton: false }) + * .setHTML("

Hello World!

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

Hello World!

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

Hello World!

") + * .addTo(map); + * ``` + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/) + */ + setHTML(html) { + const frag = document.createDocumentFragment(); + const temp = document.createElement('body'); + let child; + temp.innerHTML = html; + while (true) { + child = temp.firstChild; + if (!child) + break; + frag.appendChild(child); + } + return this.setDOMContent(frag); + } + /** + * Returns the popup's maximum width. + * + * @returns The maximum width of the popup. + */ + getMaxWidth() { + var _a; + return (_a = this._container) === null || _a === void 0 ? void 0 : _a.style.maxWidth; + } + /** + * Sets the popup's maximum width. This is setting the CSS property `max-width`. + * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width + * + * @param maxWidth - A string representing the value for the maximum width. + */ + setMaxWidth(maxWidth) { + this.options.maxWidth = maxWidth; + this._update(); + return this; + } + /** + * Sets the popup's content to the element provided as a DOM node. + * + * @param htmlNode - A DOM node to be used as content for the popup. + * @example + * Create an element with the popup content + * ```ts + * let div = document.createElement('div'); + * div.innerHTML = 'Hello, world!'; + * let popup = new Popup() + * .setLngLat(e.lngLat) + * .setDOMContent(div) + * .addTo(map); + * ``` + */ + setDOMContent(htmlNode) { + if (this._content) { + // Clear out children first. + while (this._content.hasChildNodes()) { + if (this._content.firstChild) { + this._content.removeChild(this._content.firstChild); + } + } + } + else { + this._content = DOM.create('div', 'maplibregl-popup-content', this._container); + } + // The close button should be the last tabbable element inside the popup for a good keyboard UX. + this._content.appendChild(htmlNode); + this._createCloseButton(); + this._update(); + this._focusFirstElement(); + return this; + } + /** + * Adds a CSS class to the popup container element. + * + * @param className - Non-empty string with CSS class name to add to popup container + * + * @example + * ```ts + * let popup = new Popup() + * popup.addClassName('some-class') + * ``` + */ + addClassName(className) { + if (this._container) { + this._container.classList.add(className); + } + return this; + } + /** + * Removes a CSS class from the popup container element. + * + * @param className - Non-empty string with CSS class name to remove from popup container + * + * @example + * ```ts + * let popup = new Popup() + * popup.removeClassName('some-class') + * ``` + */ + removeClassName(className) { + if (this._container) { + this._container.classList.remove(className); + } + return this; + } + /** + * Sets the popup's offset. + * + * @param offset - Sets the popup's offset. + */ + setOffset(offset) { + this.options.offset = offset; + this._update(); + return this; + } + /** + * Add or remove the given CSS class on the popup container, depending on whether the container currently has that class. + * + * @param className - Non-empty string with CSS class name to add/remove + * + * @returns if the class was removed return false, if class was added, then return true, undefined if there is no container + * + * @example + * ```ts + * let popup = new Popup() + * popup.toggleClassName('toggleClass') + * ``` + */ + toggleClassName(className) { + if (this._container) { + return this._container.classList.toggle(className); + } + } + /** + * Set the option to allow subpixel positioning of the popup by passing a boolean + * + * @param value - When boolean is true, subpixel positioning is enabled for the popup. + * + * @example + * ```ts + * let popup = new Popup() + * popup.setSubpixelPositioning(true); + * ``` + */ + setSubpixelPositioning(value) { + this.options.subpixelPositioning = value; + } + _createCloseButton() { + if (this.options.closeButton) { + this._closeButton = DOM.create('button', 'maplibregl-popup-close-button', this._content); + this._closeButton.type = 'button'; + this._closeButton.innerHTML = '×'; + this._closeButton.addEventListener('click', this._onClose); + } + } + _focusFirstElement() { + if (!this.options.focusAfterOpen || !this._container) + return; + const firstFocusable = this._container.querySelector(focusQuerySelector); + if (firstFocusable) + firstFocusable.focus(); + } +} +function normalizeOffset(offset) { + if (!offset) { + return normalizeOffset(new performance$1.P(0, 0)); + } + else if (typeof offset === 'number') { + // input specifies a radius from which to calculate offsets at all positions + const cornerOffset = Math.round(Math.abs(offset) / Math.SQRT2); + return { + 'center': new performance$1.P(0, 0), + 'top': new performance$1.P(0, offset), + 'top-left': new performance$1.P(cornerOffset, cornerOffset), + 'top-right': new performance$1.P(-cornerOffset, cornerOffset), + 'bottom': new performance$1.P(0, -offset), + 'bottom-left': new performance$1.P(cornerOffset, -cornerOffset), + 'bottom-right': new performance$1.P(-cornerOffset, -cornerOffset), + 'left': new performance$1.P(offset, 0), + 'right': new performance$1.P(-offset, 0) + }; + } + else if (offset instanceof performance$1.P || Array.isArray(offset)) { + // input specifies a single offset to be applied to all positions + const convertedOffset = performance$1.P.convert(offset); + return { + 'center': convertedOffset, + 'top': convertedOffset, + 'top-left': convertedOffset, + 'top-right': convertedOffset, + 'bottom': convertedOffset, + 'bottom-left': convertedOffset, + 'bottom-right': convertedOffset, + 'left': convertedOffset, + 'right': convertedOffset + }; + } + else { + // input specifies an offset per position + return { + 'center': performance$1.P.convert(offset['center'] || [0, 0]), + 'top': performance$1.P.convert(offset['top'] || [0, 0]), + 'top-left': performance$1.P.convert(offset['top-left'] || [0, 0]), + 'top-right': performance$1.P.convert(offset['top-right'] || [0, 0]), + 'bottom': performance$1.P.convert(offset['bottom'] || [0, 0]), + 'bottom-left': performance$1.P.convert(offset['bottom-left'] || [0, 0]), + 'bottom-right': performance$1.P.convert(offset['bottom-right'] || [0, 0]), + 'left': performance$1.P.convert(offset['left'] || [0, 0]), + 'right': performance$1.P.convert(offset['right'] || [0, 0]) + }; + } +} + +const version = packageJSON.version; +/** + * Sets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text). + * Necessary for supporting the Arabic and Hebrew languages, which are written right-to-left. + * + * @param pluginURL - URL pointing to the Mapbox RTL text plugin source. + * @param lazy - If set to `true`, maplibre will defer loading the plugin until rtl text is encountered, + * rtl text will then be rendered only after the plugin finishes loading. + * @example + * ```ts + * setRTLTextPlugin('https://unpkg.com/@mapbox/mapbox-gl-rtl-text@0.2.3/mapbox-gl-rtl-text.js', false); + * ``` + * @see [Add support for right-to-left scripts](https://maplibre.org/maplibre-gl-js/docs/examples/mapbox-gl-rtl-text/) + */ +function setRTLTextPlugin(pluginURL, lazy) { + return rtlMainThreadPluginFactory().setRTLTextPlugin(pluginURL, lazy); +} +/** + * Gets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text) status. + * The status can be `unavailable` (i.e. not requested or removed), `loading`, `loaded` or `error`. + * If the status is `loaded` and the plugin is requested again, an error will be thrown. + * + * @example + * ```ts + * const pluginStatus = getRTLTextPluginStatus(); + * ``` + */ +function getRTLTextPluginStatus() { + return rtlMainThreadPluginFactory().getRTLTextPluginStatus(); +} +/** + * Returns the package version of the library + * @returns Package version of the library + */ +function getVersion() { return version; } +/** + * Gets the number of web workers instantiated on a page with GL JS maps. + * By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3). + * Make sure to set this property before creating any map instances for it to have effect. + * + * @returns Number of workers currently configured. + * @example + * ```ts + * const workerCount = getWorkerCount() + * ``` + */ +function getWorkerCount() { return WorkerPool.workerCount; } +/** + * Sets the number of web workers instantiated on a page with GL JS maps. + * By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3). + * Make sure to set this property before creating any map instances for it to have effect. + * + * @example + * ```ts + * setWorkerCount(2); + * ``` + */ +function setWorkerCount(count) { WorkerPool.workerCount = count; } +/** + * Gets and sets the maximum number of images (raster tiles, sprites, icons) to load in parallel, + * which affects performance in raster-heavy maps. 16 by default. + * + * @returns Number of parallel requests currently configured. + * @example + * ```ts + * getMaxParallelImageRequests(); + * ``` + */ +function getMaxParallelImageRequests() { return performance$1.a.MAX_PARALLEL_IMAGE_REQUESTS; } +/** + * Sets the maximum number of images (raster tiles, sprites, icons) to load in parallel, + * which affects performance in raster-heavy maps. 16 by default. + * + * @example + * ```ts + * setMaxParallelImageRequests(10); + * ``` + */ +function setMaxParallelImageRequests(numRequests) { performance$1.a.MAX_PARALLEL_IMAGE_REQUESTS = numRequests; } +/** + * Gets the worker url + * @returns The worker url + */ +function getWorkerUrl() { return performance$1.a.WORKER_URL; } +/** + * Sets the worker url + */ +function setWorkerUrl(value) { performance$1.a.WORKER_URL = value; } +/** + * Allows loading javascript code in the worker thread. + * *Note* that since this is using some very internal classes and flows it is considered experimental and can break at any point. + * + * It can be useful for the following examples: + * 1. Using `self.addProtocol` in the worker thread - note that you might need to also register the protocol on the main thread. + * 2. Using `self.registerWorkerSource(workerSource: WorkerSource)` to register a worker source, which should come with `addSourceType` usually. + * 3. using `self.actor.registerMessageHandler` to override some internal worker operations + * @param workerUrl - the worker url e.g. a url of a javascript file to load in the worker + * @returns + * + * @example + * ```ts + * // below is an example of sending a js file to the worker to load the method there + * // Note that you'll need to call the global function `addProtocol` in the worker to register the protocol there. + * // add-protocol-worker.js + * async function loadFn(params, abortController) { + * const t = await fetch(`https://${params.url.split("://")[1]}`); + * if (t.status == 200) { + * const buffer = await t.arrayBuffer(); + * return {data: buffer} + * } else { + * throw new Error(`Tile fetch error: ${t.statusText}`); + * } + * } + * self.addProtocol('custom', loadFn); + * + * // main.js + * importScriptInWorkers('add-protocol-worker.js'); + * ``` + */ +function importScriptInWorkers(workerUrl) { return getGlobalDispatcher().broadcast("IS" /* MessageType.importScript */, workerUrl); } + +exports.AJAXError = performance$1.bh; +exports.Evented = performance$1.E; +exports.LngLat = performance$1.N; +exports.MercatorCoordinate = performance$1.Z; +exports.Point = performance$1.P; +exports.addProtocol = performance$1.bi; +exports.config = performance$1.a; +exports.removeProtocol = performance$1.bj; +exports.AttributionControl = AttributionControl; +exports.BoxZoomHandler = BoxZoomHandler; +exports.CanvasSource = CanvasSource; +exports.CooperativeGesturesHandler = CooperativeGesturesHandler; +exports.DoubleClickZoomHandler = DoubleClickZoomHandler; +exports.DragPanHandler = DragPanHandler; +exports.DragRotateHandler = DragRotateHandler; +exports.EdgeInsets = EdgeInsets; +exports.FullscreenControl = FullscreenControl; +exports.GeoJSONSource = GeoJSONSource; +exports.GeolocateControl = GeolocateControl; +exports.Hash = Hash; +exports.ImageSource = ImageSource; +exports.KeyboardHandler = KeyboardHandler; +exports.LngLatBounds = LngLatBounds; +exports.LogoControl = LogoControl; +exports.Map = Map$1; +exports.MapMouseEvent = MapMouseEvent; +exports.MapTouchEvent = MapTouchEvent; +exports.MapWheelEvent = MapWheelEvent; +exports.Marker = Marker; +exports.NavigationControl = NavigationControl; +exports.Popup = Popup; +exports.RasterDEMTileSource = RasterDEMTileSource; +exports.RasterTileSource = RasterTileSource; +exports.ScaleControl = ScaleControl; +exports.ScrollZoomHandler = ScrollZoomHandler; +exports.Style = Style; +exports.TerrainControl = TerrainControl; +exports.TwoFingersTouchPitchHandler = TwoFingersTouchPitchHandler; +exports.TwoFingersTouchRotateHandler = TwoFingersTouchRotateHandler; +exports.TwoFingersTouchZoomHandler = TwoFingersTouchZoomHandler; +exports.TwoFingersTouchZoomRotateHandler = TwoFingersTouchZoomRotateHandler; +exports.VectorTileSource = VectorTileSource; +exports.VideoSource = VideoSource; +exports.addSourceType = addSourceType; +exports.clearPrewarmedResources = clearPrewarmedResources; +exports.getMaxParallelImageRequests = getMaxParallelImageRequests; +exports.getRTLTextPluginStatus = getRTLTextPluginStatus; +exports.getVersion = getVersion; +exports.getWorkerCount = getWorkerCount; +exports.getWorkerUrl = getWorkerUrl; +exports.importScriptInWorkers = importScriptInWorkers; +exports.prewarm = prewarm; +exports.setMaxParallelImageRequests = setMaxParallelImageRequests; +exports.setRTLTextPlugin = setRTLTextPlugin; +exports.setWorkerCount = setWorkerCount; +exports.setWorkerUrl = setWorkerUrl; + +})); + +// +// Our custom intro provides a specialized "define()" function, called by the +// AMD modules below, that sets up the worker blob URL and then executes the +// main module, storing its exported value as 'maplibregl' + + +var maplibregl$1 = maplibregl; + +return maplibregl$1; + +})); +//# sourceMappingURL=maplibre-gl-unminified.js.map diff --git a/dist/maplibre-gl.css b/dist/maplibre-gl.css new file mode 100644 index 0000000000..6ceb5de955 --- /dev/null +++ b/dist/maplibre-gl.css @@ -0,0 +1 @@ +.maplibregl-map{font:12px/20px Helvetica Neue,Arial,Helvetica,sans-serif;overflow:hidden;position:relative;-webkit-tap-highlight-color:rgb(0 0 0/0)}.maplibregl-canvas{left:0;position:absolute;top:0}.maplibregl-map:fullscreen{height:100%;width:100%}.maplibregl-ctrl-group button.maplibregl-ctrl-compass{touch-action:none}.maplibregl-canvas-container.maplibregl-interactive,.maplibregl-ctrl-group button.maplibregl-ctrl-compass{cursor:grab;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-canvas-container.maplibregl-interactive.maplibregl-track-pointer{cursor:pointer}.maplibregl-canvas-container.maplibregl-interactive:active,.maplibregl-ctrl-group button.maplibregl-ctrl-compass:active{cursor:grabbing}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-canvas-container.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:pinch-zoom}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:none}.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures,.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-ctrl-bottom-left,.maplibregl-ctrl-bottom-right,.maplibregl-ctrl-top-left,.maplibregl-ctrl-top-right{pointer-events:none;position:absolute;z-index:2}.maplibregl-ctrl-top-left{left:0;top:0}.maplibregl-ctrl-top-right{right:0;top:0}.maplibregl-ctrl-bottom-left{bottom:0;left:0}.maplibregl-ctrl-bottom-right{bottom:0;right:0}.maplibregl-ctrl{clear:both;pointer-events:auto;transform:translate(0)}.maplibregl-ctrl-top-left .maplibregl-ctrl{float:left;margin:10px 0 0 10px}.maplibregl-ctrl-top-right .maplibregl-ctrl{float:right;margin:10px 10px 0 0}.maplibregl-ctrl-bottom-left .maplibregl-ctrl{float:left;margin:0 0 10px 10px}.maplibregl-ctrl-bottom-right .maplibregl-ctrl{float:right;margin:0 10px 10px 0}.maplibregl-ctrl-group{background:#fff;border-radius:4px}.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px rgba(0,0,0,.1)}@media (forced-colors:active){.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px ButtonText}}.maplibregl-ctrl-group button{background-color:transparent;border:0;box-sizing:border-box;cursor:pointer;display:block;height:29px;outline:none;padding:0;width:29px}.maplibregl-ctrl-group button+button{border-top:1px solid #ddd}.maplibregl-ctrl button .maplibregl-ctrl-icon{background-position:50%;background-repeat:no-repeat;display:block;height:100%;width:100%}@media (forced-colors:active){.maplibregl-ctrl-icon{background-color:transparent}.maplibregl-ctrl-group button+button{border-top:1px solid ButtonText}}.maplibregl-ctrl button::-moz-focus-inner{border:0;padding:0}.maplibregl-ctrl-attrib-button:focus,.maplibregl-ctrl-group button:focus{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl button:disabled{cursor:not-allowed}.maplibregl-ctrl button:disabled .maplibregl-ctrl-icon{opacity:.25}.maplibregl-ctrl button:not(:disabled):hover{background-color:rgb(0 0 0/5%)}.maplibregl-ctrl-group button:focus:focus-visible{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl-group button:focus:not(:focus-visible){box-shadow:none}.maplibregl-ctrl-group button:focus:first-child{border-radius:4px 4px 0 0}.maplibregl-ctrl-group button:focus:last-child{border-radius:0 0 4px 4px}.maplibregl-ctrl-group button:focus:only-child{border-radius:inherit}.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-terrain .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%23333' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%2333b5e5' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23aaa' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-waiting .maplibregl-ctrl-icon{animation:maplibregl-spin 2s linear infinite}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23999' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23666' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}}@keyframes maplibregl-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E");background-repeat:no-repeat;cursor:pointer;display:block;height:23px;margin:0 0 -4px -4px;overflow:hidden;width:88px}a.maplibregl-ctrl-logo.maplibregl-compact{width:14px}@media (forced-colors:active){a.maplibregl-ctrl-logo{background-color:transparent;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}.maplibregl-ctrl.maplibregl-ctrl-attrib{background-color:hsla(0,0%,100%,.5);margin:0;padding:0 5px}@media screen{.maplibregl-ctrl-attrib.maplibregl-compact{background-color:#fff;border-radius:12px;box-sizing:content-box;color:#000;margin:10px;min-height:20px;padding:2px 24px 2px 0;position:relative}.maplibregl-ctrl-attrib.maplibregl-compact-show{padding:2px 28px 2px 8px;visibility:visible}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:hsla(0,0%,100%,.5);background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:rgb(0 0 0/5%)}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:hsla(0,0%,100%,.75);border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:rgb(0 0 0/5%)}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px rgba(0,0,0,.35);box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:rgba(0,0,0,.4);color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media (hover:none),(width <= 480px){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999} \ No newline at end of file diff --git a/dist/maplibre-gl.d.ts b/dist/maplibre-gl.d.ts new file mode 100644 index 0000000000..bcf8012212 --- /dev/null +++ b/dist/maplibre-gl.d.ts @@ -0,0 +1,13307 @@ +// Generated by dts-bundle-generator v9.5.1 + +import Point from '@mapbox/point-geometry'; +import TinySDF from '@mapbox/tiny-sdf'; +import { VectorTileFeature, VectorTileLayer } from '@mapbox/vector-tile'; +import { Color, CompositeExpression, DiffCommand, DiffOperations, Feature, FeatureFilter, FeatureState, FilterSpecification, Formatted, FormattedSection, GeoJSONSourceSpecification, GlobalProperties, ICanonicalTileID, IMercatorCoordinate, ImageSourceSpecification, InterpolationType, LayerSpecification, LightSpecification, Padding, PromoteIdSpecification, PropertyValueSpecification, RasterDEMSourceSpecification, RasterSourceSpecification, ResolvedImage, SkySpecification, SourceExpression, SourceSpecification, SpriteSpecification, StylePropertyExpression, StylePropertySpecification, StyleSpecification, TerrainSpecification, TransitionSpecification, VariableAnchorOffsetCollection, VectorSourceSpecification, VideoSourceSpecification } from '@maplibre/maplibre-gl-style-spec'; +import { Options as GeoJSONVTOptions } from 'geojson-vt'; +import { mat2, mat4, vec4 } from 'gl-matrix'; +import KDBush from 'kdbush'; +import { PotpackBox } from 'potpack'; +import { ClusterProperties, Options as SuperclusterOptions } from 'supercluster'; + +/** + * A type used to store the tile's expiration date and cache control definition + */ +export type ExpiryData = { + cacheControl?: string | null; + expires?: Date | string | null; +}; +/** + * A `RequestParameters` object to be returned from Map.options.transformRequest callbacks. + * @example + * ```ts + * // use transformRequest to modify requests that begin with `http://myHost` + * transformRequest: function(url, resourceType) { + * if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) { + * return { + * url: url.replace('http', 'https'), + * headers: { 'my-custom-header': true }, + * credentials: 'include' // Include cookies for cross-origin requests + * } + * } + * } + * ``` + */ +export type RequestParameters = { + /** + * The URL to be requested. + */ + url: string; + /** + * The headers to be sent with the request. + */ + headers?: any; + /** + * Request method `'GET' | 'POST' | 'PUT'`. + */ + method?: "GET" | "POST" | "PUT"; + /** + * Request body. + */ + body?: string; + /** + * Response body type to be returned. + */ + type?: "string" | "json" | "arrayBuffer" | "image"; + /** + * `'same-origin'|'include'` Use 'include' to send cookies with cross-origin requests. + */ + credentials?: "same-origin" | "include"; + /** + * If `true`, Resource Timing API information will be collected for these transformed requests and returned in a resourceTiming property of relevant data events. + */ + collectResourceTiming?: boolean; + /** + * Parameters supported only by browser fetch API. Property of the Request interface contains the cache mode of the request. It controls how the request will interact with the browser's HTTP cache. (https://developer.mozilla.org/en-US/docs/Web/API/Request/cache) + */ + cache?: RequestCache; +}; +/** + * The response object returned from a successful AJAx request + */ +export type GetResourceResponse = ExpiryData & { + data: T; +}; +/** + * An error thrown when a HTTP request results in an error response. + */ +export declare class AJAXError extends Error { + /** + * The response's HTTP status code. + */ + status: number; + /** + * The response's HTTP status text. + */ + statusText: string; + /** + * The request's URL. + */ + url: string; + /** + * The response's body. + */ + body: Blob; + /** + * @param status - The response's HTTP status code. + * @param statusText - The response's HTTP status text. + * @param url - The request's URL. + * @param body - The response's body. + */ + constructor(status: number, statusText: string, url: string, body: Blob); +} +/** + * This method type is used to register a protocol handler. + * Use the abort controller for aborting requests. + * Return a promise with the relevant resource response. + */ +export type AddProtocolAction = (requestParameters: RequestParameters, abortController: AbortController) => Promise>; +/** + * This is a global config object used to store the configuration + * It is available in the workers as well. + * Only serializable data should be stored in it. + */ +export type Config = { + MAX_PARALLEL_IMAGE_REQUESTS: number; + MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME: number; + MAX_TILE_CACHE_ZOOM_LEVELS: number; + REGISTERED_PROTOCOLS: { + [x: string]: AddProtocolAction; + }; + WORKER_URL: string; +}; +export declare const config: Config; +/** + * A class that is serialized to and json, that can be constructed back to the original class in the worker or in the main thread + */ +export type SerializedObject = { + [_: string]: S; +}; +/** + * All the possible values that can be serialized and sent to and from the worker + */ +export type Serialized = null | void | boolean | number | string | Boolean | Number | String | Date | RegExp | ArrayBuffer | ArrayBufferView | ImageData | ImageBitmap | Blob | Array | SerializedObject; +declare class ThrottledInvoker { + _channel: MessageChannel; + _triggered: boolean; + _methodToThrottle: Function; + constructor(methodToThrottle: Function); + trigger(): void; + remove(): void; +} +declare const viewTypes: { + Int8: Int8ArrayConstructor; + Uint8: Uint8ArrayConstructor; + Int16: Int16ArrayConstructor; + Uint16: Uint16ArrayConstructor; + Int32: Int32ArrayConstructor; + Uint32: Uint32ArrayConstructor; + Float32: Float32ArrayConstructor; +}; +/** + * @internal + * A view type size + */ +export type ViewType = keyof typeof viewTypes; +declare class Struct { + _pos1: number; + _pos2: number; + _pos4: number; + _pos8: number; + readonly _structArray: StructArray; + size: number; + /** + * @param structArray - The StructArray the struct is stored in + * @param index - The index of the struct in the StructArray. + */ + constructor(structArray: StructArray, index: number); +} +/** + * @internal + * A struct array member + */ +export type StructArrayMember = { + name: string; + type: ViewType; + components: number; + offset: number; +}; +/** + * An array that can be desialized + */ +export type SerializedStructArray = { + length: number; + arrayBuffer: ArrayBuffer; +}; +declare abstract class StructArray { + capacity: number; + length: number; + isTransferred: boolean; + arrayBuffer: ArrayBuffer; + uint8: Uint8Array; + members: Array; + bytesPerElement: number; + abstract emplaceBack(...v: number[]): any; + abstract emplace(i: number, ...v: number[]): any; + constructor(); + /** + * Serialize a StructArray instance. Serializes both the raw data and the + * metadata needed to reconstruct the StructArray base class during + * deserialization. + */ + static serialize(array: StructArray, transferables?: Array): SerializedStructArray; + static deserialize(input: SerializedStructArray): any; + /** + * Resize the array to discard unused capacity. + */ + _trim(): void; + /** + * Resets the length of the array to 0 without de-allocating capacity. + */ + clear(): void; + /** + * Resize the array. + * If `n` is greater than the current length then additional elements with undefined values are added. + * If `n` is less than the current length then the array will be reduced to the first `n` elements. + * @param n - The new size of the array. + */ + resize(n: number): void; + /** + * Indicate a planned increase in size, so that any necessary allocation may + * be done once, ahead of time. + * @param n - The expected size of the array. + */ + reserve(n: number): void; + /** + * Create TypedArray views for the current ArrayBuffer. + */ + _refreshViews(): void; +} +declare class StructArrayLayout2i4 extends StructArray { + uint8: Uint8Array; + int16: Int16Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number): number; + emplace(i: number, v0: number, v1: number): number; +} +declare class StructArrayLayout3i6 extends StructArray { + uint8: Uint8Array; + int16: Int16Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number, v2: number): number; + emplace(i: number, v0: number, v1: number, v2: number): number; +} +declare class StructArrayLayout4i8 extends StructArray { + uint8: Uint8Array; + int16: Int16Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number, v2: number, v3: number): number; + emplace(i: number, v0: number, v1: number, v2: number, v3: number): number; +} +declare class StructArrayLayout2i4i12 extends StructArray { + uint8: Uint8Array; + int16: Int16Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number; + emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number; +} +declare class StructArrayLayout2i4ub8 extends StructArray { + uint8: Uint8Array; + int16: Int16Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number; + emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number; +} +declare class StructArrayLayout2f8 extends StructArray { + uint8: Uint8Array; + float32: Float32Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number): number; + emplace(i: number, v0: number, v1: number): number; +} +declare class StructArrayLayout4i4ui4i24 extends StructArray { + uint8: Uint8Array; + int16: Int16Array; + uint16: Uint16Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number): number; + emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number): number; +} +declare class StructArrayLayout3f12 extends StructArray { + uint8: Uint8Array; + float32: Float32Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number, v2: number): number; + emplace(i: number, v0: number, v1: number, v2: number): number; +} +declare class StructArrayLayout1ul4 extends StructArray { + uint8: Uint8Array; + uint32: Uint32Array; + _refreshViews(): void; + emplaceBack(v0: number): number; + emplace(i: number, v0: number): number; +} +declare class StructArrayLayout6i1ul2ui20 extends StructArray { + uint8: Uint8Array; + int16: Int16Array; + uint32: Uint32Array; + uint16: Uint16Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number): number; + emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number): number; +} +declare class StructArrayLayout2ub2f2i16 extends StructArray { + uint8: Uint8Array; + float32: Float32Array; + int16: Int16Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number; + emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number; +} +declare class StructArrayLayout3ui6 extends StructArray { + uint8: Uint8Array; + uint16: Uint16Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number, v2: number): number; + emplace(i: number, v0: number, v1: number, v2: number): number; +} +declare class StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 extends StructArray { + uint8: Uint8Array; + int16: Int16Array; + uint16: Uint16Array; + uint32: Uint32Array; + float32: Float32Array; + _refreshViews(): void; + 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): number; + 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): number; +} +declare class StructArrayLayout8i15ui1ul2f2ui64 extends StructArray { + uint8: Uint8Array; + int16: Int16Array; + uint16: Uint16Array; + uint32: Uint32Array; + float32: Float32Array; + _refreshViews(): void; + 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): number; + 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): number; +} +declare class StructArrayLayout1f4 extends StructArray { + uint8: Uint8Array; + float32: Float32Array; + _refreshViews(): void; + emplaceBack(v0: number): number; + emplace(i: number, v0: number): number; +} +declare class StructArrayLayout1ui2f12 extends StructArray { + uint8: Uint8Array; + uint16: Uint16Array; + float32: Float32Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number, v2: number): number; + emplace(i: number, v0: number, v1: number, v2: number): number; +} +declare class StructArrayLayout1ul2ui8 extends StructArray { + uint8: Uint8Array; + uint32: Uint32Array; + uint16: Uint16Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number, v2: number): number; + emplace(i: number, v0: number, v1: number, v2: number): number; +} +declare class StructArrayLayout2ui4 extends StructArray { + uint8: Uint8Array; + uint16: Uint16Array; + _refreshViews(): void; + emplaceBack(v0: number, v1: number): number; + emplace(i: number, v0: number, v1: number): number; +} +declare class StructArrayLayout1ui2 extends StructArray { + uint8: Uint8Array; + uint16: Uint16Array; + _refreshViews(): void; + emplaceBack(v0: number): number; + emplace(i: number, v0: number): number; +} +declare class CollisionBoxStruct extends Struct { + _structArray: CollisionBoxArray; + get anchorPointX(): number; + get anchorPointY(): number; + get x1(): number; + get y1(): number; + get x2(): number; + get y2(): number; + get featureIndex(): number; + get sourceLayerIndex(): number; + get bucketIndex(): number; + get anchorPoint(): Point; +} +declare class CollisionBoxArray extends StructArrayLayout6i1ul2ui20 { + /** + * Return the CollisionBoxStruct at the given location in the array. + * @param index The index of the element. + */ + get(index: number): CollisionBoxStruct; +} +declare class PlacedSymbolStruct extends Struct { + _structArray: PlacedSymbolArray; + get anchorX(): number; + get anchorY(): number; + get glyphStartIndex(): number; + get numGlyphs(): number; + get vertexStartIndex(): number; + get lineStartIndex(): number; + get lineLength(): number; + get segment(): number; + get lowerSize(): number; + get upperSize(): number; + get lineOffsetX(): number; + get lineOffsetY(): number; + get writingMode(): number; + get placedOrientation(): number; + set placedOrientation(x: number); + get hidden(): number; + set hidden(x: number); + get crossTileID(): number; + set crossTileID(x: number); + get associatedIconIndex(): number; +} +declare class PlacedSymbolArray extends StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 { + /** + * Return the PlacedSymbolStruct at the given location in the array. + * @param index The index of the element. + */ + get(index: number): PlacedSymbolStruct; +} +declare class SymbolInstanceStruct extends Struct { + _structArray: SymbolInstanceArray; + get anchorX(): number; + get anchorY(): number; + get rightJustifiedTextSymbolIndex(): number; + get centerJustifiedTextSymbolIndex(): number; + get leftJustifiedTextSymbolIndex(): number; + get verticalPlacedTextSymbolIndex(): number; + get placedIconSymbolIndex(): number; + get verticalPlacedIconSymbolIndex(): number; + get key(): number; + get textBoxStartIndex(): number; + get textBoxEndIndex(): number; + get verticalTextBoxStartIndex(): number; + get verticalTextBoxEndIndex(): number; + get iconBoxStartIndex(): number; + get iconBoxEndIndex(): number; + get verticalIconBoxStartIndex(): number; + get verticalIconBoxEndIndex(): number; + get featureIndex(): number; + get numHorizontalGlyphVertices(): number; + get numVerticalGlyphVertices(): number; + get numIconVertices(): number; + get numVerticalIconVertices(): number; + get useRuntimeCollisionCircles(): number; + get crossTileID(): number; + set crossTileID(x: number); + get textBoxScale(): number; + get collisionCircleDiameter(): number; + get textAnchorOffsetStartIndex(): number; + get textAnchorOffsetEndIndex(): number; +} +export type SymbolInstance = SymbolInstanceStruct; +declare class SymbolInstanceArray extends StructArrayLayout8i15ui1ul2f2ui64 { + /** + * Return the SymbolInstanceStruct at the given location in the array. + * @param index The index of the element. + */ + get(index: number): SymbolInstanceStruct; +} +declare class GlyphOffsetArray extends StructArrayLayout1f4 { + getoffsetX(index: number): number; +} +declare class SymbolLineVertexArray extends StructArrayLayout3i6 { + getx(index: number): number; + gety(index: number): number; + gettileUnitDistanceFromAnchor(index: number): number; +} +declare class TextAnchorOffsetStruct extends Struct { + _structArray: TextAnchorOffsetArray; + get textAnchor(): number; + get textOffset0(): number; + get textOffset1(): number; +} +export type TextAnchorOffset = TextAnchorOffsetStruct; +declare class TextAnchorOffsetArray extends StructArrayLayout1ui2f12 { + /** + * Return the TextAnchorOffsetStruct at the given location in the array. + * @param index The index of the element. + */ + get(index: number): TextAnchorOffsetStruct; +} +declare class FeatureIndexStruct extends Struct { + _structArray: FeatureIndexArray; + get featureIndex(): number; + get sourceLayerIndex(): number; + get bucketIndex(): number; +} +declare class FeatureIndexArray extends StructArrayLayout1ul2ui8 { + /** + * Return the FeatureIndexStruct at the given location in the array. + * @param index The index of the element. + */ + get(index: number): FeatureIndexStruct; +} +declare class PosArray extends StructArrayLayout2i4 { +} +declare class RasterBoundsArray extends StructArrayLayout4i8 { +} +declare class CircleLayoutArray extends StructArrayLayout2i4 { +} +declare class FillLayoutArray extends StructArrayLayout2i4 { +} +declare class FillExtrusionLayoutArray extends StructArrayLayout2i4i12 { +} +declare class LineLayoutArray extends StructArrayLayout2i4ub8 { +} +declare class LineExtLayoutArray extends StructArrayLayout2f8 { +} +declare class SymbolLayoutArray extends StructArrayLayout4i4ui4i24 { +} +declare class SymbolDynamicLayoutArray extends StructArrayLayout3f12 { +} +declare class SymbolOpacityArray extends StructArrayLayout1ul4 { +} +declare class CollisionVertexArray extends StructArrayLayout2ub2f2i16 { +} +declare class TriangleIndexArray extends StructArrayLayout3ui6 { +} +declare class LineIndexArray extends StructArrayLayout2ui4 { +} +declare class LineStripIndexArray extends StructArrayLayout1ui2 { +} +/** + * A {@link LngLat} object, an array of two numbers representing longitude and latitude, + * or an object with `lng` and `lat` or `lon` and `lat` properties. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let v1 = new LngLat(-122.420679, 37.772537); + * let v2 = [-122.420679, 37.772537]; + * let v3 = {lon: -122.420679, lat: 37.772537}; + * ``` + */ +export type LngLatLike = LngLat | { + lng: number; + lat: number; +} | { + lon: number; + lat: number; +} | [ + number, + number +]; +/** + * A `LngLat` object represents a given longitude and latitude coordinate, measured in degrees. + * These coordinates are based on the [WGS84 (EPSG:4326) standard](https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84). + * + * MapLibre GL JS uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match the + * [GeoJSON specification](https://tools.ietf.org/html/rfc7946). + * + * Note that any MapLibre GL JS method that accepts a `LngLat` object as an argument or option + * can also accept an `Array` of two numbers and will perform an implicit conversion. + * This flexible type is documented as {@link LngLatLike}. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let ll = new LngLat(-123.9749, 40.7736); + * ll.lng; // = -123.9749 + * ``` + * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/) + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Create a timeline animation](https://maplibre.org/maplibre-gl-js/docs/examples/timeline-animation/) + */ +export declare class LngLat { + lng: number; + lat: number; + /** + * @param lng - Longitude, measured in degrees. + * @param lat - Latitude, measured in degrees. + */ + constructor(lng: number, lat: number); + /** + * Returns a new `LngLat` object whose longitude is wrapped to the range (-180, 180). + * + * @returns The wrapped `LngLat` object. + * @example + * ```ts + * let ll = new LngLat(286.0251, 40.7736); + * let wrapped = ll.wrap(); + * wrapped.lng; // = -73.9749 + * ``` + */ + wrap(): LngLat; + /** + * Returns the coordinates represented as an array of two numbers. + * + * @returns The coordinates represented as an array of longitude and latitude. + * @example + * ```ts + * let ll = new LngLat(-73.9749, 40.7736); + * ll.toArray(); // = [-73.9749, 40.7736] + * ``` + */ + toArray(): [ + number, + number + ]; + /** + * Returns the coordinates represent as a string. + * + * @returns The coordinates represented as a string of the format `'LngLat(lng, lat)'`. + * @example + * ```ts + * let ll = new LngLat(-73.9749, 40.7736); + * ll.toString(); // = "LngLat(-73.9749, 40.7736)" + * ``` + */ + toString(): string; + /** + * Returns the approximate distance between a pair of coordinates in meters + * Uses the Haversine Formula (from R.W. Sinnott, "Virtues of the Haversine", Sky and Telescope, vol. 68, no. 2, 1984, p. 159) + * + * @param lngLat - coordinates to compute the distance to + * @returns Distance in meters between the two coordinates. + * @example + * ```ts + * let new_york = new LngLat(-74.0060, 40.7128); + * let los_angeles = new LngLat(-118.2437, 34.0522); + * new_york.distanceTo(los_angeles); // = 3935751.690893987, "true distance" using a non-spherical approximation is ~3966km + * ``` + */ + distanceTo(lngLat: LngLat): number; + /** + * Converts an array of two numbers or an object with `lng` and `lat` or `lon` and `lat` properties + * to a `LngLat` object. + * + * If a `LngLat` object is passed in, the function returns it unchanged. + * + * @param input - An array of two numbers or object to convert, or a `LngLat` object to return. + * @returns A new `LngLat` object, if a conversion occurred, or the original `LngLat` object. + * @example + * ```ts + * let arr = [-73.9749, 40.7736]; + * let ll = LngLat.convert(arr); + * ll; // = LngLat {lng: -73.9749, lat: 40.7736} + * ``` + */ + static convert(input: LngLatLike): LngLat; +} +/** + * A `MercatorCoordinate` object represents a projected three dimensional position. + * + * `MercatorCoordinate` uses the web mercator projection ([EPSG:3857](https://epsg.io/3857)) with slightly different units: + * + * - the size of 1 unit is the width of the projected world instead of the "mercator meter" + * - the origin of the coordinate space is at the north-west corner instead of the middle + * + * For example, `MercatorCoordinate(0, 0, 0)` is the north-west corner of the mercator world and + * `MercatorCoordinate(1, 1, 0)` is the south-east corner. If you are familiar with + * [vector tiles](https://github.com/mapbox/vector-tile-spec) it may be helpful to think + * of the coordinate space as the `0/0/0` tile with an extent of `1`. + * + * The `z` dimension of `MercatorCoordinate` is conformal. A cube in the mercator coordinate space would be rendered as a cube. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let nullIsland = new MercatorCoordinate(0.5, 0.5, 0); + * ``` + * @see [Add a custom style layer](https://maplibre.org/maplibre-gl-js/docs/examples/custom-style-layer/) + */ +export declare class MercatorCoordinate implements IMercatorCoordinate { + x: number; + y: number; + z: number; + /** + * @param x - The x component of the position. + * @param y - The y component of the position. + * @param z - The z component of the position. + */ + constructor(x: number, y: number, z?: number); + /** + * Project a `LngLat` to a `MercatorCoordinate`. + * + * @param lngLatLike - The location to project. + * @param altitude - The altitude in meters of the position. + * @returns The projected mercator coordinate. + * @example + * ```ts + * let coord = MercatorCoordinate.fromLngLat({ lng: 0, lat: 0}, 0); + * coord; // MercatorCoordinate(0.5, 0.5, 0) + * ``` + */ + static fromLngLat(lngLatLike: LngLatLike, altitude?: number): MercatorCoordinate; + /** + * Returns the `LngLat` for the coordinate. + * + * @returns The `LngLat` object. + * @example + * ```ts + * let coord = new MercatorCoordinate(0.5, 0.5, 0); + * let lngLat = coord.toLngLat(); // LngLat(0, 0) + * ``` + */ + toLngLat(): LngLat; + /** + * Returns the altitude in meters of the coordinate. + * + * @returns The altitude in meters. + * @example + * ```ts + * let coord = new MercatorCoordinate(0, 0, 0.02); + * coord.toAltitude(); // 6914.281956295339 + * ``` + */ + toAltitude(): number; + /** + * Returns the distance of 1 meter in `MercatorCoordinate` units at this latitude. + * + * For coordinates in real world units using meters, this naturally provides the scale + * to transform into `MercatorCoordinate`s. + * + * @returns Distance of 1 meter in `MercatorCoordinate` units. + */ + meterInMercatorCoordinateUnits(): number; +} +declare class CanonicalTileID implements ICanonicalTileID { + z: number; + x: number; + y: number; + key: string; + constructor(z: number, x: number, y: number); + equals(id: ICanonicalTileID): boolean; + url(urls: Array, pixelRatio: number, scheme?: string | null): string; + isChildOf(parent: ICanonicalTileID): boolean; + getTilePoint(coord: IMercatorCoordinate): Point; + toString(): string; +} +declare class UnwrappedTileID { + wrap: number; + canonical: CanonicalTileID; + key: string; + constructor(wrap: number, canonical: CanonicalTileID); +} +declare class OverscaledTileID { + overscaledZ: number; + wrap: number; + canonical: CanonicalTileID; + key: string; + posMatrix: mat4; + constructor(overscaledZ: number, wrap: number, z: number, x: number, y: number); + clone(): OverscaledTileID; + equals(id: OverscaledTileID): boolean; + scaledTo(targetZ: number): OverscaledTileID; + calculateScaledKey(targetZ: number, withWrap: boolean): string; + isChildOf(parent: OverscaledTileID): boolean; + children(sourceMaxZoom: number): OverscaledTileID[]; + isLessThan(rhs: OverscaledTileID): boolean; + wrapped(): OverscaledTileID; + unwrapTo(wrap: number): OverscaledTileID; + overscaleFactor(): number; + toUnwrapped(): UnwrappedTileID; + toString(): string; + getTilePoint(coord: MercatorCoordinate): Point; +} +/** + * A listener method used as a callback to events + */ +export type Listener = (a: any) => any; +export type Listeners = { + [_: string]: Array; +}; +declare class Event$1 { + readonly type: string; + constructor(type: string, data?: any); +} +/** + * Methods mixed in to other classes for event capabilities. + * + * @group Event Related + */ +export declare class Evented { + _listeners: Listeners; + _oneTimeListeners: Listeners; + _eventedParent: Evented; + _eventedParentData: any | (() => any); + /** + * Adds a listener to a specified event type. + * + * @param type - The event type to add a listen for. + * @param listener - The function to be called when the event is fired. + * The listener function is called with the data object passed to `fire`, + * extended with `target` and `type` properties. + */ + on(type: string, listener: Listener): this; + /** + * Removes a previously registered event listener. + * + * @param type - The event type to remove listeners for. + * @param listener - The listener function to remove. + */ + off(type: string, listener: Listener): this; + /** + * Adds a listener that will be called only once to a specified event type. + * + * The listener will be called first time the event fires after the listener is registered. + * + * @param type - The event type to listen for. + * @param listener - The function to be called when the event is fired the first time. + * @returns `this` or a promise if a listener is not provided + */ + once(type: string, listener?: Listener): this | Promise; + fire(event: Event$1 | string, properties?: any): this; + /** + * Returns a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type. + * + * @param type - The event type + * @returns `true` if there is at least one registered listener for specified event type, `false` otherwise + */ + listens(type: string): boolean; + /** + * Bubble all events fired by this instance of Evented to this parent instance of Evented. + */ + setEventedParent(parent?: Evented | null, data?: any | (() => any)): this; +} +declare class ZoomHistory { + lastZoom: number; + lastFloorZoom: number; + lastIntegerZoom: number; + lastIntegerZoomTime: number; + first: boolean; + constructor(); + update(z: number, now: number): boolean; +} +export type CrossfadeParameters = { + fromScale: number; + toScale: number; + t: number; +}; +declare class EvaluationParameters { + zoom: number; + now: number; + fadeDuration: number; + zoomHistory: ZoomHistory; + transition: TransitionSpecification; + constructor(zoom: number, options?: any); + isSupportedScript(str: string): boolean; + crossFadingFactor(): number; + getCrossfadeParameters(): CrossfadeParameters; +} +export type TimePoint = number; +/** + * A from-to type + */ +export type CrossFaded = { + to: T; + from: T; +}; +/** + * @internal + * Implementations of the `Property` interface: + * + * * Hold metadata about a property that's independent of any specific value: stuff like the type of the value, + * the default value, etc. This comes from the style specification JSON. + * * Define behavior that needs to be polymorphic across different properties: "possibly evaluating" + * an input value (see below), and interpolating between two possibly-evaluted values. + * + * The type `T` is the fully-evaluated value type (e.g. `number`, `string`, `Color`). + * The type `R` is the intermediate "possibly evaluated" value type. See below. + * + * There are two main implementations of the interface -- one for properties that allow data-driven values, + * and one for properties that don't. There are a few "special case" implementations as well: one for properties + * which cross-fade between two values rather than interpolating, one for `heatmap-color` and `line-gradient`, + * and one for `light-position`. + */ +export interface Property { + specification: StylePropertySpecification; + possiblyEvaluate(value: PropertyValue, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): R; + interpolate(a: R, b: R, t: number): R; +} +declare class PropertyValue { + property: Property; + value: PropertyValueSpecification | void; + expression: StylePropertyExpression; + constructor(property: Property, value: PropertyValueSpecification | void); + isDataDriven(): boolean; + possiblyEvaluate(parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): R; +} +export type TransitionParameters = { + now: TimePoint; + transition: TransitionSpecification; +}; +declare class TransitionablePropertyValue { + property: Property; + value: PropertyValue; + transition: TransitionSpecification | void; + constructor(property: Property); + transitioned(parameters: TransitionParameters, prior: TransitioningPropertyValue): TransitioningPropertyValue; + untransitioned(): TransitioningPropertyValue; +} +declare class Transitionable { + _properties: Properties; + _values: { + [K in keyof Props]: TransitionablePropertyValue; + }; + constructor(properties: Properties); + getValue(name: S): PropertyValueSpecification | void; + setValue(name: S, value: PropertyValueSpecification | void): void; + getTransition(name: S): TransitionSpecification | void; + setTransition(name: S, value: TransitionSpecification | void): void; + serialize(): any; + transitioned(parameters: TransitionParameters, prior: Transitioning): Transitioning; + untransitioned(): Transitioning; +} +declare class TransitioningPropertyValue { + property: Property; + value: PropertyValue; + prior: TransitioningPropertyValue; + begin: TimePoint; + end: TimePoint; + constructor(property: Property, value: PropertyValue, prior: TransitioningPropertyValue, transition: TransitionSpecification, now: TimePoint); + possiblyEvaluate(parameters: EvaluationParameters, canonical: CanonicalTileID, availableImages: Array): R; +} +declare class Transitioning { + _properties: Properties; + _values: { + [K in keyof Props]: PossiblyEvaluatedPropertyValue; + }; + constructor(properties: Properties); + possiblyEvaluate(parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): PossiblyEvaluated; + hasTransition(): boolean; +} +declare class Layout { + _properties: Properties; + _values: { + [K in keyof Props]: PropertyValue>; + }; + constructor(properties: Properties); + hasValue(name: S): boolean; + getValue(name: S): any; + setValue(name: S, value: any): void; + serialize(): any; + possiblyEvaluate(parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): PossiblyEvaluated; +} +/** + * "Possibly evaluated value" is an intermediate stage in the evaluation chain for both paint and layout property + * values. The purpose of this stage is to optimize away unnecessary recalculations for data-driven properties. Code + * which uses data-driven property values must assume that the value is dependent on feature data, and request that it + * be evaluated for each feature. But when that property value is in fact a constant or camera function, the calculation + * will not actually depend on the feature, and we can benefit from returning the prior result of having done the + * evaluation once, ahead of time, in an intermediate step whose inputs are just the value and "global" parameters + * such as current zoom level. + * + * `PossiblyEvaluatedValue` represents the three possible outcomes of this step: if the input value was a constant or + * camera expression, then the "possibly evaluated" result is a constant value. Otherwise, the input value was either + * a source or composite expression, and we must defer final evaluation until supplied a feature. We separate + * the source and composite cases because they are handled differently when generating GL attributes, buffers, and + * uniforms. + * + * Note that `PossiblyEvaluatedValue` (and `PossiblyEvaluatedPropertyValue`, below) are _not_ used for properties that + * do not allow data-driven values. For such properties, we know that the "possibly evaluated" result is always a constant + * scalar value. See below. + */ +export type PossiblyEvaluatedValue = { + kind: "constant"; + value: T; +} | SourceExpression | CompositeExpression; +declare class PossiblyEvaluatedPropertyValue { + property: DataDrivenProperty; + value: PossiblyEvaluatedValue; + parameters: EvaluationParameters; + constructor(property: DataDrivenProperty, value: PossiblyEvaluatedValue, parameters: EvaluationParameters); + isConstant(): boolean; + constantOr(value: T): T; + evaluate(feature: Feature, featureState: FeatureState, canonical?: CanonicalTileID, availableImages?: Array): T; +} +declare class PossiblyEvaluated { + _properties: Properties; + _values: PossibleEvaluatedProps; + constructor(properties: Properties); + get(name: S): PossibleEvaluatedProps[S]; +} +declare class DataConstantProperty implements Property { + specification: StylePropertySpecification; + constructor(specification: StylePropertySpecification); + possiblyEvaluate(value: PropertyValue, parameters: EvaluationParameters): T; + interpolate(a: T, b: T, t: number): T; +} +declare class DataDrivenProperty implements Property> { + specification: StylePropertySpecification; + overrides: any; + constructor(specification: StylePropertySpecification, overrides?: any); + possiblyEvaluate(value: PropertyValue>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): PossiblyEvaluatedPropertyValue; + interpolate(a: PossiblyEvaluatedPropertyValue, b: PossiblyEvaluatedPropertyValue, t: number): PossiblyEvaluatedPropertyValue; + evaluate(value: PossiblyEvaluatedValue, parameters: EvaluationParameters, feature: Feature, featureState: FeatureState, canonical?: CanonicalTileID, availableImages?: Array): T; +} +declare class CrossFadedDataDrivenProperty extends DataDrivenProperty> { + possiblyEvaluate(value: PropertyValue, PossiblyEvaluatedPropertyValue>>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): PossiblyEvaluatedPropertyValue>; + evaluate(value: PossiblyEvaluatedValue>, globals: EvaluationParameters, feature: Feature, featureState: FeatureState, canonical?: CanonicalTileID, availableImages?: Array): CrossFaded; + _calculate(min: T, mid: T, max: T, parameters: EvaluationParameters): CrossFaded; + interpolate(a: PossiblyEvaluatedPropertyValue>): PossiblyEvaluatedPropertyValue>; +} +declare class CrossFadedProperty implements Property> { + specification: StylePropertySpecification; + constructor(specification: StylePropertySpecification); + possiblyEvaluate(value: PropertyValue>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): CrossFaded; + _calculate(min: T, mid: T, max: T, parameters: EvaluationParameters): CrossFaded; + interpolate(a?: CrossFaded | null): CrossFaded; +} +declare class ColorRampProperty implements Property { + specification: StylePropertySpecification; + constructor(specification: StylePropertySpecification); + possiblyEvaluate(value: PropertyValue, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): boolean; + interpolate(): boolean; +} +declare class Properties { + properties: Props; + defaultPropertyValues: { + [K in keyof Props]: PropertyValue; + }; + defaultTransitionablePropertyValues: { + [K in keyof Props]: TransitionablePropertyValue; + }; + defaultTransitioningPropertyValues: { + [K in keyof Props]: TransitioningPropertyValue; + }; + defaultPossiblyEvaluatedValues: { + [K in keyof Props]: PossiblyEvaluatedPropertyValue; + }; + overridableProperties: Array; + constructor(properties: Props); +} +export type Size = { + width: number; + height: number; +}; +export type Point2D = { + x: number; + y: number; +}; +declare class AlphaImage { + width: number; + height: number; + data: Uint8Array; + constructor(size: Size, data?: Uint8Array | Uint8ClampedArray); + resize(size: Size): void; + clone(): AlphaImage; + static copy(srcImg: AlphaImage, dstImg: AlphaImage, srcPt: Point2D, dstPt: Point2D, size: Size): void; +} +declare class RGBAImage { + width: number; + height: number; + /** + * data must be a Uint8Array instead of Uint8ClampedArray because texImage2D does not support Uint8ClampedArray in all browsers. + */ + data: Uint8Array; + constructor(size: Size, data?: Uint8Array | Uint8ClampedArray); + resize(size: Size): void; + replace(data: Uint8Array | Uint8ClampedArray, copy?: boolean): void; + clone(): RGBAImage; + static copy(srcImg: RGBAImage | ImageData, dstImg: RGBAImage, srcPt: Point2D, dstPt: Point2D, size: Size): void; +} +/** + * The sprite data + */ +export type SpriteOnDemandStyleImage = { + width: number; + height: number; + x: number; + y: number; + context: CanvasRenderingContext2D; +}; +/** + * The style's image metadata + */ +export type StyleImageData = { + data: RGBAImage; + version?: number; + hasRenderCallback?: boolean; + userImage?: StyleImageInterface; + spriteData?: SpriteOnDemandStyleImage; +}; +/** + * Enumeration of possible values for StyleImageMetadata.textFitWidth and textFitHeight. + */ +export declare const enum TextFit { + /** + * The image will be resized on the specified axis to tightly fit the content rectangle to target text. + * This is the same as not being defined. + */ + stretchOrShrink = "stretchOrShrink", + /** + * The image will be resized on the specified axis to fit the content rectangle to the target text, but will not + * fall below the aspect ratio of the original content rectangle if the other axis is set to proportional. + */ + stretchOnly = "stretchOnly", + /** + * The image will be resized on the specified axis to fit the content rectangle to the target text and + * will resize the other axis to maintain the aspect ratio of the content rectangle. + */ + proportional = "proportional" +} +/** + * The style's image metadata + */ +export type StyleImageMetadata = { + /** + * The ratio of pixels in the image to physical pixels on the screen + */ + pixelRatio: number; + /** + * Whether the image should be interpreted as an SDF image + */ + sdf: boolean; + /** + * 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. + */ + stretchX?: Array<[ + number, + number + ]>; + /** + * 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. + */ + stretchY?: Array<[ + number, + number + ]>; + /** + * 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`. + */ + content?: [ + number, + number, + number, + number + ]; + /** + * If `icon-text-fit` is used in a layer with this image, this option defines constraints on the horizontal scaling of the image. + */ + textFitWidth?: TextFit; + /** + * If `icon-text-fit` is used in a layer with this image, this option defines constraints on the vertical scaling of the image. + */ + textFitHeight?: TextFit; +}; +/** + * the style's image, including data and metedata + */ +export type StyleImage = StyleImageData & StyleImageMetadata; +/** + * Interface for dynamically generated style images. This is a specification for + * implementers to model: it is not an exported method or class. + * + * Images implementing this interface can be redrawn for every frame. They can be used to animate + * icons and patterns or make them respond to user input. Style images can implement a + * {@link StyleImageInterface#render} method. The method is called every frame and + * can be used to update the image. + * + * @see [Add an animated icon to the map.](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-animated/) + * + * @example + * ```ts + * let flashingSquare = { + * width: 64, + * height: 64, + * data: new Uint8Array(64 * 64 * 4), + * + * onAdd: function(map) { + * this.map = map; + * }, + * + * render: function() { + * // keep repainting while the icon is on the map + * this.map.triggerRepaint(); + * + * // alternate between black and white based on the time + * let value = Math.round(Date.now() / 1000) % 2 === 0 ? 255 : 0; + * + * // check if image needs to be changed + * if (value !== this.previousValue) { + * this.previousValue = value; + * + * let bytesPerPixel = 4; + * for (let x = 0; x < this.width; x++) { + * for (let y = 0; y < this.height; y++) { + * let offset = (y * this.width + x) * bytesPerPixel; + * this.data[offset + 0] = value; + * this.data[offset + 1] = value; + * this.data[offset + 2] = value; + * this.data[offset + 3] = 255; + * } + * } + * + * // return true to indicate that the image changed + * return true; + * } + * } + * } + * + * map.addImage('flashing_square', flashingSquare); + * ``` + */ +export interface StyleImageInterface { + width: number; + height: number; + data: Uint8Array | Uint8ClampedArray; + /** + * This method is called once before every frame where the icon will be used. + * The method can optionally update the image's `data` member with a new image. + * + * If the method updates the image it must return `true` to commit the change. + * If the method returns `false` or nothing the image is assumed to not have changed. + * + * If updates are infrequent it maybe easier to use {@link Map#updateImage} to update + * the image instead of implementing this method. + * + * @returns `true` if this method updated the image. `false` if the image was not changed. + */ + render?: () => boolean; + /** + * Optional method called when the layer has been added to the Map with {@link Map#addImage}. + * + * @param map - The Map this custom layer was just added to. + */ + onAdd?: (map: Map$1, id: string) => void; + /** + * Optional method called when the icon is removed from the map with {@link Map#removeImage}. + * This gives the image a chance to clean up resources and event listeners. + */ + onRemove?: () => void; +} +declare class IndexBuffer { + context: Context; + buffer: WebGLBuffer; + dynamicDraw: boolean; + constructor(context: Context, array: TriangleIndexArray | LineIndexArray | LineStripIndexArray, dynamicDraw?: boolean); + bind(): void; + updateData(array: StructArray): void; + destroy(): void; +} +export type SerializedFeaturePositionMap = { + ids: Float64Array; + positions: Uint32Array; +}; +export type FeaturePosition = { + index: number; + start: number; + end: number; +}; +declare class FeaturePositionMap { + ids: Array; + positions: Array; + indexed: boolean; + constructor(); + add(id: unknown, index: number, start: number, end: number): void; + getPositions(id: unknown): Array; + static serialize(map: FeaturePositionMap, transferables: Array): SerializedFeaturePositionMap; + static deserialize(obj: SerializedFeaturePositionMap): FeaturePositionMap; +} +export type $ObjMap any> = { + [K in keyof T]: F extends (v: T[K]) => infer R ? R : never; +}; +export type UniformValues = $ObjMap(u: Uniform) => V>; +export type UniformLocations = { + [_: string]: WebGLUniformLocation; +}; +declare abstract class Uniform { + gl: WebGLRenderingContext | WebGL2RenderingContext; + location: WebGLUniformLocation; + current: T; + constructor(context: Context, location: WebGLUniformLocation); + abstract set(v: T): void; +} +declare class Uniform1i extends Uniform { + constructor(context: Context, location: WebGLUniformLocation); + set(v: number): void; +} +declare class Uniform1f extends Uniform { + constructor(context: Context, location: WebGLUniformLocation); + set(v: number): void; +} +declare class Uniform4f extends Uniform { + constructor(context: Context, location: WebGLUniformLocation); + set(v: vec4): void; +} +declare class UniformMatrix4f extends Uniform { + constructor(context: Context, location: WebGLUniformLocation); + set(v: mat4): void; +} +/** + * @internal + * A uniform bindings + */ +export type UniformBindings = { + [_: string]: Uniform; +}; +declare class VertexArrayObject { + context: Context; + boundProgram: Program; + boundLayoutVertexBuffer: VertexBuffer; + boundPaintVertexBuffers: Array; + boundIndexBuffer: IndexBuffer; + boundVertexOffset: number; + boundDynamicVertexBuffer: VertexBuffer; + boundDynamicVertexBuffer2: VertexBuffer; + boundDynamicVertexBuffer3: VertexBuffer; + vao: any; + constructor(); + bind(context: Context, program: Program, layoutVertexBuffer: VertexBuffer, paintVertexBuffers: Array, indexBuffer?: IndexBuffer | null, vertexOffset?: number | null, dynamicVertexBuffer?: VertexBuffer | null, dynamicVertexBuffer2?: VertexBuffer | null, dynamicVertexBuffer3?: VertexBuffer | null): void; + freshBind(program: Program, layoutVertexBuffer: VertexBuffer, paintVertexBuffers: Array, indexBuffer?: IndexBuffer | null, vertexOffset?: number | null, dynamicVertexBuffer?: VertexBuffer | null, dynamicVertexBuffer2?: VertexBuffer | null, dynamicVertexBuffer3?: VertexBuffer | null): void; + destroy(): void; +} +/** + * @internal + * A single segment of a vector + */ +export type Segment = { + sortKey?: number; + vertexOffset: number; + primitiveOffset: number; + vertexLength: number; + primitiveLength: number; + vaos: { + [_: string]: VertexArrayObject; + }; +}; +declare class SegmentVector { + static MAX_VERTEX_ARRAY_LENGTH: number; + segments: Array; + constructor(segments?: Array); + prepareSegment(numVertices: number, layoutVertexArray: StructArray, indexArray: StructArray, sortKey?: number): Segment; + get(): Segment[]; + destroy(): void; + static simpleSegment(vertexOffset: number, primitiveOffset: number, vertexLength: number, primitiveLength: number): SegmentVector; +} +declare class HeatmapBucket extends CircleBucket { + layers: Array; +} +export type HeatmapPaintProps = { + "heatmap-radius": DataDrivenProperty; + "heatmap-weight": DataDrivenProperty; + "heatmap-intensity": DataConstantProperty; + "heatmap-color": ColorRampProperty; + "heatmap-opacity": DataConstantProperty; +}; +export type HeatmapPaintPropsPossiblyEvaluated = { + "heatmap-radius": PossiblyEvaluatedPropertyValue; + "heatmap-weight": PossiblyEvaluatedPropertyValue; + "heatmap-intensity": number; + "heatmap-color": ColorRampProperty; + "heatmap-opacity": number; +}; +export type BlendFuncConstant = WebGLRenderingContextBase["ZERO"] | WebGLRenderingContextBase["ONE"] | WebGLRenderingContextBase["SRC_COLOR"] | WebGLRenderingContextBase["ONE_MINUS_SRC_COLOR"] | WebGLRenderingContextBase["DST_COLOR"] | WebGLRenderingContextBase["ONE_MINUS_DST_COLOR"] | WebGLRenderingContextBase["SRC_ALPHA"] | WebGLRenderingContextBase["ONE_MINUS_SRC_ALPHA"] | WebGLRenderingContextBase["DST_ALPHA"] | WebGLRenderingContextBase["ONE_MINUS_DST_ALPHA"] | WebGLRenderingContextBase["CONSTANT_COLOR"] | WebGLRenderingContextBase["ONE_MINUS_CONSTANT_COLOR"] | WebGLRenderingContextBase["CONSTANT_ALPHA"] | WebGLRenderingContextBase["ONE_MINUS_CONSTANT_ALPHA"] | WebGLRenderingContextBase["BLEND_COLOR"]; +export type BlendFuncType = [ + BlendFuncConstant, + BlendFuncConstant +]; +export type BlendEquationType = WebGLRenderingContextBase["FUNC_ADD"] | WebGLRenderingContextBase["FUNC_SUBTRACT"] | WebGLRenderingContextBase["FUNC_REVERSE_SUBTRACT"]; +export type ColorMaskType = [ + boolean, + boolean, + boolean, + boolean +]; +export type CompareFuncType = WebGLRenderingContextBase["NEVER"] | WebGLRenderingContextBase["LESS"] | WebGLRenderingContextBase["EQUAL"] | WebGLRenderingContextBase["LEQUAL"] | WebGLRenderingContextBase["GREATER"] | WebGLRenderingContextBase["NOTEQUAL"] | WebGLRenderingContextBase["GEQUAL"] | WebGLRenderingContextBase["ALWAYS"]; +export type DepthMaskType = boolean; +export type DepthRangeType = [ + number, + number +]; +export type DepthFuncType = CompareFuncType; +export type StencilFuncType = { + func: CompareFuncType; + ref: number; + mask: number; +}; +export type StencilOpConstant = WebGLRenderingContextBase["KEEP"] | WebGLRenderingContextBase["ZERO"] | WebGLRenderingContextBase["REPLACE"] | WebGLRenderingContextBase["INCR"] | WebGLRenderingContextBase["INCR_WRAP"] | WebGLRenderingContextBase["DECR"] | WebGLRenderingContextBase["DECR_WRAP"] | WebGLRenderingContextBase["INVERT"]; +export type StencilOpType = [ + StencilOpConstant, + StencilOpConstant, + StencilOpConstant +]; +export type TextureUnitType = number; +export type ViewportType = [ + number, + number, + number, + number +]; +export type StencilTestGL = { + func: WebGLRenderingContextBase["NEVER"]; + mask: 0; +} | { + func: WebGLRenderingContextBase["LESS"]; + mask: number; +} | { + func: WebGLRenderingContextBase["EQUAL"]; + mask: number; +} | { + func: WebGLRenderingContextBase["LEQUAL"]; + mask: number; +} | { + func: WebGLRenderingContextBase["GREATER"]; + mask: number; +} | { + func: WebGLRenderingContextBase["NOTEQUAL"]; + mask: number; +} | { + func: WebGLRenderingContextBase["GEQUAL"]; + mask: number; +} | { + func: WebGLRenderingContextBase["ALWAYS"]; + mask: 0; +}; +export type CullFaceModeType = WebGLRenderingContextBase["FRONT"] | WebGLRenderingContextBase["BACK"] | WebGLRenderingContextBase["FRONT_AND_BACK"]; +export type FrontFaceType = WebGLRenderingContextBase["CW"] | WebGLRenderingContextBase["CCW"]; +export interface IValue { + current: T; + default: T; + dirty: boolean; + get(): T; + setDefault(): void; + set(value: T): void; +} +declare class BaseValue implements IValue { + gl: WebGLRenderingContext | WebGL2RenderingContext; + current: T; + default: T; + dirty: boolean; + constructor(context: Context); + get(): T; + set(value: T): void; + getDefault(): T; + setDefault(): void; +} +declare class ClearColor extends BaseValue { + getDefault(): Color; + set(v: Color): void; +} +declare class ClearDepth extends BaseValue { + getDefault(): number; + set(v: number): void; +} +declare class ClearStencil extends BaseValue { + getDefault(): number; + set(v: number): void; +} +declare class ColorMask extends BaseValue { + getDefault(): ColorMaskType; + set(v: ColorMaskType): void; +} +declare class DepthMask extends BaseValue { + getDefault(): DepthMaskType; + set(v: DepthMaskType): void; +} +declare class StencilMask extends BaseValue { + getDefault(): number; + set(v: number): void; +} +declare class StencilFunc extends BaseValue { + getDefault(): StencilFuncType; + set(v: StencilFuncType): void; +} +declare class StencilOp extends BaseValue { + getDefault(): StencilOpType; + set(v: StencilOpType): void; +} +declare class StencilTest extends BaseValue { + getDefault(): boolean; + set(v: boolean): void; +} +declare class DepthRange extends BaseValue { + getDefault(): DepthRangeType; + set(v: DepthRangeType): void; +} +declare class DepthTest extends BaseValue { + getDefault(): boolean; + set(v: boolean): void; +} +declare class DepthFunc extends BaseValue { + getDefault(): DepthFuncType; + set(v: DepthFuncType): void; +} +declare class Blend extends BaseValue { + getDefault(): boolean; + set(v: boolean): void; +} +declare class BlendFunc extends BaseValue { + getDefault(): BlendFuncType; + set(v: BlendFuncType): void; +} +declare class BlendColor extends BaseValue { + getDefault(): Color; + set(v: Color): void; +} +declare class BlendEquation extends BaseValue { + getDefault(): BlendEquationType; + set(v: BlendEquationType): void; +} +declare class CullFace extends BaseValue { + getDefault(): boolean; + set(v: boolean): void; +} +declare class CullFaceSide extends BaseValue { + getDefault(): CullFaceModeType; + set(v: CullFaceModeType): void; +} +declare class FrontFace extends BaseValue { + getDefault(): FrontFaceType; + set(v: FrontFaceType): void; +} +declare class ProgramValue extends BaseValue { + getDefault(): WebGLProgram; + set(v?: WebGLProgram | null): void; +} +declare class ActiveTextureUnit extends BaseValue { + getDefault(): TextureUnitType; + set(v: TextureUnitType): void; +} +declare class Viewport extends BaseValue { + getDefault(): ViewportType; + set(v: ViewportType): void; +} +declare class BindFramebuffer extends BaseValue { + getDefault(): WebGLFramebuffer; + set(v?: WebGLFramebuffer | null): void; +} +declare class BindRenderbuffer extends BaseValue { + getDefault(): WebGLRenderbuffer; + set(v?: WebGLRenderbuffer | null): void; +} +declare class BindTexture extends BaseValue { + getDefault(): WebGLTexture; + set(v?: WebGLTexture | null): void; +} +declare class BindVertexBuffer extends BaseValue { + getDefault(): WebGLBuffer; + set(v?: WebGLBuffer | null): void; +} +declare class BindElementBuffer extends BaseValue { + getDefault(): WebGLBuffer; + set(v?: WebGLBuffer | null): void; +} +declare class BindVertexArray extends BaseValue { + getDefault(): WebGLVertexArrayObject | null; + set(v: WebGLVertexArrayObject | null): void; +} +declare class PixelStoreUnpack extends BaseValue { + getDefault(): number; + set(v: number): void; +} +declare class PixelStoreUnpackPremultiplyAlpha extends BaseValue { + getDefault(): boolean; + set(v: boolean): void; +} +declare class PixelStoreUnpackFlipY extends BaseValue { + getDefault(): boolean; + set(v: boolean): void; +} +declare class FramebufferAttachment extends BaseValue { + parent: WebGLFramebuffer; + context: Context; + constructor(context: Context, parent: WebGLFramebuffer); + getDefault(): any; +} +declare class ColorAttachment extends FramebufferAttachment { + setDirty(): void; + set(v?: WebGLTexture | null): void; +} +declare class DepthAttachment extends FramebufferAttachment { + set(v?: WebGLRenderbuffer | null): void; +} +declare class Framebuffer { + context: Context; + width: number; + height: number; + framebuffer: WebGLFramebuffer; + colorAttachment: ColorAttachment; + depthAttachment: DepthAttachment; + constructor(context: Context, width: number, height: number, hasDepth: boolean, hasStencil: boolean); + destroy(): void; +} +declare class HeatmapStyleLayer extends StyleLayer { + heatmapFbos: Map; + colorRamp: RGBAImage; + colorRampTexture: Texture; + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + createBucket(options: any): HeatmapBucket; + constructor(layer: LayerSpecification); + _handleSpecialPaintPropertyUpdate(name: string): void; + _updateColorRamp(): void; + resize(): void; + queryRadius(): number; + queryIntersectsFeature(): boolean; + hasOffscreenPass(): boolean; +} +export type SerializedGrid = { + buffer: ArrayBuffer; +}; +declare class TransferableGridIndex { + cells: number[][]; + arrayBuffer: ArrayBuffer; + d: number; + keys: number[]; + bboxes: number[]; + n: number; + extent: number; + padding: number; + scale: any; + uid: number; + min: number; + max: number; + constructor(extent: number | ArrayBuffer, n?: number, padding?: number); + insert(key: number, x1: number, y1: number, x2: number, y2: number): void; + _insertReadonly(): void; + _insertCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number): void; + query(x1: number, y1: number, x2: number, y2: number, intersectionTest?: Function): number[]; + _queryCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: any, seenUids: any, intersectionTest: Function): void; + _forEachCell(x1: number, y1: number, x2: number, y2: number, fn: Function, arg1: any, arg2: any, intersectionTest: any): void; + _convertFromCellCoord(x: any): number; + _convertToCellCoord(x: any): number; + toArrayBuffer(): ArrayBuffer; + static serialize(grid: TransferableGridIndex, transferables?: Array): SerializedGrid; + static deserialize(serialized: SerializedGrid): TransferableGridIndex; +} +declare class DictionaryCoder { + _stringToNumber: { + [_: string]: number; + }; + _numberToString: Array; + constructor(strings: Array); + encode(string: string): number; + decode(n: number): string; +} +/** + * A helper for type to omit a property from a type + */ +export type DistributiveKeys = T extends T ? keyof T : never; +/** + * A helper for type to omit a property from a type + */ +export type DistributiveOmit> = T extends unknown ? Omit : never; +/** + * An extended geojson feature used by the events to return data to the listener + */ +export type MapGeoJSONFeature = GeoJSONFeature & { + layer: DistributiveOmit & { + source: string; + }; + source: string; + sourceLayer?: string; + state: { + [key: string]: any; + }; +}; +declare class GeoJSONFeature { + type: "Feature"; + _geometry: GeoJSON.Geometry; + properties: { + [name: string]: any; + }; + id: number | string | undefined; + _vectorTileFeature: VectorTileFeature; + constructor(vectorTileFeature: VectorTileFeature, z: number, x: number, y: number, id: string | number | undefined); + get geometry(): GeoJSON.Geometry; + set geometry(g: GeoJSON.Geometry); + toJSON(): any; +} +/** + * A {@link LngLatBounds} object, an array of {@link LngLatLike} objects in [sw, ne] order, + * or an array of numbers in [west, south, east, north] order. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let v1 = new LngLatBounds( + * new LngLat(-73.9876, 40.7661), + * new LngLat(-73.9397, 40.8002) + * ); + * let v2 = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]) + * let v3 = [[-73.9876, 40.7661], [-73.9397, 40.8002]]; + * ``` + */ +export type LngLatBoundsLike = LngLatBounds | [ + LngLatLike, + LngLatLike +] | [ + number, + number, + number, + number +]; +/** + * A `LngLatBounds` object represents a geographical bounding box, + * defined by its southwest and northeast points in longitude and latitude. + * + * If no arguments are provided to the constructor, a `null` bounding box is created. + * + * Note that any Mapbox GL method that accepts a `LngLatBounds` object as an argument or option + * can also accept an `Array` of two {@link LngLatLike} constructs and will perform an implicit conversion. + * This flexible type is documented as {@link LngLatBoundsLike}. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let sw = new LngLat(-73.9876, 40.7661); + * let ne = new LngLat(-73.9397, 40.8002); + * let llb = new LngLatBounds(sw, ne); + * ``` + */ +export declare class LngLatBounds { + _ne: LngLat; + _sw: LngLat; + /** + * @param sw - The southwest corner of the bounding box. + * OR array of 4 numbers in the order of west, south, east, north + * OR array of 2 LngLatLike: [sw,ne] + * @param ne - The northeast corner of the bounding box. + * @example + * ```ts + * let sw = new LngLat(-73.9876, 40.7661); + * let ne = new LngLat(-73.9397, 40.8002); + * let llb = new LngLatBounds(sw, ne); + * ``` + * OR + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661, -73.9397, 40.8002]); + * ``` + * OR + * ```ts + * let llb = new LngLatBounds([sw, ne]); + * ``` + */ + constructor(sw?: LngLatLike | [ + number, + number, + number, + number + ] | [ + LngLatLike, + LngLatLike + ], ne?: LngLatLike); + /** + * Set the northeast corner of the bounding box + * + * @param ne - a {@link LngLatLike} object describing the northeast corner of the bounding box. + */ + setNorthEast(ne: LngLatLike): this; + /** + * Set the southwest corner of the bounding box + * + * @param sw - a {@link LngLatLike} object describing the southwest corner of the bounding box. + */ + setSouthWest(sw: LngLatLike): this; + /** + * Extend the bounds to include a given LngLatLike or LngLatBoundsLike. + * + * @param obj - object to extend to + */ + extend(obj: LngLatLike | LngLatBoundsLike): this; + /** + * Returns the geographical coordinate equidistant from the bounding box's corners. + * + * @returns The bounding box's center. + * @example + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]); + * llb.getCenter(); // = LngLat {lng: -73.96365, lat: 40.78315} + * ``` + */ + getCenter(): LngLat; + /** + * Returns the southwest corner of the bounding box. + * + * @returns The southwest corner of the bounding box. + */ + getSouthWest(): LngLat; + /** + * Returns the northeast corner of the bounding box. + * + * @returns The northeast corner of the bounding box. + */ + getNorthEast(): LngLat; + /** + * Returns the northwest corner of the bounding box. + * + * @returns The northwest corner of the bounding box. + */ + getNorthWest(): LngLat; + /** + * Returns the southeast corner of the bounding box. + * + * @returns The southeast corner of the bounding box. + */ + getSouthEast(): LngLat; + /** + * Returns the west edge of the bounding box. + * + * @returns The west edge of the bounding box. + */ + getWest(): number; + /** + * Returns the south edge of the bounding box. + * + * @returns The south edge of the bounding box. + */ + getSouth(): number; + /** + * Returns the east edge of the bounding box. + * + * @returns The east edge of the bounding box. + */ + getEast(): number; + /** + * Returns the north edge of the bounding box. + * + * @returns The north edge of the bounding box. + */ + getNorth(): number; + /** + * Returns the bounding box represented as an array. + * + * @returns The bounding box represented as an array, consisting of the + * southwest and northeast coordinates of the bounding represented as arrays of numbers. + * @example + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]); + * llb.toArray(); // = [[-73.9876, 40.7661], [-73.9397, 40.8002]] + * ``` + */ + toArray(): [ + number, + number + ][]; + /** + * Return the bounding box represented as a string. + * + * @returns The bounding box represents as a string of the format + * `'LngLatBounds(LngLat(lng, lat), LngLat(lng, lat))'`. + * @example + * ```ts + * let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]); + * llb.toString(); // = "LngLatBounds(LngLat(-73.9876, 40.7661), LngLat(-73.9397, 40.8002))" + * ``` + */ + toString(): string; + /** + * Check if the bounding box is an empty/`null`-type box. + * + * @returns True if bounds have been defined, otherwise false. + */ + isEmpty(): boolean; + /** + * Check if the point is within the bounding box. + * + * @param lnglat - geographic point to check against. + * @returns `true` if the point is within the bounding box. + * @example + * ```ts + * let llb = new LngLatBounds( + * new LngLat(-73.9876, 40.7661), + * new LngLat(-73.9397, 40.8002) + * ); + * + * let ll = new LngLat(-73.9567, 40.7789); + * + * console.log(llb.contains(ll)); // = true + * ``` + */ + contains(lnglat: LngLatLike): boolean; + /** + * Converts an array to a `LngLatBounds` object. + * + * If a `LngLatBounds` object is passed in, the function returns it unchanged. + * + * Internally, the function calls `LngLat#convert` to convert arrays to `LngLat` values. + * + * @param input - An array of two coordinates to convert, or a `LngLatBounds` object to return. + * @returns A new `LngLatBounds` object, if a conversion occurred, or the original `LngLatBounds` object. + * @example + * ```ts + * let arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]]; + * let llb = LngLatBounds.convert(arr); // = LngLatBounds {_sw: LngLat {lng: -73.9876, lat: 40.7661}, _ne: LngLat {lng: -73.9397, lat: 40.8002}} + * ``` + */ + static convert(input: LngLatBoundsLike | null): LngLatBounds; + /** + * Returns a `LngLatBounds` from the coordinates extended by a given `radius`. The returned `LngLatBounds` completely contains the `radius`. + * + * @param center - center coordinates of the new bounds. + * @param radius - Distance in meters from the coordinates to extend the bounds. + * @returns A new `LngLatBounds` object representing the coordinates extended by the `radius`. + * @example + * ```ts + * let center = new LngLat(-73.9749, 40.7736); + * LngLatBounds.fromLngLat(100).toArray(); // = [[-73.97501862141328, 40.77351016847229], [-73.97478137858673, 40.77368983152771]] + * ``` + */ + static fromLngLat(center: LngLat, radius?: number): LngLatBounds; + /** + * Adjusts the given bounds to handle the case where the bounds cross the 180th meridian (antimeridian). + * + * @returns The adjusted LngLatBounds + * @example + * ```ts + * let bounds = new LngLatBounds([175.813127, -20.157768], [-178. 340903, -15.449124]); + * let adjustedBounds = bounds.adjustAntiMeridian(); + * // adjustedBounds will be: [[175.813127, -20.157768], [181.659097, -15.449124]] + * ``` + */ + adjustAntiMeridian(): LngLatBounds; +} +/** + * An `EdgeInset` object represents screen space padding applied to the edges of the viewport. + * This shifts the apprent center or the vanishing point of the map. This is useful for adding floating UI elements + * on top of the map and having the vanishing point shift as UI elements resize. + * + * @group Geography and Geometry + */ +export declare class EdgeInsets { + /** + * @defaultValue 0 + */ + top: number; + /** + * @defaultValue 0 + */ + bottom: number; + /** + * @defaultValue 0 + */ + left: number; + /** + * @defaultValue 0 + */ + right: number; + constructor(top?: number, bottom?: number, left?: number, right?: number); + /** + * Interpolates the inset in-place. + * This maintains the current inset value for any inset not present in `target`. + * @param start - interpolation start + * @param target - interpolation target + * @param t - interpolation step/weight + * @returns the insets + */ + interpolate(start: PaddingOptions | EdgeInsets, target: PaddingOptions, t: number): EdgeInsets; + /** + * Utility method that computes the new apprent center or vanishing point after applying insets. + * This is in pixels and with the top left being (0.0) and +y being downwards. + * + * @param width - the width + * @param height - the height + * @returns the point + */ + getCenter(width: number, height: number): Point; + equals(other: PaddingOptions): boolean; + clone(): EdgeInsets; + /** + * Returns the current state as json, useful when you want to have a + * read-only representation of the inset. + * + * @returns state as json + */ + toJSON(): PaddingOptions; +} +/** + * 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 + * non-negative integers. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let bbox = [[-79, 43], [-73, 45]]; + * map.fitBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + * + * @example + * ```ts + * let bbox = [[-79, 43], [-73, 45]]; + * map.fitBounds(bbox, { + * padding: 20 + * }); + * ``` + * @see [Fit to the bounds of a LineString](https://maplibre.org/maplibre-gl-js/docs/examples/zoomto-linestring/) + * @see [Fit a map to a bounding box](https://maplibre.org/maplibre-gl-js/docs/examples/fitbounds/) + */ +export type PaddingOptions = { + /** + * Padding in pixels from the top of the map canvas. + */ + top: number; + /** + * Padding in pixels from the bottom of the map canvas. + */ + bottom: number; + /** + * Padding in pixels from the left of the map canvas. + */ + right: number; + /** + * Padding in pixels from the right of the map canvas. + */ + left: number; +}; +declare class TileCache { + max: number; + data: { + [key: string]: Array<{ + value: Tile; + timeout: ReturnType; + }>; + }; + order: Array; + onRemove: (element: Tile) => void; + /** + * @param max - number of permitted values + * @param onRemove - callback called with items when they expire + */ + constructor(max: number, onRemove: (element: Tile) => void); + /** + * Clear the cache + * + * @returns this cache + */ + reset(): this; + /** + * Add a key, value combination to the cache, trimming its size if this pushes + * it over max length. + * + * @param tileID - lookup key for the item + * @param data - tile data + * + * @returns this cache + */ + add(tileID: OverscaledTileID, data: Tile, expiryTimeout: number | void): this; + /** + * Determine whether the value attached to `key` is present + * + * @param tileID - the key to be looked-up + * @returns whether the cache has this value + */ + has(tileID: OverscaledTileID): boolean; + /** + * Get the value attached to a specific key and remove data from cache. + * If the key is not found, returns `null` + * + * @param tileID - the key to look up + * @returns the tile data, or null if it isn't found + */ + getAndRemove(tileID: OverscaledTileID): Tile; + _getAndRemoveByKey(key: string): Tile; + getByKey(key: string): Tile; + /** + * Get the value attached to a specific key without removing data + * from the cache. If the key is not found, returns `null` + * + * @param tileID - the key to look up + * @returns the tile data, or null if it isn't found + */ + get(tileID: OverscaledTileID): Tile; + /** + * Remove a key/value combination from the cache. + * + * @param tileID - the key for the pair to delete + * @param value - If a value is provided, remove that exact version of the value. + * @returns this cache + */ + remove(tileID: OverscaledTileID, value?: { + value: Tile; + timeout: ReturnType; + }): this; + /** + * Change the max size of the cache. + * + * @param max - the max size of the cache + * @returns this cache + */ + setMaxSize(max: number): TileCache; + /** + * Remove entries that do not pass a filter function. Used for removing + * stale tiles from the cache. + * + * @param filterFn - Determines whether the tile is filtered. If the supplied function returns false, the tile will be filtered out. + */ + filter(filterFn: (tile: Tile) => boolean): void; +} +declare class WorkerPool { + static workerCount: number; + active: { + [_ in number | string]: boolean; + }; + workers: Array; + constructor(); + acquire(mapId: number | string): Array; + release(mapId: number | string): void; + isPreloaded(): boolean; + numActive(): number; +} +declare class Dispatcher { + workerPool: WorkerPool; + actors: Array; + currentActor: number; + id: string | number; + constructor(workerPool: WorkerPool, mapId: string | number); + /** + * Broadcast a message to all Workers. + */ + broadcast(type: T, data: RequestResponseMessageMap[T][0]): Promise; + /** + * Acquires an actor to dispatch messages to. The actors are distributed in round-robin fashion. + * @returns An actor object backed by a web worker for processing messages. + */ + getActor(): Actor; + remove(mapRemoved?: boolean): void; + registerMessageHandler(type: T, handler: MessageHandler): void; +} +/** + * Four geographical coordinates, + * represented as arrays of longitude and latitude numbers, which define the corners of the image. + * The coordinates start at the top left corner of the image and proceed in clockwise order. + * They do not have to represent a rectangle. + */ +export type Coordinates = [ + [ + number, + number + ], + [ + number, + number + ], + [ + number, + number + ], + [ + number, + number + ] +]; +/** + * The options object for the {@link ImageSource#updateImage} method + */ +export type UpdateImageOptions = { + /** + * Required image URL. + */ + url: string; + /** + * The image coordinates + */ + coordinates?: Coordinates; +}; +/** + * A data source containing an image. + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-image) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * // add to map + * map.addSource('some id', { + * type: 'image', + * url: 'https://www.maplibre.org/images/foo.png', + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update coordinates + * let mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * // update url and coordinates simultaneously + * mySource.updateImage({ + * url: 'https://www.maplibre.org/images/bar.png', + * coordinates: [ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ] + * }) + * + * map.removeSource('some id'); // remove + * ``` + */ +export declare class ImageSource extends Evented implements Source { + type: string; + id: string; + minzoom: number; + maxzoom: number; + tileSize: number; + url: string; + coordinates: Coordinates; + tiles: { + [_: string]: Tile; + }; + options: any; + dispatcher: Dispatcher; + map: Map$1; + texture: Texture | null; + image: HTMLImageElement | ImageBitmap; + tileID: CanonicalTileID; + _boundsArray: RasterBoundsArray; + boundsBuffer: VertexBuffer; + boundsSegments: SegmentVector; + _loaded: boolean; + _request: AbortController; + /** @internal */ + constructor(id: string, options: ImageSourceSpecification | VideoSourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented); + load(newCoordinates?: Coordinates): Promise; + loaded(): boolean; + /** + * Updates the image URL and, optionally, the coordinates. To avoid having the image flash after changing, + * set the `raster-fade-duration` paint property on the raster layer to 0. + * + * @param options - The options object. + */ + updateImage(options: UpdateImageOptions): this; + _finishLoading(): void; + onAdd(map: Map$1): void; + onRemove(): void; + /** + * Sets the image's coordinates and re-renders the map. + * + * @param coordinates - Four geographical coordinates, + * represented as arrays of longitude and latitude numbers, which define the corners of the image. + * The coordinates start at the top left corner of the image and proceed in clockwise order. + * They do not have to represent a rectangle. + */ + setCoordinates(coordinates: Coordinates): this; + prepare(): void; + loadTile(tile: Tile): Promise; + serialize(): ImageSourceSpecification | VideoSourceSpecification | CanvasSourceSpecification; + hasTransition(): boolean; +} +/** + * Options to add a canvas source type to the map. + */ +export type CanvasSourceSpecification = { + /** + * Source type. Must be `"canvas"`. + */ + type: "canvas"; + /** + * Four geographical coordinates denoting where to place the corners of the canvas, specified in `[longitude, latitude]` pairs. + */ + coordinates: [ + [ + number, + number + ], + [ + number, + number + ], + [ + number, + number + ], + [ + number, + number + ] + ]; + /** + * 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. + * @defaultValue true + */ + animate?: boolean; + /** + * Canvas source from which to read pixels. Can be a string representing the ID of the canvas element, or the `HTMLCanvasElement` itself. + */ + canvas?: string | HTMLCanvasElement; +}; +/** + * A data source containing the contents of an HTML canvas. See {@link CanvasSourceSpecification} for detailed documentation of options. + * + * @group Sources + * + * @example + * ```ts + * // add to map + * map.addSource('some id', { + * type: 'canvas', + * canvas: 'idOfMyHTMLCanvas', + * animate: true, + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update + * let mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * map.removeSource('some id'); // remove + * ``` + */ +export declare class CanvasSource extends ImageSource { + options: CanvasSourceSpecification; + animate: boolean; + canvas: HTMLCanvasElement; + width: number; + height: number; + /** + * Enables animation. The image will be copied from the canvas to the map on each frame. + */ + play: () => void; + /** + * Disables animation. The map will display a static copy of the canvas image. + */ + pause: () => void; + _playing: boolean; + /** @internal */ + constructor(id: string, options: CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented); + load(): Promise; + /** + * Returns the HTML `canvas` element. + * + * @returns The HTML `canvas` element. + */ + getCanvas(): HTMLCanvasElement; + onAdd(map: Map$1): void; + onRemove(): void; + prepare(): void; + serialize(): CanvasSourceSpecification; + hasTransition(): boolean; + _hasInvalidDimensions(): boolean; +} +/** + * The `Source` interface must be implemented by each source type, including "core" types (`vector`, `raster`, + * `video`, etc.) and all custom, third-party types. + * + * **Event** `data` - Fired with `{dataType: 'source', sourceDataType: 'metadata'}` to indicate that any necessary metadata + * has been loaded so that it's okay to call `loadTile`; and with `{dataType: 'source', sourceDataType: 'content'}` + * to indicate that the source data has changed, so that any current caches should be flushed. + * + * @group Sources + */ +export interface Source { + readonly type: string; + /** + * The id for the source. Must not be used by any existing source. + */ + id: string; + /** + * The minimum zoom level for the source. + */ + minzoom: number; + /** + * The maximum zoom level for the source. + */ + maxzoom: number; + /** + * The tile size for the source. + */ + tileSize: number; + /** + * The attribution for the source. + */ + attribution?: string; + /** + * `true` if zoom levels are rounded to the nearest integer in the source data, `false` if they are floor-ed to the nearest integer. + */ + roundZoom?: boolean; + /** + * `false` if tiles can be drawn outside their boundaries, `true` if they cannot. + */ + isTileClipped?: boolean; + tileID?: CanonicalTileID; + /** + * `true` if tiles should be sent back to the worker for each overzoomed zoom level, `false` if not. + */ + reparseOverscaled?: boolean; + vectorLayerIds?: Array; + /** + * True if the source has transition, false otherwise. + */ + hasTransition(): boolean; + /** + * True if the source is loaded, false otherwise. + */ + loaded(): boolean; + /** + * An ability to fire an event to all the listeners, see {@link Evented} + * @param event - The event to fire + */ + fire(event: Event$1): unknown; + /** + * This method is called when the source is added to the map. + * @param map - The map instance + */ + onAdd?(map: Map$1): void; + /** + * This method is called when the source is removed from the map. + * @param map - The map instance + */ + onRemove?(map: Map$1): void; + /** + * This method does the heavy lifting of loading a tile. + * In most cases it will defer the work to the relevant worker source. + * @param tile - The tile to load + */ + loadTile(tile: Tile): Promise; + /** + * True is the tile is part of the source, false otherwise. + * @param tileID - The tile ID + */ + hasTile?(tileID: OverscaledTileID): boolean; + /** + * Allows to abort a tile loading. + * @param tile - The tile to abort + */ + abortTile?(tile: Tile): Promise; + /** + * Allows to unload a tile. + * @param tile - The tile to unload + */ + unloadTile?(tile: Tile): Promise; + /** + * @returns A plain (stringifiable) JS object representing the current state of the source. + * Creating a source using the returned object as the `options` should result in a Source that is + * equivalent to this one. + */ + serialize(): any; + /** + * Allows to execute a prepare step before the source is used. + */ + prepare?(): void; +} +/** + * A general definition of a {@link Source} class for factory usage + */ +export type SourceClass = { + new (id: string, specification: SourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented): Source; +}; +/** + * Adds a custom source type, making it available for use with {@link Map#addSource}. + * @param name - The name of the source type; source definition objects use this name in the `{type: ...}` field. + * @param SourceType - A {@link SourceClass} - which is a constructor for the `Source` interface. + * @returns a promise that is resolved when the source type is ready or rejected with an error. + */ +export declare const addSourceType: (name: string, SourceType: SourceClass) => Promise; +declare class SourceCache extends Evented { + id: string; + dispatcher: Dispatcher; + map: Map$1; + style: Style; + _source: Source; + /** + * @internal + * signifies that the TileJSON is loaded if applicable. + * if the source type does not come with a TileJSON, the flag signifies the + * source data has loaded (i.e geojson has been tiled on the worker and is ready) + */ + _sourceLoaded: boolean; + _sourceErrored: boolean; + _tiles: { + [_: string]: Tile; + }; + _prevLng: number; + _cache: TileCache; + _timers: { + [_ in any]: ReturnType; + }; + _cacheTimers: { + [_ in any]: ReturnType; + }; + _maxTileCacheSize: number; + _maxTileCacheZoomLevels: number; + _paused: boolean; + _shouldReloadOnResume: boolean; + _coveredTiles: { + [_: string]: boolean; + }; + transform: Transform; + terrain: Terrain; + used: boolean; + usedForTerrain: boolean; + tileSize: number; + _state: SourceFeatureState; + _loadedParentTiles: { + [_: string]: Tile; + }; + _loadedSiblingTiles: { + [_: string]: Tile; + }; + _didEmitContent: boolean; + _updated: boolean; + static maxUnderzooming: number; + static maxOverzooming: number; + constructor(id: string, options: SourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher); + onAdd(map: Map$1): void; + onRemove(map: Map$1): void; + /** + * Return true if no tile data is pending, tiles will not change unless + * an additional API call is received. + */ + loaded(): boolean; + getSource(): Source; + pause(): void; + resume(): void; + _loadTile(tile: Tile, id: string, state: TileState): Promise; + _unloadTile(tile: Tile): void; + _abortTile(tile: Tile): void; + serialize(): any; + prepare(context: Context): void; + /** + * Return all tile ids ordered with z-order, and cast to numbers + */ + getIds(): Array; + getRenderableIds(symbolLayer?: boolean): Array; + hasRenderableParent(tileID: OverscaledTileID): boolean; + _isIdRenderable(id: string, symbolLayer?: boolean): boolean; + reload(): void; + _reloadTile(id: string, state: TileState): Promise; + _tileLoaded(tile: Tile, id: string, previousState: TileState): void; + /** + * For raster terrain source, backfill DEM to eliminate visible tile boundaries + */ + _backfillDEM(tile: Tile): void; + /** + * Get a specific tile by TileID + */ + getTile(tileID: OverscaledTileID): Tile; + /** + * Get a specific tile by id + */ + getTileByID(id: string): Tile; + /** + * For a given set of tiles, retain children that are loaded and have a zoom + * between `zoom` (exclusive) and `maxCoveringZoom` (inclusive) + */ + _retainLoadedChildren(idealTiles: { + [_ in any]: OverscaledTileID; + }, zoom: number, maxCoveringZoom: number, retain: { + [_ in any]: OverscaledTileID; + }): void; + /** + * Find a loaded parent of the given tile (up to minCoveringZoom) + */ + findLoadedParent(tileID: OverscaledTileID, minCoveringZoom: number): Tile; + /** + * Find a loaded sibling of the given tile + */ + findLoadedSibling(tileID: OverscaledTileID): Tile; + _getLoadedTile(tileID: OverscaledTileID): Tile; + /** + * Resizes the tile cache based on the current viewport's size + * or the maxTileCacheSize option passed during map creation + * + * Larger viewports use more tiles and need larger caches. Larger viewports + * are more likely to be found on devices with more memory and on pages where + * the map is more important. + */ + updateCacheSize(transform: Transform): void; + handleWrapJump(lng: number): void; + _updateCoveredAndRetainedTiles(retain: { + [_: string]: OverscaledTileID; + }, minCoveringZoom: number, maxCoveringZoom: number, zoom: number, idealTileIDs: OverscaledTileID[], terrain?: Terrain): void; + /** + * Removes tiles that are outside the viewport and adds new tiles that + * are inside the viewport. + */ + update(transform: Transform, terrain?: Terrain): void; + releaseSymbolFadeTiles(): void; + _updateRetainedTiles(idealTileIDs: Array, zoom: number): { + [_: string]: OverscaledTileID; + }; + _updateLoadedParentTileCache(): void; + /** + * Update the cache of loaded sibling tiles + * + * Sibling tiles are tiles that share the same zoom level and + * x/y position but have different wrap values + * Maintaining sibling tile cache allows fading from old to new tiles + * of the same position and zoom level + */ + _updateLoadedSiblingTileCache(): void; + /** + * Add a tile, given its coordinate, to the pyramid. + */ + _addTile(tileID: OverscaledTileID): Tile; + _setTileReloadTimer(id: string, tile: Tile): void; + /** + * Remove a tile, given its id, from the pyramid + */ + _removeTile(id: string): void; + /** @internal */ + private _dataHandler; + /** + * Remove all tiles from this pyramid + */ + clearTiles(): void; + /** + * Search through our current tiles and attempt to find the tiles that + * cover the given bounds. + * @param pointQueryGeometry - coordinates of the corners of bounding rectangle + * @returns result items have `{tile, minX, maxX, minY, maxY}`, where min/max bounding values are the given bounds transformed in into the coordinate space of this tile. + */ + tilesIn(pointQueryGeometry: Array, maxPitchScaleFactor: number, has3DLayer: boolean): any[]; + getVisibleCoordinates(symbolLayer?: boolean): Array; + hasTransition(): boolean; + /** + * Set the value of a particular state for a feature + */ + setFeatureState(sourceLayer: string, featureId: number | string, state: any): void; + /** + * Resets the value of a particular state key for a feature + */ + removeFeatureState(sourceLayer?: string, featureId?: number | string, key?: string): void; + /** + * Get the entire state object for a feature + */ + getFeatureState(sourceLayer: string, featureId: number | string): import("@maplibre/maplibre-gl-style-spec").FeatureState; + /** + * Sets the set of keys that the tile depends on. This allows tiles to + * be reloaded when their dependencies change. + */ + setDependencies(tileKey: string, namespace: string, dependencies: Array): void; + /** + * Reloads all tiles that depend on the given keys. + */ + reloadTilesForDependencies(namespaces: Array, keys: Array): void; +} +/** + * Some metices related to a glyph + */ +export type GlyphMetrics = { + width: number; + height: number; + left: number; + top: number; + advance: number; + /** + * isDoubleResolution = true for 48px textures + */ + isDoubleResolution?: boolean; +}; +/** + * A style glyph type + */ +export type StyleGlyph = { + id: number; + bitmap: AlphaImage; + metrics: GlyphMetrics; +}; +/** + * A rectangle type with postion, width and height. + */ +export type Rect = { + x: number; + y: number; + w: number; + h: number; +}; +/** + * The glyph's position + */ +export type GlyphPosition = { + rect: Rect; + metrics: GlyphMetrics; +}; +/** + * The glyphs' positions + */ +export type GlyphPositions = { + [_: string]: { + [_: number]: GlyphPosition; + }; +}; +declare enum WritingMode { + none = 0, + horizontal = 1, + vertical = 2, + horizontalOnly = 3 +} +declare class Anchor extends Point { + angle: any; + segment?: number; + constructor(x: number, y: number, angle: number, segment?: number); + clone(): Anchor; +} +export type SymbolLayoutProps = { + "symbol-placement": DataConstantProperty<"point" | "line" | "line-center">; + "symbol-spacing": DataConstantProperty; + "symbol-avoid-edges": DataConstantProperty; + "symbol-sort-key": DataDrivenProperty; + "symbol-z-order": DataConstantProperty<"auto" | "viewport-y" | "source">; + "icon-allow-overlap": DataConstantProperty; + "icon-overlap": DataConstantProperty<"never" | "always" | "cooperative">; + "icon-ignore-placement": DataConstantProperty; + "icon-optional": DataConstantProperty; + "icon-rotation-alignment": DataConstantProperty<"map" | "viewport" | "auto">; + "icon-size": DataDrivenProperty; + "icon-text-fit": DataConstantProperty<"none" | "width" | "height" | "both">; + "icon-text-fit-padding": DataConstantProperty<[ + number, + number, + number, + number + ]>; + "icon-image": DataDrivenProperty; + "icon-rotate": DataDrivenProperty; + "icon-padding": DataDrivenProperty; + "icon-keep-upright": DataConstantProperty; + "icon-offset": DataDrivenProperty<[ + number, + number + ]>; + "icon-anchor": DataDrivenProperty<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">; + "icon-pitch-alignment": DataConstantProperty<"map" | "viewport" | "auto">; + "text-pitch-alignment": DataConstantProperty<"map" | "viewport" | "auto">; + "text-rotation-alignment": DataConstantProperty<"map" | "viewport" | "viewport-glyph" | "auto">; + "text-field": DataDrivenProperty; + "text-font": DataDrivenProperty>; + "text-size": DataDrivenProperty; + "text-max-width": DataDrivenProperty; + "text-line-height": DataConstantProperty; + "text-letter-spacing": DataDrivenProperty; + "text-justify": DataDrivenProperty<"auto" | "left" | "center" | "right">; + "text-radial-offset": DataDrivenProperty; + "text-variable-anchor": DataConstantProperty>; + "text-variable-anchor-offset": DataDrivenProperty; + "text-anchor": DataDrivenProperty<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">; + "text-max-angle": DataConstantProperty; + "text-writing-mode": DataConstantProperty>; + "text-rotate": DataDrivenProperty; + "text-padding": DataConstantProperty; + "text-keep-upright": DataConstantProperty; + "text-transform": DataDrivenProperty<"none" | "uppercase" | "lowercase">; + "text-offset": DataDrivenProperty<[ + number, + number + ]>; + "text-allow-overlap": DataConstantProperty; + "text-overlap": DataConstantProperty<"never" | "always" | "cooperative">; + "text-ignore-placement": DataConstantProperty; + "text-optional": DataConstantProperty; +}; +export type SymbolLayoutPropsPossiblyEvaluated = { + "symbol-placement": "point" | "line" | "line-center"; + "symbol-spacing": number; + "symbol-avoid-edges": boolean; + "symbol-sort-key": PossiblyEvaluatedPropertyValue; + "symbol-z-order": "auto" | "viewport-y" | "source"; + "icon-allow-overlap": boolean; + "icon-overlap": "never" | "always" | "cooperative"; + "icon-ignore-placement": boolean; + "icon-optional": boolean; + "icon-rotation-alignment": "map" | "viewport" | "auto"; + "icon-size": PossiblyEvaluatedPropertyValue; + "icon-text-fit": "none" | "width" | "height" | "both"; + "icon-text-fit-padding": [ + number, + number, + number, + number + ]; + "icon-image": PossiblyEvaluatedPropertyValue; + "icon-rotate": PossiblyEvaluatedPropertyValue; + "icon-padding": PossiblyEvaluatedPropertyValue; + "icon-keep-upright": boolean; + "icon-offset": PossiblyEvaluatedPropertyValue<[ + number, + number + ]>; + "icon-anchor": PossiblyEvaluatedPropertyValue<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">; + "icon-pitch-alignment": "map" | "viewport" | "auto"; + "text-pitch-alignment": "map" | "viewport" | "auto"; + "text-rotation-alignment": "map" | "viewport" | "viewport-glyph" | "auto"; + "text-field": PossiblyEvaluatedPropertyValue; + "text-font": PossiblyEvaluatedPropertyValue>; + "text-size": PossiblyEvaluatedPropertyValue; + "text-max-width": PossiblyEvaluatedPropertyValue; + "text-line-height": number; + "text-letter-spacing": PossiblyEvaluatedPropertyValue; + "text-justify": PossiblyEvaluatedPropertyValue<"auto" | "left" | "center" | "right">; + "text-radial-offset": PossiblyEvaluatedPropertyValue; + "text-variable-anchor": Array<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">; + "text-variable-anchor-offset": PossiblyEvaluatedPropertyValue; + "text-anchor": PossiblyEvaluatedPropertyValue<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">; + "text-max-angle": number; + "text-writing-mode": Array<"horizontal" | "vertical">; + "text-rotate": PossiblyEvaluatedPropertyValue; + "text-padding": number; + "text-keep-upright": boolean; + "text-transform": PossiblyEvaluatedPropertyValue<"none" | "uppercase" | "lowercase">; + "text-offset": PossiblyEvaluatedPropertyValue<[ + number, + number + ]>; + "text-allow-overlap": boolean; + "text-overlap": "never" | "always" | "cooperative"; + "text-ignore-placement": boolean; + "text-optional": boolean; +}; +export type SymbolPaintProps = { + "icon-opacity": DataDrivenProperty; + "icon-color": DataDrivenProperty; + "icon-halo-color": DataDrivenProperty; + "icon-halo-width": DataDrivenProperty; + "icon-halo-blur": DataDrivenProperty; + "icon-translate": DataConstantProperty<[ + number, + number + ]>; + "icon-translate-anchor": DataConstantProperty<"map" | "viewport">; + "text-opacity": DataDrivenProperty; + "text-color": DataDrivenProperty; + "text-halo-color": DataDrivenProperty; + "text-halo-width": DataDrivenProperty; + "text-halo-blur": DataDrivenProperty; + "text-translate": DataConstantProperty<[ + number, + number + ]>; + "text-translate-anchor": DataConstantProperty<"map" | "viewport">; +}; +export type SymbolPaintPropsPossiblyEvaluated = { + "icon-opacity": PossiblyEvaluatedPropertyValue; + "icon-color": PossiblyEvaluatedPropertyValue; + "icon-halo-color": PossiblyEvaluatedPropertyValue; + "icon-halo-width": PossiblyEvaluatedPropertyValue; + "icon-halo-blur": PossiblyEvaluatedPropertyValue; + "icon-translate": [ + number, + number + ]; + "icon-translate-anchor": "map" | "viewport"; + "text-opacity": PossiblyEvaluatedPropertyValue; + "text-color": PossiblyEvaluatedPropertyValue; + "text-halo-color": PossiblyEvaluatedPropertyValue; + "text-halo-width": PossiblyEvaluatedPropertyValue; + "text-halo-blur": PossiblyEvaluatedPropertyValue; + "text-translate": [ + number, + number + ]; + "text-translate-anchor": "map" | "viewport"; +}; +declare class SymbolStyleLayer extends StyleLayer { + _unevaluatedLayout: Layout; + layout: PossiblyEvaluated; + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + constructor(layer: LayerSpecification); + recalculate(parameters: EvaluationParameters, availableImages: Array): void; + getValueAndResolveTokens(name: any, feature: Feature, canonical: CanonicalTileID, availableImages: Array): any; + createBucket(parameters: BucketParameters): SymbolBucket; + queryRadius(): number; + queryIntersectsFeature(): boolean; + _setPaintOverrides(): void; + _handleOverridablePaintPropertyUpdate(name: string, oldValue: PropertyValue, newValue: PropertyValue): boolean; + static hasPaintOverride(layout: PossiblyEvaluated, propertyName: string): boolean; +} +/** + * A textured quad for rendering a single icon or glyph. + * + * The zoom range the glyph can be shown is defined by minScale and maxScale. + * + * @param tl - The offset of the top left corner from the anchor. + * @param tr - The offset of the top right corner from the anchor. + * @param bl - The offset of the bottom left corner from the anchor. + * @param br - The offset of the bottom right corner from the anchor. + * @param tex - The texture coordinates. + */ +export type SymbolQuad = { + tl: Point; + tr: Point; + bl: Point; + br: Point; + tex: { + x: number; + y: number; + w: number; + h: number; + }; + pixelOffsetTL: Point; + pixelOffsetBR: Point; + writingMode: any | void; + glyphOffset: [ + number, + number + ]; + sectionIndex: number; + isSDF: boolean; + minFontScaleX: number; + minFontScaleY: number; +}; +export type SizeData = { + kind: "constant"; + layoutSize: number; +} | { + kind: "source"; +} | { + kind: "camera"; + minZoom: number; + maxZoom: number; + minSize: number; + maxSize: number; + interpolationType: InterpolationType; +} | { + kind: "composite"; + minZoom: number; + maxZoom: number; + interpolationType: InterpolationType; +}; +export type SingleCollisionBox = { + x1: number; + y1: number; + x2: number; + y2: number; + anchorPointX: number; + anchorPointY: number; +}; +export type CollisionArrays = { + textBox?: SingleCollisionBox; + verticalTextBox?: SingleCollisionBox; + iconBox?: SingleCollisionBox; + verticalIconBox?: SingleCollisionBox; + textFeatureIndex?: number; + verticalTextFeatureIndex?: number; + iconFeatureIndex?: number; + verticalIconFeatureIndex?: number; +}; +export type SymbolFeature = { + sortKey: number | void; + text: Formatted | void; + icon: ResolvedImage; + index: number; + sourceLayerIndex: number; + geometry: Array>; + properties: any; + type: "Unknown" | "Point" | "LineString" | "Polygon"; + id?: any; +}; +export type SortKeyRange = { + sortKey: number; + symbolInstanceStart: number; + symbolInstanceEnd: number; +}; +declare function addDynamicAttributes(dynamicLayoutVertexArray: StructArray, p: Point, angle: number): void; +declare class SymbolBuffers { + layoutVertexArray: SymbolLayoutArray; + layoutVertexBuffer: VertexBuffer; + indexArray: TriangleIndexArray; + indexBuffer: IndexBuffer; + programConfigurations: ProgramConfigurationSet; + segments: SegmentVector; + dynamicLayoutVertexArray: SymbolDynamicLayoutArray; + dynamicLayoutVertexBuffer: VertexBuffer; + opacityVertexArray: SymbolOpacityArray; + opacityVertexBuffer: VertexBuffer; + hasVisibleVertices: boolean; + collisionVertexArray: CollisionVertexArray; + collisionVertexBuffer: VertexBuffer; + placedSymbolArray: PlacedSymbolArray; + constructor(programConfigurations: ProgramConfigurationSet); + isEmpty(): boolean; + upload(context: Context, dynamicIndexBuffer: boolean, upload?: boolean, update?: boolean): void; + destroy(): void; +} +declare class CollisionBuffers { + layoutVertexArray: StructArray; + layoutAttributes: Array; + layoutVertexBuffer: VertexBuffer; + indexArray: TriangleIndexArray | LineIndexArray; + indexBuffer: IndexBuffer; + segments: SegmentVector; + collisionVertexArray: CollisionVertexArray; + collisionVertexBuffer: VertexBuffer; + constructor(LayoutArray: { + new (...args: any): StructArray; + }, layoutAttributes: Array, IndexArray: { + new (...args: any): TriangleIndexArray | LineIndexArray; + }); + upload(context: Context): void; + destroy(): void; +} +declare class SymbolBucket implements Bucket { + static MAX_GLYPHS: number; + static addDynamicAttributes: typeof addDynamicAttributes; + collisionBoxArray: CollisionBoxArray; + zoom: number; + overscaling: number; + layers: Array; + layerIds: Array; + stateDependentLayers: Array; + stateDependentLayerIds: Array; + index: number; + sdfIcons: boolean; + iconsInText: boolean; + iconsNeedLinear: boolean; + bucketInstanceId: number; + justReloaded: boolean; + hasPattern: boolean; + textSizeData: SizeData; + iconSizeData: SizeData; + glyphOffsetArray: GlyphOffsetArray; + lineVertexArray: SymbolLineVertexArray; + features: Array; + symbolInstances: SymbolInstanceArray; + textAnchorOffsets: TextAnchorOffsetArray; + collisionArrays: Array; + sortKeyRanges: Array; + pixelRatio: number; + tilePixelRatio: number; + compareText: { + [_: string]: Array; + }; + fadeStartTime: number; + sortFeaturesByKey: boolean; + sortFeaturesByY: boolean; + canOverlap: boolean; + sortedAngle: number; + featureSortOrder: Array; + collisionCircleArray: Array; + placementInvProjMatrix: mat4; + placementViewportMatrix: mat4; + text: SymbolBuffers; + icon: SymbolBuffers; + textCollisionBox: CollisionBuffers; + iconCollisionBox: CollisionBuffers; + uploaded: boolean; + sourceLayerIndex: number; + sourceID: string; + symbolInstanceIndexes: Array; + writingModes: WritingMode[]; + allowVerticalPlacement: boolean; + hasRTLText: boolean; + constructor(options: BucketParameters); + createArrays(): void; + private calculateGlyphDependencies; + populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID): void; + update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: { + [_: string]: ImagePosition; + }): void; + isEmpty(): boolean; + uploadPending(): boolean; + upload(context: Context): void; + destroyDebugData(): void; + destroy(): void; + addToLineVertexArray(anchor: Anchor, line: any): { + lineStartIndex: number; + lineLength: number; + }; + addSymbols(arrays: SymbolBuffers, quads: Array, sizeVertex: any, lineOffset: [ + number, + number + ], alongLine: boolean, feature: SymbolFeature, writingMode: WritingMode, labelAnchor: Anchor, lineStartIndex: number, lineLength: number, associatedIconIndex: number, canonical: CanonicalTileID): void; + _addCollisionDebugVertex(layoutVertexArray: StructArray, collisionVertexArray: StructArray, point: Point, anchorX: number, anchorY: number, extrude: Point): any; + addCollisionDebugVertices(x1: number, y1: number, x2: number, y2: number, arrays: CollisionBuffers, boxAnchorPoint: Point, symbolInstance: SymbolInstance): void; + addDebugCollisionBoxes(startIndex: number, endIndex: number, symbolInstance: SymbolInstance, isText: boolean): void; + generateCollisionDebugBuffers(): void; + _deserializeCollisionBoxesForSymbol(collisionBoxArray: CollisionBoxArray, textStartIndex: number, textEndIndex: number, verticalTextStartIndex: number, verticalTextEndIndex: number, iconStartIndex: number, iconEndIndex: number, verticalIconStartIndex: number, verticalIconEndIndex: number): CollisionArrays; + deserializeCollisionBoxes(collisionBoxArray: CollisionBoxArray): void; + hasTextData(): boolean; + hasIconData(): boolean; + hasDebugData(): CollisionBuffers; + hasTextCollisionBoxData(): boolean; + hasIconCollisionBoxData(): boolean; + addIndicesForPlacedSymbol(iconOrText: SymbolBuffers, placedSymbolIndex: number): void; + getSortedSymbolIndexes(angle: number): any[]; + addToSortKeyRanges(symbolInstanceIndex: number, sortKey: number): void; + sortFeatures(angle: number): void; +} +export interface SymbolsByKeyEntry { + index?: KDBush; + positions?: { + x: number; + y: number; + }[]; + crossTileIDs: number[]; +} +declare class TileLayerIndex { + tileID: OverscaledTileID; + bucketInstanceId: number; + _symbolsByKey: Record; + constructor(tileID: OverscaledTileID, symbolInstances: SymbolInstanceArray, bucketInstanceId: number); + getScaledCoordinates(symbolInstance: SymbolInstance, childTileID: OverscaledTileID): { + x: number; + y: number; + }; + findMatches(symbolInstances: SymbolInstanceArray, newTileID: OverscaledTileID, zoomCrossTileIDs: { + [crossTileID: number]: boolean; + }): void; + getCrossTileIDsLists(): number[][]; +} +declare class CrossTileIDs { + maxCrossTileID: number; + constructor(); + generate(): number; +} +declare class CrossTileSymbolLayerIndex { + indexes: { + [zoom in string | number]: { + [tileId in string | number]: TileLayerIndex; + }; + }; + usedCrossTileIDs: { + [zoom in string | number]: { + [crossTileID: number]: boolean; + }; + }; + lng: number; + constructor(); + handleWrapJump(lng: number): void; + addBucket(tileID: OverscaledTileID, bucket: SymbolBucket, crossTileIDs: CrossTileIDs): boolean; + removeBucketCrossTileIDs(zoom: string | number, removedBucket: TileLayerIndex): void; + removeStaleBuckets(currentIDs: { + [k in string | number]: boolean; + }): boolean; +} +declare class CrossTileSymbolIndex { + layerIndexes: { + [layerId: string]: CrossTileSymbolLayerIndex; + }; + crossTileIDs: CrossTileIDs; + maxBucketInstanceId: number; + bucketsInCurrentPlacement: { + [_: number]: boolean; + }; + constructor(); + addLayer(styleLayer: StyleLayer, tiles: Array, lng: number): boolean; + pruneUnusedLayers(usedLayers: Array): void; +} +declare class DepthMode { + func: DepthFuncType; + mask: DepthMaskType; + range: DepthRangeType; + static ReadOnly: boolean; + static ReadWrite: boolean; + constructor(depthFunc: DepthFuncType, depthMask: DepthMaskType, depthRange: DepthRangeType); + static disabled: Readonly; +} +declare class StencilMode { + test: StencilTestGL; + ref: number; + mask: number; + fail: StencilOpConstant; + depthFail: StencilOpConstant; + pass: StencilOpConstant; + constructor(test: StencilTestGL, ref: number, mask: number, fail: StencilOpConstant, depthFail: StencilOpConstant, pass: StencilOpConstant); + static disabled: Readonly; +} +declare class ColorMode { + blendFunction: BlendFuncType; + blendColor: Color; + mask: ColorMaskType; + constructor(blendFunction: BlendFuncType, blendColor: Color, mask: ColorMaskType); + static Replace: BlendFuncType; + static disabled: Readonly; + static unblended: Readonly; + static alphaBlended: Readonly; +} +export type PoolObject = { + id: number; + fbo: Framebuffer; + texture: Texture; + stamp: number; + inUse: boolean; +}; +declare class RenderPool { + private readonly _context; + private readonly _size; + private readonly _tileSize; + private _objects; + /** + * An index array of recently used pool objects. + * Items that are used recently are last in the array + */ + private _recentlyUsed; + private _stamp; + constructor(_context: Context, _size: number, _tileSize: number); + destruct(): void; + private _createObject; + getObjectForId(id: number): PoolObject; + useObject(obj: PoolObject): void; + stampObject(obj: PoolObject): void; + getOrCreateFreeObject(): PoolObject; + freeObject(obj: PoolObject): void; + freeAllObjects(): void; + isFull(): boolean; +} +declare class RenderToTexture { + painter: Painter; + terrain: Terrain; + pool: RenderPool; + /** + * coordsDescendingInv contains a list of all tiles which should be rendered for one render-to-texture tile + * e.g. render 4 raster-tiles with size 256px to the 512px render-to-texture tile + */ + _coordsDescendingInv: { + [_: string]: { + [_: string]: Array; + }; + }; + /** + * create a string representation of all to tiles rendered to render-to-texture tiles + * this string representation is used to check if tile should be re-rendered. + */ + _coordsDescendingInvStr: { + [_: string]: { + [_: string]: string; + }; + }; + /** + * store for render-stacks + * a render stack is a set of layers which should be rendered into one texture + * every stylesheet can have multiple stacks. A new stack is created if layers which should + * not rendered to texture sit between layers which should rendered to texture. e.g. hillshading or symbols + */ + _stacks: Array>; + /** + * remember the previous processed layer to check if a new stack is needed + */ + _prevType: string; + /** + * a list of tiles that can potentially rendered + */ + _renderableTiles: Array; + /** + * a list of tiles that should be rendered to screen in the next render-call + */ + _rttTiles: Array; + /** + * a list of all layer-ids which should be rendered + */ + _renderableLayerIds: Array; + constructor(painter: Painter, terrain: Terrain); + destruct(): void; + getTexture(tile: Tile): Texture; + prepareForRender(style: Style, zoom: number): void; + /** + * due that switching textures is relatively slow, the render + * layer-by-layer context is not practicable. To bypass this problem + * this lines of code stack all layers and later render all at once. + * Because of the stylesheet possibility to mixing render-to-texture layers + * and 'live'-layers (f.e. symbols) it is necessary to create more stacks. For example + * a symbol-layer is in between of fill-layers. + * @param layer - the layer to render + * @returns if true layer is rendered to texture, otherwise false + */ + renderLayer(layer: StyleLayer): boolean; +} +/** + * A dash entry + */ +export type DashEntry = { + y: number; + height: number; + width: number; +}; +declare class LineAtlas { + width: number; + height: number; + nextRow: number; + bytes: number; + data: Uint8Array; + dashEntry: { + [_: string]: DashEntry; + }; + dirty: boolean; + texture: WebGLTexture; + constructor(width: number, height: number); + /** + * Get or create a dash line pattern. + * + * @param dasharray - the key (represented by numbers) to get the dash texture + * @param round - whether to add circle caps in between dash segments + * @returns position of dash texture in {@link DashEntry} + */ + getDash(dasharray: Array, round: boolean): DashEntry; + getDashRanges(dasharray: Array, lineAtlasWidth: number, stretch: number): any[]; + addRoundDash(ranges: any, stretch: number, n: number): void; + addRegularDash(ranges: any): void; + addDash(dasharray: Array, round: boolean): DashEntry; + bind(context: Context): void; +} +/** + * A type of MapLibre resource. + */ +export declare const enum ResourceType { + Glyphs = "Glyphs", + Image = "Image", + Source = "Source", + SpriteImage = "SpriteImage", + SpriteJSON = "SpriteJSON", + Style = "Style", + Tile = "Tile", + Unknown = "Unknown" +} +/** + * This function is used to tranform a request. + * It is used just before executing the relevant request. + */ +export type RequestTransformFunction = (url: string, resourceType?: ResourceType) => RequestParameters | undefined; +declare class RequestManager { + _transformRequestFn: RequestTransformFunction; + constructor(transformRequestFn?: RequestTransformFunction); + transformRequest(url: string, type: ResourceType): RequestParameters; + setTransformRequest(transformRequest: RequestTransformFunction): void; +} +declare function loadGlyphRange(fontstack: string, range: number, urlTemplate: string, requestManager: RequestManager): Promise<{ + [_: number]: StyleGlyph | null; +}>; +export type Entry = { + glyphs: { + [id: number]: StyleGlyph | null; + }; + requests: { + [range: number]: Promise<{ + [_: number]: StyleGlyph | null; + }>; + }; + ranges: { + [range: number]: boolean | null; + }; + tinySDF?: TinySDF; +}; +declare class GlyphManager { + requestManager: RequestManager; + localIdeographFontFamily: string | false; + entries: { + [stack: string]: Entry; + }; + url: string; + static loadGlyphRange: typeof loadGlyphRange; + static TinySDF: typeof TinySDF; + constructor(requestManager: RequestManager, localIdeographFontFamily?: string | false); + setURL(url?: string | null): void; + getGlyphs(glyphs: { + [stack: string]: Array; + }): Promise; + _getAndCacheGlyphsPromise(stack: string, id: number): Promise<{ + stack: string; + id: number; + glyph: StyleGlyph; + }>; + _doesCharSupportLocalGlyph(id: number): boolean; + _tinySDF(entry: Entry, stack: string, id: number): StyleGlyph; +} +export type RenderPass = "offscreen" | "opaque" | "translucent"; +export type PainterOptions = { + showOverdrawInspector: boolean; + showTileBoundaries: boolean; + showPadding: boolean; + rotating: boolean; + zooming: boolean; + moving: boolean; + fadeDuration: number; +}; +declare class Painter { + context: Context; + transform: Transform; + renderToTexture: RenderToTexture; + _tileTextures: { + [_: number]: Array; + }; + numSublayers: number; + depthEpsilon: number; + emptyProgramConfiguration: ProgramConfiguration; + width: number; + height: number; + pixelRatio: number; + tileExtentBuffer: VertexBuffer; + tileExtentSegments: SegmentVector; + debugBuffer: VertexBuffer; + debugSegments: SegmentVector; + rasterBoundsBuffer: VertexBuffer; + rasterBoundsSegments: SegmentVector; + viewportBuffer: VertexBuffer; + viewportSegments: SegmentVector; + quadTriangleIndexBuffer: IndexBuffer; + tileBorderIndexBuffer: IndexBuffer; + _tileClippingMaskIDs: { + [_: string]: number; + }; + stencilClearMode: StencilMode; + style: Style; + options: PainterOptions; + lineAtlas: LineAtlas; + imageManager: ImageManager; + glyphManager: GlyphManager; + depthRangeFor3D: DepthRangeType; + opaquePassCutoff: number; + renderPass: RenderPass; + currentLayer: number; + currentStencilSource: string; + nextStencilID: number; + id: string; + _showOverdrawInspector: boolean; + cache: { + [_: string]: Program; + }; + crossTileSymbolIndex: CrossTileSymbolIndex; + symbolFadeChange: number; + debugOverlayTexture: Texture; + debugOverlayCanvas: HTMLCanvasElement; + terrainFacilitator: { + dirty: boolean; + matrix: mat4; + renderTime: number; + }; + constructor(gl: WebGLRenderingContext | WebGL2RenderingContext, transform: Transform); + resize(width: number, height: number, pixelRatio: number): void; + setup(): void; + clearStencil(): void; + _renderTileClippingMasks(layer: StyleLayer, tileIDs: Array): void; + stencilModeFor3D(): StencilMode; + stencilModeForClipping(tileID: OverscaledTileID): StencilMode; + stencilConfigForOverlap(tileIDs: Array): [ + { + [_: number]: Readonly; + }, + Array + ]; + colorModeForRenderPass(): Readonly; + depthModeForSublayer(n: number, mask: DepthMaskType, func?: DepthFuncType | null): Readonly; + opaquePassEnabledForLayer(): boolean; + render(style: Style, options: PainterOptions): void; + /** + * Update the depth and coords framebuffers, if the contents of those frame buffers is out of date. + * If requireExact is false, then the contents of those frame buffers is not updated if it is close + * to accurate (that is, the camera has not moved much since it was updated last). + */ + maybeDrawDepthAndCoords(requireExact: boolean): void; + renderLayer(painter: Painter, sourceCache: SourceCache, layer: StyleLayer, coords: Array): void; + /** + * Transform a matrix to incorporate the *-translate and *-translate-anchor properties into it. + * @param inViewportPixelUnitsUnits - True when the units accepted by the matrix are in viewport pixels instead of tile units. + * @returns matrix + */ + translatePosMatrix(matrix: mat4, tile: Tile, translate: [ + number, + number + ], translateAnchor: "map" | "viewport", inViewportPixelUnitsUnits?: boolean): mat4; + saveTileTexture(texture: Texture): void; + getTileTexture(size: number): Texture; + /** + * Checks whether a pattern image is needed, and if it is, whether it is not loaded. + * + * @returns true if a needed image is missing and rendering needs to be skipped. + */ + isPatternMissing(image?: CrossFaded | null): boolean; + useProgram(name: string, programConfiguration?: ProgramConfiguration | null): Program; + setCustomLayerDefaults(): void; + setBaseState(): void; + initDebugOverlayCanvas(): void; + destroy(): void; + overLimit(): boolean; +} +declare class TerrainSourceCache extends Evented { + /** + * source-cache for the raster-dem source. + */ + sourceCache: SourceCache; + /** + * stores all render-to-texture tiles. + */ + _tiles: { + [_: string]: Tile; + }; + /** + * contains a list of tileID-keys for the current scene. (only for performance) + */ + _renderableTilesKeys: Array; + /** + * raster-dem-tile for a TileID cache. + */ + _sourceTileCache: { + [_: string]: string; + }; + /** + * minimum zoomlevel to render the terrain. + */ + minzoom: number; + /** + * maximum zoomlevel to render the terrain. + */ + maxzoom: number; + /** + * render-to-texture tileSize in scene. + */ + tileSize: number; + /** + * raster-dem tiles will load for performance the actualZoom - deltaZoom zoom-level. + */ + deltaZoom: number; + constructor(sourceCache: SourceCache); + destruct(): void; + /** + * Load Terrain Tiles, create internal render-to-texture tiles, free GPU memory. + * @param transform - the operation to do + * @param terrain - the terrain + */ + update(transform: Transform, terrain: Terrain): void; + /** + * Free render to texture cache + * @param tileID - optional, free only corresponding to tileID. + */ + freeRtt(tileID?: OverscaledTileID): void; + /** + * get a list of tiles, which are loaded and should be rendered in the current scene + * @returns the renderable tiles + */ + getRenderableTiles(): Array; + /** + * get terrain tile by the TileID key + * @param id - the tile id + * @returns the tile + */ + getTileByID(id: string): Tile; + /** + * Searches for the corresponding current renderable terrain-tiles + * @param tileID - the tile to look for + * @returns the tiles that were found + */ + getTerrainCoords(tileID: OverscaledTileID): Record; + /** + * find the covering raster-dem tile + * @param tileID - the tile to look for + * @param searchForDEM - Optional parameter to search for (parent) sourcetiles with loaded dem. + * @returns the tile + */ + getSourceTile(tileID: OverscaledTileID, searchForDEM?: boolean): Tile; + /** + * get a list of tiles, loaded after a specific time. This is used to update depth & coords framebuffers. + * @param time - the time + * @returns the relevant tiles + */ + tilesAfterTime(time?: number): Array; +} +declare class Mesh { + vertexBuffer: VertexBuffer; + indexBuffer: IndexBuffer; + segments: SegmentVector; + constructor(vertexBuffer: VertexBuffer, indexBuffer: IndexBuffer, segments: SegmentVector); + destroy(): void; +} +/** + * @internal + * A terrain GPU related object + */ +export type TerrainData = { + "u_depth": number; + "u_terrain": number; + "u_terrain_dim": number; + "u_terrain_matrix": mat4; + "u_terrain_unpack": number[]; + "u_terrain_exaggeration": number; + texture: WebGLTexture; + depthTexture: WebGLTexture; + tile: Tile; +}; +declare class Terrain { + /** + * The style this terrain corresponds to + */ + painter: Painter; + /** + * the sourcecache this terrain is based on + */ + sourceCache: TerrainSourceCache; + /** + * the TerrainSpecification object passed to this instance + */ + options: TerrainSpecification; + /** + * define the meshSize per tile. + */ + meshSize: number; + /** + * multiplicator for the elevation. Used to make terrain more "extreme". + */ + exaggeration: number; + /** + * to not see pixels in the render-to-texture tiles it is good to render them bigger + * this number is the multiplicator (must be a power of 2) for the current tileSize. + * So to get good results with not too much memory footprint a value of 2 should be fine. + */ + qualityFactor: number; + /** + * holds the framebuffer object in size of the screen to render the coords & depth into a texture. + */ + _fbo: Framebuffer; + _fboCoordsTexture: Texture; + _fboDepthTexture: Texture; + _emptyDepthTexture: Texture; + /** + * GL Objects for the terrain-mesh + * The mesh is a regular mesh, which has the advantage that it can be reused for all tiles. + */ + _mesh: Mesh; + /** + * coords index contains a list of tileID.keys. This index is used to identify + * the tile via the alpha-cannel in the coords-texture. + * As the alpha-channel has 1 Byte a max of 255 tiles can rendered without an error. + */ + coordsIndex: Array; + /** + * tile-coords encoded in the rgb channel, _coordsIndex is in the alpha-channel. + */ + _coordsTexture: Texture; + /** + * accuracy of the coords. 2 * tileSize should be enough. + */ + _coordsTextureSize: number; + /** + * variables for an empty dem texture, which is used while the raster-dem tile is loading. + */ + _emptyDemUnpack: number[]; + _emptyDemTexture: Texture; + _emptyDemMatrix: mat4; + /** + * as of overzooming of raster-dem tiles in high zoomlevels, this cache contains + * matrices to transform from vector-tile coords to raster-dem-tile coords. + */ + _demMatrixCache: { + [_: string]: { + matrix: mat4; + coord: OverscaledTileID; + }; + }; + constructor(painter: Painter, sourceCache: SourceCache, options: TerrainSpecification); + /** + * get the elevation-value from original dem-data for a given tile-coordinate + * @param tileID - the tile to get elevation for + * @param x - between 0 .. EXTENT + * @param y - between 0 .. EXTENT + * @param extent - optional, default 8192 + * @returns the elevation + */ + getDEMElevation(tileID: OverscaledTileID, x: number, y: number, extent?: number): number; + /** + * Get the elevation for given {@link LngLat} in respect of exaggeration. + * @param lnglat - the location + * @param zoom - the zoom + * @returns the elevation + */ + getElevationForLngLatZoom(lnglat: LngLat, zoom: number): number; + /** + * Get the elevation for given coordinate in respect of exaggeration. + * @param tileID - the tile id + * @param x - between 0 .. EXTENT + * @param y - between 0 .. EXTENT + * @param extent - optional, default 8192 + * @returns the elevation + */ + getElevation(tileID: OverscaledTileID, x: number, y: number, extent?: number): number; + /** + * returns a Terrain Object for a tile. Unless the tile corresponds to data (e.g. tile is loading), return a flat dem object + * @param tileID - the tile to get the terrain for + * @returns the terrain data to use in the program + */ + getTerrainData(tileID: OverscaledTileID): TerrainData; + /** + * get a framebuffer as big as the map-div, which will be used to render depth & coords into a texture + * @param texture - the texture + * @returns the frame buffer + */ + getFramebuffer(texture: string): Framebuffer; + /** + * create coords texture, needed to grab coordinates from canvas + * encode coords coordinate into 4 bytes: + * - 8 lower bits for x + * - 8 lower bits for y + * - 4 higher bits for x + * - 4 higher bits for y + * - 8 bits for coordsIndex (1 .. 255) (= number of terraintile), is later setted in draw_terrain uniform value + * @returns the texture + */ + getCoordsTexture(): Texture; + /** + * Reads a pixel from the coords-framebuffer and translate this to mercator. + * @param p - Screen-Coordinate + * @returns mercator coordinate for a screen pixel + */ + pointCoordinate(p: Point): MercatorCoordinate; + /** + * Reads the depth value from the depth-framebuffer at a given screen pixel + * @param p - Screen coordinate + * @returns depth value in clip space (between 0 and 1) + */ + depthAtPoint(p: Point): number; + /** + * create a regular mesh which will be used by all terrain-tiles + * @returns the created regular mesh + */ + getTerrainMesh(): Mesh; + /** + * Calculates a height of the frame around the terrain-mesh to avoid stiching between + * tile boundaries in different zoomlevels. + * @param zoom - current zoomlevel + * @returns the elevation delta in meters + */ + getMeshFrameDelta(zoom: number): number; + getMinTileElevationForLngLatZoom(lnglat: LngLat, zoom: number): number; + /** + * Get the minimum and maximum elevation contained in a tile. This includes any + * exaggeration included in the terrain. + * + * @param tileID - ID of the tile to be used as a source for the min/max elevation + * @returns the minimum and maximum elevation found in the tile, including the terrain's + * exaggeration + */ + getMinMaxElevation(tileID: OverscaledTileID): { + minElevation: number | null; + maxElevation: number | null; + }; + _getOverscaledTileIDFromLngLatZoom(lnglat: LngLat, zoom: number): { + tileID: OverscaledTileID; + mercatorX: number; + mercatorY: number; + }; +} +declare class Transform { + tileSize: number; + tileZoom: number; + lngRange: [ + number, + number + ]; + latRange: [ + number, + number + ]; + scale: number; + width: number; + height: number; + angle: number; + rotationMatrix: mat2; + pixelsToGLUnits: [ + number, + number + ]; + cameraToCenterDistance: number; + mercatorMatrix: mat4; + projectionMatrix: mat4; + modelViewProjectionMatrix: mat4; + invModelViewProjectionMatrix: mat4; + alignedModelViewProjectionMatrix: mat4; + fogMatrix: mat4; + pixelMatrix: mat4; + pixelMatrix3D: mat4; + pixelMatrixInverse: mat4; + glCoordMatrix: mat4; + labelPlaneMatrix: mat4; + minElevationForCurrentTile: number; + _fov: number; + _pitch: number; + _zoom: number; + _unmodified: boolean; + _renderWorldCopies: boolean; + _minZoom: number; + _maxZoom: number; + _minPitch: number; + _maxPitch: number; + _center: LngLat; + _elevation: number; + _pixelPerMeter: number; + _edgeInsets: EdgeInsets; + _constraining: boolean; + _posMatrixCache: { + [_: string]: mat4; + }; + _alignedPosMatrixCache: { + [_: string]: mat4; + }; + _fogMatrixCache: { + [_: string]: mat4; + }; + /** + * This value represents the distance from the camera to the far clipping plane. + * It is used in the calculation of the projection matrix to determine which objects are visible. + * farz should be larger than nearZ. + */ + farZ: number; + /** + * This value represents the distance from the camera to the near clipping plane. + * It is used in the calculation of the projection matrix to determine which objects are visible. + * nearZ should be smaller than farZ. + */ + nearZ: number; + constructor(minZoom?: number, maxZoom?: number, minPitch?: number, maxPitch?: number, renderWorldCopies?: boolean); + clone(): Transform; + apply(that: Transform): void; + get minZoom(): number; + set minZoom(zoom: number); + get maxZoom(): number; + set maxZoom(zoom: number); + get minPitch(): number; + set minPitch(pitch: number); + get maxPitch(): number; + set maxPitch(pitch: number); + get renderWorldCopies(): boolean; + set renderWorldCopies(renderWorldCopies: boolean); + get worldSize(): number; + get centerOffset(): Point; + get size(): Point; + get bearing(): number; + set bearing(bearing: number); + get pitch(): number; + set pitch(pitch: number); + get fov(): number; + set fov(fov: number); + get zoom(): number; + set zoom(zoom: number); + get center(): LngLat; + set center(center: LngLat); + /** + * Elevation at current center point, meters above sea level + */ + get elevation(): number; + set elevation(elevation: number); + get padding(): PaddingOptions; + set padding(padding: PaddingOptions); + /** + * The center of the screen in pixels with the top-left corner being (0,0) + * and +y axis pointing downwards. This accounts for padding. + */ + get centerPoint(): Point; + /** + * Returns if the padding params match + * + * @param padding - the padding to check against + * @returns true if they are equal, false otherwise + */ + isPaddingEqual(padding: PaddingOptions): boolean; + /** + * Helper method to update edge-insets in place + * + * @param start - the starting padding + * @param target - the target padding + * @param t - the step/weight + */ + interpolatePadding(start: PaddingOptions, target: PaddingOptions, t: number): void; + /** + * Return a zoom level that will cover all tiles the transform + * @param options - the options + * @returns zoom level An integer zoom level at which all tiles will be visible. + */ + coveringZoomLevel(options: { + /** + * Target zoom level. If true, the value will be rounded to the closest integer. Otherwise the value will be floored. + */ + roundZoom?: boolean; + /** + * Tile size, expressed in screen pixels. + */ + tileSize: number; + }): number; + /** + * Return any "wrapped" copies of a given tile coordinate that are visible + * in the current view. + */ + getVisibleUnwrappedCoordinates(tileID: CanonicalTileID): UnwrappedTileID[]; + /** + * Return all coordinates that could cover this transform for a covering + * zoom level. + * @param options - the options + * @returns OverscaledTileIDs + */ + coveringTiles(options: { + tileSize: number; + minzoom?: number; + maxzoom?: number; + roundZoom?: boolean; + reparseOverscaled?: boolean; + renderWorldCopies?: boolean; + terrain?: Terrain; + }): Array; + resize(width: number, height: number): void; + get unmodified(): boolean; + zoomScale(zoom: number): number; + scaleZoom(scale: number): number; + /** + * Convert from LngLat to world coordinates (Mercator coordinates scaled by 512) + * @param lnglat - the lngLat + * @returns Point + */ + project(lnglat: LngLat): Point; + /** + * Convert from world coordinates ([0, 512],[0, 512]) to LngLat ([-180, 180], [-90, 90]) + * @param point - world coordinate + * @returns LngLat + */ + unproject(point: Point): LngLat; + get point(): Point; + /** + * get the camera position in LngLat and altitudes in meter + * @returns An object with lngLat & altitude. + */ + getCameraPosition(): { + lngLat: LngLat; + altitude: number; + }; + /** + * This method works in combination with freezeElevation activated. + * freezeElevation is enabled during map-panning because during this the camera should sit in constant height. + * After panning finished, call this method to recalculate the zoomlevel for the current camera-height in current terrain. + * @param terrain - the terrain + */ + recalculateZoom(terrain: Terrain): void; + setLocationAtPoint(lnglat: LngLat, point: Point): void; + /** + * Given a LngLat location, return the screen point that corresponds to it + * @param lnglat - location + * @param terrain - optional terrain + * @returns screen point + */ + locationPoint(lnglat: LngLat, terrain?: Terrain): Point; + /** + * Given a point on screen, return its lnglat + * @param p - screen point + * @param terrain - optional terrain + * @returns lnglat location + */ + pointLocation(p: Point, terrain?: Terrain): LngLat; + /** + * Given a geographical lnglat, return an unrounded + * coordinate that represents it at low zoom level. + * @param lnglat - the location + * @returns The mercator coordinate + */ + locationCoordinate(lnglat: LngLat): MercatorCoordinate; + /** + * Given a Coordinate, return its geographical position. + * @param coord - mercator coordinates + * @returns lng and lat + */ + coordinateLocation(coord: MercatorCoordinate): LngLat; + /** + * Given a Point, return its mercator coordinate. + * @param p - the point + * @param terrain - optional terrain + * @returns lnglat + */ + pointCoordinate(p: Point, terrain?: Terrain): MercatorCoordinate; + /** + * Given a coordinate, return the screen point that corresponds to it + * @param coord - the coordinates + * @param elevation - the elevation + * @param pixelMatrix - the pixel matrix + * @returns screen point + */ + coordinatePoint(coord: MercatorCoordinate, elevation?: number, pixelMatrix?: mat4): Point; + /** + * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not + * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region. + * @returns Returns a {@link LngLatBounds} object describing the map's geographical bounds. + */ + getBounds(): LngLatBounds; + /** + * Returns the maximum geographical bounds the map is constrained to, or `null` if none set. + * @returns max bounds + */ + getMaxBounds(): LngLatBounds | null; + /** + * Calculate pixel height of the visible horizon in relation to map-center (e.g. height/2), + * multiplied by a static factor to simulate the earth-radius. + * The calculated value is the horizontal line from the camera-height to sea-level. + * @returns Horizon above center in pixels. + */ + getHorizon(): number; + /** + * Sets or clears the map's geographical constraints. + * @param bounds - A {@link LngLatBounds} object describing the new geographic boundaries of the map. + */ + setMaxBounds(bounds?: LngLatBounds | null): void; + calculateTileMatrix(unwrappedTileID: UnwrappedTileID): mat4; + /** + * Calculate the posMatrix that, given a tile coordinate, would be used to display the tile on a map. + * @param unwrappedTileID - the tile ID + */ + calculatePosMatrix(unwrappedTileID: UnwrappedTileID, aligned?: boolean): mat4; + /** + * Calculate the fogMatrix that, given a tile coordinate, would be used to calculate fog on the map. + * @param unwrappedTileID - the tile ID + * @private + */ + calculateFogMatrix(unwrappedTileID: UnwrappedTileID): mat4; + customLayerMatrix(): mat4; + /** + * Get center lngLat and zoom to ensure that + * 1) everything beyond the bounds is excluded + * 2) a given lngLat is as near the center as possible + * Bounds are those set by maxBounds or North & South "Poles" and, if only 1 globe is displayed, antimeridian. + */ + getConstrained(lngLat: LngLat, zoom: number): { + center: LngLat; + zoom: number; + }; + _constrain(): void; + _calcMatrices(): void; + maxPitchScaleFactor(): number; + /** + * The camera looks at the map from a 3D (lng, lat, altitude) location. Let's use `cameraLocation` + * as the name for the location under the camera and on the surface of the earth (lng, lat, 0). + * `cameraPoint` is the projected position of the `cameraLocation`. + * + * This point is useful to us because only fill-extrusions that are between `cameraPoint` and + * the query point on the surface of the earth can extend and intersect the query. + * + * When the map is not pitched the `cameraPoint` is equivalent to the center of the map because + * the camera is right above the center of the map. + */ + getCameraPoint(): Point; + /** + * When the map is pitched, some of the 3D features that intersect a query will not intersect + * the query at the surface of the earth. Instead the feature may be closer and only intersect + * the query because it extrudes into the air. + * @param queryGeometry - For point queries, the line from the query point to the "camera point", + * for other geometries, the envelope of the query geometry and the "camera point" + * @returns a geometry that includes all of the original query as well as all possible ares of the + * screen where the *base* of a visible extrusion could be. + * + */ + getCameraQueryGeometry(queryGeometry: Array): Array; + /** + * Return the distance to the camera in clip space from a LngLat. + * This can be compared to the value from the depth buffer (terrain.depthAtPoint) + * to determine whether a point is occluded. + * @param lngLat - the point + * @param elevation - the point's elevation + * @returns depth value in clip space (between 0 and 1) + */ + lngLatToCameraDepth(lngLat: LngLat, elevation: number): number; +} +export type QueryParameters = { + scale: number; + pixelPosMatrix: mat4; + transform: Transform; + tileSize: number; + queryGeometry: Array; + cameraQueryGeometry: Array; + queryPadding: number; + params: { + filter: FilterSpecification; + layers: Array; + availableImages: Array; + }; +}; +declare class FeatureIndex { + tileID: OverscaledTileID; + x: number; + y: number; + z: number; + grid: TransferableGridIndex; + grid3D: TransferableGridIndex; + featureIndexArray: FeatureIndexArray; + promoteId?: PromoteIdSpecification; + rawTileData: ArrayBuffer; + bucketLayerIDs: Array>; + vtLayers: { + [_: string]: VectorTileLayer; + }; + sourceLayerCoder: DictionaryCoder; + constructor(tileID: OverscaledTileID, promoteId?: PromoteIdSpecification | null); + insert(feature: VectorTileFeature, geometry: Array>, featureIndex: number, sourceLayerIndex: number, bucketIndex: number, is3D?: boolean): void; + loadVTLayers(): { + [_: string]: VectorTileLayer; + }; + query(args: QueryParameters, styleLayers: { + [_: string]: StyleLayer; + }, serializedLayers: { + [_: string]: any; + }, sourceFeatureState: SourceFeatureState): { + [_: string]: Array<{ + featureIndex: number; + feature: GeoJSONFeature; + }>; + }; + loadMatchingFeature(result: { + [_: string]: Array<{ + featureIndex: number; + feature: GeoJSONFeature; + intersectionZ?: boolean | number; + }>; + }, bucketIndex: number, sourceLayerIndex: number, featureIndex: number, filter: FeatureFilter, filterLayerIDs: Array, availableImages: Array, styleLayers: { + [_: string]: StyleLayer; + }, serializedLayers: { + [_: string]: any; + }, sourceFeatureState?: SourceFeatureState, intersectionTest?: (feature: VectorTileFeature, styleLayer: StyleLayer, featureState: any, id: string | number | void) => boolean | number): void; + lookupSymbolFeatures(symbolFeatureIndexes: Array, serializedLayers: { + [_: string]: StyleLayer; + }, bucketIndex: number, sourceLayerIndex: number, filterSpec: FilterSpecification, filterLayerIDs: Array, availableImages: Array, styleLayers: { + [_: string]: StyleLayer; + }): {}; + hasLayer(id: string): boolean; + getId(feature: VectorTileFeature, sourceLayerId: string): string | number; +} +/** + * The possible DEM encoding types + */ +export type DEMEncoding = "mapbox" | "terrarium" | "custom"; +declare class DEMData { + uid: string | number; + data: Uint32Array; + stride: number; + dim: number; + min: number; + max: number; + redFactor: number; + greenFactor: number; + blueFactor: number; + baseShift: number; + /** + * Constructs a `DEMData` object + * @param uid - the tile's unique id + * @param data - RGBAImage data has uniform 1px padding on all sides: square tile edge size defines stride + // and dim is calculated as stride - 2. + * @param encoding - the encoding type of the data + * @param redFactor - the red channel factor used to unpack the data, used for `custom` encoding only + * @param greenFactor - the green channel factor used to unpack the data, used for `custom` encoding only + * @param blueFactor - the blue channel factor used to unpack the data, used for `custom` encoding only + * @param baseShift - the base shift used to unpack the data, used for `custom` encoding only + */ + constructor(uid: string | number, data: RGBAImage | ImageData, encoding: DEMEncoding, redFactor?: number, greenFactor?: number, blueFactor?: number, baseShift?: number); + get(x: number, y: number): number; + getUnpackVector(): number[]; + _idx(x: number, y: number): number; + unpack(r: number, g: number, b: number): number; + getPixels(): RGBAImage; + backfillBorder(borderTile: DEMData, dx: number, dy: number): void; +} +/** + * Parameters to identify a tile + */ +export type TileParameters = { + type: string; + source: string; + uid: string | number; +}; +/** + * Parameters that are send when requesting to load a tile to the worker + */ +export type WorkerTileParameters = TileParameters & { + tileID: OverscaledTileID; + request?: RequestParameters; + zoom: number; + maxZoom?: number; + tileSize: number; + promoteId: PromoteIdSpecification; + pixelRatio: number; + showCollisionBoxes: boolean; + collectResourceTiming?: boolean; + returnDependencies?: boolean; +}; +/** + * The paremeters needed in order to load a DEM tile + */ +export type WorkerDEMTileParameters = TileParameters & { + rawImageData: RGBAImage | ImageBitmap | ImageData; + encoding: DEMEncoding; + redFactor: number; + greenFactor: number; + blueFactor: number; + baseShift: number; +}; +/** + * The worker tile's result type + */ +export type WorkerTileResult = ExpiryData & { + buckets: Array; + imageAtlas: ImageAtlas; + imageBackgroundsAtlas?: ImageAtlas; + glyphAtlasImage: AlphaImage; + featureIndex: FeatureIndex; + collisionBoxArray: CollisionBoxArray; + rawTileData?: ArrayBuffer; + resourceTiming?: Array; + glyphMap?: { + [_: string]: { + [_: number]: StyleGlyph; + }; + } | null; + iconMap?: { + [_: string]: StyleImage; + } | null; + glyphPositions?: GlyphPositions | null; +}; +/** + * The tile's state, can be: + * + * - `loading` Tile data is in the process of loading. + * - `loaded` Tile data has been loaded. Tile can be rendered. + * - `reloading` Tile data has been loaded and is being updated. Tile can be rendered. + * - `unloaded` Tile data has been deleted. + * - `errored` Tile data was not loaded because of an error. + * - `expired` Tile data was previously loaded, but has expired per its HTTP headers and is in the process of refreshing. + */ +export type TileState = "loading" | "loaded" | "reloading" | "unloaded" | "errored" | "expired"; +declare class Tile { + tileID: OverscaledTileID; + uid: number; + uses: number; + tileSize: number; + buckets: { + [_: string]: Bucket; + }; + latestFeatureIndex: FeatureIndex; + latestRawTileData: ArrayBuffer; + imageAtlas: ImageAtlas; + imageBackgroundsAtlas: ImageAtlas; + imageAtlasTexture: Texture; + imageBackgroundsAtlasTexture: Texture; + glyphAtlasImage: AlphaImage; + glyphAtlasTexture: Texture; + expirationTime: any; + expiredRequestCount: number; + state: TileState; + timeAdded: number; + fadeEndTime: number; + collisionBoxArray: CollisionBoxArray; + redoWhenDone: boolean; + showCollisionBoxes: boolean; + placementSource: any; + actor: Actor; + vtLayers: { + [_: string]: VectorTileLayer; + }; + neighboringTiles: any; + dem: DEMData; + demMatrix: mat4; + aborted: boolean; + needsHillshadePrepare: boolean; + needsTerrainPrepare: boolean; + abortController: AbortController; + texture: any; + fbo: Framebuffer; + demTexture: Texture; + refreshedUponExpiration: boolean; + reloadPromise: { + resolve: () => void; + reject: () => void; + }; + resourceTiming: Array; + queryPadding: number; + symbolFadeHoldUntil: number; + hasSymbolBuckets: boolean; + hasRTLText: boolean; + dependencies: any; + rtt: Array<{ + id: number; + stamp: number; + }>; + rttCoords: { + [_: string]: string; + }; + /** + * @param tileID - the tile ID + * @param size - The tile size + */ + constructor(tileID: OverscaledTileID, size: number); + registerFadeDuration(duration: number): void; + wasRequested(): boolean; + clearTextures(painter: any): void; + /** + * Given a data object with a 'buffers' property, load it into + * this tile's elementGroups and buffers properties and set loaded + * to true. If the data is null, like in the case of an empty + * GeoJSON tile, no-op but still set loaded to true. + * @param data - The data from the worker + * @param painter - the painter + * @param justReloaded - `true` to just reload + */ + loadVectorData(data: WorkerTileResult, painter: any, justReloaded?: boolean | null): void; + /** + * Release any data or WebGL resources referenced by this tile. + */ + unloadVectorData(): void; + getBucket(layer: StyleLayer): Bucket; + upload(context: Context): void; + prepare(imageManager: ImageManager): void; + queryRenderedFeatures(layers: { + [_: string]: StyleLayer; + }, serializedLayers: { + [_: string]: any; + }, sourceFeatureState: SourceFeatureState, queryGeometry: Array, cameraQueryGeometry: Array, scale: number, params: { + filter: FilterSpecification; + layers: Array; + availableImages: Array; + }, transform: Transform, maxPitchScaleFactor: number, pixelPosMatrix: mat4): { + [_: string]: Array<{ + featureIndex: number; + feature: GeoJSONFeature; + }>; + }; + querySourceFeatures(result: Array, params?: { + sourceLayer?: string; + filter?: FilterSpecification; + validate?: boolean; + }): void; + hasData(): boolean; + patternsLoaded(): boolean; + setExpiryData(data: ExpiryData): void; + getExpiryTimeout(): number; + setFeatureState(states: LayerFeatureStates, painter: any): void; + holdingForFade(): boolean; + symbolFadeFinished(): boolean; + clearFadeHold(): void; + setHoldDuration(duration: number): void; + setDependencies(namespace: string, dependencies: Array): void; + hasDependency(namespaces: Array, keys: Array): boolean; +} +export type FeatureStates = { + [featureId: string]: FeatureState; +}; +export type LayerFeatureStates = { + [layer: string]: FeatureStates; +}; +declare class SourceFeatureState { + state: LayerFeatureStates; + stateChanges: LayerFeatureStates; + deletedStates: {}; + constructor(); + updateState(sourceLayer: string, featureId: number | string, newState: any): void; + removeFeatureState(sourceLayer: string, featureId?: number | string, key?: string): void; + getState(sourceLayer: string, featureId: number | string): FeatureState; + initializeTileState(tile: Tile, painter: any): void; + coalesceChanges(tiles: { + [_ in any]: Tile; + }, painter: any): void; +} +declare class CircleBucket implements Bucket { + index: number; + zoom: number; + overscaling: number; + layerIds: Array; + layers: Array; + stateDependentLayers: Array; + stateDependentLayerIds: Array; + layoutVertexArray: CircleLayoutArray; + layoutVertexBuffer: VertexBuffer; + indexArray: TriangleIndexArray; + indexBuffer: IndexBuffer; + hasPattern: boolean; + programConfigurations: ProgramConfigurationSet; + segments: SegmentVector; + uploaded: boolean; + constructor(options: BucketParameters); + populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID): void; + update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: { + [_: string]: ImagePosition; + }): void; + isEmpty(): boolean; + uploadPending(): boolean; + upload(context: Context): void; + destroy(): void; + addFeature(feature: BucketFeature, geometry: Array>, index: number, canonical: CanonicalTileID): void; +} +export type CircleLayoutProps = { + "circle-sort-key": DataDrivenProperty; +}; +export type CircleLayoutPropsPossiblyEvaluated = { + "circle-sort-key": PossiblyEvaluatedPropertyValue; +}; +export type CirclePaintProps = { + "circle-radius": DataDrivenProperty; + "circle-color": DataDrivenProperty; + "circle-blur": DataDrivenProperty; + "circle-opacity": DataDrivenProperty; + "circle-translate": DataConstantProperty<[ + number, + number + ]>; + "circle-translate-anchor": DataConstantProperty<"map" | "viewport">; + "circle-pitch-scale": DataConstantProperty<"map" | "viewport">; + "circle-pitch-alignment": DataConstantProperty<"map" | "viewport">; + "circle-stroke-width": DataDrivenProperty; + "circle-stroke-color": DataDrivenProperty; + "circle-stroke-opacity": DataDrivenProperty; +}; +export type CirclePaintPropsPossiblyEvaluated = { + "circle-radius": PossiblyEvaluatedPropertyValue; + "circle-color": PossiblyEvaluatedPropertyValue; + "circle-blur": PossiblyEvaluatedPropertyValue; + "circle-opacity": PossiblyEvaluatedPropertyValue; + "circle-translate": [ + number, + number + ]; + "circle-translate-anchor": "map" | "viewport"; + "circle-pitch-scale": "map" | "viewport"; + "circle-pitch-alignment": "map" | "viewport"; + "circle-stroke-width": PossiblyEvaluatedPropertyValue; + "circle-stroke-color": PossiblyEvaluatedPropertyValue; + "circle-stroke-opacity": PossiblyEvaluatedPropertyValue; +}; +declare class CircleStyleLayer extends StyleLayer { + _unevaluatedLayout: Layout; + layout: PossiblyEvaluated; + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + constructor(layer: LayerSpecification); + createBucket(parameters: BucketParameters): CircleBucket; + queryRadius(bucket: Bucket): number; + queryIntersectsFeature(queryGeometry: Array, feature: VectorTileFeature, featureState: FeatureState, geometry: Array>, zoom: number, transform: Transform, pixelsToTileUnits: number, pixelPosMatrix: mat4): boolean; +} +declare class FillBucket implements Bucket { + index: number; + zoom: number; + overscaling: number; + layers: Array; + layerIds: Array; + stateDependentLayers: Array; + stateDependentLayerIds: Array; + patternFeatures: Array; + layoutVertexArray: FillLayoutArray; + layoutVertexBuffer: VertexBuffer; + indexArray: TriangleIndexArray; + indexBuffer: IndexBuffer; + indexArray2: LineIndexArray; + indexBuffer2: IndexBuffer; + hasPattern: boolean; + programConfigurations: ProgramConfigurationSet; + segments: SegmentVector; + segments2: SegmentVector; + uploaded: boolean; + constructor(options: BucketParameters); + populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID): void; + update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: { + [_: string]: ImagePosition; + }): void; + addFeatures(options: PopulateParameters, canonical: CanonicalTileID, imagePositions: { + [_: string]: ImagePosition; + }): void; + isEmpty(): boolean; + uploadPending(): boolean; + upload(context: Context): void; + destroy(): void; + addFeature(feature: BucketFeature, geometry: Array>, index: number, canonical: CanonicalTileID, imagePositions: { + [_: string]: ImagePosition; + }): void; +} +export type FillLayoutProps = { + "fill-sort-key": DataDrivenProperty; +}; +export type FillLayoutPropsPossiblyEvaluated = { + "fill-sort-key": PossiblyEvaluatedPropertyValue; +}; +export type FillPaintProps = { + "fill-antialias": DataConstantProperty; + "fill-opacity": DataDrivenProperty; + "fill-color": DataDrivenProperty; + "fill-outline-color": DataDrivenProperty; + "fill-translate": DataConstantProperty<[ + number, + number + ]>; + "fill-translate-anchor": DataConstantProperty<"map" | "viewport">; + "fill-pattern": CrossFadedDataDrivenProperty; +}; +export type FillPaintPropsPossiblyEvaluated = { + "fill-antialias": boolean; + "fill-opacity": PossiblyEvaluatedPropertyValue; + "fill-color": PossiblyEvaluatedPropertyValue; + "fill-outline-color": PossiblyEvaluatedPropertyValue; + "fill-translate": [ + number, + number + ]; + "fill-translate-anchor": "map" | "viewport"; + "fill-pattern": PossiblyEvaluatedPropertyValue>; +}; +declare class FillStyleLayer extends StyleLayer { + _unevaluatedLayout: Layout; + layout: PossiblyEvaluated; + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + constructor(layer: LayerSpecification); + recalculate(parameters: EvaluationParameters, availableImages: Array): void; + createBucket(parameters: BucketParameters): FillBucket; + queryRadius(): number; + queryIntersectsFeature(queryGeometry: Array, feature: VectorTileFeature, featureState: FeatureState, geometry: Array>, zoom: number, transform: Transform, pixelsToTileUnits: number): boolean; + isTileClipped(): boolean; +} +declare class FillExtrusionBucket implements Bucket { + index: number; + zoom: number; + overscaling: number; + layers: Array; + layerIds: Array; + stateDependentLayers: Array; + stateDependentLayerIds: Array; + layoutVertexArray: FillExtrusionLayoutArray; + layoutVertexBuffer: VertexBuffer; + centroidVertexArray: PosArray; + centroidVertexBuffer: VertexBuffer; + indexArray: TriangleIndexArray; + indexBuffer: IndexBuffer; + hasPattern: boolean; + programConfigurations: ProgramConfigurationSet; + segments: SegmentVector; + uploaded: boolean; + features: Array; + constructor(options: BucketParameters); + populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID): void; + addFeatures(options: PopulateParameters, canonical: CanonicalTileID, imagePositions: { + [_: string]: ImagePosition; + }): void; + update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: { + [_: string]: ImagePosition; + }): void; + isEmpty(): boolean; + uploadPending(): boolean; + upload(context: Context): void; + destroy(): void; + addFeature(feature: BucketFeature, geometry: Array>, index: number, canonical: CanonicalTileID, imagePositions: { + [_: string]: ImagePosition; + }): void; +} +export type FillExtrusionPaintProps = { + "fill-extrusion-opacity": DataConstantProperty; + "fill-extrusion-color": DataDrivenProperty; + "fill-extrusion-translate": DataConstantProperty<[ + number, + number + ]>; + "fill-extrusion-translate-anchor": DataConstantProperty<"map" | "viewport">; + "fill-extrusion-pattern": CrossFadedDataDrivenProperty; + "fill-extrusion-height": DataDrivenProperty; + "fill-extrusion-base": DataDrivenProperty; + "fill-extrusion-vertical-gradient": DataConstantProperty; +}; +export type FillExtrusionPaintPropsPossiblyEvaluated = { + "fill-extrusion-opacity": number; + "fill-extrusion-color": PossiblyEvaluatedPropertyValue; + "fill-extrusion-translate": [ + number, + number + ]; + "fill-extrusion-translate-anchor": "map" | "viewport"; + "fill-extrusion-pattern": PossiblyEvaluatedPropertyValue>; + "fill-extrusion-height": PossiblyEvaluatedPropertyValue; + "fill-extrusion-base": PossiblyEvaluatedPropertyValue; + "fill-extrusion-vertical-gradient": boolean; +}; +declare class FillExtrusionStyleLayer extends StyleLayer { + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + constructor(layer: LayerSpecification); + createBucket(parameters: BucketParameters): FillExtrusionBucket; + queryRadius(): number; + is3D(): boolean; + queryIntersectsFeature(queryGeometry: Array, feature: VectorTileFeature, featureState: FeatureState, geometry: Array>, zoom: number, transform: Transform, pixelsToTileUnits: number, pixelPosMatrix: mat4): boolean | number; +} +export type HillshadePaintProps = { + "hillshade-illumination-direction": DataConstantProperty; + "hillshade-illumination-anchor": DataConstantProperty<"map" | "viewport">; + "hillshade-exaggeration": DataConstantProperty; + "hillshade-shadow-color": DataConstantProperty; + "hillshade-highlight-color": DataConstantProperty; + "hillshade-accent-color": DataConstantProperty; +}; +export type HillshadePaintPropsPossiblyEvaluated = { + "hillshade-illumination-direction": number; + "hillshade-illumination-anchor": "map" | "viewport"; + "hillshade-exaggeration": number; + "hillshade-shadow-color": Color; + "hillshade-highlight-color": Color; + "hillshade-accent-color": Color; +}; +declare class HillshadeStyleLayer extends StyleLayer { + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + constructor(layer: LayerSpecification); + hasOffscreenPass(): boolean; +} +export type LineClips = { + start: number; + end: number; +}; +export type GradientTexture = { + texture?: Texture; + gradient?: RGBAImage; + version?: number; +}; +declare class LineBucket implements Bucket { + distance: number; + totalDistance: number; + maxLineLength: number; + scaledDistance: number; + lineClips?: LineClips; + e1: number; + e2: number; + index: number; + zoom: number; + overscaling: number; + layers: Array; + layerIds: Array; + gradients: { + [x: string]: GradientTexture; + }; + stateDependentLayers: Array; + stateDependentLayerIds: Array; + patternFeatures: Array; + lineClipsArray: Array; + layoutVertexArray: LineLayoutArray; + layoutVertexBuffer: VertexBuffer; + layoutVertexArray2: LineExtLayoutArray; + layoutVertexBuffer2: VertexBuffer; + indexArray: TriangleIndexArray; + indexBuffer: IndexBuffer; + hasPattern: boolean; + programConfigurations: ProgramConfigurationSet; + segments: SegmentVector; + uploaded: boolean; + constructor(options: BucketParameters); + populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID): void; + update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: { + [_: string]: ImagePosition; + }): void; + addFeatures(options: PopulateParameters, canonical: CanonicalTileID, imagePositions: { + [_: string]: ImagePosition; + }): void; + isEmpty(): boolean; + uploadPending(): boolean; + upload(context: Context): void; + destroy(): void; + lineFeatureClips(feature: BucketFeature): LineClips | undefined; + addFeature(feature: BucketFeature, geometry: Array>, index: number, canonical: CanonicalTileID, imagePositions: { + [_: string]: ImagePosition; + }): void; + addLine(vertices: Array, feature: BucketFeature, join: string, cap: string, miterLimit: number, roundLimit: number): void; + /** + * Add two vertices to the buffers. + * + * @param p - the line vertex to add buffer vertices for + * @param normal - vertex normal + * @param endLeft - extrude to shift the left vertex along the line + * @param endRight - extrude to shift the left vertex along the line + * @param segment - the segment object to add the vertex to + * @param round - whether this is a round cap + */ + addCurrentVertex(p: Point, normal: Point, endLeft: number, endRight: number, segment: Segment, round?: boolean): void; + addHalfVertex({ x, y }: Point, extrudeX: number, extrudeY: number, round: boolean, up: boolean, dir: number, segment: Segment): void; + updateScaledDistance(): void; + updateDistance(prev: Point, next: Point): void; +} +export type LineLayoutProps = { + "line-cap": DataConstantProperty<"butt" | "round" | "square">; + "line-join": DataDrivenProperty<"bevel" | "round" | "miter">; + "line-miter-limit": DataConstantProperty; + "line-round-limit": DataConstantProperty; + "line-sort-key": DataDrivenProperty; +}; +export type LineLayoutPropsPossiblyEvaluated = { + "line-cap": "butt" | "round" | "square"; + "line-join": PossiblyEvaluatedPropertyValue<"bevel" | "round" | "miter">; + "line-miter-limit": number; + "line-round-limit": number; + "line-sort-key": PossiblyEvaluatedPropertyValue; +}; +export type LinePaintProps = { + "line-opacity": DataDrivenProperty; + "line-color": DataDrivenProperty; + "line-translate": DataConstantProperty<[ + number, + number + ]>; + "line-translate-anchor": DataConstantProperty<"map" | "viewport">; + "line-width": DataDrivenProperty; + "line-gap-width": DataDrivenProperty; + "line-offset": DataDrivenProperty; + "line-blur": DataDrivenProperty; + "line-dasharray": CrossFadedProperty>; + "line-pattern": CrossFadedDataDrivenProperty; + "line-gradient": ColorRampProperty; +}; +export type LinePaintPropsPossiblyEvaluated = { + "line-opacity": PossiblyEvaluatedPropertyValue; + "line-color": PossiblyEvaluatedPropertyValue; + "line-translate": [ + number, + number + ]; + "line-translate-anchor": "map" | "viewport"; + "line-width": PossiblyEvaluatedPropertyValue; + "line-gap-width": PossiblyEvaluatedPropertyValue; + "line-offset": PossiblyEvaluatedPropertyValue; + "line-blur": PossiblyEvaluatedPropertyValue; + "line-dasharray": CrossFaded>; + "line-pattern": PossiblyEvaluatedPropertyValue>; + "line-gradient": ColorRampProperty; +}; +declare class LineStyleLayer extends StyleLayer { + _unevaluatedLayout: Layout; + layout: PossiblyEvaluated; + gradientVersion: number; + stepInterpolant: boolean; + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + constructor(layer: LayerSpecification); + _handleSpecialPaintPropertyUpdate(name: string): void; + gradientExpression(): import("@maplibre/maplibre-gl-style-spec").StylePropertyExpression; + recalculate(parameters: EvaluationParameters, availableImages: Array): void; + createBucket(parameters: BucketParameters): LineBucket; + queryRadius(bucket: Bucket): number; + queryIntersectsFeature(queryGeometry: Array, feature: VectorTileFeature, featureState: FeatureState, geometry: Array>, zoom: number, transform: Transform, pixelsToTileUnits: number): boolean; + isTileClipped(): boolean; +} +export type TypedStyleLayer = CircleStyleLayer | FillStyleLayer | FillExtrusionStyleLayer | HeatmapStyleLayer | HillshadeStyleLayer | LineStyleLayer | SymbolStyleLayer; +export type BinderUniform = { + name: string; + property: string; + binding: Uniform; +}; +/** + * `Binder` is the interface definition for the strategies for constructing, + * uploading, and binding paint property data as GLSL attributes. Most style- + * spec properties have a 1:1 relationship to shader attribute/uniforms, but + * some require multiple values per feature to be passed to the GPU, and in + * those cases we bind multiple attributes/uniforms. + * + * It has three implementations, one for each of the three strategies we use: + * + * * For _constant_ properties -- those whose value is a constant, or the constant + * result of evaluating a camera expression at a particular camera position -- we + * don't need a vertex attribute buffer, and instead use a uniform. + * * For data expressions, we use a vertex buffer with a single attribute value, + * the evaluated result of the source function for the given feature. + * * For composite expressions, we use a vertex buffer with two attributes: min and + * max values covering the range of zooms at which we expect the tile to be + * displayed. These values are calculated by evaluating the composite expression for + * the given feature at strategically chosen zoom levels. In addition to this + * attribute data, we also use a uniform value which the shader uses to interpolate + * between the min and max value at the final displayed zoom level. The use of a + * uniform allows us to cheaply update the value on every frame. + * + * Note that the shader source varies depending on whether we're using a uniform or + * attribute. We dynamically compile shaders at runtime to accommodate this. + */ +export interface AttributeBinder { + populatePaintArray(length: number, feature: Feature, imagePositions: { + [_: string]: ImagePosition; + }, canonical?: CanonicalTileID, formattedSection?: FormattedSection): void; + updatePaintArray(start: number, length: number, feature: Feature, featureState: FeatureState, imagePositions: { + [_: string]: ImagePosition; + }): void; + upload(a: Context): void; + destroy(): void; +} +export interface UniformBinder { + uniformNames: Array; + setUniform(uniform: Uniform, globals: GlobalProperties, currentValue: PossiblyEvaluatedPropertyValue, uniformName: string): void; + getBinding(context: Context, location: WebGLUniformLocation, name: string): Partial>; +} +declare class ProgramConfiguration { + binders: { + [_: string]: AttributeBinder | UniformBinder; + }; + cacheKey: string; + _buffers: Array; + constructor(layer: TypedStyleLayer, zoom: number, filterProperties: (_: string) => boolean); + getMaxValue(property: string): number; + populatePaintArrays(newLength: number, feature: Feature, imagePositions: { + [_: string]: ImagePosition; + }, canonical?: CanonicalTileID, formattedSection?: FormattedSection): void; + setConstantPatternPositions(posTo: ImagePosition, posFrom: ImagePosition): void; + updatePaintArrays(featureStates: FeatureStates, featureMap: FeaturePositionMap, vtLayer: VectorTileLayer, layer: TypedStyleLayer, imagePositions: { + [_: string]: ImagePosition; + }): boolean; + defines(): Array; + getBinderAttributes(): Array; + getBinderUniforms(): Array; + getPaintVertexBuffers(): Array; + getUniforms(context: Context, locations: UniformLocations): Array; + setUniforms(context: Context, binderUniforms: Array, properties: any, globals: GlobalProperties): void; + updatePaintBuffers(crossfade?: CrossfadeParameters): void; + upload(context: Context): void; + destroy(): void; +} +declare class ProgramConfigurationSet { + programConfigurations: { + [_: string]: ProgramConfiguration; + }; + needsUpload: boolean; + _featureMap: FeaturePositionMap; + _bufferOffset: number; + constructor(layers: ReadonlyArray, zoom: number, filterProperties?: (_: string) => boolean); + populatePaintArrays(length: number, feature: Feature, index: number, imagePositions: { + [_: string]: ImagePosition; + }, canonical: CanonicalTileID, formattedSection?: FormattedSection): void; + updatePaintArrays(featureStates: FeatureStates, vtLayer: VectorTileLayer, layers: ReadonlyArray, imagePositions: { + [_: string]: ImagePosition; + }): void; + get(layerId: string): ProgramConfiguration; + upload(context: Context): void; + destroy(): void; +} +declare class CullFaceMode { + enable: boolean; + mode: CullFaceModeType; + frontFace: FrontFaceType; + constructor(enable: boolean, mode: CullFaceModeType, frontFace: FrontFaceType); + static disabled: Readonly; + static backCCW: Readonly; +} +export type SkyProps = { + "sky-color": DataConstantProperty; + "horizon-color": DataConstantProperty; + "fog-color": DataConstantProperty; + "fog-ground-blend": DataConstantProperty; + "horizon-fog-blend": DataConstantProperty; + "sky-horizon-blend": DataConstantProperty; + "atmosphere-blend": DataConstantProperty; +}; +export type SkyPropsPossiblyEvaluated = { + "sky-color": Color; + "horizon-color": Color; + "fog-color": Color; + "fog-ground-blend": number; + "horizon-fog-blend": number; + "sky-horizon-blend": number; + "atmosphere-blend": number; +}; +declare class Sky extends Evented { + properties: PossiblyEvaluated; + /** + * This is used to cache the gl mesh for the sky, it should be initialized only once. + */ + mesh: Mesh | undefined; + _transitionable: Transitionable; + _transitioning: Transitioning; + constructor(sky?: SkySpecification); + setSky(sky?: SkySpecification, options?: StyleSetterOptions): void; + getSky(): SkySpecification; + updateTransitions(parameters: TransitionParameters): void; + hasTransition(): boolean; + recalculate(parameters: EvaluationParameters): void; + _validate(validate: Function, value: unknown, options?: StyleSetterOptions): boolean; + /** + * Currently fog is a very simple implementation, and should only used + * to create an atmosphere near the horizon. + * But because the fog is drawn from the far-clipping-plane to + * map-center, and because the fog does nothing know about the horizon, + * this method does a fadeout in respect of pitch. So, when the horizon + * gets out of view, which is at about pitch 70, this methods calculates + * the corresponding opacity values. Below pitch 60 the fog is completely + * invisible. + */ + calculateFogBlendOpacity(pitch: number): number; +} +export type TerrainPreludeUniformsType = { + "u_depth": Uniform1i; + "u_terrain": Uniform1i; + "u_terrain_dim": Uniform1f; + "u_terrain_matrix": UniformMatrix4f; + "u_terrain_unpack": Uniform4f; + "u_terrain_exaggeration": Uniform1f; +}; +export type DrawMode = WebGLRenderingContextBase["LINES"] | WebGLRenderingContextBase["TRIANGLES"] | WebGL2RenderingContext["LINE_STRIP"]; +declare class Program { + program: WebGLProgram; + attributes: { + [_: string]: number; + }; + numAttributes: number; + fixedUniforms: Us; + terrainUniforms: TerrainPreludeUniformsType; + binderUniforms: Array; + failedToCreate: boolean; + constructor(context: Context, source: { + fragmentSource: string; + vertexSource: string; + staticAttributes: Array; + staticUniforms: Array; + }, configuration: ProgramConfiguration, fixedUniforms: (b: Context, a: UniformLocations) => Us, showOverdrawInspector: boolean, terrain: Terrain); + draw(context: Context, drawMode: DrawMode, depthMode: Readonly, stencilMode: Readonly, colorMode: Readonly, cullFaceMode: Readonly, uniformValues: UniformValues, terrain: TerrainData, layerID: string, layoutVertexBuffer: VertexBuffer, indexBuffer: IndexBuffer, segments: SegmentVector, currentProperties?: any, zoom?: number | null, configuration?: ProgramConfiguration | null, dynamicLayoutBuffer?: VertexBuffer | null, dynamicLayoutBuffer2?: VertexBuffer | null, dynamicLayoutBuffer3?: VertexBuffer | null): void; +} +declare class VertexBuffer { + length: number; + attributes: ReadonlyArray; + itemSize: number; + dynamicDraw: boolean; + context: Context; + buffer: WebGLBuffer; + /** + * @param dynamicDraw - Whether this buffer will be repeatedly updated. + */ + constructor(context: Context, array: StructArray, attributes: ReadonlyArray, dynamicDraw?: boolean); + bind(): void; + updateData(array: StructArray): void; + enableAttributes(gl: WebGLRenderingContext | WebGL2RenderingContext, program: Program): void; + /** + * Set the attribute pointers in a WebGL context + * @param gl - The WebGL context + * @param program - The active WebGL program + * @param vertexOffset - Index of the starting vertex of the segment + */ + setVertexAttribPointers(gl: WebGLRenderingContext | WebGL2RenderingContext, program: Program, vertexOffset?: number | null): void; + /** + * Destroy the GL buffer bound to the given WebGL context + */ + destroy(): void; +} +export type ClearArgs = { + color?: Color; + depth?: number; + stencil?: number; +}; +declare class Context { + gl: WebGLRenderingContext | WebGL2RenderingContext; + currentNumAttributes: number; + maxTextureSize: number; + clearColor: ClearColor; + clearDepth: ClearDepth; + clearStencil: ClearStencil; + colorMask: ColorMask; + depthMask: DepthMask; + stencilMask: StencilMask; + stencilFunc: StencilFunc; + stencilOp: StencilOp; + stencilTest: StencilTest; + depthRange: DepthRange; + depthTest: DepthTest; + depthFunc: DepthFunc; + blend: Blend; + blendFunc: BlendFunc; + blendColor: BlendColor; + blendEquation: BlendEquation; + cullFace: CullFace; + cullFaceSide: CullFaceSide; + frontFace: FrontFace; + program: ProgramValue; + activeTexture: ActiveTextureUnit; + viewport: Viewport; + bindFramebuffer: BindFramebuffer; + bindRenderbuffer: BindRenderbuffer; + bindTexture: BindTexture; + bindVertexBuffer: BindVertexBuffer; + bindElementBuffer: BindElementBuffer; + bindVertexArray: BindVertexArray; + pixelStoreUnpack: PixelStoreUnpack; + pixelStoreUnpackPremultiplyAlpha: PixelStoreUnpackPremultiplyAlpha; + pixelStoreUnpackFlipY: PixelStoreUnpackFlipY; + extTextureFilterAnisotropic: EXT_texture_filter_anisotropic | null; + extTextureFilterAnisotropicMax?: GLfloat; + HALF_FLOAT?: GLenum; + RGBA16F?: GLenum; + RGB16F?: GLenum; + constructor(gl: WebGLRenderingContext | WebGL2RenderingContext); + setDefault(): void; + setDirty(): void; + createIndexBuffer(array: TriangleIndexArray | LineIndexArray | LineStripIndexArray, dynamicDraw?: boolean): IndexBuffer; + createVertexBuffer(array: StructArray, attributes: ReadonlyArray, dynamicDraw?: boolean): VertexBuffer; + createRenderbuffer(storageFormat: number, width: number, height: number): WebGLRenderbuffer; + createFramebuffer(width: number, height: number, hasDepth: boolean, hasStencil: boolean): Framebuffer; + clear({ color, depth, stencil }: ClearArgs): void; + setCullFace(cullFaceMode: Readonly): void; + setDepthMode(depthMode: Readonly): void; + setStencilMode(stencilMode: Readonly): void; + setColorMode(colorMode: Readonly): void; + createVertexArray(): WebGLVertexArrayObject | undefined; + deleteVertexArray(x: WebGLVertexArrayObject | undefined): void; + unbindVAO(): void; +} +export type TextureFormat = WebGLRenderingContextBase["RGBA"] | WebGLRenderingContextBase["ALPHA"]; +export type TextureFilter = WebGLRenderingContextBase["LINEAR"] | WebGLRenderingContextBase["LINEAR_MIPMAP_NEAREST"] | WebGLRenderingContextBase["NEAREST"]; +export type TextureWrap = WebGLRenderingContextBase["REPEAT"] | WebGLRenderingContextBase["CLAMP_TO_EDGE"] | WebGLRenderingContextBase["MIRRORED_REPEAT"]; +export type EmptyImage = { + width: number; + height: number; + data: null; +}; +export type DataTextureImage = RGBAImage | AlphaImage | EmptyImage; +export type TextureImage = TexImageSource | DataTextureImage; +declare class Texture { + context: Context; + size: [ + number, + number + ]; + texture: WebGLTexture; + format: TextureFormat; + filter: TextureFilter; + wrap: TextureWrap; + useMipmap: boolean; + constructor(context: Context, image: TextureImage, format: TextureFormat, options?: { + premultiply?: boolean; + useMipmap?: boolean; + } | null); + update(image: TextureImage, options?: { + premultiply?: boolean; + useMipmap?: boolean; + } | null, position?: { + x: number; + y: number; + }): void; + bind(filter: TextureFilter, wrap: TextureWrap, minFilter?: TextureFilter | null): void; + isSizePowerOfTwo(): boolean; + destroy(): void; +} +declare class ImagePosition { + paddedRect: Rect; + pixelRatio: number; + version: number; + stretchY: Array<[ + number, + number + ]>; + stretchX: Array<[ + number, + number + ]>; + content: [ + number, + number, + number, + number + ]; + textFitWidth: TextFit; + textFitHeight: TextFit; + constructor(paddedRect: Rect, { pixelRatio, version, stretchX, stretchY, content, textFitWidth, textFitHeight }: StyleImage); + get tl(): [ + number, + number + ]; + get br(): [ + number, + number + ]; + get tlbr(): Array; + get displaySize(): [ + number, + number + ]; +} +declare class ImageAtlas { + image: RGBAImage; + iconPositions: { + [_: string]: ImagePosition; + }; + patternPositions: { + [_: string]: ImagePosition; + }; + haveRenderCallbacks: Array; + uploaded: boolean; + constructor(icons: GetImagesResponse, patterns: GetImagesResponse); + addImages(images: { + [_: string]: StyleImage; + }, positions: { + [_: string]: ImagePosition; + }, bins: Array): void; + patchUpdatedImages(imageManager: ImageManager, texture: Texture): void; + patchUpdatedImage(position: ImagePosition, image: StyleImage, texture: Texture): void; +} +export type Pattern = { + bin: PotpackBox; + position: ImagePosition; +}; +declare class ImageManager extends Evented { + images: { + [_: string]: StyleImage; + }; + updatedImages: { + [_: string]: boolean; + }; + callbackDispatchedThisFrame: { + [_: string]: boolean; + }; + loaded: boolean; + /** + * This is used to track requests for images that are not yet available. When the image is loaded, + * the requestors will be notified. + */ + requestors: Array<{ + ids: Array; + promiseResolve: (value: GetImagesResponse) => void; + }>; + patterns: { + [_: string]: Pattern; + }; + atlasImage: RGBAImage; + atlasTexture: Texture; + dirty: boolean; + constructor(); + isLoaded(): boolean; + setLoaded(loaded: boolean): void; + getImage(id: string): StyleImage; + addImage(id: string, image: StyleImage): void; + _validate(id: string, image: StyleImage): boolean; + _validateStretch(stretch: Array<[ + number, + number + ]>, size: number): boolean; + _validateContent(content: [ + number, + number, + number, + number + ], image: StyleImage): boolean; + updateImage(id: string, image: StyleImage, validate?: boolean): void; + removeImage(id: string): void; + listImages(): Array; + getImages(ids: Array): Promise; + _getImagesForIds(ids: Array): GetImagesResponse; + getPixelSize(): { + width: number; + height: number; + }; + getPattern(id: string): ImagePosition; + bind(context: Context): void; + _updatePatternAtlas(): void; + beginFrame(): void; + dispatchRenderCallbacks(ids: Array): void; +} +export type LightPosition = { + x: number; + y: number; + z: number; +}; +declare class LightPositionProperty implements Property<[ + number, + number, + number +], LightPosition> { + specification: StylePropertySpecification; + constructor(); + possiblyEvaluate(value: PropertyValue<[ + number, + number, + number + ], LightPosition>, parameters: EvaluationParameters): LightPosition; + interpolate(a: LightPosition, b: LightPosition, t: number): LightPosition; +} +export type LightProps = { + "anchor": DataConstantProperty<"map" | "viewport">; + "position": LightPositionProperty; + "color": DataConstantProperty; + "intensity": DataConstantProperty; +}; +export type LightPropsPossiblyEvaluated = { + "anchor": "map" | "viewport"; + "position": LightPosition; + "color": Color; + "intensity": number; +}; +declare class Light extends Evented { + _transitionable: Transitionable; + _transitioning: Transitioning; + properties: PossiblyEvaluated; + constructor(lightOptions?: LightSpecification); + getLight(): LightSpecification; + setLight(light?: LightSpecification, options?: StyleSetterOptions): void; + updateTransitions(parameters: TransitionParameters): void; + hasTransition(): boolean; + recalculate(parameters: EvaluationParameters): void; + _validate(validate: Function, value: unknown, options?: { + validate?: boolean; + }): boolean; +} +/** + * The overlap mode for properties like `icon-overlap`and `text-overlap` + */ +export type OverlapMode = "never" | "always" | "cooperative"; +export type QueryResult = { + key: T; + x1: number; + y1: number; + x2: number; + y2: number; +}; +/** + * A key for the grid + */ +export type GridKey = { + overlapMode?: OverlapMode; +}; +declare class GridIndex { + circleKeys: Array; + boxKeys: Array; + boxCells: Array>; + circleCells: Array>; + bboxes: Array; + circles: Array; + xCellCount: number; + yCellCount: number; + width: number; + height: number; + xScale: number; + yScale: number; + boxUid: number; + circleUid: number; + constructor(width: number, height: number, cellSize: number); + keysLength(): number; + insert(key: T, x1: number, y1: number, x2: number, y2: number): void; + insertCircle(key: T, x: number, y: number, radius: number): void; + private _insertBoxCell; + private _insertCircleCell; + private _query; + query(x1: number, y1: number, x2: number, y2: number): Array>; + hitTest(x1: number, y1: number, x2: number, y2: number, overlapMode: OverlapMode, predicate?: (key: T) => boolean): boolean; + hitTestCircle(x: number, y: number, radius: number, overlapMode: OverlapMode, predicate?: (key: T) => boolean): boolean; + private _queryCell; + private _queryCellCircle; + private _forEachCell; + private _convertToXCellCoord; + private _convertToYCellCoord; + private _circlesCollide; + private _circleAndRectCollide; +} +/** + * A greatly reduced version of the `Projection` interface from the globe branch, + * used to port symbol bugfixes over to the main branch. Will be replaced with + * the proper interface once globe is merged. + */ +export type Projection = { + useSpecialProjectionForSymbols: boolean; + isOccluded(_x: any, _y: any, _t: any): boolean; + projectTileCoordinates(_x: any, _y: any, _t: any, _ele: any): PointProjection; + getPitchedTextCorrection(_transform: any, _anchor: any, _tile: any): number; + translatePosition(transform: { + angle: number; + zoom: number; + }, tile: Tile, translate: [ + number, + number + ], translateAnchor: "map" | "viewport"): [ + number, + number + ]; + getCircleRadiusCorrection(tr: any): number; +}; +/** + * The result of projecting a point to the screen, with some additional information about the projection. + */ +export type PointProjection = { + /** + * The projected point. + */ + point: Point; + /** + * The original W component of the projection. + */ + signedDistanceFromCamera: number; + /** + * For complex projections (such as globe), true if the point is occluded by the projection, such as by being on the backfacing side of the globe. + */ + isOccluded: boolean; +}; +export type IndexToPointCache = { + [lineIndex: number]: Point; +}; +/** + * @internal + * We calculate label-plane projected points for line vertices as we place glyphs along the line + * Since we will use the same vertices for potentially many glyphs, cache the results for this bucket + * over the course of the render. Each vertex location also potentially has one offset equivalent + * for us to hold onto. The vertex indices are per-symbol-bucket. + */ +export type ProjectionCache = { + /** + * tile-unit vertices projected into label-plane units + */ + projections: IndexToPointCache; + /** + * label-plane vertices which have been shifted to follow an offset line + */ + offsets: IndexToPointCache; + /** + * Cached projected anchor point. + */ + cachedAnchorPoint: Point | undefined; + /** + * Was any projected point occluded by the map itself (eg. occluded by the planet when using globe projection). + * + * Viewport-pitched line-following texts where *any* of the line points is hidden behind the planet curve becomes entirely hidden. + * This is perhaps not the most ideal behavior, but it works, it is simple and planetary-scale texts such as this seem to be a rare edge case. + */ + anyProjectionOccluded: boolean; +}; +/** + * @internal + * Arguments necessary to project a vertex to the label plane + */ +export type SymbolProjectionContext = { + /** + * Used to cache results, save cost if projecting the same vertex multiple times + */ + projectionCache: ProjectionCache; + /** + * The array of tile-unit vertices transferred from worker + */ + lineVertexArray: SymbolLineVertexArray; + /** + * Label plane projection matrix + */ + labelPlaneMatrix: mat4; + /** + * Function to get elevation at a point + * @param x - the x coordinate + * @param y - the y coordinate + */ + getElevation: (x: number, y: number) => number; + /** + * Only for creating synthetic vertices if vertex would otherwise project behind plane of camera, + * but still convenient to pass it inside this type. + */ + tileAnchorPoint: Point; + /** + * True when line glyphs are projected onto the map, instead of onto the viewport. + */ + pitchWithMap: boolean; + projection: Projection; + unwrappedTileID: UnwrappedTileID; + /** + * Viewport width. + */ + width: number; + /** + * Viewport height. + */ + height: number; + /** + * Translation in tile units, computed using text-translate and text-translate-anchor paint style properties. + */ + translation: [ + number, + number + ]; +}; +export type PlacedCircles = { + circles: Array; + offscreen: boolean; + collisionDetected: boolean; +}; +export type PlacedBox = { + box: Array; + placeable: boolean; + offscreen: boolean; +}; +export type FeatureKey = { + bucketInstanceId: number; + featureIndex: number; + collisionGroupID: number; + overlapMode: OverlapMode; +}; +declare class CollisionIndex { + grid: GridIndex; + ignoredGrid: GridIndex; + transform: Transform; + pitchFactor: number; + screenRightBoundary: number; + screenBottomBoundary: number; + gridRightBoundary: number; + gridBottomBoundary: number; + mapProjection: Projection; + perspectiveRatioCutoff: number; + constructor(transform: Transform, projection: Projection, grid?: GridIndex, ignoredGrid?: GridIndex); + placeCollisionBox(collisionBox: SingleCollisionBox, overlapMode: OverlapMode, textPixelRatio: number, posMatrix: mat4, unwrappedTileID: UnwrappedTileID, pitchWithMap: boolean, rotateWithMap: boolean, translation: [ + number, + number + ], collisionGroupPredicate?: (key: FeatureKey) => boolean, getElevation?: (x: number, y: number) => number, shift?: Point): PlacedBox; + placeCollisionCircles(overlapMode: OverlapMode, symbol: any, lineVertexArray: SymbolLineVertexArray, glyphOffsetArray: GlyphOffsetArray, fontSize: number, posMatrix: mat4, unwrappedTileID: UnwrappedTileID, labelPlaneMatrix: mat4, labelToScreenMatrix: mat4, showCollisionCircles: boolean, pitchWithMap: boolean, collisionGroupPredicate: (key: FeatureKey) => boolean, circlePixelDiameter: number, textPixelPadding: number, translation: [ + number, + number + ], getElevation: (x: number, y: number) => number): PlacedCircles; + projectPathToScreenSpace(projectedPath: Array, projectionContext: SymbolProjectionContext, labelToScreenMatrix: mat4): PointProjection[]; + /** + * Because the geometries in the CollisionIndex are an approximation of the shape of + * symbols on the map, we use the CollisionIndex to look up the symbol part of + * `queryRenderedFeatures`. + */ + queryRenderedSymbols(viewportQueryGeometry: Array): {}; + insertCollisionBox(collisionBox: Array, overlapMode: OverlapMode, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number): void; + insertCollisionCircles(collisionCircles: Array, overlapMode: OverlapMode, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number): void; + projectAndGetPerspectiveRatio(posMatrix: mat4, x: number, y: number, _unwrappedTileID: UnwrappedTileID, getElevation?: (x: number, y: number) => number): { + point: Point; + perspectiveRatio: number; + isOccluded: boolean; + signedDistanceFromCamera: any; + }; + getPerspectiveRatio(posMatrix: mat4, x: number, y: number, unwrappedTileID: UnwrappedTileID, getElevation?: (x: number, y: number) => number): number; + isOffscreen(x1: number, y1: number, x2: number, y2: number): boolean; + isInsideGrid(x1: number, y1: number, x2: number, y2: number): boolean; + getViewportMatrix(): mat4; + /** + * Applies all layout+paint properties of the given box in order to find as good approximation of its screen-space bounding box as possible. + */ + private _projectCollisionBox; +} +declare enum TextAnchorEnum { + "center" = 1, + "left" = 2, + "right" = 3, + "top" = 4, + "bottom" = 5, + "top-left" = 6, + "top-right" = 7, + "bottom-left" = 8, + "bottom-right" = 9 +} +export type TextAnchor = keyof typeof TextAnchorEnum; +declare class OpacityState { + opacity: number; + placed: boolean; + constructor(prevState: OpacityState, increment: number, placed: boolean, skipFade?: boolean | null); + isHidden(): boolean; +} +declare class JointOpacityState { + text: OpacityState; + icon: OpacityState; + constructor(prevState: JointOpacityState, increment: number, placedText: boolean, placedIcon: boolean, skipFade?: boolean | null); + isHidden(): boolean; +} +declare class JointPlacement { + text: boolean; + icon: boolean; + skipFade: boolean; + constructor(text: boolean, icon: boolean, skipFade: boolean); +} +declare class CollisionCircleArray { + invProjMatrix: mat4; + viewportMatrix: mat4; + circles: Array; + constructor(); +} +declare class RetainedQueryData { + bucketInstanceId: number; + featureIndex: FeatureIndex; + sourceLayerIndex: number; + bucketIndex: number; + tileID: OverscaledTileID; + featureSortOrder: Array; + constructor(bucketInstanceId: number, featureIndex: FeatureIndex, sourceLayerIndex: number, bucketIndex: number, tileID: OverscaledTileID); +} +export type CollisionGroup = { + ID: number; + predicate?: (key: FeatureKey) => boolean; +}; +declare class CollisionGroups { + collisionGroups: { + [groupName: string]: CollisionGroup; + }; + maxGroupID: number; + crossSourceCollisions: boolean; + constructor(crossSourceCollisions: boolean); + get(sourceID: string): CollisionGroup; +} +export type VariableOffset = { + textOffset: [ + number, + number + ]; + width: number; + height: number; + anchor: TextAnchor; + textBoxScale: number; + prevAnchor?: TextAnchor; +}; +export type TileLayerParameters = { + bucket: SymbolBucket; + layout: PossiblyEvaluated; + translationText: [ + number, + number + ]; + translationIcon: [ + number, + number + ]; + unwrappedTileID: UnwrappedTileID; + posMatrix: mat4; + textLabelPlaneMatrix: mat4; + labelToScreenMatrix: mat4; + scale: number; + textPixelRatio: number; + holdingForFade: boolean; + collisionBoxArray: CollisionBoxArray; + partiallyEvaluatedTextSize: { + uSize: number; + uSizeT: number; + }; + collisionGroup: CollisionGroup; +}; +export type BucketPart = { + sortKey?: number | void; + symbolInstanceStart: number; + symbolInstanceEnd: number; + parameters: TileLayerParameters; +}; +export type CrossTileID = string | number; +declare class Placement { + transform: Transform; + terrain: Terrain; + collisionIndex: CollisionIndex; + placements: { + [_ in CrossTileID]: JointPlacement; + }; + opacities: { + [_ in CrossTileID]: JointOpacityState; + }; + variableOffsets: { + [_ in CrossTileID]: VariableOffset; + }; + placedOrientations: { + [_ in CrossTileID]: number; + }; + commitTime: number; + prevZoomAdjustment: number; + lastPlacementChangeTime: number; + stale: boolean; + fadeDuration: number; + retainedQueryData: { + [_: number]: RetainedQueryData; + }; + collisionGroups: CollisionGroups; + prevPlacement: Placement; + zoomAtLastRecencyCheck: number; + collisionCircleArrays: { + [k in any]: CollisionCircleArray; + }; + collisionBoxArrays: Map>; + constructor(transform: Transform, projection: Projection, terrain: Terrain, fadeDuration: number, crossSourceCollisions: boolean, prevPlacement?: Placement); + private _getTerrainElevationFunc; + getBucketParts(results: Array, styleLayer: StyleLayer, tile: Tile, sortAcrossTiles: boolean): void; + attemptAnchorPlacement(textAnchorOffset: TextAnchorOffset, textBox: SingleCollisionBox, width: number, height: number, textBoxScale: number, rotateWithMap: boolean, pitchWithMap: boolean, textPixelRatio: number, posMatrix: mat4, unwrappedTileID: any, collisionGroup: CollisionGroup, textOverlapMode: OverlapMode, symbolInstance: SymbolInstance, bucket: SymbolBucket, orientation: number, translationText: [ + number, + number + ], translationIcon: [ + number, + number + ], iconBox?: SingleCollisionBox | null, getElevation?: (x: number, y: number) => number): { + shift: Point; + placedGlyphBoxes: PlacedBox; + }; + placeLayerBucketPart(bucketPart: BucketPart, seenCrossTileIDs: { + [k in string | number]: boolean; + }, showCollisionBoxes: boolean): void; + storeCollisionData(bucketInstanceId: number, symbolIndex: number, collisionArrays: CollisionArrays, placedGlyphBoxes: PlacedBox, placedIconBoxes: PlacedBox, placedGlyphCircles: PlacedCircles): void; + markUsedJustification(bucket: SymbolBucket, placedAnchor: TextAnchor, symbolInstance: SymbolInstance, orientation: number): void; + markUsedOrientation(bucket: SymbolBucket, orientation: number, symbolInstance: SymbolInstance): void; + commit(now: number): void; + updateLayerOpacities(styleLayer: StyleLayer, tiles: Array): void; + updateBucketOpacities(bucket: SymbolBucket, tileID: OverscaledTileID, seenCrossTileIDs: { + [k in string | number]: boolean; + }, collisionBoxArray?: CollisionBoxArray | null): void; + symbolFadeChange(now: number): number; + zoomAdjustment(zoom: number): number; + hasTransitions(now: number): boolean; + stillRecent(now: number, zoom: number): boolean; + setStale(): void; +} +/** + * Options to pass to query the map for the rendered features + */ +export type QueryRenderedFeaturesOptions = { + /** + * An array of [style layer IDs](https://maplibre.org/maplibre-style-spec/#layer-id) for the query to inspect. + * Only features within these layers will be returned. If this parameter is undefined, all layers will be checked. + */ + layers?: Array; + /** + * A [filter](https://maplibre.org/maplibre-style-spec/layers/#filter) to limit query results. + */ + filter?: FilterSpecification; + /** + * An array of string representing the available images + */ + availableImages?: Array; + /** + * Whether to check if the [options.filter] conforms to the MapLibre 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. + */ + validate?: boolean; +}; +/** + * The options object related to the {@link Map#querySourceFeatures} method + */ +export type QuerySourceFeatureOptions = { + /** + * The name of the source layer to query. *For vector tile sources, this parameter is required.* For GeoJSON sources, it is ignored. + */ + sourceLayer?: string; + /** + * A [filter](https://maplibre.org/maplibre-style-spec/layers/#filter) + * to limit query results. + */ + filter?: FilterSpecification; + /** + * Whether to check if the [parameters.filter] conforms to the MapLibre 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. + * @defaultValue true + */ + validate?: boolean; +}; +declare class LayerPlacement { + _sortAcrossTiles: boolean; + _currentTileIndex: number; + _currentPartIndex: number; + _seenCrossTileIDs: { + [k in string | number]: boolean; + }; + _bucketParts: Array; + constructor(styleLayer: SymbolStyleLayer); + continuePlacement(tiles: Array, placement: Placement, showCollisionBoxes: boolean, styleLayer: StyleLayer, shouldPausePlacement: () => boolean): boolean; +} +declare class PauseablePlacement { + placement: Placement; + _done: boolean; + _currentPlacementIndex: number; + _forceFullPlacement: boolean; + _showCollisionBoxes: boolean; + _inProgressLayer: LayerPlacement; + constructor(transform: Transform, terrain: Terrain, order: Array, forceFullPlacement: boolean, showCollisionBoxes: boolean, fadeDuration: number, crossSourceCollisions: boolean, prevPlacement?: Placement); + isDone(): boolean; + continuePlacement(order: Array, layers: { + [_: string]: StyleLayer; + }, layerTiles: { + [_: string]: Array; + }): void; + commit(now: number): Placement; +} +/** +* Input arguments exposed by custom render function. +*/ +export type CustomRenderMethodInput = { + /** + * This value represents the distance from the camera to the far clipping plane. + * It is used in the calculation of the projection matrix to determine which objects are visible. + * farz should be larger than nearZ. + */ + farZ: number; + /** + * This value represents the distance from the camera to the near clipping plane. + * It is used in the calculation of the projection matrix to determine which objects are visible. + * nearZ should be smaller than farZ. + */ + nearZ: number; + /** field of view of camera **/ + fov: number; + /** + * model view projection matrix + * represents the matrix converting from world space to clip space + * https://learnopengl.com/Getting-started/Coordinate-Systems + * **/ + modelViewProjectionMatrix: mat4; + /** + * projection matrix + * represents the matrix converting from view space to clip space + * https://learnopengl.com/Getting-started/Coordinate-Systems + */ + projectionMatrix: mat4; +}; +/** + * @param gl - The map's gl context. + * @param matrix - The map's camera matrix. It projects spherical mercator + * coordinates to gl clip space coordinates. The spherical mercator coordinate `[0, 0]` represents the + * top left corner of the mercator world and `[1, 1]` represents the bottom right corner. When + * the `renderingMode` is `"3d"`, the z coordinate is conformal. A box with identical x, y, and z + * lengths in mercator units would be rendered as a cube. {@link MercatorCoordinate.fromLngLat} + * can be used to project a `LngLat` to a mercator coordinate. + * @param options - Argument object with additional render inputs like camera properties. + */ +export type CustomRenderMethod = (gl: WebGLRenderingContext | WebGL2RenderingContext, matrix: mat4, options: CustomRenderMethodInput) => void; +/** + * Interface for custom style layers. This is a specification for + * implementers to model: it is not an exported method or class. + * + * Custom layers allow a user to render directly into the map's GL context using the map's camera. + * These layers can be added between any regular layers using {@link Map#addLayer}. + * + * Custom layers must have a unique `id` and must have the `type` of `"custom"`. + * They must implement `render` and may implement `prerender`, `onAdd` and `onRemove`. + * They can trigger rendering using {@link Map#triggerRepaint} + * and they should appropriately handle {@link MapContextEvent} with `webglcontextlost` and `webglcontextrestored`. + * + * The `renderingMode` property controls whether the layer is treated as a `"2d"` or `"3d"` map layer. Use: + * + * - `"renderingMode": "3d"` to use the depth buffer and share it with other layers + * - `"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 + * framebuffer and {@link CustomLayerInterface#prerender} + * + * @example + * Custom layer implemented as ES6 class + * ```ts + * class NullIslandLayer { + * constructor() { + * this.id = 'null-island'; + * this.type = 'custom'; + * this.renderingMode = '2d'; + * } + * + * onAdd(map, gl) { + * const vertexSource = ` + * uniform mat4 u_matrix; + * void main() { + * gl_Position = u_matrix * vec4(0.5, 0.5, 0.0, 1.0); + * gl_PointSize = 20.0; + * }`; + * + * const fragmentSource = ` + * void main() { + * fragColor = vec4(1.0, 0.0, 0.0, 1.0); + * }`; + * + * const vertexShader = gl.createShader(gl.VERTEX_SHADER); + * gl.shaderSource(vertexShader, vertexSource); + * gl.compileShader(vertexShader); + * const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); + * gl.shaderSource(fragmentShader, fragmentSource); + * gl.compileShader(fragmentShader); + * + * this.program = gl.createProgram(); + * gl.attachShader(this.program, vertexShader); + * gl.attachShader(this.program, fragmentShader); + * gl.linkProgram(this.program); + * } + * + * render(gl, matrix) { + * gl.useProgram(this.program); + * gl.uniformMatrix4fv(gl.getUniformLocation(this.program, "u_matrix"), false, matrix); + * gl.drawArrays(gl.POINTS, 0, 1); + * } + * } + * + * map.on('load', () => { + * map.addLayer(new NullIslandLayer()); + * }); + * ``` + */ +export interface CustomLayerInterface { + /** + * A unique layer id. + */ + id: string; + /** + * The layer's type. Must be `"custom"`. + */ + type: "custom"; + /** + * Either `"2d"` or `"3d"`. Defaults to `"2d"`. + */ + renderingMode?: "2d" | "3d"; + /** + * Called during a render frame allowing the layer to draw into the GL context. + * + * The layer can assume blending and depth state is set to allow the layer to properly + * blend and clip other layers. The layer cannot make any other assumptions about the + * current GL state. + * + * If the layer needs to render to a texture, it should implement the `prerender` method + * to do this and only use the `render` method for drawing directly into the main framebuffer. + * + * The blend function is set to `gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`. This expects + * colors to be provided in premultiplied alpha form where the `r`, `g` and `b` values are already + * multiplied by the `a` value. If you are unable to provide colors in premultiplied form you + * may want to change the blend function to + * `gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`. + */ + render: CustomRenderMethod; + /** + * Optional method called during a render frame to allow a layer to prepare resources or render into a texture. + * + * The layer cannot make any assumptions about the current GL state and must bind a framebuffer before rendering. + */ + prerender?: CustomRenderMethod; + /** + * Optional method called when the layer has been added to the Map with {@link Map#addLayer}. This + * gives the layer a chance to initialize gl resources and register event listeners. + * + * @param map - The Map this custom layer was just added to. + * @param gl - The gl context for the map. + */ + onAdd?(map: Map$1, gl: WebGLRenderingContext | WebGL2RenderingContext): void; + /** + * Optional method called when the layer has been removed from the Map with {@link Map#removeLayer}. This + * gives the layer a chance to clean up gl resources and event listeners. + * + * @param map - The Map this custom layer was just added to. + * @param gl - The gl context for the map. + */ + onRemove?(map: Map$1, gl: WebGLRenderingContext | WebGL2RenderingContext): void; +} +export type ValidationError = { + message: string; + line: number; + identifier?: string; +}; +export type Validator = (a: any) => ReadonlyArray; +/** + * A feature identifier that is bound to a source + */ +export type FeatureIdentifier = { + /** + * Unique id of the feature. + */ + id?: string | number | undefined; + /** + * The id of the vector or GeoJSON source for the feature. + */ + source: string; + /** + * *For vector tile sources, `sourceLayer` is required.* + */ + sourceLayer?: string | undefined; +}; +/** + * The options object related to the {@link Map}'s style related methods + */ +export type StyleOptions = { + /** + * If false, style validation will be skipped. Useful in production environment. + */ + validate?: boolean; + /** + * Defines a CSS + * font-family for locally overriding generation of Chinese, Japanese, and Korean characters. + * For these characters, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold). + * Set to `false`, to enable font settings from the map's style for these glyph ranges. + * Forces a full update. + */ + localIdeographFontFamily?: string | false; +}; +/** + * Supporting type to add validation to another style related type + */ +export type StyleSetterOptions = { + /** + * Whether to check if the filter conforms to the MapLibre 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. + */ + validate?: boolean; +}; +/** + * Part of {@link Map#setStyle} options, transformStyle is a convenience function that allows to modify a style after it is fetched but before it is committed to the map state. + * + * This function exposes previous and next styles, it can be commonly used to support a range of functionalities like: + * + * - when previous style carries certain 'state' that needs to be carried over to a new style gracefully; + * - when a desired style is a certain combination of previous and incoming style; + * - when an incoming style requires modification based on external state. + * + * @param previous - The current style. + * @param next - The next style. + * @returns resulting style that will to be applied to the map + * + * @example + * ```ts + * map.setStyle('https://demotiles.maplibre.org/style.json', { + * transformStyle: (previousStyle, nextStyle) => ({ + * ...nextStyle, + * sources: { + * ...nextStyle.sources, + * // copy a source from previous style + * 'osm': previousStyle.sources.osm + * }, + * layers: [ + * // background layer + * nextStyle.layers[0], + * // copy a layer from previous style + * previousStyle.layers[0], + * // other layers from the next style + * ...nextStyle.layers.slice(1).map(layer => { + * // hide the layers we don't need from demotiles style + * if (layer.id.startsWith('geolines')) { + * layer.layout = {...layer.layout || {}, visibility: 'none'}; + * // filter out US polygons + * } else if (layer.id.startsWith('coastline') || layer.id.startsWith('countries')) { + * layer.filter = ['!=', ['get', 'ADM0_A3'], 'USA']; + * } + * return layer; + * }) + * ] + * }) + * }); + * ``` + */ +export type TransformStyleFunction = (previous: StyleSpecification | undefined, next: StyleSpecification) => StyleSpecification; +/** + * The options object related to the {@link Map}'s style related methods + */ +export type StyleSwapOptions = { + /** + * If false, force a 'full' update, removing the current style + * and building the given one instead of attempting a diff-based update. + */ + diff?: boolean; + /** + * TransformStyleFunction is a convenience function + * that allows to modify a style after it is fetched but before it is committed to the map state. Refer to {@link TransformStyleFunction}. + */ + transformStyle?: TransformStyleFunction; +}; +/** + * Specifies a layer to be added to a {@link Style}. In addition to a standard {@link LayerSpecification} + * or a {@link CustomLayerInterface}, a {@link LayerSpecification} with an embedded {@link SourceSpecification} can also be provided. + */ +export type AddLayerObject = LayerSpecification | (Omit & { + source: SourceSpecification; +}) | CustomLayerInterface; +/** + * The Style base class + */ +export declare class Style extends Evented { + map: Map$1; + stylesheet: StyleSpecification; + dispatcher: Dispatcher; + imageManager: ImageManager; + glyphManager: GlyphManager; + lineAtlas: LineAtlas; + light: Light; + sky: Sky; + _frameRequest: AbortController; + _loadStyleRequest: AbortController; + _spriteRequest: AbortController; + _layers: { + [_: string]: StyleLayer; + }; + _serializedLayers: { + [_: string]: LayerSpecification; + }; + _order: Array; + sourceCaches: { + [_: string]: SourceCache; + }; + zoomHistory: ZoomHistory; + _loaded: boolean; + _changed: boolean; + _updatedSources: { + [_: string]: "clear" | "reload"; + }; + _updatedLayers: { + [_: string]: true; + }; + _removedLayers: { + [_: string]: StyleLayer; + }; + _changedImages: { + [_: string]: true; + }; + _glyphsDidChange: boolean; + _updatedPaintProps: { + [layer: string]: true; + }; + _layerOrderChanged: boolean; + _spritesImagesIds: { + [spriteId: string]: string[]; + }; + _availableImages: Array; + crossTileSymbolIndex: CrossTileSymbolIndex; + pauseablePlacement: PauseablePlacement; + placement: Placement; + z: number; + constructor(map: Map$1, options?: StyleOptions); + _rtlPluginLoaded: () => void; + loadURL(url: string, options?: StyleSwapOptions & StyleSetterOptions, previousStyle?: StyleSpecification): void; + loadJSON(json: StyleSpecification, options?: StyleSetterOptions & StyleSwapOptions, previousStyle?: StyleSpecification): void; + loadEmpty(): void; + _load(json: StyleSpecification, options: StyleSwapOptions & StyleSetterOptions, previousStyle?: StyleSpecification): void; + private _createLayers; + _loadSprite(sprite: SpriteSpecification, isUpdate?: boolean, completion?: (err: Error) => void): void; + _unloadSprite(): void; + _validateLayer(layer: StyleLayer): void; + loaded(): boolean; + /** + * @hidden + * take an array of string IDs, and based on this._layers, generate an array of LayerSpecification + * @param ids - an array of string IDs, for which serialized layers will be generated. If omitted, all serialized layers will be returned + * @param returnClose - if true, return a clone of the layer object + * @returns generated result + */ + private _serializeByIds; + /** + * @hidden + * Lazy initialization of this._serializedLayers dictionary and return it + * @returns this._serializedLayers dictionary + */ + private _serializedAllLayers; + hasTransitions(): boolean; + _checkLoaded(): void; + /** + * @internal + * Apply queued style updates in a batch and recalculate zoom-dependent paint properties. + */ + update(parameters: EvaluationParameters): void; + _updateTilesForChangedImages(): void; + _updateTilesForChangedGlyphs(): void; + _updateWorkerLayers(updatedIds: Array, removedIds: Array): void; + _resetUpdates(): void; + /** + * Update this style's state to match the given style JSON, performing only + * the necessary mutations. + * + * May throw an Error ('Unimplemented: METHOD') if the mapbox-gl-style-spec + * diff algorithm produces an operation that is not supported. + * + * @returns true if any changes were made; false otherwise + */ + setState(nextState: StyleSpecification, options?: StyleSwapOptions & StyleSetterOptions): boolean; + _getOperationsToPerform(diff: DiffCommand[]): { + operations: Function[]; + unimplemented: string[]; + }; + addImage(id: string, image: StyleImage): this; + updateImage(id: string, image: StyleImage): void; + getImage(id: string): StyleImage; + removeImage(id: string): this; + _afterImageUpdated(id: string): void; + listImages(): string[]; + addSource(id: string, source: SourceSpecification | CanvasSourceSpecification, options?: StyleSetterOptions): void; + /** + * Remove a source from this stylesheet, given its id. + * @param id - id of the source to remove + * @throws if no source is found with the given ID + */ + removeSource(id: string): this; + /** + * Set the data of a GeoJSON source, given its id. + * @param id - id of the source + * @param data - GeoJSON source + */ + setGeoJSONSourceData(id: string, data: GeoJSON.GeoJSON | string): void; + /** + * Get a source by ID. + * @param id - ID of the desired source + * @returns source + */ + getSource(id: string): Source | undefined; + /** + * Add a layer to the map style. The layer will be inserted before the layer with + * ID `before`, or appended if `before` is omitted. + * @param layerObject - The style layer to add. + * @param before - ID of an existing layer to insert before + * @param options - Style setter options. + */ + addLayer(layerObject: AddLayerObject, before?: string, options?: StyleSetterOptions): this; + /** + * Moves a layer to a different z-position. The layer will be inserted before the layer with + * ID `before`, or appended if `before` is omitted. + * @param id - ID of the layer to move + * @param before - ID of an existing layer to insert before + */ + moveLayer(id: string, before?: string): void; + /** + * Remove the layer with the given id from the style. + * A {@link ErrorEvent} event will be fired if no such layer exists. + * + * @param id - id of the layer to remove + */ + removeLayer(id: string): void; + /** + * Return the style layer object with the given `id`. + * + * @param id - id of the desired layer + * @returns a layer, if one with the given `id` exists + */ + getLayer(id: string): StyleLayer | undefined; + /** + * Return the ids of all layers currently in the style, including custom layers, in order. + * + * @returns ids of layers, in order + */ + getLayersOrder(): string[]; + /** + * Checks if a specific layer is present within the style. + * + * @param id - the id of the desired layer + * @returns a boolean specifying if the given layer is present + */ + hasLayer(id: string): boolean; + setLayerZoomRange(layerId: string, minzoom?: number | null, maxzoom?: number | null): void; + setFilter(layerId: string, filter?: FilterSpecification | null, options?: StyleSetterOptions): void; + /** + * Get a layer's filter object + * @param layer - the layer to inspect + * @returns the layer's filter, if any + */ + getFilter(layer: string): FilterSpecification | void; + setLayoutProperty(layerId: string, name: string, value: any, options?: StyleSetterOptions): void; + /** + * Get a layout property's value from a given layer + * @param layerId - the layer to inspect + * @param name - the name of the layout property + * @returns the property value + */ + getLayoutProperty(layerId: string, name: string): any; + setPaintProperty(layerId: string, name: string, value: any, options?: StyleSetterOptions): void; + getPaintProperty(layer: string, name: string): unknown; + setFeatureState(target: FeatureIdentifier, state: any): void; + removeFeatureState(target: FeatureIdentifier, key?: string): void; + getFeatureState(target: FeatureIdentifier): import("@maplibre/maplibre-gl-style-spec").FeatureState; + getTransition(): { + duration: number; + delay: number; + } & import("@maplibre/maplibre-gl-style-spec").TransitionSpecification; + serialize(): StyleSpecification | undefined; + _updateLayer(layer: StyleLayer): void; + _flattenAndSortRenderedFeatures(sourceResults: Array<{ + [key: string]: Array<{ + featureIndex: number; + feature: MapGeoJSONFeature; + }>; + }>): any[]; + queryRenderedFeatures(queryGeometry: any, params: QueryRenderedFeaturesOptions, transform: Transform): any[]; + querySourceFeatures(sourceID: string, params?: QuerySourceFeatureOptions): any[]; + getLight(): LightSpecification; + setLight(lightOptions: LightSpecification, options?: StyleSetterOptions): void; + getSky(): SkySpecification; + setSky(skyOptions?: SkySpecification, options?: StyleSetterOptions): void; + _validate(validate: Validator, key: string, value: any, props: any, options?: { + validate?: boolean; + }): boolean; + _remove(mapRemoved?: boolean): void; + _clearSource(id: string): void; + _reloadSource(id: string): void; + _updateSources(transform: Transform): void; + _generateCollisionBoxes(): void; + _updatePlacement(transform: Transform, showCollisionBoxes: boolean, fadeDuration: number, crossSourceCollisions: boolean, forceFullPlacement?: boolean): boolean; + _releaseSymbolFadeTiles(): void; + getImages(mapId: string | number, params: GetImagesParameters): Promise; + getGlyphs(mapId: string | number, params: GetGlyphsParameters): Promise; + getGlyphsUrl(): string; + setGlyphs(glyphsUrl: string | null, options?: StyleSetterOptions): void; + /** + * Add a sprite. + * + * @param id - The id of the desired sprite + * @param url - The url to load the desired sprite from + * @param options - The style setter options + * @param completion - The completion handler + */ + addSprite(id: string, url: string, options?: StyleSetterOptions, completion?: (err: Error) => void): void; + /** + * Remove a sprite by its id. When the last sprite is removed, the whole `this.stylesheet.sprite` object becomes + * `undefined`. This falsy `undefined` value later prevents attempts to load the sprite when it's absent. + * + * @param id - the id of the sprite to remove + */ + removeSprite(id: string): void; + /** + * Get the current sprite value. + * + * @returns empty array when no sprite is set; id-url pairs otherwise + */ + getSprite(): { + id: string; + url: string; + }[]; + /** + * Set a new value for the style's sprite. + * + * @param sprite - new sprite value + * @param options - style setter options + * @param completion - the completion handler + */ + setSprite(sprite: SpriteSpecification, options?: StyleSetterOptions, completion?: (err: Error) => void): void; +} +export type BucketParameters = { + index: number; + layers: Array; + zoom: number; + pixelRatio: number; + overscaling: number; + collisionBoxArray: CollisionBoxArray; + sourceLayerIndex: number; + sourceID: string; +}; +export type PopulateParameters = { + featureIndex: FeatureIndex; + iconDependencies: {}; + patternDependencies: {}; + glyphDependencies: {}; + availableImages: Array; +}; +export type IndexedFeature = { + feature: VectorTileFeature; + id: number | string; + index: number; + sourceLayerIndex: number; +}; +export type BucketFeature = { + index: number; + sourceLayerIndex: number; + geometry: Array>; + properties: any; + type: 0 | 1 | 2 | 3; + id?: any; + readonly patterns: { + [_: string]: { + "min": string; + "mid": string; + "max": string; + }; + }; + sortKey?: number; +}; +/** + * The `Bucket` interface is the single point of knowledge about turning vector + * tiles into WebGL buffers. + * + * `Bucket` is an abstract interface. An implementation exists for each style layer type. + * Create a bucket via the `StyleLayer#createBucket` method. + * + * The concrete bucket types, using layout options from the style layer, + * transform feature geometries into vertex and index data for use by the + * vertex shader. They also (via `ProgramConfiguration`) use feature + * properties and the zoom level to populate the attributes needed for + * data-driven styling. + * + * Buckets are designed to be built on a worker thread and then serialized and + * transferred back to the main thread for rendering. On the worker side, a + * bucket's vertex, index, and attribute data is stored in `bucket.arrays: ArrayGroup`. + * When a bucket's data is serialized and sent back to the main thread, + * is gets deserialized (using `new Bucket(serializedBucketData)`, with + * the array data now stored in `bucket.buffers: BufferGroup`. BufferGroups + * hold the same data as ArrayGroups, but are tuned for consumption by WebGL. + */ +export interface Bucket { + layerIds: Array; + hasPattern: boolean; + readonly layers: Array; + readonly stateDependentLayers: Array; + readonly stateDependentLayerIds: Array; + populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID): void; + update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: { + [_: string]: ImagePosition; + }): void; + isEmpty(): boolean; + upload(context: Context): void; + uploadPending(): boolean; + /** + * Release the WebGL resources associated with the buffers. Note that because + * buckets are shared between layers having the same layout properties, they + * must be destroyed in groups (all buckets for a tile, or all symbol buckets). + */ + destroy(): void; +} +declare abstract class StyleLayer extends Evented { + id: string; + metadata: unknown; + type: LayerSpecification["type"] | CustomLayerInterface["type"]; + source: string; + sourceLayer: string; + minzoom: number; + maxzoom: number; + filter: FilterSpecification | void; + visibility: "visible" | "none" | void; + _crossfadeParameters: CrossfadeParameters; + _unevaluatedLayout: Layout; + readonly layout: unknown; + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + readonly paint: unknown; + _featureFilter: FeatureFilter; + readonly onAdd: ((map: Map$1) => void); + readonly onRemove: ((map: Map$1) => void); + queryRadius?(bucket: Bucket): number; + queryIntersectsFeature?(queryGeometry: Array, feature: VectorTileFeature, featureState: FeatureState, geometry: Array>, zoom: number, transform: Transform, pixelsToTileUnits: number, pixelPosMatrix: mat4): boolean | number; + constructor(layer: LayerSpecification | CustomLayerInterface, properties: Readonly<{ + layout?: Properties; + paint?: Properties; + }>); + getCrossfadeParameters(): CrossfadeParameters; + getLayoutProperty(name: string): any; + setLayoutProperty(name: string, value: any, options?: StyleSetterOptions): void; + getPaintProperty(name: string): unknown; + setPaintProperty(name: string, value: unknown, options?: StyleSetterOptions): boolean; + _handleSpecialPaintPropertyUpdate(_: string): void; + _handleOverridablePaintPropertyUpdate(name: string, oldValue: PropertyValue, newValue: PropertyValue): boolean; + isHidden(zoom: number): boolean; + updateTransitions(parameters: TransitionParameters): void; + hasTransition(): boolean; + recalculate(parameters: EvaluationParameters, availableImages: Array): void; + serialize(): LayerSpecification; + _validate(validate: Function, key: string, name: string, value: unknown, options?: StyleSetterOptions): boolean; + is3D(): boolean; + isTileClipped(): boolean; + hasOffscreenPass(): boolean; + resize(): void; + isStateDependent(): boolean; +} +/** + * A way to identify a feature, either by string or by number + */ +export type GeoJSONFeatureId = number | string; +/** + * The geojson source diff object + */ +export type GeoJSONSourceDiff = { + /** + * When set to `true` it will remove all features + */ + removeAll?: boolean; + /** + * An array of features IDs to remove + */ + remove?: Array; + /** + * An array of features to add + */ + add?: Array; + /** + * An array of update objects + */ + update?: Array; +}; +/** + * A geojson feature diff object + */ +export type GeoJSONFeatureDiff = { + /** + * The feature ID + */ + id: GeoJSONFeatureId; + /** + * If it's a new geometry, place it here + */ + newGeometry?: GeoJSON.Geometry; + /** + * Setting to `true` will remove all preperties + */ + removeAllProperties?: boolean; + /** + * The properties keys to remove + */ + removeProperties?: Array; + /** + * The properties to add or update along side their values + */ + addOrUpdateProperties?: Array<{ + key: string; + value: any; + }>; +}; +/** + * The geojson worker options that can be passed to the worker + */ +export type GeoJSONWorkerOptions = { + source?: string; + cluster?: boolean; + geojsonVtOptions?: GeoJSONVTOptions; + superclusterOptions?: SuperclusterOptions; + clusterProperties?: ClusterProperties; + filter?: Array; + promoteId?: string; + collectResourceTiming?: boolean; +}; +/** + * Parameters needed to load a geojson to the worker + */ +export type LoadGeoJSONParameters = GeoJSONWorkerOptions & { + type: "geojson"; + request?: RequestParameters; + /** + * Literal GeoJSON data. Must be provided if `request.url` is not. + */ + data?: string; + dataDiff?: GeoJSONSourceDiff; +}; +/** + * The possible option of the plugin's status + * + * `unavailable`: Not loaded. + * + * `deferred`: The plugin URL has been specified, but loading has been deferred. + * + * `requested`: at least one tile needs RTL to render, but the plugin has not been set + * + * `loading`: RTL is in the process of being loaded by worker. + * + * `loaded`: The plugin is now loaded + * + * `error`: The plugin failed to load + */ +export type RTLPluginStatus = "unavailable" | "deferred" | "requested" | "loading" | "loaded" | "error"; +/** + * The RTL plugin state + */ +export type PluginState = { + pluginStatus: RTLPluginStatus; + pluginURL: string; +}; +/** + * The parameters needed in order to get information about the cluster + */ +export type ClusterIDAndSource = { + type: "geojson"; + clusterId: number; + source: string; +}; +/** + * Parameters needed to get the leaves of a cluster + */ +export type GetClusterLeavesParams = ClusterIDAndSource & { + limit: number; + offset: number; +}; +/** + * The result of the call to load a geojson source + */ +export type GeoJSONWorkerSourceLoadDataResult = { + resourceTiming?: { + [_: string]: Array; + }; + abandoned?: boolean; +}; +/** + * Parameters needed to remove a source + */ +export type RemoveSourceParams = { + source: string; + type: string; +}; +/** + * Parameters needed to update the layers + */ +export type UpdateLayersParamaeters = { + layers: Array; + removedIds: Array; +}; +/** + * Parameters needed to get the images + */ +export type GetImagesParameters = { + icons: Array; + source: string; + tileID: OverscaledTileID; + type: string; +}; +/** + * Parameters needed to get the glyphs + */ +export type GetGlyphsParameters = { + type: string; + stacks: { + [_: string]: Array; + }; + source: string; + tileID: OverscaledTileID; +}; +/** + * A response object returned when requesting glyphs + */ +export type GetGlyphsResponse = { + [stack: string]: { + [id: number]: StyleGlyph; + }; +}; +/** + * A response object returned when requesting images + */ +export type GetImagesResponse = { + [_: string]: StyleImage; +}; +/** + * All the possible message types that can be sent to and from the worker + */ +export declare const enum MessageType { + loadDEMTile = "LDT", + getClusterExpansionZoom = "GCEZ", + getClusterChildren = "GCC", + getClusterLeaves = "GCL", + loadData = "LD", + getData = "GD", + loadTile = "LT", + reloadTile = "RT", + getGlyphs = "GG", + getImages = "GI", + setImages = "SI", + setLayers = "SL", + updateLayers = "UL", + syncRTLPluginState = "SRPS", + setReferrer = "SR", + removeSource = "RS", + removeMap = "RM", + importScript = "IS", + removeTile = "RMT", + abortTile = "AT", + removeDEMTile = "RDT", + getResource = "GR" +} +/** + * This is basically a mapping between all the calls that are made to and from the workers. + * The key is the event name, the first parameter is the event input type, and the last parameter is the output type. + */ +export type RequestResponseMessageMap = { + [MessageType.loadDEMTile]: [ + WorkerDEMTileParameters, + DEMData + ]; + [MessageType.getClusterExpansionZoom]: [ + ClusterIDAndSource, + number + ]; + [MessageType.getClusterChildren]: [ + ClusterIDAndSource, + Array + ]; + [MessageType.getClusterLeaves]: [ + GetClusterLeavesParams, + Array + ]; + [MessageType.loadData]: [ + LoadGeoJSONParameters, + GeoJSONWorkerSourceLoadDataResult + ]; + [MessageType.getData]: [ + LoadGeoJSONParameters, + GeoJSON.GeoJSON + ]; + [MessageType.loadTile]: [ + WorkerTileParameters, + WorkerTileResult + ]; + [MessageType.reloadTile]: [ + WorkerTileParameters, + WorkerTileResult + ]; + [MessageType.getGlyphs]: [ + GetGlyphsParameters, + GetGlyphsResponse + ]; + [MessageType.getImages]: [ + GetImagesParameters, + GetImagesResponse + ]; + [MessageType.setImages]: [ + string[], + void + ]; + [MessageType.setLayers]: [ + Array, + void + ]; + [MessageType.updateLayers]: [ + UpdateLayersParamaeters, + void + ]; + [MessageType.syncRTLPluginState]: [ + PluginState, + PluginState + ]; + [MessageType.setReferrer]: [ + string, + void + ]; + [MessageType.removeSource]: [ + RemoveSourceParams, + void + ]; + [MessageType.removeMap]: [ + undefined, + void + ]; + [MessageType.importScript]: [ + string, + void + ]; + [MessageType.removeTile]: [ + TileParameters, + void + ]; + [MessageType.abortTile]: [ + TileParameters, + void + ]; + [MessageType.removeDEMTile]: [ + TileParameters, + void + ]; + [MessageType.getResource]: [ + RequestParameters, + GetResourceResponse + ]; +}; +/** + * The message to be sent by the actor + */ +export type ActorMessage = { + type: T; + data: RequestResponseMessageMap[T][0]; + targetMapId?: string | number | null; + mustQueue?: boolean; + sourceMapId?: string | number | null; +}; +/** + * An interface to be sent to the actor in order for it to allow communication between the worker and the main thread + */ +export interface ActorTarget { + addEventListener: typeof window.addEventListener; + removeEventListener: typeof window.removeEventListener; + postMessage: typeof window.postMessage; + terminate?: () => void; +} +/** + * This is used to define the parameters of the message that is sent to the worker and back + */ +export type MessageData = { + id: string; + type: MessageType | "" | ""; + origin: string; + data?: Serialized; + targetMapId?: string | number | null; + mustQueue?: boolean; + error?: Serialized | null; + sourceMapId: string | number | null; +}; +export type ResolveReject = { + resolve: (value?: RequestResponseMessageMap[MessageType][1]) => void; + reject: (reason?: Error) => void; +}; +/** + * This interface allowing to substitute only the sendAsync method of the Actor class. + */ +export interface IActor { + sendAsync(message: ActorMessage, abortController?: AbortController): Promise; +} +export type MessageHandler = (mapId: string | number, params: RequestResponseMessageMap[T][0], abortController?: AbortController) => Promise; +declare class Actor implements IActor { + target: ActorTarget; + mapId: string | number | null; + resolveRejects: { + [x: string]: ResolveReject; + }; + name: string; + tasks: { + [x: string]: MessageData; + }; + taskQueue: Array; + abortControllers: { + [x: number | string]: AbortController; + }; + invoker: ThrottledInvoker; + globalScope: ActorTarget; + messageHandlers: { + [x in MessageType]?: MessageHandler; + }; + subscription: Subscription; + /** + * @param target - The target + * @param mapId - A unique identifier for the Map instance using this Actor. + */ + constructor(target: ActorTarget, mapId?: string | number); + registerMessageHandler(type: T, handler: MessageHandler): void; + /** + * Sends a message from a main-thread map to a Worker or from a Worker back to + * a main-thread map instance. + * @param message - the message to send + * @param abortController - an optional AbortController to abort the request + * @returns a promise that will be resolved with the response data + */ + sendAsync(message: ActorMessage, abortController?: AbortController): Promise; + receive(message: { + data: MessageData; + }): void; + process(): void; + processTask(id: string, task: MessageData): Promise; + completeTask(id: string, err: Error, data?: RequestResponseMessageMap[MessageType][1]): void; + remove(): void; +} +export interface Subscription { + unsubscribe(): void; +} +/** + * Makes optional keys required and add the the undefined type. + * + * ``` + * interface Test { + * foo: number; + * bar?: number; + * baz: number | undefined; + * } + * + * Complete { + * foo: number; + * bar: number | undefined; + * baz: number | undefined; + * } + * + * ``` + * + * See https://medium.com/terria/typescript-transforming-optional-properties-to-required-properties-that-may-be-undefined-7482cb4e1585 + */ +export type Complete = { + [P in keyof Required]: Pick extends Required> ? T[P] : (T[P] | undefined); +}; +/** + * Adds the map's position to its page's location hash. + * Passed as an option to the map object. + * + * @group Markers and Controls + */ +export declare class Hash { + _map: Map$1; + _hashName: string; + constructor(hashName?: string | null); + /** + * Map element to listen for coordinate changes + * + * @param map - The map object + */ + addTo(map: Map$1): this; + /** + * Removes hash + */ + remove(): this; + getHashString(mapFeedback?: boolean): string; + _getCurrentHash: () => any; + _onHashChange: () => boolean; + _updateHashUnthrottled: () => void; + _removeHash: () => void; + /** + * Mobile Safari doesn't allow updating the hash more than 100 times per 30 seconds. + */ + _updateHash: () => ReturnType; +} +export type TaskID = number; +export type Task = { + callback: (timeStamp: number) => void; + id: TaskID; + cancelled: boolean; +}; +declare class TaskQueue { + _queue: Array; + _id: TaskID; + _cleared: boolean; + _currentlyRunning: Array | false; + constructor(); + add(callback: (timeStamp: number) => void): TaskID; + remove(id: TaskID): void; + run(timeStamp?: number): void; + clear(): void; +} +export interface DragMovementResult { + bearingDelta?: number; + pitchDelta?: number; + around?: Point; + panDelta?: Point; +} +export interface DragPanResult extends DragMovementResult { + around: Point; + panDelta: Point; +} +export interface DragRotateResult extends DragMovementResult { + bearingDelta: number; +} +export interface DragPitchResult extends DragMovementResult { + pitchDelta: number; +} +export interface DragMoveHandler extends Handler { + dragStart: (e: E, point: Point) => void; + dragMove: (e: E, point: Point) => T | void; + dragEnd: (e: E) => void; + getClickTolerance: () => number; +} +/** + * `MousePanHandler` allows the user to pan the map by clicking and dragging + */ +export interface MousePanHandler extends DragMoveHandler { +} +/** + * `MouseRotateHandler` allows the user to rotate the map by clicking and dragging + */ +export interface MouseRotateHandler extends DragMoveHandler { +} +/** + * `MousePitchHandler` allows the user to zoom the map by pitching + */ +export interface MousePitchHandler extends DragMoveHandler { +} +declare class TouchPanHandler implements Handler { + _enabled: boolean; + _active: boolean; + _touches: { + [k in string | number]: Point; + }; + _clickTolerance: number; + _sum: Point; + _map: Map$1; + constructor(options: { + clickTolerance: number; + }, map: Map$1); + reset(): void; + _shouldBePrevented(touchesCount: number): boolean; + touchstart(e: TouchEvent, points: Array, mapTouches: Array): { + around: Point; + panDelta: Point; + }; + touchmove(e: TouchEvent, points: Array, mapTouches: Array): { + around: Point; + panDelta: Point; + }; + touchend(e: TouchEvent, points: Array, mapTouches: Array): void; + touchcancel(): void; + _calculateTransform(e: TouchEvent, points: Array, mapTouches: Array): { + around: Point; + panDelta: Point; + }; + enable(): void; + disable(): void; + isEnabled(): boolean; + isActive(): boolean; +} +/** + * A {@link DragPanHandler} options object + */ +export type DragPanOptions = { + /** + * factor used to scale the drag velocity + * @defaultValue 0 + */ + linearity?: number; + /** + * easing function applied to `map.panTo` when applying the drag. + * @param t - the easing function + * @defaultValue bezier(0, 0, 0.3, 1) + */ + easing?: (t: number) => number; + /** + * the maximum value of the drag velocity. + * @defaultValue 1400 + */ + deceleration?: number; + /** + * the rate at which the speed reduces after the pan ends. + * @defaultValue 2500 + */ + maxSpeed?: number; +}; +/** + * The `DragPanHandler` allows the user to pan the map by clicking and dragging + * the cursor. + * + * @group Handlers + */ +export declare class DragPanHandler { + _el: HTMLElement; + _mousePan: MousePanHandler; + _touchPan: TouchPanHandler; + _inertiaOptions: DragPanOptions | boolean; + /** @internal */ + constructor(el: HTMLElement, mousePan: MousePanHandler, touchPan: TouchPanHandler); + /** + * Enables the "drag to pan" interaction. + * + * @param options - Options object + * @example + * ```ts + * map.dragPan.enable(); + * map.dragPan.enable({ + * linearity: 0.3, + * easing: bezier(0, 0, 0.3, 1), + * maxSpeed: 1400, + * deceleration: 2500, + * }); + * ``` + */ + enable(options?: DragPanOptions | boolean): void; + /** + * Disables the "drag to pan" interaction. + * + * @example + * ```ts + * map.dragPan.disable(); + * ``` + */ + disable(): void; + /** + * Returns a Boolean indicating whether the "drag to pan" interaction is enabled. + * + * @returns `true` if the "drag to pan" interaction is enabled. + */ + isEnabled(): boolean; + /** + * Returns a Boolean indicating whether the "drag to pan" interaction is active, i.e. currently being used. + * + * @returns `true` if the "drag to pan" interaction is active. + */ + isActive(): boolean; +} +declare class HandlerInertia { + _map: Map$1; + _inertiaBuffer: Array<{ + time: number; + settings: any; + }>; + constructor(map: Map$1); + clear(): void; + record(settings: any): void; + _drainInertiaBuffer(): void; + _onMoveEnd(panInertiaOptions?: DragPanOptions | boolean): any; +} +/** + * Handlers interpret dom events and return camera changes that should be + * applied to the map (`HandlerResult`s). The camera changes are all deltas. + * The handler itself should have no knowledge of the map's current state. + * This makes it easier to merge multiple results and keeps handlers simpler. + * For example, if there is a mousedown and mousemove, the mousePan handler + * would return a `panDelta` on the mousemove. + */ +export interface Handler { + enable(): void; + disable(): void; + isEnabled(): boolean; + /** + * This is used to indicate if the handler is currently active or not. + * In case a handler is active, it will block other handlers from getting the relevant events. + * There is an allow list of handlers that can be active at the same time, which is configured when adding a handler. + */ + isActive(): boolean; + /** + * `reset` can be called by the manager at any time and must reset everything to it's original state + */ + reset(): void; + readonly touchstart?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void; + readonly touchmove?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void; + readonly touchmoveWindow?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void; + readonly touchend?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void; + readonly touchcancel?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void; + readonly mousedown?: (e: MouseEvent, point: Point) => HandlerResult | void; + readonly mousemove?: (e: MouseEvent, point: Point) => HandlerResult | void; + readonly mousemoveWindow?: (e: MouseEvent, point: Point) => HandlerResult | void; + readonly mouseup?: (e: MouseEvent, point: Point) => HandlerResult | void; + readonly mouseupWindow?: (e: MouseEvent, point: Point) => HandlerResult | void; + readonly dblclick?: (e: MouseEvent, point: Point) => HandlerResult | void; + readonly contextmenu?: (e: MouseEvent) => HandlerResult | void; + readonly wheel?: (e: WheelEvent, point: Point) => HandlerResult | void; + readonly keydown?: (e: KeyboardEvent) => HandlerResult | void; + readonly keyup?: (e: KeyboardEvent) => HandlerResult | void; + /** + * `renderFrame` is the only non-dom event. It is called during render + * frames and can be used to smooth camera changes (see scroll handler). + */ + readonly renderFrame?: () => HandlerResult | void; +} +/** + * All handler methods that are called with events can optionally return a `HandlerResult`. + */ +export type HandlerResult = { + panDelta?: Point; + zoomDelta?: number; + bearingDelta?: number; + pitchDelta?: number; + /** + * the point to not move when changing the camera + */ + around?: Point | null; + /** + * same as above, except for pinch actions, which are given higher priority + */ + pinchAround?: Point | null; + /** + * A method that can fire a one-off easing by directly changing the map's camera. + */ + cameraAnimation?: (map: Map$1) => any; + /** + * The last three properties are needed by only one handler: scrollzoom. + * The DOM event to be used as the `originalEvent` on any camera change events. + */ + originalEvent?: Event$1; + /** + * Makes the manager trigger a frame, allowing the handler to return multiple results over time (see scrollzoom). + */ + needsRenderFrame?: boolean; + /** + * The camera changes won't get recorded for inertial zooming. + */ + noInertia?: boolean; +}; +export type EventInProgress = { + handlerName: string; + originalEvent: Event$1; +}; +export type EventsInProgress = { + zoom?: EventInProgress; + pitch?: EventInProgress; + rotate?: EventInProgress; + drag?: EventInProgress; +}; +declare class HandlerManager { + _map: Map$1; + _el: HTMLElement; + _handlers: Array<{ + handlerName: string; + handler: Handler; + allowed: Array; + }>; + _eventsInProgress: EventsInProgress; + _frameId: number; + _inertia: HandlerInertia; + _bearingSnap: number; + _handlersById: { + [x: string]: Handler; + }; + _updatingCamera: boolean; + _changes: Array<[ + HandlerResult, + EventsInProgress, + { + [handlerName: string]: Event$1; + } + ]>; + _terrainMovement: boolean; + _zoom: { + handlerName: string; + }; + _previousActiveHandlers: { + [x: string]: Handler; + }; + _listeners: Array<[ + Window | Document | HTMLElement, + string, + { + passive?: boolean; + capture?: boolean; + } | undefined + ]>; + constructor(map: Map$1, options: CompleteMapOptions); + destroy(): void; + _addDefaultHandlers(options: CompleteMapOptions): void; + _add(handlerName: string, handler: Handler, allowed?: Array): void; + stop(allowEndAnimation: boolean): void; + isActive(): boolean; + isZooming(): boolean; + isRotating(): boolean; + isMoving(): boolean; + _blockedByActive(activeHandlers: { + [x: string]: Handler; + }, allowed: Array, myName: string): boolean; + handleWindowEvent: (e: { + type: "mousemove" | "mouseup" | "touchmove"; + }) => void; + _getMapTouches(touches: TouchList): TouchList; + handleEvent: (e: Event$1, eventName?: keyof Handler) => void; + mergeHandlerResult(mergedHandlerResult: HandlerResult, eventsInProgress: EventsInProgress, handlerResult: HandlerResult, name: string, e?: UIEvent): void; + _applyChanges(): void; + _updateMapTransform(combinedResult: HandlerResult, combinedEventsInProgress: EventsInProgress, deactivatedHandlers: { + [handlerName: string]: Event$1; + }): void; + _fireEvents(newEventsInProgress: EventsInProgress, deactivatedHandlers: { + [handlerName: string]: Event$1; + }, allowEndAnimation: boolean): void; + _fireEvent(type: string, e?: Event$1): void; + _requestFrame(): number; + _triggerRenderFrame(): void; +} +/** + * A [Point](https://github.com/mapbox/point-geometry) or an array of two numbers representing `x` and `y` screen coordinates in pixels. + * + * @group Geography and Geometry + * + * @example + * ```ts + * let p1 = new Point(-77, 38); // a PointLike which is a Point + * let p2 = [-77, 38]; // a PointLike which is an array of two numbers + * ``` + */ +export type PointLike = Point | [ + number, + number +]; +/** + * A helper to allow require of at least one property + */ +export type RequireAtLeastOne = { + [K in keyof T]-?: Required> & Partial>>; +}[keyof T]; +/** + * Options common to {@link Map#jumpTo}, {@link Map#easeTo}, and {@link Map#flyTo}, controlling the desired location, + * zoom, bearing, and pitch of the camera. All properties are optional, and when a property is omitted, the current + * camera value for that property will remain unchanged. + * + * @example + * Set the map's initial perspective with CameraOptions + * ```ts + * let map = new Map({ + * container: 'map', + * style: 'https://demotiles.maplibre.org/style.json', + * center: [-73.5804, 45.53483], + * pitch: 60, + * bearing: -60, + * zoom: 10 + * }); + * ``` + * @see [Set pitch and bearing](https://maplibre.org/maplibre-gl-js/docs/examples/set-perspective/) + * @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js/docs/examples/jump-to/) + * @see [Fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/flyto/) + * @see [Display buildings in 3D](https://maplibre.org/maplibre-gl-js/docs/examples/3d-buildings/) + */ +export type CameraOptions = CenterZoomBearing & { + /** + * The desired pitch in degrees. The pitch is the angle towards the horizon + * measured in degrees with a range between 0 and 60 degrees. For example, pitch: 0 provides the appearance + * of looking straight down at the map, while pitch: 60 tilts the user's perspective towards the horizon. + * Increasing the pitch value is often used to display 3D objects. + */ + pitch?: number; + /** + * If `zoom` is specified, `around` determines the point around which the zoom is centered. + */ + around?: LngLatLike; +}; +/** + * Holds center, zoom and bearing properties + */ +export type CenterZoomBearing = { + /** + * The desired center. + */ + center?: LngLatLike; + /** + * The desired zoom level. + */ + zoom?: number; + /** + * The desired bearing in degrees. The bearing is the compass direction that + * is "up". For example, `bearing: 90` orients the map so that east is up. + */ + bearing?: number; +}; +/** + * The options object related to the {@link Map#jumpTo} method + */ +export type JumpToOptions = CameraOptions & { + /** + * Dimensions in pixels applied on each side of the viewport for shifting the vanishing point. + */ + padding?: PaddingOptions; +}; +/** + * A options object for the {@link Map#cameraForBounds} method + */ +export type CameraForBoundsOptions = CameraOptions & { + /** + * The amount of padding in pixels to add to the given bounds. + */ + padding?: number | RequireAtLeastOne; + /** + * The center of the given bounds relative to the map's center, measured in pixels. + * @defaultValue [0, 0] + */ + offset?: PointLike; + /** + * The maximum zoom level to allow when the camera would transition to the specified bounds. + */ + maxZoom?: number; +}; +/** + * The {@link Map#flyTo} options object + */ +export type FlyToOptions = AnimationOptions & CameraOptions & { + /** + * The zooming "curve" that will occur along the + * flight path. A high value maximizes zooming for an exaggerated animation, while a low + * value minimizes zooming for an effect closer to {@link Map#easeTo}. 1.42 is the average + * value selected by participants in the user study discussed in + * [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf). A value of + * `Math.pow(6, 0.25)` would be equivalent to the root mean squared average velocity. A + * value of 1 would produce a circular motion. + * @defaultValue 1.42 + */ + curve?: number; + /** + * The zero-based zoom level at the peak of the flight path. If + * `options.curve` is specified, this option is ignored. + */ + minZoom?: number; + /** + * The average speed of the animation defined in relation to + * `options.curve`. A speed of 1.2 means that the map appears to move along the flight path + * by 1.2 times `options.curve` screenfuls every second. A _screenful_ is the map's visible span. + * It does not correspond to a fixed physical distance, but varies by zoom level. + * @defaultValue 1.2 + */ + speed?: number; + /** + * The average speed of the animation measured in screenfuls + * per second, assuming a linear timing curve. If `options.speed` is specified, this option is ignored. + */ + screenSpeed?: number; + /** + * The animation's maximum duration, measured in milliseconds. + * If duration exceeds maximum duration, it resets to 0. + */ + maxDuration?: number; + /** + * The amount of padding in pixels to add to the given bounds. + */ + padding?: number | RequireAtLeastOne; +}; +export type EaseToOptions = AnimationOptions & CameraOptions & { + delayEndEvents?: number; + padding?: number | RequireAtLeastOne; +}; +/** + * Options for {@link Map#fitBounds} method + */ +export type FitBoundsOptions = FlyToOptions & { + /** + * If `true`, the map transitions using {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. + * See those functions and {@link AnimationOptions} for information about options available. + * @defaultValue false + */ + linear?: boolean; + /** + * The center of the given bounds relative to the map's center, measured in pixels. + * @defaultValue [0, 0] + */ + offset?: PointLike; + /** + * The maximum zoom level to allow when the map view transitions to the specified bounds. + */ + maxZoom?: number; +}; +/** + * Options common to map movement methods that involve animation, such as {@link Map#panBy} and + * {@link Map#easeTo}, controlling the duration and easing function of the animation. All properties + * are optional. + * + */ +export type AnimationOptions = { + /** + * The animation's duration, measured in milliseconds. + */ + duration?: number; + /** + * A function taking a time in the range 0..1 and returning a number where 0 is + * the initial state and 1 is the final state. + */ + easing?: (_: number) => number; + /** + * of the target center relative to real map container center at the end of animation. + */ + offset?: PointLike; + /** + * If `false`, no animation will occur. + */ + animate?: boolean; + /** + * If `true`, then the animation is considered essential and will not be affected by + * [`prefers-reduced-motion`](https://developer.mozilla.org/en-US/docs/Web/CSS/\@media/prefers-reduced-motion). + */ + essential?: boolean; + /** + * Default false. Needed in 3D maps to let the camera stay in a constant + * height based on sea-level. After the animation finished the zoom-level will be recalculated in respect of + * the distance from the camera to the center-coordinate-altitude. + */ + freezeElevation?: boolean; +}; +/** + * A callback hook that allows manipulating the camera and being notified about camera updates before they happen + */ +export type CameraUpdateTransformFunction = (next: { + center: LngLat; + zoom: number; + pitch: number; + bearing: number; + elevation: number; +}) => { + center?: LngLat; + zoom?: number; + pitch?: number; + bearing?: number; + elevation?: number; +}; +declare abstract class Camera extends Evented { + transform: Transform; + terrain: Terrain; + handlers: HandlerManager; + _moving: boolean; + _zooming: boolean; + _rotating: boolean; + _pitching: boolean; + _padding: boolean; + _bearingSnap: number; + _easeStart: number; + _easeOptions: { + duration?: number; + easing?: (_: number) => number; + }; + _easeId: string | void; + _onEaseFrame: (_: number) => void; + _onEaseEnd: (easeId?: string) => void; + _easeFrameId: TaskID; + /** + * @internal + * holds the geographical coordinate of the target + */ + _elevationCenter: LngLat; + /** + * @internal + * holds the targ altitude value, = center elevation of the target. + * This value may changes during flight, because new terrain-tiles loads during flight. + */ + _elevationTarget: number; + /** + * @internal + * holds the start altitude value, = center elevation before animation begins + * this value will recalculated during flight in respect of changing _elevationTarget values, + * so the linear interpolation between start and target keeps smooth and without jumps. + */ + _elevationStart: number; + /** + * @internal + * Saves the current state of the elevation freeze - this is used during map movement to prevent "rocky" camera movement. + */ + _elevationFreeze: boolean; + /** + * @internal + * Used to track accumulated changes during continuous interaction + */ + _requestedCameraState?: Transform; + /** + * A callback used to defer camera updates or apply arbitrary constraints. + * If specified, this Camera instance can be used as a stateless component in React etc. + */ + transformCameraUpdate: CameraUpdateTransformFunction | null; + abstract _requestRenderFrame(a: () => void): TaskID; + abstract _cancelRenderFrame(_: TaskID): void; + constructor(transform: Transform, options: { + bearingSnap: number; + }); + /** + * Returns the map's geographical centerpoint. + * + * @returns The map's geographical centerpoint. + * @example + * Return a LngLat object such as `{lng: 0, lat: 0}` + * ```ts + * let center = map.getCenter(); + * // access longitude and latitude values directly + * let {lng, lat} = map.getCenter(); + * ``` + */ + getCenter(): LngLat; + /** + * Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param center - The centerpoint to set. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * map.setCenter([-74, 38]); + * ``` + */ + setCenter(center: LngLatLike, eventData?: any): this; + /** + * Pans the map by the specified offset. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param offset - `x` and `y` coordinates by which to pan the map. + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/) + */ + panBy(offset: PointLike, options?: AnimationOptions, eventData?: any): this; + /** + * Pans the map to the specified location with an animated transition. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param lnglat - The location to pan the map to. + * @param options - Options describing the destination and animation of the transition. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * map.panTo([-74, 38]); + * // Specify that the panTo animation should last 5000 milliseconds. + * map.panTo([-74, 38], {duration: 5000}); + * ``` + * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/live-update-feature/) + */ + panTo(lnglat: LngLatLike, options?: AnimationOptions, eventData?: any): this; + /** + * Returns the map's current zoom level. + * + * @returns The map's current zoom level. + * @example + * ```ts + * map.getZoom(); + * ``` + */ + getZoom(): number; + /** + * Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param zoom - The zoom level to set (0-20). + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Zoom to the zoom level 5 without an animated transition + * ```ts + * map.setZoom(5); + * ``` + */ + setZoom(zoom: number, eventData?: any): this; + /** + * Zooms the map to the specified zoom level, with an animated transition. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param zoom - The zoom level to transition to. + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * // Zoom to the zoom level 5 without an animated transition + * map.zoomTo(5); + * // Zoom to the zoom level 8 with an animated transition + * map.zoomTo(8, { + * duration: 2000, + * offset: [100, 50] + * }); + * ``` + */ + zoomTo(zoom: number, options?: AnimationOptions | null, eventData?: any): this; + /** + * Increases the map's zoom level by 1. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Zoom the map in one level with a custom animation duration + * ```ts + * map.zoomIn({duration: 1000}); + * ``` + */ + zoomIn(options?: AnimationOptions, eventData?: any): this; + /** + * Decreases the map's zoom level by 1. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Zoom the map out one level with a custom animation offset + * ```ts + * map.zoomOut({offset: [80, 60]}); + * ``` + */ + zoomOut(options?: AnimationOptions, eventData?: any): this; + /** + * Returns the map's current bearing. The bearing is the compass direction that is "up"; for example, a bearing + * of 90° orients the map so that east is up. + * + * @returns The map's current bearing. + * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/) + */ + getBearing(): number; + /** + * Sets the map's bearing (rotation). The bearing is the compass direction that is "up"; for example, a bearing + * of 90° orients the map so that east is up. + * + * Equivalent to `jumpTo({bearing: bearing})`. + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param bearing - The desired bearing. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Rotate the map to 90 degrees + * ```ts + * map.setBearing(90); + * ``` + */ + setBearing(bearing: number, eventData?: any): this; + /** + * Returns the current padding applied around the map viewport. + * + * @returns The current padding around the map viewport. + */ + getPadding(): PaddingOptions; + /** + * Sets the padding in pixels around the viewport. + * + * Equivalent to `jumpTo({padding: padding})`. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param padding - The desired padding. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * Sets a left padding of 300px, and a top padding of 50px + * ```ts + * map.setPadding({ left: 300, top: 50 }); + * ``` + */ + setPadding(padding: PaddingOptions, eventData?: any): this; + /** + * Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction + * that is "up"; for example, a bearing of 90° orients the map so that east is up. + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param bearing - The desired bearing. + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + rotateTo(bearing: number, options?: AnimationOptions, eventData?: any): this; + /** + * Rotates the map so that north is up (0° bearing), with an animated transition. + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + resetNorth(options?: AnimationOptions, eventData?: any): this; + /** + * Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + resetNorthPitch(options?: AnimationOptions, eventData?: any): this; + /** + * Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the + * `bearingSnap` threshold). + * + * Triggers the following events: `movestart`, `moveend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + snapToNorth(options?: AnimationOptions, eventData?: any): this; + /** + * Returns the map's current pitch (tilt). + * + * @returns The map's current pitch, measured in degrees away from the plane of the screen. + */ + getPitch(): number; + /** + * Sets the map's pitch (tilt). Equivalent to `jumpTo({pitch: pitch})`. + * + * Triggers the following events: `movestart`, `moveend`, `pitchstart`, and `pitchend`. + * + * @param pitch - The pitch to set, measured in degrees away from the plane of the screen (0-60). + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + */ + setPitch(pitch: number, eventData?: any): this; + /** + * @param bounds - Calculate the center for these bounds in the viewport and use + * the highest zoom level up to and including `Map#getMaxZoom()` that fits + * in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0. + * Bounds will be taken in [sw, ne] order. Southwest point will always be to the left of the northeast point. + * @param options - Options object + * @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`. + * If map is unable to fit, method will warn and return undefined. + * @example + * ```ts + * let bbox = [[-79, 43], [-73, 45]]; + * let newCameraTransform = map.cameraForBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + */ + cameraForBounds(bounds: LngLatBoundsLike, options?: CameraForBoundsOptions): CenterZoomBearing | undefined; + /** + * @internal + * Calculate the center of these two points in the viewport and use + * the highest zoom level up to and including `Map#getMaxZoom()` that fits + * the points in the viewport at the specified bearing. + * @param p0 - First point + * @param p1 - Second point + * @param bearing - Desired map bearing at end of animation, in degrees + * @param options - the camera options + * @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`. + * If map is unable to fit, method will warn and return undefined. + * @example + * ```ts + * let p0 = [-79, 43]; + * let p1 = [-73, 45]; + * let bearing = 90; + * let newCameraTransform = map._cameraForBoxAndBearing(p0, p1, bearing, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + */ + _cameraForBoxAndBearing(p0: LngLatLike, p1: LngLatLike, bearing: number, options?: CameraForBoundsOptions): CenterZoomBearing | undefined; + /** + * Pans and zooms the map to contain its visible area within the specified geographical bounds. + * This function will also reset the map's bearing to 0 if bearing is nonzero. + * + * Triggers the following events: `movestart` and `moveend`. + * + * @param bounds - Center these bounds in the viewport and use the highest + * zoom level up to and including `Map#getMaxZoom()` that fits them in the viewport. + * Bounds will be taken in [sw, ne] order. Southwest point will always be to the left of the northeast point. + * @param options - Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * let bbox = [[-79, 43], [-73, 45]]; + * map.fitBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + * @see [Fit a map to a bounding box](https://maplibre.org/maplibre-gl-js/docs/examples/fitbounds/) + */ + fitBounds(bounds: LngLatBoundsLike, options?: FitBoundsOptions, eventData?: any): this; + /** + * Pans, rotates and zooms the map to to fit the box made by points p0 and p1 + * once the map is rotated to the specified bearing. To zoom without rotating, + * pass in the current map bearing. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend` and `rotate`. + * + * @param p0 - First point on screen, in pixel coordinates + * @param p1 - Second point on screen, in pixel coordinates + * @param bearing - Desired map bearing at end of animation, in degrees + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * let p0 = [220, 400]; + * let p1 = [500, 900]; + * map.fitScreenCoordinates(p0, p1, map.getBearing(), { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * ``` + * @see Used by {@link BoxZoomHandler} + */ + fitScreenCoordinates(p0: PointLike, p1: PointLike, bearing: number, options?: FitBoundsOptions, eventData?: any): this; + _fitInternal(calculatedOptions?: CenterZoomBearing, options?: FitBoundsOptions, eventData?: any): this; + /** + * Changes any combination of center, zoom, bearing, and pitch, without + * an animated transition. The map will retain its current values for any + * details not specified in `options`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`, + * `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options object + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * // jump to coordinates at current zoom + * map.jumpTo({center: [0, 0]}); + * // jump with zoom, pitch, and bearing options + * map.jumpTo({ + * center: [0, 0], + * zoom: 8, + * pitch: 45, + * bearing: 90 + * }); + * ``` + * @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js/docs/examples/jump-to/) + * @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/live-update-feature/) + */ + jumpTo(options: JumpToOptions, eventData?: any): this; + /** + * Calculates pitch, zoom and bearing for looking at `newCenter` with the camera position being `newCenter` + * and returns them as {@link CameraOptions}. + * @param from - The camera to look from + * @param altitudeFrom - The altitude of the camera to look from + * @param to - The center to look at + * @param altitudeTo - Optional altitude of the center to look at. If none given the ground height will be used. + * @returns the calculated camera options + */ + calculateCameraOptionsFromTo(from: LngLat, altitudeFrom: number, to: LngLat, altitudeTo?: number): CameraOptions; + /** + * Changes any combination of `center`, `zoom`, `bearing`, `pitch`, and `padding` with an animated transition + * between old and new values. The map will retain its current values for any + * details not specified in `options`. + * + * Note: The transition will happen instantly if the user has enabled + * the `reduced motion` accessibility feature enabled in their operating system, + * unless `options` includes `essential: true`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`, + * `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options describing the destination and animation of the transition. + * Accepts {@link CameraOptions} and {@link AnimationOptions}. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/) + */ + easeTo(options: EaseToOptions & { + easeId?: string; + noMoveStart?: boolean; + }, eventData?: any): this; + _prepareEase(eventData: any, noMoveStart: boolean, currently?: any): void; + _prepareElevation(center: LngLat): void; + _updateElevation(k: number): void; + _finalizeElevation(): void; + /** + * @internal + * Called when the camera is about to be manipulated. + * If `transformCameraUpdate` is specified or terrain is enabled, a copy of + * the current transform is created to track the accumulated changes. + * This underlying transform represents the "desired state" proposed by input handlers / animations / UI controls. + * It may differ from the state used for rendering (`this.transform`). + * @returns Transform to apply changes to + */ + _getTransformForUpdate(): Transform; + /** + * @internal + * Checks the given transform for the camera being below terrain surface and + * returns new pitch and zoom to fix that. + * + * With the new pitch and zoom, the camera will be at the same ground + * position but at higher altitude. It will still point to the same spot on + * the map. + * + * @param tr - The transform to check. + */ + _elevateCameraIfInsideTerrain(tr: Transform): { + pitch?: number; + zoom?: number; + }; + /** + * @internal + * Called after the camera is done being manipulated. + * @param tr - the requested camera end state + * If the camera is inside terrain, it gets elevated. + * Call `transformCameraUpdate` if present, and then apply the "approved" changes. + */ + _applyUpdatedTransform(tr: Transform): void; + _fireMoveEvents(eventData?: any): void; + _afterEase(eventData?: any, easeId?: string): void; + /** + * Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that + * evokes flight. The animation seamlessly incorporates zooming and panning to help + * the user maintain her bearings even after traversing a great distance. + * + * Note: The animation will be skipped, and this will behave equivalently to `jumpTo` + * if the user has the `reduced motion` accessibility feature enabled in their operating system, + * unless 'options' includes `essential: true`. + * + * Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`, + * `pitch`, `pitchend`, and `rotate`. + * + * @param options - Options describing the destination and animation of the transition. + * Accepts {@link CameraOptions}, {@link AnimationOptions}, + * and the following additional options. + * @param eventData - Additional properties to be added to event objects of events triggered by this method. + * @example + * ```ts + * // fly with default options to null island + * map.flyTo({center: [0, 0], zoom: 9}); + * // using flyTo options + * map.flyTo({ + * center: [0, 0], + * zoom: 9, + * speed: 0.2, + * curve: 1, + * easing(t) { + * return t; + * } + * }); + * ``` + * @see [Fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/flyto/) + * @see [Slowly fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/flyto-options/) + * @see [Fly to a location based on scroll position](https://maplibre.org/maplibre-gl-js/docs/examples/scroll-fly-to/) + */ + flyTo(options: FlyToOptions, eventData?: any): this; + isEasing(): boolean; + /** + * Stops any animated transition underway. + */ + stop(): this; + _stop(allowGestures?: boolean, easeId?: string): this; + _ease(frame: (_: number) => void, finish: () => void, options: { + animate?: boolean; + duration?: number; + easing?: (_: number) => number; + }): void; + _renderFrameCallback: () => void; + _normalizeBearing(bearing: number, currentBearing: number): number; + _normalizeCenter(center: LngLat, tr: Transform): void; + /** + * Get the elevation difference between a given point + * and a point that is currently in the middle of the screen. + * This method should be used for proper positioning of custom 3d objects, as explained [here](https://maplibre.org/maplibre-gl-js/docs/examples/add-3d-model-with-terrain/) + * Returns null if terrain is not enabled. + * This method is subject to change in Maplibre GL JS v5. + * @param lngLatLike - [x,y] or LngLat coordinates of the location + * @returns elevation offset in meters + */ + queryTerrainElevation(lngLatLike: LngLatLike): number | null; +} +/** + * A position defintion for the control to be placed, can be in one of the corners of the map. + * When two or more controls are places in the same location they are stacked toward the center of the map. + */ +export type ControlPosition = "top-left" | "top-right" | "bottom-left" | "bottom-right"; +/** + * Interface for interactive controls added to the map. This is a + * specification for implementers to model: it is not + * an exported method or class. + * + * Controls must implement `onAdd` and `onRemove`, and must own an + * element, which is often a `div` element. To use MapLibre GL JS's + * default control styling, add the `maplibregl-ctrl` class to your control's + * node. + * + * @example + * ```ts + * class HelloWorldControl: IControl { + * onAdd(map) { + * this._map = map; + * this._container = document.createElement('div'); + * this._container.className = 'maplibregl-ctrl'; + * this._container.textContent = 'Hello, world'; + * return this._container; + * } + * + * onRemove() { + * this._container.parentNode.removeChild(this._container); + * this._map = undefined; + * } + * } + * ``` + */ +export interface IControl { + /** + * Register a control on the map and give it a chance to register event listeners + * and resources. This method is called by {@link Map#addControl} + * internally. + * + * @param map - the Map this control will be added to + * @returns The control's container element. This should + * be created by the control and returned by onAdd without being attached + * to the DOM: the map will insert the control's element into the DOM + * as necessary. + */ + onAdd(map: Map$1): HTMLElement; + /** + * Unregister a control on the map and give it a chance to detach event listeners + * and resources. This method is called by {@link Map#removeControl} + * internally. + * + * @param map - the Map this control will be removed from + */ + onRemove(map: Map$1): void; + /** + * Optionally provide a default position for this control. If this method + * is implemented and {@link Map#addControl} is called without the `position` + * parameter, the value returned by getDefaultPosition will be used as the + * control's position. + * + * @returns a control position, one of the values valid in addControl. + */ + readonly getDefaultPosition?: () => ControlPosition; +} +/** + * An event from the mouse relevant to a specific layer. + * + * @group Event Related + */ +export type MapLayerMouseEvent = MapMouseEvent & { + features?: MapGeoJSONFeature[]; +}; +/** + * An event from a touch device relevant to a specific layer. + * + * @group Event Related + */ +export type MapLayerTouchEvent = MapTouchEvent & { + features?: MapGeoJSONFeature[]; +}; +/** + * The source event data type + */ +export type MapSourceDataType = "content" | "metadata" | "visibility" | "idle"; +/** + * `MapLayerEventType` - a mapping between the event name and the event. + * **Note:** These events are compatible with the optional `layerId` parameter. + * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the + * event action contains a visible portion of the specified layer. + * The following example can be used for all the events. + * + * @group Event Related + * @example + * ```ts + * // Initialize the map + * let map = new Map({ // map options }); + * // Set an event listener for a specific layer + * map.on('the-event-name', 'poi-label', (e) => { + * console.log('An event has occurred on a visible portion of the poi-label layer'); + * }); + * ``` + */ +export type MapLayerEventType = { + /** + * Fired when a pointing device (usually a mouse) is pressed and released contains a visible portion of the specified layer. + * + * @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure/) + * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-on-symbol/) + */ + click: MapLayerMouseEvent; + /** + * Fired when a pointing device (usually a mouse) is pressed and released twice contains a visible portion of the specified layer. + * + * **Note:** Under normal conditions, this event will be preceded by two `click` events. + */ + dblclick: MapLayerMouseEvent; + /** + * Fired when a pointing device (usually a mouse) is pressed while inside a visible portion of the specified layer. + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + mousedown: MapLayerMouseEvent; + /** + * Fired when a pointing device (usually a mouse) is released while inside a visible portion of the specified layer. + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + mouseup: MapLayerMouseEvent; + /** + * Fired when a pointing device (usually a mouse) is moved while the cursor is inside a visible portion of the specified layer. + * As you move the cursor across the layer, the event will fire every time the cursor changes position within that layer. + * + * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/) + * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/) + * @see [Display a popup on over](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + */ + mousemove: MapLayerMouseEvent; + /** + * Fired when a pointing device (usually a mouse) enters a visible portion of a specified layer from + * outside that layer or outside the map canvas. + * + * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-on-symbol/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + */ + mouseenter: MapLayerMouseEvent; + /** + * Fired when a pointing device (usually a mouse) leaves a visible portion of a specified layer, or leaves + * the map canvas. + * + * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + */ + mouseleave: MapLayerMouseEvent; + /** + * Fired when a pointing device (usually a mouse) is moved inside a visible portion of the specified layer. + * + * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/) + * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + */ + mouseover: MapLayerMouseEvent; + /** + * Fired when a point device (usually a mouse) leaves the visible portion of the specified layer. + */ + mouseout: MapLayerMouseEvent; + /** + * Fired when the right button of the mouse is clicked or the context menu key is pressed within visible portion of the specified layer. + */ + contextmenu: MapLayerMouseEvent; + /** + * Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the visible portion of the specified layer. + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + touchstart: MapLayerTouchEvent; + /** + * Fired when a [`touchend`](https://developer.mozilla.org/en-US/docs/Web/Events/touchend) event occurs within the visible portion of the specified layer. + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + touchend: MapLayerTouchEvent; + /** + * Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the visible portion of the specified layer. + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + touchcancel: MapLayerTouchEvent; +}; +/** + * `MapEventType` - a mapping between the event name and the event value. + * These events are used with the {@link Map#on} method. + * When using a `layerId` with {@link Map#on} method, please refer to {@link MapLayerEventType}. + * The following example can be used for all the events. + * + * @group Event Related + * @example + * ```ts + * // Initialize the map + * let map = new Map({ // map options }); + * // Set an event listener + * map.on('the-event-name', () => { + * console.log('An event has occurred!'); + * }); + * ``` + */ +export type MapEventType = { + /** + * Fired when an error occurs. This is GL JS's primary error reporting + * mechanism. We use an event instead of `throw` to better accommodate + * asynchronous operations. If no listeners are bound to the `error` event, the + * error will be printed to the console. + */ + error: ErrorEvent; + /** + * Fired immediately after all necessary resources have been downloaded + * and the first visually complete rendering of the map has occurred. + * + * @see [Draw GeoJSON points](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-markers/) + * @see [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/live-geojson/) + * @see [Animate a point](https://maplibre.org/maplibre-gl-js/docs/examples/animate-point-along-line/) + */ + load: MapLibreEvent; + /** + * Fired after the last frame rendered before the map enters an + * "idle" state: + * + * - No camera transitions are in progress + * - All currently requested tiles have loaded + * - All fade/transition animations have completed + */ + idle: MapLibreEvent; + /** + * Fired immediately after the map has been removed with {@link Map#remove}. + */ + remove: MapLibreEvent; + /** + * Fired whenever the map is drawn to the screen, as the result of + * + * - a change to the map's position, zoom, pitch, or bearing + * - a change to the map's style + * - a change to a GeoJSON source + * - the loading of a vector tile, GeoJSON file, glyph, or sprite + */ + render: MapLibreEvent; + /** + * Fired immediately after the map has been resized. + */ + resize: MapLibreEvent; + /** + * Fired when the WebGL context is lost. + */ + webglcontextlost: MapContextEvent; + /** + * Fired when the WebGL context is restored. + */ + webglcontextrestored: MapContextEvent; + /** + * Fired when any map data (style, source, tile, etc) begins loading or + * changing asynchronously. All `dataloading` events are followed by a `data`, + * `dataabort` or `error` event. + */ + dataloading: MapDataEvent; + /** + * Fired when any map data loads or changes. See {@link MapDataEvent} for more information. + * @see [Display HTML clusters with custom properties](https://maplibre.org/maplibre-gl-js/docs/examples/cluster-html/) + */ + data: MapDataEvent; + tiledataloading: MapDataEvent; + /** + * Fired when one of the map's sources begins loading or changing asynchronously. + * All `sourcedataloading` events are followed by a `sourcedata`, `sourcedataabort` or `error` event. + */ + sourcedataloading: MapSourceDataEvent; + /** + * Fired when the map's style begins loading or changing asynchronously. + * All `styledataloading` events are followed by a `styledata` + * or `error` event. + */ + styledataloading: MapStyleDataEvent; + /** + * Fired when one of the map's sources loads or changes, including if a tile belonging + * to a source loads or changes. + */ + sourcedata: MapSourceDataEvent; + /** + * Fired when the map's style loads or changes. + */ + styledata: MapStyleDataEvent; + /** + * Fired when an icon or pattern needed by the style is missing. The missing image can + * be added with {@link Map#addImage} within this event listener callback to prevent the image from + * being skipped. This event can be used to dynamically generate icons and patterns. + * @see [Generate and add a missing icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-missing-generated/) + */ + styleimagemissing: MapStyleImageMissingEvent; + /** + * Fired when a request for one of the map's sources' tiles or data is aborted. + */ + dataabort: MapDataEvent; + /** + * Fired when a request for one of the map's sources' data is aborted. + */ + sourcedataabort: MapSourceDataEvent; + /** + * Fired when the user cancels a "box zoom" interaction, or when the bounding box does not meet the minimum size threshold. + * See {@link BoxZoomHandler}. + */ + boxzoomcancel: MapLibreZoomEvent; + /** + * Fired when a "box zoom" interaction starts. See {@link BoxZoomHandler}. + */ + boxzoomstart: MapLibreZoomEvent; + /** + * Fired when a "box zoom" interaction ends. See {@link BoxZoomHandler}. + */ + boxzoomend: MapLibreZoomEvent; + /** + * Fired when a [`touchcancel`](https://developer.mozilla.org/en-US/docs/Web/Events/touchcancel) event occurs within the map. + */ + touchcancel: MapTouchEvent; + /** + * Fired when a [`touchmove`](https://developer.mozilla.org/en-US/docs/Web/Events/touchmove) event occurs within the map. + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + touchmove: MapTouchEvent; + /** + * Fired when a [`touchend`](https://developer.mozilla.org/en-US/docs/Web/Events/touchend) event occurs within the map. + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + touchend: MapTouchEvent; + /** + * Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the map. + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + touchstart: MapTouchEvent; + /** + * Fired when a pointing device (usually a mouse) is pressed and released at the same point on the map. + * + * @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure/) + * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-on-symbol/) + */ + click: MapMouseEvent; + /** + * Fired when the right button of the mouse is clicked or the context menu key is pressed within the map. + */ + contextmenu: MapMouseEvent; + /** + * Fired when a pointing device (usually a mouse) is pressed and released twice at the same point on the map in rapid succession. + * + * **Note:** Under normal conditions, this event will be preceded by two `click` events. + */ + dblclick: MapMouseEvent; + /** + * Fired when a pointing device (usually a mouse) is moved while the cursor is inside the map. + * As you move the cursor across the map, the event will fire every time the cursor changes position within the map. + * + * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/) + * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/) + * @see [Display a popup on over](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + */ + mousemove: MapMouseEvent; + /** + * Fired when a pointing device (usually a mouse) is released within the map. + * + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + mouseup: MapMouseEvent; + /** + * Fired when a pointing device (usually a mouse) is pressed within the map. + * + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + mousedown: MapMouseEvent; + /** + * Fired when a point device (usually a mouse) leaves the map's canvas. + */ + mouseout: MapMouseEvent; + /** + * Fired when a pointing device (usually a mouse) is moved within the map. + * As you move the cursor across a web page containing a map, + * the event will fire each time it enters the map or any child elements. + * + * @see [Get coordinates of the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/mouse-position/) + * @see [Highlight features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + */ + mouseover: MapMouseEvent; + /** + * Fired just before the map begins a transition from one + * view to another, as the result of either user interaction or methods such as {@link Map#jumpTo}. + * + */ + movestart: MapLibreEvent; + /** + * Fired repeatedly during an animated transition from one view to + * another, as the result of either user interaction or methods such as {@link Map#flyTo}. + * + * @see [Display HTML clusters with custom properties](https://maplibre.org/maplibre-gl-js/docs/examples/cluster-html/) + */ + move: MapLibreEvent; + /** + * Fired just after the map completes a transition from one + * view to another, as the result of either user interaction or methods such as {@link Map#jumpTo}. + * + * @see [Display HTML clusters with custom properties](https://maplibre.org/maplibre-gl-js/docs/examples/cluster-html/) + */ + moveend: MapLibreEvent; + /** + * Fired just before the map begins a transition from one zoom level to another, + * as the result of either user interaction or methods such as {@link Map#flyTo}. + */ + zoomstart: MapLibreEvent; + /** + * Fired repeatedly during an animated transition from one zoom level to another, + * as the result of either user interaction or methods such as {@link Map#flyTo}. + */ + zoom: MapLibreEvent; + /** + * Fired just after the map completes a transition from one zoom level to another, + * as the result of either user interaction or methods such as {@link Map#flyTo}. + */ + zoomend: MapLibreEvent; + /** + * Fired when a "drag to rotate" interaction starts. See {@link DragRotateHandler}. + */ + rotatestart: MapLibreEvent; + /** + * Fired repeatedly during a "drag to rotate" interaction. See {@link DragRotateHandler}. + */ + rotate: MapLibreEvent; + /** + * Fired when a "drag to rotate" interaction ends. See {@link DragRotateHandler}. + */ + rotateend: MapLibreEvent; + /** + * Fired when a "drag to pan" interaction starts. See {@link DragPanHandler}. + */ + dragstart: MapLibreEvent; + /** + * Fired repeatedly during a "drag to pan" interaction. See {@link DragPanHandler}. + */ + drag: MapLibreEvent; + /** + * Fired when a "drag to pan" interaction ends. See {@link DragPanHandler}. + * @see [Create a draggable marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/) + */ + dragend: MapLibreEvent; + /** + * Fired whenever the map's pitch (tilt) begins a change as + * the result of either user interaction or methods such as {@link Map#flyTo} . + */ + pitchstart: MapLibreEvent; + /** + * Fired repeatedly during the map's pitch (tilt) animation between + * one state and another as the result of either user interaction + * or methods such as {@link Map#flyTo}. + */ + pitch: MapLibreEvent; + /** + * Fired immediately after the map's pitch (tilt) finishes changing as + * the result of either user interaction or methods such as {@link Map#flyTo}. + */ + pitchend: MapLibreEvent; + /** + * Fired when a [`wheel`](https://developer.mozilla.org/en-US/docs/Web/Events/wheel) event occurs within the map. + */ + wheel: MapWheelEvent; + /** + * Fired when terrain is changed + */ + terrain: MapTerrainEvent; + /** + * Fired whenever the cooperativeGestures option prevents a gesture from being handled by the map. + * This is useful for showing your own UI when this happens. + */ + cooperativegestureprevented: MapLibreEvent & { + gestureType: "wheel_zoom" | "touch_pan"; + }; +}; +/** + * The base event for MapLibre + * + * @group Event Related + */ +export type MapLibreEvent = { + type: keyof MapEventType | keyof MapLayerEventType; + target: Map$1; + originalEvent: TOrig; +}; +/** + * The style data event + * + * @group Event Related + */ +export type MapStyleDataEvent = MapLibreEvent & { + dataType: "style"; +}; +/** + * The source data event interface + * + * @group Event Related + */ +export type MapSourceDataEvent = MapLibreEvent & { + dataType: "source"; + /** + * True if the event has a `dataType` of `source` and the source has no outstanding network requests. + */ + isSourceLoaded: boolean; + /** + * The [style spec representation of the source](https://maplibre.org/maplibre-style-spec/#sources) if the event has a `dataType` of `source`. + */ + source: SourceSpecification; + sourceId: string; + sourceDataType: MapSourceDataType; + /** + * The tile being loaded or changed, if the event has a `dataType` of `source` and + * the event is related to loading of a tile. + */ + tile: any; +}; +/** + * `MapMouseEvent` is the event type for mouse-related map events. + * + * @group Event Related + * + * @example + * ```ts + * // The `click` event is an example of a `MapMouseEvent`. + * // Set up an event listener on the map. + * map.on('click', (e) => { + * // The event object (e) contains information like the + * // coordinates of the point on the map that was clicked. + * console.log('A click event has occurred at ' + e.lngLat); + * }); + * ``` + */ +export declare class MapMouseEvent extends Event$1 implements MapLibreEvent { + /** + * The event type + */ + type: "mousedown" | "mouseup" | "click" | "dblclick" | "mousemove" | "mouseover" | "mouseenter" | "mouseleave" | "mouseout" | "contextmenu"; + /** + * The `Map` object that fired the event. + */ + target: Map$1; + /** + * The DOM event which caused the map event. + */ + originalEvent: MouseEvent; + /** + * The pixel coordinates of the mouse cursor, relative to the map and measured from the top left corner. + */ + point: Point; + /** + * The geographic location on the map of the mouse cursor. + */ + lngLat: LngLat; + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the following default map behaviors: + * + * * On `mousedown` events, the behavior of {@link DragPanHandler} + * * On `mousedown` events, the behavior of {@link DragRotateHandler} + * * On `mousedown` events, the behavior of {@link BoxZoomHandler} + * * On `dblclick` events, the behavior of {@link DoubleClickZoomHandler} + * + */ + preventDefault(): void; + /** + * `true` if `preventDefault` has been called. + */ + get defaultPrevented(): boolean; + _defaultPrevented: boolean; + constructor(type: string, map: Map$1, originalEvent: MouseEvent, data?: any); +} +/** + * `MapTouchEvent` is the event type for touch-related map events. + * + * @group Event Related + */ +export declare class MapTouchEvent extends Event$1 implements MapLibreEvent { + /** + * The event type. + */ + type: "touchstart" | "touchmove" | "touchend" | "touchcancel"; + /** + * The `Map` object that fired the event. + */ + target: Map$1; + /** + * The DOM event which caused the map event. + */ + originalEvent: TouchEvent; + /** + * The geographic location on the map of the center of the touch event points. + */ + lngLat: LngLat; + /** + * The pixel coordinates of the center of the touch event points, relative to the map and measured from the top left + * corner. + */ + point: Point; + /** + * The array of pixel coordinates corresponding to a + * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property. + */ + points: Array; + /** + * The geographical locations on the map corresponding to a + * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property. + */ + lngLats: Array; + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the following default map behaviors: + * + * * On `touchstart` events, the behavior of {@link DragPanHandler} + * * On `touchstart` events, the behavior of {@link TwoFingersTouchZoomRotateHandler} + * + */ + preventDefault(): void; + /** + * `true` if `preventDefault` has been called. + */ + get defaultPrevented(): boolean; + _defaultPrevented: boolean; + constructor(type: string, map: Map$1, originalEvent: TouchEvent); +} +/** + * `MapWheelEvent` is the event type for the `wheel` map event. + * + * @group Event Related + */ +export declare class MapWheelEvent extends Event$1 { + /** + * The event type. + */ + type: "wheel"; + /** + * The `Map` object that fired the event. + */ + target: Map$1; + /** + * The DOM event which caused the map event. + */ + originalEvent: WheelEvent; + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the behavior of {@link ScrollZoomHandler}. + */ + preventDefault(): void; + /** + * `true` if `preventDefault` has been called. + */ + get defaultPrevented(): boolean; + _defaultPrevented: boolean; + /** */ + constructor(type: string, map: Map$1, originalEvent: WheelEvent); +} +/** + * A `MapLibreZoomEvent` is the event type for the boxzoom-related map events emitted by the {@link BoxZoomHandler}. + * + * @group Event Related + */ +export type MapLibreZoomEvent = { + /** + * The type of boxzoom event. One of `boxzoomstart`, `boxzoomend` or `boxzoomcancel` + */ + type: "boxzoomstart" | "boxzoomend" | "boxzoomcancel"; + /** + * The `Map` instance that triggered the event + */ + target: Map$1; + /** + * The DOM event that triggered the boxzoom event. Can be a `MouseEvent` or `KeyboardEvent` + */ + originalEvent: MouseEvent; +}; +/** + * A `MapDataEvent` object is emitted with the `data` + * and `dataloading` events. Possible values for + * `dataType`s are: + * + * - `'source'`: The non-tile data associated with any source + * - `'style'`: The [style](https://maplibre.org/maplibre-style-spec/) used by the map + * + * Possible values for `sourceDataType`s are: + * + * - `'metadata'`: indicates that any necessary source metadata has been loaded (such as TileJSON) and it is ok to start loading tiles + * - `'content'`: indicates the source data has changed (such as when source.setData() has been called on GeoJSONSource) + * - `'visibility'`: send when the source becomes used when at least one of its layers becomes visible in style sense (inside the layer's zoom range and with layout.visibility set to 'visible') + * - `'idle'`: indicates that no new source data has been fetched (but the source has done loading) + * + * @group Event Related + * + * @example + * ```ts + * // The sourcedata event is an example of MapDataEvent. + * // Set up an event listener on the map. + * map.on('sourcedata', (e) => { + * if (e.isSourceLoaded) { + * // Do something when the source has finished loading + * } + * }); + * ``` + */ +export type MapDataEvent = { + /** + * The event type. + */ + type: string; + /** + * The type of data that has changed. One of `'source'`, `'style'`. + */ + dataType: string; + /** + * Included if the event has a `dataType` of `source` and the event signals that internal data has been received or changed. Possible values are `metadata`, `content`, `visibility` and `idle`. + */ + sourceDataType: MapSourceDataType; +}; +/** + * The terrain event + * + * @group Event Related + */ +export type MapTerrainEvent = { + type: "terrain"; +}; +/** + * An event related to the web gl context + * + * @group Event Related + */ +export type MapContextEvent = { + type: "webglcontextlost" | "webglcontextrestored"; + originalEvent: WebGLContextEvent; +}; +/** + * The style image missing event + * + * @group Event Related + * + * @see [Generate and add a missing icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-missing-generated/) + */ +export type MapStyleImageMissingEvent = MapLibreEvent & { + type: "styleimagemissing"; + id: string; +}; +/** + * The {@link AttributionControl} options object + */ +export type AttributionControlOptions = { + /** + * If `true`, the attribution control will always collapse when moving the map. If `false`, + * force the expanded attribution control. The default is a responsive attribution that collapses when the user moves the map on maps 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 and when the automatic compact resizing for default settings are not sufficient.** + */ + compact?: boolean; + /** + * Attributions to show in addition to any other attributions. + */ + customAttribution?: string | Array; +}; +/** + * An `AttributionControl` control presents the map's attribution information. By default, the attribution control is expanded (regardless of map width). + * @group Markers and Controls + * @example + * ```ts + * let map = new Map({attributionControl: false}) + * .addControl(new AttributionControl({ + * compact: true + * })); + * ``` + */ +export declare class AttributionControl implements IControl { + options: AttributionControlOptions; + _map: Map$1; + _compact: boolean | undefined; + _container: HTMLElement; + _innerContainer: HTMLElement; + _compactButton: HTMLElement; + _editLink: HTMLAnchorElement; + _attribHTML: string; + styleId: string; + styleOwner: string; + /** + * @param options - the attribution options + */ + constructor(options?: AttributionControlOptions); + getDefaultPosition(): ControlPosition; + /** {@inheritDoc IControl.onAdd} */ + onAdd(map: Map$1): HTMLElement; + /** {@inheritDoc IControl.onRemove} */ + onRemove(): void; + _setElementTitle(element: HTMLElement, title: "ToggleAttribution" | "MapFeedback"): void; + _toggleAttribution: () => void; + _updateData: (e: MapDataEvent) => void; + _updateAttributions(): void; + _updateCompact: () => void; + _updateCompactMinimize: () => void; +} +declare const defaultLocale: { + "AttributionControl.ToggleAttribution": string; + "AttributionControl.MapFeedback": string; + "FullscreenControl.Enter": string; + "FullscreenControl.Exit": string; + "GeolocateControl.FindMyLocation": string; + "GeolocateControl.LocationNotAvailable": string; + "LogoControl.Title": string; + "Map.Title": string; + "Marker.Title": string; + "NavigationControl.ResetBearing": string; + "NavigationControl.ZoomIn": string; + "NavigationControl.ZoomOut": string; + "Popup.Close": string; + "ScaleControl.Feet": string; + "ScaleControl.Meters": string; + "ScaleControl.Kilometers": string; + "ScaleControl.Miles": string; + "ScaleControl.NauticalMiles": string; + "TerrainControl.Enable": string; + "TerrainControl.Disable": string; + "CooperativeGesturesHandler.WindowsHelpText": string; + "CooperativeGesturesHandler.MacHelpText": string; + "CooperativeGesturesHandler.MobileHelpText": string; +}; +declare class TransformProvider { + _map: Map$1; + constructor(map: Map$1); + get transform(): Transform; + get center(): { + lng: number; + lat: number; + }; + get zoom(): number; + get pitch(): number; + get bearing(): number; + unproject(point: PointLike): LngLat; +} +/** + * An options object sent to the enable function of some of the handlers + */ +export type AroundCenterOptions = { + /** + * If "center" is passed, map will zoom around the center of map + */ + around: "center"; +}; +declare abstract class TwoFingersTouchHandler implements Handler { + _enabled?: boolean; + _active?: boolean; + _firstTwoTouches?: [ + number, + number + ]; + _vector?: Point; + _startVector?: Point; + _aroundCenter?: boolean; + /** @internal */ + constructor(); + reset(): void; + abstract _start(points: [ + Point, + Point + ]): void; + abstract _move(points: [ + Point, + Point + ], pinchAround: Point | null, e: TouchEvent): HandlerResult | void; + touchstart(e: TouchEvent, points: Array, mapTouches: Array): void; + touchmove(e: TouchEvent, points: Array, mapTouches: Array): HandlerResult | void; + touchend(e: TouchEvent, points: Array, mapTouches: Array): void; + touchcancel(): void; + /** + * Enables the "drag to pitch" interaction. + * + * @example + * ```ts + * map.touchPitch.enable(); + * ``` + */ + enable(options?: AroundCenterOptions | boolean | null): void; + /** + * Disables the "drag to pitch" interaction. + * + * @example + * ```ts + * map.touchPitch.disable(); + * ``` + */ + disable(): void; + /** + * Returns a Boolean indicating whether the "drag to pitch" interaction is enabled. + * + * @returns `true` if the "drag to pitch" interaction is enabled. + */ + isEnabled(): boolean; + /** + * Returns a Boolean indicating whether the "drag to pitch" interaction is active, i.e. currently being used. + * + * @returns `true` if the "drag to pitch" interaction is active. + */ + isActive(): boolean; +} +/** + * The `TwoFingersTouchHandler`s allows the user to zoom the map two fingers + * + * @group Handlers + */ +export declare class TwoFingersTouchZoomHandler extends TwoFingersTouchHandler { + _distance?: number; + _startDistance?: number; + reset(): void; + _start(points: [ + Point, + Point + ]): void; + _move(points: [ + Point, + Point + ], pinchAround: Point | null): HandlerResult | void; +} +/** + * The `TwoFingersTouchHandler`s allows the user to rotate the map two fingers + * + * @group Handlers + */ +export declare class TwoFingersTouchRotateHandler extends TwoFingersTouchHandler { + _minDiameter?: number; + reset(): void; + _start(points: [ + Point, + Point + ]): void; + _move(points: [ + Point, + Point + ], pinchAround: Point | null, _e: TouchEvent): HandlerResult | void; + _isBelowThreshold(vector: Point): boolean; +} +/** + * The `TwoFingersTouchPitchHandler` allows the user to pitch the map by dragging up and down with two fingers. + * + * @group Handlers + */ +export declare class TwoFingersTouchPitchHandler extends TwoFingersTouchHandler { + _valid?: boolean; + _firstMove?: number; + _lastPoints?: [ + Point, + Point + ]; + _map: Map$1; + _currentTouchCount: number; + constructor(map: Map$1); + reset(): void; + touchstart(e: TouchEvent, points: Array, mapTouches: Array): void; + _start(points: [ + Point, + Point + ]): void; + _move(points: [ + Point, + Point + ], center: Point | null, e: TouchEvent): HandlerResult | void; + gestureBeginsVertically(vectorA: Point, vectorB: Point, timeStamp: number): boolean | undefined; +} +/** + * The `ScrollZoomHandler` allows the user to zoom the map by scrolling. + * + * @group Handlers + */ +export declare class ScrollZoomHandler implements Handler { + _map: Map$1; + _tr: TransformProvider; + _enabled: boolean; + _active: boolean; + _zooming: boolean; + _aroundCenter: boolean; + _around: LngLat; + _aroundPoint: Point; + _type: "wheel" | "trackpad" | null; + _lastValue: number; + _timeout: ReturnType; + _finishTimeout: ReturnType; + _lastWheelEvent: any; + _lastWheelEventTime: number; + _startZoom: number; + _targetZoom: number; + _delta: number; + _easing: ((a: number) => number); + _prevEase: { + start: number; + duration: number; + easing: (_: number) => number; + }; + _frameId: boolean; + _triggerRenderFrame: () => void; + _defaultZoomRate: number; + _wheelZoomRate: number; + /** @internal */ + constructor(map: Map$1, triggerRenderFrame: () => void); + /** + * Set the zoom rate of a trackpad + * @param zoomRate - 1/100 The rate used to scale trackpad movement to a zoom value. + * @example + * Speed up trackpad zoom + * ```ts + * map.scrollZoom.setZoomRate(1/25); + * ``` + */ + setZoomRate(zoomRate: number): void; + /** + * Set the zoom rate of a mouse wheel + * @param wheelZoomRate - 1/450 The rate used to scale mouse wheel movement to a zoom value. + * @example + * Slow down zoom of mouse wheel + * ```ts + * map.scrollZoom.setWheelZoomRate(1/600); + * ``` + */ + setWheelZoomRate(wheelZoomRate: number): void; + /** + * Returns a Boolean indicating whether the "scroll to zoom" interaction is enabled. + * @returns `true` if the "scroll to zoom" interaction is enabled. + */ + isEnabled(): boolean; + isActive(): boolean; + isZooming(): boolean; + /** + * Enables the "scroll to zoom" interaction. + * + * @param options - Options object. + * @example + * ```ts + * map.scrollZoom.enable(); + * map.scrollZoom.enable({ around: 'center' }) + * ``` + */ + enable(options?: AroundCenterOptions | boolean): void; + /** + * Disables the "scroll to zoom" interaction. + * + * @example + * ```ts + * map.scrollZoom.disable(); + * ``` + */ + disable(): void; + /** + * Determines whether or not the gesture is blocked due to cooperativeGestures. + */ + _shouldBePrevented(e: WheelEvent): boolean; + wheel(e: WheelEvent): void; + _onTimeout: (initialEvent: MouseEvent) => void; + _start(e: MouseEvent): void; + renderFrame(): { + noInertia: boolean; + needsRenderFrame: boolean; + zoomDelta: number; + around: Point; + originalEvent: any; + }; + _smoothOutEasing(duration: number): (t: number) => number; + reset(): void; +} +/** + * The `BoxZoomHandler` allows the user to zoom the map to fit within a bounding box. + * The bounding box is defined by clicking and holding `shift` while dragging the cursor. + * + * @group Handlers + */ +export declare class BoxZoomHandler implements Handler { + _map: Map$1; + _tr: TransformProvider; + _el: HTMLElement; + _container: HTMLElement; + _enabled: boolean; + _active: boolean; + _startPos: Point; + _lastPos: Point; + _box: HTMLElement; + _clickTolerance: number; + /** @internal */ + constructor(map: Map$1, options: { + clickTolerance: number; + }); + /** + * Returns a Boolean indicating whether the "box zoom" interaction is enabled. + * + * @returns `true` if the "box zoom" interaction is enabled. + */ + isEnabled(): boolean; + /** + * Returns a Boolean indicating whether the "box zoom" interaction is active, i.e. currently being used. + * + * @returns `true` if the "box zoom" interaction is active. + */ + isActive(): boolean; + /** + * Enables the "box zoom" interaction. + * + * @example + * ```ts + * map.boxZoom.enable(); + * ``` + */ + enable(): void; + /** + * Disables the "box zoom" interaction. + * + * @example + * ```ts + * map.boxZoom.disable(); + * ``` + */ + disable(): void; + mousedown(e: MouseEvent, point: Point): void; + mousemoveWindow(e: MouseEvent, point: Point): void; + mouseupWindow(e: MouseEvent, point: Point): { + cameraAnimation: (map: any) => any; + }; + keydown(e: KeyboardEvent): void; + reset(): void; + _fireEvent(type: string, e: any): Map$1; +} +/** + * Options object for `DragRotateHandler`. + */ +export type DragRotateHandlerOptions = { + /** + * Control the map pitch in addition to the bearing + * @defaultValue true + */ + pitchWithRotate: boolean; +}; +/** + * The `DragRotateHandler` allows the user to rotate the map by clicking and + * dragging the cursor while holding the right mouse button or `ctrl` key. + * + * @group Handlers + */ +export declare class DragRotateHandler { + _mouseRotate: MouseRotateHandler; + _mousePitch: MousePitchHandler; + _pitchWithRotate: boolean; + /** @internal */ + constructor(options: DragRotateHandlerOptions, mouseRotate: MouseRotateHandler, mousePitch: MousePitchHandler); + /** + * Enables the "drag to rotate" interaction. + * + * @example + * ```ts + * map.dragRotate.enable(); + * ``` + */ + enable(): void; + /** + * Disables the "drag to rotate" interaction. + * + * @example + * ```ts + * map.dragRotate.disable(); + * ``` + */ + disable(): void; + /** + * Returns a Boolean indicating whether the "drag to rotate" interaction is enabled. + * + * @returns `true` if the "drag to rotate" interaction is enabled. + */ + isEnabled(): boolean; + /** + * Returns a Boolean indicating whether the "drag to rotate" interaction is active, i.e. currently being used. + * + * @returns `true` if the "drag to rotate" interaction is active. + */ + isActive(): boolean; +} +/** + * The {@link CooperativeGesturesHandler} options object for the gesture settings + */ +export type GestureOptions = boolean; +/** + * A `CooperativeGestureHandler` is a control that adds cooperative gesture info when user tries to zoom in/out. + * + * When the CooperativeGestureHandler blocks a gesture, it will emit a `cooperativegestureprevented` event. + * + * @group Handlers + * + * @example + * ```ts + * const map = new Map({ + * cooperativeGestures: true + * }); + * ``` + * @see [Example: cooperative gestures](https://maplibre.org/maplibre-gl-js/docs/examples/cooperative-gestures/) + **/ +export declare class CooperativeGesturesHandler implements Handler { + _options: GestureOptions; + _map: Map$1; + _container: HTMLElement; + /** + * This is the key that will allow to bypass the cooperative gesture protection + */ + _bypassKey: "metaKey" | "ctrlKey"; + _enabled: boolean; + constructor(map: Map$1, options: GestureOptions); + isActive(): boolean; + reset(): void; + _setupUI(): void; + _destroyUI(): void; + enable(): void; + disable(): void; + isEnabled(): boolean; + isBypassed(event: MouseEvent | WheelEvent | PointerEvent): boolean; + notifyGestureBlocked(gestureType: "wheel_zoom" | "touch_pan", originalEvent: Event$1): void; +} +/** + * The `KeyboardHandler` allows the user to zoom, rotate, and pan the map using + * the following keyboard shortcuts: + * + * - `=` / `+`: Increase the zoom level by 1. + * - `Shift-=` / `Shift-+`: Increase the zoom level by 2. + * - `-`: Decrease the zoom level by 1. + * - `Shift--`: Decrease the zoom level by 2. + * - Arrow keys: Pan by 100 pixels. + * - `Shift+⇢`: Increase the rotation by 15 degrees. + * - `Shift+⇠`: Decrease the rotation by 15 degrees. + * - `Shift+⇡`: Increase the pitch by 10 degrees. + * - `Shift+⇣`: Decrease the pitch by 10 degrees. + * + * @group Handlers + */ +export declare class KeyboardHandler implements Handler { + _tr: TransformProvider; + _enabled: boolean; + _active: boolean; + _panStep: number; + _bearingStep: number; + _pitchStep: number; + _rotationDisabled: boolean; + /** @internal */ + constructor(map: Map$1); + reset(): void; + keydown(e: KeyboardEvent): { + cameraAnimation: (map: Map$1) => void; + }; + /** + * Enables the "keyboard rotate and zoom" interaction. + * + * @example + * ```ts + * map.keyboard.enable(); + * ``` + */ + enable(): void; + /** + * Disables the "keyboard rotate and zoom" interaction. + * + * @example + * ```ts + * map.keyboard.disable(); + * ``` + */ + disable(): void; + /** + * Returns a Boolean indicating whether the "keyboard rotate and zoom" + * interaction is enabled. + * + * @returns `true` if the "keyboard rotate and zoom" + * interaction is enabled. + */ + isEnabled(): boolean; + /** + * Returns true if the handler is enabled and has detected the start of a + * zoom/rotate gesture. + * + * @returns `true` if the handler is enabled and has detected the + * start of a zoom/rotate gesture. + */ + isActive(): boolean; + /** + * Disables the "keyboard pan/rotate" interaction, leaving the + * "keyboard zoom" interaction enabled. + * + * @example + * ```ts + * map.keyboard.disableRotation(); + * ``` + */ + disableRotation(): void; + /** + * Enables the "keyboard pan/rotate" interaction. + * + * @example + * ```ts + * map.keyboard.enable(); + * map.keyboard.enableRotation(); + * ``` + */ + enableRotation(): void; +} +declare class ClickZoomHandler implements Handler { + _tr: TransformProvider; + _enabled: boolean; + _active: boolean; + /** @internal */ + constructor(map: Map$1); + reset(): void; + dblclick(e: MouseEvent, point: Point): { + cameraAnimation: (map: Map$1) => void; + }; + enable(): void; + disable(): void; + isEnabled(): boolean; + isActive(): boolean; +} +declare class SingleTapRecognizer { + numTouches: number; + centroid: Point; + startTime: number; + aborted: boolean; + touches: { + [k in number | string]: Point; + }; + constructor(options: { + numTouches: number; + }); + reset(): void; + touchstart(e: TouchEvent, points: Array, mapTouches: Array): void; + touchmove(e: TouchEvent, points: Array, mapTouches: Array): void; + touchend(e: TouchEvent, points: Array, mapTouches: Array): Point; +} +declare class TapRecognizer { + singleTap: SingleTapRecognizer; + numTaps: number; + lastTime: number; + lastTap: Point; + count: number; + constructor(options: { + numTaps: number; + numTouches: number; + }); + reset(): void; + touchstart(e: TouchEvent, points: Array, mapTouches: Array): void; + touchmove(e: TouchEvent, points: Array, mapTouches: Array): void; + touchend(e: TouchEvent, points: Array, mapTouches: Array): Point; +} +declare class TapZoomHandler implements Handler { + _tr: TransformProvider; + _enabled: boolean; + _active: boolean; + _zoomIn: TapRecognizer; + _zoomOut: TapRecognizer; + constructor(map: Map$1); + reset(): void; + touchstart(e: TouchEvent, points: Array, mapTouches: Array): void; + touchmove(e: TouchEvent, points: Array, mapTouches: Array): void; + touchend(e: TouchEvent, points: Array, mapTouches: Array): { + cameraAnimation: (map: Map$1) => Map$1; + }; + touchcancel(): void; + enable(): void; + disable(): void; + isEnabled(): boolean; + isActive(): boolean; +} +/** + * The `DoubleClickZoomHandler` allows the user to zoom the map at a point by + * double clicking or double tapping. + * + * @group Handlers + */ +export declare class DoubleClickZoomHandler { + _clickZoom: ClickZoomHandler; + _tapZoom: TapZoomHandler; + /** @internal */ + constructor(clickZoom: ClickZoomHandler, TapZoom: TapZoomHandler); + /** + * Enables the "double click to zoom" interaction. + * + * @example + * ```ts + * map.doubleClickZoom.enable(); + * ``` + */ + enable(): void; + /** + * Disables the "double click to zoom" interaction. + * + * @example + * ```ts + * map.doubleClickZoom.disable(); + * ``` + */ + disable(): void; + /** + * Returns a Boolean indicating whether the "double click to zoom" interaction is enabled. + * + * @returns `true` if the "double click to zoom" interaction is enabled. + */ + isEnabled(): boolean; + /** + * Returns a Boolean indicating whether the "double click to zoom" interaction is active, i.e. currently being used. + * + * @returns `true` if the "double click to zoom" interaction is active. + */ + isActive(): boolean; +} +declare class TapDragZoomHandler implements Handler { + _enabled: boolean; + _active: boolean; + _swipePoint: Point; + _swipeTouch: number; + _tapTime: number; + _tapPoint: Point; + _tap: TapRecognizer; + constructor(); + reset(): void; + touchstart(e: TouchEvent, points: Array, mapTouches: Array): void; + touchmove(e: TouchEvent, points: Array, mapTouches: Array): { + zoomDelta: number; + }; + touchend(e: TouchEvent, points: Array, mapTouches: Array): void; + touchcancel(): void; + enable(): void; + disable(): void; + isEnabled(): boolean; + isActive(): boolean; +} +/** + * The `TwoFingersTouchZoomRotateHandler` allows the user to zoom and rotate the map by + * pinching on a touchscreen. + * + * They can zoom with one finger by double tapping and dragging. On the second tap, + * hold the finger down and drag up or down to zoom in or out. + * + * @group Handlers + */ +export declare class TwoFingersTouchZoomRotateHandler { + _el: HTMLElement; + _touchZoom: TwoFingersTouchZoomHandler; + _touchRotate: TwoFingersTouchRotateHandler; + _tapDragZoom: TapDragZoomHandler; + _rotationDisabled: boolean; + _enabled: boolean; + /** @internal */ + constructor(el: HTMLElement, touchZoom: TwoFingersTouchZoomHandler, touchRotate: TwoFingersTouchRotateHandler, tapDragZoom: TapDragZoomHandler); + /** + * Enables the "pinch to rotate and zoom" interaction. + * + * @param options - Options object. + * + * @example + * ```ts + * map.touchZoomRotate.enable(); + * map.touchZoomRotate.enable({ around: 'center' }); + * ``` + */ + enable(options?: AroundCenterOptions | boolean | null): void; + /** + * Disables the "pinch to rotate and zoom" interaction. + * + * @example + * ```ts + * map.touchZoomRotate.disable(); + * ``` + */ + disable(): void; + /** + * Returns a Boolean indicating whether the "pinch to rotate and zoom" interaction is enabled. + * + * @returns `true` if the "pinch to rotate and zoom" interaction is enabled. + */ + isEnabled(): boolean; + /** + * Returns true if the handler is enabled and has detected the start of a zoom/rotate gesture. + * + * @returns `true` if the handler is active, `false` otherwise + */ + isActive(): boolean; + /** + * Disables the "pinch to rotate" interaction, leaving the "pinch to zoom" + * interaction enabled. + * + * @example + * ```ts + * map.touchZoomRotate.disableRotation(); + * ``` + */ + disableRotation(): void; + /** + * Enables the "pinch to rotate" interaction. + * + * @example + * ```ts + * map.touchZoomRotate.enable(); + * map.touchZoomRotate.enableRotation(); + * ``` + */ + enableRotation(): void; +} +/** + * The {@link Map} options object. + */ +export type MapOptions = { + /** + * 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. + * For example, `http://path/to/my/page.html#2.59/39.26/53.07/-24.1/60`. + * An additional string may optionally be provided to indicate a parameter-styled hash, + * e.g. http://path/to/my/page.html#map=2.59/39.26/53.07/-24.1/60&foo=bar, where foo + * is a custom parameter and bar is an arbitrary hash distinct from the map hash. + * @defaultValue false + */ + hash?: boolean | string; + /** + * If `false`, no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction. + * @defaultValue true + */ + interactive?: boolean; + /** + * The HTML element in which MapLibre GL JS will render the map, or the element's string `id`. The specified element must have no children. + */ + container: HTMLElement | string; + /** + * The threshold, measured in degrees, that determines when the map's + * bearing will snap to north. For example, with a `bearingSnap` of 7, if the user rotates + * the map within 7 degrees of north, the map will automatically snap to exact north. + * @defaultValue 7 + */ + bearingSnap?: number; + /** + * If set, an {@link AttributionControl} will be added to the map with the provided options. + * To disable the attribution control, pass `false`. + * Note: showing the logo of MapLibre is not required for using MapLibre. + * @defaultValue compact: true, customAttribution: "MapLibre ...". + */ + attributionControl?: false | AttributionControlOptions; + /** + * If `true`, the MapLibre logo will be shown. + */ + maplibreLogo?: boolean; + /** + * A string representing the position of the MapLibre wordmark on the map. Valid options are `top-left`,`top-right`, `bottom-left`, or `bottom-right`. + * @defaultValue 'bottom-left' + */ + logoPosition?: ControlPosition; + /** + * If `true`, map creation will fail if the performance of MapLibre GL JS would be dramatically worse than expected + * (i.e. a software renderer would be used). + * @defaultValue false + */ + failIfMajorPerformanceCaveat?: boolean; + /** + * 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. + * @defaultValue false + */ + preserveDrawingBuffer?: boolean; + /** + * If `true`, the gl context will be created with MSAA antialiasing, which can be useful for antialiasing custom layers. + * Disabled by default as a performance optimization. + */ + antialias?: boolean; + /** + * If `false`, the map won't attempt to re-request tiles once they expire per their HTTP `cacheControl`/`expires` headers. + * @defaultValue true + */ + refreshExpiredTiles?: boolean; + /** + * If set, the map will be constrained to the given bounds. + */ + maxBounds?: LngLatBoundsLike; + /** + * If `true`, the "scroll to zoom" interaction is enabled. {@link AroundCenterOptions} are passed as options to {@link ScrollZoomHandler#enable}. + * @defaultValue true + */ + scrollZoom?: boolean | AroundCenterOptions; + /** + * The minimum zoom level of the map (0-24). + * @defaultValue 0 + */ + minZoom?: number | null; + /** + * The maximum zoom level of the map (0-24). + * @defaultValue 22 + */ + maxZoom?: number | null; + /** + * The minimum pitch of the map (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. + * @defaultValue 0 + */ + minPitch?: number | null; + /** + * The maximum pitch of the map (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. + * @defaultValue 60 + */ + maxPitch?: number | null; + /** + * If `true`, the "box zoom" interaction is enabled (see {@link BoxZoomHandler}). + * @defaultValue true + */ + boxZoom?: boolean; + /** + * If `true`, the "drag to rotate" interaction is enabled (see {@link DragRotateHandler}). + * @defaultValue true + */ + dragRotate?: boolean; + /** + * If `true`, the "drag to pan" interaction is enabled. An `Object` value is passed as options to {@link DragPanHandler#enable}. + * @defaultValue true + */ + dragPan?: boolean | DragPanOptions; + /** + * If `true`, keyboard shortcuts are enabled (see {@link KeyboardHandler}). + * @defaultValue true + */ + keyboard?: boolean; + /** + * If `true`, the "double click to zoom" interaction is enabled (see {@link DoubleClickZoomHandler}). + * @defaultValue true + */ + doubleClickZoom?: boolean; + /** + * If `true`, the "pinch to rotate and zoom" interaction is enabled. An `Object` value is passed as options to {@link TwoFingersTouchZoomRotateHandler#enable}. + * @defaultValue true + */ + touchZoomRotate?: boolean | AroundCenterOptions; + /** + * If `true`, the "drag to pitch" interaction is enabled. An `Object` value is passed as options to {@link TwoFingersTouchPitchHandler#enable}. + * @defaultValue true + */ + touchPitch?: boolean | AroundCenterOptions; + /** + * If `true` or set to an options object, the map is only accessible on desktop while holding Command/Ctrl and only accessible on mobile with two fingers. Interacting with the map using normal gestures will trigger an informational screen. With this option enabled, "drag to pitch" requires a three-finger gesture. Cooperative gestures are disabled when a map enters fullscreen using {@link FullscreenControl}. + * @defaultValue false + */ + cooperativeGestures?: GestureOptions; + /** + * If `true`, the map will automatically resize when the browser window resizes. + * @defaultValue true + */ + trackResize?: boolean; + /** + * The initial geographical centerpoint of the map. If `center` is not specified in the constructor options, MapLibre 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: MapLibre GL JS uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON. + * @defaultValue [0, 0] + */ + center?: LngLatLike; + /** + * The initial zoom level of the map. If `zoom` is not specified in the constructor options, MapLibre 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`. + * @defaultValue 0 + */ + zoom?: number; + /** + * The initial bearing (rotation) of the map, measured in degrees counter-clockwise from north. If `bearing` is not specified in the constructor options, MapLibre 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`. + * @defaultValue 0 + */ + bearing?: number; + /** + * 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, MapLibre 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`. Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. + * @defaultValue 0 + */ + pitch?: number; + /** + * If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`: + * + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * @defaultValue true + */ + renderWorldCopies?: boolean; + /** + * 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 which can be set using `maxTileCacheZoomLevels` constructor options. + * @defaultValue null + */ + maxTileCacheSize?: number | null; + /** + * The maximum number of zoom levels for which to store tiles for a given source. Tile cache dynamic size is calculated by multiplying `maxTileCacheZoomLevels` with the approximate number of tiles in the viewport for a given source. + * @defaultValue 5 + */ + maxTileCacheZoomLevels?: number; + /** + * 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. + * Expected to return an object with a `url` property and optionally `headers` and `credentials` properties. + * @defaultValue null + */ + transformRequest?: RequestTransformFunction | null; + /** + * A callback run before the map's camera is moved due to user input or animation. The callback can be used to modify the new center, zoom, pitch and bearing. + * Expected to return an object containing center, zoom, pitch or bearing values to overwrite. + * @defaultValue null + */ + transformCameraUpdate?: CameraUpdateTransformFunction | 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). + * @defaultValue null + */ + locale?: any; + /** + * Controls the duration of the fade-in/fade-out animation for label collisions after initial map load, in milliseconds. This setting affects all symbol layers. This setting does not affect the duration of runtime styling transitions or raster tile cross-fading. + * @defaultValue 300 + */ + fadeDuration?: number; + /** + * 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. + * @defaultValue true + */ + crossSourceCollisions?: boolean; + /** + * 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. + * @defaultValue false + */ + collectResourceTiming?: boolean; + /** + * 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). + * @defaultValue 3 + */ + clickTolerance?: number; + /** + * The initial bounds of the map. If `bounds` is specified, it overrides `center` and `zoom` constructor options. + */ + bounds?: LngLatBoundsLike; + /** + * A {@link FitBoundsOptions} options object to use _only_ when fitting the initial `bounds` provided above. + */ + fitBoundsOptions?: FitBoundsOptions; + /** + * Defines a CSS + * font-family for locally overriding generation of Chinese, Japanese, and Korean characters. + * For these characters, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold). + * Set to `false`, to enable font settings from the map's style for these glyph ranges. + * The purpose of this option is to avoid bandwidth-intensive glyph server requests. (See [Use locally generated ideographs](https://maplibre.org/maplibre-gl-js/docs/examples/local-ideographs).) + * @defaultValue 'sans-serif' + */ + localIdeographFontFamily?: string | false; + /** + * The map's MapLibre style. This must be a JSON object conforming to + * the schema described in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/), + * or a URL to such JSON. + * When the style is not specified, calling {@link Map#setStyle} is required to render the map. + */ + style?: StyleSpecification | string; + /** + * If `false`, the map's pitch (tilt) control with "drag to rotate" interaction will be disabled. + * @defaultValue true + */ + pitchWithRotate?: boolean; + /** + * The pixel ratio. + * The canvas' `width` attribute will be `container.clientWidth * pixelRatio` and its `height` attribute will be `container.clientHeight * pixelRatio`. Defaults to `devicePixelRatio` if not specified. + */ + pixelRatio?: number; + /** + * If false, style validation will be skipped. Useful in production environment. + * @defaultValue true + */ + validateStyle?: boolean; + /** + * The canvas' `width` and `height` max size. The values are passed as an array where the first element is max width and the second element is max height. + * You shouldn't set this above WebGl `MAX_TEXTURE_SIZE`. + * @defaultValue [4096, 4096]. + */ + maxCanvasSize?: [ + number, + number + ]; + /** + * Determines whether to cancel, or retain, tiles from the current viewport which are still loading but which belong to a farther (smaller) zoom level than the current one. + * * If `true`, when zooming in, tiles which didn't manage to load for previous zoom levels will become canceled. This might save some computing resources for slower devices, but the map details might appear more abruptly at the end of the zoom. + * * If `false`, when zooming in, the previous zoom level(s) tiles will progressively appear, giving a smoother map details experience. However, more tiles will be rendered in a short period of time. + * @defaultValue true + */ + cancelPendingTileRequestsWhileZooming?: boolean; +}; +export type CompleteMapOptions = Complete; +export type DelegatedListener = { + layers: string[]; + listener: Listener; + delegates: { + [E in keyof MapEventType]?: Delegate; + }; +}; +export type Delegate = (e: E) => void; +/** + * The `Map` object represents the map on your page. It exposes methods + * and properties that enable you to programmatically change the map, + * and fires events as users interact with it. + * + * You create a `Map` by specifying a `container` and other options, see {@link MapOptions} for the full list. + * Then MapLibre GL JS initializes the map on the page and returns your `Map` object. + * + * @group Main + * + * @example + * ```ts + * let map = new Map({ + * container: 'map', + * center: [-122.420679, 37.772537], + * zoom: 13, + * style: style_object, + * hash: true, + * transformRequest: (url, resourceType)=> { + * if(resourceType === 'Source' && url.startsWith('http://myHost')) { + * return { + * url: url.replace('http', 'https'), + * headers: { 'my-custom-header': true}, + * credentials: 'include' // Include cookies for cross-origin requests + * } + * } + * } + * }); + * ``` + * @see [Display a map](https://maplibre.org/maplibre-gl-js/docs/examples/simple-map/) + */ +declare class Map$1 extends Camera { + style: Style; + painter: Painter; + _container: HTMLElement; + _canvasContainer: HTMLElement; + _controlContainer: HTMLElement; + _controlPositions: Record; + _interactive: boolean; + _showTileBoundaries: boolean; + _showCollisionBoxes: boolean; + _showPadding: boolean; + _showOverdrawInspector: boolean; + _repaint: boolean; + _vertices: boolean; + _canvas: HTMLCanvasElement; + _maxTileCacheSize: number | null; + _maxTileCacheZoomLevels: number; + _frameRequest: AbortController; + _styleDirty: boolean; + _sourcesDirty: boolean; + _placementDirty: boolean; + _loaded: boolean; + _idleTriggered: boolean; + _fullyLoaded: boolean; + _trackResize: boolean; + _resizeObserver: ResizeObserver; + _preserveDrawingBuffer: boolean; + _failIfMajorPerformanceCaveat: boolean; + _antialias: boolean; + _refreshExpiredTiles: boolean; + _hash: Hash; + _delegatedListeners: Record; + _fadeDuration: number; + _crossSourceCollisions: boolean; + _crossFadingFactor: number; + _collectResourceTiming: boolean; + _renderTaskQueue: TaskQueue; + _controls: Array; + _mapId: number; + _localIdeographFontFamily: string | false; + _validateStyle: boolean; + _requestManager: RequestManager; + _locale: typeof defaultLocale; + _removed: boolean; + _clickTolerance: number; + _overridePixelRatio: number | null | undefined; + _maxCanvasSize: [ + number, + number + ]; + _terrainDataCallback: (e: MapStyleDataEvent | MapSourceDataEvent) => void; + /** + * @internal + * image queue throttling handle. To be used later when clean up + */ + _imageQueueHandle: number; + /** + * The map's {@link ScrollZoomHandler}, which implements zooming in and out with a scroll wheel or trackpad. + * Find more details and examples using `scrollZoom` in the {@link ScrollZoomHandler} section. + */ + scrollZoom: ScrollZoomHandler; + /** + * The map's {@link BoxZoomHandler}, which implements zooming using a drag gesture with the Shift key pressed. + * Find more details and examples using `boxZoom` in the {@link BoxZoomHandler} section. + */ + boxZoom: BoxZoomHandler; + /** + * The map's {@link DragRotateHandler}, which implements rotating the map while dragging with the right + * mouse button or with the Control key pressed. Find more details and examples using `dragRotate` + * in the {@link DragRotateHandler} section. + */ + dragRotate: DragRotateHandler; + /** + * The map's {@link DragPanHandler}, which implements dragging the map with a mouse or touch gesture. + * Find more details and examples using `dragPan` in the {@link DragPanHandler} section. + */ + dragPan: DragPanHandler; + /** + * The map's {@link KeyboardHandler}, which allows the user to zoom, rotate, and pan the map using keyboard + * shortcuts. Find more details and examples using `keyboard` in the {@link KeyboardHandler} section. + */ + keyboard: KeyboardHandler; + /** + * The map's {@link DoubleClickZoomHandler}, which allows the user to zoom by double clicking. + * Find more details and examples using `doubleClickZoom` in the {@link DoubleClickZoomHandler} section. + */ + doubleClickZoom: DoubleClickZoomHandler; + /** + * The map's {@link TwoFingersTouchZoomRotateHandler}, which allows the user to zoom or rotate the map with touch gestures. + * Find more details and examples using `touchZoomRotate` in the {@link TwoFingersTouchZoomRotateHandler} section. + */ + touchZoomRotate: TwoFingersTouchZoomRotateHandler; + /** + * The map's {@link TwoFingersTouchPitchHandler}, which allows the user to pitch the map with touch gestures. + * Find more details and examples using `touchPitch` in the {@link TwoFingersTouchPitchHandler} section. + */ + touchPitch: TwoFingersTouchPitchHandler; + /** + * The map's {@link CooperativeGesturesHandler}, which allows the user to see cooperative gesture info when user tries to zoom in/out. + * Find more details and examples using `cooperativeGestures` in the {@link CooperativeGesturesHandler} section. + */ + cooperativeGestures: CooperativeGesturesHandler; + /** + * The map's property which determines whether to cancel, or retain, tiles from the current viewport which are still loading but which belong to a farther (smaller) zoom level than the current one. + * * If `true`, when zooming in, tiles which didn't manage to load for previous zoom levels will become canceled. This might save some computing resources for slower devices, but the map details might appear more abruptly at the end of the zoom. + * * If `false`, when zooming in, the previous zoom level(s) tiles will progressively appear, giving a smoother map details experience. However, more tiles will be rendered in a short period of time. + * @defaultValue true + */ + cancelPendingTileRequestsWhileZooming: boolean; + constructor(options: MapOptions); + /** + * @internal + * Returns a unique number for this map instance which is used for the MapLoadEvent + * to make sure we only fire one event per instantiated map object. + * @returns the uniq map ID + */ + _getMapId(): number; + /** + * Adds an {@link IControl} to the map, calling `control.onAdd(this)`. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param control - The {@link IControl} to add. + * @param position - position on the map to which the control will be added. + * Valid values are `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. Defaults to `'top-right'`. + * @example + * Add zoom and rotation controls to the map. + * ```ts + * map.addControl(new NavigationControl()); + * ``` + * @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigation/) + */ + addControl(control: IControl, position?: ControlPosition): Map$1; + /** + * Removes the control from the map. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param control - The {@link IControl} to remove. + * @example + * ```ts + * // Define a new navigation control. + * let navigation = new NavigationControl(); + * // Add zoom and rotation controls to the map. + * map.addControl(navigation); + * // Remove zoom and rotation controls from the map. + * map.removeControl(navigation); + * ``` + */ + removeControl(control: IControl): Map$1; + /** + * Checks if a control exists on the map. + * + * @param control - The {@link IControl} to check. + * @returns true if map contains control. + * @example + * ```ts + * // Define a new navigation control. + * let navigation = new NavigationControl(); + * // Add zoom and rotation controls to the map. + * map.addControl(navigation); + * // Check that the navigation control exists on the map. + * map.hasControl(navigation); + * ``` + */ + hasControl(control: IControl): boolean; + calculateCameraOptionsFromTo(from: LngLat, altitudeFrom: number, to: LngLat, altitudeTo?: number): CameraOptions; + /** + * Resizes the map according to the dimensions of its + * `container` element. + * + * Checks if the map container size changed and updates the map if it has changed. + * This method must be called after the map's `container` is resized programmatically + * or when the map is shown after being initially hidden with CSS. + * + * Triggers the following events: `movestart`, `move`, `moveend`, and `resize`. + * + * @param eventData - Additional properties to be passed to `movestart`, `move`, `resize`, and `moveend` + * events that get triggered as a result of resize. This can be useful for differentiating the + * source of an event (for example, user-initiated or programmatically-triggered events). + * @example + * Resize the map when the map container is shown after being initially hidden with CSS. + * ```ts + * let mapDiv = document.getElementById('map'); + * if (mapDiv.style.visibility === true) map.resize(); + * ``` + */ + resize(eventData?: any): Map$1; + /** + * @internal + * Return the map's pixel ratio eventually scaled down to respect maxCanvasSize. + * Internally you should use this and not getPixelRatio(). + */ + _getClampedPixelRatio(width: number, height: number): number; + /** + * Returns the map's pixel ratio. + * Note that the pixel ratio actually applied may be lower to respect maxCanvasSize. + * @returns The pixel ratio. + */ + getPixelRatio(): number; + /** + * Sets the map's pixel ratio. This allows to override `devicePixelRatio`. + * After this call, the canvas' `width` attribute will be `container.clientWidth * pixelRatio` + * and its height attribute will be `container.clientHeight * pixelRatio`. + * Set this to null to disable `devicePixelRatio` override. + * Note that the pixel ratio actually applied may be lower to respect maxCanvasSize. + * @param pixelRatio - The pixel ratio. + */ + setPixelRatio(pixelRatio: number): void; + /** + * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not + * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region. + * @returns The geographical bounds of the map as {@link LngLatBounds}. + * @example + * ```ts + * let bounds = map.getBounds(); + * ``` + */ + getBounds(): LngLatBounds; + /** + * Returns the maximum geographical bounds the map is constrained to, or `null` if none set. + * @returns The map object. + * @example + * ```ts + * let maxBounds = map.getMaxBounds(); + * ``` + */ + getMaxBounds(): LngLatBounds | null; + /** + * Sets or clears the map's geographical bounds. + * + * Pan and zoom operations are constrained within these bounds. + * If a pan or zoom is performed that would + * display regions outside these bounds, the map will + * instead display a position and zoom level + * as close as possible to the operation's request while still + * remaining within the bounds. + * + * @param bounds - The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds. + * @example + * Define bounds that conform to the `LngLatBoundsLike` object as set the max bounds. + * ```ts + * let bounds = [ + * [-74.04728, 40.68392], // [west, south] + * [-73.91058, 40.87764] // [east, north] + * ]; + * map.setMaxBounds(bounds); + * ``` + */ + setMaxBounds(bounds?: LngLatBoundsLike | null): Map$1; + /** + * Sets or clears the map's minimum zoom level. + * If the map's current zoom level is lower than the new minimum, + * the map will zoom to the new minimum. + * + * It is not always possible to zoom out and reach the set `minZoom`. + * Other factors such as map height may restrict zooming. For example, + * if the map is 512px tall it will not be possible to zoom below zoom 0 + * no matter what the `minZoom` is set to. + * + * A {@link ErrorEvent} event will be fired if minZoom is out of bounds. + * + * @param minZoom - The minimum zoom level to set (-2 - 24). + * If `null` or `undefined` is provided, the function removes the current minimum zoom (i.e. sets it to -2). + * @example + * ```ts + * map.setMinZoom(12.25); + * ``` + */ + setMinZoom(minZoom?: number | null): Map$1; + /** + * Returns the map's minimum allowable zoom level. + * + * @returns minZoom + * @example + * ```ts + * let minZoom = map.getMinZoom(); + * ``` + */ + getMinZoom(): number; + /** + * Sets or clears the map's maximum zoom level. + * If the map's current zoom level is higher than the new maximum, + * the map will zoom to the new maximum. + * + * A {@link ErrorEvent} event will be fired if minZoom is out of bounds. + * + * @param maxZoom - The maximum zoom level to set. + * If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22). + * @example + * ```ts + * map.setMaxZoom(18.75); + * ``` + */ + setMaxZoom(maxZoom?: number | null): Map$1; + /** + * Returns the map's maximum allowable zoom level. + * + * @returns The maxZoom + * @example + * ```ts + * let maxZoom = map.getMaxZoom(); + * ``` + */ + getMaxZoom(): number; + /** + * Sets or clears the map's minimum pitch. + * If the map's current pitch is lower than the new minimum, + * the map will pitch to the new minimum. + * + * A {@link ErrorEvent} event will be fired if minPitch is out of bounds. + * + * @param minPitch - The minimum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. + * If `null` or `undefined` is provided, the function removes the current minimum pitch (i.e. sets it to 0). + */ + setMinPitch(minPitch?: number | null): Map$1; + /** + * Returns the map's minimum allowable pitch. + * + * @returns The minPitch + */ + getMinPitch(): number; + /** + * Sets or clears the map's maximum pitch. + * If the map's current pitch is higher than the new maximum, + * the map will pitch to the new maximum. + * + * A {@link ErrorEvent} event will be fired if maxPitch is out of bounds. + * + * @param maxPitch - The maximum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. + * If `null` or `undefined` is provided, the function removes the current maximum pitch (sets it to 60). + */ + setMaxPitch(maxPitch?: number | null): Map$1; + /** + * Returns the map's maximum allowable pitch. + * + * @returns The maxPitch + */ + getMaxPitch(): number; + /** + * 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`: + * + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * @returns The renderWorldCopies + * @example + * ```ts + * let worldCopiesRendered = map.getRenderWorldCopies(); + * ``` + * @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/) + */ + getRenderWorldCopies(): boolean; + /** + * Sets the state of `renderWorldCopies`. + * + * @param renderWorldCopies - If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`: + * + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * + * `undefined` is treated as `true`, `null` is treated as `false`. + * @example + * ```ts + * map.setRenderWorldCopies(true); + * ``` + * @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/) + */ + setRenderWorldCopies(renderWorldCopies?: boolean | null): Map$1; + /** + * Returns a [Point](https://github.com/mapbox/point-geometry) representing pixel coordinates, relative to the map's `container`, + * that correspond to the specified geographical location. + * + * @param lnglat - The geographical location to project. + * @returns The [Point](https://github.com/mapbox/point-geometry) corresponding to `lnglat`, relative to the map's `container`. + * @example + * ```ts + * let coordinate = [-122.420679, 37.772537]; + * let point = map.project(coordinate); + * ``` + */ + project(lnglat: LngLatLike): Point; + /** + * Returns a {@link LngLat} representing geographical coordinates that correspond + * to the specified pixel coordinates. + * + * @param point - The pixel coordinates to unproject. + * @returns The {@link LngLat} corresponding to `point`. + * @example + * ```ts + * map.on('click', (e) => { + * // When the map is clicked, get the geographic coordinate. + * let coordinate = map.unproject(e.point); + * }); + * ``` + */ + unproject(point: PointLike): LngLat; + /** + * Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture. + * @returns true if the map is moving. + * @example + * ```ts + * let isMoving = map.isMoving(); + * ``` + */ + isMoving(): boolean; + /** + * Returns true if the map is zooming due to a camera animation or user gesture. + * @returns true if the map is zooming. + * @example + * ```ts + * let isZooming = map.isZooming(); + * ``` + */ + isZooming(): boolean; + /** + * Returns true if the map is rotating due to a camera animation or user gesture. + * @returns true if the map is rotating. + * @example + * ```ts + * map.isRotating(); + * ``` + */ + isRotating(): boolean; + _createDelegatedListener(type: keyof MapEventType | string, layerIds: string[], listener: Listener): DelegatedListener; + _saveDelegatedListener(type: keyof MapEventType | string, delegatedListener: DelegatedListener): void; + _removeDelegatedListener(type: string, layerIds: string[], listener: Listener): void; + /** + * @event + * Adds a listener for events of a specified type, optionally limited to features in a specified style layer(s). + * See {@link MapEventType} and {@link MapLayerEventType} for a full list of events and their description. + * + * | Event | Compatible with `layerId` | + * |------------------------|---------------------------| + * | `mousedown` | yes | + * | `mouseup` | yes | + * | `mouseover` | yes | + * | `mouseout` | yes | + * | `mousemove` | yes | + * | `mouseenter` | yes (required) | + * | `mouseleave` | yes (required) | + * | `click` | yes | + * | `dblclick` | yes | + * | `contextmenu` | yes | + * | `touchstart` | yes | + * | `touchend` | yes | + * | `touchcancel` | yes | + * | `wheel` | | + * | `resize` | | + * | `remove` | | + * | `touchmove` | | + * | `movestart` | | + * | `move` | | + * | `moveend` | | + * | `dragstart` | | + * | `drag` | | + * | `dragend` | | + * | `zoomstart` | | + * | `zoom` | | + * | `zoomend` | | + * | `rotatestart` | | + * | `rotate` | | + * | `rotateend` | | + * | `pitchstart` | | + * | `pitch` | | + * | `pitchend` | | + * | `boxzoomstart` | | + * | `boxzoomend` | | + * | `boxzoomcancel` | | + * | `webglcontextlost` | | + * | `webglcontextrestored` | | + * | `load` | | + * | `render` | | + * | `idle` | | + * | `error` | | + * | `data` | | + * | `styledata` | | + * | `sourcedata` | | + * | `dataloading` | | + * | `styledataloading` | | + * | `sourcedataloading` | | + * | `styleimagemissing` | | + * | `dataabort` | | + * | `sourcedataabort` | | + * + * @param type - The event type to listen for. Events compatible with the optional `layerId` parameter are triggered + * when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas. + * @param layer - The ID of a style layer or a listener if no ID is provided. Event will only be triggered if its location + * is within a visible feature in this layer. The event will have a `features` property containing + * an array of the matching features. If `layer` is not supplied, the event will not have a `features` property. + * Please note that many event types are not compatible with the optional `layer` parameter. + * @param listener - The function to be called when the event is fired. + * @example + * ```ts + * // Set an event listener that will fire + * // when the map has finished loading + * map.on('load', () => { + * // Once the map has finished loading, + * // add a new layer + * map.addLayer({ + * id: 'points-of-interest', + * source: { + * type: 'vector', + * url: 'https://maplibre.org/maplibre-style-spec/' + * }, + * 'source-layer': 'poi_label', + * type: 'circle', + * paint: { + * // MapLibre Style Specification paint properties + * }, + * layout: { + * // MapLibre Style Specification layout properties + * } + * }); + * }); + * ``` + * @example + * ```ts + * // Set an event listener that will fire + * // when a feature on the countries layer of the map is clicked + * map.on('click', 'countries', (e) => { + * new Popup() + * .setLngLat(e.lngLat) + * .setHTML(`Country name: ${e.features[0].properties.name}`) + * .addTo(map); + * }); + * ``` + * @see [Display popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-on-symbol/) + * @see [Create a hover effect](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/) + * @see [Create a draggable marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + on(type: T, layer: string, listener: (ev: MapLayerEventType[T] & Object) => void): Map$1; + /** + * Overload of the `on` method that allows to listen to events specifying multiple layers. + * @event + * @param type - The type of the event. + * @param layerIds - The array of style layer IDs. + * @param listener - The listener callback. + */ + on(type: T, layerIds: string[], listener: (ev: MapLayerEventType[T] & Object) => void): this; + /** + * Overload of the `on` method that allows to listen to events without specifying a layer. + * @event + * @param type - The type of the event. + * @param listener - The listener callback. + */ + on(type: T, listener: (ev: MapEventType[T] & Object) => void): this; + /** + * Overload of the `on` method that allows to listen to events without specifying a layer. + * @event + * @param type - The type of the event. + * @param listener - The listener callback. + */ + on(type: keyof MapEventType | string, listener: Listener): this; + /** + * Adds a listener that will be called only once to a specified event type, optionally limited to features in a specified style layer. + * + * @event + * @param type - The event type to listen for; one of `'mousedown'`, `'mouseup'`, `'click'`, `'dblclick'`, + * `'mousemove'`, `'mouseenter'`, `'mouseleave'`, `'mouseover'`, `'mouseout'`, `'contextmenu'`, `'touchstart'`, + * `'touchend'`, or `'touchcancel'`. `mouseenter` and `mouseover` events are triggered when the cursor enters + * a visible portion of the specified layer from outside that layer or outside the map canvas. `mouseleave` + * and `mouseout` events are triggered when the cursor leaves a visible portion of the specified layer, or leaves + * the map canvas. + * @param layer - The ID of a style layer or a listener if no ID is provided. Only events whose location is within a visible + * feature in this layer will trigger the listener. The event will have a `features` property containing + * an array of the matching features. + * @param listener - The function to be called when the event is fired. + * @returns `this` if listener is provided, promise otherwise to allow easier usage of async/await + */ + once(type: T, layer: string, listener?: (ev: MapLayerEventType[T] & Object) => void): this | Promise; + /** + * Overload of the `once` method that allows to listen to events specifying multiple layers. + * @event + * @param type - The type of the event. + * @param layerIds - The array of style layer IDs. + * @param listener - The listener callback. + */ + once(type: T, layerIds: string[], listener?: (ev: MapLayerEventType[T] & Object) => void): this | Promise; + /** + * Overload of the `once` method that allows to listen to events without specifying a layer. + * @event + * @param type - The type of the event. + * @param listener - The listener callback. + */ + once(type: T, listener?: (ev: MapEventType[T] & Object) => void): this | Promise; + /** + * Overload of the `once` method that allows to listen to events without specifying a layer. + * @event + * @param type - The type of the event. + * @param listener - The listener callback. + */ + once(type: keyof MapEventType | string, listener?: Listener): this | Promise; + /** + * Removes an event listener for events previously added with `Map#on`. + * + * @event + * @param type - The event type previously used to install the listener. + * @param layer - The layer ID or listener previously used to install the listener. + * @param listener - The function previously installed as a listener. + */ + off(type: T, layer: string, listener: (ev: MapLayerEventType[T] & Object) => void): this; + /** + * Overload of the `off` method that allows to remove an event created with multiple layers. + * Provide the same layer IDs as to `on` or `once`, when the listener was registered. + * @event + * @param type - The type of the event. + * @param layers - The layer IDs previously used to install the listener. + * @param listener - The function previously installed as a listener. + */ + off(type: T, layers: string[], listener: (ev: MapLayerEventType[T] & Object) => void): this; + /** + * Overload of the `off` method that allows to remove an event created without specifying a layer. + * @event + * @param type - The type of the event. + * @param listener - The function previously installed as a listener. + */ + off(type: T, listener: (ev: MapEventType[T] & Object) => void): this; + /** + * Overload of the `off` method that allows to remove an event created without specifying a layer. + * @event + * @param type - The type of the event. + * @param listener - The function previously installed as a listener. + */ + off(type: keyof MapEventType | string, listener: Listener): this; + /** + * Returns an array of MapGeoJSONFeature objects + * representing visible features that satisfy the query parameters. + * + * @param geometryOrOptions - (optional) The geometry of the query region: + * either a single point or southwest and northeast points describing a bounding box. + * Omitting this parameter (i.e. calling {@link Map#queryRenderedFeatures} with zero arguments, + * or with only a `options` argument) is equivalent to passing a bounding box encompassing the entire + * map viewport. + * The geometryOrOptions can receive a {@link QueryRenderedFeaturesOptions} only to support a situation where the function receives only one parameter which is the options parameter. + * @param options - (optional) Options object. + * + * @returns An array of MapGeoJSONFeature objects. + * + * The `properties` value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only + * string and numeric property values are supported (i.e. `null`, `Array`, and `Object` values are not supported). + * + * Each feature includes top-level `layer`, `source`, and `sourceLayer` properties. The `layer` property is an object + * representing the style layer to which the feature belongs. Layout and paint properties in this object contain values + * which are fully evaluated for the given zoom level and feature. + * + * Only features that are currently rendered are included. Some features will **not** be included, like: + * + * - Features from layers whose `visibility` property is `"none"`. + * - Features from layers whose zoom range excludes the current zoom level. + * - Symbol features that have been hidden due to text or icon collision. + * + * Features from all other layers are included, including features that may have no visible + * contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to + * 0. + * + * The topmost rendered feature appears first in the returned array, and subsequent features are sorted by + * descending z-order. Features that are rendered multiple times (due to wrapping across the antemeridian at low + * zoom levels) are returned only once (though subject to the following caveat). + * + * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature + * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple + * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. + * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding + * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile + * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple + * tiles due to tile buffering. + * + * @example + * Find all features at a point + * ```ts + * let features = map.queryRenderedFeatures( + * [20, 35], + * { layers: ['my-layer-name'] } + * ); + * ``` + * + * @example + * Find all features within a static bounding box + * ```ts + * let features = map.queryRenderedFeatures( + * [[10, 20], [30, 50]], + * { layers: ['my-layer-name'] } + * ); + * ``` + * + * @example + * Find all features within a bounding box around a point + * ```ts + * let width = 10; + * let height = 20; + * let features = map.queryRenderedFeatures([ + * [point.x - width / 2, point.y - height / 2], + * [point.x + width / 2, point.y + height / 2] + * ], { layers: ['my-layer-name'] }); + * ``` + * + * @example + * Query all rendered features from a single layer + * ```ts + * let features = map.queryRenderedFeatures({ layers: ['my-layer-name'] }); + * ``` + * @see [Get features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/queryrenderedfeatures/) + */ + queryRenderedFeatures(geometryOrOptions?: PointLike | [ + PointLike, + PointLike + ] | QueryRenderedFeaturesOptions, options?: QueryRenderedFeaturesOptions): MapGeoJSONFeature[]; + /** + * Returns an array of MapGeoJSONFeature objects + * representing features within the specified vector tile or GeoJSON source that satisfy the query parameters. + * + * @param sourceId - The ID of the vector tile or GeoJSON source to query. + * @param parameters - The options object. + * @returns An array of MapGeoJSONFeature objects. + * + * In contrast to {@link Map#queryRenderedFeatures}, this function returns all features matching the query parameters, + * whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded + * vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently + * visible viewport. + * + * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature + * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple + * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. + * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding + * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile + * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple + * tiles due to tile buffering. + * + * @example + * Find all features in one source layer in a vector source + * ```ts + * let features = map.querySourceFeatures('your-source-id', { + * sourceLayer: 'your-source-layer' + * }); + * ``` + * + */ + querySourceFeatures(sourceId: string, parameters?: QuerySourceFeatureOptions | null): MapGeoJSONFeature[]; + /** + * Updates the map's MapLibre style object with a new value. + * + * 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 + * against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites + * (images used for icons and patterns) and glyphs (fonts for label text) **cannot** be diffed. If the sprites or fonts used in the current + * style and the given style are different in any way, the map renderer will force a full update, removing the current style and building + * the given one from scratch. + * + * + * @param style - A JSON object conforming to the schema described in the + * [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/), or a URL to such JSON. + * @param options - The options object. + * + * @example + * ```ts + * map.setStyle("https://demotiles.maplibre.org/style.json"); + * + * map.setStyle('https://demotiles.maplibre.org/style.json', { + * transformStyle: (previousStyle, nextStyle) => ({ + * ...nextStyle, + * sources: { + * ...nextStyle.sources, + * // copy a source from previous style + * 'osm': previousStyle.sources.osm + * }, + * layers: [ + * // background layer + * nextStyle.layers[0], + * // copy a layer from previous style + * previousStyle.layers[0], + * // other layers from the next style + * ...nextStyle.layers.slice(1).map(layer => { + * // hide the layers we don't need from demotiles style + * if (layer.id.startsWith('geolines')) { + * layer.layout = {...layer.layout || {}, visibility: 'none'}; + * // filter out US polygons + * } else if (layer.id.startsWith('coastline') || layer.id.startsWith('countries')) { + * layer.filter = ['!=', ['get', 'ADM0_A3'], 'USA']; + * } + * return layer; + * }) + * ] + * }) + * }); + * ``` + */ + setStyle(style: StyleSpecification | string | null, options?: StyleSwapOptions & StyleOptions): this; + /** + * Updates the requestManager's transform request with a new function + * + * @param transformRequest - 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. + * Expected to return an object with a `url` property and optionally `headers` and `credentials` properties + * + * @example + * ```ts + * map.setTransformRequest((url: string, resourceType: string) => {}); + * ``` + */ + setTransformRequest(transformRequest: RequestTransformFunction): this; + _getUIString(key: keyof typeof defaultLocale): string; + _updateStyle(style: StyleSpecification | string | null, options?: StyleSwapOptions & StyleOptions): this; + _lazyInitEmptyStyle(): void; + _diffStyle(style: StyleSpecification | string, options?: StyleSwapOptions & StyleOptions): void; + _updateDiff(style: StyleSpecification, options?: StyleSwapOptions & StyleOptions): void; + /** + * Returns the map's MapLibre style object, a JSON object which can be used to recreate the map's style. + * + * @returns The map's style JSON object. + * + * @example + * ```ts + * let styleJson = map.getStyle(); + * ``` + * + */ + getStyle(): StyleSpecification; + /** + * Returns a Boolean indicating whether the map's style is fully loaded. + * + * @returns A Boolean indicating whether the style is fully loaded. + * + * @example + * ```ts + * let styleLoadStatus = map.isStyleLoaded(); + * ``` + */ + isStyleLoaded(): boolean | void; + /** + * Adds a source to the map's style. + * + * Events triggered: + * + * Triggers the `source.add` event. + * + * @param id - The ID of the source to add. Must not conflict with existing sources. + * @param source - The source object, conforming to the + * MapLibre Style Specification's [source definition](https://maplibre.org/maplibre-style-spec/sources) or + * {@link CanvasSourceSpecification}. + * @example + * ```ts + * map.addSource('my-data', { + * type: 'vector', + * url: 'https://demotiles.maplibre.org/tiles/tiles.json' + * }); + * ``` + * @example + * ```ts + * map.addSource('my-data', { + * "type": "geojson", + * "data": { + * "type": "Feature", + * "geometry": { + * "type": "Point", + * "coordinates": [-77.0323, 38.9131] + * }, + * "properties": { + * "title": "Mapbox DC", + * "marker-symbol": "monument" + * } + * } + * }); + * ``` + * @see GeoJSON source: [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/live-geojson/) + */ + addSource(id: string, source: SourceSpecification | CanvasSourceSpecification): this; + /** + * Returns a Boolean indicating whether the source is loaded. Returns `true` if the source with + * the given ID in the map's style has no outstanding network requests, otherwise `false`. + * + * A {@link ErrorEvent} event will be fired if there is no source wit the specified ID. + * + * @param id - The ID of the source to be checked. + * @returns A Boolean indicating whether the source is loaded. + * @example + * ```ts + * let sourceLoaded = map.isSourceLoaded('bathymetry-data'); + * ``` + */ + isSourceLoaded(id: string): boolean; + /** + * Loads a 3D terrain mesh, based on a "raster-dem" source. + * + * Triggers the `terrain` event. + * + * @param options - Options object. + * @example + * ```ts + * map.setTerrain({ source: 'terrain' }); + * ``` + */ + setTerrain(options: TerrainSpecification | null): this; + /** + * Get the terrain-options if terrain is loaded + * @returns the TerrainSpecification passed to setTerrain + * @example + * ```ts + * map.getTerrain(); // { source: 'terrain' }; + * ``` + */ + getTerrain(): TerrainSpecification | null; + /** + * Returns a Boolean indicating whether all tiles in the viewport from all sources on + * the style are loaded. + * + * @returns A Boolean indicating whether all tiles are loaded. + * @example + * ```ts + * let tilesLoaded = map.areTilesLoaded(); + * ``` + */ + areTilesLoaded(): boolean; + /** + * Removes a source from the map's style. + * + * @param id - The ID of the source to remove. + * @example + * ```ts + * map.removeSource('bathymetry-data'); + * ``` + */ + removeSource(id: string): Map$1; + /** + * Returns the source with the specified ID in the map's style. + * + * This method is often used to update a source using the instance members for the relevant + * source type as defined in classes that derive from {@link Source}. + * For example, setting the `data` for a GeoJSON source or updating the `url` and `coordinates` + * of an image source. + * + * @param id - The ID of the source to get. + * @returns The style source with the specified ID or `undefined` if the ID + * corresponds to no existing sources. + * The shape of the object varies by source type. + * A list of options for each source type is available on the MapLibre Style Specification's + * [Sources](https://maplibre.org/maplibre-style-spec/sources/) page. + * @example + * ```ts + * let sourceObject = map.getSource('points'); + * ``` + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + * @see [Animate a point](https://maplibre.org/maplibre-gl-js/docs/examples/animate-point-along-line/) + * @see [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/live-geojson/) + */ + getSource(id: string): TSource | undefined; + /** + * Add an image to the style. This image can be displayed on the map like any other icon in the style's + * sprite using the image's ID with + * [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image), + * [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern), + * [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern), + * or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern). + * + * A {@link ErrorEvent} event will be fired if the image parameter is invalid or there is not enough space in the sprite to add this image. + * + * @param id - The ID of the image. + * @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data` + * properties with the same format as `ImageData`. + * @param options - Options object. + * @example + * ```ts + * // If the style's sprite does not already contain an image with ID 'cat', + * // add the image 'cat-icon.png' to the style's sprite with the ID 'cat'. + * const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png'); + * if (!map.hasImage('cat')) map.addImage('cat', image.data); + * + * // Add a stretchable image that can be used with `icon-text-fit` + * // In this example, the image is 600px wide by 400px high. + * const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png'); + * if (map.hasImage('border-image')) return; + * map.addImage('border-image', image.data, { + * content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border + * stretchX: [[16, 584]], // stretch everything horizontally except the 16px border + * stretchY: [[16, 384]], // stretch everything vertically except the 16px border + * }); + * ``` + * @see Use `HTMLImageElement`: [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image/) + * @see Use `ImageData`: [Add a generated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-generated/) + */ + addImage(id: string, image: HTMLImageElement | ImageBitmap | ImageData | { + width: number; + height: number; + data: Uint8Array | Uint8ClampedArray; + } | StyleImageInterface, options?: Partial): this; + /** + * Update an existing image in a style. This image can be displayed on the map like any other icon in the style's + * sprite using the image's ID with + * [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image), + * [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern), + * [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern), + * or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern). + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param id - The ID of the image. + * @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data` + * properties with the same format as `ImageData`. + * @example + * ```ts + * // If an image with the ID 'cat' already exists in the style's sprite, + * // replace that image with a new image, 'other-cat-icon.png'. + * if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png'); + * ``` + */ + updateImage(id: string, image: HTMLImageElement | ImageBitmap | ImageData | { + width: number; + height: number; + data: Uint8Array | Uint8ClampedArray; + } | StyleImageInterface): this; + /** + * Returns an image, specified by ID, currently available in the map. + * This includes both images from the style's original sprite + * and any images that have been added at runtime using {@link Map#addImage}. + * + * @param id - The ID of the image. + * @returns An image in the map with the specified ID. + * + * @example + * ```ts + * let coffeeShopIcon = map.getImage("coffee_cup"); + * ``` + */ + getImage(id: string): StyleImage; + /** + * Check whether or not an image with a specific ID exists in the style. This checks both images + * in the style's original sprite and any images + * that have been added at runtime using {@link Map#addImage}. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param id - The ID of the image. + * + * @returns A Boolean indicating whether the image exists. + * @example + * Check if an image with the ID 'cat' exists in the style's sprite. + * ```ts + * let catIconExists = map.hasImage('cat'); + * ``` + */ + hasImage(id: string): boolean; + /** + * Remove an image from a style. This can be an image from the style's original + * sprite or any images + * that have been added at runtime using {@link Map#addImage}. + * + * @param id - The ID of the image. + * + * @example + * ```ts + * // If an image with the ID 'cat' exists in + * // the style's sprite, remove it. + * if (map.hasImage('cat')) map.removeImage('cat'); + * ``` + */ + removeImage(id: string): void; + /** + * Load an image from an external URL to be used with {@link Map#addImage}. External + * domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS). + * + * @param url - The URL of the image file. Image file must be in png, webp, or jpg format. + * @returns a promise that is resolved when the image is loaded + * + * @example + * Load an image from an external URL. + * ```ts + * const response = await map.loadImage('https://picsum.photos/50/50'); + * // Add the loaded image to the style's sprite with the ID 'photo'. + * map.addImage('photo', response.data); + * ``` + * @see [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image/) + */ + loadImage(url: string): Promise>; + /** + * Returns an Array of strings containing the IDs of all images currently available in the map. + * This includes both images from the style's original sprite + * and any images that have been added at runtime using {@link Map#addImage}. + * + * @returns An Array of strings containing the names of all sprites/images currently available in the map. + * + * @example + * ```ts + * let allImages = map.listImages(); + * ``` + */ + listImages(): Array; + /** + * Adds a [MapLibre style layer](https://maplibre.org/maplibre-style-spec/layers) + * to the map's style. + * + * A layer defines how data from a specified source will be styled. Read more about layer types + * and available paint and layout properties in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/layers). + * + * @param layer - The layer to add, + * conforming to either the MapLibre Style Specification's [layer definition](https://maplibre.org/maplibre-style-spec/layers) or, + * less commonly, the {@link CustomLayerInterface} specification. Can also be a layer definition with an embedded source definition. + * The MapLibre Style Specification's layer definition is appropriate for most layers. + * + * @param beforeId - The ID of an existing layer to insert the new layer before, + * resulting in the new layer appearing visually beneath the existing layer. + * If this argument is not specified, the layer will be appended to the end of the layers array + * and appear visually above all other layers. + * + * @example + * Add a circle layer with a vector source + * ```ts + * map.addLayer({ + * id: 'points-of-interest', + * source: { + * type: 'vector', + * url: 'https://demotiles.maplibre.org/tiles/tiles.json' + * }, + * 'source-layer': 'poi_label', + * type: 'circle', + * paint: { + * // MapLibre Style Specification paint properties + * }, + * layout: { + * // MapLibre Style Specification layout properties + * } + * }); + * ``` + * + * @example + * Define a source before using it to create a new layer + * ```ts + * map.addSource('state-data', { + * type: 'geojson', + * data: 'path/to/data.geojson' + * }); + * + * map.addLayer({ + * id: 'states', + * // References the GeoJSON source defined above + * // and does not require a `source-layer` + * source: 'state-data', + * type: 'symbol', + * layout: { + * // Set the label content to the + * // feature's `name` property + * text-field: ['get', 'name'] + * } + * }); + * ``` + * + * @example + * Add a new symbol layer before an existing layer + * ```ts + * map.addLayer({ + * id: 'states', + * // References a source that's already been defined + * source: 'state-data', + * type: 'symbol', + * layout: { + * // Set the label content to the + * // feature's `name` property + * text-field: ['get', 'name'] + * } + * // Add the layer before the existing `cities` layer + * }, 'cities'); + * ``` + * @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/cluster/) + * @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/vector-source/) + * @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/wms/) + */ + addLayer(layer: AddLayerObject, beforeId?: string): this; + /** + * Moves a layer to a different z-position. + * + * @param id - The ID of the layer to move. + * @param 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. + * + * @example + * 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. + * ```ts + * map.moveLayer('polygon', 'country-label'); + * ``` + */ + moveLayer(id: string, beforeId?: string): this; + /** + * Removes the layer with the given ID from the map's style. + * + * An {@link ErrorEvent} will be fired if the image parameter is invald. + * + * @param id - The ID of the layer to remove + * + * @example + * If a layer with ID 'state-data' exists, remove it. + * ```ts + * if (map.getLayer('state-data')) map.removeLayer('state-data'); + * ``` + */ + removeLayer(id: string): this; + /** + * Returns the layer with the specified ID in the map's style. + * + * @param id - The ID of the layer to get. + * @returns The layer with the specified ID, or `undefined` + * if the ID corresponds to no existing layers. + * + * @example + * ```ts + * let stateDataLayer = map.getLayer('state-data'); + * ``` + * @see [Filter symbols by toggling a list](https://maplibre.org/maplibre-gl-js/docs/examples/filter-markers/) + * @see [Filter symbols by text input](https://maplibre.org/maplibre-gl-js/docs/examples/filter-markers-by-input/) + */ + getLayer(id: string): StyleLayer | undefined; + /** + * Return the ids of all layers currently in the style, including custom layers, in order. + * + * @returns ids of layers, in order + * + * @example + * ```ts + * const orderedLayerIds = map.getLayersOrder(); + * ``` + */ + getLayersOrder(): string[]; + /** + * Sets the zoom extent for the specified style layer. The zoom extent includes the + * [minimum zoom level](https://maplibre.org/maplibre-style-spec/layers/#minzoom) + * and [maximum zoom level](https://maplibre.org/maplibre-style-spec/layers/#maxzoom)) + * at which the layer will be rendered. + * + * Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the + * minimum zoom level of the _source layer_ because the data does not exist at those zoom levels. If the minimum + * zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style + * layer will not be rendered at all zoom levels in the zoom range. + * + * @param layerId - The ID of the layer to which the zoom extent will be applied. + * @param minzoom - The minimum zoom to set (0-24). + * @param maxzoom - The maximum zoom to set (0-24). + * + * @example + * ```ts + * map.setLayerZoomRange('my-layer', 2, 5); + * ``` + */ + setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this; + /** + * Sets the filter for the specified style layer. + * + * Filters control which features a style layer renders from its source. + * Any feature for which the filter expression evaluates to `true` will be + * rendered on the map. Those that are false will be hidden. + * + * Use `setFilter` to show a subset of your source data. + * + * To clear the filter, pass `null` or `undefined` as the second parameter. + * + * @param layerId - The ID of the layer to which the filter will be applied. + * @param filter - The filter, conforming to the MapLibre Style Specification's + * [filter definition](https://maplibre.org/maplibre-style-spec/layers/#filter). If `null` or `undefined` is provided, the function removes any existing filter from the layer. + * @param options - Options object. + * + * @example + * Display only features with the 'name' property 'USA' + * ```ts + * map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']); + * ``` + * @example + * Display only features with five or more 'available-spots' + * ```ts + * map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]); + * ``` + * @example + * Remove the filter for the 'bike-docks' style layer + * ```ts + * map.setFilter('bike-docks', null); + * ``` + * @see [Create a timeline animation](https://maplibre.org/maplibre-gl-js/docs/examples/timeline-animation/) + */ + setFilter(layerId: string, filter?: FilterSpecification | null, options?: StyleSetterOptions): this; + /** + * Returns the filter applied to the specified style layer. + * + * @param layerId - The ID of the style layer whose filter to get. + * @returns The layer's filter. + */ + getFilter(layerId: string): FilterSpecification | void; + /** + * Sets the value of a paint property in the specified style layer. + * + * @param layerId - The ID of the layer to set the paint property in. + * @param name - The name of the paint property to set. + * @param value - The value of the paint property to set. + * Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/). + * Pass `null` to unset the existing value. + * @param options - Options object. + * @example + * ```ts + * map.setPaintProperty('my-layer', 'fill-color', '#faafee'); + * ``` + * @see [Change a layer's color with buttons](https://maplibre.org/maplibre-gl-js/docs/examples/color-switcher/) + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + setPaintProperty(layerId: string, name: string, value: any, options?: StyleSetterOptions): this; + /** + * Returns the value of a paint property in the specified style layer. + * + * @param layerId - The ID of the layer to get the paint property from. + * @param name - The name of a paint property to get. + * @returns The value of the specified paint property. + */ + getPaintProperty(layerId: string, name: string): unknown; + /** + * Sets the value of a layout property in the specified style layer. + * + * @param layerId - The ID of the layer to set the layout property in. + * @param name - The name of the layout property to set. + * @param value - The value of the layout property. Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/). + * @param options - The options object. + * @example + * ```ts + * map.setLayoutProperty('my-layer', 'visibility', 'none'); + * ``` + */ + setLayoutProperty(layerId: string, name: string, value: any, options?: StyleSetterOptions): this; + /** + * Returns the value of a layout property in the specified style layer. + * + * @param layerId - The ID of the layer to get the layout property from. + * @param name - The name of the layout property to get. + * @returns The value of the specified layout property. + */ + getLayoutProperty(layerId: string, name: string): any; + /** + * Sets the value of the style's glyphs property. + * + * @param glyphsUrl - Glyph URL to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/glyphs/). + * @param options - Options object. + * @example + * ```ts + * map.setGlyphs('https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf'); + * ``` + */ + setGlyphs(glyphsUrl: string | null, options?: StyleSetterOptions): this; + /** + * Returns the value of the style's glyphs URL + * + * @returns glyphs Style's glyphs url + */ + getGlyphs(): string | null; + /** + * Adds a sprite to the map's style. Fires the `style` event. + * + * @param id - The ID of the sprite to add. Must not conflict with existing sprites. + * @param url - The URL to load the sprite from + * @param options - Options object. + * @example + * ```ts + * map.addSprite('sprite-two', 'http://example.com/sprite-two'); + * ``` + */ + addSprite(id: string, url: string, options?: StyleSetterOptions): this; + /** + * Removes the sprite from the map's style. Fires the `style` event. + * + * @param id - The ID of the sprite to remove. If the sprite is declared as a single URL, the ID must be "default". + * @example + * ```ts + * map.removeSprite('sprite-two'); + * map.removeSprite('default'); + * ``` + */ + removeSprite(id: string): this; + /** + * Returns the as-is value of the style's sprite. + * + * @returns style's sprite list of id-url pairs + */ + getSprite(): { + id: string; + url: string; + }[]; + /** + * Sets the value of the style's sprite property. + * + * @param spriteUrl - Sprite URL to set. + * @param options - Options object. + * @example + * ```ts + * map.setSprite('YOUR_SPRITE_URL'); + * ``` + */ + setSprite(spriteUrl: string | null, options?: StyleSetterOptions): this; + /** + * Sets the any combination of light values. + * + * @param light - Light properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/light). + * @param options - Options object. + * + * @example + * ```ts + * let layerVisibility = map.getLayoutProperty('my-layer', 'visibility'); + * ``` + */ + setLight(light: LightSpecification, options?: StyleSetterOptions): this; + /** + * Returns the value of the light object. + * + * @returns light Light properties of the style. + */ + getLight(): LightSpecification; + /** + * Loads sky and fog defined by {@link SkySpecification} onto the map. + * Note: The fog only shows when using the terrain 3D feature. + * @param sky - Sky properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/sky/). + * @returns `this` + * @example + * ```ts + * map.setSky({ 'sky-color': '#00f' }); + * ``` + */ + setSky(sky: SkySpecification): this; + /** + * Returns the value of the sky object. + * + * @returns the sky properties of the style. + * @example + * ```ts + * map.getSky(); + * ``` + */ + getSky(): SkySpecification; + /** + * Sets the `state` of a feature. + * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime. + * When using this method, the `state` object is merged with any existing key-value pairs in the feature's state. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * This method can only be used with sources that have a `feature.id` attribute. The `feature.id` attribute can be defined in three ways: + * + * - For vector or GeoJSON sources, including an `id` attribute in the original data file. + * - For vector or GeoJSON sources, using the [`promoteId`](https://maplibre.org/maplibre-style-spec/sources/#vector-promoteId) option at the time the source is defined. + * - For GeoJSON sources, using the [`generateId`](https://maplibre.org/maplibre-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. + * + * _Note: You can use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state) to access the values in a feature's state object for the purposes of styling._ + * + * @param feature - Feature identifier. Feature objects returned from + * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param state - A set of key-value pairs. The values should be valid JSON types. + * + * @example + * ```ts + * // When the mouse moves over the `my-layer` layer, update + * // the feature state for the feature under the mouse + * map.on('mousemove', 'my-layer', (e) => { + * if (e.features.length > 0) { + * map.setFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id, + * }, { + * hover: true + * }); + * } + * }); + * ``` + * @see [Create a hover effect](https://maplibre.org/maplibre-gl-js/docs/examples/hover-styles/) + */ + setFeatureState(feature: FeatureIdentifier, state: any): this; + /** + * Removes the `state` of a feature, setting it back to the default behavior. + * If only a `target.source` is specified, it will remove the state for all features from that source. + * If `target.id` is also specified, it will remove all keys for that feature's state. + * If `key` is also specified, it removes only that key from that feature's state. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * @param target - Identifier of where to remove state. It can be a source, a feature, or a specific key of feature. + * Feature objects returned from {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param key - (optional) The key in the feature state to reset. + * @example + * Reset the entire state object for all features in the `my-source` source + * ```ts + * map.removeFeatureState({ + * source: 'my-source' + * }); + * ``` + * + * @example + * When the mouse leaves the `my-layer` layer, + * reset the entire state object for the + * feature under the mouse + * ```ts + * map.on('mouseleave', 'my-layer', (e) => { + * map.removeFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }); + * }); + * ``` + * + * @example + * When the mouse leaves the `my-layer` layer, + * reset only the `hover` key-value pair in the + * state for the feature under the mouse + * ```ts + * map.on('mouseleave', 'my-layer', (e) => { + * map.removeFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }, 'hover'); + * }); + * ``` + */ + removeFeatureState(target: FeatureIdentifier, key?: string): this; + /** + * Gets the `state` of a feature. + * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * _Note: To access the values in a feature's state object for the purposes of styling the feature, use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state)._ + * + * @param feature - Feature identifier. Feature objects returned from + * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @returns The state of the feature: a set of key-value pairs that was assigned to the feature at runtime. + * + * @example + * When the mouse moves over the `my-layer` layer, + * get the feature state for the feature under the mouse + * ```ts + * map.on('mousemove', 'my-layer', (e) => { + * if (e.features.length > 0) { + * map.getFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }); + * } + * }); + * ``` + */ + getFeatureState(feature: FeatureIdentifier): any; + /** + * Returns the map's containing HTML element. + * + * @returns The map's container. + */ + getContainer(): HTMLElement; + /** + * Returns the HTML element containing the map's `` element. + * + * If you want to add non-GL overlays to the map, you should append them to this element. + * + * This is the element to which event bindings for map interactivity (such as panning and zooming) are + * attached. It will receive bubbled events from child elements such as the ``, but not from + * map controls. + * + * @returns The container of the map's ``. + * @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-point/) + */ + getCanvasContainer(): HTMLElement; + /** + * Returns the map's `` element. + * + * @returns The map's `` element. + * @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-on-symbol/) + */ + getCanvas(): HTMLCanvasElement; + _containerDimensions(): number[]; + _setupContainer(): void; + _resizeCanvas(width: number, height: number, pixelRatio: number): void; + _setupPainter(): void; + _contextLost: (event: any) => void; + _contextRestored: (event: any) => void; + _onMapScroll: (event: any) => boolean; + /** + * Returns a Boolean indicating whether the map is fully loaded. + * + * Returns `false` if the style is not yet fully loaded, + * or if there has been a change to the sources or style that + * has not yet fully loaded. + * + * @returns A Boolean indicating whether the map is fully loaded. + */ + loaded(): boolean; + /** + * @internal + * Update this map's style and sources, and re-render the map. + * + * @param updateStyle - mark the map's style for reprocessing as + * well as its sources + */ + _update(updateStyle?: boolean): this; + /** + * @internal + * Request that the given callback be executed during the next render + * frame. Schedule a render frame if one is not already scheduled. + * + * @returns An id that can be used to cancel the callback + */ + _requestRenderFrame(callback: () => void): TaskID; + _cancelRenderFrame(id: TaskID): void; + /** + * @internal + * Call when a (re-)render of the map is required: + * + * - The style has changed (`setPaintProperty()`, etc.) + * - Source data has changed (e.g. tiles have finished loading) + * - The map has is moving (or just finished moving) + * - A transition is in progress + * + * @param paintStartTimeStamp - The time when the animation frame began executing. + */ + _render(paintStartTimeStamp: number): this; + /** + * Force a synchronous redraw of the map. + * @example + * ```ts + * map.redraw(); + * ``` + */ + redraw(): this; + /** + * Clean up and release all internal resources associated with this map. + * + * This includes DOM elements, event bindings, web workers, and WebGL resources. + * + * Use this method when you are done using the map and wish to ensure that it no + * longer consumes browser resources. Afterwards, you must not call any other + * methods on the map. + */ + remove(): void; + /** + * Trigger the rendering of a single frame. Use this method with custom layers to + * repaint the map when the layer changes. Calling this multiple times before the + * next frame is rendered will still result in only a single frame being rendered. + * @example + * ```ts + * map.triggerRepaint(); + * ``` + * @see [Add a 3D model](https://maplibre.org/maplibre-gl-js/docs/examples/add-3d-model/) + * @see [Add an animated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-image-animated/) + */ + triggerRepaint(): void; + _onWindowOnline: () => void; + /** + * Gets and sets a Boolean indicating whether the map will render an outline + * around each tile and the tile ID. These tile boundaries are useful for + * debugging. + * + * The uncompressed file size of the first vector source is drawn in the top left + * corner of each tile, next to the tile ID. + * + * @example + * ```ts + * map.showTileBoundaries = true; + * ``` + */ + get showTileBoundaries(): boolean; + set showTileBoundaries(value: boolean); + /** + * Gets and sets a Boolean indicating whether the map will visualize + * the padding offsets. + */ + get showPadding(): boolean; + set showPadding(value: boolean); + /** + * Gets and sets a Boolean indicating whether the map will render boxes + * around all symbols in the data source, revealing which symbols + * were rendered or which were hidden due to collisions. + * This information is useful for debugging. + */ + get showCollisionBoxes(): boolean; + set showCollisionBoxes(value: boolean); + /** + * Gets and sets a Boolean indicating whether the map should color-code + * each fragment to show how many times it has been shaded. + * White fragments have been shaded 8 or more times. + * Black fragments have been shaded 0 times. + * This information is useful for debugging. + */ + get showOverdrawInspector(): boolean; + set showOverdrawInspector(value: boolean); + /** + * Gets and sets a Boolean indicating whether the map will + * continuously repaint. This information is useful for analyzing performance. + */ + get repaint(): boolean; + set repaint(value: boolean); + get vertices(): boolean; + set vertices(value: boolean); + /** + * Returns the package version of the library + * @returns Package version of the library + */ + get version(): string; + /** + * Returns the elevation for the point where the camera is looking. + * This value corresponds to: + * "meters above sea level" * "exaggeration" + * @returns The elevation. + */ + getCameraTargetElevation(): number; +} +export interface OneFingerTouchRotateHandler extends DragMoveHandler { +} +export interface OneFingerTouchPitchHandler extends DragMoveHandler { +} +/** + * The {@link NavigationControl} options object + */ +export type NavigationControlOptions = { + /** + * If `true` the compass button is included. + */ + showCompass?: boolean; + /** + * If `true` the zoom-in and zoom-out buttons are included. + */ + showZoom?: boolean; + /** + * If `true` the pitch is visualized by rotating X-axis of compass. + */ + visualizePitch?: boolean; +}; +/** + * A `NavigationControl` control contains zoom buttons and a compass. + * + * @group Markers and Controls + * + * @example + * ```ts + * let nav = new NavigationControl(); + * map.addControl(nav, 'top-left'); + * ``` + * @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigation/) + */ +export declare class NavigationControl implements IControl { + _map: Map$1; + options: NavigationControlOptions; + _container: HTMLElement; + _zoomInButton: HTMLButtonElement; + _zoomOutButton: HTMLButtonElement; + _compass: HTMLButtonElement; + _compassIcon: HTMLElement; + _handler: MouseRotateWrapper; + /** + * @param options - the control's options + */ + constructor(options?: NavigationControlOptions); + _updateZoomButtons: () => void; + _rotateCompassArrow: () => void; + /** {@inheritDoc IControl.onAdd} */ + onAdd(map: Map$1): HTMLElement; + /** {@inheritDoc IControl.onRemove} */ + onRemove(): void; + _createButton(className: string, fn: (e?: any) => unknown): HTMLButtonElement; + _setButtonTitle: (button: HTMLButtonElement, title: "ZoomIn" | "ZoomOut" | "ResetBearing") => void; +} +declare class MouseRotateWrapper { + map: Map$1; + _clickTolerance: number; + element: HTMLElement; + mouseRotate: MouseRotateHandler; + touchRotate: OneFingerTouchRotateHandler; + mousePitch: MousePitchHandler; + touchPitch: OneFingerTouchPitchHandler; + _startPos: Point; + _lastPos: Point; + constructor(map: Map$1, element: HTMLElement, pitch?: boolean); + startMouse(e: MouseEvent, point: Point): void; + startTouch(e: TouchEvent, point: Point): void; + moveMouse(e: MouseEvent, point: Point): void; + moveTouch(e: TouchEvent, point: Point): void; + off(): void; + offTemp(): void; + mousedown: (e: MouseEvent) => void; + mousemove: (e: MouseEvent) => void; + mouseup: (e: MouseEvent) => void; + touchstart: (e: TouchEvent) => void; + touchmove: (e: TouchEvent) => void; + touchend: (e: TouchEvent) => void; + reset: () => void; +} +/** + * Where to position the anchor. + * Used by a popup and a marker. + */ +export type PositionAnchor = "center" | "top" | "bottom" | "left" | "right" | "top-left" | "top-right" | "bottom-left" | "bottom-right"; +/** + * A pixel offset specified as: + * + * - a single number specifying a distance from the location + * - a {@link PointLike} specifying a constant offset + * - an object of {@link Point}s specifying an offset for each anchor position + * + * Negative offsets indicate left and up. + */ +export type Offset = number | PointLike | { + [_ in PositionAnchor]: PointLike; +}; +/** + * The {@link Popup} options object + */ +export type PopupOptions = { + /** + * If `true`, a close button will appear in the top right corner of the popup. + * @defaultValue true + */ + closeButton?: boolean; + /** + * If `true`, the popup will closed when the map is clicked. + * @defaultValue true + */ + closeOnClick?: boolean; + /** + * If `true`, the popup will closed when the map moves. + * @defaultValue false + */ + closeOnMove?: boolean; + /** + * If `true`, the popup will try to focus the first focusable element inside the popup. + * @defaultValue true + */ + focusAfterOpen?: boolean; + /** + * A string indicating the part of the Popup that should + * be positioned closest to the coordinate set via {@link Popup#setLngLat}. + * Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`, + * `'top-right'`, `'bottom-left'`, and `'bottom-right'`. If unset the anchor will be + * dynamically set to ensure the popup falls within the map container with a preference + * for `'bottom'`. + */ + anchor?: PositionAnchor; + /** + * A pixel offset applied to the popup's location + */ + offset?: Offset; + /** + * Space-separated CSS class names to add to popup container + */ + className?: string; + /** + * A string that sets the CSS property of the popup's maximum width, eg `'300px'`. + * To ensure the popup resizes to fit its content, set this property to `'none'`. + * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width + * @defaultValue '240px' + */ + maxWidth?: string; + /** + * If `true`, rounding is disabled for placement of the popup, allowing for + * subpixel positioning and smoother movement when the popup is translated. + * @defaultValue false + */ + subpixelPositioning?: boolean; +}; +/** + * A popup component. + * + * @group Markers and Controls + * + * + * @example + * Create a popup + * ```ts + * let popup = new Popup(); + * // Set an event listener that will fire + * // any time the popup is opened + * popup.on('open', () => { + * console.log('popup was opened'); + * }); + * ``` + * + * @example + * Create a popup + * ```ts + * let popup = new Popup(); + * // Set an event listener that will fire + * // any time the popup is closed + * popup.on('close', () => { + * console.log('popup was closed'); + * }); + * ``` + * + * @example + * ```ts + * let markerHeight = 50, markerRadius = 10, linearOffset = 25; + * let popupOffsets = { + * 'top': [0, 0], + * 'top-left': [0,0], + * 'top-right': [0,0], + * 'bottom': [0, -markerHeight], + * 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + * 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + * 'left': [markerRadius, (markerHeight - markerRadius) * -1], + * 'right': [-markerRadius, (markerHeight - markerRadius) * -1] + * }; + * let popup = new Popup({offset: popupOffsets, className: 'my-class'}) + * .setLngLat(e.lngLat) + * .setHTML("

Hello World!

") + * .setMaxWidth("300px") + * .addTo(map); + * ``` + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/) + * + * ## Events + * + * **Event** `open` of type {@link Event} will be fired when the popup is opened manually or programmatically. + * + * **Event** `close` of type {@link Event} will be fired when the popup is closed manually or programmatically. + */ +export declare class Popup extends Evented { + _map: Map$1; + options: PopupOptions; + _content: HTMLElement; + _container: HTMLElement; + _closeButton: HTMLButtonElement; + _tip: HTMLElement; + _lngLat: LngLat; + _trackPointer: boolean; + _pos: Point; + _flatPos: Point; + /** + * @param options - the options + */ + constructor(options?: PopupOptions); + /** + * Adds the popup to a map. + * + * @param map - The MapLibre GL JS map to add the popup to. + * @example + * ```ts + * new Popup() + * .setLngLat([0, 0]) + * .setHTML("

Null Island

") + * .addTo(map); + * ``` + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + * @see [Show polygon information on click](https://maplibre.org/maplibre-gl-js/docs/examples/polygon-popup-on-click/) + */ + addTo(map: Map$1): this; + /** + * @returns `true` if the popup is open, `false` if it is closed. + */ + isOpen(): boolean; + /** + * Removes the popup from the map it has been added to. + * + * @example + * ```ts + * let popup = new Popup().addTo(map); + * popup.remove(); + * ``` + */ + remove: () => this; + /** + * Returns the geographical location of the popup's anchor. + * + * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously + * set by `setLngLat` because `Popup` wraps the anchor longitude across copies of the world to keep + * the popup on screen. + * + * @returns The geographical location of the popup's anchor. + */ + getLngLat(): LngLat; + /** + * Sets the geographical location of the popup's anchor, and moves the popup to it. Replaces trackPointer() behavior. + * + * @param lnglat - The geographical location to set as the popup's anchor. + */ + setLngLat(lnglat: LngLatLike): this; + /** + * Tracks the popup anchor to the cursor position on screens with a pointer device (it will be hidden on touchscreens). Replaces the `setLngLat` behavior. + * For most use cases, set `closeOnClick` and `closeButton` to `false`. + * @example + * ```ts + * let popup = new Popup({ closeOnClick: false, closeButton: false }) + * .setHTML("

Hello World!

") + * .trackPointer() + * .addTo(map); + * ``` + */ + trackPointer(): this; + /** + * Returns the `Popup`'s HTML element. + * @example + * Change the `Popup` element's font size + * ```ts + * let popup = new Popup() + * .setLngLat([-96, 37.8]) + * .setHTML("

Hello World!

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

Hello World!

") + * .addTo(map); + * ``` + * @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/popup/) + * @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-hover/) + * @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/popup-on-click/) + * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/) + */ + setHTML(html: string): this; + /** + * Returns the popup's maximum width. + * + * @returns The maximum width of the popup. + */ + getMaxWidth(): string; + /** + * Sets the popup's maximum width. This is setting the CSS property `max-width`. + * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width + * + * @param maxWidth - A string representing the value for the maximum width. + */ + setMaxWidth(maxWidth: string): this; + /** + * Sets the popup's content to the element provided as a DOM node. + * + * @param htmlNode - A DOM node to be used as content for the popup. + * @example + * Create an element with the popup content + * ```ts + * let div = document.createElement('div'); + * div.innerHTML = 'Hello, world!'; + * let popup = new Popup() + * .setLngLat(e.lngLat) + * .setDOMContent(div) + * .addTo(map); + * ``` + */ + setDOMContent(htmlNode: Node): this; + /** + * Adds a CSS class to the popup container element. + * + * @param className - Non-empty string with CSS class name to add to popup container + * + * @example + * ```ts + * let popup = new Popup() + * popup.addClassName('some-class') + * ``` + */ + addClassName(className: string): this; + /** + * Removes a CSS class from the popup container element. + * + * @param className - Non-empty string with CSS class name to remove from popup container + * + * @example + * ```ts + * let popup = new Popup() + * popup.removeClassName('some-class') + * ``` + */ + removeClassName(className: string): this; + /** + * Sets the popup's offset. + * + * @param offset - Sets the popup's offset. + */ + setOffset(offset?: Offset): this; + /** + * Add or remove the given CSS class on the popup container, depending on whether the container currently has that class. + * + * @param className - Non-empty string with CSS class name to add/remove + * + * @returns if the class was removed return false, if class was added, then return true, undefined if there is no container + * + * @example + * ```ts + * let popup = new Popup() + * popup.toggleClassName('toggleClass') + * ``` + */ + toggleClassName(className: string): boolean | undefined; + /** + * Set the option to allow subpixel positioning of the popup by passing a boolean + * + * @param value - When boolean is true, subpixel positioning is enabled for the popup. + * + * @example + * ```ts + * let popup = new Popup() + * popup.setSubpixelPositioning(true); + * ``` + */ + setSubpixelPositioning(value: boolean): void; + _createCloseButton(): void; + _onMouseUp: (event: MapMouseEvent) => void; + _onMouseMove: (event: MapMouseEvent) => void; + _onDrag: (event: MapMouseEvent) => void; + _update: (cursor?: Point) => void; + _focusFirstElement(): void; + _onClose: () => void; +} +/** + * Alignment options of rotation and pitch + */ +export type Alignment = "map" | "viewport" | "auto"; +/** + * The {@link Marker} options object + */ +export type MarkerOptions = { + /** + * DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker. + */ + element?: HTMLElement; + /** + * Space-separated CSS class names to add to marker element. + */ + className?: string; + /** + * The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up. + */ + offset?: PointLike; + /** + * A string indicating the part of the Marker that should be positioned closest to the coordinate set via {@link Marker#setLngLat}. + * Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. + * @defaultValue 'center' + * */ + anchor?: PositionAnchor; + /** + * The color to use for the default marker if options.element is not provided. The default is light blue. + * @defaultValue '#3FB1CE' + */ + color?: string; + /** + * 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`. + * @defaultValue 1 + */ + scale?: number; + /** + * A boolean indicating whether or not a marker is able to be dragged to a new position on the map. + * @defaultValue false + */ + draggable?: boolean; + /** + * 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. + * @defaultValue 0 + */ + clickTolerance?: number; + /** + * The rotation angle of the marker in degrees, relative to its respective `rotationAlignment` setting. A positive value will rotate the marker clockwise. + * @defaultValue 0 + */ + rotation?: number; + /** + * `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`. + * @defaultValue 'auto' + */ + rotationAlignment?: Alignment; + /** + * `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`. + * @defaultValue 'auto' + */ + pitchAlignment?: Alignment; + /** + * Marker's opacity when it's in clear view (not behind 3d terrain) + * @defaultValue 1 + */ + opacity?: string; + /** + * Marker's opacity when it's behind 3d terrain + * @defaultValue 0.2 + */ + opacityWhenCovered?: string; + /** + * If `true`, rounding is disabled for placement of the marker, allowing for + * subpixel positioning and smoother movement when the marker is translated. + * @defaultValue false + */ + subpixelPositioning?: boolean; +}; +/** + * Creates a marker component + * + * @group Markers and Controls + * + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([30.5, 50.5]) + * .addTo(map); + * ``` + * + * @example + * Set options + * ```ts + * let marker = new Marker({ + * color: "#FFFFFF", + * draggable: true + * }).setLngLat([30.5, 50.5]) + * .addTo(map); + * ``` + * @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/custom-marker-icons/) + * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/) + * + * ## Events + * + * **Event** `dragstart` of type {@link Event} will be fired when dragging starts. + * + * **Event** `drag` of type {@link Event} will be fired while dragging. + * + * **Event** `dragend` of type {@link Event} will be fired when the marker is finished being dragged. + */ +export declare class Marker extends Evented { + _map: Map$1; + _anchor: PositionAnchor; + _offset: Point; + _element: HTMLElement; + _popup: Popup; + _lngLat: LngLat; + _pos: Point; + _flatPos: Point; + _color: string; + _scale: number; + _defaultMarker: boolean; + _draggable: boolean; + _clickTolerance: number; + _isDragging: boolean; + _state: "inactive" | "pending" | "active"; + _positionDelta: Point; + _pointerdownPos: Point; + _rotation: number; + _pitchAlignment: Alignment; + _rotationAlignment: Alignment; + _originalTabIndex: string; + _opacity: string; + _opacityWhenCovered: string; + _opacityTimeout: ReturnType; + _subpixelPositioning: boolean; + /** + * @param options - the options + */ + constructor(options?: MarkerOptions); + /** + * Attaches the `Marker` to a `Map` object. + * @param map - The MapLibre GL JS map to add the marker to. + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([30.5, 50.5]) + * .addTo(map); // add the marker to the map + * ``` + */ + addTo(map: Map$1): this; + /** + * Removes the marker from a map + * @example + * ```ts + * let marker = new Marker().addTo(map); + * marker.remove(); + * ``` + */ + remove(): this; + /** + * Get the marker's geographical location. + * + * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously + * set by `setLngLat` because `Marker` wraps the anchor longitude across copies of the world to keep + * the marker on screen. + * + * @returns A {@link LngLat} describing the marker's location. + * @example + * ```ts + * // Store the marker's longitude and latitude coordinates in a variable + * let lngLat = marker.getLngLat(); + * // Print the marker's longitude and latitude values in the console + * console.log('Longitude: ' + lngLat.lng + ', Latitude: ' + lngLat.lat ) + * ``` + * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/) + */ + getLngLat(): LngLat; + /** + * Set the marker's geographical position and move it. + * @param lnglat - A {@link LngLat} describing where the marker should be located. + * @example + * Create a new marker, set the longitude and latitude, and add it to the map + * ```ts + * new Marker() + * .setLngLat([-65.017, -16.457]) + * .addTo(map); + * ``` + * @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/custom-marker-icons/) + * @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/drag-a-marker/) + */ + setLngLat(lnglat: LngLatLike): this; + /** + * Returns the `Marker`'s HTML element. + * @returns element + */ + getElement(): HTMLElement; + /** + * Binds a {@link Popup} to the {@link Marker}. + * @param popup - An instance of the {@link Popup} class. If undefined or null, any popup + * set on this {@link Marker} instance is unset. + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([0, 0]) + * .setPopup(new Popup().setHTML("

Hello World!

")) // add popup + * .addTo(map); + * ``` + * @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/set-popup/) + */ + setPopup(popup?: Popup | null): this; + /** + * Set the option to allow subpixel positioning of the marker by passing a boolean + * + * @param value - when set to `true`, subpixel positioning is enabled for the marker. + * + * @example + * ```ts + * let marker = new Marker() + * marker.setSubpixelPositioning(true); + * ``` + */ + setSubpixelPositioning(value: boolean): this; + _onKeyPress: (e: KeyboardEvent) => void; + _onMapClick: (e: MapMouseEvent) => void; + /** + * Returns the {@link Popup} instance that is bound to the {@link Marker}. + * @returns popup + * @example + * ```ts + * let marker = new Marker() + * .setLngLat([0, 0]) + * .setPopup(new Popup().setHTML("

Hello World!

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

Hello World!

")) + * .addTo(map); + * + * marker.togglePopup(); // toggle popup open or closed + * ``` + */ + togglePopup(): this; + _updateOpacity(force?: boolean): void; + _update: (e?: { + type: "move" | "moveend" | "terrain" | "render"; + }) => void; + /** + * Get the marker's offset. + * @returns The marker's screen coordinates in pixels. + */ + getOffset(): Point; + /** + * Sets the offset of the marker + * @param offset - The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up. + */ + setOffset(offset: PointLike): this; + /** + * Adds a CSS class to the marker element. + * + * @param className - on-empty string with CSS class name to add to marker element + * + * @example + * ``` + * let marker = new Marker() + * marker.addClassName('some-class') + * ``` + */ + addClassName(className: string): void; + /** + * Removes a CSS class from the marker element. + * + * @param className - Non-empty string with CSS class name to remove from marker element + * + * @example + * ```ts + * let marker = new Marker() + * marker.removeClassName('some-class') + * ``` + */ + removeClassName(className: string): void; + /** + * Add or remove the given CSS class on the marker element, depending on whether the element currently has that class. + * + * @param className - Non-empty string with CSS class name to add/remove + * + * @returns if the class was removed return false, if class was added, then return true + * + * @example + * ```ts + * let marker = new Marker() + * marker.toggleClassName('toggleClass') + * ``` + */ + toggleClassName(className: string): boolean; + _onMove: (e: MapMouseEvent | MapTouchEvent) => void; + _onUp: () => void; + _addDragHandler: (e: MapMouseEvent | MapTouchEvent) => void; + /** + * Sets the `draggable` property and functionality of the marker + * @param shouldBeDraggable - Turns drag functionality on/off + */ + setDraggable(shouldBeDraggable?: boolean): this; + /** + * Returns true if the marker can be dragged + * @returns True if the marker is draggable. + */ + isDraggable(): boolean; + /** + * Sets the `rotation` property of the marker. + * @param rotation - The rotation angle of the marker (clockwise, in degrees), relative to its respective {@link Marker#setRotationAlignment} setting. + */ + setRotation(rotation?: number): this; + /** + * Returns the current rotation angle of the marker (in degrees). + * @returns The current rotation angle of the marker. + */ + getRotation(): number; + /** + * Sets the `rotationAlignment` property of the marker. + * @param alignment - Sets the `rotationAlignment` property of the marker. defaults to 'auto' + */ + setRotationAlignment(alignment?: Alignment): this; + /** + * Returns the current `rotationAlignment` property of the marker. + * @returns The current rotational alignment of the marker. + */ + getRotationAlignment(): Alignment; + /** + * Sets the `pitchAlignment` property of the marker. + * @param alignment - Sets the `pitchAlignment` property of the marker. If alignment is 'auto', it will automatically match `rotationAlignment`. + */ + setPitchAlignment(alignment?: Alignment): this; + /** + * Returns the current `pitchAlignment` property of the marker. + * @returns The current pitch alignment of the marker in degrees. + */ + getPitchAlignment(): Alignment; + /** + * Sets the `opacity` and `opacityWhenCovered` properties of the marker. + * When called without arguments, resets opacity and opacityWhenCovered to defaults + * @param opacity - Sets the `opacity` property of the marker. + * @param opacityWhenCovered - Sets the `opacityWhenCovered` property of the marker. + */ + setOpacity(opacity?: string, opacityWhenCovered?: string): this; +} +/** + * The {@link GeolocateControl} options object + */ +export type GeolocateControlOptions = { + /** + * A Geolocation API [PositionOptions](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) object. + * @defaultValue `{enableHighAccuracy: false, timeout: 6000}` + */ + positionOptions?: PositionOptions; + /** + * A 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. + */ + fitBoundsOptions?: FitBoundsOptions; + /** + * If `true` the `GeolocateControl` becomes a toggle button and when active the map will receive updates to the user's location as it changes. + * @defaultValue false + */ + trackUserLocation?: boolean; + /** + * 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`. + * @defaultValue true + */ + showAccuracyCircle?: boolean; + /** + * By default a dot will be shown on the map at the user's location. Set to `false` to disable. + * @defaultValue true + */ + showUserLocation?: boolean; +}; +/** + * A `GeolocateControl` control provides a button that uses the browser's geolocation + * API to locate the user on the map. + * + * Not all browsers support geolocation, + * and some users may disable the feature. Geolocation support for modern + * browsers including Chrome requires sites to be served over HTTPS. If + * geolocation support is not available, the `GeolocateControl` will show + * as disabled. + * + * The zoom level applied will depend on the accuracy of the geolocation provided by the device. + * + * 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: + * * 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. + * * passive - the user's location dot automatically updates, but the map's camera does not. Occurs upon the user initiating a map movement. + * * disabled - occurs if Geolocation is not available, disabled or denied. + * + * These interaction states can't be controlled programmatically, rather they are set based on user interactions. + * + * ## State Diagram + * ![GeolocateControl state diagram](https://github.com/maplibre/maplibre-gl-js/assets/3269297/78e720e5-d781-4da8-9803-a7a0e6aaaa9f) + * + * @group Markers and Controls + * + * @example + * ```ts + * map.addControl(new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * })); + * ``` + * @see [Locate the user](https://maplibre.org/maplibre-gl-js/docs/examples/locate-user/) + * + * ## Events + * + * **Event** `trackuserlocationend` of type {@link Event} will be fired when the `GeolocateControl` 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. + * + * **Event** `trackuserlocationstart` of type {@link Event} will be fired when the `GeolocateControl` 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). + * + * **Event** `userlocationlostfocus` of type {@link Event} will be fired when the `GeolocateControl` 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. + * + * **Event** `userlocationfocus` of type {@link Event} will be fired when the `GeolocateControl` changes to the active lock state, which happens upon 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. + * + * **Event** `geolocate` of type {@link Event} will be fired on each Geolocation API position update which returned as success. + * `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). + * + * **Event** `error` of type {@link Event} will be fired on each Geolocation API position update which returned as an error. + * `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). + * + * **Event** `outofmaxbounds` of type {@link Event} will be fired on each Geolocation API position update which returned as success but user position is out of map `maxBounds`. + * `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). + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a trackuserlocationend event occurs. + * geolocate.on('trackuserlocationend', () => { + * console.log('A trackuserlocationend event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a trackuserlocationstart event occurs. + * geolocate.on('trackuserlocationstart', () => { + * console.log('A trackuserlocationstart event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an userlocationlostfocus event occurs. + * geolocate.on('userlocationlostfocus', function() { + * console.log('An userlocationlostfocus event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an userlocationfocus event occurs. + * geolocate.on('userlocationfocus', function() { + * console.log('An userlocationfocus event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a geolocate event occurs. + * geolocate.on('geolocate', () => { + * console.log('A geolocate event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an error event occurs. + * geolocate.on('error', () => { + * console.log('An error event has occurred.') + * }); + * ``` + * + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an outofmaxbounds event occurs. + * geolocate.on('outofmaxbounds', () => { + * console.log('An outofmaxbounds event has occurred.') + * }); + * ``` + */ +export declare class GeolocateControl extends Evented implements IControl { + _map: Map$1; + options: GeolocateControlOptions; + _container: HTMLElement; + _dotElement: HTMLElement; + _circleElement: HTMLElement; + _geolocateButton: HTMLButtonElement; + _geolocationWatchID: number; + _timeoutId: ReturnType; + _watchState: "OFF" | "ACTIVE_LOCK" | "WAITING_ACTIVE" | "ACTIVE_ERROR" | "BACKGROUND" | "BACKGROUND_ERROR"; + _lastKnownPosition: any; + _userLocationDotMarker: Marker; + _accuracyCircleMarker: Marker; + _accuracy: number; + _setup: boolean; + /** + * @param options - the control's options + */ + constructor(options: GeolocateControlOptions); + /** {@inheritDoc IControl.onAdd} */ + onAdd(map: Map$1): HTMLElement; + /** {@inheritDoc IControl.onRemove} */ + onRemove(): void; + /** + * Check if the Geolocation API Position is outside the map's `maxBounds`. + * + * @param position - the Geolocation API Position + * @returns `true` if position is outside the map's `maxBounds`, otherwise returns `false`. + */ + _isOutOfMapMaxBounds(position: GeolocationPosition): boolean; + _setErrorState(): void; + /** + * When the Geolocation API returns a new location, update the `GeolocateControl`. + * + * @param position - the Geolocation API Position + */ + _onSuccess: (position: GeolocationPosition) => void; + /** + * Update the camera location to center on the current position + * + * @param position - the Geolocation API Position + */ + _updateCamera: (position: GeolocationPosition) => void; + /** + * Update the user location dot Marker to the current position + * + * @param position - the Geolocation API Position + */ + _updateMarker: (position?: GeolocationPosition | null) => void; + _updateCircleRadius(): void; + _onZoom: () => void; + _onError: (error: GeolocationPositionError) => void; + _finish: () => void; + _setupUI: () => void; + _finishSetupUI: (supported: boolean) => void; + /** + * Programmatically request and move the map to the user's location. + * + * @returns `false` if called before control was added to a map, otherwise returns `true`. + * @example + * ```ts + * // Initialize the geolocate control. + * let geolocate = new GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * map.on('load', () => { + * geolocate.trigger(); + * }); + * ``` + */ + trigger(): boolean; + _clearWatch(): void; +} +/** + * The {@link LogoControl} options object + */ +export type LogoControlOptions = { + /** + * If `true`, force a compact logo. + * If `false`, force the full logo. The default is a responsive logo that collapses when the map is less than 640 pixels wide. + */ + compact?: boolean; +}; +/** + * A `LogoControl` is a control that adds the watermark. + * + * @group Markers and Controls + * + * @example + * ```ts + * map.addControl(new LogoControl({compact: false})); + * ``` + **/ +export declare class LogoControl implements IControl { + options: LogoControlOptions; + _map: Map$1; + _compact: boolean; + _container: HTMLElement; + /** + * @param options - the control's options + */ + constructor(options?: LogoControlOptions); + getDefaultPosition(): ControlPosition; + /** {@inheritDoc IControl.onAdd} */ + onAdd(map: Map$1): HTMLElement; + /** {@inheritDoc IControl.onRemove} */ + onRemove(): void; + _updateCompact: () => void; +} +/** + * The unit type for length to use for the {@link ScaleControl} + */ +export type Unit = "imperial" | "metric" | "nautical"; +/** + * The {@link ScaleControl} options object + */ +export type ScaleControlOptions = { + /** + * The maximum length of the scale control in pixels. + * @defaultValue 100 + */ + maxWidth?: number; + /** + * Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`). + * @defaultValue 'metric' + */ + unit?: Unit; +}; +/** + * A `ScaleControl` control displays the ratio of a distance on the map to the corresponding distance on the ground. + * + * @group Markers and Controls + * + * @example + * ```ts + * let scale = new ScaleControl({ + * maxWidth: 80, + * unit: 'imperial' + * }); + * map.addControl(scale); + * + * scale.setUnit('metric'); + * ``` + */ +export declare class ScaleControl implements IControl { + _map: Map$1; + _container: HTMLElement; + options: ScaleControlOptions; + /** + * @param options - the control's options + */ + constructor(options?: ScaleControlOptions); + getDefaultPosition(): ControlPosition; + _onMove: () => void; + /** {@inheritDoc IControl.onAdd} */ + onAdd(map: Map$1): HTMLElement; + /** {@inheritDoc IControl.onRemove} */ + onRemove(): void; + /** + * Set the scale's unit of the distance + * + * @param unit - Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`). + */ + setUnit: (unit: Unit) => void; +} +/** + * The {@link FullscreenControl} options object + */ +export type FullscreenControlOptions = { + /** + * `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. + */ + container?: HTMLElement; +}; +/** + * A `FullscreenControl` control contains a button for toggling the map in and out of fullscreen mode. + * When [requestFullscreen](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen) is not supported, fullscreen is handled via CSS properties. + * The map's `cooperativeGestures` option is temporarily disabled while the map + * is in fullscreen mode, and is restored when the map exist fullscreen mode. + * + * @group Markers and Controls + * @param options - the full screen control options + * + * @example + * ```ts + * map.addControl(new FullscreenControl({container: document.querySelector('body')})); + * ``` + * @see [View a fullscreen map](https://maplibre.org/maplibre-gl-js/docs/examples/fullscreen/) + * + * ## Events + * + * **Event** `fullscreenstart` of type {@link Event} will be fired when fullscreen mode has started. + * + * **Event** `fullscreenend` of type {@link Event} will be fired when fullscreen mode has ended. + */ +export declare class FullscreenControl extends Evented implements IControl { + _map: Map$1; + _controlContainer: HTMLElement; + _fullscreen: boolean; + _fullscreenchange: string; + _fullscreenButton: HTMLButtonElement; + _container: HTMLElement; + _prevCooperativeGesturesEnabled: boolean; + /** + * @param options - the control's options + */ + constructor(options?: FullscreenControlOptions); + /** {@inheritDoc IControl.onAdd} */ + onAdd(map: Map$1): HTMLElement; + /** {@inheritDoc IControl.onRemove} */ + onRemove(): void; + _setupUI(): void; + _updateTitle(): void; + _getTitle(): string; + _isFullscreen(): boolean; + _onFullscreenChange: () => void; + _handleFullscreenChange(): void; + _onClickFullscreen: () => void; + _exitFullscreen(): void; + _requestFullscreen(): void; + _togglePseudoFullScreen(): void; +} +/** + * A `TerrainControl` control contains a button for turning the terrain on and off. + * + * @group Markers and Controls + * + * @example + * ```ts + * let map = new Map({TerrainControl: false}) + * .addControl(new TerrainControl({ + * source: "terrain" + * })); + * ``` + */ +export declare class TerrainControl implements IControl { + options: TerrainSpecification; + _map: Map$1; + _container: HTMLElement; + _terrainButton: HTMLButtonElement; + /** + * @param options - the control's options + */ + constructor(options: TerrainSpecification); + /** {@inheritDoc IControl.onAdd} */ + onAdd(map: Map$1): HTMLElement; + /** {@inheritDoc IControl.onRemove} */ + onRemove(): void; + _toggleTerrain: () => void; + _updateTerrainIcon: () => void; +} +/** + * Initializes resources like WebWorkers that can be shared across maps to lower load + * times in some situations. `setWorkerUrl()` and `setWorkerCount()`, if being + * used, must be set before `prewarm()` is called to have an effect. + * + * By default, the lifecycle of these resources is managed automatically, and they are + * lazily initialized when a Map is first created. By invoking `prewarm()`, these + * resources will be created ahead of time, and will not be cleared when the last Map + * is removed from the page. This allows them to be re-used by new Map instances that + * are created later. They can be manually cleared by calling + * `clearPrewarmedResources()`. This is only necessary if your web page remains + * active but stops using maps altogether. + * + * This is primarily useful when using GL-JS maps in a single page app, wherein a user + * would navigate between various views that can cause Map instances to constantly be + * created and destroyed. + * + * @example + * ```ts + * prewarm() + * ``` + */ +export declare function prewarm(): void; +/** + * Clears up resources that have previously been created by `prewarm()`. + * Note that this is typically not necessary. You should only call this function + * if you expect the user of your app to not return to a Map view at any point + * in your application. + * + * @example + * ```ts + * clearPrewarmedResources() + * ``` + */ +export declare function clearPrewarmedResources(): void; +/** + * Options object for GeoJSONSource. + */ +export type GeoJSONSourceOptions = GeoJSONSourceSpecification & { + workerOptions?: GeoJSONWorkerOptions; + collectResourceTiming?: boolean; + data: GeoJSON.GeoJSON | string; +}; +export type GeoJSONSourceInternalOptions = { + data?: GeoJSON.GeoJSON | string | undefined; + cluster?: boolean; + clusterMaxZoom?: number; + clusterRadius?: number; + clusterMinPoints?: number; + generateId?: boolean; +}; +/** + * The cluster options to set + */ +export type SetClusterOptions = { + /** + * Whether or not to cluster + */ + cluster?: boolean; + /** + * The cluster's max zoom + */ + clusterMaxZoom?: number; + /** + * The cluster's radius + */ + clusterRadius?: number; +}; +/** + * A source containing GeoJSON. + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-geojson) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'geojson', + * data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson' + * }); + * ``` + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'geojson', + * data: { + * "type": "FeatureCollection", + * "features": [{ + * "type": "Feature", + * "properties": {}, + * "geometry": { + * "type": "Point", + * "coordinates": [ + * -76.53063297271729, + * 39.18174077994108 + * ] + * } + * }] + * } + * }); + * ``` + * + * @example + * ```ts + * map.getSource('some id').setData({ + * "type": "FeatureCollection", + * "features": [{ + * "type": "Feature", + * "properties": { "name": "Null Island" }, + * "geometry": { + * "type": "Point", + * "coordinates": [ 0, 0 ] + * } + * }] + * }); + * ``` + * @see [Draw GeoJSON points](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-markers/) + * @see [Add a GeoJSON line](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-line/) + * @see [Create a heatmap from points](https://maplibre.org/maplibre-gl-js/docs/examples/heatmap-layer/) + * @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/cluster/) + */ +export declare class GeoJSONSource extends Evented implements Source { + type: "geojson"; + id: string; + minzoom: number; + maxzoom: number; + tileSize: number; + attribution: string; + promoteId: PromoteIdSpecification; + isTileClipped: boolean; + reparseOverscaled: boolean; + _data: GeoJSON.GeoJSON | string | undefined; + _options: GeoJSONSourceInternalOptions; + workerOptions: GeoJSONWorkerOptions; + map: Map$1; + actor: Actor; + _pendingLoads: number; + _collectResourceTiming: boolean; + _removed: boolean; + /** @internal */ + constructor(id: string, options: GeoJSONSourceOptions, dispatcher: Dispatcher, eventedParent: Evented); + load(): Promise; + onAdd(map: Map$1): void; + /** + * Sets the GeoJSON data and re-renders the map. + * + * @param data - A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files. + */ + setData(data: GeoJSON.GeoJSON | string): this; + /** + * Updates the source's GeoJSON, and re-renders the map. + * + * For sources with lots of features, this method can be used to make updates more quickly. + * + * This approach requires unique IDs for every feature in the source. The IDs can either be specified on the feature, + * or by using the promoteId option to specify which property should be used as the ID. + * + * It is an error to call updateData on a source that did not have unique IDs for each of its features already. + * + * Updates are applied on a best-effort basis, updating an ID that does not exist will not result in an error. + * + * @param diff - The changes that need to be applied. + */ + updateData(diff: GeoJSONSourceDiff): this; + /** + * Allows to get the source's actual GeoJSON data. + * + * @returns a promise which resolves to the source's actual GeoJSON data + */ + getData(): Promise; + /** + * To disable/enable clustering on the source options + * @param options - The options to set + * @example + * ```ts + * map.getSource('some id').setClusterOptions({cluster: false}); + * map.getSource('some id').setClusterOptions({cluster: false, clusterRadius: 50, clusterMaxZoom: 14}); + * ``` + */ + setClusterOptions(options: SetClusterOptions): this; + /** + * For clustered sources, fetches the zoom at which the given cluster expands. + * + * @param clusterId - The value of the cluster's `cluster_id` property. + * @returns a promise that is resolved with the zoom number + */ + getClusterExpansionZoom(clusterId: number): Promise; + /** + * For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features). + * + * @param clusterId - The value of the cluster's `cluster_id` property. + * @returns a promise that is resolved when the features are retrieved + */ + getClusterChildren(clusterId: number): Promise>; + /** + * For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features). + * + * @param clusterId - The value of the cluster's `cluster_id` property. + * @param limit - The maximum number of features to return. + * @param offset - The number of features to skip (e.g. for pagination). + * @returns a promise that is resolved when the features are retrieved + * @example + * Retrieve cluster leaves on click + * ```ts + * map.on('click', 'clusters', (e) => { + * let features = map.queryRenderedFeatures(e.point, { + * layers: ['clusters'] + * }); + * + * let clusterId = features[0].properties.cluster_id; + * let pointCount = features[0].properties.point_count; + * let clusterSource = map.getSource('clusters'); + * + * const features = await clusterSource.getClusterLeaves(clusterId, pointCount); + * // Print cluster leaves in the console + * console.log('Cluster leaves:', features); + * }); + * ``` + */ + getClusterLeaves(clusterId: number, limit: number, offset: number): Promise>; + /** + * Responsible for invoking WorkerSource's geojson.loadData target, which + * handles loading the geojson data and preparing to serve it up as tiles, + * using geojson-vt or supercluster as appropriate. + * @param diff - the diff object + */ + _updateWorkerData(diff?: GeoJSONSourceDiff): Promise; + loaded(): boolean; + loadTile(tile: Tile): Promise; + abortTile(tile: Tile): Promise; + unloadTile(tile: Tile): Promise; + onRemove(): void; + serialize(): GeoJSONSourceSpecification; + hasTransition(): boolean; +} +declare class TileBounds { + bounds: LngLatBounds; + minzoom: number; + maxzoom: number; + constructor(bounds: [ + number, + number, + number, + number + ], minzoom?: number | null, maxzoom?: number | null); + validateBounds(bounds: [ + number, + number, + number, + number + ]): LngLatBoundsLike; + contains(tileID: CanonicalTileID): boolean; +} +/** + * A source containing raster tiles (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * map.addSource('raster-source', { + * 'type': 'raster', + * 'tiles': ['https://tiles.stadiamaps.com/tiles/stamen_watercolor/{z}/{x}/{y}.jpg'], + * 'tileSize': 256, + * }); + * ``` + * + * @example + * ```ts + * map.addSource('wms-test-source', { + * 'type': 'raster', + * // use the tiles option to specify a WMS tile source URL + * 'tiles': [ + * 'https://img.nj.gov/imagerywms/Natural2015?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&transparent=true&width=256&height=256&layers=Natural2015' + * ], + * 'tileSize': 256 + * }); + * ``` + * @see [Add a raster tile source](https://maplibre.org/maplibre-gl-js/docs/examples/map-tiles/) + * @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/wms/) + * @see [Display a satellite map](https://maplibre.org/maplibre-gl-js/docs/examples/satellite-map/) + */ +export declare class RasterTileSource extends Evented implements Source { + type: "raster" | "raster-dem"; + id: string; + minzoom: number; + maxzoom: number; + url: string; + scheme: string; + tileSize: number; + bounds: [ + number, + number, + number, + number + ]; + tileBounds: TileBounds; + roundZoom: boolean; + dispatcher: Dispatcher; + map: Map$1; + tiles: Array; + _loaded: boolean; + _options: RasterSourceSpecification | RasterDEMSourceSpecification; + _tileJSONRequest: AbortController; + constructor(id: string, options: RasterSourceSpecification | RasterDEMSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented); + load(): Promise; + loaded(): boolean; + onAdd(map: Map$1): void; + onRemove(): void; + setSourceProperty(callback: Function): void; + /** + * Sets the source `tiles` property and re-renders the map. + * + * @param tiles - An array of one or more tile source URLs, as in the raster tiles spec (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) + */ + setTiles(tiles: Array): this; + /** + * Sets the source `url` property and re-renders the map. + * + * @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`. + */ + setUrl(url: string): this; + serialize(): RasterSourceSpecification | RasterDEMSourceSpecification; + hasTile(tileID: OverscaledTileID): boolean; + loadTile(tile: Tile): Promise; + abortTile(tile: Tile): Promise; + unloadTile(tile: Tile): Promise; + hasTransition(): boolean; +} +/** + * A source containing raster DEM tiles (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.) + * This source can be used to show hillshading and 3D terrain + * + * @group Sources + * + * @example + * ```ts + * map.addSource('raster-dem-source', { + * type: 'raster-dem', + * url: 'https://demotiles.maplibre.org/terrain-tiles/tiles.json', + * tileSize: 256 + * }); + * ``` + * @see [3D Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/3d-terrain/) + */ +export declare class RasterDEMTileSource extends RasterTileSource implements Source { + encoding: DEMEncoding; + redFactor?: number; + greenFactor?: number; + blueFactor?: number; + baseShift?: number; + constructor(id: string, options: RasterDEMSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented); + loadTile(tile: Tile): Promise; + readImageNow(img: ImageBitmap | HTMLImageElement): Promise; + _getNeighboringTiles(tileID: OverscaledTileID): {}; + unloadTile(tile: Tile): Promise; +} +export type VectorTileSourceOptions = VectorSourceSpecification & { + collectResourceTiming?: boolean; + tileSize?: number; +}; +/** + * A source containing vector tiles in [Mapbox Vector Tile format](https://docs.mapbox.com/vector-tiles/reference/). + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'vector', + * url: 'https://demotiles.maplibre.org/tiles/tiles.json' + * }); + * ``` + * + * @example + * ```ts + * map.addSource('some id', { + * type: 'vector', + * tiles: ['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt'], + * minzoom: 6, + * maxzoom: 14 + * }); + * ``` + * + * @example + * ```ts + * map.getSource('some id').setUrl("https://demotiles.maplibre.org/tiles/tiles.json"); + * ``` + * + * @example + * ```ts + * map.getSource('some id').setTiles(['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt']); + * ``` + * @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/vector-source/) + */ +export declare class VectorTileSource extends Evented implements Source { + type: "vector"; + id: string; + minzoom: number; + maxzoom: number; + url: string; + scheme: string; + tileSize: number; + promoteId: PromoteIdSpecification; + _options: VectorSourceSpecification; + _collectResourceTiming: boolean; + dispatcher: Dispatcher; + map: Map$1; + bounds: [ + number, + number, + number, + number + ]; + tiles: Array; + tileBounds: TileBounds; + reparseOverscaled: boolean; + isTileClipped: boolean; + _tileJSONRequest: AbortController; + _loaded: boolean; + constructor(id: string, options: VectorTileSourceOptions, dispatcher: Dispatcher, eventedParent: Evented); + load(): Promise; + loaded(): boolean; + hasTile(tileID: OverscaledTileID): boolean; + onAdd(map: Map$1): void; + setSourceProperty(callback: Function): void; + /** + * Sets the source `tiles` property and re-renders the map. + * + * @param tiles - An array of one or more tile source URLs, as in the TileJSON spec. + */ + setTiles(tiles: Array): this; + /** + * Sets the source `url` property and re-renders the map. + * + * @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`. + */ + setUrl(url: string): this; + onRemove(): void; + serialize(): VectorSourceSpecification; + loadTile(tile: Tile): Promise; + private _afterTileLoadWorkerResponse; + abortTile(tile: Tile): Promise; + unloadTile(tile: Tile): Promise; + hasTransition(): boolean; +} +/** + * A data source containing video. + * (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-video) for detailed documentation of options.) + * + * @group Sources + * + * @example + * ```ts + * // add to map + * map.addSource('some id', { + * type: 'video', + * url: [ + * 'https://www.mapbox.com/blog/assets/baltimore-smoke.mp4', + * 'https://www.mapbox.com/blog/assets/baltimore-smoke.webm' + * ], + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update + * let mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * map.removeSource('some id'); // remove + * ``` + * @see [Add a video](https://maplibre.org/maplibre-gl-js/docs/examples/video-on-a-map/) + * + * Note that when rendered as a raster layer, the layer's `raster-fade-duration` property will cause the video to fade in. + * This happens when playback is started, paused and resumed, or when the video's coordinates are updated. To avoid this behavior, + * set the layer's `raster-fade-duration` property to `0`. + */ +export declare class VideoSource extends ImageSource { + options: VideoSourceSpecification; + urls: Array; + video: HTMLVideoElement; + roundZoom: boolean; + constructor(id: string, options: VideoSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented); + load(): Promise; + /** + * Pauses the video. + */ + pause(): void; + /** + * Plays the video. + */ + play(): void; + /** + * Sets playback to a timestamp, in seconds. + */ + seek(seconds: number): void; + /** + * Returns the HTML `video` element. + * + * @returns The HTML `video` element. + */ + getVideo(): HTMLVideoElement; + onAdd(map: Map$1): void; + /** + * Sets the video's coordinates and re-renders the map. + */ + prepare(): this; + serialize(): VideoSourceSpecification; + hasTransition(): boolean; +} +/** + * Adds a custom load resource function that will be called when using a URL that starts with a custom url schema. + * This will happen in the main thread, and workers might call it if they don't know how to handle the protocol. + * The example below will be triggered for custom:// urls defined in the sources list in the style definitions. + * The function passed will receive the request parameters and should return with the resulting resource, + * for example a pbf vector tile, non-compressed, represented as ArrayBuffer. + * + * @param customProtocol - the protocol to hook, for example 'custom' + * @param loadFn - the function to use when trying to fetch a tile specified by the customProtocol + * @example + * ```ts + * // This will fetch a file using the fetch API (this is obviously a non interesting example...) + * addProtocol('custom', async (params, abortController) => { + * const t = await fetch(`https://${params.url.split("://")[1]}`); + * if (t.status == 200) { + * const buffer = await t.arrayBuffer(); + * return {data: buffer} + * } else { + * throw new Error(`Tile fetch error: ${t.statusText}`); + * } + * }); + * // the following is an example of a way to return an error when trying to load a tile + * addProtocol('custom2', async (params, abortController) => { + * throw new Error('someErrorMessage')); + * }); + * ``` + */ +export declare function addProtocol(customProtocol: string, loadFn: AddProtocolAction): void; +/** + * Removes a previously added protocol in the main thread. + * + * @param customProtocol - the custom protocol to remove registration for + * @example + * ```ts + * removeProtocol('custom'); + * ``` + */ +export declare function removeProtocol(customProtocol: string): void; +/** + * Sets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text). + * Necessary for supporting the Arabic and Hebrew languages, which are written right-to-left. + * + * @param pluginURL - URL pointing to the Mapbox RTL text plugin source. + * @param lazy - If set to `true`, maplibre will defer loading the plugin until rtl text is encountered, + * rtl text will then be rendered only after the plugin finishes loading. + * @example + * ```ts + * setRTLTextPlugin('https://unpkg.com/@mapbox/mapbox-gl-rtl-text@0.2.3/mapbox-gl-rtl-text.js', false); + * ``` + * @see [Add support for right-to-left scripts](https://maplibre.org/maplibre-gl-js/docs/examples/mapbox-gl-rtl-text/) + */ +export declare function setRTLTextPlugin(pluginURL: string, lazy: boolean): Promise; +/** + * Gets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text) status. + * The status can be `unavailable` (i.e. not requested or removed), `loading`, `loaded` or `error`. + * If the status is `loaded` and the plugin is requested again, an error will be thrown. + * + * @example + * ```ts + * const pluginStatus = getRTLTextPluginStatus(); + * ``` + */ +export declare function getRTLTextPluginStatus(): string; +/** + * Returns the package version of the library + * @returns Package version of the library + */ +export declare function getVersion(): string; +/** + * Gets the number of web workers instantiated on a page with GL JS maps. + * By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3). + * Make sure to set this property before creating any map instances for it to have effect. + * + * @returns Number of workers currently configured. + * @example + * ```ts + * const workerCount = getWorkerCount() + * ``` + */ +export declare function getWorkerCount(): number; +/** + * Sets the number of web workers instantiated on a page with GL JS maps. + * By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3). + * Make sure to set this property before creating any map instances for it to have effect. + * + * @example + * ```ts + * setWorkerCount(2); + * ``` + */ +export declare function setWorkerCount(count: number): void; +/** + * Gets and sets the maximum number of images (raster tiles, sprites, icons) to load in parallel, + * which affects performance in raster-heavy maps. 16 by default. + * + * @returns Number of parallel requests currently configured. + * @example + * ```ts + * getMaxParallelImageRequests(); + * ``` + */ +export declare function getMaxParallelImageRequests(): number; +/** + * Sets the maximum number of images (raster tiles, sprites, icons) to load in parallel, + * which affects performance in raster-heavy maps. 16 by default. + * + * @example + * ```ts + * setMaxParallelImageRequests(10); + * ``` + */ +export declare function setMaxParallelImageRequests(numRequests: number): void; +/** + * Gets the worker url + * @returns The worker url + */ +export declare function getWorkerUrl(): string; +/** + * Sets the worker url + */ +export declare function setWorkerUrl(value: string): void; +/** + * Allows loading javascript code in the worker thread. + * *Note* that since this is using some very internal classes and flows it is considered experimental and can break at any point. + * + * It can be useful for the following examples: + * 1. Using `self.addProtocol` in the worker thread - note that you might need to also register the protocol on the main thread. + * 2. Using `self.registerWorkerSource(workerSource: WorkerSource)` to register a worker source, which should come with `addSourceType` usually. + * 3. using `self.actor.registerMessageHandler` to override some internal worker operations + * @param workerUrl - the worker url e.g. a url of a javascript file to load in the worker + * @returns + * + * @example + * ```ts + * // below is an example of sending a js file to the worker to load the method there + * // Note that you'll need to call the global function `addProtocol` in the worker to register the protocol there. + * // add-protocol-worker.js + * async function loadFn(params, abortController) { + * const t = await fetch(`https://${params.url.split("://")[1]}`); + * if (t.status == 200) { + * const buffer = await t.arrayBuffer(); + * return {data: buffer} + * } else { + * throw new Error(`Tile fetch error: ${t.statusText}`); + * } + * } + * self.addProtocol('custom', loadFn); + * + * // main.js + * importScriptInWorkers('add-protocol-worker.js'); + * ``` + */ +export declare function importScriptInWorkers(workerUrl: string): Promise; +export type * from "@maplibre/maplibre-gl-style-spec"; + +export { + Color, + CompositeExpression, + DiffCommand, + DiffOperations, + Feature, + FeatureFilter, + FeatureState, + FilterSpecification, + Formatted, + FormattedSection, + GeoJSONSourceSpecification, + GlobalProperties, + ICanonicalTileID, + IMercatorCoordinate, + ImageSourceSpecification, + InterpolationType, + LayerSpecification, + LightSpecification, + Map$1 as Map, + Padding, + Point, + PromoteIdSpecification, + PropertyValueSpecification, + RasterDEMSourceSpecification, + RasterSourceSpecification, + ResolvedImage, + SkySpecification, + SourceExpression, + SourceSpecification, + SpriteSpecification, + StylePropertyExpression, + StylePropertySpecification, + StyleSpecification, + TerrainSpecification, + TransitionSpecification, + VariableAnchorOffsetCollection, + VectorSourceSpecification, + VideoSourceSpecification, +}; + +export as namespace maplibregl; + +export {}; diff --git a/dist/maplibre-gl.js b/dist/maplibre-gl.js new file mode 100644 index 0000000000..b3d66d64a3 --- /dev/null +++ b/dist/maplibre-gl.js @@ -0,0 +1,59 @@ +/** + * MapLibre GL JS + * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v4.7.0/LICENSE.txt + */ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.maplibregl = factory()); +})(this, (function () { 'use strict'; + +/* eslint-disable */ + +var maplibregl = {}; +var modules = {}; +function define(moduleName, _dependencies, moduleFactory) { + modules[moduleName] = moduleFactory; + + // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) + if (moduleName !== 'index') { + return; + } + + // we assume that when an index module is initializing then other modules are loaded already + var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);' + + var sharedModule = {}; + // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) + // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) + // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following + modules.shared(sharedModule); + modules.index(maplibregl, sharedModule); + + if (typeof window !== 'undefined') { + maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); + } + + return maplibregl; +}; + + + +define("shared",["exports"],(function(t){"use strict";function e(t,e,r,n){return new(r||(r=Promise))((function(i,s){function a(t){try{l(n.next(t));}catch(t){s(t);}}function o(t){try{l(n.throw(t));}catch(t){s(t);}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e);}))).then(a,o);}l((n=n.apply(t,e||[])).next());}))}function r(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}"function"==typeof SuppressedError&&SuppressedError;var n=i;function i(t,e){this.x=t,this.y=e;}i.prototype={clone:function(){return new i(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},i.convert=function(t){return t instanceof i?t:Array.isArray(t)?new i(t[0],t[1]):t};var s=r(n),a=o;function o(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}o.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}};var l=r(a);let u,c;function h(){return null==u&&(u="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),u}function p(){if(null==c&&(c=!1,h())){const t=5,e=new OffscreenCanvas(t,t).getContext("2d",{willReadFrequently:!0});if(e){for(let r=0;ri.solve(t)}const d=f(.25,.1,.25,1);function y(t,e,r){return Math.min(r,Math.max(e,t))}function m(t,e,r){const n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function g(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}let x=1;function v(t,e,r){const n={};for(const r in t)n[r]=e.call(this,t[r],r,t);return n}function b(t,e,r){const n={};for(const r in t)e.call(this,t[r],r,t)&&(n[r]=t[r]);return n}function w(t){return Array.isArray(t)?t.map(w):"object"==typeof t&&t?v(t,w):t}const _={};function A(t){_[t]||("undefined"!=typeof console&&console.warn(t),_[t]=!0);}function S(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function k(t){return "undefined"!=typeof WorkerGlobalScope&&void 0!==t&&t instanceof WorkerGlobalScope}let M=null;function I(t){return "undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const z="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function P(t,r,n,i,s){return e(this,void 0,void 0,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const e=new VideoFrame(t,{timestamp:0});try{const a=null==e?void 0:e.format;if(!a||!a.startsWith("BGR")&&!a.startsWith("RGB"))throw new Error(`Unrecognized format ${a}`);const o=a.startsWith("BGR"),l=new Uint8ClampedArray(i*s*4);if(yield e.copyTo(l,function(t,e,r,n,i){const s=4*Math.max(-e,0),a=(Math.max(0,r)-r)*n*4+s,o=4*n,l=Math.max(0,e),u=Math.max(0,r);return {rect:{x:l,y:u,width:Math.min(t.width,e+n)-l,height:Math.min(t.height,r+i)-u},layout:[{offset:a,stride:o}]}}(t,r,n,i,s)),o)for(let t=0;tk(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,O=function(t,r){if(/:\/\//.test(t.url)&&!/^https?:|^file:/.test(t.url)){const e=T(t.url);if(e)return e(t,r);if(k(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,targetMapId:$},r)}if(!(/^file:/.test(n=t.url)||/^file:/.test(D())&&!/^\w+:/.test(n))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(t,r){return e(this,void 0,void 0,(function*(){const e=new Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,cache:t.cache,referrer:D(),signal:r.signal});"json"!==t.type||e.headers.has("Accept")||e.headers.set("Accept","application/json");const n=yield fetch(e);if(!n.ok){const e=yield n.blob();throw new L(n.status,n.statusText,t.url,e)}let i;i="arrayBuffer"===t.type||"image"===t.type?n.arrayBuffer():"json"===t.type?n.json():n.text();const s=yield i;if(r.signal.aborted)throw E();return {data:s,cacheControl:n.headers.get("Cache-Control"),expires:n.headers.get("Expires")}}))}(t,r);if(k(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,mustQueue:!0,targetMapId:$},r)}var n;return function(t,e){return new Promise(((r,n)=>{var i;const s=new XMLHttpRequest;s.open(t.method||"GET",t.url,!0),"arrayBuffer"!==t.type&&"image"!==t.type||(s.responseType="arraybuffer");for(const e in t.headers)s.setRequestHeader(e,t.headers[e]);"json"===t.type&&(s.responseType="text",(null===(i=t.headers)||void 0===i?void 0:i.Accept)||s.setRequestHeader("Accept","application/json")),s.withCredentials="include"===t.credentials,s.onerror=()=>{n(new Error(s.statusText));},s.onload=()=>{if(!e.signal.aborted)if((s.status>=200&&s.status<300||0===s.status)&&null!==s.response){let e=s.response;if("json"===t.type)try{e=JSON.parse(s.response);}catch(t){return void n(t)}r({data:e,cacheControl:s.getResponseHeader("Cache-Control"),expires:s.getResponseHeader("Expires")});}else {const e=new Blob([s.response],{type:s.getResponseHeader("Content-Type")});n(new L(s.status,s.statusText,t.url,e));}},e.signal.addEventListener("abort",(()=>{s.abort(),n(E());})),s.send(t.body);}))}(t,r)};function j(t){if(!t||t.indexOf("://")<=0||0===t.indexOf("data:image/")||0===t.indexOf("blob:"))return !0;const e=new URL(t),r=window.location;return e.protocol===r.protocol&&e.host===r.host}function R(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function U(t,e,r){if(r&&r[t]){const n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}class q{constructor(t,e={}){g(this,e),this.type=t;}}class N extends q{constructor(t,e={}){super("error",g({error:t},e));}}class Z{on(t,e){return this._listeners=this._listeners||{},R(t,e,this._listeners),this}off(t,e){return U(t,e,this._listeners),U(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},R(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new q(t,e||{}));const r=t.type;if(this.listens(r)){t.target=this;const e=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];for(const r of e)r.call(this,t);const n=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];for(const e of n)U(r,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(g(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t));}else t instanceof N&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var G={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"enum",default:"mercator",values:{mercator:{},globe:{}}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const K=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function X(t,e){const r={};for(const e in t)"ref"!==e&&(r[e]=t[e]);return K.forEach((t=>{t in e&&(r[t]=e[t]);})),r}function H(t,e){if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return !1;for(let r=0;r`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const _t=[lt,ut,ct,ht,pt,mt,ft,bt(dt),gt,xt,vt];function At(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!At(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of _t)if(!At(t,e))return null}return `Expected ${wt(t)} but found ${wt(e)} instead.`}function St(t,e){return e.some((e=>e.kind===t.kind))}function kt(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function Mt(t,e){return "array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const It=.96422,zt=.82521,Pt=4/29,Ct=6/29,Bt=3*Ct*Ct,Vt=Ct*Ct*Ct,Et=Math.PI/180,Ft=180/Math.PI;function Tt(t){return (t%=360)<0&&(t+=360),t}function $t([t,e,r,n]){let i,s;const a=Dt((.2225045*(t=Lt(t))+.7168786*(e=Lt(e))+.0606169*(r=Lt(r)))/1);t===e&&e===r?i=s=a:(i=Dt((.4360747*t+.3850649*e+.1430804*r)/It),s=Dt((.0139322*t+.0971045*e+.7141733*r)/zt));const o=116*a-16;return [o<0?0:o,500*(i-a),200*(a-s),n]}function Lt(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Dt(t){return t>Vt?Math.pow(t,1/3):t/Bt+Pt}function Ot([t,e,r,n]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,a=isNaN(r)?i:i-r/200;return i=1*Rt(i),s=It*Rt(s),a=zt*Rt(a),[jt(3.1338561*s-1.6168667*i-.4906146*a),jt(-.9787684*s+1.9161415*i+.033454*a),jt(.0719453*s-.2289914*i+1.4052427*a),n]}function jt(t){return (t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function Rt(t){return t>Ct?t*t*t:Bt*(t-Pt)}function Ut(t){return parseInt(t.padEnd(2,t),16)/255}function qt(t,e){return Nt(e?t/100:t,0,1)}function Nt(t,e,r){return Math.min(Math.max(e,t),r)}function Zt(t){return !t.some(Number.isNaN)}const Gt={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};class Kt{constructor(t,e,r,n=1,i=!0){this.r=t,this.g=e,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[t,e,r,n]));}static parse(t){if(t instanceof Kt)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return [0,0,0,0];const e=Gt[t];if(e){const[t,r,n]=e;return [t/255,r/255,n/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let r=1;return [Ut(t.slice(r,r+=e)),Ut(t.slice(r,r+=e)),Ut(t.slice(r,r+=e)),Ut(t.slice(r,r+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,r,n,i,s,a,o,l,u,c,h,p]=e,f=[i||" ",o||" ",c].join("");if(" "===f||" /"===f||",,"===f||",,,"===f){const t=[n,a,u].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[Nt(+r/e,0,1),Nt(+s/e,0,1),Nt(+l/e,0,1),h?qt(+h,p):1];if(Zt(t))return t}}return}}const r=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[t,e,n,i,s,a,o,l,u]=r,c=[n||" ",s||" ",o].join("");if(" "===c||" /"===c||",,"===c||",,,"===c){const t=[+e,Nt(+i,0,100),Nt(+a,0,100),l?qt(+l,u):1];if(Zt(t))return function([t,e,r,n]){function i(n){const i=(n+t/30)%12,s=e*Math.min(r,1-r);return r-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=Tt(t),e/=100,r/=100,[i(0),i(8),i(4),n]}(t)}}}(t);return e?new Kt(...e,!1):void 0}get rgb(){const{r:t,g:e,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[t/i,e/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,r,n,i]=$t(t),s=Math.sqrt(r*r+n*n);return [Math.round(1e4*s)?Tt(Math.atan2(n,r)*Ft):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",$t(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,r,n]=this.rgb;return `rgba(${[t,e,r].map((t=>Math.round(255*t))).join(",")},${n})`}}Kt.black=new Kt(0,0,0,1),Kt.white=new Kt(1,1,1,1),Kt.transparent=new Kt(0,0,0,0),Kt.red=new Kt(1,0,0,1);class Xt{constructor(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class Ht{constructor(t,e,r,n,i){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i;}}class Yt{constructor(t){this.sections=t;}static fromString(t){return new Yt([new Ht(t,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof Yt?t:Yt.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class Jt{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Jt)return t;if("number"==typeof t)return new Jt([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]];}return new Jt(t)}}toString(){return JSON.stringify(this.values)}}const Wt=new Set(["center","left","right","top","bottom","top-left","top-right","bottom-left","bottom-right"]);class Qt{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof Qt)return t;if(Array.isArray(t)&&!(t.length<1)&&t.length%2==0){for(let e=0;e=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[t,e,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function re(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof Kt||t instanceof Xt||t instanceof Yt||t instanceof Jt||t instanceof Qt||t instanceof te)return !0;if(Array.isArray(t)){for(const e of t)if(!re(e))return !1;return !0}if("object"==typeof t){for(const e in t)if(!re(t[e]))return !1;return !0}return !1}function ne(t){if(null===t)return lt;if("string"==typeof t)return ct;if("boolean"==typeof t)return ht;if("number"==typeof t)return ut;if(t instanceof Kt)return pt;if(t instanceof Xt)return yt;if(t instanceof Yt)return mt;if(t instanceof Jt)return gt;if(t instanceof Qt)return vt;if(t instanceof te)return xt;if(Array.isArray(t)){const e=t.length;let r;for(const e of t){const t=ne(e);if(r){if(r===t)continue;r=dt;break}r=t;}return bt(r||dt,e)}return ft}function ie(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof Kt||t instanceof Yt||t instanceof Jt||t instanceof Qt||t instanceof te?t.toString():JSON.stringify(t)}class se{constructor(t,e){this.type=t,this.value=e;}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!re(t[1]))return e.error("invalid value");const r=t[1];let n=ne(r);const i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new se(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return !0}}class ae{constructor(t){this.name="ExpressionEvaluationError",this.message=t;}toJSON(){return this.message}}const oe={string:ct,number:ut,boolean:ht,object:ft};class le{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r,n=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const r=t[1];if("string"!=typeof r||!(r in oe)||"object"===r)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=oe[r],n++;}else i=dt;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],n++;}r=bt(i,s);}else {if(!oe[i])throw new Error(`Types doesn't contain name = ${i}`);r=oe[i];}const s=[];for(;nt.outputDefined()))}}const ue={"to-boolean":ht,"to-color":pt,"to-number":ut,"to-string":ct};class ce{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[0];if(!ue[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");const n=ue[r],i=[];for(let r=1;r4?`Invalid rbga value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:ee(e[0],e[1],e[2],e[3]),!r))return new Kt(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new ae(r||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"padding":{let e;for(const r of this.args){e=r.evaluate(t);const n=Jt.parse(e);if(n)return n}throw new ae(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"variableAnchorOffsetCollection":{let e;for(const r of this.args){e=r.evaluate(t);const n=Qt.parse(e);if(n)return n}throw new ae(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"number":{let e=null;for(const r of this.args){if(e=r.evaluate(t),null===e)return 0;const n=Number(e);if(!isNaN(n))return n}throw new ae(`Could not convert ${JSON.stringify(e)} to number.`)}case"formatted":return Yt.fromString(ie(this.args[0].evaluate(t)));case"resolvedImage":return te.fromString(ie(this.args[0].evaluate(t)));default:return ie(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}const he=["Unknown","Point","LineString","Polygon"];class pe{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null;}id(){return this.feature&&"id"in this.feature?this.feature.id:null}geometryType(){return this.feature?"number"==typeof this.feature.type?he[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(t){let e=this._parseColorCache[t];return e||(e=this._parseColorCache[t]=Kt.parse(t)),e}}class fe{constructor(t,e,r=[],n,i=new ot,s=[]){this.registry=t,this.path=r,this.key=r.map((t=>`[${t}]`)).join(""),this.scope=i,this.errors=s,this.expectedType=n,this._isConstant=e;}parse(t,e,r,n,i={}){return e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)}_parse(t,e){function r(t,e,r){return "assert"===r?new le(e,[t]):"coerce"===r?new ce(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const n=t[0];if("string"!=typeof n)return this.error(`Expression name must be a string, but found ${typeof n} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[n];if(i){let n=i.parse(t,this);if(!n)return null;if(this.expectedType){const t=this.expectedType,i=n.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind)if("color"!==t.kind&&"formatted"!==t.kind&&"resolvedImage"!==t.kind||"value"!==i.kind&&"string"!==i.kind)if("padding"!==t.kind||"value"!==i.kind&&"number"!==i.kind&&"array"!==i.kind)if("variableAnchorOffsetCollection"!==t.kind||"value"!==i.kind&&"array"!==i.kind){if(this.checkSubtype(t,i))return null}else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"assert");}if(!(n instanceof se)&&"resolvedImage"!==n.type.kind&&this._isConstant(n)){const t=new pe;try{n=new se(n.type,n.evaluate(t));}catch(t){return this.error(t.message),null}}return n}return this.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,r){const n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new fe(this.registry,this._isConstant,n,e||null,i,this.errors)}error(t,...e){const r=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new at(r,t));}checkSubtype(t,e){const r=At(t,e);return r&&this.error(r),r}}class de{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result);}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const r=[];for(let n=1;n=r.length)throw new ae(`Array index out of bounds: ${e} > ${r.length-1}.`);if(e!==Math.floor(e))throw new ae(`Array index must be an integer, but found ${e} instead.`);return r[e]}eachChild(t){t(this.index),t(this.input);}outputDefined(){return !1}}class ge{constructor(t,e){this.type=ht,this.needle=t,this.haystack=e;}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,dt),n=e.parse(t[2],2,dt);return r&&n?St(r.type,[ht,ct,ut,lt,dt])?new ge(r,n):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${wt(r.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return !1;if(!kt(e,["boolean","string","number","null"]))throw new ae(`Expected first argument to be of type boolean, string, number or null, but found ${wt(ne(e))} instead.`);if(!kt(r,["string","array"]))throw new ae(`Expected second argument to be of type array or string, but found ${wt(ne(r))} instead.`);return r.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack);}outputDefined(){return !0}}class xe{constructor(t,e,r){this.type=ut,this.needle=t,this.haystack=e,this.fromIndex=r;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,dt),n=e.parse(t[2],2,dt);if(!r||!n)return null;if(!St(r.type,[ht,ct,ut,lt,dt]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${wt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,ut);return i?new xe(r,n,i):null}return new xe(r,n)}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!kt(e,["boolean","string","number","null"]))throw new ae(`Expected first argument to be of type boolean, string, number or null, but found ${wt(ne(e))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(t)),kt(r,["string"])){const t=r.indexOf(e,n);return -1===t?-1:[...r.slice(0,t)].length}if(kt(r,["array"]))return r.indexOf(e,n);throw new ae(`Expected second argument to be of type array or string, but found ${wt(ne(r))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);}outputDefined(){return !1}}class ve{constructor(t,e,r,n,i,s){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=s;}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const i={},s=[];for(let a=2;aNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return u.error("Numeric branch labels must be integer values.");if(r){if(u.checkSubtype(r,ne(t)))return null}else r=ne(t);if(void 0!==i[String(t)])return u.error("Branch labels must be unique.");i[String(t)]=s.length;}const c=e.parse(l,a,n);if(!c)return null;n=n||c.type,s.push(c);}const a=e.parse(t[1],1,dt);if(!a)return null;const o=e.parse(t[t.length-1],t.length-1,n);return o?"value"!==a.type.kind&&e.concat(1).checkSubtype(r,a.type)?null:new ve(r,n,a,i,s,o):null}evaluate(t){const e=this.input.evaluate(t);return (ne(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class be{constructor(t,e,r){this.type=t,this.branches=e,this.otherwise=r;}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const n=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}}class we{constructor(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,dt),n=e.parse(t[2],2,ut);if(!r||!n)return null;if(!St(r.type,[bt(dt),ct,dt]))return e.error(`Expected first argument to be of type array or string, but found ${wt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,ut);return i?new we(r.type,r,n,i):null}return new we(r.type,r,n)}evaluate(t){const e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);let n;if(this.endIndex&&(n=this.endIndex.evaluate(t)),kt(e,["string"]))return [...e].slice(r,n).join("");if(kt(e,["array"]))return e.slice(r,n);throw new ae(`Expected first argument to be of type array or string, but found ${wt(ne(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);}outputDefined(){return !1}}function _e(t,e){const r=t.length-1;let n,i,s=0,a=r,o=0;for(;s<=a;)if(o=Math.floor((s+a)/2),n=t[o],i=t[o+1],n<=e){if(o===r||ee))throw new ae("Input is not a number.");a=o-1;}return 0}class Ae{constructor(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of r)this.labels.push(t),this.outputs.push(e);}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const r=e.parse(t[1],1,ut);if(!r)return null;const n=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let r=1;r=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',o);const u=e.parse(a,l,i);if(!u)return null;i=i||u.type,n.push([s,u]);}return new Ae(i,r,n)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[_e(e,n)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function Se(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ke=Me;function Me(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}Me.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(void 0===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}};var Ie=Se(ke);function ze(t,e,r){return t+r*(e-t)}function Pe(t,e,r){return t.map(((t,n)=>ze(t,e[n],r)))}const Ce={number:ze,color:function(t,e,r,n="rgb"){switch(n){case"rgb":{const[n,i,s,a]=Pe(t.rgb,e.rgb,r);return new Kt(n,i,s,a,!1)}case"hcl":{const[n,i,s,a]=t.hcl,[o,l,u,c]=e.hcl;let h,p;if(isNaN(n)||isNaN(o))isNaN(n)?isNaN(o)?h=NaN:(h=o,1!==s&&0!==s||(p=l)):(h=n,1!==u&&0!==u||(p=i));else {let t=o-n;o>n&&t>180?t-=360:o180&&(t+=360),h=n+r*t;}const[f,d,y,m]=function([t,e,r,n]){return t=isNaN(t)?0:t*Et,Ot([r,Math.cos(t)*e,Math.sin(t)*e,n])}([h,null!=p?p:ze(i,l,r),ze(s,u,r),ze(a,c,r)]);return new Kt(f,d,y,m,!1)}case"lab":{const[n,i,s,a]=Ot(Pe(t.lab,e.lab,r));return new Kt(n,i,s,a,!1)}}},array:Pe,padding:function(t,e,r){return new Jt(Pe(t.values,e.values,r))},variableAnchorOffsetCollection:function(t,e,r){const n=t.values,i=e.values;if(n.length!==i.length)throw new ae(`Cannot interpolate values of different length. from: ${t.toString()}, to: ${e.toString()}`);const s=[];for(let t=0;t"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:t};}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,ut),!i)return null;const a=[];let o=null;"interpolate-hcl"===r||"interpolate-lab"===r?o=pt:e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType);for(let t=0;t=r)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(n,l,o);if(!u)return null;o=o||u.type,a.push([r,u]);}return Mt(o,ut)||Mt(o,pt)||Mt(o,gt)||Mt(o,vt)||Mt(o,bt(ut))?new Be(o,r,n,i,a):e.error(`Type ${wt(o)} is not interpolatable.`)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);const s=_e(e,n),a=Be.interpolationFactor(this.interpolation,n,e[s],e[s+1]),o=r[s].evaluate(t),l=r[s+1].evaluate(t);switch(this.operator){case"interpolate":return Ce[this.type.kind](o,l,a);case"interpolate-hcl":return Ce.color(o,l,a,"hcl");case"interpolate-lab":return Ce.color(o,l,a,"lab")}}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function Ve(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}class Ee{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expectected at least one argument.");let r=null;const n=e.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const n of t.slice(1)){const t=e.parse(n,1+i.length,r,void 0,{typeAnnotation:"omit"});if(!t)return null;r=r||t.type,i.push(t);}if(!r)throw new Error("No output type");const s=n&&i.some((t=>At(n,t.type)));return new Ee(s?dt:r,i)}evaluate(t){let e,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(t),r&&r instanceof te&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null!==r)break;return r}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function Fe(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function Te(t,e,r,n){return 0===n.compare(e,r)}function $e(t,e,r){const n="=="!==t&&"!="!==t;return class i{constructor(t,e,r){this.type=ht,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const r=t[0];let s=e.parse(t[1],1,dt);if(!s)return null;if(!Fe(r,s.type))return e.concat(1).error(`"${r}" comparisons are not supported for type '${wt(s.type)}'.`);let a=e.parse(t[2],2,dt);if(!a)return null;if(!Fe(r,a.type))return e.concat(2).error(`"${r}" comparisons are not supported for type '${wt(a.type)}'.`);if(s.type.kind!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error(`Cannot compare types '${wt(s.type)}' and '${wt(a.type)}'.`);n&&("value"===s.type.kind&&"value"!==a.type.kind?s=new le(a.type,[s]):"value"!==s.type.kind&&"value"===a.type.kind&&(a=new le(s.type,[a])));let o=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error("Cannot use collator to compare non-string types.");if(o=e.parse(t[3],3,yt),!o)return null}return new i(s,a,o)}evaluate(i){const s=this.lhs.evaluate(i),a=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const e=ne(s),r=ne(a);if(e.kind!==r.kind||"string"!==e.kind&&"number"!==e.kind)throw new ae(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const t=ne(s),r=ne(a);if("string"!==t.kind||"string"!==r.kind)return e(i,s,a)}return this.collator?r(i,s,a,this.collator.evaluate(i)):e(i,s,a)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);}outputDefined(){return !0}}}const Le=$e("==",(function(t,e,r){return e===r}),Te),De=$e("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !Te(0,e,r,n)})),Oe=$e("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),Re=$e("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),Ue=$e(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0}));class qe{constructor(t,e,r){this.type=yt,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");const n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,ht);if(!n)return null;const i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,ht);if(!i)return null;let s=null;return r.locale&&(s=e.parse(r.locale,1,ct),!s)?null:new qe(n,i,s)}evaluate(t){return new Xt(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);}outputDefined(){return !1}}class Ne{constructor(t,e,r,n,i){this.type=ct,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,ut);if(!r)return null;const n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=e.parse(n.locale,1,ct),!i))return null;let s=null;if(n.currency&&(s=e.parse(n.currency,1,ct),!s))return null;let a=null;if(n["min-fraction-digits"]&&(a=e.parse(n["min-fraction-digits"],1,ut),!a))return null;let o=null;return n["max-fraction-digits"]&&(o=e.parse(n["max-fraction-digits"],1,ut),!o)?null:new Ne(r,i,s,a,o)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);}outputDefined(){return !1}}class Ze{constructor(t){this.type=mt,this.sections=t;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");const n=[];let i=!1;for(let r=1;r<=t.length-1;++r){const s=t[r];if(i&&"object"==typeof s&&!Array.isArray(s)){i=!1;let t=null;if(s["font-scale"]&&(t=e.parse(s["font-scale"],1,ut),!t))return null;let r=null;if(s["text-font"]&&(r=e.parse(s["text-font"],1,bt(ct)),!r))return null;let a=null;if(s["text-color"]&&(a=e.parse(s["text-color"],1,pt),!a))return null;const o=n[n.length-1];o.scale=t,o.font=r,o.textColor=a;}else {const s=e.parse(t[r],1,dt);if(!s)return null;const a=s.type.kind;if("string"!==a&&"value"!==a&&"null"!==a&&"resolvedImage"!==a)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:s,scale:null,font:null,textColor:null});}}return new Ze(n)}evaluate(t){return new Yt(this.sections.map((e=>{const r=e.content.evaluate(t);return ne(r)===xt?new Ht("",r,null,null,null):new Ht(ie(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor);}outputDefined(){return !1}}class Ge{constructor(t){this.type=xt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,ct);return r?new Ge(r):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),r=te.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r}eachChild(t){t(this.input);}outputDefined(){return !1}}class Ke{constructor(t){this.type=ut,this.input=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error(`Expected argument of type string or array, but found ${wt(r.type)} instead.`):new Ke(r):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return [...e].length;if(Array.isArray(e))return e.length;throw new ae(`Expected value to be of type string or array, but found ${wt(ne(e))} instead.`)}eachChild(t){t(this.input);}outputDefined(){return !1}}const Xe=8192;function He(t,e){const r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*Xe),Math.round(n*i*Xe)]}function Ye(t,e){const r=Math.pow(2,e.z);return [(i=(t[0]/Xe+e.x)/r,360*i-180),(n=(t[1]/Xe+e.y)/r,360/Math.PI*Math.atan(Math.exp((180-360*n)*Math.PI/180))-90)];var n,i;}function Je(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function We(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function Qe(t,e,r){const n=t[0]-e[0],i=t[1]-e[1],s=t[0]-r[0],a=t[1]-r[1];return n*a-s*i==0&&n*s<=0&&i*a<=0}function tr(t,e,r,n){return 0!=(i=[n[0]-r[0],n[1]-r[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!ar(t,e,r,n)||!ar(r,n,t,e));var i,s;}function er(t,e,r){for(const n of r)for(let r=0;r(i=t)[1]!=(a=o[e+1])[1]>i[1]&&i[0]<(a[0]-s[0])*(i[1]-s[1])/(a[1]-s[1])+s[0]&&(n=!n);}var i,s,a;return n}function nr(t,e){for(const r of e)if(rr(t,r))return !0;return !1}function ir(t,e){for(const r of t)if(!rr(r,e))return !1;for(let r=0;r0&&o<0||a<0&&o>0}function or(t,e,r){const n=[];for(let i=0;ir[2]){const e=.5*n;let i=t[0]-r[0]>e?-n:r[0]-t[0]>e?n:0;0===i&&(i=t[0]-r[2]>e?-n:r[2]-t[0]>e?n:0),t[0]+=i;}Je(e,t);}function cr(t,e,r,n){const i=Math.pow(2,n.z)*Xe,s=[n.x*Xe,n.y*Xe],a=[];for(const n of t)for(const t of n){const n=[t.x+s[0],t.y+s[1]];ur(n,e,r,i),a.push(n);}return a}function hr(t,e,r,n){const i=Math.pow(2,n.z)*Xe,s=[n.x*Xe,n.y*Xe],a=[];for(const r of t){const t=[];for(const n of r){const r=[n.x+s[0],n.y+s[1]];Je(e,r),t.push(r);}a.push(t);}if(e[2]-e[0]<=i/2){(o=e)[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(const t of a)for(const n of t)ur(n,e,r,i);}var o;return a}class pr{constructor(t,e){this.type=ht,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(re(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const r of e.features){const{type:e,coordinates:n}=r.geometry;"Polygon"===e&&t.push(n),"MultiPolygon"===e&&t.push(...n);}if(t.length)return new pr(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new pr(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new pr(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=or(e.coordinates,n,i),a=cr(t.geometry(),r,n,i);if(!We(r,n))return !1;for(const t of a)if(!rr(t,s))return !1}if("MultiPolygon"===e.type){const s=lr(e.coordinates,n,i),a=cr(t.geometry(),r,n,i);if(!We(r,n))return !1;for(const t of a)if(!nr(t,s))return !1}return !0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=or(e.coordinates,n,i),a=hr(t.geometry(),r,n,i);if(!We(r,n))return !1;for(const t of a)if(!ir(t,s))return !1}if("MultiPolygon"===e.type){const s=lr(e.coordinates,n,i),a=hr(t.geometry(),r,n,i);if(!We(r,n))return !1;for(const t of a)if(!sr(t,s))return !1}return !0}(t,this.geometries)}return !1}eachChild(){}outputDefined(){return !0}}let fr=class{constructor(t=[],e=((t,e)=>te?1:0)){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}};function dr(t,e,r,n,i){yr(t,e,r,n||t.length-1,i||gr);}function yr(t,e,r,n,i){for(;n>r;){if(n-r>600){var s=n-r+1,a=e-r+1,o=Math.log(s),l=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*l*(s-l)/s)*(a-s/2<0?-1:1);yr(t,e,Math.max(r,Math.floor(e-a*l/s+u)),Math.min(n,Math.floor(e+(s-a)*l/s+u)),i);}var c=t[e],h=r,p=n;for(mr(t,r,e),i(t[n],c)>0&&mr(t,r,n);h0;)p--;}0===i(t[r],c)?mr(t,r,p):mr(t,++p,n),p<=e&&(r=p+1),e<=p&&(n=p-1);}}function mr(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}function gr(t,e){return te?1:0}function xr(t,e){if(t.length<=1)return [t];const r=[];let n,i;for(const e of t){const t=br(e);0!==t&&(e.area=Math.abs(t),void 0===i&&(i=t<0),i===t<0?(n&&r.push(n),n=[e]):n.push(e));}if(n&&r.push(n),e>1)for(let t=0;t1?(l=t[o+1][0],u=t[o+1][1]):p>0&&(l+=c/this.kx*p,u+=h/this.ky*p)),c=this.wrap(e[0]-l)*this.kx,h=(e[1]-u)*this.ky;const f=c*c+h*h;f180;)t-=360;return t}}function kr(t,e){return e[0]-t[0]}function Mr(t){return t[1]-t[0]+1}function Ir(t,e){return t[1]>=t[0]&&t[1]t[1])return [null,null];const r=Mr(t);if(e){if(2===r)return [t,null];const e=Math.floor(r/2);return [[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===r)return [t,null];const n=Math.floor(r/2)-1;return [[t[0],t[0]+n],[t[0]+n+1,t[1]]]}function Pr(t,e){if(!Ir(e,t.length))return [1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=e[0];n<=e[1];++n)Je(r,t[n]);return r}function Cr(t){const e=[1/0,1/0,-1/0,-1/0];for(const r of t)for(const t of r)Je(e,t);return e}function Br(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function Vr(t,e,r){if(!Br(t)||!Br(e))return NaN;let n=0,i=0;return t[2]e[2]&&(n=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=n)return n;if(We(i,s)){if(Or(t,e))return 0}else if(Or(e,t))return 0;let a=1/0;for(const n of t)for(let t=0,i=n.length,s=i-1;t0;){const i=a.pop();if(i[0]>=s)continue;const l=i[1],u=e?50:100;if(Mr(l)<=u){if(!Ir(l,t.length))return NaN;if(e){const e=Dr(t,l,r,n);if(isNaN(e)||0===e)return e;s=Math.min(s,e);}else for(let e=l[0];e<=l[1];++e){const i=Lr(t[e],r,n);if(s=Math.min(s,i),0===s)return 0}}else {const r=zr(l,e);Rr(a,s,n,t,o,r[0]),Rr(a,s,n,t,o,r[1]);}}return s}function Nr(t,e,r,n,i,s=1/0){let a=Math.min(s,i.distance(t[0],r[0]));if(0===a)return a;const o=new fr([[0,[0,t.length-1],[0,r.length-1]]],kr);for(;o.length>0;){const s=o.pop();if(s[0]>=a)continue;const l=s[1],u=s[2],c=e?50:100,h=n?50:100;if(Mr(l)<=c&&Mr(u)<=h){if(!Ir(l,t.length)&&Ir(u,r.length))return NaN;let s;if(e&&n)s=Tr(t,l,r,u,i),a=Math.min(a,s);else if(e&&!n){const e=t.slice(l[0],l[1]+1);for(let t=u[0];t<=u[1];++t)if(s=Er(r[t],e,i),a=Math.min(a,s),0===a)return a}else if(!e&&n){const e=r.slice(u[0],u[1]+1);for(let r=l[0];r<=l[1];++r)if(s=Er(t[r],e,i),a=Math.min(a,s),0===a)return a}else s=$r(t,l,r,u,i),a=Math.min(a,s);}else {const s=zr(l,e),c=zr(u,n);Ur(o,a,i,t,r,s[0],c[0]),Ur(o,a,i,t,r,s[0],c[1]),Ur(o,a,i,t,r,s[1],c[0]),Ur(o,a,i,t,r,s[1],c[1]);}}return a}function Zr(t){return "MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class Gr{constructor(t,e){this.type=ut,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(re(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new Gr(e,e.features.map((t=>Zr(t.geometry))).flat());if("Feature"===e.type)return new Gr(e,Zr(e.geometry));if("type"in e&&"coordinates"in e)return new Gr(e,Zr(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Ye([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new Sr(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case"Point":s=Math.min(s,Nr(n,!1,[t.coordinates],!1,i,s));break;case"LineString":s=Math.min(s,Nr(n,!1,t.coordinates,!0,i,s));break;case"Polygon":s=Math.min(s,qr(n,!1,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>Ye([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new Sr(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case"Point":s=Math.min(s,Nr(n,!0,[t.coordinates],!1,i,s));break;case"LineString":s=Math.min(s,Nr(n,!0,t.coordinates,!0,i,s));break;case"Polygon":s=Math.min(s,qr(n,!0,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const r=t.geometry();if(0===r.length||0===r[0].length)return NaN;const n=xr(r,0).map((e=>e.map((e=>e.map((e=>Ye([e.x,e.y],t.canonical))))))),i=new Sr(n[0][0][0][1]);let s=1/0;for(const t of e)for(const e of n){switch(t.type){case"Point":s=Math.min(s,qr([t.coordinates],!1,e,i,s));break;case"LineString":s=Math.min(s,qr(t.coordinates,!0,e,i,s));break;case"Polygon":s=Math.min(s,jr(e,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return !0}}const Kr={"==":Le,"!=":De,">":je,"<":Oe,">=":Ue,"<=":Re,array:le,at:me,boolean:le,case:be,coalesce:Ee,collator:qe,format:Ze,image:Ge,in:ge,"index-of":xe,interpolate:Be,"interpolate-hcl":Be,"interpolate-lab":Be,length:Ke,let:de,literal:se,match:ve,number:le,"number-format":Ne,object:le,slice:we,step:Ae,string:le,"to-boolean":ce,"to-color":ce,"to-number":ce,"to-string":ce,var:ye,within:pr,distance:Gr};class Xr{constructor(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t);}outputDefined(){return !1}static parse(t,e){const r=t[0],n=Xr.definitions[r];if(!n)return e.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,s=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=s.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let o=null;for(const[n,s]of a){o=new fe(e.registry,Qr,e.path,null,e.scope);const a=[];let l=!1;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(wt).join(", ")})`:`(${wt(e.type)}...)`;var e;})).join(" | "),n=[];for(let r=1;r{r=e?r&&Qr(t):r&&t instanceof se;})),!!r&&tn(t)&&rn(t,["zoom","heatmap-density","line-progress","accumulated","is-supported-script"])}function tn(t){if(t instanceof Xr){if("get"===t.name&&1===t.args.length)return !1;if("feature-state"===t.name)return !1;if("has"===t.name&&1===t.args.length)return !1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return !1;if(/^filter-/.test(t.name))return !1}if(t instanceof pr)return !1;if(t instanceof Gr)return !1;let e=!0;return t.eachChild((t=>{e&&!tn(t)&&(e=!1);})),e}function en(t){if(t instanceof Xr&&"feature-state"===t.name)return !1;let e=!0;return t.eachChild((t=>{e&&!en(t)&&(e=!1);})),e}function rn(t,e){if(t instanceof Xr&&e.indexOf(t.name)>=0)return !1;let r=!0;return t.eachChild((t=>{r&&!rn(t,e)&&(r=!1);})),r}function nn(t){return {result:"success",value:t}}function sn(t){return {result:"error",value:t}}function an(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function on(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function ln(t){return !!t.expression&&t.expression.interpolated}function un(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function cn(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)}function hn(t){return t}function pn(t,e){const r="color"===e.type,n=t.stops&&"object"==typeof t.stops[0][0],i=n||!(n||void 0!==t.property),s=t.type||(ln(e)?"exponential":"interval");if(r||"padding"===e.type){const n=r?Kt.parse:Jt.parse;(t=st({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],n(t[1])]))),t.default=n(t.default?t.default:e.default);}if(t.colorSpace&&"rgb"!==(a=t.colorSpace)&&"hcl"!==a&&"lab"!==a)throw new Error(`Unknown color space: "${t.colorSpace}"`);var a;let o,l,u;if("exponential"===s)o=mn;else if("interval"===s)o=yn;else if("categorical"===s){o=dn,l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];u=typeof t.stops[0][0];}else {if("identity"!==s)throw new Error(`Unknown function type "${s}"`);o=gn;}if(n){const r={},n=[];for(let e=0;et[0])),evaluate:({zoom:r},n)=>mn({stops:i,base:t.base},e,r).evaluate(r,n)}}if(i){const r="exponential"===s?{name:"exponential",base:void 0!==t.base?t.base:1}:null;return {kind:"camera",interpolationType:r,interpolationFactor:Be.interpolationFactor.bind(void 0,r),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:r})=>o(t,e,r,l,u)}}return {kind:"source",evaluate(r,n){const i=n&&n.properties?n.properties[t.property]:void 0;return void 0===i?fn(t.default,e.default):o(t,e,i,l,u)}}}function fn(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function dn(t,e,r,n,i){return fn(typeof r===i?n[r]:void 0,t.default,e.default)}function yn(t,e,r){if("number"!==un(r))return fn(t.default,e.default);const n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];const i=_e(t.stops.map((t=>t[0])),r);return t.stops[i][1]}function mn(t,e,r){const n=void 0!==t.base?t.base:1;if("number"!==un(r))return fn(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];const s=_e(t.stops.map((t=>t[0])),r),a=function(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[s][0],t.stops[s+1][0]),o=t.stops[s][1],l=t.stops[s+1][1],u=Ce[e.type]||hn;return "function"==typeof o.evaluate?{evaluate(...e){const r=o.evaluate.apply(void 0,e),n=l.evaluate.apply(void 0,e);if(void 0!==r&&void 0!==n)return u(r,n,a,t.colorSpace)}}:u(o,l,a,t.colorSpace)}function gn(t,e,r){switch(e.type){case"color":r=Kt.parse(r);break;case"formatted":r=Yt.fromString(r.toString());break;case"resolvedImage":r=te.fromString(r.toString());break;case"padding":r=Jt.parse(r);break;default:un(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0);}return fn(r,t.default,e.default)}Xr.register(Kr,{error:[{kind:"error"},[ct],(t,[e])=>{throw new ae(e.evaluate(t))}],typeof:[ct,[dt],(t,[e])=>wt(ne(e.evaluate(t)))],"to-rgba":[bt(ut,4),[pt],(t,[e])=>{const[r,n,i,s]=e.evaluate(t).rgb;return [255*r,255*n,255*i,s]}],rgb:[pt,[ut,ut,ut],Hr],rgba:[pt,[ut,ut,ut,ut],Hr],has:{type:ht,overloads:[[[ct],(t,[e])=>Yr(e.evaluate(t),t.properties())],[[ct,ft],(t,[e,r])=>Yr(e.evaluate(t),r.evaluate(t))]]},get:{type:dt,overloads:[[[ct],(t,[e])=>Jr(e.evaluate(t),t.properties())],[[ct,ft],(t,[e,r])=>Jr(e.evaluate(t),r.evaluate(t))]]},"feature-state":[dt,[ct],(t,[e])=>Jr(e.evaluate(t),t.featureState||{})],properties:[ft,[],t=>t.properties()],"geometry-type":[ct,[],t=>t.geometryType()],id:[dt,[],t=>t.id()],zoom:[ut,[],t=>t.globals.zoom],"heatmap-density":[ut,[],t=>t.globals.heatmapDensity||0],"line-progress":[ut,[],t=>t.globals.lineProgress||0],accumulated:[dt,[],t=>void 0===t.globals.accumulated?null:t.globals.accumulated],"+":[ut,Wr(ut),(t,e)=>{let r=0;for(const n of e)r+=n.evaluate(t);return r}],"*":[ut,Wr(ut),(t,e)=>{let r=1;for(const n of e)r*=n.evaluate(t);return r}],"-":{type:ut,overloads:[[[ut,ut],(t,[e,r])=>e.evaluate(t)-r.evaluate(t)],[[ut],(t,[e])=>-e.evaluate(t)]]},"/":[ut,[ut,ut],(t,[e,r])=>e.evaluate(t)/r.evaluate(t)],"%":[ut,[ut,ut],(t,[e,r])=>e.evaluate(t)%r.evaluate(t)],ln2:[ut,[],()=>Math.LN2],pi:[ut,[],()=>Math.PI],e:[ut,[],()=>Math.E],"^":[ut,[ut,ut],(t,[e,r])=>Math.pow(e.evaluate(t),r.evaluate(t))],sqrt:[ut,[ut],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[ut,[ut],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[ut,[ut],(t,[e])=>Math.log(e.evaluate(t))],log2:[ut,[ut],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[ut,[ut],(t,[e])=>Math.sin(e.evaluate(t))],cos:[ut,[ut],(t,[e])=>Math.cos(e.evaluate(t))],tan:[ut,[ut],(t,[e])=>Math.tan(e.evaluate(t))],asin:[ut,[ut],(t,[e])=>Math.asin(e.evaluate(t))],acos:[ut,[ut],(t,[e])=>Math.acos(e.evaluate(t))],atan:[ut,[ut],(t,[e])=>Math.atan(e.evaluate(t))],min:[ut,Wr(ut),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[ut,Wr(ut),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[ut,[ut],(t,[e])=>Math.abs(e.evaluate(t))],round:[ut,[ut],(t,[e])=>{const r=e.evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[ut,[ut],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[ut,[ut],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[ht,[ct,dt],(t,[e,r])=>t.properties()[e.value]===r.value],"filter-id-==":[ht,[dt],(t,[e])=>t.id()===e.value],"filter-type-==":[ht,[ct],(t,[e])=>t.geometryType()===e.value],"filter-<":[ht,[ct,dt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n{const r=t.id(),n=e.value;return typeof r==typeof n&&r":[ht,[ct,dt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[ht,[dt],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>n}],"filter-<=":[ht,[ct,dt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[ht,[dt],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r<=n}],"filter->=":[ht,[ct,dt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[ht,[dt],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>=n}],"filter-has":[ht,[dt],(t,[e])=>e.value in t.properties()],"filter-has-id":[ht,[],t=>null!==t.id()&&void 0!==t.id()],"filter-type-in":[ht,[bt(ct)],(t,[e])=>e.value.indexOf(t.geometryType())>=0],"filter-id-in":[ht,[bt(dt)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[ht,[ct,bt(dt)],(t,[e,r])=>r.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[ht,[ct,bt(dt)],(t,[e,r])=>function(t,e,r,n){for(;r<=n;){const i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[e.value],r.value,0,r.value.length-1)],all:{type:ht,overloads:[[[ht,ht],(t,[e,r])=>e.evaluate(t)&&r.evaluate(t)],[Wr(ht),(t,e)=>{for(const r of e)if(!r.evaluate(t))return !1;return !0}]]},any:{type:ht,overloads:[[[ht,ht],(t,[e,r])=>e.evaluate(t)||r.evaluate(t)],[Wr(ht),(t,e)=>{for(const r of e)if(r.evaluate(t))return !0;return !1}]]},"!":[ht,[ht],(t,[e])=>!e.evaluate(t)],"is-supported-script":[ht,[ct],(t,[e])=>{const r=t.globals&&t.globals.isSupportedScript;return !r||r(e.evaluate(t))}],upcase:[ct,[ct],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[ct,[ct],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[ct,Wr(dt),(t,e)=>e.map((e=>ie(e.evaluate(t)))).join("")],"resolved-locale":[ct,[yt],(t,[e])=>e.evaluate(t).resolvedLocale()]});class xn{constructor(t,e){var r;this.expression=t,this._warningHistory={},this._evaluator=new pe,this._defaultValue=e?"color"===(r=e).type&&cn(r.default)?new Kt(0,0,0,0):"color"===r.type?Kt.parse(r.default)||null:"padding"===r.type?Jt.parse(r.default)||null:"variableAnchorOffsetCollection"===r.type?Qt.parse(r.default)||null:void 0===r.default?null:r.default:null,this._enumValues=e&&"enum"===e.type?e.values:null;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,r,n,i,s){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new ae(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function vn(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Kr}function bn(t,e){const r=new fe(Kr,Qr,[],e?function(t){const e={color:pt,string:ct,number:ut,enum:ct,boolean:ht,formatted:mt,padding:gt,resolvedImage:xt,variableAnchorOffsetCollection:vt};return "array"===t.type?bt(e[t.value]||dt,t.length):e[t.type]}(e):void 0),n=r.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return n?nn(new xn(n,e)):sn(r.errors)}class wn{constructor(t,e){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!en(e.expression);}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._styleExpression.evaluate(t,e,r,n,i,s)}}class _n{constructor(t,e,r,n){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!en(e.expression),this.interpolationType=n;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._styleExpression.evaluate(t,e,r,n,i,s)}interpolationFactor(t,e,r){return this.interpolationType?Be.interpolationFactor(this.interpolationType,t,e,r):0}}function An(t,e){const r=bn(t,e);if("error"===r.result)return r;const n=r.value.expression,i=tn(n);if(!i&&!an(e))return sn([new at("","data expressions not supported")]);const s=rn(n,["zoom"]);if(!s&&!on(e))return sn([new at("","zoom expressions not supported")]);const a=kn(n);return a||s?a instanceof at?sn([a]):a instanceof Be&&!ln(e)?sn([new at("",'"interpolate" expressions cannot be used with this property')]):nn(a?new _n(i?"camera":"composite",r.value,a.labels,a instanceof Be?a.interpolation:void 0):new wn(i?"constant":"source",r.value)):sn([new at("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class Sn{constructor(t,e){this._parameters=t,this._specification=e,st(this,pn(this._parameters,this._specification));}static deserialize(t){return new Sn(t._parameters,t._specification)}static serialize(t){return {_parameters:t._parameters,_specification:t._specification}}}function kn(t){let e=null;if(t instanceof de)e=kn(t.result);else if(t instanceof Ee){for(const r of t.args)if(e=kn(r),e)break}else (t instanceof Ae||t instanceof Be)&&t.input instanceof Xr&&"zoom"===t.input.name&&(e=t);return e instanceof at||t.eachChild((t=>{const r=kn(t);r instanceof at?e=r:!e&&r?e=new at("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&r&&e!==r&&(e=new at("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),e}function Mn(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case"has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case"!in":case"!has":case"none":return !1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case"any":case"all":for(const e of t.slice(1))if(!Mn(e)&&"boolean"!=typeof e)return !1;return !0;default:return !0}}const In={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function zn(t){if(null==t)return {filter:()=>!0,needGeometry:!1};Mn(t)||(t=Bn(t));const e=bn(t,In);if("error"===e.result)throw new Error(e.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return {filter:(t,r,n)=>e.value.evaluate(t,r,{},n),needGeometry:Cn(t)}}function Pn(t,e){return te?1:0}function Cn(t){if(!Array.isArray(t))return !1;if("within"===t[0]||"distance"===t[0])return !0;for(let e=1;e"===e||"<="===e||">="===e?Vn(t[1],t[2],e):"any"===e?(r=t.slice(1),["any"].concat(r.map(Bn))):"all"===e?["all"].concat(t.slice(1).map(Bn)):"none"===e?["all"].concat(t.slice(1).map(Bn).map(Tn)):"in"===e?En(t[1],t.slice(2)):"!in"===e?Tn(En(t[1],t.slice(2))):"has"===e?Fn(t[1]):"!has"!==e||Tn(Fn(t[1]));var r;}function Vn(t,e,r){switch(t){case"$type":return [`filter-type-${r}`,e];case"$id":return [`filter-id-${r}`,e];default:return [`filter-${r}`,t,e]}}function En(t,e){if(0===e.length)return !1;switch(t){case"$type":return ["filter-type-in",["literal",e]];case"$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort(Pn)]]:["filter-in-small",t,["literal",e]]}}function Fn(t){switch(t){case"$type":return !0;case"$id":return ["filter-has-id"];default:return ["filter-has",t]}}function Tn(t){return ["!",t]}function $n(t){const e=typeof t;if("number"===e||"boolean"===e||"string"===e||null==t)return JSON.stringify(t);if(Array.isArray(t)){let e="[";for(const r of t)e+=`${$n(r)},`;return `${e}]`}const r=Object.keys(t).sort();let n="{";for(let e=0;en.maximum?[new it(e,r,`${r} is greater than the maximum value ${n.maximum}`)]:[]}function Nn(t){const e=t.valueSpec,r=On(t.value.type);let n,i,s,a={};const o="categorical"!==r&&void 0===t.value.property,l=!o,u="array"===un(t.value.stops)&&"array"===un(t.value.stops[0])&&"object"===un(t.value.stops[0][0]),c=Rn({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===r)return [new it(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const n=t.value;return e=e.concat(Un({key:t.key,value:n,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===un(n)&&0===n.length&&e.push(new it(t.key,n,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===r&&o&&c.push(new it(t.key,t.value,'missing required property "property"')),"identity"===r||t.value.stops||c.push(new it(t.key,t.value,'missing required property "stops"')),"exponential"===r&&t.valueSpec.expression&&!ln(t.valueSpec)&&c.push(new it(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!an(t.valueSpec)?c.push(new it(t.key,t.value,"property functions not supported")):o&&!on(t.valueSpec)&&c.push(new it(t.key,t.value,"zoom functions not supported"))),"categorical"!==r&&!u||void 0!==t.value.property||c.push(new it(t.key,t.value,'"property" property is required')),c;function h(t){let r=[];const n=t.value,o=t.key;if("array"!==un(n))return [new it(o,n,`array expected, ${un(n)} found`)];if(2!==n.length)return [new it(o,n,`array length 2 expected, length ${n.length} found`)];if(u){if("object"!==un(n[0]))return [new it(o,n,`object expected, ${un(n[0])} found`)];if(void 0===n[0].zoom)return [new it(o,n,"object stop key must have zoom")];if(void 0===n[0].value)return [new it(o,n,"object stop key must have value")];if(s&&s>On(n[0].zoom))return [new it(o,n[0].zoom,"stop zoom values must appear in ascending order")];On(n[0].zoom)!==s&&(s=On(n[0].zoom),i=void 0,a={}),r=r.concat(Rn({key:`${o}[0]`,value:n[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:qn,value:p}}));}else r=r.concat(p({key:`${o}[0]`,value:n[0],valueSpec:{},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},n));return vn(jn(n[1]))?r.concat([new it(`${o}[1]`,n[1],"expressions are not allowed in function stops.")]):r.concat(t.validateSpec({key:`${o}[1]`,value:n[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const o=un(t.value),l=On(t.value),u=null!==t.value?t.value:s;if(n){if(o!==n)return [new it(t.key,u,`${o} stop domain type must match previous stop domain type ${n}`)]}else n=o;if("number"!==o&&"string"!==o&&"boolean"!==o)return [new it(t.key,u,"stop domain value must be a number, string, or boolean")];if("number"!==o&&"categorical"!==r){let n=`number expected, ${o} found`;return an(e)&&void 0===r&&(n+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new it(t.key,u,n)]}return "categorical"!==r||"number"!==o||isFinite(l)&&Math.floor(l)===l?"categorical"!==r&&"number"===o&&void 0!==i&&lnew it(`${t.key}${e.key}`,t.value,e.message)));const r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return [new it(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!en(r))return [new it(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!en(r))return [new it(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!rn(r,["zoom","feature-state"]))return [new it(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!tn(r))return [new it(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function Gn(t){const e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(On(r))&&i.push(new it(e,r,`expected one of [${n.values.join(", ")}], ${JSON.stringify(r)} found`)):-1===Object.keys(n.values).indexOf(On(r))&&i.push(new it(e,r,`expected one of [${Object.keys(n.values).join(", ")}], ${JSON.stringify(r)} found`)),i}function Kn(t){return Mn(jn(t.value))?Zn(st({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):Xn(t)}function Xn(t){const e=t.value,r=t.key;if("array"!==un(e))return [new it(r,e,`array expected, ${un(e)} found`)];const n=t.styleSpec;let i,s=[];if(e.length<1)return [new it(r,e,"filter array must have at least 1 element")];switch(s=s.concat(Gn({key:`${r}[0]`,value:e[0],valueSpec:n.filter_operator,style:t.style,styleSpec:t.styleSpec})),On(e[0])){case"<":case"<=":case">":case">=":e.length>=2&&"$type"===On(e[1])&&s.push(new it(r,e,`"$type" cannot be use with operator "${e[0]}"`));case"==":case"!=":3!==e.length&&s.push(new it(r,e,`filter array for operator "${e[0]}" must have 3 elements`));case"in":case"!in":e.length>=2&&(i=un(e[1]),"string"!==i&&s.push(new it(`${r}[1]`,e[1],`string expected, ${i} found`)));for(let a=2;a{t in r&&e.push(new it(n,r[t],`"${t}" is prohibited for ref layers`));})),i.layers.forEach((e=>{On(e.id)===o&&(t=e);})),t?t.ref?e.push(new it(n,r.ref,"ref cannot reference another ref layer")):a=On(t.type):e.push(new it(n,r.ref,`ref layer "${o}" not found`));}else if("background"!==a)if(r.source){const t=i.sources&&i.sources[r.source],s=t&&On(t.type);t?"vector"===s&&"raster"===a?e.push(new it(n,r.source,`layer "${r.id}" requires a raster source`)):"raster-dem"!==s&&"hillshade"===a?e.push(new it(n,r.source,`layer "${r.id}" requires a raster-dem source`)):"raster"===s&&"raster"!==a?e.push(new it(n,r.source,`layer "${r.id}" requires a vector source`)):"vector"!==s||r["source-layer"]?"raster-dem"===s&&"hillshade"!==a?e.push(new it(n,r.source,"raster-dem source can only be used with layer type 'hillshade'.")):"line"!==a||!r.paint||!r.paint["line-gradient"]||"geojson"===s&&t.lineMetrics||e.push(new it(n,r,`layer "${r.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):e.push(new it(n,r,`layer "${r.id}" must specify a "source-layer"`)):e.push(new it(n,r.source,`source "${r.source}" not found`));}else e.push(new it(n,r,'missing required property "source"'));return e=e.concat(Rn({key:n,value:r,valueSpec:s.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${n}.type`,value:r.type,valueSpec:s.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:r,objectKey:"type"}),filter:Kn,layout:t=>Rn({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Jn(st({layerType:a},t))}}),paint:t=>Rn({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>Yn(st({layerType:a},t))}})}})),e}function Qn(t){const e=t.value,r=t.key,n=un(e);return "string"!==n?[new it(r,e,`string expected, ${n} found`)]:[]}const ti={promoteId:function({key:t,value:e}){if("string"===un(e))return Qn({key:t,value:e});{const r=[];for(const n in e)r.push(...Qn({key:`${t}.${n}`,value:e[n]}));return r}}};function ei(t){const e=t.value,r=t.key,n=t.styleSpec,i=t.style,s=t.validateSpec;if(!e.type)return [new it(r,e,'"type" is required')];const a=On(e.type);let o;switch(a){case"vector":case"raster":return o=Rn({key:r,value:e,valueSpec:n[`source_${a.replace("-","_")}`],style:t.style,styleSpec:n,objectElementValidators:ti,validateSpec:s}),o;case"raster-dem":return o=function(t){var e;const r=null!==(e=t.sourceName)&&void 0!==e?e:"",n=t.value,i=t.styleSpec,s=i.source_raster_dem,a=t.style;let o=[];const l=un(n);if(void 0===n)return o;if("object"!==l)return o.push(new it("source_raster_dem",n,`object expected, ${l} found`)),o;const u="custom"===On(n.encoding),c=["redFactor","greenFactor","blueFactor","baseShift"],h=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in n)!u&&c.includes(e)?o.push(new it(e,n[e],`In "${r}": "${e}" is only valid when "encoding" is set to "custom". ${h} encoding found`)):s[e]?o=o.concat(t.validateSpec({key:e,value:n[e],valueSpec:s[e],validateSpec:t.validateSpec,style:a,styleSpec:i})):o.push(new it(e,n[e],`unknown property "${e}"`));return o}({sourceName:r,value:e,style:t.style,styleSpec:n,validateSpec:s}),o;case"geojson":if(o=Rn({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,validateSpec:s,objectElementValidators:ti}),e.cluster)for(const t in e.clusterProperties){const[n,i]=e.clusterProperties[t],a="string"==typeof n?[n,["accumulated"],["get",t]]:n;o.push(...Zn({key:`${r}.${t}.map`,value:i,validateSpec:s,expressionContext:"cluster-map"})),o.push(...Zn({key:`${r}.${t}.reduce`,value:a,validateSpec:s,expressionContext:"cluster-reduce"}));}return o;case"video":return Rn({key:r,value:e,valueSpec:n.source_video,style:i,validateSpec:s,styleSpec:n});case"image":return Rn({key:r,value:e,valueSpec:n.source_image,style:i,validateSpec:s,styleSpec:n});case"canvas":return [new it(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Gn({key:`${r}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:i,validateSpec:s,styleSpec:n})}}function ri(t){const e=t.value,r=t.styleSpec,n=r.light,i=t.style;let s=[];const a=un(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new it("light",e,`object expected, ${a} found`)]),s;for(const a in e){const o=a.match(/^(.*)-transition$/);s=s.concat(o&&n[o[1]]&&n[o[1]].transition?t.validateSpec({key:a,value:e[a],valueSpec:r.transition,validateSpec:t.validateSpec,style:i,styleSpec:r}):n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new it(a,e[a],`unknown property "${a}"`)]);}return s}function ni(t){const e=t.value,r=t.styleSpec,n=r.sky,i=t.style,s=un(e);if(void 0===e)return [];if("object"!==s)return [new it("sky",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new it(s,e[s],`unknown property "${s}"`)]);return a}function ii(t){const e=t.value,r=t.styleSpec,n=r.terrain,i=t.style;let s=[];const a=un(e);if(void 0===e)return s;if("object"!==a)return s=s.concat([new it("terrain",e,`object expected, ${a} found`)]),s;for(const a in e)s=s.concat(n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new it(a,e[a],`unknown property "${a}"`)]);return s}function si(t){let e=[];const r=t.value,n=t.key;if(Array.isArray(r)){const i=[],s=[];for(const a in r)r[a].id&&i.includes(r[a].id)&&e.push(new it(n,r,`all the sprites' ids must be unique, but ${r[a].id} is duplicated`)),i.push(r[a].id),r[a].url&&s.includes(r[a].url)&&e.push(new it(n,r,`all the sprites' URLs must be unique, but ${r[a].url} is duplicated`)),s.push(r[a].url),e=e.concat(Rn({key:`${n}[${a}]`,value:r[a],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:t.validateSpec}));return e}return Qn({key:n,value:r})}const ai={"*":()=>[],array:Un,boolean:function(t){const e=t.value,r=t.key,n=un(e);return "boolean"!==n?[new it(r,e,`boolean expected, ${n} found`)]:[]},number:qn,color:function(t){const e=t.key,r=t.value,n=un(r);return "string"!==n?[new it(e,r,`color expected, ${n} found`)]:Kt.parse(String(r))?[]:[new it(e,r,`color expected, "${r}" found`)]},constants:Dn,enum:Gn,filter:Kn,function:Nn,layer:Wn,object:Rn,source:ei,light:ri,sky:ni,terrain:ii,projection:function(t){const e=t.value,r=t.styleSpec,n=r.projection,i=t.style,s=un(e);if(void 0===e)return [];if("object"!==s)return [new it("projection",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new it(s,e[s],`unknown property "${s}"`)]);return a},string:Qn,formatted:function(t){return 0===Qn(t).length?[]:Zn(t)},resolvedImage:function(t){return 0===Qn(t).length?[]:Zn(t)},padding:function(t){const e=t.key,r=t.value;if("array"===un(r)){if(r.length<1||r.length>4)return [new it(e,r,`padding requires 1 to 4 values; ${r.length} values found`)];const n={type:"number"};let i=[];for(let s=0;s[]}})),t.constants&&(r=r.concat(Dn({key:"constants",value:t.constants,style:t,styleSpec:e,validateSpec:oi}))),hi(r)}function ci(t){return function(e){return t({...e,validateSpec:oi})}}function hi(t){return [].concat(t).sort(((t,e)=>t.line-e.line))}function pi(t){return function(...e){return hi(t.apply(this,e))}}ui.source=pi(ci(ei)),ui.sprite=pi(ci(si)),ui.glyphs=pi(ci(li)),ui.light=pi(ci(ri)),ui.sky=pi(ci(ni)),ui.terrain=pi(ci(ii)),ui.layer=pi(ci(Wn)),ui.filter=pi(ci(Kn)),ui.paintProperty=pi(ci(Yn)),ui.layoutProperty=pi(ci(Jn));const fi=ui,di=fi.light,yi=fi.sky,mi=fi.paintProperty,gi=fi.layoutProperty;function xi(t,e){let r=!1;if(e&&e.length)for(const n of e)t.fire(new N(new Error(n.message))),r=!0;return r}class vi{constructor(t,e,r){const n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(let t=0;t=u[l+0]&&n>=u[l+1])?(a[h]=!0,s.push(i[h])):a[h]=!1;}}}}_forEachCell(t,e,r,n,i,s,a,o){const l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(r),h=this._convertToCellCoord(n);for(let p=l;p<=c;p++)for(let l=u;l<=h;l++){const u=this.d*l+p;if((!o||o(this._convertFromCellCoord(p),this._convertFromCellCoord(l),this._convertFromCellCoord(p+1),this._convertFromCellCoord(l+1)))&&i.call(this,t,e,r,n,u,s,a,o))return}}_convertFromCellCoord(t){return (t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let r=0;for(let t=0;t=0)continue;const s=t[n];i[n]=bi[r].shallow.indexOf(n)>=0?s:ki(s,e);}t instanceof Error&&(i.message=t.message);}if(i.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==r&&(i.$name=r),i}function Mi(t){if(Si(t))return t;if(Array.isArray(t))return t.map(Mi);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=Ai(t)||"Object";if(!bi[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:r}=bi[e];if(!r)throw new Error(`can't deserialize unregistered class ${e}`);if(r.deserialize)return r.deserialize(t);const n=Object.create(r.prototype);for(const r of Object.keys(t)){if("$name"===r)continue;const i=t[r];n[r]=bi[e].shallow.indexOf(r)>=0?i:Mi(i);}return n}class Ii{constructor(){this.first=!0;}update(t,e){const r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoomt>=128&&t<=255,"Hangul Jamo":t=>t>=4352&&t<=4607,Khmer:t=>t>=6016&&t<=6143,"General Punctuation":t=>t>=8192&&t<=8303,"Letterlike Symbols":t=>t>=8448&&t<=8527,"Number Forms":t=>t>=8528&&t<=8591,"Miscellaneous Technical":t=>t>=8960&&t<=9215,"Control Pictures":t=>t>=9216&&t<=9279,"Optical Character Recognition":t=>t>=9280&&t<=9311,"Enclosed Alphanumerics":t=>t>=9312&&t<=9471,"Geometric Shapes":t=>t>=9632&&t<=9727,"Miscellaneous Symbols":t=>t>=9728&&t<=9983,"Miscellaneous Symbols and Arrows":t=>t>=11008&&t<=11263,"Ideographic Description Characters":t=>t>=12272&&t<=12287,"CJK Symbols and Punctuation":t=>t>=12288&&t<=12351,Katakana:t=>t>=12448&&t<=12543,Kanbun:t=>t>=12688&&t<=12703,"CJK Strokes":t=>t>=12736&&t<=12783,"Enclosed CJK Letters and Months":t=>t>=12800&&t<=13055,"CJK Compatibility":t=>t>=13056&&t<=13311,"Yijing Hexagram Symbols":t=>t>=19904&&t<=19967,"Private Use Area":t=>t>=57344&&t<=63743,"Vertical Forms":t=>t>=65040&&t<=65055,"CJK Compatibility Forms":t=>t>=65072&&t<=65103,"Small Form Variants":t=>t>=65104&&t<=65135,"Halfwidth and Fullwidth Forms":t=>t>=65280&&t<=65519};function Pi(t){for(const e of t)if(Ti(e.charCodeAt(0)))return !0;return !1}function Ci(t){for(const e of t)if(!Ei(e.charCodeAt(0)))return !1;return !0}function Bi(t){const e=t.map((t=>{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}const Vi=Bi(["Arab","Dupl","Mong","Ougr","Syrc"]);function Ei(t){return !Vi.test(String.fromCodePoint(t))}const Fi=Bi(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function Ti(t){return !(746!==t&&747!==t&&(t<4352||!(zi["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||zi["CJK Compatibility"](t)||zi["CJK Strokes"](t)||!(!zi["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||zi["Enclosed CJK Letters and Months"](t)||zi["Ideographic Description Characters"](t)||zi.Kanbun(t)||zi.Katakana(t)&&12540!==t||!(!zi["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!zi["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||zi["Vertical Forms"](t)||zi["Yijing Hexagram Symbols"](t)||/\p{sc=Cans}/u.test(String.fromCodePoint(t))||/\p{sc=Hang}/u.test(String.fromCodePoint(t))||Fi.test(String.fromCodePoint(t)))))}function $i(t){return !(Ti(t)||function(t){return !!(zi["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||zi["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||zi["Letterlike Symbols"](t)||zi["Number Forms"](t)||zi["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||zi["Control Pictures"](t)&&9251!==t||zi["Optical Character Recognition"](t)||zi["Enclosed Alphanumerics"](t)||zi["Geometric Shapes"](t)||zi["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||zi["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||zi["CJK Symbols and Punctuation"](t)||zi.Katakana(t)||zi["Private Use Area"](t)||zi["CJK Compatibility Forms"](t)||zi["Small Form Variants"](t)||zi["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}const Li=Bi(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function Di(t){return Li.test(String.fromCodePoint(t))}function Oi(t,e){return !(!e&&Di(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||zi.Khmer(t))}function ji(t){for(const e of t)if(Di(e.charCodeAt(0)))return !0;return !1}const Ri=new class{constructor(){this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null;}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL;}getState(){return {pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText;}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getPluginURL(){return this.pluginURL}getRTLTextPluginStatus(){return this.pluginStatus}};class Ui{constructor(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new Ii,this.transition={});}isSupportedScript(t){return function(t,e){for(const r of t)if(!Oi(r.charCodeAt(0),e))return !1;return !0}(t,"loaded"===Ri.getRTLTextPluginStatus())}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}}}class qi{constructor(t,e){this.property=t,this.value=e,this.expression=function(t,e){if(cn(t))return new Sn(t,e);if(vn(t)){const r=An(t,e);if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return r.value}{let r=t;return "color"===e.type&&"string"==typeof t?r=Kt.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)&&(r=Qt.parse(t)):r=Jt.parse(t),{kind:"constant",evaluate:()=>r}}}(void 0===e?t.specification.default:e,t.specification);}isDataDriven(){return "source"===this.expression.kind||"composite"===this.expression.kind}possiblyEvaluate(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)}}class Ni{constructor(t){this.property=t,this.value=new qi(t,void 0);}transitioned(t,e){return new Gi(this.property,this.value,e,g({},t.transition,this.transition),t.now)}untransitioned(){return new Gi(this.property,this.value,null,{},0)}}class Zi{constructor(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues);}getValue(t){return w(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Ni(this._values[t].property)),this._values[t].value=new qi(this._values[t].property,null===e?void 0:w(e));}getTransition(t){return w(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new Ni(this._values[t].property)),this._values[t].transition=w(e)||void 0;}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);void 0!==r&&(t[e]=r);const n=this.getTransition(e);void 0!==n&&(t[`${e}-transition`]=n);}return t}transitioned(t,e){const r=new Ki(this._properties);for(const n of Object.keys(this._values))r._values[n]=this._values[n].transitioned(t,e._values[n]);return r}untransitioned(){const t=new Ki(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class Gi{constructor(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);}possiblyEvaluate(t,e,r){const n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),s=this.prior;if(s){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(n=1)return 1;const e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}(a))}}return i}}class Ki{constructor(t){this._properties=t,this._values=Object.create(t.defaultTransitioningPropertyValues);}possiblyEvaluate(t,e,r){const n=new Yi(this._properties);for(const i of Object.keys(this._values))n._values[i]=this._values[i].possiblyEvaluate(t,e,r);return n}hasTransition(){for(const t of Object.keys(this._values))if(this._values[t].prior)return !0;return !1}}class Xi{constructor(t){this._properties=t,this._values=Object.create(t.defaultPropertyValues);}hasValue(t){return void 0!==this._values[t].value}getValue(t){return w(this._values[t].value)}setValue(t,e){this._values[t]=new qi(this._values[t].property,null===e?void 0:w(e));}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);void 0!==r&&(t[e]=r);}return t}possiblyEvaluate(t,e,r){const n=new Yi(this._properties);for(const i of Object.keys(this._values))n._values[i]=this._values[i].possiblyEvaluate(t,e,r);return n}}class Hi{constructor(t,e,r){this.property=t,this.value=e,this.parameters=r;}isConstant(){return "constant"===this.value.kind}constantOr(t){return "constant"===this.value.kind?this.value.value:t}evaluate(t,e,r,n){return this.property.evaluate(this.value,this.parameters,t,e,r,n)}}class Yi{constructor(t){this._properties=t,this._values=Object.create(t.defaultPossiblyEvaluatedValues);}get(t){return this._values[t]}}class Ji{constructor(t){this.specification=t;}possiblyEvaluate(t,e){if(t.isDataDriven())throw new Error("Value should not be data driven");return t.expression.evaluate(e)}interpolate(t,e,r){const n=Ce[this.specification.type];return n?n(t,e,r):t}}class Wi{constructor(t,e){this.specification=t,this.overrides=e;}possiblyEvaluate(t,e,r,n){return new Hi(this,"constant"===t.expression.kind||"camera"===t.expression.kind?{kind:"constant",value:t.expression.evaluate(e,null,{},r,n)}:t.expression,e)}interpolate(t,e,r){if("constant"!==t.value.kind||"constant"!==e.value.kind)return t;if(void 0===t.value.value||void 0===e.value.value)return new Hi(this,{kind:"constant",value:void 0},t.parameters);const n=Ce[this.specification.type];if(n){const i=n(t.value.value,e.value.value,r);return new Hi(this,{kind:"constant",value:i},t.parameters)}return t}evaluate(t,e,r,n,i,s){return "constant"===t.kind?t.value:t.evaluate(e,r,n,i,s)}}class Qi extends Wi{possiblyEvaluate(t,e,r,n){if(void 0===t.value)return new Hi(this,{kind:"constant",value:void 0},e);if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n),s="resolvedImage"===t.property.specification.type&&"string"!=typeof i?i.name:i,a=this._calculate(s,s,s,e);return new Hi(this,{kind:"constant",value:a},e)}if("camera"===t.expression.kind){const r=this._calculate(t.expression.evaluate({zoom:e.zoom-1}),t.expression.evaluate({zoom:e.zoom}),t.expression.evaluate({zoom:e.zoom+1}),e);return new Hi(this,{kind:"constant",value:r},e)}return new Hi(this,t.expression,e)}evaluate(t,e,r,n,i,s){if("source"===t.kind){const a=t.evaluate(e,r,n,i,s);return this._calculate(a,a,a,e)}return "composite"===t.kind?this._calculate(t.evaluate({zoom:Math.floor(e.zoom)-1},r,n),t.evaluate({zoom:Math.floor(e.zoom)},r,n),t.evaluate({zoom:Math.floor(e.zoom)+1},r,n),e):t.value}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class ts{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new Ui(Math.floor(e.zoom-1),e)),t.expression.evaluate(new Ui(Math.floor(e.zoom),e)),t.expression.evaluate(new Ui(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class es{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)}interpolate(){return !1}}class rs{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const r=t[e];r.specification.overridable&&this.overridableProperties.push(e);const n=this.defaultPropertyValues[e]=new qi(r,void 0),i=this.defaultTransitionablePropertyValues[e]=new Ni(r);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}}}wi("DataDrivenProperty",Wi),wi("DataConstantProperty",Ji),wi("CrossFadedDataDrivenProperty",Qi),wi("CrossFadedProperty",ts),wi("ColorRampProperty",es);const ns="-transition";class is extends Z{constructor(t,e){if(super(),this.id=t.id,this.type=t.type,this._featureFilter={filter:()=>!0,needGeometry:!1},"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter),e.layout&&(this._unevaluatedLayout=new Xi(e.layout)),e.paint)){this._transitionablePaint=new Zi(e.paint);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:!1});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new Yi(e.paint);}}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)}setLayoutProperty(t,e,r={}){null!=e&&this._validate(gi,`layers.${this.id}.layout.${t}`,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);}getPaintProperty(t){return t.endsWith(ns)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,r={}){if(null!=e&&this._validate(mi,`layers.${this.id}.paint.${t}`,t,e,r))return !1;if(t.endsWith(ns))return this._transitionablePaint.setTransition(t.slice(0,-11),e||void 0),!1;{const r=this._transitionablePaint._values[t],n="cross-faded-data-driven"===r.property.specification["property-type"],i=r.value.isDataDriven(),s=r.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const a=this._transitionablePaint._values[t].value;return a.isDataDriven()||i||n||this._handleOverridablePaintPropertyUpdate(t,s,a)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,r){return !1}isHidden(t){return !!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);}serialize(){const t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),b(t,((t,e)=>!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,r,n,i={}){return (!i||!1!==i.validate)&&xi(this,t.call(fi,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:G,style:{glyphs:!0,sprite:!0}}))}is3D(){return !1}isTileClipped(){return !1}hasOffscreenPass(){return !1}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof Hi&&an(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1}}const ss={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class as{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;}}class os{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0);}static serialize(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());}clear(){this.length=0;}resize(t){this.reserve(t),this.length=t;}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function ls(t,e=1){let r=0,n=0;return {members:t.map((t=>{const i=ss[t.type].BYTES_PER_ELEMENT,s=r=us(r,Math.max(e,i)),a=t.components||1;return n=Math.max(n,i),r+=i*a,{name:t.name,type:t.type,components:a,offset:s}})),size:us(r,Math.max(n,e)),alignment:e}}function us(t,e){return Math.ceil(t/e)*e}class cs extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t}}cs.prototype.bytesPerElement=4,wi("StructArrayLayout2i4",cs);class hs extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t}}hs.prototype.bytesPerElement=6,wi("StructArrayLayout3i6",hs);class ps extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,t}}ps.prototype.bytesPerElement=8,wi("StructArrayLayout4i8",ps);class fs extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}fs.prototype.bytesPerElement=12,wi("StructArrayLayout2i4i12",fs);class ds extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=4*t,l=8*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.uint8[l+4]=n,this.uint8[l+5]=i,this.uint8[l+6]=s,this.uint8[l+7]=a,t}}ds.prototype.bytesPerElement=8,wi("StructArrayLayout2i4ub8",ds);class ys extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t}}ys.prototype.bytesPerElement=8,wi("StructArrayLayout2f8",ys);class ms extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,r,n,i,s,a,o,l,u)}emplace(t,e,r,n,i,s,a,o,l,u,c){const h=10*t;return this.uint16[h+0]=e,this.uint16[h+1]=r,this.uint16[h+2]=n,this.uint16[h+3]=i,this.uint16[h+4]=s,this.uint16[h+5]=a,this.uint16[h+6]=o,this.uint16[h+7]=l,this.uint16[h+8]=u,this.uint16[h+9]=c,t}}ms.prototype.bytesPerElement=20,wi("StructArrayLayout10ui20",ms);class gs extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,s,a,o,l,u,c,h)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=a,this.uint16[f+6]=o,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}gs.prototype.bytesPerElement=24,wi("StructArrayLayout4i4ui4i24",gs);class xs extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}xs.prototype.bytesPerElement=12,wi("StructArrayLayout3f12",xs);class vs extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}vs.prototype.bytesPerElement=4,wi("StructArrayLayout1ul4",vs);class bs extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l){const u=this.length;return this.resize(u+1),this.emplace(u,t,e,r,n,i,s,a,o,l)}emplace(t,e,r,n,i,s,a,o,l,u){const c=10*t,h=5*t;return this.int16[c+0]=e,this.int16[c+1]=r,this.int16[c+2]=n,this.int16[c+3]=i,this.int16[c+4]=s,this.int16[c+5]=a,this.uint32[h+3]=o,this.uint16[c+8]=l,this.uint16[c+9]=u,t}}bs.prototype.bytesPerElement=20,wi("StructArrayLayout6i1ul2ui20",bs);class ws extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}ws.prototype.bytesPerElement=12,wi("StructArrayLayout2i2i2i12",ws);class _s extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=4*t,o=8*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.int16[o+6]=i,this.int16[o+7]=s,t}}_s.prototype.bytesPerElement=16,wi("StructArrayLayout2f1f2i16",_s);class As extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=16*t,l=4*t,u=8*t;return this.uint8[o+0]=e,this.uint8[o+1]=r,this.float32[l+1]=n,this.float32[l+2]=i,this.int16[u+6]=s,this.int16[u+7]=a,t}}As.prototype.bytesPerElement=16,wi("StructArrayLayout2ub2f2i16",As);class Ss extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t}}Ss.prototype.bytesPerElement=6,wi("StructArrayLayout3ui6",Ss);class ks extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g){const x=24*t,v=12*t,b=48*t;return this.int16[x+0]=e,this.int16[x+1]=r,this.uint16[x+2]=n,this.uint16[x+3]=i,this.uint32[v+2]=s,this.uint32[v+3]=a,this.uint32[v+4]=o,this.uint16[x+10]=l,this.uint16[x+11]=u,this.uint16[x+12]=c,this.float32[v+7]=h,this.float32[v+8]=p,this.uint8[b+36]=f,this.uint8[b+37]=d,this.uint8[b+38]=y,this.uint32[v+10]=m,this.int16[x+22]=g,t}}ks.prototype.bytesPerElement=48,wi("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",ks);class Ms extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,A,S,k,M,I){const z=this.length;return this.resize(z+1),this.emplace(z,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,A,S,k,M,I)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,A,S,k,M,I,z){const P=32*t,C=16*t;return this.int16[P+0]=e,this.int16[P+1]=r,this.int16[P+2]=n,this.int16[P+3]=i,this.int16[P+4]=s,this.int16[P+5]=a,this.int16[P+6]=o,this.int16[P+7]=l,this.uint16[P+8]=u,this.uint16[P+9]=c,this.uint16[P+10]=h,this.uint16[P+11]=p,this.uint16[P+12]=f,this.uint16[P+13]=d,this.uint16[P+14]=y,this.uint16[P+15]=m,this.uint16[P+16]=g,this.uint16[P+17]=x,this.uint16[P+18]=v,this.uint16[P+19]=b,this.uint16[P+20]=w,this.uint16[P+21]=_,this.uint16[P+22]=A,this.uint32[C+12]=S,this.float32[C+13]=k,this.float32[C+14]=M,this.uint16[P+30]=I,this.uint16[P+31]=z,t}}Ms.prototype.bytesPerElement=64,wi("StructArrayLayout8i15ui1ul2f2ui64",Ms);class Is extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}Is.prototype.bytesPerElement=4,wi("StructArrayLayout1f4",Is);class zs extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[6*t+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}zs.prototype.bytesPerElement=12,wi("StructArrayLayout1ui2f12",zs);class Ps extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t}}Ps.prototype.bytesPerElement=8,wi("StructArrayLayout1ul2ui8",Ps);class Cs extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t}}Cs.prototype.bytesPerElement=4,wi("StructArrayLayout2ui4",Cs);class Bs extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}Bs.prototype.bytesPerElement=2,wi("StructArrayLayout1ui2",Bs);class Vs extends os{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=r,this.float32[s+2]=n,this.float32[s+3]=i,t}}Vs.prototype.bytesPerElement=16,wi("StructArrayLayout4f16",Vs);class Es extends as{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new s(this.anchorPointX,this.anchorPointY)}}Es.prototype.size=20;class Fs extends bs{get(t){return new Es(this,t)}}wi("CollisionBoxArray",Fs);class Ts extends as{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t;}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t;}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t;}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}Ts.prototype.size=48;class $s extends ks{get(t){return new Ts(this,t)}}wi("PlacedSymbolArray",$s);class Ls extends as{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t;}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}Ls.prototype.size=64;class Ds extends Ms{get(t){return new Ls(this,t)}}wi("SymbolInstanceArray",Ds);class Os extends Is{getoffsetX(t){return this.float32[1*t+0]}}wi("GlyphOffsetArray",Os);class js extends hs{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}wi("SymbolLineVertexArray",js);class Rs extends as{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}Rs.prototype.size=12;class Us extends zs{get(t){return new Rs(this,t)}}wi("TextAnchorOffsetArray",Us);class qs extends as{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}qs.prototype.size=8;class Ns extends Ps{get(t){return new qs(this,t)}}wi("FeatureIndexArray",Ns);class Zs extends cs{}class Gs extends cs{}class Ks extends cs{}class Xs extends fs{}class Hs extends ds{}class Ys extends ys{}class Js extends ms{}class Ws extends gs{}class Qs extends xs{}class ta extends vs{}class ea extends ws{}class ra extends As{}class na extends Ss{}class ia extends Cs{}const sa=ls([{name:"a_pos",components:2,type:"Int16"}],4),{members:aa}=sa;class oa{constructor(t=[]){this.segments=t;}prepareSegment(t,e,r,n){let i=this.segments[this.segments.length-1];return t>oa.MAX_VERTEX_ARRAY_LENGTH&&A(`Max vertices per segment is ${oa.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}`),(!i||i.vertexLength+t>oa.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n)&&(i={vertexOffset:e.length,primitiveOffset:r.length,vertexLength:0,primitiveLength:0},void 0!==n&&(i.sortKey=n),this.segments.push(i)),i}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy();}static simpleSegment(t,e,r,n){return new oa([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])}}function la(t,e){return 256*(t=y(Math.floor(t),0,255))+y(Math.floor(e),0,255)}oa.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,wi("SegmentVector",oa);const ua=ls([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var ca={exports:{}},ha={exports:{}};ha.exports=function(t,e){var r,n,i,s,a,o,l,u;for(n=t.length-(r=3&t.length),i=e,a=3432918353,o=461845907,u=0;u>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,r){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0};var pa=ha.exports,fa={exports:{}};fa.exports=function(t,e){for(var r,n=t.length,i=e^n,s=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++s;switch(n){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0};var da=pa,ya=fa.exports;ca.exports=da,ca.exports.murmur3=da,ca.exports.murmur2=ya;var ma=r(ca.exports);class ga{constructor(){this.ids=[],this.positions=[],this.indexed=!1;}add(t,e,r,n){this.ids.push(xa(t)),this.positions.push(e,r,n);}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=xa(t);let r=0,n=this.ids.length-1;for(;r>1;this.ids[t]>=e?n=t:r=t+1;}const i=[];for(;this.ids[r]===e;)i.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return i}static serialize(t,e){const r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return va(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}}static deserialize(t){const e=new ga;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e}}function xa(t){const e=+t;return !isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:ma(String(t))}function va(t,e,r,n){for(;r>1];let s=r-1,a=n+1;for(;;){do{s++;}while(t[s]i);if(s>=a)break;ba(t,s,a),ba(e,3*s,3*a),ba(e,3*s+1,3*a+1),ba(e,3*s+2,3*a+2);}a-r`u_${t}`)),this.type=r;}setUniform(t,e,r){t.set(r.constantOr(this.value));}getBinding(t,e,r){return "color"===this.type?new Sa(t,e):new _a(t,e)}}class za{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;}setUniform(t,e,r,n){const i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i);}getBinding(t,e,r){return "u_pattern"===r.substr(0,9)?new Aa(t,e):new _a(t,e)}}class Pa{constructor(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?2:1,offset:0}))),this.paintVertexArray=new n;}populatePaintArray(t,e,r,n,i){const s=this.paintVertexArray.length,a=this.expression.evaluate(new Ui(0),e,{},n,[],i);this.paintVertexArray.resize(t),this._setPaintValue(s,t,a);}updatePaintArray(t,e,r,n){const i=this.expression.evaluate({zoom:0},r,n);this._setPaintValue(t,e,i);}_setPaintValue(t,e,r){if("color"===this.type){const n=Ma(r);for(let r=t;r`u_${t}_t`)),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?4:2,offset:0}))),this.paintVertexArray=new s;}populatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new Ui(this.zoom),e,{},n,[],i),a=this.expression.evaluate(new Ui(this.zoom+1),e,{},n,[],i),o=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(o,t,s,a);}updatePaintArray(t,e,r,n){const i=this.expression.evaluate({zoom:this.zoom},r,n),s=this.expression.evaluate({zoom:this.zoom+1},r,n);this._setPaintValue(t,e,i,s);}_setPaintValue(t,e,r,n){if("color"===this.type){const i=Ma(r),s=Ma(n);for(let r=t;r`#define HAS_UNIFORM_${t}`)));}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const r=this.binders[e];if(r instanceof Pa||r instanceof Ca)for(let e=0;e!0)){this.programConfigurations={};for(const n of t)this.programConfigurations[n.id]=new Va(n,e,r);this.needsUpload=!1,this._featureMap=new ga,this._bufferOffset=0;}populatePaintArrays(t,e,r,n,i,s){for(const r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e,n,i,s);void 0!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0;}updatePaintArrays(t,e,r,n){for(const i of r)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(t,this._featureMap,e,i,n)||this.needsUpload;}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy();}}function Fa(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function Ta(t,e,r){const n={color:{source:ys,composite:Vs},number:{source:Is,composite:ys}},i=function(t){return {"line-pattern":{source:Js,composite:Js},"fill-pattern":{source:Js,composite:Js},"fill-extrusion-pattern":{source:Js,composite:Js}}[t]}(t);return i&&i[r]||n[e][r]}wi("ConstantBinder",Ia),wi("CrossFadedConstantBinder",za),wi("SourceExpressionBinder",Pa),wi("CrossFadedCompositeBinder",Ba),wi("CompositeExpressionBinder",Ca),wi("ProgramConfiguration",Va,{omit:["_buffers"]}),wi("ProgramConfigurationSet",Ea);const $a=8192,La=Math.pow(2,14)-1,Da=-La-1;function Oa(t){const e=$a/t.extent,r=t.loadGeometry();for(let t=0;tr.x+1||sr.y+1)&&A("Geometry exceeds allowed extent, reduce your vector tile buffer size");}}return r}function ja(t,e){return {type:t.type,id:t.id,properties:t.properties,geometry:e?Oa(t):[]}}function Ra(t,e,r,n,i){t.emplaceBack(2*e+(n+1)/2,2*r+(i+1)/2);}class Ua{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Gs,this.indexArray=new na,this.segments=new oa,this.programConfigurations=new Ea(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){const n=this.layers[0],i=[];let s=null,a=!1;"circle"===n.type&&(s=n.layout.get("circle-sort-key"),a=!s.isConstant());for(const{feature:e,id:n,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=ja(e,t);if(!this.layers[0]._featureFilter.filter(new Ui(this.zoom),u,r))continue;const c=a?s.evaluate(u,{},r):void 0,h={id:n,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Oa(e),patterns:{},sortKey:c};i.push(h);}a&&i.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of i){const{geometry:i,index:s,sourceLayerIndex:a}=n,o=t[s].feature;this.addFeature(n,i,s,r),e.featureIndex.insert(o,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,aa),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}addFeature(t,e,r,n){for(const r of e)for(const e of r){const r=e.x,n=e.y;if(r<0||r>=$a||n<0||n>=$a)continue;const i=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,t.sortKey),s=i.vertexLength;Ra(this.layoutVertexArray,r,n,-1,-1),Ra(this.layoutVertexArray,r,n,1,-1),Ra(this.layoutVertexArray,r,n,1,1),Ra(this.layoutVertexArray,r,n,-1,1),this.indexArray.emplaceBack(s,s+1,s+2),this.indexArray.emplaceBack(s,s+3,s+2),i.vertexLength+=4,i.primitiveLength+=2;}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{},n);}}function qa(t,e){for(let r=0;r1){if(Ka(t,e))return !0;for(let n=0;n1?r:r.sub(e)._mult(i)._add(e))}function Ja(t,e){let r,n,i,s=!1;for(let a=0;ae.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(s=!s);}return s}function Wa(t,e){let r=!1;for(let n=0,i=t.length-1;ne.y!=a.y>e.y&&e.x<(a.x-s.x)*(e.y-s.y)/(a.y-s.y)+s.x&&(r=!r);}return r}function Qa(t,e,r){const n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return !1;const s=S(t,e,r[0]);return s!==S(t,e,r[1])||s!==S(t,e,r[2])||s!==S(t,e,r[3])}function to(t,e,r){const n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function eo(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function ro(t,e,r,n,i){if(!e[0]&&!e[1])return t;const a=s.convert(e)._mult(i);"viewport"===r&&a._rotate(-n);const o=[];for(let e=0;eyo(t,e)))}(l,o),p=c?u*a:u;for(const t of n)for(const e of t){const t=c?e:yo(e,o);let r=p;const n=po([],[e.x,e.y,0,1],o);if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?r*=n[3]/s.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(r*=s.cameraToCenterDistance/n[3]),Na(h,t,r))return !0}return !1}}function yo(t,e){const r=po([],[t.x,t.y,0,1],e);return new s(r[0]/r[3],r[1]/r[3])}class mo extends Ua{}let go;wi("HeatmapBucket",mo,{omit:["layers"]});var xo={get paint(){return go=go||new rs({"heatmap-radius":new Wi(G.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Wi(G.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Ji(G.paint_heatmap["heatmap-intensity"]),"heatmap-color":new es(G.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Ji(G.paint_heatmap["heatmap-opacity"])})}};function vo(t,{width:e,height:r},n,i){if(i){if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==e*r*n)throw new RangeError(`mismatched image size. expected: ${i.length} but got: ${e*r*n}`)}else i=new Uint8Array(e*r*n);return t.width=e,t.height=r,t.data=i,t}function bo(t,{width:e,height:r},n){if(e===t.width&&r===t.height)return;const i=vo({},{width:e,height:r},n);wo(t,i,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,r)},n),t.width=e,t.height=r,t.data=i.data;}function wo(t,e,r,n,i,s){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");const a=t.data,o=e.data;if(a===o)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=s;const a=t.expression.evaluate(e);i.data[r+n+0]=Math.floor(255*a.r/a.a),i.data[r+n+1]=Math.floor(255*a.g/a.a),i.data[r+n+2]=Math.floor(255*a.b/a.a),i.data[r+n+3]=Math.floor(255*a.a);};if(t.clips)for(let e=0,i=0;e80*r){o=1/0,l=1/0;let e=-1/0,n=-1/0;for(let s=r;se&&(e=r),i>n&&(n=i);}u=Math.max(e-o,n-l),u=0!==u?32767/u:0;}return To(s,a,r,o,l,u,0),a}function Eo(t,e,r,n,i){let s;if(i===function(t,e,r,n){let i=0;for(let s=e,a=r-n;s0)for(let i=e;i=e;i-=n)s=tl(i/n|0,t[i],t[i+1],s);return s&&Xo(s,s.next)&&(el(s),s=s.next),s}function Fo(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!Xo(n,n.next)&&0!==Ko(n.prev,n,n.next))n=n.next;else {if(el(n),n=e=n.prev,n===n.next)break;r=!0;}}while(r||n!==e);return e}function To(t,e,r,n,i,s,a){if(!t)return;!a&&s&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=qo(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let s=null;for(e=0;i;){e++;let a=i,o=0;for(let t=0;t0||l>0&&a;)0!==o&&(0===l||!a||i.z<=a.z)?(n=i,i=i.nextZ,o--):(n=a,a=a.nextZ,l--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;i=a;}s.nextZ=null,r*=2;}while(e>1)}(i);}(t,n,i,s);let o=t;for(;t.prev!==t.next;){const l=t.prev,u=t.next;if(s?Lo(t,n,i,s):$o(t))e.push(l.i,t.i,u.i),el(t),t=u.next,o=u.next;else if((t=u)===o){a?1===a?To(t=Do(Fo(t),e),e,r,n,i,s,2):2===a&&Oo(t,e,r,n,i,s):To(Fo(t),e,r,n,i,s,1);break}}}function $o(t){const e=t.prev,r=t,n=t.next;if(Ko(e,r,n)>=0)return !1;const i=e.x,s=r.x,a=n.x,o=e.y,l=r.y,u=n.y,c=is?i>a?i:a:s>a?s:a,f=o>l?o>u?o:u:l>u?l:u;let d=n.next;for(;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&Zo(i,o,s,l,a,u,d.x,d.y)&&Ko(d.prev,d,d.next)>=0)return !1;d=d.next;}return !0}function Lo(t,e,r,n){const i=t.prev,s=t,a=t.next;if(Ko(i,s,a)>=0)return !1;const o=i.x,l=s.x,u=a.x,c=i.y,h=s.y,p=a.y,f=ol?o>u?o:u:l>u?l:u,m=c>h?c>p?c:p:h>p?h:p,g=qo(f,d,e,r,n),x=qo(y,m,e,r,n);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Zo(o,c,l,h,u,p,v.x,v.y)&&Ko(v.prev,v,v.next)>=0)return !1;if(v=v.prevZ,b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Zo(o,c,l,h,u,p,b.x,b.y)&&Ko(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&Zo(o,c,l,h,u,p,v.x,v.y)&&Ko(v.prev,v,v.next)>=0)return !1;v=v.prevZ;}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&Zo(o,c,l,h,u,p,b.x,b.y)&&Ko(b.prev,b,b.next)>=0)return !1;b=b.nextZ;}return !0}function Do(t,e){let r=t;do{const n=r.prev,i=r.next.next;!Xo(n,i)&&Ho(n,r,r.next,i)&&Wo(n,i)&&Wo(i,n)&&(e.push(n.i,r.i,i.i),el(r),el(r.next),r=t=i),r=r.next;}while(r!==t);return Fo(r)}function Oo(t,e,r,n,i,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&Go(a,t)){let o=Qo(a,t);return a=Fo(a,a.next),o=Fo(o,o.next),To(a,e,r,n,i,s,0),void To(o,e,r,n,i,s,0)}t=t.next;}a=a.next;}while(a!==t)}function jo(t,e){return t.x-e.x}function Ro(t,e){const r=function(t,e){let r=e;const n=t.x,i=t.y;let s,a=-1/0;do{if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){const t=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(t<=n&&t>a&&(a=t,s=r.x=r.x&&r.x>=l&&n!==r.x&&Zo(is.x||r.x===s.x&&Uo(s,r)))&&(s=r,c=e);}r=r.next;}while(r!==o);return s}(t,e);if(!r)return e;const n=Qo(r,t);return Fo(n,n.next),Fo(r,r.next)}function Uo(t,e){return Ko(t.prev,t,e.prev)<0&&Ko(e.next,t,t.next)<0}function qo(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function No(t){let e=t,r=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(n-o)>=(r-a)*(e-o)&&(r-a)*(s-o)>=(i-a)*(n-o)}function Go(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&Ho(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(Wo(t,e)&&Wo(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{r.y>s!=r.next.y>s&&r.next.y!==r.y&&i<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Ko(t.prev,t,e.prev)||Ko(t,e.prev,e))||Xo(t,e)&&Ko(t.prev,t,t.next)>0&&Ko(e.prev,e,e.next)>0)}function Ko(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Xo(t,e){return t.x===e.x&&t.y===e.y}function Ho(t,e,r,n){const i=Jo(Ko(t,e,r)),s=Jo(Ko(t,e,n)),a=Jo(Ko(r,n,t)),o=Jo(Ko(r,n,e));return i!==s&&a!==o||!(0!==i||!Yo(t,r,e))||!(0!==s||!Yo(t,n,e))||!(0!==a||!Yo(r,t,n))||!(0!==o||!Yo(r,e,n))}function Yo(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function Jo(t){return t>0?1:t<0?-1:0}function Wo(t,e){return Ko(t.prev,t,t.next)<0?Ko(t,e,t.next)>=0&&Ko(t,t.prev,e)>=0:Ko(t,e,t.prev)<0||Ko(t,t.next,e)<0}function Qo(t,e){const r=rl(t.i,t.x,t.y),n=rl(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,s.next=n,n.prev=s,n}function tl(t,e,r,n){const i=rl(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function el(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ);}function rl(t,e,r){return {i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function nl(t,e,r){const n=r.patternDependencies;let i=!1;for(const r of e){const e=r.paint.get(`${t}-pattern`);e.isConstant()||(i=!0);const s=e.constantOr(null);s&&(i=!0,n[s.to]=!0,n[s.from]=!0);}return i}function il(t,e,r,n,i){const s=i.patternDependencies;for(const a of e){const e=a.paint.get(`${t}-pattern`).value;if("constant"!==e.kind){let t=e.evaluate({zoom:n-1},r,{},i.availableImages),o=e.evaluate({zoom:n},r,{},i.availableImages),l=e.evaluate({zoom:n+1},r,{},i.availableImages);t=t&&t.name?t.name:t,o=o&&o.name?o.name:o,l=l&&l.name?l.name:l,s[t]=!0,s[o]=!0,s[l]=!0,r.patterns[a.id]={min:t,mid:o,max:l};}}return r}class sl{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new Ks,this.indexArray=new na,this.indexArray2=new ia,this.programConfigurations=new Ea(t.layers,t.zoom),this.segments=new oa,this.segments2=new oa,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=nl("fill",this.layers,e);const n=this.layers[0].layout.get("fill-sort-key"),i=!n.isConstant(),s=[];for(const{feature:a,id:o,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=ja(a,t);if(!this.layers[0]._featureFilter.filter(new Ui(this.zoom),c,r))continue;const h=i?n.evaluate(c,{},r,e.availableImages):void 0,p={id:o,properties:a.properties,type:a.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:Oa(a),patterns:{},sortKey:h};s.push(p);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=il("fill",this.layers,n,this.zoom,e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{});e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}addFeatures(t,e,r){for(const t of this.patternFeatures)this.addFeature(t,t.geometry,t.index,e,r);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Bo),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());}addFeature(t,e,r,n,i){for(const t of xr(e,500)){let e=0;for(const r of t)e+=r.length;const r=this.segments.prepareSegment(e,this.layoutVertexArray,this.indexArray),n=r.vertexLength,i=[],s=[];for(const e of t){if(0===e.length)continue;e!==t[0]&&s.push(i.length/2);const r=this.segments2.prepareSegment(e.length,this.layoutVertexArray,this.indexArray2),n=r.vertexLength;this.layoutVertexArray.emplaceBack(e[0].x,e[0].y),this.indexArray2.emplaceBack(n+e.length-1,n),i.push(e[0].x),i.push(e[0].y);for(let t=1;t>3;}if(i--,1===n||2===n)s+=t.readSVarint(),a+=t.readSVarint(),1===n&&(e&&o.push(e),e=[]),e.push(new dl(s,a));else {if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone());}}return e&&o.push(e),o},ml.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,s=0,a=1/0,o=-1/0,l=1/0,u=-1/0;t.pos>3;}if(n--,1===r||2===r)(i+=t.readSVarint())o&&(o=i),(s+=t.readSVarint())u&&(u=s);else if(7!==r)throw new Error("unknown command "+r)}return [a,l,o,u]},ml.prototype.toGeoJSON=function(t,e,r){var n,i,s=this.extent*Math.pow(2,r),a=this.extent*t,o=this.extent*e,l=this.loadGeometry(),u=ml.types[this.type];function c(t){for(var e=0;e>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null;}return e}(r));}wl.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new vl(this._pbf,e,this.extent,this._keys,this._values)};var Al=bl;function Sl(t,e,r){if(3===t){var n=new Al(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n);}}fl.VectorTile=function(t,e){this.layers=t.readFields(Sl,{},e);},fl.VectorTileFeature=yl,fl.VectorTileLayer=bl;const kl=fl.VectorTileFeature.types,Ml=Math.pow(2,13);function Il(t,e,r,n,i,s,a,o){t.emplaceBack(e,r,2*Math.floor(n*Ml)+a,i*Ml*2,s*Ml*2,Math.round(o));}class zl{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Xs,this.centroidVertexArray=new Zs,this.indexArray=new na,this.programConfigurations=new Ea(t.layers,t.zoom),this.segments=new oa,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.features=[],this.hasPattern=nl("fill-extrusion",this.layers,e);for(const{feature:n,id:i,index:s,sourceLayerIndex:a}of t){const t=this.layers[0]._featureFilter.needGeometry,o=ja(n,t);if(!this.layers[0]._featureFilter.filter(new Ui(this.zoom),o,r))continue;const l={id:i,sourceLayerIndex:a,index:s,geometry:t?o.geometry:Oa(n),properties:n.properties,type:n.type,patterns:{}};this.hasPattern?this.features.push(il("fill-extrusion",this.layers,l,this.zoom,e)):this.addFeature(l,l.geometry,s,r,{}),e.featureIndex.insert(n,l.geometry,s,a,this.index,!0);}}addFeatures(t,e,r){for(const t of this.features){const{geometry:n}=t;this.addFeature(t,n,t.index,e,r);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,pl),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,hl.members,!0),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy());}addFeature(t,e,r,n,i){for(const r of xr(e,500)){const e={x:0,y:0,vertexCount:0};let n=0;for(const t of r)n+=t.length;let i=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray);for(const t of r){if(0===t.length)continue;if(Cl(t))continue;let r=0;for(let n=0;n=1){const a=t[n-1];if(!Pl(s,a)){i.vertexLength+4>oa.MAX_VERTEX_ARRAY_LENGTH&&(i=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const t=s.sub(a)._perp()._unit(),n=a.dist(s);r+n>32768&&(r=0),Il(this.layoutVertexArray,s.x,s.y,t.x,t.y,0,0,r),Il(this.layoutVertexArray,s.x,s.y,t.x,t.y,0,1,r),e.x+=2*s.x,e.y+=2*s.y,e.vertexCount+=2,r+=n,Il(this.layoutVertexArray,a.x,a.y,t.x,t.y,0,0,r),Il(this.layoutVertexArray,a.x,a.y,t.x,t.y,0,1,r),e.x+=2*a.x,e.y+=2*a.y,e.vertexCount+=2;const o=i.vertexLength;this.indexArray.emplaceBack(o,o+2,o+1),this.indexArray.emplaceBack(o+1,o+2,o+3),i.vertexLength+=4,i.primitiveLength+=2;}}}}if(i.vertexLength+n>oa.MAX_VERTEX_ARRAY_LENGTH&&(i=this.segments.prepareSegment(n,this.layoutVertexArray,this.indexArray)),"Polygon"!==kl[t.type])continue;const s=[],a=[],o=i.vertexLength;for(const t of r)if(0!==t.length){t!==r[0]&&a.push(s.length/2);for(let r=0;r$a)||t.y===e.y&&(t.y<0||t.y>$a)}function Cl(t){return t.every((t=>t.x<0))||t.every((t=>t.x>$a))||t.every((t=>t.y<0))||t.every((t=>t.y>$a))}let Bl;wi("FillExtrusionBucket",zl,{omit:["layers","features"]});var Vl={get paint(){return Bl=Bl||new rs({"fill-extrusion-opacity":new Ji(G["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Wi(G["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Ji(G["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Ji(G["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Qi(G["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new Wi(G["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Wi(G["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new Ji(G["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class El extends is{constructor(t){super(t,Vl);}createBucket(t){return new zl(t)}queryRadius(){return eo(this.paint.get("fill-extrusion-translate"))}is3D(){return !0}queryIntersectsFeature(t,e,r,n,i,a,o,l){const u=ro(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),a.angle,o),c=this.paint.get("fill-extrusion-height").evaluate(e,r),h=this.paint.get("fill-extrusion-base").evaluate(e,r),p=function(t,e,r,n){const i=[];for(const r of t){const t=[r.x,r.y,0,1];po(t,t,e),i.push(new s(t[0]/t[3],t[1]/t[3]));}return i}(u,l),f=function(t,e,r,n){const i=[],a=[],o=n[8]*e,l=n[9]*e,u=n[10]*e,c=n[11]*e,h=n[8]*r,p=n[9]*r,f=n[10]*r,d=n[11]*r;for(const e of t){const t=[],r=[];for(const i of e){const e=i.x,a=i.y,y=n[0]*e+n[4]*a+n[12],m=n[1]*e+n[5]*a+n[13],g=n[2]*e+n[6]*a+n[14],x=n[3]*e+n[7]*a+n[15],v=g+u,b=x+c,w=y+h,_=m+p,A=g+f,S=x+d,k=new s((y+o)/b,(m+l)/b);k.z=v/b,t.push(k);const M=new s(w/S,_/S);M.z=A/S,r.push(M);}i.push(t),a.push(r);}return [i,a]}(n,h,c,l);return function(t,e,r){let n=1/0;Za(r,e)&&(n=Tl(r,e[0]));for(let i=0;it.id)),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={};})),this.layoutVertexArray=new Hs,this.layoutVertexArray2=new Ys,this.indexArray=new na,this.programConfigurations=new Ea(t.layers,t.zoom),this.segments=new oa,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=nl("line",this.layers,e);const n=this.layers[0].layout.get("line-sort-key"),i=!n.isConstant(),s=[];for(const{feature:e,id:a,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=ja(e,t);if(!this.layers[0]._featureFilter.filter(new Ui(this.zoom),u,r))continue;const c=i?n.evaluate(u,{},r):void 0,h={id:a,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:Oa(e),patterns:{},sortKey:c};s.push(h);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=il("line",this.layers,n,this.zoom,e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{});e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}addFeatures(t,e,r){for(const t of this.patternFeatures)this.addFeature(t,t.geometry,t.index,e,r);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,Ol)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Ll),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_end"))return {start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,r,n,i){const s=this.layers[0].layout,a=s.get("line-join").evaluate(t,{}),o=s.get("line-cap"),l=s.get("line-miter-limit"),u=s.get("line-round-limit");this.lineClips=this.lineFeatureClips(t);for(const r of e)this.addLine(r,t,a,o,l,u);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n);}addLine(t,e,r,n,i,s){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[o-1].equals(t[o-2]);)o--;let l=0;for(;l0;if(w&&e>l){const t=h.dist(p);if(t>2*u){const e=h.sub(h.sub(p)._mult(u/t)._round());this.updateDistance(p,e),this.addCurrentVertex(e,d,0,0,c),p=e;}}const A=p&&f;let S=A?r:a?"butt":n;if(A&&"round"===S&&(vi&&(S="bevel"),"bevel"===S&&(v>2&&(S="flipbevel"),v100)m=y.mult(-1);else {const t=v*d.add(y).mag()/d.sub(y).mag();m._perp()._mult(t*(_?-1:1));}this.addCurrentVertex(h,m,0,0,c),this.addCurrentVertex(h,m.mult(-1),0,0,c);}else if("bevel"===S||"fakeround"===S){const t=-Math.sqrt(v*v-1),e=_?t:0,r=_?0:t;if(p&&this.addCurrentVertex(h,d,e,r,c),"fakeround"===S){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*u){const e=h.add(f.sub(h)._mult(u/t)._round());this.updateDistance(h,e),this.addCurrentVertex(e,y,0,0,c),h=e;}}}}addCurrentVertex(t,e,r,n,i,s=!1){const a=e.y*n-e.x,o=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,s,!1,r,i),this.addHalfVertex(t,a,o,s,!0,-n,i),this.distance>Ul/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,r,n,i,s));}addHalfVertex({x:t,y:e},r,n,i,s,a,o){const l=.5*(this.lineClips?this.scaledDistance*(Ul-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*r)+128,Math.round(63*n)+128,1+(0===a?0:a<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,u),o.primitiveLength++),s?this.e2=u:this.e1=u;}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance;}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance();}}let Nl,Zl;wi("LineBucket",ql,{omit:["layers","patternFeatures"]});var Gl={get paint(){return Zl=Zl||new rs({"line-opacity":new Wi(G.paint_line["line-opacity"]),"line-color":new Wi(G.paint_line["line-color"]),"line-translate":new Ji(G.paint_line["line-translate"]),"line-translate-anchor":new Ji(G.paint_line["line-translate-anchor"]),"line-width":new Wi(G.paint_line["line-width"]),"line-gap-width":new Wi(G.paint_line["line-gap-width"]),"line-offset":new Wi(G.paint_line["line-offset"]),"line-blur":new Wi(G.paint_line["line-blur"]),"line-dasharray":new ts(G.paint_line["line-dasharray"]),"line-pattern":new Qi(G.paint_line["line-pattern"]),"line-gradient":new es(G.paint_line["line-gradient"])})},get layout(){return Nl=Nl||new rs({"line-cap":new Ji(G.layout_line["line-cap"]),"line-join":new Wi(G.layout_line["line-join"]),"line-miter-limit":new Ji(G.layout_line["line-miter-limit"]),"line-round-limit":new Ji(G.layout_line["line-round-limit"]),"line-sort-key":new Wi(G.layout_line["line-sort-key"])})}};class Kl extends Wi{possiblyEvaluate(t,e){return e=new Ui(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,r,n){return e=g({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,r,n)}}let Xl;class Hl extends is{constructor(t){super(t,Gl),this.gradientVersion=0,Xl||(Xl=new Kl(Gl.paint.properties["line-width"].specification),Xl.useIntegerZoom=!0);}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return void 0!==t._styleExpression}(t)&&t._styleExpression.expression instanceof Ae,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=Xl.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t);}createBucket(t){return new ql(t)}queryRadius(t){const e=t,r=Yl(to("line-width",this,e),to("line-gap-width",this,e)),n=to("line-offset",this,e);return r/2+Math.abs(n)+eo(this.paint.get("line-translate"))}queryIntersectsFeature(t,e,r,n,i,a,o){const l=ro(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),a.angle,o),u=o/2*Yl(this.paint.get("line-width").evaluate(e,r),this.paint.get("line-gap-width").evaluate(e,r)),c=this.paint.get("line-offset").evaluate(e,r);return c&&(n=function(t,e){const r=[];for(let n=0;n=3)for(let e=0;e0?e+2*t:t}const Jl=ls([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Wl=ls([{name:"a_projected_pos",components:3,type:"Float32"}],4);ls([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Ql=ls([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);ls([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const tu=ls([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),eu=ls([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function ru(t,e,r){return t.sections.forEach((t=>{t.text=function(t,e,r){const n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),Ri.applyArabicShaping&&(t=Ri.applyArabicShaping(t)),t}(t.text,e,r);})),t}ls([{name:"triangle",components:3,type:"Uint16"}]),ls([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),ls([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),ls([{type:"Float32",name:"offsetX"}]),ls([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),ls([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const nu={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var iu=24,su=lu,au=function(t,e,r,n,i){var s,a,o=8*i-n-1,l=(1<>1,c=-7,h=r?i-1:0,p=r?-1:1,f=t[e+h];for(h+=p,s=f&(1<<-c)-1,f>>=-c,c+=o;c>0;s=256*s+t[e+h],h+=p,c-=8);for(a=s&(1<<-c)-1,s>>=-c,c+=n;c>0;a=256*a+t[e+h],h+=p,c-=8);if(0===s)s=1-u;else {if(s===l)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),s-=u;}return (f?-1:1)*a*Math.pow(2,s-n)},ou=function(t,e,r,n,i,s){var a,o,l,u=8*s-i-1,c=(1<>1,p=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:s-1,d=n?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=c):(a=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-a))<1&&(a--,l*=2),(e+=a+h>=1?p/l:p*Math.pow(2,1-h))*l>=2&&(a++,l/=2),a+h>=c?(o=0,a=c):a+h>=1?(o=(e*l-1)*Math.pow(2,i),a+=h):(o=e*Math.pow(2,h-1)*Math.pow(2,i),a=0));i>=8;t[r+f]=255&o,f+=d,o/=256,i-=8);for(a=a<0;t[r+f]=255&a,f+=d,a/=256,u-=8);t[r+f-d]|=128*y;};function lu(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length;}lu.Varint=0,lu.Fixed64=1,lu.Bytes=2,lu.Fixed32=5;var uu=4294967296,cu=1/uu,hu="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");function pu(t){return t.type===lu.Bytes?t.readVarint()+t.pos:t.pos+1}function fu(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function du(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i];}function yu(t,e){for(var r=0;r>>8,t[r+2]=e>>>16,t[r+3]=e>>>24;}function Mu(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}lu.prototype={destroy:function(){this.buf=null;},readFields:function(t,e,r){for(r=r||this.length;this.pos>3,s=this.pos;this.type=7&n,t(i,e,this),this.pos===s&&this.skip(n);}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=Su(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=Mu(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=Su(this.buf,this.pos)+Su(this.buf,this.pos+4)*uu;return this.pos+=8,t},readSFixed64:function(){var t=Su(this.buf,this.pos)+Mu(this.buf,this.pos+4)*uu;return this.pos+=8,t},readFloat:function(){var t=au(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=au(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,s=r.buf;if(n=(112&(i=s[r.pos++]))>>4,i<128)return fu(t,n,e);if(n|=(127&(i=s[r.pos++]))<<3,i<128)return fu(t,n,e);if(n|=(127&(i=s[r.pos++]))<<10,i<128)return fu(t,n,e);if(n|=(127&(i=s[r.pos++]))<<17,i<128)return fu(t,n,e);if(n|=(127&(i=s[r.pos++]))<<24,i<128)return fu(t,n,e);if(n|=(1&(i=s[r.pos++]))<<31,i<128)return fu(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&hu?function(t,e,r){return hu.decode(t.subarray(e,r))}(this.buf,e,t):function(t,e,r){for(var n="",i=e;i239?4:l>223?3:l>191?2:1;if(i+c>r)break;1===c?l<128&&(u=l):2===c?128==(192&(s=t[i+1]))&&(u=(31&l)<<6|63&s)<=127&&(u=null):3===c?(a=t[i+2],128==(192&(s=t[i+1]))&&128==(192&a)&&((u=(15&l)<<12|(63&s)<<6|63&a)<=2047||u>=55296&&u<=57343)&&(u=null)):4===c&&(a=t[i+2],o=t[i+3],128==(192&(s=t[i+1]))&&128==(192&a)&&128==(192&o)&&((u=(15&l)<<18|(63&s)<<12|(63&a)<<6|63&o)<=65535||u>=1114112)&&(u=null)),null===u?(u=65533,c=1):u>65535&&(u-=65536,n+=String.fromCharCode(u>>>10&1023|55296),u=56320|1023&u),n+=String.fromCharCode(u),i+=c;}return n}(this.buf,e,t)},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){if(this.type!==lu.Bytes)return t.push(this.readVarint(e));var r=pu(this);for(t=t||[];this.pos127;);else if(e===lu.Bytes)this.pos=this.readVarint()+this.pos;else if(e===lu.Fixed32)this.pos+=4;else {if(e!==lu.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8;}},writeTag:function(t,e){this.writeVarint(t<<3|e);},realloc:function(t){for(var e=this.length||16;e268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))));}(n,e);}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))));},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t);},writeBoolean:function(t){this.writeVarint(Boolean(t));},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,s=0;s55295&&n<57344){if(!i){n>56319||s+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&du(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;},writeFloat:function(t){this.realloc(4),ou(this.buf,t,this.pos,!0,23,4),this.pos+=4;},writeDouble:function(t){this.realloc(8),ou(this.buf,t,this.pos,!0,52,8),this.pos+=8;},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&du(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;},writeMessage:function(t,e,r){this.writeTag(t,lu.Bytes),this.writeRawMessage(e,r);},writePackedVarint:function(t,e){e.length&&this.writeMessage(t,yu,e);},writePackedSVarint:function(t,e){e.length&&this.writeMessage(t,mu,e);},writePackedBoolean:function(t,e){e.length&&this.writeMessage(t,vu,e);},writePackedFloat:function(t,e){e.length&&this.writeMessage(t,gu,e);},writePackedDouble:function(t,e){e.length&&this.writeMessage(t,xu,e);},writePackedFixed32:function(t,e){e.length&&this.writeMessage(t,bu,e);},writePackedSFixed32:function(t,e){e.length&&this.writeMessage(t,wu,e);},writePackedFixed64:function(t,e){e.length&&this.writeMessage(t,_u,e);},writePackedSFixed64:function(t,e){e.length&&this.writeMessage(t,Au,e);},writeBytesField:function(t,e){this.writeTag(t,lu.Bytes),this.writeBytes(e);},writeFixed32Field:function(t,e){this.writeTag(t,lu.Fixed32),this.writeFixed32(e);},writeSFixed32Field:function(t,e){this.writeTag(t,lu.Fixed32),this.writeSFixed32(e);},writeFixed64Field:function(t,e){this.writeTag(t,lu.Fixed64),this.writeFixed64(e);},writeSFixed64Field:function(t,e){this.writeTag(t,lu.Fixed64),this.writeSFixed64(e);},writeVarintField:function(t,e){this.writeTag(t,lu.Varint),this.writeVarint(e);},writeSVarintField:function(t,e){this.writeTag(t,lu.Varint),this.writeSVarint(e);},writeStringField:function(t,e){this.writeTag(t,lu.Bytes),this.writeString(e);},writeFloatField:function(t,e){this.writeTag(t,lu.Fixed32),this.writeFloat(e);},writeDoubleField:function(t,e){this.writeTag(t,lu.Fixed64),this.writeDouble(e);},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e));}};var Iu=r(su);const zu=3;function Pu(t,e,r){1===t&&r.readMessage(Cu,e);}function Cu(t,e,r){if(3===t){const{id:t,bitmap:n,width:i,height:s,left:a,top:o,advance:l}=r.readMessage(Bu,{});e.push({id:t,bitmap:new _o({width:i+2*zu,height:s+2*zu},n),metrics:{width:i,height:s,left:a,top:o,advance:l}});}}function Bu(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint());}const Vu=zu;function Eu(t){let e=0,r=0;for(const n of t)e+=n.w*n.h,r=Math.max(r,n.w);t.sort(((t,e)=>e.h-t.h));const n=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}];let i=0,s=0;for(const e of t)for(let t=n.length-1;t>=0;t--){const r=n[t];if(!(e.w>r.w||e.h>r.h)){if(e.x=r.x,e.y=r.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===r.w&&e.h===r.h){const e=n.pop();t=0&&r>=t&&Uu[this.text.charCodeAt(r)];r--)e--;this.text=this.text.substring(t,e),this.sectionIndex=this.sectionIndex.slice(t,e);}substring(t,e){const r=new ju;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((t,e)=>Math.max(t,this.sections[e].scale)),0)}addTextSection(t,e){this.text+=t.text,this.sections.push(Ou.forText(t.scale,t.fontStack||e));const r=this.sections.length-1;for(let e=0;e=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Ru(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=ju.fromFeature(e,s);let g;p===t.ah.vertical&&m.verticalizePunctuation();const{processBidirectionalText:x,processStyledBidirectionalText:v}=Ri;if(x&&1===m.sections.length){g=[];const t=x(m.toString(),Yu(m,c,a,r,i,d));for(const e of t){const t=new ju;t.text=e,t.sections=m.sections;for(let r=0;r0&&n>_&&(_=n);}else {const t=n[y.fontStack],e=t&&t[g];if(e&&e.rect)A=e.rect,b=e.metrics;else {const t=r[y.fontStack],e=t&&t[g];if(!e)continue;b=e.metrics;}x=(s-y.scale)*iu;}M?(e.verticalizable=!0,w.push({glyph:g,imageName:S,x:f,y:d+x,vertical:M,scale:y.scale,fontStack:y.fontStack,sectionIndex:m,metrics:b,rect:A}),f+=k*y.scale+c):(w.push({glyph:g,imageName:S,x:f,y:d+x,vertical:M,scale:y.scale,fontStack:y.fontStack,sectionIndex:m,metrics:b,rect:A}),f+=b.advance*y.scale+c);}0!==w.length&&(y=Math.max(f-c,y),Wu(w,0,w.length-1,g,_)),f=0;const A=a*s+_;b.lineOffset=Math.max(_,l),d+=A,m=Math.max(A,m),++x;}var v;const b=d-Du,{horizontalAlign:w,verticalAlign:_}=Ju(o);((function(t,e,r,n,i,s,a,o,l){const u=(e-r)*i;let c=0;c=s!==a?-o*n-Du:(-n*l+.5)*a;for(const e of t)for(const t of e.positionedGlyphs)t.x+=u,t.y+=c;}))(e.positionedLines,g,w,_,y,m,a,b,s.length),e.top+=-_*b,e.bottom=e.top+b,e.left+=-w*y,e.right=e.left+y;}(w,r,n,i,g,o,l,u,p,c,f,y),!function(t){for(const e of t)if(0!==e.positionedGlyphs.length)return !1;return !0}(b)&&w}const Uu={9:!0,10:!0,11:!0,12:!0,13:!0,32:!0},qu={10:!0,32:!0,38:!0,41:!0,43:!0,45:!0,47:!0,173:!0,183:!0,8203:!0,8208:!0,8211:!0,8231:!0},Nu={40:!0};function Zu(t,e,r,n,i,s){if(e.imageName){const t=n[e.imageName];return t?t.displaySize[0]*e.scale*iu/s+i:0}{const n=r[e.fontStack],s=n&&n[t];return s?s.metrics.advance*e.scale+i:0}}function Gu(t,e,r,n){const i=Math.pow(t-e,2);return n?t=0;let u=0;for(let r=0;ru){const t=Math.ceil(s/u);i*=t/a,a=t;}return {x1:n,y1:i,x2:n+s,y2:i+a}}function ec(t,e,r,n,i,s){const a=t.image;let o;if(a.content){const t=a.content,e=a.pixelRatio||1;o=[t[0]/e,t[1]/e,a.displaySize[0]-t[2]/e,a.displaySize[1]-t[3]/e];}const l=e.left*s,u=e.right*s;let c,h,p,f;"width"===r||"both"===r?(f=i[0]+l-n[3],h=i[0]+u+n[1]):(f=i[0]+(l+u-a.displaySize[0])/2,h=f+a.displaySize[0]);const d=e.top*s,y=e.bottom*s;return "height"===r||"both"===r?(c=i[1]+d-n[0],p=i[1]+y+n[2]):(c=i[1]+(d+y-a.displaySize[1])/2,p=c+a.displaySize[1]),{image:a,top:c,right:h,bottom:p,left:f,collisionPadding:o}}const rc=255,nc=128,ic=rc*nc;function sc(t,e){const{expression:r}=e;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new Ui(t+1))};if("source"===r.kind)return {kind:"source"};{const{zoomStops:e,interpolationType:n}=r;let i=0;for(;it.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=lo([]),this.placementViewportMatrix=lo([]);const r=this.layers[0]._unevaluatedLayout._values;this.textSizeData=sc(this.zoom,r["text-size"]),this.iconSizeData=sc(this.zoom,r["icon-size"]);const n=this.layers[0].layout,i=n.get("symbol-sort-key"),s=n.get("symbol-z-order");this.canOverlap="never"!==ac(n,"text-overlap","text-allow-overlap")||"never"!==ac(n,"icon-overlap","icon-allow-overlap")||n.get("text-ignore-placement")||n.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==s&&!i.isConstant(),this.sortFeaturesByY=("viewport-y"===s||"auto"===s&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===n.get("symbol-placement")&&(this.writingModes=n.get("text-writing-mode").map((e=>t.ah[e]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=e.sourceID;}createArrays(){this.text=new pc(new Ea(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new pc(new Ea(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new Os,this.lineVertexArray=new js,this.symbolInstances=new Ds,this.textAnchorOffsets=new Us;}calculateGlyphDependencies(t,e,r,n,i){for(let s=0;s0)&&("constant"!==a.value.kind||a.value.value.length>0),c="constant"!==l.value.kind||!!l.value.value||Object.keys(l.parameters).length>0,h=s.get("symbol-sort-key");if(this.features=[],!u&&!c)return;const p=r.iconDependencies,f=r.glyphDependencies,d=r.availableImages,y=new Ui(this.zoom);for(const{feature:r,id:o,index:l,sourceLayerIndex:m}of e){const e=i._featureFilter.needGeometry,g=ja(r,e);if(!i._featureFilter.filter(y,g,n))continue;let x,v;if(e||(g.geometry=Oa(r)),u){const t=i.getValueAndResolveTokens("text-field",g,n,d),e=Yt.factory(t),r=this.hasRTLText=this.hasRTLText||hc(e);(!r||"unavailable"===Ri.getRTLTextPluginStatus()||r&&Ri.isParsed())&&(x=ru(e,i,g));}if(c){const t=i.getValueAndResolveTokens("icon-image",g,n,d);v=t instanceof te?t:te.fromString(t);}if(!x&&!v)continue;const b=this.sortFeaturesByKey?h.evaluate(g,{},n):void 0;if(this.features.push({id:o,text:x,icon:v,index:l,sourceLayerIndex:m,geometry:g.geometry,properties:r.properties,type:oc[r.type],sortKey:b}),v&&(p[v.name]=!0),x){const e=a.evaluate(g,{},n).join(","),r="viewport"!==s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(t.ah.vertical)>=0;for(const t of x.sections)if(t.image)p[t.image.name]=!0;else {const n=Pi(x.toString()),i=t.fontStack||e,s=f[i]=f[i]||{};this.calculateGlyphDependencies(t.text,s,r,this.allowVerticalPlacement,n);}}}"line"===s.get("symbol-placement")&&(this.features=function(t){const e={},r={},n=[];let i=0;function s(e){n.push(t[e]),i++;}function a(t,e,i){const s=r[t];return delete r[t],r[e]=s,n[s].geometry[0].pop(),n[s].geometry[0]=n[s].geometry[0].concat(i[0]),s}function o(t,r,i){const s=e[r];return delete e[r],e[t]=s,n[s].geometry[0].shift(),n[s].geometry[0]=i[0].concat(n[s].geometry[0]),s}function l(t,e,r){const n=r?e[0][e[0].length-1]:e[0][0];return `${t}:${n.x}:${n.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey));}update(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,r),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,r));}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0;}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();}addToLineVertexArray(t,e){const r=this.lineVertexArray.length;if(void 0!==t.segment){let r=t.dist(e[t.segment+1]),n=t.dist(e[t.segment]);const i={};for(let n=t.segment+1;n=0;r--)i[r]={x:e[r].x,y:e[r].y,tileUnitDistanceFromAnchor:n},r>0&&(n+=e[r-1].dist(e[r]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs;for(let e=r.vertexStartIndex;en[t]-n[e]||i[e]-i[t])),s}addToSortKeyRanges(t,e){const r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,r)=>{t>=0&&r.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t);})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}}}let yc,mc;wi("SymbolBucket",dc,{omit:["layers","collisionBoxArray","features","compareText"]}),dc.MAX_GLYPHS=65535,dc.addDynamicAttributes=cc;var gc={get paint(){return mc=mc||new rs({"icon-opacity":new Wi(G.paint_symbol["icon-opacity"]),"icon-color":new Wi(G.paint_symbol["icon-color"]),"icon-halo-color":new Wi(G.paint_symbol["icon-halo-color"]),"icon-halo-width":new Wi(G.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Wi(G.paint_symbol["icon-halo-blur"]),"icon-translate":new Ji(G.paint_symbol["icon-translate"]),"icon-translate-anchor":new Ji(G.paint_symbol["icon-translate-anchor"]),"text-opacity":new Wi(G.paint_symbol["text-opacity"]),"text-color":new Wi(G.paint_symbol["text-color"],{runtimeType:pt,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new Wi(G.paint_symbol["text-halo-color"]),"text-halo-width":new Wi(G.paint_symbol["text-halo-width"]),"text-halo-blur":new Wi(G.paint_symbol["text-halo-blur"]),"text-translate":new Ji(G.paint_symbol["text-translate"]),"text-translate-anchor":new Ji(G.paint_symbol["text-translate-anchor"])})},get layout(){return yc=yc||new rs({"symbol-placement":new Ji(G.layout_symbol["symbol-placement"]),"symbol-spacing":new Ji(G.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Ji(G.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Wi(G.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Ji(G.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new Ji(G.layout_symbol["icon-allow-overlap"]),"icon-overlap":new Ji(G.layout_symbol["icon-overlap"]),"icon-ignore-placement":new Ji(G.layout_symbol["icon-ignore-placement"]),"icon-optional":new Ji(G.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Ji(G.layout_symbol["icon-rotation-alignment"]),"icon-size":new Wi(G.layout_symbol["icon-size"]),"icon-text-fit":new Ji(G.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Ji(G.layout_symbol["icon-text-fit-padding"]),"icon-image":new Wi(G.layout_symbol["icon-image"]),"icon-rotate":new Wi(G.layout_symbol["icon-rotate"]),"icon-padding":new Wi(G.layout_symbol["icon-padding"]),"icon-keep-upright":new Ji(G.layout_symbol["icon-keep-upright"]),"icon-offset":new Wi(G.layout_symbol["icon-offset"]),"icon-anchor":new Wi(G.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Ji(G.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Ji(G.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Ji(G.layout_symbol["text-rotation-alignment"]),"text-field":new Wi(G.layout_symbol["text-field"]),"text-font":new Wi(G.layout_symbol["text-font"]),"text-size":new Wi(G.layout_symbol["text-size"]),"text-max-width":new Wi(G.layout_symbol["text-max-width"]),"text-line-height":new Ji(G.layout_symbol["text-line-height"]),"text-letter-spacing":new Wi(G.layout_symbol["text-letter-spacing"]),"text-justify":new Wi(G.layout_symbol["text-justify"]),"text-radial-offset":new Wi(G.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Ji(G.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new Wi(G.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new Wi(G.layout_symbol["text-anchor"]),"text-max-angle":new Ji(G.layout_symbol["text-max-angle"]),"text-writing-mode":new Ji(G.layout_symbol["text-writing-mode"]),"text-rotate":new Wi(G.layout_symbol["text-rotate"]),"text-padding":new Ji(G.layout_symbol["text-padding"]),"text-keep-upright":new Ji(G.layout_symbol["text-keep-upright"]),"text-transform":new Wi(G.layout_symbol["text-transform"]),"text-offset":new Wi(G.layout_symbol["text-offset"]),"text-allow-overlap":new Ji(G.layout_symbol["text-allow-overlap"]),"text-overlap":new Ji(G.layout_symbol["text-overlap"]),"text-ignore-placement":new Ji(G.layout_symbol["text-ignore-placement"]),"text-optional":new Ji(G.layout_symbol["text-optional"])})}};class xc{constructor(t){if(void 0===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:lt,this.defaultValue=t;}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);}outputDefined(){return !1}serialize(){return null}}wi("FormatSectionOverride",xc,{omit:["defaultValue"]});class vc extends is{constructor(t){super(t,gc);}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const r of t)e.indexOf(r)<0&&e.push(r);this.layout._values["text-writing-mode"]=e;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();}getValueAndResolveTokens(t,e,r,n){const i=this.layout.get(t).evaluate(e,{},r,n),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||vn(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,r)=>t&&r in t?String(t[r]):""))}(e.properties,i)}createBucket(t){return new dc(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of gc.paint.overridableProperties){if(!vc.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),r=new xc(e),n=new xn(r,e.property.specification);let i=null;i="constant"===e.value.kind||"source"===e.value.kind?new wn("source",n):new _n("composite",n,e.value.zoomStops),this.paint._values[t]=new Hi(e.property,i,e.parameters);}}_handleOverridablePaintPropertyUpdate(t,e,r){return !(!this.layout||e.isDataDriven()||r.isDataDriven())&&vc.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const r=t.get("text-field"),n=gc.paint.properties[e];let i=!1;const s=t=>{for(const e of t)if(n.overrides&&n.overrides.hasOverride(e))return void(i=!0)};if("constant"===r.value.kind&&r.value.value instanceof Yt)s(r.value.value.sections);else if("source"===r.value.kind){const t=e=>{i||(e instanceof se&&ne(e.value)===mt?s(e.value.sections):e instanceof Ze?s(e.sections):e.eachChild(t));},e=r.value;e._styleExpression&&t(e._styleExpression.expression);}return i}}let bc;var wc={get paint(){return bc=bc||new rs({"background-color":new Ji(G.paint_background["background-color"]),"background-pattern":new ts(G.paint_background["background-pattern"]),"background-opacity":new Ji(G.paint_background["background-opacity"])})}};class _c extends is{constructor(t){super(t,wc);}}let Ac;var Sc={get paint(){return Ac=Ac||new rs({"raster-opacity":new Ji(G.paint_raster["raster-opacity"]),"raster-hue-rotate":new Ji(G.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Ji(G.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Ji(G.paint_raster["raster-brightness-max"]),"raster-saturation":new Ji(G.paint_raster["raster-saturation"]),"raster-contrast":new Ji(G.paint_raster["raster-contrast"]),"raster-resampling":new Ji(G.paint_raster["raster-resampling"]),"raster-fade-duration":new Ji(G.paint_raster["raster-fade-duration"])})}};class kc extends is{constructor(t){super(t,Sc);}}class Mc extends is{constructor(t){super(t,{}),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},this.implementation=t;}is3D(){return "3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return !1}serialize(){throw new Error("Custom layers cannot be serialized")}}class Ic{constructor(t){this._methodToThrottle=t,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle();});}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._methodToThrottle();}),0));}remove(){delete this._channel,this._methodToThrottle=()=>{};}}const zc=6371008.8;class Pc{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Pc(m(this.lng,-180,180),this.lat)}toArray(){return [this.lng,this.lat]}toString(){return `LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return zc*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof Pc)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new Pc(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new Pc(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const Cc=2*Math.PI*zc;function Bc(t){return Cc*Math.cos(t*Math.PI/180)}function Vc(t){return (180+t)/360}function Ec(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function Fc(t,e){return t/Bc(e)}function Tc(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}class $c{constructor(t,e,r=0){this.x=+t,this.y=+e,this.z=+r;}static fromLngLat(t,e=0){const r=Pc.convert(t);return new $c(Vc(r.lng),Ec(r.lat),Fc(e,r.lat))}toLngLat(){return new Pc(360*this.x-180,Tc(this.y))}toAltitude(){return this.z*Bc(Tc(this.y))}meterInMercatorCoordinateUnits(){return 1/Cc*(t=Tc(this.y),1/Math.cos(t*Math.PI/180));var t;}}function Lc(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}class Dc{constructor(t,e,r){if(!function(t,e,r){return !(t<0||t>25||r<0||r>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,r))throw new Error(`x=${e}, y=${r}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=r,this.key=Rc(0,t,t,e,r);}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,r){const n=(s=this.y,a=this.z,o=Lc(256*(i=this.x),256*(s=Math.pow(2,a)-s-1),a),l=Lc(256*(i+1),256*(s+1),a),o[0]+","+o[1]+","+l[0]+","+l[1]);var i,s,a,o,l;const u=function(t,e,r){let n,i="";for(let s=t;s>0;s--)n=1<1?"@2x":"").replace(/{quadkey}/g,u).replace(/{bbox-epsg-3857}/g,n)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new s((t.x*e-this.x)*$a,(t.y*e-this.y)*$a)}toString(){return `${this.z}/${this.x}/${this.y}`}}class Oc{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Rc(t,e.z,e.z,e.x,e.y);}}class jc{constructor(t,e,r,n,i){if(t= z; overscaledZ = ${t}; z = ${r}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Dc(r,+n,+i),this.key=Rc(e,t,r,n,i);}clone(){return new jc(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new jc(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new jc(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const r=this.canonical.z-t;return t>this.canonical.z?Rc(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Rc(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)}isChildOf(t){if(t.wrap!==this.wrap)return !1;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return [new jc(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new jc(e,this.wrap,e,r,n),new jc(e,this.wrap,e,r+1,n),new jc(e,this.wrap,e,r,n+1),new jc(e,this.wrap,e,r+1,n+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.ythis.max&&(this.max=r),r=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)}unpack(t,e,r){return t*this.redFactor+e*this.greenFactor+r*this.blueFactor-this.baseShift}getPixels(){return new Ao({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let n=e*this.dim,i=e*this.dim+this.dim,s=r*this.dim,a=r*this.dim+this.dim;switch(e){case-1:n=i-1;break;case 1:i=n+1;}switch(r){case-1:s=a-1;break;case 1:a=s+1;}const o=-e*this.dim,l=-r*this.dim;for(let e=s;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class Nc{constructor(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(t){this._geometry=t;}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t}}class Zc{constructor(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new vi($a,16,0),this.grid3D=new vi($a,16,0),this.featureIndexArray=new Ns,this.promoteId=e;}insert(t,e,r,n,i,s){const a=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);const o=s?this.grid3D:this.grid;for(let t=0;t=0&&n[3]>=0&&o.insert(a,n[0],n[1],n[2],n[3]);}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new fl.VectorTile(new Iu(this.rawTileData)).layers,this.sourceLayerCoder=new qc(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(t,e,r,n){this.loadVTLayers();const i=t.params||{},a=$a/t.tileSize/t.scale,o=zn(i.filter),l=t.queryGeometry,u=t.queryPadding*a,c=Kc(l),h=this.grid.query(c.minX-u,c.minY-u,c.maxX+u,c.maxY+u),p=Kc(t.cameraQueryGeometry),f=this.grid3D.query(p.minX-u,p.minY-u,p.maxX+u,p.maxY+u,((e,r,n,i)=>function(t,e,r,n,i){for(const s of t)if(e<=s.x&&r<=s.y&&n>=s.x&&i>=s.y)return !0;const a=[new s(e,r),new s(e,i),new s(n,i),new s(n,r)];if(t.length>2)for(const e of a)if(Wa(t,e))return !0;for(let e=0;e(p||(p=Oa(e)),r.queryIntersectsFeature(l,e,n,p,this.z,t.transform,a,t.pixelPosMatrix))));}return d}loadMatchingFeature(t,e,r,n,i,s,a,o,l,u,c){const h=this.bucketLayerIDs[e];if(s&&!function(t,e){for(let r=0;r=0)return !0;return !1}(s,h))return;const p=this.sourceLayerCoder.decode(r),f=this.vtLayers[p].feature(n);if(i.needGeometry){const t=ja(f,!0);if(!i.filter(new Ui(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!i.filter(new Ui(this.tileID.overscaledZ),f))return;const d=this.getId(f,p);for(let e=0;e{const a=e instanceof Yi?e.get(s):null;return a&&a.evaluate?a.evaluate(r,n,i):a}))}function Kc(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return {minX:e,minY:r,maxX:n,maxY:i}}function Xc(t,e){return e-t}function Hc(t,e,r,n,i){const a=[];for(let o=0;o=n&&c.x>=n||(o.x>=n?o=new s(n,o.y+(n-o.x)/(c.x-o.x)*(c.y-o.y))._round():c.x>=n&&(c=new s(n,o.y+(n-o.x)/(c.x-o.x)*(c.y-o.y))._round()),o.y>=i&&c.y>=i||(o.y>=i?o=new s(o.x+(i-o.y)/(c.y-o.y)*(c.x-o.x),i)._round():c.y>=i&&(c=new s(o.x+(i-o.y)/(c.y-o.y)*(c.x-o.x),i)._round()),u&&o.equals(u[u.length-1])||(u=[o],a.push(u)),u.push(c)))));}}return a}wi("FeatureIndex",Zc,{omit:["rawTileData","sourceLayerCoder"]});class Yc extends s{constructor(t,e,r,n){super(t,e),this.angle=r,void 0!==n&&(this.segment=n);}clone(){return new Yc(this.x,this.y,this.angle,this.segment)}}function Jc(t,e,r,n,i){if(void 0===e.segment||0===r)return !0;let s=e,a=e.segment+1,o=0;for(;o>-r/2;){if(a--,a<0)return !1;o-=t[a].dist(s),s=t[a];}o+=t[a].dist(t[a+1]),a++;const l=[];let u=0;for(;on;)u-=l.shift().angleDelta;if(u>i)return !1;a++,o+=e.dist(r);}return !0}function Wc(t){let e=0;for(let r=0;ru){const c=(u-l)/s,h=Ce.number(n.x,i.x,c),p=Ce.number(n.y,i.y,c),f=new Yc(h,p,i.angleTo(n),r);return f._round(),!a||Jc(t,f,o,a,e)?f:void 0}l+=s;}}function rh(t,e,r,n,i,s,a,o,l){const u=Qc(n,s,a),c=th(n,i),h=c*a,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const r=new Yc(g,x,y,e);r._round(),n&&!Jc(t,r,s,n,i)||f.push(r);}}h+=d;}return o||f.length||a||(f=nh(t,h/2,r,n,i,s,a,!0,l)),f}wi("Anchor",Yc);const ih=Fu;function sh(t,e,r,n){const i=[],a=t.image,o=a.pixelRatio,l=a.paddedRect.w-2*ih,u=a.paddedRect.h-2*ih;let c={x1:t.left,y1:t.top,x2:t.right,y2:t.bottom};const h=a.stretchX||[[0,l]],p=a.stretchY||[[0,u]],f=(t,e)=>t+e[1]-e[0],d=h.reduce(f,0),y=p.reduce(f,0),m=l-d,g=u-y;let x=0,v=d,b=0,w=y,_=0,A=m,S=0,k=g;if(a.content&&n){const e=a.content,r=e[2]-e[0],n=e[3]-e[1];(a.textFitWidth||a.textFitHeight)&&(c=tc(t)),x=ah(h,0,e[0]),b=ah(p,0,e[1]),v=ah(h,e[0],e[2]),w=ah(p,e[1],e[3]),_=e[0]-x,S=e[1]-b,A=r-v,k=n-w;}const M=c.x1,I=c.y1,z=c.x2-M,P=c.y2-I,C=(t,n,i,l)=>{const u=lh(t.stretch-x,v,z,M),c=uh(t.fixed-_,A,t.stretch,d),h=lh(n.stretch-b,w,P,I),p=uh(n.fixed-S,k,n.stretch,y),f=lh(i.stretch-x,v,z,M),m=uh(i.fixed-_,A,i.stretch,d),g=lh(l.stretch-b,w,P,I),C=uh(l.fixed-S,k,l.stretch,y),B=new s(u,h),V=new s(f,h),E=new s(f,g),F=new s(u,g),T=new s(c/o,p/o),$=new s(m/o,C/o),L=e*Math.PI/180;if(L){const t=Math.sin(L),e=Math.cos(L),r=[e,-t,t,e];B._matMult(r),V._matMult(r),F._matMult(r),E._matMult(r);}const D=t.stretch+t.fixed,O=n.stretch+n.fixed;return {tl:B,tr:V,bl:F,br:E,tex:{x:a.paddedRect.x+ih+D,y:a.paddedRect.y+ih+O,w:i.stretch+i.fixed-D,h:l.stretch+l.fixed-O},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:T,pixelOffsetBR:$,minFontScaleX:A/o/z,minFontScaleY:k/o/P,isSDF:r}};if(n&&(a.stretchX||a.stretchY)){const t=oh(h,m,d),e=oh(p,g,y);for(let r=0;r0&&(n=Math.max(10,n),this.circleDiameter=n);}else {const u=(null===(h=a.image)||void 0===h?void 0:h.content)&&(a.image.textFitWidth||a.image.textFitHeight)?tc(a):{x1:a.left,y1:a.top,x2:a.right,y2:a.bottom};u.y1=u.y1*o-l[0],u.y2=u.y2*o+l[2],u.x1=u.x1*o-l[3],u.x2=u.x2*o+l[1];const p=a.collisionPadding;if(p&&(u.x1-=p[0]*o,u.y1-=p[1]*o,u.x2+=p[2]*o,u.y2+=p[3]*o),c){const t=new s(u.x1,u.y1),e=new s(u.x2,u.y1),r=new s(u.x1,u.y2),n=new s(u.x2,u.y2),i=c*Math.PI/180;t._rotate(i),e._rotate(i),r._rotate(i),n._rotate(i),u.x1=Math.min(t.x,e.x,r.x,n.x),u.x2=Math.max(t.x,e.x,r.x,n.x),u.y1=Math.min(t.y,e.y,r.y,n.y),u.y2=Math.max(t.y,e.y,r.y,n.y);}t.emplaceBack(e.x,e.y,u.x1,u.y1,u.x2,u.y2,r,n,i);}this.boxEndIndex=t.length;}}class hh{constructor(t=[],e=((t,e)=>te?1:0)){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}}function ph(t,e=1,r=!1){let n=1/0,i=1/0,a=-1/0,o=-1/0;const l=t[0];for(let t=0;ta)&&(a=e.x),(!t||e.y>o)&&(o=e.y);}const u=Math.min(a-n,o-i);let c=u/2;const h=new hh([],fh);if(0===u)return new s(n,i);for(let e=n;ep.d||!p.d)&&(p=n,r&&console.log("found best %d after %d probes",Math.round(1e4*n.d)/1e4,f)),n.max-p.d<=e||(c=n.h/2,h.push(new dh(n.p.x-c,n.p.y-c,c,t)),h.push(new dh(n.p.x+c,n.p.y-c,c,t)),h.push(new dh(n.p.x-c,n.p.y+c,c,t)),h.push(new dh(n.p.x+c,n.p.y+c,c,t)),f+=4);}return r&&(console.log(`num probes: ${f}`),console.log(`best distance: ${p.d}`)),p.p}function fh(t,e){return e.max-t.max}function dh(t,e,r,n){this.p=new s(t,e),this.h=r,this.d=function(t,e){let r=!1,n=1/0;for(let i=0;it.y!=o.y>t.y&&t.x<(o.x-i.x)*(t.y-i.y)/(o.y-i.y)+i.x&&(r=!r),n=Math.min(n,Ya(t,i,o));}}return (r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2;}var yh;t.aq=void 0,(yh=t.aq||(t.aq={}))[yh.center=1]="center",yh[yh.left=2]="left",yh[yh.right=3]="right",yh[yh.top=4]="top",yh[yh.bottom=5]="bottom",yh[yh["top-left"]=6]="top-left",yh[yh["top-right"]=7]="top-right",yh[yh["bottom-left"]=8]="bottom-left",yh[yh["bottom-right"]=9]="bottom-right";const mh=7,gh=Number.POSITIVE_INFINITY;function xh(t,e){return e[1]!==gh?function(t,e,r){let n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case"top-right":case"top-left":case"top":i=r-mh;break;case"bottom-right":case"bottom-left":case"bottom":i=-r+mh;}switch(t){case"top-right":case"bottom-right":case"right":n=-e;break;case"top-left":case"bottom-left":case"left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){let r=0,n=0;e<0&&(e=0);const i=e/Math.SQRT2;switch(t){case"top-right":case"top-left":n=i-mh;break;case"bottom-right":case"bottom-left":n=-i+mh;break;case"bottom":n=-e+mh;break;case"top":n=e-mh;}switch(t){case"top-right":case"bottom-right":r=-i;break;case"top-left":case"bottom-left":r=i;break;case"left":r=e;break;case"right":r=-e;}return [r,n]}(t,e[0])}function vh(t,e,r){var n;const i=t.layout,s=null===(n=i.get("text-variable-anchor-offset"))||void 0===n?void 0:n.evaluate(e,{},r);if(s){const t=s.values,e=[];for(let r=0;rt*iu));n.startsWith("top")?i[1]-=mh:n.startsWith("bottom")&&(i[1]+=mh),e[r+1]=i;}return new Qt(e)}const a=i.get("text-variable-anchor");if(a){let n;n=void 0!==t._unevaluatedLayout.getValue("text-radial-offset")?[i.get("text-radial-offset").evaluate(e,{},r)*iu,gh]:i.get("text-offset").evaluate(e,{},r).map((t=>t*iu));const s=[];for(const t of a)s.push(t,xh(t,n));return new Qt(s)}return null}function bh(t){switch(t){case"right":case"top-right":case"bottom-right":return "right";case"left":case"top-left":case"bottom-left":return "left"}return "center"}function wh(e,r,n,i,s,a,o,l,u,c,h){let p=a.textMaxSize.evaluate(r,{});void 0===p&&(p=o);const f=e.layers[0].layout,d=f.get("icon-offset").evaluate(r,{},h),y=Ah(n.horizontal),m=o/24,g=e.tilePixelRatio*m,x=e.tilePixelRatio*p/24,v=e.tilePixelRatio*l,b=e.tilePixelRatio*f.get("symbol-spacing"),w=f.get("text-padding")*e.tilePixelRatio,_=function(t,e,r,n=1){const i=t.get("icon-padding").evaluate(e,{},r),s=i&&i.values;return [s[0]*n,s[1]*n,s[2]*n,s[3]*n]}(f,r,h,e.tilePixelRatio),S=f.get("text-max-angle")/180*Math.PI,k="viewport"!==f.get("text-rotation-alignment")&&"point"!==f.get("symbol-placement"),M="map"===f.get("icon-rotation-alignment")&&"point"!==f.get("symbol-placement"),I=f.get("symbol-placement"),z=b/2,P=f.get("icon-text-fit");let C;i&&"none"!==P&&(e.allowVerticalPlacement&&n.vertical&&(C=ec(i,n.vertical,P,f.get("icon-text-fit-padding"),d,m)),y&&(i=ec(i,y,P,f.get("icon-text-fit-padding"),d,m)));const B=(l,p)=>{p.x<0||p.x>=$a||p.y<0||p.y>=$a||function(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,k,M){const I=e.addToLineVertexArray(r,n);let z,P,C,B,V=0,E=0,F=0,T=0,$=-1,L=-1;const D={};let O=ma("");if(e.allowVerticalPlacement&&i.vertical){const t=l.layout.get("text-rotate").evaluate(w,{},k)+90;C=new ch(u,r,c,h,p,i.vertical,f,d,y,t),o&&(B=new ch(u,r,c,h,p,o,g,x,y,t));}if(s){const n=l.layout.get("icon-rotate").evaluate(w,{}),i="none"!==l.layout.get("icon-text-fit"),a=sh(s,n,S,i),f=o?sh(o,n,S,i):void 0;P=new ch(u,r,c,h,p,s,g,x,!1,n),V=4*a.length;const d=e.iconSizeData;let y=null;"source"===d.kind?(y=[nc*l.layout.get("icon-size").evaluate(w,{})],y[0]>ic&&A(`${e.layerIds[0]}: Value for "icon-size" is >= ${rc}. Reduce your "icon-size".`)):"composite"===d.kind&&(y=[nc*_.compositeIconSizes[0].evaluate(w,{},k),nc*_.compositeIconSizes[1].evaluate(w,{},k)],(y[0]>ic||y[1]>ic)&&A(`${e.layerIds[0]}: Value for "icon-size" is >= ${rc}. Reduce your "icon-size".`)),e.addSymbols(e.icon,a,y,b,v,w,t.ah.none,r,I.lineStartIndex,I.lineLength,-1,k),$=e.icon.placedSymbolArray.length-1,f&&(E=4*f.length,e.addSymbols(e.icon,f,y,b,v,w,t.ah.vertical,r,I.lineStartIndex,I.lineLength,-1,k),L=e.icon.placedSymbolArray.length-1);}const j=Object.keys(i.horizontal);for(const n of j){const s=i.horizontal[n];if(!z){O=ma(s.text);const t=l.layout.get("text-rotate").evaluate(w,{},k);z=new ch(u,r,c,h,p,s,f,d,y,t);}const o=1===s.positionedLines.length;if(F+=_h(e,r,s,a,l,y,w,m,I,i.vertical?t.ah.horizontal:t.ah.horizontalOnly,o?j:[n],D,$,_,k),o)break}i.vertical&&(T+=_h(e,r,i.vertical,a,l,y,w,m,I,t.ah.vertical,["vertical"],D,L,_,k));const R=z?z.boxStartIndex:e.collisionBoxArray.length,U=z?z.boxEndIndex:e.collisionBoxArray.length,q=C?C.boxStartIndex:e.collisionBoxArray.length,N=C?C.boxEndIndex:e.collisionBoxArray.length,Z=P?P.boxStartIndex:e.collisionBoxArray.length,G=P?P.boxEndIndex:e.collisionBoxArray.length,K=B?B.boxStartIndex:e.collisionBoxArray.length,X=B?B.boxEndIndex:e.collisionBoxArray.length;let H=-1;const Y=(t,e)=>t&&t.circleDiameter?Math.max(t.circleDiameter,e):e;H=Y(z,H),H=Y(C,H),H=Y(P,H),H=Y(B,H);const J=H>-1?1:0;J&&(H*=M/iu),e.glyphOffsetArray.length>=dc.MAX_GLYPHS&&A("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==w.sortKey&&e.addToSortKeyRanges(e.symbolInstances.length,w.sortKey);const W=vh(l,w,k),[Q,tt]=function(e,r){const n=e.length,i=null==r?void 0:r.values;if((null==i?void 0:i.length)>0)for(let r=0;r=0?D.right:-1,D.center>=0?D.center:-1,D.left>=0?D.left:-1,D.vertical||-1,$,L,O,R,U,q,N,Z,G,K,X,c,F,T,V,E,J,0,f,H,Q,tt);}(e,p,l,n,i,s,C,e.layers[0],e.collisionBoxArray,r.index,r.sourceLayerIndex,e.index,g,[w,w,w,w],k,u,v,_,M,d,r,a,c,h,o);};if("line"===I)for(const t of Hc(r.geometry,0,0,$a,$a)){const r=rh(t,b,S,n.vertical||y,i,24,x,e.overscaling,$a);for(const n of r)y&&Sh(e,y.text,z,n)||B(t,n);}else if("line-center"===I){for(const t of r.geometry)if(t.length>1){const e=eh(t,S,n.vertical||y,i,24,x);e&&B(t,e);}}else if("Polygon"===r.type)for(const t of xr(r.geometry,0)){const e=ph(t,16);B(t[0],new Yc(e.x,e.y,0));}else if("LineString"===r.type)for(const t of r.geometry)B(t,new Yc(t[0].x,t[0].y,0));else if("Point"===r.type)for(const t of r.geometry)for(const e of t)B([e],new Yc(e.x,e.y,0));}function _h(t,e,r,n,i,a,o,l,u,c,h,p,f,d,y){const m=function(t,e,r,n,i,a,o,l){const u=n.layout.get("text-rotate").evaluate(a,{})*Math.PI/180,c=[];for(const t of e.positionedLines)for(const n of t.positionedGlyphs){if(!n.rect)continue;const a=n.rect||{};let h=Vu+1,p=!0,f=1,d=0;const y=(i||l)&&n.vertical,m=n.metrics.advance*n.scale/2;if(l&&e.verticalizable&&(d=t.lineOffset/2-(n.imageName?-(iu-n.metrics.width*n.scale)/2:(n.scale-1)*iu)),n.imageName){const t=o[n.imageName];p=t.sdf,f=t.pixelRatio,h=Fu/f;}const g=i?[n.x+m,n.y]:[0,0];let x=i?[0,0]:[n.x+m+r[0],n.y+r[1]-d],v=[0,0];y&&(v=x,x=[0,0]);const b=n.metrics.isDoubleResolution?2:1,w=(n.metrics.left-h)*n.scale-m+x[0],_=(-n.metrics.top-h)*n.scale+x[1],A=w+a.w/b*n.scale/f,S=_+a.h/b*n.scale/f,k=new s(w,_),M=new s(A,_),I=new s(w,S),z=new s(A,S);if(y){const t=new s(-m,m-Du),e=-Math.PI/2,r=iu/2-m,i=new s(5-Du-r,-(n.imageName?r:0)),a=new s(...v);k._rotateAround(e,t)._add(i)._add(a),M._rotateAround(e,t)._add(i)._add(a),I._rotateAround(e,t)._add(i)._add(a),z._rotateAround(e,t)._add(i)._add(a);}if(u){const t=Math.sin(u),e=Math.cos(u),r=[e,-t,t,e];k._matMult(r),M._matMult(r),I._matMult(r),z._matMult(r);}const P=new s(0,0),C=new s(0,0);c.push({tl:k,tr:M,bl:I,br:z,tex:a,writingMode:e.writingMode,glyphOffset:g,sectionIndex:n.sectionIndex,isSDF:p,pixelOffsetTL:P,pixelOffsetBR:C,minFontScaleX:0,minFontScaleY:0});}return c}(0,r,l,i,a,o,n,t.allowVerticalPlacement),g=t.textSizeData;let x=null;"source"===g.kind?(x=[nc*i.layout.get("text-size").evaluate(o,{})],x[0]>ic&&A(`${t.layerIds[0]}: Value for "text-size" is >= ${rc}. Reduce your "text-size".`)):"composite"===g.kind&&(x=[nc*d.compositeTextSizes[0].evaluate(o,{},y),nc*d.compositeTextSizes[1].evaluate(o,{},y)],(x[0]>ic||x[1]>ic)&&A(`${t.layerIds[0]}: Value for "text-size" is >= ${rc}. Reduce your "text-size".`)),t.addSymbols(t.text,m,x,l,a,o,c,e,u.lineStartIndex,u.lineLength,f,y);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*m.length}function Ah(t){for(const e in t)return t[e];return null}function Sh(t,e,r,n){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(n.dist(t[e])>4;if(1!==n)throw new Error(`Got v${n} data when expected v1.`);const i=kh[15&r];if(!i)throw new Error("Unrecognized array type.");const[s]=new Uint16Array(t,2,1),[a]=new Uint32Array(t,4,1);return new Mh(a,s,i,t)}constructor(t,e=64,r=Float64Array,n){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=kh.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,a=t*this.IndexArrayType.BYTES_PER_ELEMENT,o=(8-a%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);n&&n instanceof ArrayBuffer?(this.data=n,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=2*t,this._finished=!0):(this.data=new ArrayBuffer(8+s+a+o),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t);}add(t,e){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=e,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return Ih(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,e,r,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:s,nodeSize:a}=this,o=[0,i.length-1,0],l=[];for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=a){for(let a=h;a<=c;a++){const o=s[2*a],u=s[2*a+1];o>=t&&o<=r&&u>=e&&u<=n&&l.push(i[a]);}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=r&&d>=e&&d<=n&&l.push(i[p]),(0===u?t<=f:e<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?r>=f:n>=d)&&(o.push(p+1),o.push(c),o.push(1-u));}return l}within(t,e,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:n,coords:i,nodeSize:s}=this,a=[0,n.length-1,0],o=[],l=r*r;for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=s){for(let r=h;r<=c;r++)Bh(i[2*r],i[2*r+1],t,e)<=l&&o.push(n[r]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];Bh(f,d,t,e)<=l&&o.push(n[p]),(0===u?t-r<=f:e-r<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?t+r>=f:e+r>=d)&&(a.push(p+1),a.push(c),a.push(1-u));}return o}}function Ih(t,e,r,n,i,s){if(i-n<=r)return;const a=n+i>>1;zh(t,e,a,n,i,s),Ih(t,e,r,n,a-1,1-s),Ih(t,e,r,a+1,i,1-s);}function zh(t,e,r,n,i,s){for(;i>n;){if(i-n>600){const a=i-n+1,o=r-n+1,l=Math.log(a),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(a-u)/a)*(o-a/2<0?-1:1);zh(t,e,r,Math.max(n,Math.floor(r-o*u/a+c)),Math.min(i,Math.floor(r+(a-o)*u/a+c)),s);}const a=e[2*r+s];let o=n,l=i;for(Ph(t,e,n,r),e[2*i+s]>a&&Ph(t,e,n,i);oa;)l--;}e[2*n+s]===a?Ph(t,e,n,l):(l++,Ph(t,e,l,i)),l<=r&&(n=l+1),r<=l&&(i=l-1);}}function Ph(t,e,r,n){Ch(t,r,n),Ch(e,2*r,2*n),Ch(e,2*r+1,2*n+1);}function Ch(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function Bh(t,e,r,n){const i=t-r,s=e-n;return i*i+s*s}var Vh;t.bg=void 0,(Vh=t.bg||(t.bg={})).create="create",Vh.load="load",Vh.fullLoad="fullLoad";let Eh=null,Fh=[];const Th=1e3/60,$h="loadTime",Lh="fullLoadTime",Dh={mark(t){performance.mark(t);},frame(t){const e=t;null!=Eh&&Fh.push(e-Eh),Eh=e;},clearMetrics(){Eh=null,Fh=[],performance.clearMeasures($h),performance.clearMeasures(Lh);for(const e in t.bg)performance.clearMarks(t.bg[e]);},getPerformanceMetrics(){performance.measure($h,t.bg.create,t.bg.load),performance.measure(Lh,t.bg.create,t.bg.fullLoad);const e=performance.getEntriesByName($h)[0].duration,r=performance.getEntriesByName(Lh)[0].duration,n=Fh.length,i=1/(Fh.reduce(((t,e)=>t+e),0)/n/1e3),s=Fh.filter((t=>t>Th)).reduce(((t,e)=>t+(e-Th)/Th),0);return {loadTime:e,fullLoadTime:r,fps:i,percentDroppedFrames:s/(n+s)*100,totalFrames:n}}};t.$=class extends ps{},t.A=oo,t.B=yi,t.C=function(t){if(null==M){const e=t.navigator?t.navigator.userAgent:null;M=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return M},t.D=Ji,t.E=Z,t.F=class{constructor(t,e){this.target=t,this.mapId=e,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new Ic((()=>this.process())),this.subscription=function(t,e,r,n){return t.addEventListener(e,r,!1),{unsubscribe:()=>{t.removeEventListener(e,r,!1);}}}(this.target,"message",(t=>this.receive(t))),this.globalScope=k(self)?t:window;}registerMessageHandler(t,e){this.messageHandlers[t]=e;}sendAsync(t,e){return new Promise(((r,n)=>{const i=Math.round(1e18*Math.random()).toString(36).substring(0,10);this.resolveRejects[i]={resolve:r,reject:n},e&&e.signal.addEventListener("abort",(()=>{delete this.resolveRejects[i];const e={id:i,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e);}),{once:!0});const s=[],a=Object.assign(Object.assign({},t),{id:i,sourceMapId:this.mapId,origin:location.origin,data:ki(t.data,s)});this.target.postMessage(a,{transfer:s});}))}receive(t){const e=t.data,r=e.id;if(!("file://"!==e.origin&&"file://"!==location.origin&&"resource://android"!==e.origin&&"resource://android"!==location.origin&&e.origin!==location.origin||e.targetMapId&&this.mapId!==e.targetMapId)){if(""===e.type){delete this.tasks[r];const t=this.abortControllers[r];return delete this.abortControllers[r],void(t&&t.abort())}if(k(self)||e.mustQueue)return this.tasks[r]=e,this.taskQueue.push(r),void this.invoker.trigger();this.processTask(r,e);}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e);}processTask(t,r){return e(this,void 0,void 0,(function*(){if(""===r.type){const e=this.resolveRejects[t];if(delete this.resolveRejects[t],!e)return;return void(r.error?e.reject(Mi(r.error)):e.resolve(Mi(r.data)))}if(!this.messageHandlers[r.type])return void this.completeTask(t,new Error(`Could not find a registered handler for ${r.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const e=Mi(r.data),n=new AbortController;this.abortControllers[t]=n;try{const i=yield this.messageHandlers[r.type](r.sourceMapId,e,n);this.completeTask(t,null,i);}catch(e){this.completeTask(t,e);}}))}completeTask(t,e,r){const n=[];delete this.abortControllers[t];const i={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?ki(e):null,data:ki(r,n)};this.target.postMessage(i,{transfer:n});}remove(){this.invoker.remove(),this.subscription.unsubscribe();}},t.G=$,t.H=function(){var t=new oo(16);return oo!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.I=Tu,t.J=function(t,e,r){var n,i,s,a,o,l,u,c,h,p,f,d,y=r[0],m=r[1],g=r[2];return e===t?(t[12]=e[0]*y+e[4]*m+e[8]*g+e[12],t[13]=e[1]*y+e[5]*m+e[9]*g+e[13],t[14]=e[2]*y+e[6]*m+e[10]*g+e[14],t[15]=e[3]*y+e[7]*m+e[11]*g+e[15]):(i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],t[0]=n=e[0],t[1]=i,t[2]=s,t[3]=a,t[4]=o,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=p,t[10]=f,t[11]=d,t[12]=n*y+o*m+h*g+e[12],t[13]=i*y+l*m+p*g+e[13],t[14]=s*y+u*m+f*g+e[14],t[15]=a*y+c*m+d*g+e[15]),t},t.K=function(t,e,r){var n=r[0],i=r[1],s=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*s,t[9]=e[9]*s,t[10]=e[10]*s,t[11]=e[11]*s,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.L=uo,t.M=function(t,e){const r={};for(let n=0;n{const e=window.document.createElement("video");return e.muted=!0,new Promise((r=>{e.onloadstart=()=>{r(e);};for(const r of t){const t=window.document.createElement("source");j(r)||(e.crossOrigin="Anonymous"),t.src=r,e.appendChild(t);}}))},t.a4=function(){return x++},t.a5=Fs,t.a6=dc,t.a7=zn,t.a8=ja,t.a9=Nc,t.aA=function(t){if("custom"===t.type)return new Mc(t);switch(t.type){case"background":return new _c(t);case"circle":return new fo(t);case"fill":return new ul(t);case"fill-extrusion":return new El(t);case"heatmap":return new Mo(t);case"hillshade":return new Po(t);case"line":return new Hl(t);case"raster":return new kc(t);case"symbol":return new vc(t)}},t.aB=w,t.aC=function(t,e){if(!t)return [{command:"setStyle",args:[e]}];let r=[];try{if(!H(t.version,e.version))return [{command:"setStyle",args:[e]}];H(t.center,e.center)||r.push({command:"setCenter",args:[e.center]}),H(t.zoom,e.zoom)||r.push({command:"setZoom",args:[e.zoom]}),H(t.bearing,e.bearing)||r.push({command:"setBearing",args:[e.bearing]}),H(t.pitch,e.pitch)||r.push({command:"setPitch",args:[e.pitch]}),H(t.sprite,e.sprite)||r.push({command:"setSprite",args:[e.sprite]}),H(t.glyphs,e.glyphs)||r.push({command:"setGlyphs",args:[e.glyphs]}),H(t.transition,e.transition)||r.push({command:"setTransition",args:[e.transition]}),H(t.light,e.light)||r.push({command:"setLight",args:[e.light]}),H(t.terrain,e.terrain)||r.push({command:"setTerrain",args:[e.terrain]}),H(t.sky,e.sky)||r.push({command:"setSky",args:[e.sky]}),H(t.projection,e.projection)||r.push({command:"setProjection",args:[e.projection]});const n={},i=[];!function(t,e,r,n){let i;for(i in e=e||{},t=t||{})Object.prototype.hasOwnProperty.call(t,i)&&(Object.prototype.hasOwnProperty.call(e,i)||W(i,r,n));for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&(Object.prototype.hasOwnProperty.call(t,i)?H(t[i],e[i])||("geojson"===t[i].type&&"geojson"===e[i].type&&tt(t,e,i)?Y(r,{command:"setGeoJSONSourceData",args:[i,e[i].data]}):Q(i,e,r,n)):J(i,e,r));}(t.sources,e.sources,i,n);const s=[];t.layers&&t.layers.forEach((t=>{"source"in t&&n[t.source]?r.push({command:"removeLayer",args:[t.id]}):s.push(t);})),r=r.concat(i),function(t,e,r){e=e||[];const n=(t=t||[]).map(rt),i=e.map(rt),s=t.reduce(nt,{}),a=e.reduce(nt,{}),o=n.slice(),l=Object.create(null);let u,c,h,p,f;for(let t=0,e=0;t@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((t,r,n,i)=>{const s=n||i;return e[r]=!s||s.toLowerCase(),""})),e["max-age"]){const t=parseInt(e["max-age"],10);isNaN(t)?delete e["max-age"]:e["max-age"]=t;}return e},t.ab=function(t,e){const r=[];for(const n in t)n in e||r.push(n);return r},t.ac=y,t.ad=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[4],c=e[5],h=e[6],p=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i+u*n,t[1]=a*i+c*n,t[2]=o*i+h*n,t[3]=l*i+p*n,t[4]=u*i-s*n,t[5]=c*i-a*n,t[6]=h*i-o*n,t[7]=p*i-l*n,t},t.ae=function(t){var e=new oo(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.af=po,t.ag=function(t,e){let r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){const{interpolationType:i,minZoom:s,maxZoom:a}=t,o=i?y(Be.interpolationFactor(i,e,s,a),0,1):0;"camera"===t.kind?n=Ce.number(t.minSize,t.maxSize,o):r=o;}return {uSizeT:r,uSize:n}},t.ai=function(t,{uSize:e,uSizeT:r},{lowerSize:n,upperSize:i}){return "source"===t.kind?n/nc:"composite"===t.kind?Ce.number(n/nc,i/nc,r):e},t.aj=cc,t.ak=function(t,e,r,n){const i=e.y-t.y,a=e.x-t.x,o=n.y-r.y,l=n.x-r.x,u=o*a-l*i;if(0===u)return null;const c=(l*(t.y-r.y)-o*(t.x-r.x))/u;return new s(t.x+c*a,t.y+c*i)},t.al=Hc,t.am=qa,t.an=lo,t.ao=function(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return [e,r,n,i]},t.ap=iu,t.ar=ac,t.as=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],y=e[13],m=e[14],g=e[15],x=r*o-n*a,v=r*l-i*a,b=r*u-s*a,w=n*l-i*o,_=n*u-s*o,A=i*u-s*l,S=c*y-h*d,k=c*m-p*d,M=c*g-f*d,I=h*m-p*y,z=h*g-f*y,P=p*g-f*m,C=x*P-v*z+b*I+w*M-_*k+A*S;return C?(t[0]=(o*P-l*z+u*I)*(C=1/C),t[1]=(i*z-n*P-s*I)*C,t[2]=(y*A-m*_+g*w)*C,t[3]=(p*_-h*A-f*w)*C,t[4]=(l*M-a*P-u*k)*C,t[5]=(r*P-i*M+s*k)*C,t[6]=(m*b-d*A-g*v)*C,t[7]=(c*A-p*b+f*v)*C,t[8]=(a*z-o*M+u*S)*C,t[9]=(n*M-r*z-s*S)*C,t[10]=(d*_-y*b+g*x)*C,t[11]=(h*b-c*_-f*x)*C,t[12]=(o*k-a*I-l*S)*C,t[13]=(r*I-n*k+i*S)*C,t[14]=(y*v-d*w-m*x)*C,t[15]=(c*w-h*v+p*x)*C,t):null},t.at=bh,t.au=Ju,t.av=Mh,t.aw=function(){const t={},e=G.$version;for(const r in G.$root){const n=G.$root[r];if(n.required){let i=null;i="version"===r?e:"array"===n.type?[]:{},null!=i&&(t[r]=i);}}return t},t.ax=Ii,t.ay=D,t.az=function(t){t=t.slice();const e=Object.create(null);for(let r=0;r25||n<0||n>=1||r<0||r>=1)},t.bc=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},t.bd=class extends hs{},t.be=zc,t.bf=Dh,t.bh=L,t.bi=function(t,e){F.REGISTERED_PROTOCOLS[t]=e;},t.bj=function(t){delete F.REGISTERED_PROTOCOLS[t];},t.bk=function(t,e){const r={};for(let n=0;nt*iu));}let v=o?"center":n.get("text-justify").evaluate(i,{},e.canonical);const b="point"===n.get("symbol-placement")?n.get("text-max-width").evaluate(i,{},e.canonical)*iu:1/0,w=()=>{e.bucket.allowVerticalPlacement&&Pi(s)&&(d.vertical=Ru(y,e.glyphMap,e.glyphPositions,e.imagePositions,c,b,a,m,"left",f,g,t.ah.vertical,!0,p,h));};if(!o&&x){const r=new Set;if("auto"===v)for(let t=0;te(void 0,void 0,void 0,(function*(){if(0===t.byteLength)return createImageBitmap(new ImageData(1,1));const e=new Blob([new Uint8Array(t)],{type:"image/png"});try{return createImageBitmap(e)}catch(t){throw new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),t.e=g,t.f=t=>new Promise(((e,r)=>{const n=new Image;n.onload=()=>{e(n),URL.revokeObjectURL(n.src),n.onload=null,window.requestAnimationFrame((()=>{n.src=z;}));},n.onerror=()=>r(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."));const i=new Blob([new Uint8Array(t)],{type:"image/png"});n.src=t.byteLength?URL.createObjectURL(i):z;})),t.g=T,t.h=(t,e)=>O(g(t,{type:"json"}),e),t.i=k,t.j=N,t.k=q,t.l=(t,e)=>O(g(t,{type:"arrayBuffer"}),e),t.m=O,t.n=function(t){return new Iu(t).readFields(Pu,[])},t.o=_o,t.p=Eu,t.q=rs,t.r=di,t.s=j,t.t=xi,t.u=fi,t.v=G,t.w=A,t.x=function([t,e,r]){return e+=90,e*=Math.PI/180,r*=Math.PI/180,{x:t*Math.cos(e)*Math.sin(r),y:t*Math.sin(e)*Math.sin(r),z:t*Math.cos(r)}},t.y=Ce,t.z=Ui;})); + +define("worker",["./shared"],(function(e){"use strict";class t{constructor(e){this.keyCache={},e&&this.replace(e);}replace(e){this._layerConfigs={},this._layers={},this.update(e,[]);}update(t,o){for(const o of t){this._layerConfigs[o.id]=o;const t=this._layers[o.id]=e.aA(o);t._featureFilter=e.a7(t.filter),this.keyCache[o.id]&&delete this.keyCache[o.id];}for(const e of o)delete this.keyCache[e],delete this._layerConfigs[e],delete this._layers[e];this.familiesBySource={};const i=e.bk(Object.values(this._layerConfigs),this.keyCache);for(const e of i){const t=e.map((e=>this._layers[e.id])),o=t[0];if("none"===o.visibility)continue;const i=o.source||"";let s=this.familiesBySource[i];s||(s=this.familiesBySource[i]={});const r=o.sourceLayer||"_geojsonTileLayer";let n=s[r];n||(n=s[r]=[]),n.push(t);}}}class o{constructor(t){const o={},i=[];for(const e in t){const s=t[e],r=o[e]={};for(const e in s){const t=s[+e];if(!t||0===t.bitmap.width||0===t.bitmap.height)continue;const o={x:0,y:0,w:t.bitmap.width+2,h:t.bitmap.height+2};i.push(o),r[e]={rect:o,metrics:t.metrics};}}const{w:s,h:r}=e.p(i),n=new e.o({width:s||1,height:r||1});for(const i in t){const s=t[i];for(const t in s){const r=s[+t];if(!r||0===r.bitmap.width||0===r.bitmap.height)continue;const a=o[i][t].rect;e.o.copy(r.bitmap,n,{x:0,y:0},{x:a.x+1,y:a.y+1},r.bitmap);}}this.image=n,this.positions=o;}}e.bl("GlyphAtlas",o);class i{constructor(t){this.tileID=new e.S(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId,this.inFlightDependencies=[];}parse(t,i,r,n){return e._(this,void 0,void 0,(function*(){this.status="parsing",this.data=t,this.collisionBoxArray=new e.a5;const a=new e.bm(Object.keys(t.layers).sort()),l=new e.bn(this.tileID,this.promoteId);l.bucketLayerIDs=[];const c={},u={featureIndex:l,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:r},h=i.familiesBySource[this.source];for(const o in h){const i=t.layers[o];if(!i)continue;1===i.version&&e.w(`Vector tile source "${this.source}" layer "${o}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const n=a.encode(o),d=[];for(let e=0;e=o.maxzoom||"none"!==o.visibility&&(s(t,this.zoom,r),(c[o.id]=o.createBucket({index:l.bucketLayerIDs.length,layers:t,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:n,sourceID:this.source})).populate(d,u,this.tileID.canonical),l.bucketLayerIDs.push(t.map((e=>e.id))));}}const d=e.aF(u.glyphDependencies,(e=>Object.keys(e).map(Number)));this.inFlightDependencies.forEach((e=>null==e?void 0:e.abort())),this.inFlightDependencies=[];let f=Promise.resolve({});if(Object.keys(d).length){const e=new AbortController;this.inFlightDependencies.push(e),f=n.sendAsync({type:"GG",data:{stacks:d,source:this.source,tileID:this.tileID,type:"glyphs"}},e);}const g=Object.keys(u.iconDependencies);let p=Promise.resolve({}),m=Promise.resolve({});if(g.length){const e=new AbortController;this.inFlightDependencies.push(e),p=n.sendAsync({type:"GI",data:{icons:g,source:this.source,tileID:this.tileID,type:"icons"}},e);const t=g.filter((e=>e.includes("msdf"))).map((e=>e.replace("msdf","msdf-backgrounds")));t.length&&(m=n.sendAsync({type:"GI",data:{icons:t,source:this.source,tileID:this.tileID,type:"icons"}},e));}const y=Object.keys(u.patternDependencies);let v=Promise.resolve({});if(y.length){const e=new AbortController;this.inFlightDependencies.push(e),v=n.sendAsync({type:"GI",data:{icons:y,source:this.source,tileID:this.tileID,type:"patterns"}},e);}const[w,x,b,S]=yield Promise.all([f,p,m,v]),_=new o(w),M=new e.bo(x,S),I=new e.bo(b,{});for(const t in c){const o=c[t];o instanceof e.a6?(s(o.layers,this.zoom,r),e.bp({bucket:o,glyphMap:w,glyphPositions:_.positions,imageMap:x,imagePositions:M.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical})):o.hasPattern&&(o instanceof e.bq||o instanceof e.br||o instanceof e.bs)&&(s(o.layers,this.zoom,r),o.addFeatures(u,this.tileID.canonical,M.patternPositions));}return this.status="done",{buckets:Object.values(c).filter((e=>!e.isEmpty())),featureIndex:l,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:_.image,imageAtlas:M,imageBackgroundsAtlas:I,glyphMap:this.returnDependencies?w:null,iconMap:this.returnDependencies?x:null,glyphPositions:this.returnDependencies?_.positions:null}}))}}function s(t,o,i){const s=new e.z(o);for(const e of t)e.recalculate(s,i);}class r{constructor(e,t,o){this.actor=e,this.layerIndex=t,this.availableImages=o,this.fetching={},this.loading={},this.loaded={};}loadVectorTile(t,o){return e._(this,void 0,void 0,(function*(){const i=yield e.l(t.request,o);try{return {vectorTile:new e.bt.VectorTile(new e.bu(i.data)),rawData:i.data,cacheControl:i.cacheControl,expires:i.expires}}catch(e){const o=new Uint8Array(i.data);let s=`Unable to parse the tile at ${t.request.url}, `;throw s+=31===o[0]&&139===o[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${e.message}`,new Error(s)}}))}loadTile(t){return e._(this,void 0,void 0,(function*(){const o=t.uid,s=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.bv(t.request),r=new i(t);this.loading[o]=r;const n=new AbortController;r.abort=n;try{const i=yield this.loadVectorTile(t,n);if(delete this.loading[o],!i)return null;const a=i.rawData,l={};i.expires&&(l.expires=i.expires),i.cacheControl&&(l.cacheControl=i.cacheControl);const c={};if(s){const e=s.finish();e&&(c.resourceTiming=JSON.parse(JSON.stringify(e)));}r.vectorTile=i.vectorTile;const u=r.parse(i.vectorTile,this.layerIndex,this.availableImages,this.actor);this.loaded[o]=r,this.fetching[o]={rawTileData:a,cacheControl:l,resourceTiming:c};try{const t=yield u;return e.e({rawTileData:a.slice(0)},t,l,c)}finally{delete this.fetching[o];}}catch(e){throw delete this.loading[o],r.status="done",this.loaded[o]=r,e}}))}reloadTile(t){return e._(this,void 0,void 0,(function*(){const o=t.uid;if(!this.loaded||!this.loaded[o])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const i=this.loaded[o];if(i.showCollisionBoxes=t.showCollisionBoxes,"parsing"===i.status){const t=yield i.parse(i.vectorTile,this.layerIndex,this.availableImages,this.actor);let s;if(this.fetching[o]){const{rawTileData:i,cacheControl:r,resourceTiming:n}=this.fetching[o];delete this.fetching[o],s=e.e({rawTileData:i.slice(0)},t,r,n);}else s=t;return s}if("done"===i.status&&i.vectorTile)return i.parse(i.vectorTile,this.layerIndex,this.availableImages,this.actor)}))}abortTile(t){return e._(this,void 0,void 0,(function*(){const e=this.loading,o=t.uid;e&&e[o]&&e[o].abort&&(e[o].abort.abort(),delete e[o]);}))}removeTile(t){return e._(this,void 0,void 0,(function*(){this.loaded&&this.loaded[t.uid]&&delete this.loaded[t.uid];}))}}class n{constructor(){this.loaded={};}loadTile(t){return e._(this,void 0,void 0,(function*(){const{uid:o,encoding:i,rawImageData:s,redFactor:r,greenFactor:n,blueFactor:a,baseShift:l}=t,c=s.width+2,u=s.height+2,h=e.b(s)?new e.R({width:c,height:u},yield e.bw(s,-1,-1,c,u)):s,d=new e.bx(o,h,i,r,n,a,l);return this.loaded=this.loaded||{},this.loaded[o]=d,d}))}removeTile(e){const t=this.loaded,o=e.uid;t&&t[o]&&delete t[o];}}function a(e,t){if(0!==e.length){l(e[0],t);for(var o=1;o=Math.abs(a)?o-l+a:a-l+o,o=l;}o+i>=0!=!!t&&e.reverse();}var c=e.by((function e(t,o){var i,s=t&&t.type;if("FeatureCollection"===s)for(i=0;i>31}function I(e,t){for(var o=e.loadGeometry(),i=e.type,s=0,r=0,n=o.length,a=0;ae},T=Math.fround||(C=new Float32Array(1),e=>(C[0]=+e,C[0]));var C;const L=3,O=5,F=6;class z{constructor(e){this.options=Object.assign(Object.create(D),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[];}load(e){const{log:t,minZoom:o,maxZoom:i}=this.options;t&&console.time("total time");const s=`prepare ${e.length} points`;t&&console.time(s),this.points=e;const r=[];for(let t=0;t=o;e--){const o=+Date.now();n=this.trees[e]=this._createTree(this._cluster(n,e)),t&&console.log("z%d: %d clusters in %dms",e,n.numItems,+Date.now()-o);}return t&&console.timeEnd("total time"),this}getClusters(e,t){let o=((e[0]+180)%360+360)%360-180;const i=Math.max(-90,Math.min(90,e[1]));let s=180===e[2]?180:((e[2]+180)%360+360)%360-180;const r=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)o=-180,s=180;else if(o>s){const e=this.getClusters([o,i,180,r],t),n=this.getClusters([-180,i,s,r],t);return e.concat(n)}const n=this.trees[this._limitZoom(t)],a=n.range(E(o),j(r),E(s),j(i)),l=n.data,c=[];for(const e of a){const t=this.stride*e;c.push(l[t+O]>1?A(l,t,this.clusterProps):this.points[l[t+L]]);}return c}getChildren(e){const t=this._getOriginId(e),o=this._getOriginZoom(e),i="No cluster with the specified id.",s=this.trees[o];if(!s)throw new Error(i);const r=s.data;if(t*this.stride>=r.length)throw new Error(i);const n=this.options.radius/(this.options.extent*Math.pow(2,o-1)),a=s.within(r[t*this.stride],r[t*this.stride+1],n),l=[];for(const t of a){const o=t*this.stride;r[o+4]===e&&l.push(r[o+O]>1?A(r,o,this.clusterProps):this.points[r[o+L]]);}if(0===l.length)throw new Error(i);return l}getLeaves(e,t,o){const i=[];return this._appendLeaves(i,e,t=t||10,o=o||0,0),i}getTile(e,t,o){const i=this.trees[this._limitZoom(e)],s=Math.pow(2,e),{extent:r,radius:n}=this.options,a=n/r,l=(o-a)/s,c=(o+1+a)/s,u={features:[]};return this._addTileFeatures(i.range((t-a)/s,l,(t+1+a)/s,c),i.data,t,o,s,u),0===t&&this._addTileFeatures(i.range(1-a/s,l,1,c),i.data,s,o,s,u),t===s-1&&this._addTileFeatures(i.range(0,l,a/s,c),i.data,-1,o,s,u),u.features.length?u:null}getClusterExpansionZoom(e){let t=this._getOriginZoom(e)-1;for(;t<=this.options.maxZoom;){const o=this.getChildren(e);if(t++,1!==o.length)break;e=o[0].properties.cluster_id;}return t}_appendLeaves(e,t,o,i,s){const r=this.getChildren(t);for(const t of r){const r=t.properties;if(r&&r.cluster?s+r.point_count<=i?s+=r.point_count:s=this._appendLeaves(e,r.cluster_id,o,i,s):s1;let l,c,u;if(a)l=G(t,e,this.clusterProps),c=t[e],u=t[e+1];else {const o=this.points[t[e+L]];l=o.properties;const[i,s]=o.geometry.coordinates;c=E(i),u=j(s);}const h={type:1,geometry:[[Math.round(this.options.extent*(c*s-o)),Math.round(this.options.extent*(u*s-i))]],tags:l};let d;d=a||this.options.generateId?t[e+L]:this.points[t[e+L]].id,void 0!==d&&(h.id=d),r.features.push(h);}}_limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}_cluster(e,t){const{radius:o,extent:i,reduce:s,minPoints:r}=this.options,n=o/(i*Math.pow(2,t)),a=e.data,l=[],c=this.stride;for(let o=0;ot&&(f+=a[o+O]);}if(f>d&&f>=r){let e,r=i*d,n=u*d,g=-1;const p=((o/c|0)<<5)+(t+1)+this.points.length;for(const i of h){const l=i*c;if(a[l+2]<=t)continue;a[l+2]=t;const u=a[l+O];r+=a[l]*u,n+=a[l+1]*u,a[l+4]=p,s&&(e||(e=this._map(a,o,!0),g=this.clusterProps.length,this.clusterProps.push(e)),s(e,this._map(a,l)));}a[o+4]=p,l.push(r/f,n/f,1/0,p,-1,f),s&&l.push(g);}else {for(let e=0;e1)for(const e of h){const o=e*c;if(!(a[o+2]<=t)){a[o+2]=t;for(let e=0;e>5}_getOriginZoom(e){return (e-this.points.length)%32}_map(e,t,o){if(e[t+O]>1){const i=this.clusterProps[e[t+F]];return o?Object.assign({},i):i}const i=this.points[e[t+L]].properties,s=this.options.map(i);return o&&s===i?Object.assign({},s):s}}function A(e,t,o){return {type:"Feature",id:e[t+L],properties:G(e,t,o),geometry:{type:"Point",coordinates:[(i=e[t],360*(i-.5)),R(e[t+1])]}};var i;}function G(e,t,o){const i=e[t+O],s=i>=1e4?`${Math.round(i/1e3)}k`:i>=1e3?Math.round(i/100)/10+"k":i,r=e[t+F],n=-1===r?{}:Object.assign({},o[r]);return Object.assign(n,{cluster:!0,cluster_id:e[t+L],point_count:i,point_count_abbreviated:s})}function E(e){return e/360+.5}function j(e){const t=Math.sin(e*Math.PI/180),o=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return o<0?0:o>1?1:o}function R(e){const t=(180-360*e)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}function Z(e,t,o,i){let s=i;const r=t+(o-t>>1);let n,a=o-t;const l=e[t],c=e[t+1],u=e[o],h=e[o+1];for(let i=t+3;is)n=i,s=t;else if(t===s){const e=Math.abs(i-r);ei&&(n-t>3&&Z(e,t,n,i),e[n+2]=s,o-n>3&&Z(e,n,o,i));}function N(e,t,o,i,s,r){let n=s-o,a=r-i;if(0!==n||0!==a){const l=((e-o)*n+(t-i)*a)/(n*n+a*a);l>1?(o=s,i=r):l>0&&(o+=n*l,i+=a*l);}return n=e-o,a=t-i,n*n+a*a}function J(e,t,o,i){const s={id:null==e?null:e,type:t,geometry:o,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===t||"MultiPoint"===t||"LineString"===t)W(s,o);else if("Polygon"===t)W(s,o[0]);else if("MultiLineString"===t)for(const e of o)W(s,e);else if("MultiPolygon"===t)for(const e of o)W(s,e[0]);return s}function W(e,t){for(let o=0;o0&&(n+=i?(s*l-a*r)/2:Math.sqrt(Math.pow(a-s,2)+Math.pow(l-r,2))),s=a,r=l;}const a=t.length-3;t[2]=1,Z(t,0,a,o),t[a+2]=1,t.size=Math.abs(n),t.start=0,t.end=t.size;}function q(e,t,o,i){for(let s=0;s1?1:o}function U(e,t,o,i,s,r,n,a){if(i/=t,r>=(o/=t)&&n=i)return null;const l=[];for(const t of e){const e=t.geometry;let r=t.type;const n=0===s?t.minX:t.minY,c=0===s?t.maxX:t.maxY;if(n>=o&&c=i)continue;let u=[];if("Point"===r||"MultiPoint"===r)$(e,u,o,i,s);else if("LineString"===r)K(e,u,o,i,s,!1,a.lineMetrics);else if("MultiLineString"===r)ee(e,u,o,i,s,!1);else if("Polygon"===r)ee(e,u,o,i,s,!0);else if("MultiPolygon"===r)for(const t of e){const e=[];ee(t,e,o,i,s,!0),e.length&&u.push(e);}if(u.length){if(a.lineMetrics&&"LineString"===r){for(const e of u)l.push(J(t.id,r,e,t.tags));continue}"LineString"!==r&&"MultiLineString"!==r||(1===u.length?(r="LineString",u=u[0]):r="MultiLineString"),"Point"!==r&&"MultiPoint"!==r||(r=3===u.length?"Point":"MultiPoint"),l.push(J(t.id,r,u,t.tags));}}return l.length?l:null}function $(e,t,o,i,s){for(let r=0;r=o&&n<=i&&te(t,e[r],e[r+1],e[r+2]);}}function K(e,t,o,i,s,r,n){let a=Q(e);const l=0===s?oe:ie;let c,u,h=e.start;for(let d=0;do&&(u=l(a,f,g,m,y,o),n&&(a.start=h+c*u)):v>i?w=o&&(u=l(a,f,g,m,y,o),x=!0),w>i&&v<=i&&(u=l(a,f,g,m,y,i),x=!0),!r&&x&&(n&&(a.end=h+c*u),t.push(a),a=Q(e)),n&&(h+=c);}let d=e.length-3;const f=e[d],g=e[d+1],p=0===s?f:g;p>=o&&p<=i&&te(a,f,g,e[d+2]),d=a.length-3,r&&d>=3&&(a[d]!==a[0]||a[d+1]!==a[1])&&te(a,a[0],a[1],a[2]),a.length&&t.push(a);}function Q(e){const t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function ee(e,t,o,i,s,r){for(const n of e)K(n,t,o,i,s,r,!1);}function te(e,t,o,i){e.push(t,o,i);}function oe(e,t,o,i,s,r){const n=(r-t)/(i-t);return te(e,r,o+(s-o)*n,1),n}function ie(e,t,o,i,s,r){const n=(r-o)/(s-o);return te(e,t+(i-t)*n,r,1),n}function se(e,t){const o=[];for(let i=0;i0&&t.size<(s?n:i))return void(o.numPoints+=t.length/3);const a=[];for(let e=0;en)&&(o.numSimplified++,a.push(t[e],t[e+1])),o.numPoints++;s&&function(e,t){let o=0;for(let t=0,i=e.length,s=i-2;t0===t)for(let t=0,o=e.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");let i=function(e,t){const o=[];if("FeatureCollection"===e.type)for(let i=0;i1&&console.time("creation"),d=this.tiles[h]=le(e,t,o,i,l),this.tileCoords.push({z:t,x:o,y:i}),c)){c>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,o,i,d.numFeatures,d.numPoints,d.numSimplified),console.timeEnd("creation"));const e=`z${t}`;this.stats[e]=(this.stats[e]||0)+1,this.total++;}if(d.source=e,null==s){if(t===l.indexMaxZoom||d.numPoints<=l.indexMaxPoints)continue}else {if(t===l.maxZoom||t===s)continue;if(null!=s){const e=s-t;if(o!==r>>e||i!==n>>e)continue}}if(d.source=null,0===e.length)continue;c>1&&console.time("clipping");const f=.5*l.buffer/l.extent,g=.5-f,p=.5+f,m=1+f;let y=null,v=null,w=null,x=null,b=U(e,u,o-f,o+p,0,d.minX,d.maxX,l),S=U(e,u,o+g,o+m,0,d.minX,d.maxX,l);e=null,b&&(y=U(b,u,i-f,i+p,1,d.minY,d.maxY,l),v=U(b,u,i+g,i+m,1,d.minY,d.maxY,l),b=null),S&&(w=U(S,u,i-f,i+p,1,d.minY,d.maxY,l),x=U(S,u,i+g,i+m,1,d.minY,d.maxY,l),S=null),c>1&&console.timeEnd("clipping"),a.push(y||[],t+1,2*o,2*i),a.push(v||[],t+1,2*o,2*i+1),a.push(w||[],t+1,2*o+1,2*i),a.push(x||[],t+1,2*o+1,2*i+1);}}getTile(e,t,o){e=+e,t=+t,o=+o;const i=this.options,{extent:s,debug:r}=i;if(e<0||e>24)return null;const n=1<1&&console.log("drilling down to z%d-%d-%d",e,t,o);let l,c=e,u=t,h=o;for(;!l&&c>0;)c--,u>>=1,h>>=1,l=this.tiles[fe(c,u,h)];return l&&l.source?(r>1&&(console.log("found parent tile z%d-%d-%d",c,u,h),console.time("drilling down")),this.splitTile(l.source,c,u,h,e,t,o),r>1&&console.timeEnd("drilling down"),this.tiles[a]?ne(this.tiles[a],s):null):null}}function fe(e,t,o){return 32*((1<{n.properties=e;const t={};for(const e of a)t[e]=i[e].evaluate(r,n);return t},t.reduce=(e,t)=>{n.properties=t;for(const t of a)r.accumulated=e[t],e[t]=s[t].evaluate(r,n);},t}(t)).load((yield this._pendingData).features):(s=yield this._pendingData,new de(s,t.geojsonVtOptions)),this.loaded={};const o={};if(i){const e=i.finish();e&&(o.resourceTiming={},o.resourceTiming[t.source]=JSON.parse(JSON.stringify(e)));}return o}catch(t){if(delete this._pendingRequest,e.bB(t))return {abandoned:!0};throw t}var s;}))}getData(){return e._(this,void 0,void 0,(function*(){return this._pendingData}))}reloadTile(e){const t=this.loaded;return t&&t[e.uid]?super.reloadTile(e):this.loadTile(e)}loadAndProcessGeoJSON(t,o){return e._(this,void 0,void 0,(function*(){let i=yield this.loadGeoJSON(t,o);if(delete this._pendingRequest,"object"!=typeof i)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(c(i,!0),t.filter){const o=e.bC(t.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===o.result)throw new Error(o.value.map((e=>`${e.key}: ${e.message}`)).join(", "));const s=i.features.filter((e=>o.value.evaluate({zoom:0},e)));i={type:"FeatureCollection",features:s};}return i}))}loadGeoJSON(t,o){return e._(this,void 0,void 0,(function*(){const{promoteId:i}=t;if(t.request){const s=yield e.h(t.request,o);return this._dataUpdateable=pe(s.data,i)?me(s.data,i):void 0,s.data}if("string"==typeof t.data)try{const e=JSON.parse(t.data);return this._dataUpdateable=pe(e,i)?me(e,i):void 0,e}catch(e){throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`)}if(!t.dataDiff)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${t.source}`);return function(e,t,o){var i,s,r,n;if(t.removeAll&&e.clear(),t.remove)for(const o of t.remove)e.delete(o);if(t.add)for(const i of t.add){const t=ge(i,o);null!=t&&e.set(t,i);}if(t.update)for(const o of t.update){let t=e.get(o.id);if(null==t)continue;const a=!o.removeAllProperties&&((null===(i=o.removeProperties)||void 0===i?void 0:i.length)>0||(null===(s=o.addOrUpdateProperties)||void 0===s?void 0:s.length)>0);if((o.newGeometry||o.removeAllProperties||a)&&(t=Object.assign({},t),e.set(o.id,t),a&&(t.properties=Object.assign({},t.properties))),o.newGeometry&&(t.geometry=o.newGeometry),o.removeAllProperties)t.properties={};else if((null===(r=o.removeProperties)||void 0===r?void 0:r.length)>0)for(const e of o.removeProperties)Object.prototype.hasOwnProperty.call(t.properties,e)&&delete t.properties[e];if((null===(n=o.addOrUpdateProperties)||void 0===n?void 0:n.length)>0)for(const{key:e,value:i}of o.addOrUpdateProperties)t.properties[e]=i;}}(this._dataUpdateable,t.dataDiff,i),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(t){return e._(this,void 0,void 0,(function*(){this._pendingRequest&&this._pendingRequest.abort();}))}getClusterExpansionZoom(e){return this._geoJSONIndex.getClusterExpansionZoom(e.clusterId)}getClusterChildren(e){return this._geoJSONIndex.getChildren(e.clusterId)}getClusterLeaves(e){return this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset)}}class ve{constructor(t){this.self=t,this.actor=new e.F(t),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw new Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t;},this.self.addProtocol=e.bi,this.self.removeProtocol=e.bj,this.self.registerRTLTextPlugin=t=>{if(e.bD.isParsed())throw new Error("RTL text plugin already registered.");e.bD.setMethods(t);},this.actor.registerMessageHandler("LDT",((e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t))),this.actor.registerMessageHandler("RDT",((t,o)=>e._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(t,o.source).removeTile(o);})))),this.actor.registerMessageHandler("GCEZ",((t,o)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,o.type,o.source).getClusterExpansionZoom(o)})))),this.actor.registerMessageHandler("GCC",((t,o)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,o.type,o.source).getClusterChildren(o)})))),this.actor.registerMessageHandler("GCL",((t,o)=>e._(this,void 0,void 0,(function*(){return this._getWorkerSource(t,o.type,o.source).getClusterLeaves(o)})))),this.actor.registerMessageHandler("LD",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t))),this.actor.registerMessageHandler("GD",((e,t)=>this._getWorkerSource(e,t.type,t.source).getData())),this.actor.registerMessageHandler("LT",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t))),this.actor.registerMessageHandler("RT",((e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t))),this.actor.registerMessageHandler("AT",((e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t))),this.actor.registerMessageHandler("RMT",((e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t))),this.actor.registerMessageHandler("RS",((t,o)=>e._(this,void 0,void 0,(function*(){if(!this.workerSources[t]||!this.workerSources[t][o.type]||!this.workerSources[t][o.type][o.source])return;const e=this.workerSources[t][o.type][o.source];delete this.workerSources[t][o.type][o.source],void 0!==e.removeSource&&e.removeSource(o);})))),this.actor.registerMessageHandler("RM",(t=>e._(this,void 0,void 0,(function*(){delete this.layerIndexes[t],delete this.availableImages[t],delete this.workerSources[t],delete this.demWorkerSources[t];})))),this.actor.registerMessageHandler("SR",((t,o)=>e._(this,void 0,void 0,(function*(){this.referrer=o;})))),this.actor.registerMessageHandler("SRPS",((e,t)=>this._syncRTLPluginState(e,t))),this.actor.registerMessageHandler("IS",((t,o)=>e._(this,void 0,void 0,(function*(){this.self.importScripts(o);})))),this.actor.registerMessageHandler("SI",((e,t)=>this._setImages(e,t))),this.actor.registerMessageHandler("UL",((t,o)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).update(o.layers,o.removedIds);})))),this.actor.registerMessageHandler("SL",((t,o)=>e._(this,void 0,void 0,(function*(){this._getLayerIndex(t).replace(o);}))));}_setImages(t,o){return e._(this,void 0,void 0,(function*(){this.availableImages[t]=o;for(const e in this.workerSources[t]){const i=this.workerSources[t][e];for(const e in i)i[e].availableImages=o;}}))}_syncRTLPluginState(t,o){return e._(this,void 0,void 0,(function*(){if(e.bD.isParsed())return e.bD.getState();if("loading"!==o.pluginStatus)return e.bD.setState(o),o;const t=o.pluginURL;if(this.self.importScripts(t),e.bD.isParsed()){const o={pluginStatus:"loaded",pluginURL:t};return e.bD.setState(o),o}throw e.bD.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${t}`)}))}_getAvailableImages(e){let t=this.availableImages[e];return t||(t=[]),t}_getLayerIndex(e){let o=this.layerIndexes[e];return o||(o=this.layerIndexes[e]=new t),o}_getWorkerSource(e,t,o){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][o]){const i={sendAsync:(t,o)=>(t.targetMapId=e,this.actor.sendAsync(t,o))};switch(t){case"vector":this.workerSources[e][t][o]=new r(i,this._getLayerIndex(e),this._getAvailableImages(e));break;case"geojson":this.workerSources[e][t][o]=new ye(i,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][o]=new this.externalWorkerSourceTypes[t](i,this._getLayerIndex(e),this._getAvailableImages(e));}}return this.workerSources[e][t][o]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new n),this.demWorkerSources[e][t]}}return e.i(self)&&(self.worker=new ve(self)),ve})); + +define("index",["exports","./shared"],(function(t,e){"use strict";var i="4.7.0";let a,s;const o={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frameAsync:t=>new Promise(((i,a)=>{const s=requestAnimationFrame(i);t.signal.addEventListener("abort",(()=>{cancelAnimationFrame(s),a(e.c());}));})),getImageData(t,e=0){return this.getImageCanvasContext(t).getImageData(-e,-e,t.width+2*e,t.height+2*e)},getImageCanvasContext(t){const e=window.document.createElement("canvas"),i=e.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("failed to create canvas 2d context");return e.width=t.width,e.height=t.height,i.drawImage(t,0,0,t.width,t.height),i},resolveURL:t=>(a||(a=document.createElement("a")),a.href=t,a.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==s&&(s=matchMedia("(prefers-reduced-motion: reduce)")),s.matches)}};class r{static testProp(t){if(!r.docStyle)return t[0];for(let e=0;e{window.removeEventListener("click",r.suppressClickInternal,!0);}),0);}static getScale(t){const e=t.getBoundingClientRect();return {x:e.width/t.offsetWidth||1,y:e.height/t.offsetHeight||1,boundingClientRect:e}}static getPoint(t,i,a){const s=i.boundingClientRect;return new e.P((a.clientX-s.left)/i.x-t.clientLeft,(a.clientY-s.top)/i.y-t.clientTop)}static mousePos(t,e){const i=r.getScale(t);return r.getPoint(t,i,e)}static touchPos(t,e){const i=[],a=r.getScale(t);for(let s=0;s{l&&d(l),l=null,u=!0;},h.onerror=()=>{c=!0,l=null;},h.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(t){let i,a,s,o;t.resetRequestQueue=()=>{i=[],a=0,s=0,o={};},t.addThrottleControl=t=>{const e=s++;return o[e]=t,e},t.removeThrottleControl=t=>{delete o[t],l();},t.getImage=(t,a,s=!0)=>new Promise(((o,r)=>{n.supported&&(t.headers||(t.headers={}),t.headers.accept="image/webp,*/*"),e.e(t,{type:"image"}),i.push({abortController:a,requestParameters:t,supportImageRefresh:s,state:"queued",onError:t=>{r(t);},onSuccess:t=>{o(t);}}),l();}));const r=t=>e._(this,void 0,void 0,(function*(){t.state="running";const{requestParameters:i,supportImageRefresh:s,onError:o,onSuccess:r,abortController:n}=t,c=!1===s&&!e.i(self)&&!e.g(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((t,e)=>t&&"accept"===e),!0));a++;const u=c?h(i,n):e.m(i,n);try{const i=yield u;delete t.abortController,t.state="completed",i.data instanceof HTMLImageElement||e.b(i.data)?r(i):i.data&&r({data:yield(d=i.data,"function"==typeof createImageBitmap?e.d(d):e.f(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(e){delete t.abortController,o(e);}finally{a--,l();}var d;})),l=()=>{const t=(()=>{for(const t of Object.keys(o))if(o[t]())return !0;return !1})()?e.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:e.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let e=a;e0;e++){const t=i.shift();t.abortController.signal.aborted?e--:r(t);}},h=(t,i)=>new Promise(((a,s)=>{const o=new Image,r=t.url,n=t.credentials;n&&"include"===n?o.crossOrigin="use-credentials":(n&&"same-origin"===n||!e.s(r))&&(o.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{o.src="",s(e.c());})),o.fetchPriority="high",o.onload=()=>{o.onerror=o.onload=null,a({data:o});},o.onerror=()=>{o.onerror=o.onload=null,i.signal.aborted||s(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."));},o.src=r;}));}(_||(_={})),_.resetRequestQueue();class p{constructor(t){this._transformRequestFn=t;}transformRequest(t,e){return this._transformRequestFn&&this._transformRequestFn(t,e)||{url:t}}setTransformRequest(t){this._transformRequestFn=t;}}function m(t){var i=new e.A(3);return i[0]=t[0],i[1]=t[1],i[2]=t[2],i}var f,g=function(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t[2]=e[2]-i[2],t};f=new e.A(3),e.A!=Float32Array&&(f[0]=0,f[1]=0,f[2]=0);var v=function(t){var e=t[0],i=t[1];return e*e+i*i};function x(t){const e=[];if("string"==typeof t)e.push({id:"default",url:t});else if(t&&t.length>0){const i=[];for(const{id:a,url:s}of t){const t=`${a}${s}`;-1===i.indexOf(t)&&(i.push(t),e.push({id:a,url:s}));}}return e}function y(t,e,i){const a=t.split("?");return a[0]+=`${e}${i}`,a.join("?")}!function(){var t=new e.A(2);e.A!=Float32Array&&(t[0]=0,t[1]=0);}();class b{constructor(t,e,i,a){this.context=t,this.format=i,this.texture=t.gl.createTexture(),this.update(e,a);}update(t,i,a){const{width:s,height:o}=t,r=!(this.size&&this.size[0]===s&&this.size[1]===o||a),{context:n}=this,{gl:l}=n;if(this.useMipmap=Boolean(i&&i.useMipmap),l.bindTexture(l.TEXTURE_2D,this.texture),n.pixelStoreUnpackFlipY.set(!1),n.pixelStoreUnpack.set(1),n.pixelStoreUnpackPremultiplyAlpha.set(this.format===l.RGBA&&(!i||!1!==i.premultiply)),r)this.size=[s,o],t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement||t instanceof ImageData||e.b(t)?l.texImage2D(l.TEXTURE_2D,0,this.format,this.format,l.UNSIGNED_BYTE,t):l.texImage2D(l.TEXTURE_2D,0,this.format,s,o,0,this.format,l.UNSIGNED_BYTE,t.data);else {const{x:i,y:r}=a||{x:0,y:0};t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement||t instanceof ImageData||e.b(t)?l.texSubImage2D(l.TEXTURE_2D,0,i,r,l.RGBA,l.UNSIGNED_BYTE,t):l.texSubImage2D(l.TEXTURE_2D,0,i,r,s,o,l.RGBA,l.UNSIGNED_BYTE,t.data);}this.useMipmap&&this.isSizePowerOfTwo()&&l.generateMipmap(l.TEXTURE_2D);}bind(t,e,i){const{context:a}=this,{gl:s}=a;s.bindTexture(s.TEXTURE_2D,this.texture),i!==s.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(i=s.LINEAR),t!==this.filter&&(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,t),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,i||t),this.filter=t),e!==this.wrap&&(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,e),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,e),this.wrap=e);}isSizePowerOfTwo(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0}destroy(){const{gl:t}=this.context;t.deleteTexture(this.texture),this.texture=null;}}function w(t){const{userImage:e}=t;return !!(e&&e.render&&e.render())&&(t.data.replace(new Uint8Array(e.data.buffer)),!0)}class T extends e.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new e.R({width:1,height:1}),this.dirty=!0;}isLoaded(){return this.loaded}setLoaded(t){if(this.loaded!==t&&(this.loaded=t,t)){for(const{ids:t,promiseResolve:e}of this.requestors)e(this._getImagesForIds(t));this.requestors=[];}}getImage(t){const i=this.images[t];if(i&&!i.data&&i.spriteData){const t=i.spriteData;i.data=new e.R({width:t.width,height:t.height},t.context.getImageData(t.x,t.y,t.width,t.height).data),i.spriteData=null;}return i}addImage(t,e){if(this.images[t])throw new Error(`Image id ${t} already exist, use updateImage instead`);this._validate(t,e)&&(this.images[t]=e);}_validate(t,i){let a=!0;const s=i.data||i.spriteData;return this._validateStretch(i.stretchX,s&&s.width)||(this.fire(new e.j(new Error(`Image "${t}" has invalid "stretchX" value`))),a=!1),this._validateStretch(i.stretchY,s&&s.height)||(this.fire(new e.j(new Error(`Image "${t}" has invalid "stretchY" value`))),a=!1),this._validateContent(i.content,i)||(this.fire(new e.j(new Error(`Image "${t}" has invalid "content" value`))),a=!1),a}_validateStretch(t,e){if(!t)return !0;let i=0;for(const a of t){if(a[0]{let a=!0;if(!this.isLoaded())for(const e of t)this.images[e]||(a=!1);this.isLoaded()||a?e(this._getImagesForIds(t)):this.requestors.push({ids:t,promiseResolve:e});}))}_getImagesForIds(t){const i={};for(const a of t){let t=this.getImage(a);t||(this.fire(new e.k("styleimagemissing",{id:a})),t=this.getImage(a)),t?i[a]={data:t.data.clone(),pixelRatio:t.pixelRatio,sdf:t.sdf,version:t.version,stretchX:t.stretchX,stretchY:t.stretchY,content:t.content,textFitWidth:t.textFitWidth,textFitHeight:t.textFitHeight,hasRenderCallback:Boolean(t.userImage&&t.userImage.render)}:e.w(`Image "${a}" 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.`);}return i}getPixelSize(){const{width:t,height:e}=this.atlasImage;return {width:t,height:e}}getPattern(t){const i=this.patterns[t],a=this.getImage(t);if(!a)return null;if(i&&i.position.version===a.version)return i.position;if(i)i.position.version=a.version;else {const i={w:a.data.width+2,h:a.data.height+2,x:0,y:0},s=new e.I(i,a);this.patterns[t]={bin:i,position:s};}return this._updatePatternAtlas(),this.patterns[t].position}bind(t){const e=t.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new b(t,this.atlasImage,e.RGBA),this.atlasTexture.bind(e.LINEAR,e.CLAMP_TO_EDGE);}_updatePatternAtlas(){const t=[];for(const e in this.patterns)t.push(this.patterns[e].bin);const{w:i,h:a}=e.p(t),s=this.atlasImage;s.resize({width:i||1,height:a||1});for(const t in this.patterns){const{bin:i}=this.patterns[t],a=i.x+1,o=i.y+1,r=this.getImage(t).data,n=r.width,l=r.height;e.R.copy(r,s,{x:0,y:0},{x:a,y:o},{width:n,height:l}),e.R.copy(r,s,{x:0,y:l-1},{x:a,y:o-1},{width:n,height:1}),e.R.copy(r,s,{x:0,y:0},{x:a,y:o+l},{width:n,height:1}),e.R.copy(r,s,{x:n-1,y:0},{x:a-1,y:o},{width:1,height:l}),e.R.copy(r,s,{x:0,y:0},{x:a+n,y:o},{width:1,height:l});}this.dirty=!0;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(t){for(const i of t){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=!0;const t=this.getImage(i);t||e.w(`Image with ID: "${i}" was not found`),w(t)&&this.updateImage(i,t);}}}const I=1e20;function E(t,e,i,a,s,o,r,n,l){for(let h=e;h-1);l++,o[l]=n,r[l]=h,r[l+1]=I;}for(let n=0,l=0;n65535)throw new Error("glyphs > 65535 not supported");if(e.ranges[s])return {stack:t,id:i,glyph:a};if(!this.url)throw new Error("glyphsUrl is not set");if(!e.requests[s]){const i=C.loadGlyphRange(t,s,this.url,this.requestManager);e.requests[s]=i;}const o=yield e.requests[s];for(const t in o)this._doesCharSupportLocalGlyph(+t)||(e.glyphs[+t]=o[+t]);return e.ranges[s]=!0,{stack:t,id:i,glyph:o[i]||null}}))}_doesCharSupportLocalGlyph(t){return !!this.localIdeographFontFamily&&/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(t))}_tinySDF(t,i,a){const s=this.localIdeographFontFamily;if(!s)return;if(!this._doesCharSupportLocalGlyph(a))return;let o=t.tinySDF;if(!o){let e="400";/bold/i.test(i)?e="900":/medium/i.test(i)?e="500":/light/i.test(i)&&(e="200"),o=t.tinySDF=new C.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,fontFamily:s,fontWeight:e});}const r=o.draw(String.fromCharCode(a));return {id:a,bitmap:new e.o({width:r.width||60,height:r.height||60},r.data),metrics:{width:r.glyphWidth/2||24,height:r.glyphHeight/2||24,left:r.glyphLeft/2+.5||0,top:r.glyphTop/2-27.5||-8,advance:r.glyphAdvance/2||24,isDoubleResolution:!0}}}}C.loadGlyphRange=function(t,i,a,s){return e._(this,void 0,void 0,(function*(){const o=256*i,r=o+255,n=s.transformRequest(a.replace("{fontstack}",t).replace("{range}",`${o}-${r}`),"Glyphs"),l=yield e.l(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${o}-${r}`);const h={};for(const t of e.n(l.data))h[t.id]=t;return h}))},C.TinySDF=class{constructor({fontSize:t=24,buffer:e=3,radius:i=8,cutoff:a=.25,fontFamily:s="sans-serif",fontWeight:o="normal",fontStyle:r="normal"}={}){this.buffer=e,this.cutoff=a,this.radius=i;const n=this.size=t+4*e,l=this._createCanvas(n),h=this.ctx=l.getContext("2d",{willReadFrequently:!0});h.font=`${r} ${o} ${t}px ${s}`,h.textBaseline="alphabetic",h.textAlign="left",h.fillStyle="black",this.gridOuter=new Float64Array(n*n),this.gridInner=new Float64Array(n*n),this.f=new Float64Array(n),this.z=new Float64Array(n+1),this.v=new Uint16Array(n);}_createCanvas(t){const e=document.createElement("canvas");return e.width=e.height=t,e}draw(t){const{width:e,actualBoundingBoxAscent:i,actualBoundingBoxDescent:a,actualBoundingBoxLeft:s,actualBoundingBoxRight:o}=this.ctx.measureText(t),r=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(o-s))),l=Math.min(this.size-this.buffer,r+Math.ceil(a)),h=n+2*this.buffer,c=l+2*this.buffer,u=Math.max(h*c,0),d=new Uint8ClampedArray(u),_={data:d,width:h,height:c,glyphWidth:n,glyphHeight:l,glyphTop:r,glyphLeft:0,glyphAdvance:e};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:g}=this;p.clearRect(m,m,n,l),p.fillText(t,m,m+r);const v=p.getImageData(m,m,n,l);g.fill(I,0,u),f.fill(0,0,u);for(let t=0;t0?t*t:0,f[a]=t<0?t*t:0;}}E(g,0,0,h,c,h,this.f,this.v,this.z),E(f,m,m,n,l,h,this.f,this.v,this.z);for(let t=0;t1&&(r=t[++o]);const l=Math.abs(n-r.left),h=Math.abs(n-r.right),c=Math.min(l,h);let u;const d=e/i*(a+1);if(r.isDash){const t=a-Math.abs(d);u=Math.sqrt(c*c+t*t);}else u=a-Math.sqrt(c*c+d*d);this.data[s+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(t){for(let e=t.length-1;e>=0;--e){const i=t[e],a=t[e+1];i.zeroLength?t.splice(e,1):a&&a.isDash===i.isDash&&(a.left=i.left,t.splice(e,1));}const e=t[0],i=t[t.length-1];e.isDash===i.isDash&&(e.left=i.left-this.width,i.right=e.right+this.width);const a=this.width*this.nextRow;let s=0,o=t[s];for(let e=0;e1&&(o=t[++s]);const i=Math.abs(e-o.left),r=Math.abs(e-o.right),n=Math.min(i,r);this.data[a+e]=Math.max(0,Math.min(255,(o.isDash?n:-n)+128));}}addDash(t,i){const a=i?7:0,s=2*a+1;if(this.nextRow+s>this.height)return e.w("LineAtlas out of space"),null;let o=0;for(let e=0;e{t.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[k]}numActive(){return Object.keys(this.active).length}}const F=Math.floor(o.hardwareConcurrency/2);let B,O;function N(){return B||(B=new L),B}L.workerCount=e.C(globalThis)?Math.max(Math.min(F,3),1):1;class U{constructor(t,i){this.workerPool=t,this.actors=[],this.currentActor=0,this.id=i;const a=this.workerPool.acquire(i);for(let t=0;t{t.remove();})),this.actors=[],t&&this.workerPool.release(this.id);}registerMessageHandler(t,e){for(const i of this.actors)i.registerMessageHandler(t,e);}}function j(){return O||(O=new U(N(),e.G),O.registerMessageHandler("GR",((t,i,a)=>e.m(i,a)))),O}function Z(t,i){const a=e.H();return e.J(a,a,[1,1,0]),e.K(a,a,[.5*t.width,.5*t.height,1]),e.L(a,a,t.calculatePosMatrix(i.toUnwrapped()))}function G(t,e,i,a,s,o){const r=function(t,e,i){if(t)for(const a of t){const t=e[a];if(t&&t.source===i&&"fill-extrusion"===t.type)return !0}else for(const t in e){const a=e[t];if(a.source===i&&"fill-extrusion"===a.type)return !0}return !1}(s&&s.layers,e,t.id),n=o.maxPitchScaleFactor(),l=t.tilesIn(a,n,r);l.sort(q);const h=[];for(const a of l)h.push({wrappedTileID:a.tileID.wrapped().key,queryResults:a.tile.queryRenderedFeatures(e,i,t._state,a.queryGeometry,a.cameraQueryGeometry,a.scale,s,o,n,Z(t.transform,a.tileID))});const c=function(t){const e={},i={};for(const a of t){const t=a.queryResults,s=a.wrappedTileID,o=i[s]=i[s]||{};for(const i in t){const a=t[i],s=o[i]=o[i]||{},r=e[i]=e[i]||[];for(const t of a)s[t.featureIndex]||(s[t.featureIndex]=!0,r.push(t));}}return e}(h);for(const e in c)c[e].forEach((e=>{const i=e.feature,a=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=a;}));return c}function q(t,e){const i=t.tileID,a=e.tileID;return i.overscaledZ-a.overscaledZ||i.canonical.y-a.canonical.y||i.wrap-a.wrap||i.canonical.x-a.canonical.x}function V(t,i,a){return e._(this,void 0,void 0,(function*(){let s=t;if(t.url?s=(yield e.h(i.transformRequest(t.url,"Source"),a)).data:yield o.frameAsync(a),!s)return null;const r=e.M(e.e(s,t),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in s&&s.vector_layers&&(r.vectorLayerIds=s.vector_layers.map((t=>t.id))),r}))}class H{constructor(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):Array.isArray(t)&&(4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1])));}setNorthEast(t){return this._ne=t instanceof e.N?new e.N(t.lng,t.lat):e.N.convert(t),this}setSouthWest(t){return this._sw=t instanceof e.N?new e.N(t.lng,t.lat):e.N.convert(t),this}extend(t){const i=this._sw,a=this._ne;let s,o;if(t instanceof e.N)s=t,o=t;else {if(!(t instanceof H))return Array.isArray(t)?4===t.length||t.every(Array.isArray)?this.extend(H.convert(t)):this.extend(e.N.convert(t)):t&&("lng"in t||"lon"in t)&&"lat"in t?this.extend(e.N.convert(t)):this;if(s=t._sw,o=t._ne,!s||!o)return this}return i||a?(i.lng=Math.min(s.lng,i.lng),i.lat=Math.min(s.lat,i.lat),a.lng=Math.max(o.lng,a.lng),a.lat=Math.max(o.lat,a.lat)):(this._sw=new e.N(s.lng,s.lat),this._ne=new e.N(o.lng,o.lat)),this}getCenter(){return new e.N((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new e.N(this.getWest(),this.getNorth())}getSouthEast(){return new e.N(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return [this._sw.toArray(),this._ne.toArray()]}toString(){return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return !(this._sw&&this._ne)}contains(t){const{lng:i,lat:a}=e.N.convert(t);let s=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(s=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=a&&a<=this._ne.lat&&s}static convert(t){return t instanceof H?t:t?new H(t):t}static fromLngLat(t,i=0){const a=360*i/40075017,s=a/Math.cos(Math.PI/180*t.lat);return new H(new e.N(t.lng-s,t.lat-a),new e.N(t.lng+s,t.lat+a))}adjustAntiMeridian(){const t=new e.N(this._sw.lng,this._sw.lat),i=new e.N(this._ne.lng,this._ne.lat);return new H(t,t.lng>i.lng?new e.N(i.lng+360,i.lat):i)}}class W{constructor(t,e,i){this.bounds=H.convert(this.validateBounds(t)),this.minzoom=e||0,this.maxzoom=i||24;}validateBounds(t){return Array.isArray(t)&&4===t.length?[Math.max(-180,t[0]),Math.max(-90,t[1]),Math.min(180,t[2]),Math.min(90,t[3])]:[-180,-90,180,90]}contains(t){const i=Math.pow(2,t.z),a=Math.floor(e.O(this.bounds.getWest())*i),s=Math.floor(e.Q(this.bounds.getNorth())*i),o=Math.ceil(e.O(this.bounds.getEast())*i),r=Math.ceil(e.Q(this.bounds.getSouth())*i);return t.x>=a&&t.x=s&&t.y{this._options.tiles=t;})),this}setUrl(t){return this.setSourceProperty((()=>{this.url=t,this._options.url=t;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return e.e({},this._options)}loadTile(t){return e._(this,void 0,void 0,(function*(){const e=t.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(e,"Tile"),uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,tileSize:this.tileSize*t.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId};i.request.collectResourceTiming=this._collectResourceTiming;let a="RT";if(t.actor&&"expired"!==t.state){if("loading"===t.state)return new Promise(((e,i)=>{t.reloadPromise={resolve:e,reject:i};}))}else t.actor=this.dispatcher.getActor(),a="LT";t.abortController=new AbortController;try{const e=yield t.actor.sendAsync({type:a,data:i},t.abortController);if(delete t.abortController,t.aborted)return;this._afterTileLoadWorkerResponse(t,e);}catch(e){if(delete t.abortController,t.aborted)return;if(e&&404!==e.status)throw e;this._afterTileLoadWorkerResponse(t,null);}}))}_afterTileLoadWorkerResponse(t,e){if(e&&e.resourceTiming&&(t.resourceTiming=e.resourceTiming),e&&this.map._refreshExpiredTiles&&t.setExpiryData(e),t.loadVectorData(e,this.map.painter),t.reloadPromise){const e=t.reloadPromise;t.reloadPromise=null,this.loadTile(t).then(e.resolve).catch(e.reject);}}abortTile(t){return e._(this,void 0,void 0,(function*(){t.abortController&&(t.abortController.abort(),delete t.abortController),t.actor&&(yield t.actor.sendAsync({type:"AT",data:{uid:t.uid,type:this.type,source:this.id}}));}))}unloadTile(t){return e._(this,void 0,void 0,(function*(){t.unloadVectorData(),t.actor&&(yield t.actor.sendAsync({type:"RMT",data:{uid:t.uid,type:this.type,source:this.id}}));}))}hasTransition(){return !1}}class X extends e.E{constructor(t,i,a,s){super(),this.id=t,this.dispatcher=a,this.setEventedParent(s),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=e.e({type:"raster"},i),e.e(this,e.M(i,["url","scheme","tileSize"]));}load(){return e._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new e.k("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const t=yield V(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,t&&(e.e(this,t),t.bounds&&(this.tileBounds=new W(t.bounds,this.minzoom,this.maxzoom)),this.fire(new e.k("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new e.k("data",{dataType:"source",sourceDataType:"content"})));}catch(t){this._tileJSONRequest=null,this.fire(new e.j(t));}}))}loaded(){return this._loaded}onAdd(t){this.map=t,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(t){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),t(),this.load();}setTiles(t){return this.setSourceProperty((()=>{this._options.tiles=t;})),this}setUrl(t){return this.setSourceProperty((()=>{this.url=t,this._options.url=t;})),this}serialize(){return e.e({},this._options)}hasTile(t){return !this.tileBounds||this.tileBounds.contains(t.canonical)}loadTile(t){return e._(this,void 0,void 0,(function*(){const e=t.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);t.abortController=new AbortController;try{const i=yield _.getImage(this.map._requestManager.transformRequest(e,"Tile"),t.abortController,this.map._refreshExpiredTiles);if(delete t.abortController,t.aborted)return void(t.state="unloaded");if(i&&i.data){this.map._refreshExpiredTiles&&i.cacheControl&&i.expires&&t.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const e=this.map.painter.context,a=e.gl,s=i.data;t.texture=this.map.painter.getTileTexture(s.width),t.texture?t.texture.update(s,{useMipmap:!0}):(t.texture=new b(e,s,a.RGBA,{useMipmap:!0}),t.texture.bind(a.LINEAR,a.CLAMP_TO_EDGE,a.LINEAR_MIPMAP_NEAREST)),t.state="loaded";}}catch(e){if(delete t.abortController,t.aborted)t.state="unloaded";else if(e)throw t.state="errored",e}}))}abortTile(t){return e._(this,void 0,void 0,(function*(){t.abortController&&(t.abortController.abort(),delete t.abortController);}))}unloadTile(t){return e._(this,void 0,void 0,(function*(){t.texture&&this.map.painter.saveTileTexture(t.texture);}))}hasTransition(){return !1}}class K extends X{constructor(t,i,a,s){super(t,i,a,s),this.type="raster-dem",this.maxzoom=22,this._options=e.e({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(t){return e._(this,void 0,void 0,(function*(){const i=t.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),a=this.map._requestManager.transformRequest(i,"Tile");t.neighboringTiles=this._getNeighboringTiles(t.tileID),t.abortController=new AbortController;try{const i=yield _.getImage(a,t.abortController,this.map._refreshExpiredTiles);if(delete t.abortController,t.aborted)return void(t.state="unloaded");if(i&&i.data){const a=i.data;this.map._refreshExpiredTiles&&i.cacheControl&&i.expires&&t.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const s=e.b(a)&&e.U()?a:yield this.readImageNow(a),o={type:this.type,uid:t.uid,source:this.id,rawImageData:s,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!t.actor||"expired"===t.state){t.actor=this.dispatcher.getActor();const e=yield t.actor.sendAsync({type:"LDT",data:o});t.dem=e,t.needsHillshadePrepare=!0,t.needsTerrainPrepare=!0,t.state="loaded";}}}catch(e){if(delete t.abortController,t.aborted)t.state="unloaded";else if(e)throw t.state="errored",e}}))}readImageNow(t){return e._(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&e.V()){const i=t.width+2,a=t.height+2;try{return new e.R({width:i,height:a},yield e.W(t,-1,-1,i,a))}catch(t){}}return o.getImageData(t,1)}))}_getNeighboringTiles(t){const i=t.canonical,a=Math.pow(2,i.z),s=(i.x-1+a)%a,o=0===i.x?t.wrap-1:t.wrap,r=(i.x+1+a)%a,n=i.x+1===a?t.wrap+1:t.wrap,l={};return l[new e.S(t.overscaledZ,o,i.z,s,i.y).key]={backfilled:!1},l[new e.S(t.overscaledZ,n,i.z,r,i.y).key]={backfilled:!1},i.y>0&&(l[new e.S(t.overscaledZ,o,i.z,s,i.y-1).key]={backfilled:!1},l[new e.S(t.overscaledZ,t.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new e.S(t.overscaledZ,n,i.z,r,i.y-1).key]={backfilled:!1}),i.y+10&&e.e(s,{resourceTiming:a}),this.fire(new e.k("data",Object.assign(Object.assign({},s),{sourceDataType:"metadata"}))),this.fire(new e.k("data",Object.assign(Object.assign({},s),{sourceDataType:"content"})));}catch(t){if(this._pendingLoads--,this._removed)return void this.fire(new e.k("dataabort",{dataType:"source"}));this.fire(new e.j(t));}}))}loaded(){return 0===this._pendingLoads}loadTile(t){return e._(this,void 0,void 0,(function*(){const e=t.actor?"RT":"LT";t.actor=this.actor;const i={type:this.type,uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId};t.abortController=new AbortController;const a=yield this.actor.sendAsync({type:e,data:i},t.abortController);delete t.abortController,t.unloadVectorData(),t.aborted||t.loadVectorData(a,this.map.painter,"RT"===e);}))}abortTile(t){return e._(this,void 0,void 0,(function*(){t.abortController&&(t.abortController.abort(),delete t.abortController),t.aborted=!0;}))}unloadTile(t){return e._(this,void 0,void 0,(function*(){t.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:t.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return e.e({},this._options,{type:this.type,data:this._data})}hasTransition(){return !1}}var Y=e.Y([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class Q extends e.E{constructor(t,e,i,a){super(),this.id=t,this.dispatcher=i,this.coordinates=e.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(a),this.options=e;}load(t){return e._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new e.k("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const e=yield _.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,e&&e.data&&(this.image=e.data,t&&(this.coordinates=t),this._finishLoading());}catch(t){this._request=null,this._loaded=!0,this.fire(new e.j(t));}}))}loaded(){return this._loaded}updateImage(t){return t.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=t.url,this.load(t.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new e.k("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(t){this.map=t,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(t){this.coordinates=t;const i=t.map(e.Z.fromLngLat);this.tileID=function(t){let i=1/0,a=1/0,s=-1/0,o=-1/0;for(const e of t)i=Math.min(i,e.x),a=Math.min(a,e.y),s=Math.max(s,e.x),o=Math.max(o,e.y);const r=Math.max(s-i,o-a),n=Math.max(0,Math.floor(-Math.log(r)/Math.LN2)),l=Math.pow(2,n);return new e.a1(n,Math.floor((i+s)/2*l),Math.floor((a+o)/2*l))}(i),this.minzoom=this.maxzoom=this.tileID.z;const a=i.map((t=>this.tileID.getTilePoint(t)._round()));return this._boundsArray=new e.$,this._boundsArray.emplaceBack(a[0].x,a[0].y,0,0),this._boundsArray.emplaceBack(a[1].x,a[1].y,e.X,0),this._boundsArray.emplaceBack(a[3].x,a[3].y,0,e.X),this._boundsArray.emplaceBack(a[2].x,a[2].y,e.X,e.X),this.boundsBuffer&&(this.boundsBuffer.destroy(),delete this.boundsBuffer),this.fire(new e.k("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const t=this.map.painter.context,i=t.gl;this.boundsBuffer||(this.boundsBuffer=t.createVertexBuffer(this._boundsArray,Y.members)),this.boundsSegments||(this.boundsSegments=e.a0.simpleSegment(0,0,4,2)),this.texture||(this.texture=new b(t,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let a=!1;for(const t in this.tiles){const e=this.tiles[t];"loaded"!==e.state&&(e.state="loaded",e.texture=this.texture,a=!0);}a&&this.fire(new e.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(t){return e._(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(t.tileID.canonical)?(this.tiles[String(t.tileID.wrap)]=t,t.buckets={}):t.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return !1}}class tt extends Q{constructor(t,e,i,a){super(t,e,i,a),this.roundZoom=!0,this.type="video",this.options=e;}load(){return e._(this,void 0,void 0,(function*(){this._loaded=!1;const t=this.options;this.urls=[];for(const e of t.urls)this.urls.push(this.map._requestManager.transformRequest(e,"Source").url);try{const t=yield e.a3(this.urls);if(this._loaded=!0,!t)return;this.video=t,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading();}catch(t){this.fire(new e.j(t));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(t){if(this.video){const i=this.video.seekable;ti.end(0)?this.fire(new e.j(new e.a2(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=t;}}getVideo(){return this.video}onAdd(t){this.map||(this.map=t,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const t=this.map.painter.context,i=t.gl;this.boundsBuffer||(this.boundsBuffer=t.createVertexBuffer(this._boundsArray,Y.members)),this.boundsSegments||(this.boundsSegments=e.a0.simpleSegment(0,0,4,2)),this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new b(t,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let a=!1;for(const t in this.tiles){const e=this.tiles[t];"loaded"!==e.state&&(e.state="loaded",e.texture=this.texture,a=!0);}a&&this.fire(new e.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class et extends Q{constructor(t,i,a,s){super(t,i,a,s),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((t=>!Array.isArray(t)||2!==t.length||t.some((t=>"number"!=typeof t))))||this.fire(new e.j(new e.a2(`sources.${t}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new e.j(new e.a2(`sources.${t}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new e.j(new e.a2(`sources.${t}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new e.j(new e.a2(`sources.${t}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new e.j(new e.a2(`sources.${t}`,null,'missing required property "canvas"'))),this.options=i,this.animate=void 0===i.animate||i.animate;}load(){return e._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new e.j(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let t=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,t=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,t=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,a=i.gl;this.boundsBuffer||(this.boundsBuffer=i.createVertexBuffer(this._boundsArray,Y.members)),this.boundsSegments||(this.boundsSegments=e.a0.simpleSegment(0,0,4,2)),this.texture?(t||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new b(i,this.canvas,a.RGBA,{premultiply:!0});let s=!1;for(const t in this.tiles){const e=this.tiles[t];"loaded"!==e.state&&(e.state="loaded",e.texture=this.texture,s=!0);}s&&this.fire(new e.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const t of [this.canvas.width,this.canvas.height])if(isNaN(t)||t<=0)return !0;return !1}}const it={},at=t=>{switch(t){case"geojson":return J;case"image":return Q;case"raster":return X;case"raster-dem":return K;case"vector":return $;case"video":return tt;case"canvas":return et}return it[t]},st="RTLPluginLoaded";class ot extends e.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=j();}_syncState(t){return this.status=t,this.dispatcher.broadcast("SRPS",{pluginStatus:t,pluginURL:this.url}).catch((t=>{throw this.status="error",t}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(t){return e._(this,arguments,void 0,(function*(t,e=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=o.resolveURL(t),!this.url)throw new Error(`requested url ${t} is invalid`);if("unavailable"===this.status){if(!e)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return e._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new e.k(st));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let rt=null;function nt(){return rt||(rt=new ot),rt}class lt{constructor(t,i){this.timeAdded=0,this.fadeEndTime=0,this.tileID=t,this.uid=e.a4(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading";}registerFadeDuration(t){const e=t+this.timeAdded;ee.getLayer(t))).filter(Boolean);if(0!==t.length){a.layers=t,a.stateDependentLayerIds&&(a.stateDependentLayers=a.stateDependentLayerIds.map((e=>t.filter((t=>t.id===e))[0])));for(const e of t)i[e.id]=a;}}return i}(t.buckets,i.style),this.hasSymbolBuckets=!1;for(const t in this.buckets){const i=this.buckets[t];if(i instanceof e.a6){if(this.hasSymbolBuckets=!0,!a)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const t in this.buckets){const i=this.buckets[t];if(i instanceof e.a6&&i.hasRTLText){this.hasRTLText=!0,nt().lazyLoad();break}}this.queryPadding=0;for(const t in this.buckets){const e=this.buckets[t];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(t).queryRadius(e));}t.imageAtlas&&(this.imageAtlas=t.imageAtlas),t.imageBackgroundsAtlas&&(this.imageBackgroundsAtlas=t.imageBackgroundsAtlas),t.glyphAtlasImage&&(this.glyphAtlasImage=t.glyphAtlasImage);}else this.collisionBoxArray=new e.a5;}unloadVectorData(){for(const t in this.buckets)this.buckets[t].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageBackgroundsAtlasTexture&&this.imageBackgroundsAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.imageBackgroundsAtlas&&(this.imageBackgroundsAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(t){return this.buckets[t.id]}upload(t){for(const e in this.buckets){const i=this.buckets[e];i.uploadPending()&&i.upload(t);}const e=t.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new b(t,this.imageAtlas.image,e.RGBA),this.imageAtlas.uploaded=!0),this.imageBackgroundsAtlas&&!this.imageBackgroundsAtlas.uploaded&&(this.imageBackgroundsAtlasTexture=new b(t,this.imageBackgroundsAtlas.image,e.RGBA),this.imageBackgroundsAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new b(t,this.glyphAtlasImage,e.ALPHA),this.glyphAtlasImage=null);}prepare(t){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(t,this.imageAtlasTexture),this.imageBackgroundsAtlas&&this.imageBackgroundsAtlas.patchUpdatedImages(t,this.imageBackgroundsAtlasTexture);}queryRenderedFeatures(t,e,i,a,s,o,r,n,l,h){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:a,cameraQueryGeometry:s,scale:o,tileSize:this.tileSize,pixelPosMatrix:h,transform:n,params:r,queryPadding:this.queryPadding*l},t,e,i):{}}querySourceFeatures(t,i){const a=this.latestFeatureIndex;if(!a||!a.rawTileData)return;const s=a.loadVTLayers(),o=i&&i.sourceLayer?i.sourceLayer:"",r=s._geojsonTileLayer||s[o];if(!r)return;const n=e.a7(i&&i.filter),{z:l,x:h,y:c}=this.tileID.canonical,u={z:l,x:h,y:c};for(let i=0;it)e=!1;else if(i)if(this.expirationTime{this.remove(t,s);}),i)),this.data[a].push(s),this.order.push(a),this.order.length>this.max){const t=this._getAndRemoveByKey(this.order[0]);t&&this.onRemove(t);}return this}has(t){return t.wrapped().key in this.data}getAndRemove(t){return this.has(t)?this._getAndRemoveByKey(t.wrapped().key):null}_getAndRemoveByKey(t){const e=this.data[t].shift();return e.timeout&&clearTimeout(e.timeout),0===this.data[t].length&&delete this.data[t],this.order.splice(this.order.indexOf(t),1),e.value}getByKey(t){const e=this.data[t];return e?e[0].value:null}get(t){return this.has(t)?this.data[t.wrapped().key][0].value:null}remove(t,e){if(!this.has(t))return this;const i=t.wrapped().key,a=void 0===e?0:this.data[i].indexOf(e),s=this.data[i][a];return this.data[i].splice(a,1),s.timeout&&clearTimeout(s.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(s.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(t){for(this.max=t;this.order.length>this.max;){const t=this._getAndRemoveByKey(this.order[0]);t&&this.onRemove(t);}return this}filter(t){const e=[];for(const i in this.data)for(const a of this.data[i])t(a.value)||e.push(a);for(const t of e)this.remove(t.value.tileID,t);}}class ct{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(t,i,a){const s=String(i);if(this.stateChanges[t]=this.stateChanges[t]||{},this.stateChanges[t][s]=this.stateChanges[t][s]||{},e.e(this.stateChanges[t][s],a),null===this.deletedStates[t]){this.deletedStates[t]={};for(const e in this.state[t])e!==s&&(this.deletedStates[t][e]=null);}else if(this.deletedStates[t]&&null===this.deletedStates[t][s]){this.deletedStates[t][s]={};for(const e in this.state[t][s])a[e]||(this.deletedStates[t][s][e]=null);}else for(const e in a)this.deletedStates[t]&&this.deletedStates[t][s]&&null===this.deletedStates[t][s][e]&&delete this.deletedStates[t][s][e];}removeFeatureState(t,e,i){if(null===this.deletedStates[t])return;const a=String(e);if(this.deletedStates[t]=this.deletedStates[t]||{},i&&void 0!==e)null!==this.deletedStates[t][a]&&(this.deletedStates[t][a]=this.deletedStates[t][a]||{},this.deletedStates[t][a][i]=null);else if(void 0!==e)if(this.stateChanges[t]&&this.stateChanges[t][a])for(i in this.deletedStates[t][a]={},this.stateChanges[t][a])this.deletedStates[t][a][i]=null;else this.deletedStates[t][a]=null;else this.deletedStates[t]=null;}getState(t,i){const a=String(i),s=e.e({},(this.state[t]||{})[a],(this.stateChanges[t]||{})[a]);if(null===this.deletedStates[t])return {};if(this.deletedStates[t]){const e=this.deletedStates[t][i];if(null===e)return {};for(const t in e)delete s[t];}return s}initializeTileState(t,e){t.setFeatureState(this.state,e);}coalesceChanges(t,i){const a={};for(const t in this.stateChanges){this.state[t]=this.state[t]||{};const i={};for(const a in this.stateChanges[t])this.state[t][a]||(this.state[t][a]={}),e.e(this.state[t][a],this.stateChanges[t][a]),i[a]=this.state[t][a];a[t]=i;}for(const t in this.deletedStates){this.state[t]=this.state[t]||{};const i={};if(null===this.deletedStates[t])for(const e in this.state[t])i[e]={},this.state[t][e]={};else for(const e in this.deletedStates[t]){if(null===this.deletedStates[t][e])this.state[t][e]={};else for(const i of Object.keys(this.deletedStates[t][e]))delete this.state[t][e][i];i[e]=this.state[t][e];}a[t]=a[t]||{},e.e(a[t],i);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(a).length)for(const e in t)t[e].setFeatureState(a,i);}}class ut extends e.E{constructor(t,e,i){super(),this.id=t,this.dispatcher=i,this.on("data",(t=>this._dataHandler(t))),this.on("dataloading",(()=>{this._sourceErrored=!1;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((t,e,i,a)=>{const s=new(at(e.type))(t,e,i,a);if(s.id!==t)throw new Error(`Expected Source id to be ${t} instead of ${s.id}`);return s})(t,e,i,this),this._tiles={},this._cache=new ht(0,(t=>this._unloadTile(t))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new ct,this._didEmitContent=!1,this._updated=!1;}onAdd(t){this.map=t,this._maxTileCacheSize=t?t._maxTileCacheSize:null,this._maxTileCacheZoomLevels=t?t._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(t);}onRemove(t){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(t);}loaded(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return !0;if(!this._updated)return !1;for(const t in this._tiles){const e=this._tiles[t];if("loaded"!==e.state&&"errored"!==e.state)return !1}return !0}getSource(){return this._source}pause(){this._paused=!0;}resume(){if(!this._paused)return;const t=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,t&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(t,i,a){return e._(this,void 0,void 0,(function*(){try{yield this._source.loadTile(t),this._tileLoaded(t,i,a);}catch(i){t.state="errored",404!==i.status?this._source.fire(new e.j(i,{tile:t})):this.update(this.transform,this.terrain);}}))}_unloadTile(t){this._source.unloadTile&&this._source.unloadTile(t);}_abortTile(t){this._source.abortTile&&this._source.abortTile(t),this._source.fire(new e.k("dataabort",{tile:t,coord:t.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(t){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const e in this._tiles){const i=this._tiles[e];i.upload(t),i.prepare(this.map.style.imageManager);}}getIds(){return Object.values(this._tiles).map((t=>t.tileID)).sort(dt).map((t=>t.key))}getRenderableIds(t){const i=[];for(const e in this._tiles)this._isIdRenderable(e,t)&&i.push(this._tiles[e]);return t?i.sort(((t,i)=>{const a=t.tileID,s=i.tileID,o=new e.P(a.canonical.x,a.canonical.y)._rotate(this.transform.angle),r=new e.P(s.canonical.x,s.canonical.y)._rotate(this.transform.angle);return a.overscaledZ-s.overscaledZ||r.y-o.y||r.x-o.x})).map((t=>t.tileID.key)):i.map((t=>t.tileID)).sort(dt).map((t=>t.key))}hasRenderableParent(t){const e=this.findLoadedParent(t,0);return !!e&&this._isIdRenderable(e.tileID.key)}_isIdRenderable(t,e){return this._tiles[t]&&this._tiles[t].hasData()&&!this._coveredTiles[t]&&(e||!this._tiles[t].holdingForFade())}reload(){if(this._paused)this._shouldReloadOnResume=!0;else {this._cache.reset();for(const t in this._tiles)"errored"!==this._tiles[t].state&&this._reloadTile(t,"reloading");}}_reloadTile(t,i){return e._(this,void 0,void 0,(function*(){const e=this._tiles[t];e&&("loading"!==e.state&&(e.state=i),yield this._loadTile(e,t,i));}))}_tileLoaded(t,i,a){t.timeAdded=o.now(),"expired"===a&&(t.refreshedUponExpiration=!0),this._setTileReloadTimer(i,t),"raster-dem"===this.getSource().type&&t.dem&&this._backfillDEM(t),this._state.initializeTileState(t,this.map?this.map.painter:null),t.aborted||this._source.fire(new e.k("data",{dataType:"source",tile:t,coord:t.tileID}));}_backfillDEM(t){const e=this.getRenderableIds();for(let a=0;a1||(Math.abs(i)>1&&(1===Math.abs(i+s)?i+=s:1===Math.abs(i-s)&&(i-=s)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,i,a),t.neighboringTiles&&t.neighboringTiles[o]&&(t.neighboringTiles[o].backfilled=!0)));}}getTile(t){return this.getTileByID(t.key)}getTileByID(t){return this._tiles[t]}_retainLoadedChildren(t,e,i,a){for(const s in this._tiles){let o=this._tiles[s];if(a[s]||!o.hasData()||o.tileID.overscaledZ<=e||o.tileID.overscaledZ>i)continue;let r=o.tileID;for(;o&&o.tileID.overscaledZ>e+1;){const t=o.tileID.scaledTo(o.tileID.overscaledZ-1);o=this._tiles[t.key],o&&o.hasData()&&(r=t);}let n=r;for(;n.overscaledZ>e;)if(n=n.scaledTo(n.overscaledZ-1),t[n.key]){a[r.key]=r;break}}}findLoadedParent(t,e){if(t.key in this._loadedParentTiles){const i=this._loadedParentTiles[t.key];return i&&i.tileID.overscaledZ>=e?i:null}for(let i=t.overscaledZ-1;i>=e;i--){const e=t.scaledTo(i),a=this._getLoadedTile(e);if(a)return a}}findLoadedSibling(t){return this._getLoadedTile(t)}_getLoadedTile(t){const e=this._tiles[t.key];return e&&e.hasData()?e:this._cache.getByKey(t.wrapped().key)}updateCacheSize(t){const i=Math.ceil(t.width/this._source.tileSize)+1,a=Math.ceil(t.height/this._source.tileSize)+1,s=Math.floor(i*a*(null===this._maxTileCacheZoomLevels?e.a.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),o="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,s):s;this._cache.setMaxSize(o);}handleWrapJump(t){const e=Math.round((t-(void 0===this._prevLng?t:this._prevLng))/360);if(this._prevLng=t,e){const t={};for(const i in this._tiles){const a=this._tiles[i];a.tileID=a.tileID.unwrapTo(a.tileID.wrap+e),t[a.tileID.key]=a;}this._tiles=t;for(const t in this._timers)clearTimeout(this._timers[t]),delete this._timers[t];for(const t in this._tiles)this._setTileReloadTimer(t,this._tiles[t]);}}_updateCoveredAndRetainedTiles(t,e,i,a,s,r){const n={},l={},h=Object.keys(t),c=o.now();for(const i of h){const a=t[i],s=this._tiles[i];if(!s||0!==s.fadeEndTime&&s.fadeEndTime<=c)continue;const o=this.findLoadedParent(a,e),r=this.findLoadedSibling(a),h=o||r||null;h&&(this._addTile(h.tileID),n[h.tileID.key]=h.tileID),l[i]=a;}this._retainLoadedChildren(l,a,i,t);for(const e in n)t[e]||(this._coveredTiles[e]=!0,t[e]=n[e]);if(r){const e={},i={};for(const t of s)this._tiles[t.key].hasData()?e[t.key]=t:i[t.key]=t;for(const a in i){const s=i[a].children(this._source.maxzoom);this._tiles[s[0].key]&&this._tiles[s[1].key]&&this._tiles[s[2].key]&&this._tiles[s[3].key]&&(e[s[0].key]=t[s[0].key]=s[0],e[s[1].key]=t[s[1].key]=s[1],e[s[2].key]=t[s[2].key]=s[2],e[s[3].key]=t[s[3].key]=s[3],delete i[a]);}for(const a in i){const s=i[a],o=this.findLoadedParent(s,this._source.minzoom),r=this.findLoadedSibling(s),n=o||r||null;if(n){e[n.tileID.key]=t[n.tileID.key]=n.tileID;for(const t in e)e[t].isChildOf(n.tileID)&&delete e[t];}}for(const t in this._tiles)e[t]||(this._coveredTiles[t]=!0);}}update(t,i){if(!this._sourceLoaded||this._paused)return;let a;this.transform=t,this.terrain=i,this.updateCacheSize(t),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?a=t.getVisibleUnwrappedCoordinates(this._source.tileID).map((t=>new e.S(t.canonical.z,t.wrap,t.canonical.z,t.canonical.x,t.canonical.y))):(a=t.coveringTiles({tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i}),this._source.hasTile&&(a=a.filter((t=>this._source.hasTile(t))))):a=[];const s=t.coveringZoomLevel(this._source),o=Math.max(s-ut.maxOverzooming,this._source.minzoom),r=Math.max(s+ut.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const t={};for(const e of a)if(e.canonical.z>this._source.minzoom){const i=e.scaledTo(e.canonical.z-1);t[i.key]=i;const a=e.scaledTo(Math.max(this._source.minzoom,Math.min(e.canonical.z,5)));t[a.key]=a;}a=a.concat(Object.values(t));}const n=0===a.length&&!this._updated&&this._didEmitContent;this._updated=!0,n&&this.fire(new e.k("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const l=this._updateRetainedTiles(a,s);_t(this._source.type)&&this._updateCoveredAndRetainedTiles(l,o,r,s,a,i);for(const t in l)this._tiles[t].clearFadeHold();const h=e.ab(this._tiles,l);for(const t of h){const e=this._tiles[t];e.hasSymbolBuckets&&!e.holdingForFade()?e.setHoldDuration(this.map._fadeDuration):e.hasSymbolBuckets&&!e.symbolFadeFinished()||this._removeTile(t);}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache();}releaseSymbolFadeTiles(){for(const t in this._tiles)this._tiles[t].holdingForFade()&&this._removeTile(t);}_updateRetainedTiles(t,e){var i;const a={},s={},o=Math.max(e-ut.maxOverzooming,this._source.minzoom),r=Math.max(e+ut.maxUnderzooming,this._source.minzoom),n={};for(const i of t){const t=this._addTile(i);a[i.key]=i,t.hasData()||ethis._source.maxzoom){const t=r.children(this._source.maxzoom)[0],e=this.getTile(t);if(e&&e.hasData()){a[t.key]=t;continue}}else {const t=r.children(this._source.maxzoom);if(a[t[0].key]&&a[t[1].key]&&a[t[2].key]&&a[t[3].key])continue}let n=t.wasRequested();for(let e=r.overscaledZ-1;e>=o;--e){const o=r.scaledTo(e);if(s[o.key])break;if(s[o.key]=!0,t=this.getTile(o),!t&&n&&(t=this._addTile(o)),t){const e=t.hasData();if((e||!(null===(i=this.map)||void 0===i?void 0:i.cancelPendingTileRequestsWhileZooming)||n)&&(a[o.key]=o),n=t.wasRequested(),e)break}}}return a}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const t in this._tiles){const e=[];let i,a=this._tiles[t].tileID;for(;a.overscaledZ>0;){if(a.key in this._loadedParentTiles){i=this._loadedParentTiles[a.key];break}e.push(a.key);const t=a.scaledTo(a.overscaledZ-1);if(i=this._getLoadedTile(t),i)break;a=t;}for(const t of e)this._loadedParentTiles[t]=i;}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const t in this._tiles){const e=this._tiles[t].tileID,i=this._getLoadedTile(e);this._loadedSiblingTiles[e.key]=i;}}_addTile(t){let i=this._tiles[t.key];if(i)return i;i=this._cache.getAndRemove(t),i&&(this._setTileReloadTimer(t.key,i),i.tileID=t,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[t.key]&&(clearTimeout(this._cacheTimers[t.key]),delete this._cacheTimers[t.key],this._setTileReloadTimer(t.key,i)));const a=i;return i||(i=new lt(t,this._source.tileSize*t.overscaleFactor()),this._loadTile(i,t.key,i.state)),i.uses++,this._tiles[t.key]=i,a||this._source.fire(new e.k("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(t,e){t in this._timers&&(clearTimeout(this._timers[t]),delete this._timers[t]);const i=e.getExpiryTimeout();i&&(this._timers[t]=setTimeout((()=>{this._reloadTile(t,"expired"),delete this._timers[t];}),i));}_removeTile(t){const e=this._tiles[t];e&&(e.uses--,delete this._tiles[t],this._timers[t]&&(clearTimeout(this._timers[t]),delete this._timers[t]),e.uses>0||(e.hasData()&&"reloading"!==e.state?this._cache.add(e.tileID,e,e.getExpiryTimeout()):(e.aborted=!0,this._abortTile(e),this._unloadTile(e))));}_dataHandler(t){const e=t.sourceDataType;"source"===t.dataType&&"metadata"===e&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===t.dataType&&"content"===e&&(this.reload(),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0);}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const t in this._tiles)this._removeTile(t);this._cache.reset();}tilesIn(t,i,a){const s=[],o=this.transform;if(!o)return s;const r=a?o.getCameraQueryGeometry(t):t,n=t.map((t=>o.pointCoordinate(t,this.terrain))),l=r.map((t=>o.pointCoordinate(t,this.terrain))),h=this.getIds();let c=1/0,u=1/0,d=-1/0,_=-1/0;for(const t of l)c=Math.min(c,t.x),u=Math.min(u,t.y),d=Math.max(d,t.x),_=Math.max(_,t.y);for(let t=0;t=0&&f[1].y+m>=0){const t=n.map((t=>r.getTilePoint(t))),e=l.map((t=>r.getTilePoint(t)));s.push({tile:a,tileID:r,queryGeometry:t,cameraQueryGeometry:e,scale:p});}}return s}getVisibleCoordinates(t){const e=this.getRenderableIds(t).map((t=>this._tiles[t].tileID));for(const t of e)t.posMatrix=this.transform.calculatePosMatrix(t.toUnwrapped());return e}hasTransition(){if(this._source.hasTransition())return !0;if(_t(this._source.type)){const t=o.now();for(const e in this._tiles)if(this._tiles[e].fadeEndTime>=t)return !0}return !1}setFeatureState(t,e,i){this._state.updateState(t=t||"_geojsonTileLayer",e,i);}removeFeatureState(t,e,i){this._state.removeFeatureState(t=t||"_geojsonTileLayer",e,i);}getFeatureState(t,e){return this._state.getState(t=t||"_geojsonTileLayer",e)}setDependencies(t,e,i){const a=this._tiles[t];a&&a.setDependencies(e,i);}reloadTilesForDependencies(t,e){for(const i in this._tiles)this._tiles[i].hasDependency(t,e)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(t,e)));}}function dt(t,e){const i=Math.abs(2*t.wrap)-+(t.wrap<0),a=Math.abs(2*e.wrap)-+(e.wrap<0);return t.overscaledZ-e.overscaledZ||a-i||e.canonical.y-t.canonical.y||e.canonical.x-t.canonical.x}function _t(t){return "raster"===t||"image"===t||"video"===t}ut.maxOverzooming=10,ut.maxUnderzooming=3;class pt{constructor(t,e){this.reset(t,e);}reset(t,e){this.points=t||[],this._distances=[0];for(let t=1;t0?(s-r)/n:0;return this.points[o].mult(1-l).add(this.points[i].mult(l))}}function mt(t,e){let i=!0;return "always"===t||"never"!==t&&"never"!==e||(i=!1),i}class ft{constructor(t,e,i){const a=this.boxCells=[],s=this.circleCells=[];this.xCellCount=Math.ceil(t/i),this.yCellCount=Math.ceil(e/i);for(let t=0;tthis.width||a<0||e>this.height)return [];const n=[];if(t<=0&&e<=0&&this.width<=i&&this.height<=a){if(s)return [{key:null,x1:t,y1:e,x2:i,y2:a}];for(let t=0;t0}hitTestCircle(t,e,i,a,s){const o=t-i,r=t+i,n=e-i,l=e+i;if(r<0||o>this.width||l<0||n>this.height)return !1;const h=[];return this._forEachCell(o,n,r,l,this._queryCellCircle,h,{hitTest:!0,overlapMode:a,circle:{x:t,y:e,radius:i},seenUids:{box:{},circle:{}}},s),h.length>0}_queryCell(t,e,i,a,s,o,r,n){const{seenUids:l,hitTest:h,overlapMode:c}=r,u=this.boxCells[s];if(null!==u){const s=this.bboxes;for(const r of u)if(!l.box[r]){l.box[r]=!0;const u=4*r,d=this.boxKeys[r];if(t<=s[u+2]&&e<=s[u+3]&&i>=s[u+0]&&a>=s[u+1]&&(!n||n(d))&&(!h||!mt(c,d.overlapMode))&&(o.push({key:d,x1:s[u],y1:s[u+1],x2:s[u+2],y2:s[u+3]}),h))return !0}}const d=this.circleCells[s];if(null!==d){const s=this.circles;for(const r of d)if(!l.circle[r]){l.circle[r]=!0;const u=3*r,d=this.circleKeys[r];if(this._circleAndRectCollide(s[u],s[u+1],s[u+2],t,e,i,a)&&(!n||n(d))&&(!h||!mt(c,d.overlapMode))){const t=s[u],e=s[u+1],i=s[u+2];if(o.push({key:d,x1:t-i,y1:e-i,x2:t+i,y2:e+i}),h)return !0}}}return !1}_queryCellCircle(t,e,i,a,s,o,r,n){const{circle:l,seenUids:h,overlapMode:c}=r,u=this.boxCells[s];if(null!==u){const t=this.bboxes;for(const e of u)if(!h.box[e]){h.box[e]=!0;const i=4*e,a=this.boxKeys[e];if(this._circleAndRectCollide(l.x,l.y,l.radius,t[i+0],t[i+1],t[i+2],t[i+3])&&(!n||n(a))&&!mt(c,a.overlapMode))return o.push(!0),!0}}const d=this.circleCells[s];if(null!==d){const t=this.circles;for(const e of d)if(!h.circle[e]){h.circle[e]=!0;const i=3*e,a=this.circleKeys[e];if(this._circlesCollide(t[i],t[i+1],t[i+2],l.x,l.y,l.radius)&&(!n||n(a))&&!mt(c,a.overlapMode))return o.push(!0),!0}}}_forEachCell(t,e,i,a,s,o,r,n){const l=this._convertToXCellCoord(t),h=this._convertToYCellCoord(e),c=this._convertToXCellCoord(i),u=this._convertToYCellCoord(a);for(let d=l;d<=c;d++)for(let l=h;l<=u;l++)if(s.call(this,t,e,i,a,this.xCellCount*l+d,o,r,n))return}_convertToXCellCoord(t){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(t*this.xScale)))}_convertToYCellCoord(t){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(t*this.yScale)))}_circlesCollide(t,e,i,a,s,o){const r=a-t,n=s-e,l=i+o;return l*l>r*r+n*n}_circleAndRectCollide(t,e,i,a,s,o,r){const n=(o-a)/2,l=Math.abs(t-(a+n));if(l>n+i)return !1;const h=(r-s)/2,c=Math.abs(e-(s+h));if(c>h+i)return !1;if(l<=n||c<=h)return !0;const u=l-n,d=c-h;return u*u+d*d<=i*i}}function gt(t,i,a,s,o){const r=e.H();return i?(e.K(r,r,[1/o,1/o,1]),a||e.ad(r,r,s.angle)):e.L(r,s.labelPlaneMatrix,t),r}function vt(t,i,a,s,o){if(i){const i=e.ae(t);return e.K(i,i,[o,o,1]),a||e.ad(i,i,-s.angle),i}return s.glCoordMatrix}function xt(t,i,a,s){let o;s?(o=[t,i,s(t,i),1],e.af(o,o,a)):(o=[t,i,0,1],kt(o,o,a));const r=o[3];return {point:new e.P(o[0]/r,o[1]/r),signedDistanceFromCamera:r,isOccluded:!1}}function yt(t,e){return .5+t/e*.5}function bt(t,e){return t.x>=-e[0]&&t.x<=e[0]&&t.y>=-e[1]&&t.y<=e[1]}function wt(t,i,a,s,o,r,n,l,h,c,u,d,_,p,m){const f=s?t.textSizeData:t.iconSizeData,g=e.ag(f,a.transform.zoom),v=[256/a.width*2+1,256/a.height*2+1],x=s?t.text.dynamicLayoutVertexArray:t.icon.dynamicLayoutVertexArray;x.clear();const y=t.lineVertexArray,b=s?t.text.placedSymbolArray:t.icon.placedSymbolArray,w=a.transform.width/a.transform.height;let T=!1;for(let s=0;sMath.abs(a.x-i.x)*s?{useVertical:!0}:(t===e.ah.vertical?i.ya.x)?{needsFlipping:!0}:null}function Et(t,i,a,s,o,r,n,l,h,c,u){const d=a/24,_=i.lineOffsetX*d,p=i.lineOffsetY*d;let m;if(i.numGlyphs>1){const e=i.glyphStartIndex+i.numGlyphs,a=i.lineStartIndex,r=i.lineStartIndex+i.lineLength,h=Tt(d,l,_,p,s,i,u,t);if(!h)return {notEnoughRoom:!0};const f=xt(h.first.point.x,h.first.point.y,n,t.getElevation).point,g=xt(h.last.point.x,h.last.point.y,n,t.getElevation).point;if(o&&!s){const t=It(i.writingMode,f,g,c);if(t)return t}m=[h.first];for(let o=i.glyphStartIndex+1;o0?n.point:function(t,e,i,a,s,o){return Pt(t,e,i,1,s,o)}(t.tileAnchorPoint,o,a,0,r,t),h=It(i.writingMode,a,l,c);if(h)return h}const a=Mt(d*l.getoffsetX(i.glyphStartIndex),_,p,s,i.segment,i.lineStartIndex,i.lineStartIndex+i.lineLength,t,u);if(!a||t.projectionCache.anyProjectionOccluded)return {notEnoughRoom:!0};m=[a];}for(const t of m)e.aj(h,t.point,t.angle);return {}}function Pt(t,e,i,a,s,o){const r=t.add(t.sub(e)._unit()),n=void 0!==s?xt(r.x,r.y,s,o.getElevation).point:St(r.x,r.y,o).point,l=i.sub(n);return i.add(l._mult(a/l.mag()))}function Ct(t,i,a){const s=i.projectionCache;if(s.projections[t])return s.projections[t];const o=new e.P(i.lineVertexArray.getx(t),i.lineVertexArray.gety(t)),r=St(o.x,o.y,i);if(r.signedDistanceFromCamera>0)return s.projections[t]=r.point,s.anyProjectionOccluded=s.anyProjectionOccluded||r.isOccluded,r.point;const n=t-a.direction;return function(t,e,i,a,s){return Pt(t,e,i,a,void 0,s)}(0===a.distanceFromAnchor?i.tileAnchorPoint:new e.P(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),o,a.previousVertex,a.absOffsetX-a.distanceFromAnchor+1,i)}function St(t,e,i){const a=t+i.translation[0],s=e+i.translation[1];let o;return !i.pitchWithMap&&i.projection.useSpecialProjectionForSymbols?(o=i.projection.projectTileCoordinates(a,s,i.unwrappedTileID,i.getElevation),o.point.x=(.5*o.point.x+.5)*i.width,o.point.y=(.5*-o.point.y+.5)*i.height):(o=xt(a,s,i.labelPlaneMatrix,i.getElevation),o.isOccluded=!1),o}function Dt(t,e,i){return t._unit()._perp()._mult(e*i)}function zt(t,i,a,s,o,r,n,l,h){if(l.projectionCache.offsets[t])return l.projectionCache.offsets[t];const c=a.add(i);if(t+h.direction=o)return l.projectionCache.offsets[t]=c,c;const u=Ct(t+h.direction,l,h),d=Dt(u.sub(a),n,h.direction),_=a.add(d),p=u.add(d);return l.projectionCache.offsets[t]=e.ak(r,c,_,p)||c,l.projectionCache.offsets[t]}function Mt(t,e,i,a,s,o,r,n,l){const h=a?t-e:t+e;let c=h>0?1:-1,u=0;a&&(c*=-1,u=Math.PI),c<0&&(u+=Math.PI);let d,_=c>0?o+s:o+s+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=St(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,x=0;const y=Math.abs(h),b=[];let w;for(;v+x<=y;){if(_+=c,_=r)return null;v+=x,g=f,m=p;const t={absOffsetX:y,direction:c,distanceFromAnchor:v,previousVertex:g};if(f=Ct(_,n,t),0===i)b.push(g),w=f.sub(g);else {let e;const a=f.sub(g);e=0===a.mag()?Dt(Ct(_+c,n,t).sub(f),i,c):Dt(a,i,c),m||(m=g.add(e)),p=zt(_,e,f,o,r,m,i,n,t),b.push(m),w=p.sub(m);}x=w.mag();}const T=w._mult((y-v)/x)._add(m||g),I=u+Math.atan2(f.y-g.y,f.x-g.x);return b.push(T),{point:T,angle:l?I:0,path:b}}const At=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function Rt(t,e){for(let i=0;i=1;t--)l.push(r.path[t]);for(let t=1;tt.signedDistanceFromCamera<=0))?[]:t.map((t=>t.point));}let m=[];if(l.length>0){const t=l[0].clone(),i=l[0].clone();for(let e=1;e=a.x&&i.x<=s.x&&t.y>=a.y&&i.y<=s.y?[l]:i.xs.x||i.ys.y?[]:e.al([l],a.x,a.y,s.x,s.y);}for(const e of m){o.reset(e,.25*i);let a=0;a=o.length<=.5*i?1:Math.ceil(o.paddedLength/u)+1;for(let e=0;ext(t.x,t.y,i,e.getElevation)))}queryRenderedSymbols(t){if(0===t.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[];let a=1/0,s=1/0,o=-1/0,r=-1/0;for(const n of t){const t=new e.P(n.x+Lt,n.y+Lt);a=Math.min(a,t.x),s=Math.min(s,t.y),o=Math.max(o,t.x),r=Math.max(r,t.y),i.push(t);}const n=this.grid.query(a,s,o,r).concat(this.ignoredGrid.query(a,s,o,r)),l={},h={};for(const t of n){const a=t.key;if(void 0===l[a.bucketInstanceId]&&(l[a.bucketInstanceId]={}),l[a.bucketInstanceId][a.featureIndex])continue;const s=[new e.P(t.x1,t.y1),new e.P(t.x2,t.y1),new e.P(t.x2,t.y2),new e.P(t.x1,t.y2)];e.am(i,s)&&(l[a.bucketInstanceId][a.featureIndex]=!0,void 0===h[a.bucketInstanceId]&&(h[a.bucketInstanceId]=[]),h[a.bucketInstanceId].push(a.featureIndex));}return h}insertCollisionBox(t,e,i,a,s,o){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:a,featureIndex:s,collisionGroupID:o,overlapMode:e},t[0],t[1],t[2],t[3]);}insertCollisionCircles(t,e,i,a,s,o){const r=i?this.ignoredGrid:this.grid,n={bucketInstanceId:a,featureIndex:s,collisionGroupID:o,overlapMode:e};for(let e=0;e=this.screenRightBoundary||athis.screenBottomBoundary}isInsideGrid(t,e,i,a){return i>=0&&t=0&&ethis.projectAndGetPerspectiveRatio(a,t.x,t.y,s,h)));I=t.some((t=>!t.isOccluded)),T=t.map((t=>t.point));}else I=!0;return {box:e.ao(T),allPointsOccluded:!I}}}function Bt(t,i,a){return i*(e.X/(t.tileSize*Math.pow(2,a-t.tileID.overscaledZ)))}class Ot{constructor(t,e,i,a){this.opacity=t?Math.max(0,Math.min(1,t.opacity+(t.placed?e:-e))):a&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class Nt{constructor(t,e,i,a,s){this.text=new Ot(t?t.text:null,e,i,s),this.icon=new Ot(t?t.icon:null,e,a,s);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ut{constructor(t,e,i){this.text=t,this.icon=e,this.skipFade=i;}}class jt{constructor(){this.invProjMatrix=e.H(),this.viewportMatrix=e.H(),this.circles=[];}}class Zt{constructor(t,e,i,a,s){this.bucketInstanceId=t,this.featureIndex=e,this.sourceLayerIndex=i,this.bucketIndex=a,this.tileID=s;}}class Gt{constructor(t){this.crossSourceCollisions=t,this.maxGroupID=0,this.collisionGroups={};}get(t){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[t]){const e=++this.maxGroupID;this.collisionGroups[t]={ID:e,predicate:t=>t.collisionGroupID===e};}return this.collisionGroups[t]}}function qt(t,i,a,s,o){const{horizontalAlign:r,verticalAlign:n}=e.au(t);return new e.P(-(r-.5)*i+s[0]*o,-(n-.5)*a+s[1]*o)}class Vt{constructor(t,e,i,a,s,o){this.transform=t.clone(),this.terrain=i,this.collisionIndex=new Ft(this.transform,e),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=a,this.retainedQueryData={},this.collisionGroups=new Gt(s),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=o,o&&(o.prevPlacement=void 0),this.placedOrientations={};}_getTerrainElevationFunc(t){const e=this.terrain;return e?(i,a)=>e.getElevation(t,i,a):null}getBucketParts(t,i,a,s){const o=a.getBucket(i),r=a.latestFeatureIndex;if(!o||!r||i.id!==o.layerIds[0])return;const n=a.collisionBoxArray,l=o.layers[0].layout,h=o.layers[0].paint,c=Math.pow(2,this.transform.zoom-a.tileID.overscaledZ),u=a.tileSize/e.X,d=a.tileID.toUnwrapped(),_=this.transform.calculatePosMatrix(d),p="map"===l.get("text-pitch-alignment"),m="map"===l.get("text-rotation-alignment"),f=Bt(a,1,this.transform.zoom),g=this.collisionIndex.mapProjection.translatePosition(this.transform,a,h.get("text-translate"),h.get("text-translate-anchor")),v=this.collisionIndex.mapProjection.translatePosition(this.transform,a,h.get("icon-translate"),h.get("icon-translate-anchor")),x=gt(_,p,m,this.transform,f);let y=null;if(p){const t=vt(_,p,m,this.transform,f);y=e.L([],this.transform.labelPlaneMatrix,t);}this.retainedQueryData[o.bucketInstanceId]=new Zt(o.bucketInstanceId,r,o.sourceLayerIndex,o.index,a.tileID);const b={bucket:o,layout:l,translationText:g,translationIcon:v,posMatrix:_,unwrappedTileID:d,textLabelPlaneMatrix:x,labelToScreenMatrix:y,scale:c,textPixelRatio:u,holdingForFade:a.holdingForFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:e.ag(o.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(o.sourceID)};if(s)for(const e of o.sortKeyRanges){const{sortKey:i,symbolInstanceStart:a,symbolInstanceEnd:s}=e;t.push({sortKey:i,symbolInstanceStart:a,symbolInstanceEnd:s,parameters:b});}else t.push({symbolInstanceStart:0,symbolInstanceEnd:o.symbolInstances.length,parameters:b});}attemptAnchorPlacement(t,i,a,s,o,r,n,l,h,c,u,d,_,p,m,f,g,v,x){const y=e.aq[t.textAnchor],b=[t.textOffset0,t.textOffset1],w=qt(y,a,s,b,o),T=this.collisionIndex.placeCollisionBox(i,d,l,h,c,n,r,f,u.predicate,x,w);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,h,c,n,r,g,u.predicate,x,w).placeable)&&T.placeable){let t;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(t=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:b,width:a,height:s,anchor:y,textBoxScale:o,prevAnchor:t},this.markUsedJustification(p,y,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:w,placedGlyphBoxes:T}}}placeLayerBucketPart(t,i,a){const{bucket:s,layout:o,translationText:r,translationIcon:n,posMatrix:l,unwrappedTileID:h,textLabelPlaneMatrix:c,labelToScreenMatrix:u,textPixelRatio:d,holdingForFade:_,collisionBoxArray:p,partiallyEvaluatedTextSize:m,collisionGroup:f}=t.parameters,g=o.get("text-optional"),v=o.get("icon-optional"),x=e.ar(o,"text-overlap","text-allow-overlap"),y="always"===x,b=e.ar(o,"icon-overlap","icon-allow-overlap"),w="always"===b,T="map"===o.get("text-rotation-alignment"),I="map"===o.get("text-pitch-alignment"),E="none"!==o.get("icon-text-fit"),P="viewport-y"===o.get("symbol-z-order"),C=y&&(w||!s.hasIconData()||v),S=w&&(y||!s.hasTextData()||g);!s.collisionArrays&&p&&s.deserializeCollisionBoxes(p);const D=this._getTerrainElevationFunc(this.retainedQueryData[s.bucketInstanceId].tileID),z=(t,p,w)=>{var P,z;if(i[t.crossTileID])return;if(_)return void(this.placements[t.crossTileID]=new Ut(!1,!1,!1));let M=!1,A=!1,R=!0,k=null,L={box:null,placeable:!1,offscreen:null},F={box:null,placeable:!1,offscreen:null},B=null,O=null,N=null,U=0,j=0,Z=0;p.textFeatureIndex?U=p.textFeatureIndex:t.useRuntimeCollisionCircles&&(U=t.featureIndex),p.verticalTextFeatureIndex&&(j=p.verticalTextFeatureIndex);const G=p.textBox;if(G){const i=i=>{let a=e.ah.horizontal;if(s.allowVerticalPlacement&&!i&&this.prevPlacement){const e=this.prevPlacement.placedOrientations[t.crossTileID];e&&(this.placedOrientations[t.crossTileID]=e,a=e,this.markUsedOrientation(s,a,t));}return a},o=(i,a)=>{if(s.allowVerticalPlacement&&t.numVerticalGlyphVertices>0&&p.verticalTextBox){for(const t of s.writingModes)if(t===e.ah.vertical?(L=a(),F=L):L=i(),L&&L.placeable)break}else L=i();},c=t.textAnchorOffsetStartIndex,u=t.textAnchorOffsetEndIndex;if(u===c){const a=(e,i)=>{const a=this.collisionIndex.placeCollisionBox(e,x,d,l,h,I,T,r,f.predicate,D);return a&&a.placeable&&(this.markUsedOrientation(s,i,t),this.placedOrientations[t.crossTileID]=i),a};o((()=>a(G,e.ah.horizontal)),(()=>{const i=p.verticalTextBox;return s.allowVerticalPlacement&&t.numVerticalGlyphVertices>0&&i?a(i,e.ah.vertical):{box:null,offscreen:null}})),i(L&&L.placeable);}else {let _=e.aq[null===(z=null===(P=this.prevPlacement)||void 0===P?void 0:P.variableOffsets[t.crossTileID])||void 0===z?void 0:z.anchor];const m=(i,o,p)=>{const m=i.x2-i.x1,g=i.y2-i.y1,v=t.textBoxScale,y=E&&"never"===b?o:null;let w=null,P="never"===x?1:2,C="never";_&&P++;for(let e=0;em(G,p.iconBox,e.ah.horizontal)),(()=>{const i=p.verticalTextBox;return s.allowVerticalPlacement&&(!L||!L.placeable)&&t.numVerticalGlyphVertices>0&&i?m(i,p.verticalIconBox,e.ah.vertical):{box:null,occluded:!0,offscreen:null}})),L&&(M=L.placeable,R=L.offscreen);const g=i(L&&L.placeable);if(!M&&this.prevPlacement){const e=this.prevPlacement.variableOffsets[t.crossTileID];e&&(this.variableOffsets[t.crossTileID]=e,this.markUsedJustification(s,e.anchor,t,g));}}}if(B=L,M=B&&B.placeable,R=B&&B.offscreen,t.useRuntimeCollisionCircles){const i=s.text.placedSymbolArray.get(t.centerJustifiedTextSymbolIndex),n=e.ai(s.textSizeData,m,i),d=o.get("text-padding");O=this.collisionIndex.placeCollisionCircles(x,i,s.lineVertexArray,s.glyphOffsetArray,n,l,h,c,u,a,I,f.predicate,t.collisionCircleDiameter,d,r,D),O.circles.length&&O.collisionDetected&&!a&&e.w("Collisions detected, but collision boxes are not shown"),M=y||O.circles.length>0&&!O.collisionDetected,R=R&&O.offscreen;}if(p.iconFeatureIndex&&(Z=p.iconFeatureIndex),p.iconBox){const t=t=>this.collisionIndex.placeCollisionBox(t,b,d,l,h,I,T,n,f.predicate,D,E&&k?k:void 0);F&&F.placeable&&p.verticalIconBox?(N=t(p.verticalIconBox),A=N.placeable):(N=t(p.iconBox),A=N.placeable),R=R&&N.offscreen;}const q=g||0===t.numHorizontalGlyphVertices&&0===t.numVerticalGlyphVertices,V=v||0===t.numIconVertices;q||V?V?q||(A=A&&M):M=A&&M:A=M=A&&M;const H=A&&N.placeable;if(M&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,x,o.get("text-ignore-placement"),s.bucketInstanceId,F&&F.placeable&&j?j:U,f.ID),H&&this.collisionIndex.insertCollisionBox(N.box,b,o.get("icon-ignore-placement"),s.bucketInstanceId,Z,f.ID),O&&M&&this.collisionIndex.insertCollisionCircles(O.circles,x,o.get("text-ignore-placement"),s.bucketInstanceId,U,f.ID),a&&this.storeCollisionData(s.bucketInstanceId,w,p,B,N,O),0===t.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===s.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[t.crossTileID]=new Ut(M||C,A||S,R||s.justReloaded),i[t.crossTileID]=!0;};if(P){if(0!==t.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const e=s.getSortedSymbolIndexes(this.transform.angle);for(let t=e.length-1;t>=0;--t){const i=e[t];z(s.symbolInstances.get(i),s.collisionArrays[i],i);}}else for(let e=t.symbolInstanceStart;e=0&&(t.text.placedSymbolArray.get(e).crossTileID=o>=0&&e!==o?0:a.crossTileID);}markUsedOrientation(t,i,a){const s=i===e.ah.horizontal||i===e.ah.horizontalOnly?i:0,o=i===e.ah.vertical?i:0,r=[a.leftJustifiedTextSymbolIndex,a.centerJustifiedTextSymbolIndex,a.rightJustifiedTextSymbolIndex];for(const e of r)t.text.placedSymbolArray.get(e).placedOrientation=s;a.verticalPlacedTextSymbolIndex&&(t.text.placedSymbolArray.get(a.verticalPlacedTextSymbolIndex).placedOrientation=o);}commit(t){this.commitTime=t,this.zoomAtLastRecencyCheck=this.transform.zoom;const e=this.prevPlacement;let i=!1;this.prevZoomAdjustment=e?e.zoomAdjustment(this.transform.zoom):0;const a=e?e.symbolFadeChange(t):1,s=e?e.opacities:{},o=e?e.variableOffsets:{},r=e?e.placedOrientations:{};for(const t in this.placements){const e=this.placements[t],o=s[t];o?(this.opacities[t]=new Nt(o,a,e.text,e.icon),i=i||e.text!==o.text.placed||e.icon!==o.icon.placed):(this.opacities[t]=new Nt(null,a,e.text,e.icon,e.skipFade),i=i||e.text||e.icon);}for(const t in s){const e=s[t];if(!this.opacities[t]){const s=new Nt(e,a,!1,!1);s.isHidden()||(this.opacities[t]=s,i=i||e.text.placed||e.icon.placed);}}for(const t in o)this.variableOffsets[t]||!this.opacities[t]||this.opacities[t].isHidden()||(this.variableOffsets[t]=o[t]);for(const t in r)this.placedOrientations[t]||!this.opacities[t]||this.opacities[t].isHidden()||(this.placedOrientations[t]=r[t]);if(e&&void 0===e.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=t:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=e?e.lastPlacementChangeTime:t);}updateLayerOpacities(t,e){const i={};for(const a of e){const e=a.getBucket(t);e&&a.latestFeatureIndex&&t.id===e.layerIds[0]&&this.updateBucketOpacities(e,a.tileID,i,a.collisionBoxArray);}}updateBucketOpacities(t,i,a,s){t.hasTextData()&&(t.text.opacityVertexArray.clear(),t.text.hasVisibleVertices=!1),t.hasIconData()&&(t.icon.opacityVertexArray.clear(),t.icon.hasVisibleVertices=!1),t.hasIconCollisionBoxData()&&t.iconCollisionBox.collisionVertexArray.clear(),t.hasTextCollisionBoxData()&&t.textCollisionBox.collisionVertexArray.clear();const o=t.layers[0],r=o.layout,n=new Nt(null,0,!1,!1,!0),l=r.get("text-allow-overlap"),h=r.get("icon-allow-overlap"),c=o._unevaluatedLayout.hasValue("text-variable-anchor")||o._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===r.get("text-rotation-alignment"),d="map"===r.get("text-pitch-alignment"),_="none"!==r.get("icon-text-fit"),p=new Nt(null,0,l&&(h||!t.hasIconData()||r.get("icon-optional")),h&&(l||!t.hasTextData()||r.get("text-optional")),!0);!t.collisionArrays&&s&&(t.hasIconCollisionBoxData()||t.hasTextCollisionBoxData())&&t.deserializeCollisionBoxes(s);const m=(t,e,i)=>{for(let a=0;a0,v=this.placedOrientations[s.crossTileID],x=v===e.ah.vertical,y=v===e.ah.horizontal||v===e.ah.horizontalOnly;if(o>0||r>0){const e=te(h.text);m(t.text,o,x?ee:e),m(t.text,r,y?ee:e);const i=h.text.isHidden();[s.rightJustifiedTextSymbolIndex,s.centerJustifiedTextSymbolIndex,s.leftJustifiedTextSymbolIndex].forEach((e=>{e>=0&&(t.text.placedSymbolArray.get(e).hidden=i||x?1:0);})),s.verticalPlacedTextSymbolIndex>=0&&(t.text.placedSymbolArray.get(s.verticalPlacedTextSymbolIndex).hidden=i||y?1:0);const a=this.variableOffsets[s.crossTileID];a&&this.markUsedJustification(t,a.anchor,s,v);const n=this.placedOrientations[s.crossTileID];n&&(this.markUsedJustification(t,"left",s,n),this.markUsedOrientation(t,n,s));}if(g){const e=te(h.icon),i=!(_&&s.verticalPlacedIconSymbolIndex&&x);s.placedIconSymbolIndex>=0&&(m(t.icon,s.numIconVertices,i?e:ee),t.icon.placedSymbolArray.get(s.placedIconSymbolIndex).hidden=h.icon.isHidden()),s.verticalPlacedIconSymbolIndex>=0&&(m(t.icon,s.numVerticalIconVertices,i?ee:e),t.icon.placedSymbolArray.get(s.verticalPlacedIconSymbolIndex).hidden=h.icon.isHidden());}const b=f&&f.has(i)?f.get(i):{text:null,icon:null};if(t.hasIconCollisionBoxData()||t.hasTextCollisionBoxData()){const a=t.collisionArrays[i];if(a){let i=new e.P(0,0);if(a.textBox||a.verticalTextBox){let e=!0;if(c){const t=this.variableOffsets[l];t?(i=qt(t.anchor,t.width,t.height,t.textOffset,t.textBoxScale),u&&i._rotate(d?this.transform.angle:-this.transform.angle)):e=!1;}if(a.textBox||a.verticalTextBox){let s;a.textBox&&(s=x),a.verticalTextBox&&(s=y),Ht(t.textCollisionBox.collisionVertexArray,h.text.placed,!e||s,b.text,i.x,i.y);}}if(a.iconBox||a.verticalIconBox){const e=Boolean(!y&&a.verticalIconBox);let s;a.iconBox&&(s=e),a.verticalIconBox&&(s=!e),Ht(t.iconCollisionBox.collisionVertexArray,h.icon.placed,s,b.icon,_?i.x:0,_?i.y:0);}}}}if(t.sortFeatures(this.transform.angle),this.retainedQueryData[t.bucketInstanceId]&&(this.retainedQueryData[t.bucketInstanceId].featureSortOrder=t.featureSortOrder),t.hasTextData()&&t.text.opacityVertexBuffer&&t.text.opacityVertexBuffer.updateData(t.text.opacityVertexArray),t.hasIconData()&&t.icon.opacityVertexBuffer&&t.icon.opacityVertexBuffer.updateData(t.icon.opacityVertexArray),t.hasIconCollisionBoxData()&&t.iconCollisionBox.collisionVertexBuffer&&t.iconCollisionBox.collisionVertexBuffer.updateData(t.iconCollisionBox.collisionVertexArray),t.hasTextCollisionBoxData()&&t.textCollisionBox.collisionVertexBuffer&&t.textCollisionBox.collisionVertexBuffer.updateData(t.textCollisionBox.collisionVertexArray),t.text.opacityVertexArray.length!==t.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${t.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${t.text.layoutVertexArray.length}) / 4`);if(t.icon.opacityVertexArray.length!==t.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${t.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${t.icon.layoutVertexArray.length}) / 4`);if(t.bucketInstanceId in this.collisionCircleArrays){const e=this.collisionCircleArrays[t.bucketInstanceId];t.placementInvProjMatrix=e.invProjMatrix,t.placementViewportMatrix=e.viewportMatrix,t.collisionCircleArray=e.circles,delete this.collisionCircleArrays[t.bucketInstanceId];}}symbolFadeChange(t){return 0===this.fadeDuration?1:(t-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(t){return Math.max(0,(this.transform.zoom-t)/1.5)}hasTransitions(t){return this.stale||t-this.lastPlacementChangeTimet}setStale(){this.stale=!0;}}function Ht(t,e,i,a,s,o){a&&0!==a.length||(a=[0,0,0,0]);const r=a[0]-Lt,n=a[1]-Lt,l=a[2]-Lt,h=a[3]-Lt;t.emplaceBack(e?1:0,i?1:0,s||0,o||0,r,n),t.emplaceBack(e?1:0,i?1:0,s||0,o||0,l,n),t.emplaceBack(e?1:0,i?1:0,s||0,o||0,l,h),t.emplaceBack(e?1:0,i?1:0,s||0,o||0,r,h);}const Wt=Math.pow(2,25),$t=Math.pow(2,24),Xt=Math.pow(2,17),Kt=Math.pow(2,16),Jt=Math.pow(2,9),Yt=Math.pow(2,8),Qt=Math.pow(2,1);function te(t){if(0===t.opacity&&!t.placed)return 0;if(1===t.opacity&&t.placed)return 4294967295;const e=t.placed?1:0,i=Math.floor(127*t.opacity);return i*Wt+e*$t+i*Xt+e*Kt+i*Jt+e*Yt+i*Qt+e}const ee=0;function ie(){return {isOccluded:(t,e,i)=>!1,getPitchedTextCorrection:(t,e,i)=>1,get useSpecialProjectionForSymbols(){return !1},projectTileCoordinates(t,e,i,a){throw new Error("Not implemented.")},translatePosition:(t,e,i,a)=>function(t,e,i,a,s=!1){if(!i[0]&&!i[1])return [0,0];const o=s?"map"===a?t.angle:0:"viewport"===a?-t.angle:0;if(o){const t=Math.sin(o),e=Math.cos(o);i=[i[0]*e-i[1]*t,i[0]*t+i[1]*e];}return [s?i[0]:Bt(e,i[0],t.zoom),s?i[1]:Bt(e,i[1],t.zoom)]}(t,e,i,a),getCircleRadiusCorrection:t=>1}}class ae{constructor(t){this._sortAcrossTiles="viewport-y"!==t.layout.get("symbol-z-order")&&!t.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(t,e,i,a,s){const o=this._bucketParts;for(;this._currentTileIndext.sortKey-e.sortKey)));this._currentPartIndex!this._forceFullPlacement&&o.now()-a>2;for(;this._currentPlacementIndex>=0;){const a=e[t[this._currentPlacementIndex]],o=this.placement.collisionIndex.transform.zoom;if("symbol"===a.type&&(!a.minzoom||a.minzoom<=o)&&(!a.maxzoom||a.maxzoom>o)){if(this._inProgressLayer||(this._inProgressLayer=new ae(a)),this._inProgressLayer.continuePlacement(i[a.source],this.placement,this._showCollisionBoxes,a,s))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;}commit(t){return this.placement.commit(t),this.placement}}const oe=512/e.X/2;class re{constructor(t,i,a){this.tileID=t,this.bucketInstanceId=a,this._symbolsByKey={};const s=new Map;for(let t=0;t({x:Math.floor(t.anchorX*oe),y:Math.floor(t.anchorY*oe)}))),crossTileIDs:i.map((t=>t.crossTileID))};if(a.positions.length>128){const t=new e.av(a.positions.length,16,Uint16Array);for(const{x:e,y:i}of a.positions)t.add(e,i);t.finish(),delete a.positions,a.index=t;}this._symbolsByKey[t]=a;}}getScaledCoordinates(t,i){const{x:a,y:s,z:o}=this.tileID.canonical,{x:r,y:n,z:l}=i.canonical,h=oe/Math.pow(2,l-o),c=(n*e.X+t.anchorY)*h,u=s*e.X*oe;return {x:Math.floor((r*e.X+t.anchorX)*h-a*e.X*oe),y:Math.floor(c-u)}}findMatches(t,e,i){const a=this.tileID.canonical.zt))}}class ne{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class le{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(t){const e=Math.round((t-this.lng)/360);if(0!==e)for(const t in this.indexes){const i=this.indexes[t],a={};for(const t in i){const s=i[t];s.tileID=s.tileID.unwrapTo(s.tileID.wrap+e),a[s.tileID.key]=s;}this.indexes[t]=a;}this.lng=t;}addBucket(t,e,i){if(this.indexes[t.overscaledZ]&&this.indexes[t.overscaledZ][t.key]){if(this.indexes[t.overscaledZ][t.key].bucketInstanceId===e.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(t.overscaledZ,this.indexes[t.overscaledZ][t.key]);}for(let t=0;tt.overscaledZ)for(const i in s){const o=s[i];o.tileID.isChildOf(t)&&o.findMatches(e.symbolInstances,t,a);}else {const o=s[t.scaledTo(Number(i)).key];o&&o.findMatches(e.symbolInstances,t,a);}}for(let t=0;t{e[t]=!0;}));for(const t in this.layerIndexes)e[t]||delete this.layerIndexes[t];}}const ce=(t,i)=>e.t(t,i&&i.filter((t=>"source.canvas"!==t.identifier))),ue=e.aw();class de extends e.E{constructor(t,i={}){super(),this._rtlPluginLoaded=()=>{for(const t in this.sourceCaches){const e=this.sourceCaches[t].getSource().type;"vector"!==e&&"geojson"!==e||this.sourceCaches[t].reload();}},this.map=t,this.dispatcher=new U(N(),t._getMapId()),this.dispatcher.registerMessageHandler("GG",((t,e)=>this.getGlyphs(t,e))),this.dispatcher.registerMessageHandler("GI",((t,e)=>this.getImages(t,e))),this.imageManager=new T,this.imageManager.setEventedParent(this),this.glyphManager=new C(t._requestManager,i.localIdeographFontFamily),this.lineAtlas=new R(256,512),this.crossTileSymbolIndex=new he,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new e.ax,this._loaded=!1,this._availableImages=[],this._resetUpdates(),this.dispatcher.broadcast("SR",e.ay()),nt().on(st,this._rtlPluginLoaded),this.on("data",(t=>{if("source"!==t.dataType||"metadata"!==t.sourceDataType)return;const e=this.sourceCaches[t.sourceId];if(!e)return;const i=e.getSource();if(i&&i.vectorLayerIds)for(const t in this._layers){const e=this._layers[t];e.source===i.id&&this._validateLayer(e);}}));}loadURL(t,i={},a){this.fire(new e.k("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate;const s=this.map._requestManager.transformRequest(t,"Style");this._loadStyleRequest=new AbortController;const o=this._loadStyleRequest;e.h(s,this._loadStyleRequest).then((t=>{this._loadStyleRequest=null,this._load(t.data,i,a);})).catch((t=>{this._loadStyleRequest=null,t&&!o.signal.aborted&&this.fire(new e.j(t));}));}loadJSON(t,i={},a){this.fire(new e.k("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,o.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,i.validate=!1!==i.validate,this._load(t,i,a);})).catch((()=>{}));}loadEmpty(){this.fire(new e.k("dataloading",{dataType:"style"})),this._load(ue,{validate:!1});}_load(t,i,a){var s;const o=i.transformStyle?i.transformStyle(a,t):t;if(!i.validate||!ce(this,e.u(o))){this._loaded=!0,this.stylesheet=o;for(const t in o.sources)this.addSource(t,o.sources[t],{validate:!1});o.sprite?this._loadSprite(o.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(o.glyphs),this._createLayers(),this.light=new z(this.stylesheet.light),this.sky=new A(this.stylesheet.sky),this.map.setTerrain(null!==(s=this.stylesheet.terrain)&&void 0!==s?s:null),this.fire(new e.k("data",{dataType:"style"})),this.fire(new e.k("style.load"));}}_createLayers(){const t=e.az(this.stylesheet.layers);this.dispatcher.broadcast("SL",t),this._order=t.map((t=>t.id)),this._layers={},this._serializedLayers=null;for(const i of t){const t=e.aA(i);t.setEventedParent(this,{layer:{id:i.id}}),this._layers[i.id]=t;}}_loadSprite(t,i=!1,a=void 0){let s;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(t,i,a,s){return e._(this,void 0,void 0,(function*(){const r=x(t),n=a>1?"@2x":"",l={},h={};for(const{id:t,url:a}of r){const o=i.transformRequest(y(a,n,".json"),"SpriteJSON");l[t]=e.h(o,s);const r=i.transformRequest(y(a,n,".png"),"SpriteImage");h[t]=_.getImage(r,s);}return yield Promise.all([...Object.values(l),...Object.values(h)]),function(t,i){return e._(this,void 0,void 0,(function*(){const e={};for(const a in t){e[a]={};const s=o.getImageCanvasContext((yield i[a]).data),r=(yield t[a]).data;for(const t in r){const{width:i,height:o,x:n,y:l,sdf:h,pixelRatio:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=r[t];e[a][t]={data:null,pixelRatio:c,sdf:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:o,x:n,y:l,context:s}};}}return e}))}(l,h)}))}(t,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((t=>{if(this._spriteRequest=null,t)for(const e in t){this._spritesImagesIds[e]=[];const a=this._spritesImagesIds[e]?this._spritesImagesIds[e].filter((e=>!(e in t))):[];for(const t of a)this.imageManager.removeImage(t),this._changedImages[t]=!0;for(const a in t[e]){const s="default"===e?a:`${e}:${a}`;this._spritesImagesIds[e].push(s),s in this.imageManager.images?this.imageManager.updateImage(s,t[e][a],!1):this.imageManager.addImage(s,t[e][a]),i&&(this._changedImages[s]=!0);}}})).catch((t=>{this._spriteRequest=null,s=t,this.fire(new e.j(s));})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),i&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new e.k("data",{dataType:"style"})),a&&a(s);}));}_unloadSprite(){for(const t of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(t),this._changedImages[t]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new e.k("data",{dataType:"style"}));}_validateLayer(t){const i=this.sourceCaches[t.source];if(!i)return;const a=t.sourceLayer;if(!a)return;const s=i.getSource();("geojson"===s.type||s.vectorLayerIds&&-1===s.vectorLayerIds.indexOf(a))&&this.fire(new e.j(new Error(`Source layer "${a}" does not exist on source "${s.id}" as specified by style layer "${t.id}".`)));}loaded(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(const t in this.sourceCaches)if(!this.sourceCaches[t].loaded())return !1;return !!this.imageManager.isLoaded()}_serializeByIds(t,i=!1){const a=this._serializedAllLayers();if(!t||0===t.length)return Object.values(i?e.aB(a):a);const s=[];for(const o of t)if(a[o]){const t=i?e.aB(a[o]):a[o];s.push(t);}return s}_serializedAllLayers(){let t=this._serializedLayers;if(t)return t;t=this._serializedLayers={};const e=Object.keys(this._layers);for(const i of e){const e=this._layers[i];"custom"!==e.type&&(t[i]=e.serialize());}return t}hasTransitions(){if(this.light&&this.light.hasTransition())return !0;if(this.sky&&this.sky.hasTransition())return !0;for(const t in this.sourceCaches)if(this.sourceCaches[t].hasTransition())return !0;for(const t in this._layers)if(this._layers[t].hasTransition())return !0;return !1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(t){if(!this._loaded)return;const i=this._changed;if(i){const e=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(e.length||i.length)&&this._updateWorkerLayers(e,i);for(const t in this._updatedSources){const e=this._updatedSources[t];if("reload"===e)this._reloadSource(t);else {if("clear"!==e)throw new Error(`Invalid action ${e}`);this._clearSource(t);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const e in this._updatedPaintProps)this._layers[e].updateTransitions(t);this.light.updateTransitions(t),this.sky.updateTransitions(t),this._resetUpdates();}const a={};for(const t in this.sourceCaches){const e=this.sourceCaches[t];a[t]=e.used,e.used=!1;}for(const e of this._order){const i=this._layers[e];i.recalculate(t,this._availableImages),!i.isHidden(t.zoom)&&i.source&&(this.sourceCaches[i.source].used=!0);}for(const t in a){const i=this.sourceCaches[t];!!a[t]!=!!i.used&&i.fire(new e.k("data",{sourceDataType:"visibility",dataType:"source",sourceId:t}));}this.light.recalculate(t),this.sky.recalculate(t),this.z=t.zoom,i&&this.fire(new e.k("data",{dataType:"style"}));}_updateTilesForChangedImages(){const t=Object.keys(this._changedImages);if(t.length){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["icons","patterns"],t);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1;}}_updateWorkerLayers(t,e){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(t,!1),removedIds:e});}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1;}setState(t,i={}){var a;this._checkLoaded();const s=this.serialize();if(t=i.transformStyle?i.transformStyle(s,t):t,(null===(a=i.validate)||void 0===a||a)&&ce(this,e.u(t)))return !1;(t=e.aB(t)).layers=e.az(t.layers);const o=e.aC(s,t),r=this._getOperationsToPerform(o);if(r.unimplemented.length>0)throw new Error(`Unimplemented: ${r.unimplemented.join(", ")}.`);if(0===r.operations.length)return !1;for(const t of r.operations)t();return this.stylesheet=t,this._serializedLayers=null,!0}_getOperationsToPerform(t){const e=[],i=[];for(const a of t)switch(a.command){case"setCenter":case"setZoom":case"setBearing":case"setPitch":continue;case"addLayer":e.push((()=>this.addLayer.apply(this,a.args)));break;case"removeLayer":e.push((()=>this.removeLayer.apply(this,a.args)));break;case"setPaintProperty":e.push((()=>this.setPaintProperty.apply(this,a.args)));break;case"setLayoutProperty":e.push((()=>this.setLayoutProperty.apply(this,a.args)));break;case"setFilter":e.push((()=>this.setFilter.apply(this,a.args)));break;case"addSource":e.push((()=>this.addSource.apply(this,a.args)));break;case"removeSource":e.push((()=>this.removeSource.apply(this,a.args)));break;case"setLayerZoomRange":e.push((()=>this.setLayerZoomRange.apply(this,a.args)));break;case"setLight":e.push((()=>this.setLight.apply(this,a.args)));break;case"setGeoJSONSourceData":e.push((()=>this.setGeoJSONSourceData.apply(this,a.args)));break;case"setGlyphs":e.push((()=>this.setGlyphs.apply(this,a.args)));break;case"setSprite":e.push((()=>this.setSprite.apply(this,a.args)));break;case"setSky":e.push((()=>this.setSky.apply(this,a.args)));break;case"setTerrain":e.push((()=>this.map.setTerrain.apply(this,a.args)));break;case"setTransition":e.push((()=>{}));break;default:i.push(a.command);}return {operations:e,unimplemented:i}}addImage(t,i){if(this.getImage(t))return this.fire(new e.j(new Error(`An image named "${t}" already exists.`)));this.imageManager.addImage(t,i),this._afterImageUpdated(t);}updateImage(t,e){this.imageManager.updateImage(t,e);}getImage(t){return this.imageManager.getImage(t)}removeImage(t){if(!this.getImage(t))return this.fire(new e.j(new Error(`An image named "${t}" does not exist.`)));this.imageManager.removeImage(t),this._afterImageUpdated(t);}_afterImageUpdated(t){this._availableImages=this.imageManager.listImages(),this._changedImages[t]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new e.k("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(t,i,a={}){if(this._checkLoaded(),void 0!==this.sourceCaches[t])throw new Error(`Source "${t}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(e.u.source,`sources.${t}`,i,null,a))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);const s=this.sourceCaches[t]=new ut(t,i,this.dispatcher);s.style=this,s.setEventedParent(this,(()=>({isSourceLoaded:s.loaded(),source:s.serialize(),sourceId:t}))),s.onAdd(this.map),this._changed=!0;}removeSource(t){if(this._checkLoaded(),void 0===this.sourceCaches[t])throw new Error("There is no source with this ID");for(const i in this._layers)if(this._layers[i].source===t)return this.fire(new e.j(new Error(`Source "${t}" cannot be removed while layer "${i}" is using it.`)));const i=this.sourceCaches[t];delete this.sourceCaches[t],delete this._updatedSources[t],i.fire(new e.k("data",{sourceDataType:"metadata",dataType:"source",sourceId:t})),i.setEventedParent(null),i.onRemove(this.map),this._changed=!0;}setGeoJSONSourceData(t,e){if(this._checkLoaded(),void 0===this.sourceCaches[t])throw new Error(`There is no source with this ID=${t}`);const i=this.sourceCaches[t].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(e),this._changed=!0;}getSource(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()}addLayer(t,i,a={}){this._checkLoaded();const s=t.id;if(this.getLayer(s))return void this.fire(new e.j(new Error(`Layer "${s}" already exists on this map.`)));let o;if("custom"===t.type){if(ce(this,e.aD(t)))return;o=e.aA(t);}else {if("source"in t&&"object"==typeof t.source&&(this.addSource(s,t.source),t=e.aB(t),t=e.e(t,{source:s})),this._validate(e.u.layer,`layers.${s}`,t,{arrayIndex:-1},a))return;o=e.aA(t),this._validateLayer(o),o.setEventedParent(this,{layer:{id:s}});}const r=i?this._order.indexOf(i):this._order.length;if(i&&-1===r)this.fire(new e.j(new Error(`Cannot add layer "${s}" before non-existing layer "${i}".`)));else {if(this._order.splice(r,0,s),this._layerOrderChanged=!0,this._layers[s]=o,this._removedLayers[s]&&o.source&&"custom"!==o.type){const t=this._removedLayers[s];delete this._removedLayers[s],t.type!==o.type?this._updatedSources[o.source]="clear":(this._updatedSources[o.source]="reload",this.sourceCaches[o.source].pause());}this._updateLayer(o),o.onAdd&&o.onAdd(this.map);}}moveLayer(t,i){if(this._checkLoaded(),this._changed=!0,!this._layers[t])return void this.fire(new e.j(new Error(`The layer '${t}' does not exist in the map's style and cannot be moved.`)));if(t===i)return;const a=this._order.indexOf(t);this._order.splice(a,1);const s=i?this._order.indexOf(i):this._order.length;i&&-1===s?this.fire(new e.j(new Error(`Cannot move layer "${t}" before non-existing layer "${i}".`))):(this._order.splice(s,0,t),this._layerOrderChanged=!0);}removeLayer(t){this._checkLoaded();const i=this._layers[t];if(!i)return void this.fire(new e.j(new Error(`Cannot remove non-existing layer "${t}".`)));i.setEventedParent(null);const a=this._order.indexOf(t);this._order.splice(a,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[t]=i,delete this._layers[t],this._serializedLayers&&delete this._serializedLayers[t],delete this._updatedLayers[t],delete this._updatedPaintProps[t],i.onRemove&&i.onRemove(this.map);}getLayer(t){return this._layers[t]}getLayersOrder(){return [...this._order]}hasLayer(t){return t in this._layers}setLayerZoomRange(t,i,a){this._checkLoaded();const s=this.getLayer(t);s?s.minzoom===i&&s.maxzoom===a||(null!=i&&(s.minzoom=i),null!=a&&(s.maxzoom=a),this._updateLayer(s)):this.fire(new e.j(new Error(`Cannot set the zoom range of non-existing layer "${t}".`)));}setFilter(t,i,a={}){this._checkLoaded();const s=this.getLayer(t);if(s){if(!e.aE(s.filter,i))return null==i?(s.filter=void 0,void this._updateLayer(s)):void(this._validate(e.u.filter,`layers.${s.id}.filter`,i,null,a)||(s.filter=e.aB(i),this._updateLayer(s)))}else this.fire(new e.j(new Error(`Cannot filter non-existing layer "${t}".`)));}getFilter(t){return e.aB(this.getLayer(t).filter)}setLayoutProperty(t,i,a,s={}){this._checkLoaded();const o=this.getLayer(t);o?e.aE(o.getLayoutProperty(i),a)||(o.setLayoutProperty(i,a,s),this._updateLayer(o)):this.fire(new e.j(new Error(`Cannot style non-existing layer "${t}".`)));}getLayoutProperty(t,i){const a=this.getLayer(t);if(a)return a.getLayoutProperty(i);this.fire(new e.j(new Error(`Cannot get style of non-existing layer "${t}".`)));}setPaintProperty(t,i,a,s={}){this._checkLoaded();const o=this.getLayer(t);o?e.aE(o.getPaintProperty(i),a)||(o.setPaintProperty(i,a,s)&&this._updateLayer(o),this._changed=!0,this._updatedPaintProps[t]=!0,this._serializedLayers=null):this.fire(new e.j(new Error(`Cannot style non-existing layer "${t}".`)));}getPaintProperty(t,e){return this.getLayer(t).getPaintProperty(e)}setFeatureState(t,i){this._checkLoaded();const a=t.source,s=t.sourceLayer,o=this.sourceCaches[a];if(void 0===o)return void this.fire(new e.j(new Error(`The source '${a}' does not exist in the map's style.`)));const r=o.getSource().type;"geojson"===r&&s?this.fire(new e.j(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==r||s?(void 0===t.id&&this.fire(new e.j(new Error("The feature id parameter must be provided."))),o.setFeatureState(s,t.id,i)):this.fire(new e.j(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(t,i){this._checkLoaded();const a=t.source,s=this.sourceCaches[a];if(void 0===s)return void this.fire(new e.j(new Error(`The source '${a}' does not exist in the map's style.`)));const o=s.getSource().type,r="vector"===o?t.sourceLayer:void 0;"vector"!==o||r?i&&"string"!=typeof t.id&&"number"!=typeof t.id?this.fire(new e.j(new Error("A feature id is required to remove its specific state property."))):s.removeFeatureState(r,t.id,i):this.fire(new e.j(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(t){this._checkLoaded();const i=t.source,a=t.sourceLayer,s=this.sourceCaches[i];if(void 0!==s)return "vector"!==s.getSource().type||a?(void 0===t.id&&this.fire(new e.j(new Error("The feature id parameter must be provided."))),s.getFeatureState(a,t.id)):void this.fire(new e.j(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new e.j(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return e.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const t=e.aF(this.sourceCaches,(t=>t.serialize())),i=this._serializeByIds(this._order,!0),a=this.map.getTerrain()||void 0,s=this.stylesheet;return e.aG({version:s.version,name:s.name,metadata:s.metadata,light:s.light,sky:s.sky,center:s.center,zoom:s.zoom,bearing:s.bearing,pitch:s.pitch,sprite:s.sprite,glyphs:s.glyphs,transition:s.transition,sources:t,layers:i,terrain:a},(t=>void 0!==t))}_updateLayer(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&"raster"!==this.sourceCaches[t.source].getSource().type&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._serializedLayers=null,this._changed=!0;}_flattenAndSortRenderedFeatures(t){const e=t=>"fill-extrusion"===this._layers[t].type,i={},a=[];for(let s=this._order.length-1;s>=0;s--){const o=this._order[s];if(e(o)){i[o]=s;for(const e of t){const t=e[o];if(t)for(const e of t)a.push(e);}}}a.sort(((t,e)=>e.intersectionZ-t.intersectionZ));const s=[];for(let o=this._order.length-1;o>=0;o--){const r=this._order[o];if(e(r))for(let t=a.length-1;t>=0;t--){const e=a[t].feature;if(i[e.layer.id]{const a=i.featureSortOrder;if(a){const i=a.indexOf(t.featureIndex);return a.indexOf(e.featureIndex)-i}return e.featureIndex-t.featureIndex}));for(const t of s)e.push(t);}}for(const e in n)n[e].forEach((a=>{const s=a.feature,o=i[t[e].source].getFeatureState(s.layer["source-layer"],s.id);s.source=s.layer.source,s.layer["source-layer"]&&(s.sourceLayer=s.layer["source-layer"]),s.state=o;}));return n}(this._layers,r,this.sourceCaches,t,i,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(o)}querySourceFeatures(t,i){i&&i.filter&&this._validate(e.u.filter,"querySourceFeatures.filter",i.filter,null,i);const a=this.sourceCaches[t];return a?function(t,e){const i=t.getRenderableIds().map((e=>t.getTileByID(e))),a=[],s={};for(let t=0;tt.getTileByID(e))).sort(((t,e)=>e.tileID.overscaledZ-t.tileID.overscaledZ||(t.tileID.isLessThan(e.tileID)?-1:1)));}const a=this.crossTileSymbolIndex.addLayer(i,l[i.source],t.center.lng);r=r||a;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((s=s||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.now(),t.zoom))&&(this.pauseablePlacement=new se(t,this.map.terrain,this._order,s,e,i,a,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.now()),n=!0),r&&this.pauseablePlacement.placement.setStale()),n||r)for(const t of this._order){const e=this._layers[t];"symbol"===e.type&&this.placement.updateLayerOpacities(e,l[e.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(o.now())}_releaseSymbolFadeTiles(){for(const t in this.sourceCaches)this.sourceCaches[t].releaseSymbolFadeTiles();}getImages(t,i){return e._(this,void 0,void 0,(function*(){const t=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const e=this.sourceCaches[i.source];return e&&e.setDependencies(i.tileID.key,i.type,i.icons),t}))}getGlyphs(t,i){return e._(this,void 0,void 0,(function*(){const t=yield this.glyphManager.getGlyphs(i.stacks),e=this.sourceCaches[i.source];return e&&e.setDependencies(i.tileID.key,i.type,[""]),t}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(t,i={}){this._checkLoaded(),t&&this._validate(e.u.glyphs,"glyphs",t,null,i)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=t,this.glyphManager.entries={},this.glyphManager.setURL(t));}addSprite(t,i,a={},s){this._checkLoaded();const o=[{id:t,url:i}],r=[...x(this.stylesheet.sprite),...o];this._validate(e.u.sprite,"sprite",r,null,a)||(this.stylesheet.sprite=r,this._loadSprite(o,!0,s));}removeSprite(t){this._checkLoaded();const i=x(this.stylesheet.sprite);if(i.find((e=>e.id===t))){if(this._spritesImagesIds[t])for(const e of this._spritesImagesIds[t])this.imageManager.removeImage(e),this._changedImages[e]=!0;i.splice(i.findIndex((e=>e.id===t)),1),this.stylesheet.sprite=i.length>0?i:void 0,delete this._spritesImagesIds[t],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new e.k("data",{dataType:"style"}));}else this.fire(new e.j(new Error(`Sprite "${t}" doesn't exists on this map.`)));}getSprite(){return x(this.stylesheet.sprite)}setSprite(t,i={},a){this._checkLoaded(),t&&this._validate(e.u.sprite,"sprite",t,null,i)||(this.stylesheet.sprite=t,t?this._loadSprite(t,!0,a):(this._unloadSprite(),a&&a(null)));}}var _e=e.Y([{name:"a_pos",type:"Int16",components:2}]);const pe={prelude:me("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\n","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture2D(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture2D(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}"),background:me("uniform vec4 u_color;uniform float u_opacity;void main() {gl_FragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),backgroundPattern:me("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:me("varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);lowp float antialiasblur=v_data.z;float antialiased_blur=-max(blur,antialiasblur);float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));gl_FragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);float ele=get_elevation(circle_center);v_visibility=calculate_visibility(u_matrix*vec4(circle_center,ele,1.0));if (u_pitch_with_map) {vec2 corner_position=circle_center;if (u_scale_with_map) {corner_position+=extrude*(radius+stroke_width)*u_extrude_scale;} else {vec4 projected_center=u_matrix*vec4(circle_center,0,1);corner_position+=extrude*(radius+stroke_width)*u_extrude_scale*(projected_center.w/u_camera_to_center_distance);}gl_Position=u_matrix*vec4(corner_position,ele,1);} else {gl_Position=u_matrix*vec4(circle_center,ele,1);if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:me("void main() {gl_FragColor=vec4(1.0);}","attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),heatmap:me("uniform highp float u_intensity;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);gl_FragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec4 pos=vec4(floor(a_pos*0.5)+extrude,get_elevation(floor(a_pos*0.5)),1);gl_Position=u_matrix*pos;}"),heatmapTexture:me("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:me("varying float v_placed;varying float v_notUsed;void main() {float alpha=0.5;gl_FragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}","attribute vec2 a_anchor_pos;attribute vec2 a_placed;attribute vec2 a_box_real;uniform mat4 u_matrix;uniform vec2 u_pixel_extrude_scale;varying float v_placed;varying float v_notUsed;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:me("varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}","attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),debug:me("uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}","attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,get_elevation(a_pos),1);}"),fill:me("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}"),fillOutline:me("varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),fillOutlinePattern:me("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),fillPattern:me("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:me("varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:me("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:me("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:me("uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}"),line:me("uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:me("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,v_uv);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;attribute float a_uv_x;attribute float a_split_index;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:me("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:me("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:me("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:me("uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_tex;varying float v_fade_opacity;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:me("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_2;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nfloat median(vec3 values) {return max(min(values.r,values.g),min(max(values.r,values.g),values.b));}float screenPxRange(float fontScale) {return fontScale*SDF_PX;}vec4 renderText(vec4 fill_color,vec4 halo_color,float opacity,float halo_width,float halo_blur,float EDGE_GAMMA,vec2 tex,float gamma_scale,float size,float fade_opacity) {float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}return color*(alpha*opacity*fade_opacity);}vec4 renderMSDFIcon(vec4 fill_color,vec4 halo_color,float opacity,float EDGE_GAMMA,vec2 tex,float gamma_scale,float size,float fade_opacity) {float fontScale=size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;vec3 s=texture2D(u_texture,tex).rgb;float sd=median(s);float dist=sd-0.5;if (u_is_halo) {color=halo_color;s=texture2D(u_texture_2,tex).rgb;sd=median(s);dist=sd-0.5;}float clampedDistance=clamp(dist*screenPxRange(fontScale)+0.5,0.0,1.0);highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,clampedDistance);return color*(alpha*opacity*fade_opacity);}void main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];gl_FragColor=u_is_text ? renderText(fill_color,halo_color,opacity,halo_width,halo_blur,EDGE_GAMMA,tex,gamma_scale,size,fade_opacity) : renderMSDFIcon(fill_color,halo_color,opacity,EDGE_GAMMA,tex,gamma_scale,size,fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_data0;varying vec3 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:me("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec4 v_data0;varying vec4 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:me("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;varying vec2 v_texture_pos;varying float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture2D(u_texture,v_texture_pos);if (v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);gl_FragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {gl_FragColor=surface_color;}}","attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform mat4 u_fog_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;varying float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:me("varying float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {gl_FragColor=pack(v_depth);}","attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:me("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;varying vec2 v_texture_pos;void main() {vec4 rgba=texture2D(u_texture,v_texture_pos);gl_FragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);}"),sky:me("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform float u_horizon;uniform float u_sky_horizon_blend;void main() {float y=gl_FragCoord.y;if (y > u_horizon) {float blend=y-u_horizon;if (blend < u_sky_horizon_blend) {gl_FragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {gl_FragColor=u_sky_color;}}}","attribute vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function me(t,e){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,a=e.match(/attribute ([\w]+) ([\w]+)/g),s=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),o=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),r=o?o.concat(s):s,n={};return {fragmentSource:t=t.replace(i,((t,e,i,a,s)=>(n[s]=!0,"define"===e?`\n#ifndef HAS_UNIFORM_u_${s}\nvarying ${i} ${a} ${s};\n#else\nuniform ${i} ${a} u_${s};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${s}\n ${i} ${a} ${s} = u_${s};\n#endif\n`))),vertexSource:e=e.replace(i,((t,e,i,a,s)=>{const o="float"===a?"vec2":"vec4",r=s.match(/color/)?"color":o;return n[s]?"define"===e?`\n#ifndef HAS_UNIFORM_u_${s}\nuniform lowp float u_${s}_t;\nattribute ${i} ${o} a_${s};\nvarying ${i} ${a} ${s};\n#else\nuniform ${i} ${a} u_${s};\n#endif\n`:"vec4"===r?`\n#ifndef HAS_UNIFORM_u_${s}\n ${s} = a_${s};\n#else\n ${i} ${a} ${s} = u_${s};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${s}\n ${s} = unpack_mix_${r}(a_${s}, u_${s}_t);\n#else\n ${i} ${a} ${s} = u_${s};\n#endif\n`:"define"===e?`\n#ifndef HAS_UNIFORM_u_${s}\nuniform lowp float u_${s}_t;\nattribute ${i} ${o} a_${s};\n#else\nuniform ${i} ${a} u_${s};\n#endif\n`:"vec4"===r?`\n#ifndef HAS_UNIFORM_u_${s}\n ${i} ${a} ${s} = a_${s};\n#else\n ${i} ${a} ${s} = u_${s};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${s}\n ${i} ${a} ${s} = unpack_mix_${r}(a_${s}, u_${s}_t);\n#else\n ${i} ${a} ${s} = u_${s};\n#endif\n`})),staticAttributes:a,staticUniforms:r}}class fe{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;}bind(t,e,i,a,s,o,r,n,l){this.context=t;let h=this.boundPaintVertexBuffers.length!==a.length;for(let t=0;!h&&t({u_matrix:t,u_texture:0,u_ele_delta:i,u_fog_matrix:a,u_fog_color:s?s.properties.get("fog-color"):e.aM.white,u_fog_ground_blend:s?s.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:s?s.calculateFogBlendOpacity(o):0,u_horizon_color:s?s.properties.get("horizon-color"):e.aM.white,u_horizon_fog_blend:s?s.properties.get("horizon-fog-blend"):1});function ve(t){const e=[];for(let i=0;i({u_depth:new e.aH(t,i.u_depth),u_terrain:new e.aH(t,i.u_terrain),u_terrain_dim:new e.aI(t,i.u_terrain_dim),u_terrain_matrix:new e.aJ(t,i.u_terrain_matrix),u_terrain_unpack:new e.aK(t,i.u_terrain_unpack),u_terrain_exaggeration:new e.aI(t,i.u_terrain_exaggeration)}))(t,b),this.binderUniforms=a?a.getUniforms(t,b):[];}draw(t,e,i,a,s,o,r,n,l,h,c,u,d,_,p,m,f,g){const v=t.gl;if(this.failedToCreate)return;if(t.program.set(this.program),t.setDepthMode(i),t.setStencilMode(a),t.setColorMode(s),t.setCullFace(o),n){t.activeTexture.set(v.TEXTURE2),v.bindTexture(v.TEXTURE_2D,n.depthTexture),t.activeTexture.set(v.TEXTURE3),v.bindTexture(v.TEXTURE_2D,n.texture);for(const t in this.terrainUniforms)this.terrainUniforms[t].set(n[t]);}for(const t in this.fixedUniforms)this.fixedUniforms[t].set(r[t]);p&&p.setUniforms(t,this.binderUniforms,d,{zoom:_});let x=0;switch(e){case v.LINES:x=2;break;case v.TRIANGLES:x=3;break;case v.LINE_STRIP:x=1;}for(const i of u.get()){const a=i.vaos||(i.vaos={});(a[l]||(a[l]=new fe)).bind(t,this,h,p?p.getPaintVertexBuffers():[],c,i.vertexOffset,m,f,g),v.drawElements(e,i.primitiveLength*x,v.UNSIGNED_SHORT,i.primitiveOffset*x*2);}}}function ye(t,e,i){const a=1/Bt(i,1,e.transform.tileZoom),s=Math.pow(2,i.tileID.overscaledZ),o=i.tileSize*Math.pow(2,e.transform.tileZoom)/s,r=o*(i.tileID.canonical.x+i.tileID.wrap*s),n=o*i.tileID.canonical.y;return {u_image:0,u_texsize:i.imageAtlasTexture.size,u_scale:[a,t.fromScale,t.toScale],u_fade:t.t,u_pixel_coord_upper:[r>>16,n>>16],u_pixel_coord_lower:[65535&r,65535&n]}}const be=(t,i,a,s)=>{const o=i.style.light,r=o.properties.get("position"),n=[r.x,r.y,r.z],l=function(){var t=new e.A(9);return e.A!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t}();"viewport"===o.properties.get("anchor")&&function(t,e){var i=Math.sin(e),a=Math.cos(e);t[0]=a,t[1]=i,t[2]=0,t[3]=-i,t[4]=a,t[5]=0,t[6]=0,t[7]=0,t[8]=1;}(l,-i.transform.angle),function(t,e,i){var a=e[0],s=e[1],o=e[2];t[0]=a*i[0]+s*i[3]+o*i[6],t[1]=a*i[1]+s*i[4]+o*i[7],t[2]=a*i[2]+s*i[5]+o*i[8];}(n,n,l);const h=o.properties.get("color");return {u_matrix:t,u_lightpos:n,u_lightintensity:o.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+a,u_opacity:s}},we=(t,i,a,s,o,r,n)=>e.e(be(t,i,a,s),ye(r,i,n),{u_height_factor:-Math.pow(2,o.overscaledZ)/n.tileSize/8}),Te=t=>({u_matrix:t}),Ie=(t,i,a,s)=>e.e(Te(t),ye(a,i,s)),Ee=(t,e)=>({u_matrix:t,u_world:e}),Pe=(t,i,a,s,o)=>e.e(Ie(t,i,a,s),{u_world:o}),Ce=(t,e,i,a)=>{const s=t.transform;let o,r;if("map"===a.paint.get("circle-pitch-alignment")){const t=Bt(i,1,s.zoom);o=!0,r=[t,t];}else o=!1,r=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===a.paint.get("circle-pitch-scale")),u_matrix:t.translatePosMatrix(e.posMatrix,i,a.paint.get("circle-translate"),a.paint.get("circle-translate-anchor")),u_pitch_with_map:+o,u_device_pixel_ratio:t.pixelRatio,u_extrude_scale:r}},Se=(t,e,i)=>({u_matrix:t,u_inv_matrix:e,u_camera_to_center_distance:i.cameraToCenterDistance,u_viewport_size:[i.width,i.height]}),De=(t,e,i=1)=>({u_matrix:t,u_color:e,u_overlay:0,u_overlay_scale:i}),ze=t=>({u_matrix:t}),Me=(t,e,i,a)=>({u_matrix:t,u_extrude_scale:Bt(e,1,i),u_intensity:a}),Ae=(t,i,a,s)=>{const o=e.H();e.aP(o,0,t.width,t.height,0,0,1);const r=t.context.gl;return {u_matrix:o,u_world:[r.drawingBufferWidth,r.drawingBufferHeight],u_image:a,u_color_ramp:s,u_opacity:i.paint.get("heatmap-opacity")}};function Re(t,i){const a=Math.pow(2,i.canonical.z),s=i.canonical.y;return [new e.Z(0,s/a).toLngLat().lat,new e.Z(0,(s+1)/a).toLngLat().lat]}const ke=(t,e,i,a)=>{const s=t.transform;return {u_matrix:Ne(t,e,i,a),u_ratio:1/Bt(e,1,s.zoom),u_device_pixel_ratio:t.pixelRatio,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},Le=(t,i,a,s,o)=>e.e(ke(t,i,a,o),{u_image:0,u_image_height:s}),Fe=(t,e,i,a,s)=>{const o=t.transform,r=Oe(e,o);return {u_matrix:Ne(t,e,i,s),u_texsize:e.imageAtlasTexture.size,u_ratio:1/Bt(e,1,o.zoom),u_device_pixel_ratio:t.pixelRatio,u_image:0,u_scale:[r,a.fromScale,a.toScale],u_fade:a.t,u_units_to_pixels:[1/o.pixelsToGLUnits[0],1/o.pixelsToGLUnits[1]]}},Be=(t,i,a,s,o,r)=>{const n=t.lineAtlas,l=Oe(i,t.transform),h="round"===a.layout.get("line-cap"),c=n.getDash(s.from,h),u=n.getDash(s.to,h),d=c.width*o.fromScale,_=u.width*o.toScale;return e.e(ke(t,i,a,r),{u_patternscale_a:[l/d,-c.height/2],u_patternscale_b:[l/_,-u.height/2],u_sdfgamma:n.width/(256*Math.min(d,_)*t.pixelRatio)/2,u_image:0,u_tex_y_a:c.y,u_tex_y_b:u.y,u_mix:o.t})};function Oe(t,e){return 1/Bt(t,1,e.tileZoom)}function Ne(t,e,i,a){return t.translatePosMatrix(a?a.posMatrix:e.tileID.posMatrix,e,i.paint.get("line-translate"),i.paint.get("line-translate-anchor"))}const Ue=(t,e,i,a,s)=>{return {u_matrix:t,u_tl_parent:e,u_scale_parent:i,u_buffer_scale:1,u_fade_t:a.mix,u_opacity:a.opacity*s.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:s.paint.get("raster-brightness-min"),u_brightness_high:s.paint.get("raster-brightness-max"),u_saturation_factor:(r=s.paint.get("raster-saturation"),r>0?1-1/(1.001-r):-r),u_contrast_factor:(o=s.paint.get("raster-contrast"),o>0?1/(1-o):1+o),u_spin_weights:je(s.paint.get("raster-hue-rotate"))};var o,r;};function je(t){t*=Math.PI/180;const e=Math.sin(t),i=Math.cos(t);return [(2*i+1)/3,(-Math.sqrt(3)*e-i+1)/3,(Math.sqrt(3)*e-i+1)/3]}const Ze=(t,e,i,a,s,o,r,n,l,h,c,u,d,_)=>{const p=r.transform;return {u_is_size_zoom_constant:+("constant"===t||"source"===t),u_is_size_feature_constant:+("constant"===t||"camera"===t),u_size_t:e?e.uSizeT:0,u_size:e?e.uSize:0,u_camera_to_center_distance:p.cameraToCenterDistance,u_pitch:p.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:p.width/p.height,u_fade_change:r.options.fadeDuration?r.symbolFadeChange:1,u_matrix:n,u_label_plane_matrix:l,u_coord_matrix:h,u_is_text:+u,u_pitch_with_map:+a,u_is_along_line:s,u_is_variable_anchor:o,u_texsize:d,u_texture:0,u_translation:c,u_pitched_scale:_}},Ge=(t,i,a,s,o,r,n,l,h,c,u,d,_,p,m)=>{const f=n.transform;return e.e(Ze(t,i,a,s,o,r,n,l,h,c,u,d,_,m),{u_gamma_scale:s?Math.cos(f._pitch)*f.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:+p,u_texture_2:1})},qe=(t,i,a,s,o,r,n,l,h,c,u,d,_,p)=>e.e(Ge(t,i,a,s,o,r,n,l,h,c,u,!0,d,!0,p),{u_texsize_icon:_,u_texture_icon:1}),Ve=(t,e,i)=>({u_matrix:t,u_opacity:e,u_color:i}),He=(t,i,a,s,o,r)=>e.e(function(t,e,i,a){const s=i.imageManager.getPattern(t.from.toString()),o=i.imageManager.getPattern(t.to.toString()),{width:r,height:n}=i.imageManager.getPixelSize(),l=Math.pow(2,a.tileID.overscaledZ),h=a.tileSize*Math.pow(2,i.transform.tileZoom)/l,c=h*(a.tileID.canonical.x+a.tileID.wrap*l),u=h*a.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:s.tl,u_pattern_br_a:s.br,u_pattern_tl_b:o.tl,u_pattern_br_b:o.br,u_texsize:[r,n],u_mix:e.t,u_pattern_size_a:s.displaySize,u_pattern_size_b:o.displaySize,u_scale_a:e.fromScale,u_scale_b:e.toScale,u_tile_units_to_pixels:1/Bt(a,1,i.transform.tileZoom),u_pixel_coord_upper:[c>>16,u>>16],u_pixel_coord_lower:[65535&c,65535&u]}}(s,r,a,o),{u_matrix:t,u_opacity:i}),We={fillExtrusion:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_lightpos:new e.aN(t,i.u_lightpos),u_lightintensity:new e.aI(t,i.u_lightintensity),u_lightcolor:new e.aN(t,i.u_lightcolor),u_vertical_gradient:new e.aI(t,i.u_vertical_gradient),u_opacity:new e.aI(t,i.u_opacity)}),fillExtrusionPattern:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_lightpos:new e.aN(t,i.u_lightpos),u_lightintensity:new e.aI(t,i.u_lightintensity),u_lightcolor:new e.aN(t,i.u_lightcolor),u_vertical_gradient:new e.aI(t,i.u_vertical_gradient),u_height_factor:new e.aI(t,i.u_height_factor),u_image:new e.aH(t,i.u_image),u_texsize:new e.aO(t,i.u_texsize),u_pixel_coord_upper:new e.aO(t,i.u_pixel_coord_upper),u_pixel_coord_lower:new e.aO(t,i.u_pixel_coord_lower),u_scale:new e.aN(t,i.u_scale),u_fade:new e.aI(t,i.u_fade),u_opacity:new e.aI(t,i.u_opacity)}),fill:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix)}),fillPattern:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_image:new e.aH(t,i.u_image),u_texsize:new e.aO(t,i.u_texsize),u_pixel_coord_upper:new e.aO(t,i.u_pixel_coord_upper),u_pixel_coord_lower:new e.aO(t,i.u_pixel_coord_lower),u_scale:new e.aN(t,i.u_scale),u_fade:new e.aI(t,i.u_fade)}),fillOutline:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_world:new e.aO(t,i.u_world)}),fillOutlinePattern:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_world:new e.aO(t,i.u_world),u_image:new e.aH(t,i.u_image),u_texsize:new e.aO(t,i.u_texsize),u_pixel_coord_upper:new e.aO(t,i.u_pixel_coord_upper),u_pixel_coord_lower:new e.aO(t,i.u_pixel_coord_lower),u_scale:new e.aN(t,i.u_scale),u_fade:new e.aI(t,i.u_fade)}),circle:(t,i)=>({u_camera_to_center_distance:new e.aI(t,i.u_camera_to_center_distance),u_scale_with_map:new e.aH(t,i.u_scale_with_map),u_pitch_with_map:new e.aH(t,i.u_pitch_with_map),u_extrude_scale:new e.aO(t,i.u_extrude_scale),u_device_pixel_ratio:new e.aI(t,i.u_device_pixel_ratio),u_matrix:new e.aJ(t,i.u_matrix)}),collisionBox:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_pixel_extrude_scale:new e.aO(t,i.u_pixel_extrude_scale)}),collisionCircle:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_inv_matrix:new e.aJ(t,i.u_inv_matrix),u_camera_to_center_distance:new e.aI(t,i.u_camera_to_center_distance),u_viewport_size:new e.aO(t,i.u_viewport_size)}),debug:(t,i)=>({u_color:new e.aL(t,i.u_color),u_matrix:new e.aJ(t,i.u_matrix),u_overlay:new e.aH(t,i.u_overlay),u_overlay_scale:new e.aI(t,i.u_overlay_scale)}),clippingMask:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix)}),heatmap:(t,i)=>({u_extrude_scale:new e.aI(t,i.u_extrude_scale),u_intensity:new e.aI(t,i.u_intensity),u_matrix:new e.aJ(t,i.u_matrix)}),heatmapTexture:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_world:new e.aO(t,i.u_world),u_image:new e.aH(t,i.u_image),u_color_ramp:new e.aH(t,i.u_color_ramp),u_opacity:new e.aI(t,i.u_opacity)}),hillshade:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_image:new e.aH(t,i.u_image),u_latrange:new e.aO(t,i.u_latrange),u_light:new e.aO(t,i.u_light),u_shadow:new e.aL(t,i.u_shadow),u_highlight:new e.aL(t,i.u_highlight),u_accent:new e.aL(t,i.u_accent)}),hillshadePrepare:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_image:new e.aH(t,i.u_image),u_dimension:new e.aO(t,i.u_dimension),u_zoom:new e.aI(t,i.u_zoom),u_unpack:new e.aK(t,i.u_unpack)}),line:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_ratio:new e.aI(t,i.u_ratio),u_device_pixel_ratio:new e.aI(t,i.u_device_pixel_ratio),u_units_to_pixels:new e.aO(t,i.u_units_to_pixels)}),lineGradient:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_ratio:new e.aI(t,i.u_ratio),u_device_pixel_ratio:new e.aI(t,i.u_device_pixel_ratio),u_units_to_pixels:new e.aO(t,i.u_units_to_pixels),u_image:new e.aH(t,i.u_image),u_image_height:new e.aI(t,i.u_image_height)}),linePattern:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_texsize:new e.aO(t,i.u_texsize),u_ratio:new e.aI(t,i.u_ratio),u_device_pixel_ratio:new e.aI(t,i.u_device_pixel_ratio),u_image:new e.aH(t,i.u_image),u_units_to_pixels:new e.aO(t,i.u_units_to_pixels),u_scale:new e.aN(t,i.u_scale),u_fade:new e.aI(t,i.u_fade)}),lineSDF:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_ratio:new e.aI(t,i.u_ratio),u_device_pixel_ratio:new e.aI(t,i.u_device_pixel_ratio),u_units_to_pixels:new e.aO(t,i.u_units_to_pixels),u_patternscale_a:new e.aO(t,i.u_patternscale_a),u_patternscale_b:new e.aO(t,i.u_patternscale_b),u_sdfgamma:new e.aI(t,i.u_sdfgamma),u_image:new e.aH(t,i.u_image),u_tex_y_a:new e.aI(t,i.u_tex_y_a),u_tex_y_b:new e.aI(t,i.u_tex_y_b),u_mix:new e.aI(t,i.u_mix)}),raster:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_tl_parent:new e.aO(t,i.u_tl_parent),u_scale_parent:new e.aI(t,i.u_scale_parent),u_buffer_scale:new e.aI(t,i.u_buffer_scale),u_fade_t:new e.aI(t,i.u_fade_t),u_opacity:new e.aI(t,i.u_opacity),u_image0:new e.aH(t,i.u_image0),u_image1:new e.aH(t,i.u_image1),u_brightness_low:new e.aI(t,i.u_brightness_low),u_brightness_high:new e.aI(t,i.u_brightness_high),u_saturation_factor:new e.aI(t,i.u_saturation_factor),u_contrast_factor:new e.aI(t,i.u_contrast_factor),u_spin_weights:new e.aN(t,i.u_spin_weights)}),symbolIcon:(t,i)=>({u_is_size_zoom_constant:new e.aH(t,i.u_is_size_zoom_constant),u_is_size_feature_constant:new e.aH(t,i.u_is_size_feature_constant),u_size_t:new e.aI(t,i.u_size_t),u_size:new e.aI(t,i.u_size),u_camera_to_center_distance:new e.aI(t,i.u_camera_to_center_distance),u_pitch:new e.aI(t,i.u_pitch),u_rotate_symbol:new e.aH(t,i.u_rotate_symbol),u_aspect_ratio:new e.aI(t,i.u_aspect_ratio),u_fade_change:new e.aI(t,i.u_fade_change),u_matrix:new e.aJ(t,i.u_matrix),u_label_plane_matrix:new e.aJ(t,i.u_label_plane_matrix),u_coord_matrix:new e.aJ(t,i.u_coord_matrix),u_is_text:new e.aH(t,i.u_is_text),u_pitch_with_map:new e.aH(t,i.u_pitch_with_map),u_is_along_line:new e.aH(t,i.u_is_along_line),u_is_variable_anchor:new e.aH(t,i.u_is_variable_anchor),u_texsize:new e.aO(t,i.u_texsize),u_texture:new e.aH(t,i.u_texture),u_translation:new e.aO(t,i.u_translation),u_pitched_scale:new e.aI(t,i.u_pitched_scale)}),symbolSDF:(t,i)=>({u_is_size_zoom_constant:new e.aH(t,i.u_is_size_zoom_constant),u_is_size_feature_constant:new e.aH(t,i.u_is_size_feature_constant),u_size_t:new e.aI(t,i.u_size_t),u_size:new e.aI(t,i.u_size),u_camera_to_center_distance:new e.aI(t,i.u_camera_to_center_distance),u_pitch:new e.aI(t,i.u_pitch),u_rotate_symbol:new e.aH(t,i.u_rotate_symbol),u_aspect_ratio:new e.aI(t,i.u_aspect_ratio),u_fade_change:new e.aI(t,i.u_fade_change),u_matrix:new e.aJ(t,i.u_matrix),u_label_plane_matrix:new e.aJ(t,i.u_label_plane_matrix),u_coord_matrix:new e.aJ(t,i.u_coord_matrix),u_is_text:new e.aH(t,i.u_is_text),u_pitch_with_map:new e.aH(t,i.u_pitch_with_map),u_is_along_line:new e.aH(t,i.u_is_along_line),u_is_variable_anchor:new e.aH(t,i.u_is_variable_anchor),u_texsize:new e.aO(t,i.u_texsize),u_texture:new e.aH(t,i.u_texture),u_texture_2:new e.aH(t,i.u_texture_2),u_gamma_scale:new e.aI(t,i.u_gamma_scale),u_device_pixel_ratio:new e.aI(t,i.u_device_pixel_ratio),u_is_halo:new e.aH(t,i.u_is_halo),u_translation:new e.aO(t,i.u_translation),u_pitched_scale:new e.aI(t,i.u_pitched_scale)}),symbolTextAndIcon:(t,i)=>({u_is_size_zoom_constant:new e.aH(t,i.u_is_size_zoom_constant),u_is_size_feature_constant:new e.aH(t,i.u_is_size_feature_constant),u_size_t:new e.aI(t,i.u_size_t),u_size:new e.aI(t,i.u_size),u_camera_to_center_distance:new e.aI(t,i.u_camera_to_center_distance),u_pitch:new e.aI(t,i.u_pitch),u_rotate_symbol:new e.aH(t,i.u_rotate_symbol),u_aspect_ratio:new e.aI(t,i.u_aspect_ratio),u_fade_change:new e.aI(t,i.u_fade_change),u_matrix:new e.aJ(t,i.u_matrix),u_label_plane_matrix:new e.aJ(t,i.u_label_plane_matrix),u_coord_matrix:new e.aJ(t,i.u_coord_matrix),u_is_text:new e.aH(t,i.u_is_text),u_pitch_with_map:new e.aH(t,i.u_pitch_with_map),u_is_along_line:new e.aH(t,i.u_is_along_line),u_is_variable_anchor:new e.aH(t,i.u_is_variable_anchor),u_texsize:new e.aO(t,i.u_texsize),u_texsize_icon:new e.aO(t,i.u_texsize_icon),u_texture:new e.aH(t,i.u_texture),u_texture_icon:new e.aH(t,i.u_texture_icon),u_gamma_scale:new e.aI(t,i.u_gamma_scale),u_device_pixel_ratio:new e.aI(t,i.u_device_pixel_ratio),u_is_halo:new e.aH(t,i.u_is_halo),u_translation:new e.aO(t,i.u_translation),u_pitched_scale:new e.aI(t,i.u_pitched_scale)}),background:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_opacity:new e.aI(t,i.u_opacity),u_color:new e.aL(t,i.u_color)}),backgroundPattern:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_opacity:new e.aI(t,i.u_opacity),u_image:new e.aH(t,i.u_image),u_pattern_tl_a:new e.aO(t,i.u_pattern_tl_a),u_pattern_br_a:new e.aO(t,i.u_pattern_br_a),u_pattern_tl_b:new e.aO(t,i.u_pattern_tl_b),u_pattern_br_b:new e.aO(t,i.u_pattern_br_b),u_texsize:new e.aO(t,i.u_texsize),u_mix:new e.aI(t,i.u_mix),u_pattern_size_a:new e.aO(t,i.u_pattern_size_a),u_pattern_size_b:new e.aO(t,i.u_pattern_size_b),u_scale_a:new e.aI(t,i.u_scale_a),u_scale_b:new e.aI(t,i.u_scale_b),u_pixel_coord_upper:new e.aO(t,i.u_pixel_coord_upper),u_pixel_coord_lower:new e.aO(t,i.u_pixel_coord_lower),u_tile_units_to_pixels:new e.aI(t,i.u_tile_units_to_pixels)}),terrain:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_texture:new e.aH(t,i.u_texture),u_ele_delta:new e.aI(t,i.u_ele_delta),u_fog_matrix:new e.aJ(t,i.u_fog_matrix),u_fog_color:new e.aL(t,i.u_fog_color),u_fog_ground_blend:new e.aI(t,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new e.aI(t,i.u_fog_ground_blend_opacity),u_horizon_color:new e.aL(t,i.u_horizon_color),u_horizon_fog_blend:new e.aI(t,i.u_horizon_fog_blend)}),terrainDepth:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_ele_delta:new e.aI(t,i.u_ele_delta)}),terrainCoords:(t,i)=>({u_matrix:new e.aJ(t,i.u_matrix),u_texture:new e.aH(t,i.u_texture),u_terrain_coords_id:new e.aI(t,i.u_terrain_coords_id),u_ele_delta:new e.aI(t,i.u_ele_delta)}),sky:(t,i)=>({u_sky_color:new e.aL(t,i.u_sky_color),u_horizon_color:new e.aL(t,i.u_horizon_color),u_horizon:new e.aI(t,i.u_horizon),u_sky_horizon_blend:new e.aI(t,i.u_sky_horizon_blend)})};class $e{constructor(t,e,i){this.context=t;const a=t.gl;this.buffer=a.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),t.bindElementBuffer.set(this.buffer),a.bufferData(a.ELEMENT_ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?a.DYNAMIC_DRAW:a.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer;}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(t){const e=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),e.bufferSubData(e.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const Xe={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class Ke{constructor(t,e,i,a){this.length=e.length,this.attributes=i,this.itemSize=e.bytesPerElement,this.dynamicDraw=a,this.context=t;const s=t.gl;this.buffer=s.createBuffer(),t.bindVertexBuffer.set(this.buffer),s.bufferData(s.ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?s.DYNAMIC_DRAW:s.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer;}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(t){if(t.length!==this.length)throw new Error(`Length of new data is ${t.length}, which doesn't match current length of ${this.length}`);const e=this.context.gl;this.bind(),e.bufferSubData(e.ARRAY_BUFFER,0,t.arrayBuffer);}enableAttributes(t,e){for(let i=0;i0){const i=e.H();e.aQ(i,m.placementInvProjMatrix,t.transform.glCoordMatrix),e.aQ(i,i,m.placementViewportMatrix),h.push({circleArray:g,circleOffset:u,transform:p.posMatrix,invTransform:i,coord:p}),c+=g.length/4,u=c;}f&&l.draw(r,n.LINES,Oi.disabled,Ui.disabled,t.colorModeForRenderPass(),ji.disabled,{u_matrix:p.posMatrix,u_pixel_extrude_scale:[1/(d=t.transform).width,1/d.height]},t.style.map.terrain&&t.style.map.terrain.getTerrainData(p),a.id,f.layoutVertexBuffer,f.indexBuffer,f.segments,null,t.transform.zoom,null,null,f.collisionVertexBuffer);}var d;if(!o||!h.length)return;const _=t.useProgram("collisionCircle"),p=new e.aR;p.resize(4*c),p._trim();let m=0;for(const t of h)for(let e=0;e=0&&(v[x.associatedIconIndex]={shiftedAnchor:z,angle:M});}else Rt(x.numGlyphs,f);}if(c){g.clear();const i=t.icon.placedSymbolArray;for(let t=0;tt.style.map.terrain.getElevation(l,e,i):null,i="map"===a.layout.get("text-rotation-alignment");wt(h,l.posMatrix,t,o,j,G,v,c,i,f,l.toUnwrapped(),m.width,m.height,q,e);}const W=l.posMatrix,$=o&&E||H,X=x||$?qi:j,K=Z,J=_&&0!==a.paint.get(o?"text-halo-width":"icon-halo-width").constantOr(1);let Y;Y=_?h.iconsInText?qe(I.kind,z,y,v,x,$,t,W,X,K,q,A,B,C):Ge(I.kind,z,y,v,x,$,t,W,X,K,q,o,A,!0,C):Ze(I.kind,z,y,v,x,$,t,W,X,K,q,o,A,C);const Q={program:D,buffers:u,uniformValues:Y,atlasTexture:R,atlasBackgroundTexture:F,atlasTextureIcon:O,atlasInterpolation:k,atlasInterpolationIcon:L,isSDF:_,hasHalo:J};if(w&&h.canOverlap){T=!0;const t=u.segments.get();for(const i of t)P.push({segments:new e.a0([i]),sortKey:i.sortKey,state:Q,terrainData:M});}else P.push({segments:u.segments,sortKey:0,state:Q,terrainData:M});}T&&P.sort(((t,e)=>t.sortKey-e.sortKey));for(const e of P){const i=e.state;if(_.activeTexture.set(p.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,p.CLAMP_TO_EDGE),(i.atlasTextureIcon||i.atlasBackgroundTexture)&&(_.activeTexture.set(p.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,p.CLAMP_TO_EDGE),i.atlasBackgroundTexture&&i.atlasBackgroundTexture.bind(i.atlasInterpolation,p.CLAMP_TO_EDGE)),i.isSDF){const s=i.uniformValues;i.hasHalo&&(s.u_is_halo=1,Ki(i.buffers,e.segments,a,t,i.program,I,u,d,s,e.terrainData)),s.u_is_halo=0;}Ki(i.buffers,e.segments,a,t,i.program,I,u,d,i.uniformValues,e.terrainData);}}function Ki(t,e,i,a,s,o,r,n,l,h){const c=a.context;s.draw(c,c.gl.TRIANGLES,o,r,n,ji.disabled,l,h,i.id,t.layoutVertexBuffer,t.indexBuffer,e,i.paint,a.transform.zoom,t.programConfigurations.get(i.id),t.dynamicLayoutVertexBuffer,t.opacityVertexBuffer);}function Ji(t,i,a,s){const o=t.context,r=o.gl,n=Ui.disabled,l=new Fi([r.ONE,r.ONE],e.aM.transparent,[!0,!0,!0,!0]),h=i.getBucket(a);if(!h)return;const c=s.key;let u=a.heatmapFbos.get(c);u||(u=Qi(o,i.tileSize,i.tileSize),a.heatmapFbos.set(c,u)),o.bindFramebuffer.set(u.framebuffer),o.viewport.set([0,0,i.tileSize,i.tileSize]),o.clear({color:e.aM.transparent});const d=h.programConfigurations.get(a.id),_=t.useProgram("heatmap",d),p=t.style.map.terrain.getTerrainData(s);_.draw(o,r.TRIANGLES,Oi.disabled,n,l,ji.disabled,Me(s.posMatrix,i,t.transform.zoom,a.paint.get("heatmap-intensity")),p,a.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,a.paint,t.transform.zoom,d);}function Yi(t,e,i){const a=t.context,s=a.gl;a.setColorMode(t.colorModeForRenderPass());const o=ta(a,e),r=i.key,n=e.heatmapFbos.get(r);n&&(a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,n.colorAttachment.get()),a.activeTexture.set(s.TEXTURE1),o.bind(s.LINEAR,s.CLAMP_TO_EDGE),t.useProgram("heatmapTexture").draw(a,s.TRIANGLES,Oi.disabled,Ui.disabled,t.colorModeForRenderPass(),ji.disabled,Ae(t,e,0,1),null,e.id,t.rasterBoundsBuffer,t.quadTriangleIndexBuffer,t.rasterBoundsSegments,e.paint,t.transform.zoom),n.destroy(),e.heatmapFbos.delete(r));}function Qi(t,e,i){var a,s;const o=t.gl,r=o.createTexture();o.bindTexture(o.TEXTURE_2D,r),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR);const n=null!==(a=t.HALF_FLOAT)&&void 0!==a?a:o.UNSIGNED_BYTE,l=null!==(s=t.RGBA16F)&&void 0!==s?s:o.RGBA;o.texImage2D(o.TEXTURE_2D,0,l,e,i,0,o.RGBA,n,null);const h=t.createFramebuffer(e,i,!1,!1);return h.colorAttachment.set(r),h}function ta(t,e){return e.colorRampTexture||(e.colorRampTexture=new b(t,e.colorRamp,t.gl.RGBA)),e.colorRampTexture}function ea(t,e,i,a,s){if(!i||!a||!a.imageAtlas)return;const o=a.imageAtlas.patternPositions;let r=o[i.to.toString()],n=o[i.from.toString()];if(!r&&n&&(r=n),!n&&r&&(n=r),!r||!n){const t=s.getPaintProperty(e);r=o[t],n=o[t];}r&&n&&t.setConstantPatternPositions(r,n);}function ia(t,e,i,a,s,o,r){const n=t.context.gl,l="fill-pattern",h=i.paint.get(l),c=h&&h.constantOr(1),u=i.getCrossfadeParameters();let d,_,p,m,f;r?(_=c&&!i.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",d=n.LINES):(_=c?"fillPattern":"fill",d=n.TRIANGLES);const g=h.constantOr(null);for(const h of a){const a=e.getTile(h);if(c&&!a.patternsLoaded())continue;const v=a.getBucket(i);if(!v)continue;const x=v.programConfigurations.get(i.id),y=t.useProgram(_,x),b=t.style.map.terrain&&t.style.map.terrain.getTerrainData(h);c&&(t.context.activeTexture.set(n.TEXTURE0),a.imageAtlasTexture.bind(n.LINEAR,n.CLAMP_TO_EDGE),x.updatePaintBuffers(u)),ea(x,l,g,a,i);const w=b?h:null,T=t.translatePosMatrix(w?w.posMatrix:h.posMatrix,a,i.paint.get("fill-translate"),i.paint.get("fill-translate-anchor"));if(r){m=v.indexBuffer2,f=v.segments2;const e=[n.drawingBufferWidth,n.drawingBufferHeight];p="fillOutlinePattern"===_&&c?Pe(T,t,u,a,e):Ee(T,e);}else m=v.indexBuffer,f=v.segments,p=c?Ie(T,t,u,a):Te(T);y.draw(t.context,d,s,t.stencilModeForClipping(h),o,ji.disabled,p,b,i.id,v.layoutVertexBuffer,m,f,i.paint,t.transform.zoom,x);}}function aa(t,e,i,a,s,o,r){const n=t.context,l=n.gl,h="fill-extrusion-pattern",c=i.paint.get(h),u=c.constantOr(1),d=i.getCrossfadeParameters(),_=i.paint.get("fill-extrusion-opacity"),p=c.constantOr(null);for(const c of a){const a=e.getTile(c),m=a.getBucket(i);if(!m)continue;const f=t.style.map.terrain&&t.style.map.terrain.getTerrainData(c),g=m.programConfigurations.get(i.id),v=t.useProgram(u?"fillExtrusionPattern":"fillExtrusion",g);u&&(t.context.activeTexture.set(l.TEXTURE0),a.imageAtlasTexture.bind(l.LINEAR,l.CLAMP_TO_EDGE),g.updatePaintBuffers(d)),ea(g,h,p,a,i);const x=t.translatePosMatrix(c.posMatrix,a,i.paint.get("fill-extrusion-translate"),i.paint.get("fill-extrusion-translate-anchor")),y=i.paint.get("fill-extrusion-vertical-gradient"),b=u?we(x,t,y,_,c,d,a):be(x,t,y,_);v.draw(n,n.gl.TRIANGLES,s,o,r,ji.backCCW,b,f,i.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,i.paint,t.transform.zoom,g,t.style.map.terrain&&m.centroidVertexBuffer);}}function sa(t,e,i,a,s,o,r){const n=t.context,l=n.gl,h=i.fbo;if(!h)return;const c=t.useProgram("hillshade"),u=t.style.map.terrain&&t.style.map.terrain.getTerrainData(e);n.activeTexture.set(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,h.colorAttachment.get()),c.draw(n,l.TRIANGLES,s,o,r,ji.disabled,((t,e,i,a)=>{const s=i.paint.get("hillshade-shadow-color"),o=i.paint.get("hillshade-highlight-color"),r=i.paint.get("hillshade-accent-color");let n=i.paint.get("hillshade-illumination-direction")*(Math.PI/180);"viewport"===i.paint.get("hillshade-illumination-anchor")&&(n-=t.transform.angle);const l=!t.options.moving;return {u_matrix:a?a.posMatrix:t.transform.calculatePosMatrix(e.tileID.toUnwrapped(),l),u_image:0,u_latrange:Re(0,e.tileID),u_light:[i.paint.get("hillshade-exaggeration"),n],u_shadow:s,u_highlight:o,u_accent:r}})(t,i,a,u?e:null),u,a.id,t.rasterBoundsBuffer,t.quadTriangleIndexBuffer,t.rasterBoundsSegments);}function oa(t,i,a,s,o,r){const n=t.context,l=n.gl,h=i.dem;if(h&&h.data){const c=h.dim,u=h.stride,d=h.getPixels();if(n.activeTexture.set(l.TEXTURE1),n.pixelStoreUnpackPremultiplyAlpha.set(!1),i.demTexture=i.demTexture||t.getTileTexture(u),i.demTexture){const t=i.demTexture;t.update(d,{premultiply:!1}),t.bind(l.NEAREST,l.CLAMP_TO_EDGE);}else i.demTexture=new b(n,d,l.RGBA,{premultiply:!1}),i.demTexture.bind(l.NEAREST,l.CLAMP_TO_EDGE);n.activeTexture.set(l.TEXTURE0);let _=i.fbo;if(!_){const t=new b(n,{width:c,height:c,data:null},l.RGBA);t.bind(l.LINEAR,l.CLAMP_TO_EDGE),_=i.fbo=n.createFramebuffer(c,c,!0,!1),_.colorAttachment.set(t.texture);}n.bindFramebuffer.set(_.framebuffer),n.viewport.set([0,0,c,c]),t.useProgram("hillshadePrepare").draw(n,l.TRIANGLES,s,o,r,ji.disabled,((t,i)=>{const a=i.stride,s=e.H();return e.aP(s,0,e.X,-e.X,0,0,1),e.J(s,s,[0,-e.X,0]),{u_matrix:s,u_image:1,u_dimension:[a,a],u_zoom:t.overscaledZ,u_unpack:i.getUnpackVector()}})(i.tileID,h),null,a.id,t.rasterBoundsBuffer,t.quadTriangleIndexBuffer,t.rasterBoundsSegments),i.needsHillshadePrepare=!1;}}function ra(t,i,a,s,r,n){const l=s.paint.get("raster-fade-duration");if(!n&&l>0){const s=o.now(),n=(s-t.timeAdded)/l,h=i?(s-i.timeAdded)/l:-1,c=a.getSource(),u=r.coveringZoomLevel({tileSize:c.tileSize,roundZoom:c.roundZoom}),d=!i||Math.abs(i.tileID.overscaledZ-u)>Math.abs(t.tileID.overscaledZ-u),_=d&&t.refreshedUponExpiration?1:e.ac(d?n:1-h,0,1);return t.refreshedUponExpiration&&n>=1&&(t.refreshedUponExpiration=!1),i?{opacity:1,mix:1-_}:{opacity:_,mix:0}}return {opacity:1,mix:0}}const na=new e.aM(1,0,0,1),la=new e.aM(0,1,0,1),ha=new e.aM(0,0,1,1),ca=new e.aM(1,0,1,1),ua=new e.aM(0,1,1,1);function da(t,e,i,a){pa(t,0,e+i/2,t.transform.width,i,a);}function _a(t,e,i,a){pa(t,e-i/2,0,i,t.transform.height,a);}function pa(t,e,i,a,s,o){const r=t.context,n=r.gl;n.enable(n.SCISSOR_TEST),n.scissor(e*t.pixelRatio,i*t.pixelRatio,a*t.pixelRatio,s*t.pixelRatio),r.clear({color:o}),n.disable(n.SCISSOR_TEST);}function ma(t,i,a){const s=t.context,o=s.gl,r=a.posMatrix,n=t.useProgram("debug"),l=Oi.disabled,h=Ui.disabled,c=t.colorModeForRenderPass(),u="$debug",d=t.style.map.terrain&&t.style.map.terrain.getTerrainData(a);s.activeTexture.set(o.TEXTURE0);const _=i.getTileByID(a.key).latestRawTileData,p=Math.floor((_&&_.byteLength||0)/1024),m=i.getTile(a).tileSize,f=512/Math.min(m,512)*(a.overscaledZ/t.transform.zoom)*.5;let g=a.canonical.toString();a.overscaledZ!==a.canonical.z&&(g+=` => ${a.overscaledZ}`),function(t,e){t.initDebugOverlayCanvas();const i=t.debugOverlayCanvas,a=t.context.gl,s=t.debugOverlayCanvas.getContext("2d");s.clearRect(0,0,i.width,i.height),s.shadowColor="white",s.shadowBlur=2,s.lineWidth=1.5,s.strokeStyle="white",s.textBaseline="top",s.font="bold 36px Open Sans, sans-serif",s.fillText(e,5,5),s.strokeText(e,5,5),t.debugOverlayTexture.update(i),t.debugOverlayTexture.bind(a.LINEAR,a.CLAMP_TO_EDGE);}(t,`${g} ${p}kB`),n.draw(s,o.TRIANGLES,l,h,Fi.alphaBlended,ji.disabled,De(r,e.aM.transparent,f),null,u,t.debugBuffer,t.quadTriangleIndexBuffer,t.debugSegments),n.draw(s,o.LINE_STRIP,l,h,c,ji.disabled,De(r,e.aM.red),d,u,t.debugBuffer,t.tileBorderIndexBuffer,t.debugSegments);}function fa(t,e,i){const a=t.context,s=a.gl,o=t.colorModeForRenderPass(),r=new Oi(s.LEQUAL,Oi.ReadWrite,t.depthRangeFor3D),n=t.useProgram("terrain"),l=e.getTerrainMesh();a.bindFramebuffer.set(null),a.viewport.set([0,0,t.width,t.height]);for(const h of i){const i=t.renderToTexture.getTexture(h),c=e.getTerrainData(h.tileID);a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,i.texture);const u=t.transform.calculatePosMatrix(h.tileID.toUnwrapped()),d=e.getMeshFrameDelta(t.transform.zoom),_=t.transform.calculateFogMatrix(h.tileID.toUnwrapped()),p=ge(u,d,_,t.style.sky,t.transform.pitch);n.draw(a,s.TRIANGLES,r,Ui.disabled,o,ji.backCCW,p,c,"terrain",l.vertexBuffer,l.indexBuffer,l.segments);}}class ga{constructor(t,e,i){this.vertexBuffer=t,this.indexBuffer=e,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}class va{constructor(t,i){this.context=new Bi(t),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:e.an(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=ut.maxUnderzooming+ut.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new he;}resize(t,e,i){if(this.width=Math.floor(t*i),this.height=Math.floor(e*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const t of this.style._order)this.style._layers[t].resize();}setup(){const t=this.context,i=new e.aX;i.emplaceBack(0,0),i.emplaceBack(e.X,0),i.emplaceBack(0,e.X),i.emplaceBack(e.X,e.X),this.tileExtentBuffer=t.createVertexBuffer(i,_e.members),this.tileExtentSegments=e.a0.simpleSegment(0,0,4,2);const a=new e.aX;a.emplaceBack(0,0),a.emplaceBack(e.X,0),a.emplaceBack(0,e.X),a.emplaceBack(e.X,e.X),this.debugBuffer=t.createVertexBuffer(a,_e.members),this.debugSegments=e.a0.simpleSegment(0,0,4,5);const s=new e.$;s.emplaceBack(0,0,0,0),s.emplaceBack(e.X,0,e.X,0),s.emplaceBack(0,e.X,0,e.X),s.emplaceBack(e.X,e.X,e.X,e.X),this.rasterBoundsBuffer=t.createVertexBuffer(s,Y.members),this.rasterBoundsSegments=e.a0.simpleSegment(0,0,4,2);const o=new e.aX;o.emplaceBack(0,0),o.emplaceBack(1,0),o.emplaceBack(0,1),o.emplaceBack(1,1),this.viewportBuffer=t.createVertexBuffer(o,_e.members),this.viewportSegments=e.a0.simpleSegment(0,0,4,2);const r=new e.aZ;r.emplaceBack(0),r.emplaceBack(1),r.emplaceBack(3),r.emplaceBack(2),r.emplaceBack(0),this.tileBorderIndexBuffer=t.createIndexBuffer(r);const n=new e.aY;n.emplaceBack(0,1,2),n.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=t.createIndexBuffer(n);const l=this.context.gl;this.stencilClearMode=new Ui({func:l.ALWAYS,mask:0},0,255,l.ZERO,l.ZERO,l.ZERO);}clearStencil(){const t=this.context,i=t.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const a=e.H();e.aP(a,0,this.width,this.height,0,0,1),e.K(a,a,[i.drawingBufferWidth,i.drawingBufferHeight,0]),this.useProgram("clippingMask").draw(t,i.TRIANGLES,Oi.disabled,this.stencilClearMode,Fi.disabled,ji.disabled,ze(a),null,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(t,e){if(this.currentStencilSource===t.source||!t.isTileClipped()||!e||!e.length)return;this.currentStencilSource=t.source;const i=this.context,a=i.gl;this.nextStencilID+e.length>256&&this.clearStencil(),i.setColorMode(Fi.disabled),i.setDepthMode(Oi.disabled);const s=this.useProgram("clippingMask");this._tileClippingMaskIDs={};for(const t of e){const e=this._tileClippingMaskIDs[t.key]=this.nextStencilID++,o=this.style.map.terrain&&this.style.map.terrain.getTerrainData(t);s.draw(i,a.TRIANGLES,Oi.disabled,new Ui({func:a.ALWAYS,mask:0},e,255,a.KEEP,a.KEEP,a.REPLACE),Fi.disabled,ji.disabled,ze(t.posMatrix),o,"$clipping",this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const t=this.nextStencilID++,e=this.context.gl;return new Ui({func:e.NOTEQUAL,mask:255},t,255,e.KEEP,e.KEEP,e.REPLACE)}stencilModeForClipping(t){const e=this.context.gl;return new Ui({func:e.EQUAL,mask:255},this._tileClippingMaskIDs[t.key],0,e.KEEP,e.KEEP,e.REPLACE)}stencilConfigForOverlap(t){const e=this.context.gl,i=t.sort(((t,e)=>e.overscaledZ-t.overscaledZ)),a=i[i.length-1].overscaledZ,s=i[0].overscaledZ-a+1;if(s>1){this.currentStencilSource=void 0,this.nextStencilID+s>256&&this.clearStencil();const t={};for(let i=0;i({u_sky_color:t.properties.get("sky-color"),u_horizon_color:t.properties.get("horizon-color"),u_horizon:(e.height/2+e.getHorizon())*i,u_sky_horizon_blend:t.properties.get("sky-horizon-blend")*e.height/2*i}))(i,t.style.map.transform,t.pixelRatio),r=new Oi(s.LEQUAL,Oi.ReadWrite,[0,1]),n=Ui.disabled,l=t.colorModeForRenderPass(),h=t.useProgram("sky");if(!i.mesh){const t=new e.aX;t.emplaceBack(-1,-1),t.emplaceBack(1,-1),t.emplaceBack(1,1),t.emplaceBack(-1,1);const s=new e.aY;s.emplaceBack(0,1,2),s.emplaceBack(0,2,3),i.mesh=new ga(a.createVertexBuffer(t,_e.members),a.createIndexBuffer(s),e.a0.simpleSegment(0,0,t.length,s.length));}h.draw(a,s.TRIANGLES,r,n,l,ji.disabled,o,void 0,"sky",i.mesh.vertexBuffer,i.mesh.indexBuffer,i.mesh.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(t._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=a.length-1;this.currentLayer>=0;this.currentLayer--){const t=this.style._layers[a[this.currentLayer]],e=s[t.source],i=r[t.source];this._renderTileClippingMasks(t,i),this.renderLayer(this,e,t,i);}for(this.renderPass="translucent",this.currentLayer=0;this.currentLayeri.source&&!i.isHidden(e)?[t.sourceCaches[i.source]]:[])),s=a.filter((t=>"vector"===t.getSource().type)),o=a.filter((t=>"vector"!==t.getSource().type)),r=t=>{(!i||i.getSource().maxzoomr(t))),i||o.forEach((t=>r(t))),i}(this.style,this.transform.zoom);t&&function(t,e,i){for(let a=0;a0),s&&(e.b0(i,a),this.terrainFacilitator.renderTime=Date.now(),this.terrainFacilitator.dirty=!1,function(t,i){const a=t.context,s=a.gl,o=Fi.unblended,r=new Oi(s.LEQUAL,Oi.ReadWrite,[0,1]),n=i.getTerrainMesh(),l=i.sourceCache.getRenderableTiles(),h=t.useProgram("terrainDepth");a.bindFramebuffer.set(i.getFramebuffer("depth").framebuffer),a.viewport.set([0,0,t.width/devicePixelRatio,t.height/devicePixelRatio]),a.clear({color:e.aM.transparent,depth:1});for(const e of l){const l=i.getTerrainData(e.tileID),c={u_matrix:t.transform.calculatePosMatrix(e.tileID.toUnwrapped()),u_ele_delta:i.getMeshFrameDelta(t.transform.zoom)};h.draw(a,s.TRIANGLES,r,Ui.disabled,o,ji.backCCW,c,l,"terrain",n.vertexBuffer,n.indexBuffer,n.segments);}a.bindFramebuffer.set(null),a.viewport.set([0,0,t.width,t.height]);}(this,this.style.map.terrain),function(t,i){const a=t.context,s=a.gl,o=Fi.unblended,r=new Oi(s.LEQUAL,Oi.ReadWrite,[0,1]),n=i.getTerrainMesh(),l=i.getCoordsTexture(),h=i.sourceCache.getRenderableTiles(),c=t.useProgram("terrainCoords");a.bindFramebuffer.set(i.getFramebuffer("coords").framebuffer),a.viewport.set([0,0,t.width/devicePixelRatio,t.height/devicePixelRatio]),a.clear({color:e.aM.transparent,depth:1}),i.coordsIndex=[];for(const e of h){const h=i.getTerrainData(e.tileID);a.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,l.texture);const u={u_matrix:t.transform.calculatePosMatrix(e.tileID.toUnwrapped()),u_terrain_coords_id:(255-i.coordsIndex.length)/255,u_texture:0,u_ele_delta:i.getMeshFrameDelta(t.transform.zoom)};c.draw(a,s.TRIANGLES,r,Ui.disabled,o,ji.backCCW,u,h,"terrain",n.vertexBuffer,n.indexBuffer,n.segments),i.coordsIndex.push(e.tileID.key);}a.bindFramebuffer.set(null),a.viewport.set([0,0,t.width,t.height]);}(this,this.style.map.terrain));}renderLayer(t,i,a,s){if(!a.isHidden(this.transform.zoom)&&("background"===a.type||"custom"===a.type||(s||[]).length))switch(this.id=a.id,a.type){case"symbol":!function(t,i,a,s,o){if("translucent"!==t.renderPass)return;const r=Ui.disabled,n=t.colorModeForRenderPass();(a._unevaluatedLayout.hasValue("text-variable-anchor")||a._unevaluatedLayout.hasValue("text-variable-anchor-offset"))&&function(t,i,a,s,o,r,n,l,h){const c=i.transform,u=ie(),d="map"===o,_="map"===r;for(const o of t){const t=s.getTile(o),r=t.getBucket(a);if(!r||!r.text||!r.text.segments.get().length)continue;const p=e.ag(r.textSizeData,c.zoom),m=Bt(t,1,i.transform.zoom),f=gt(o.posMatrix,_,d,i.transform,m),g="none"!==a.layout.get("icon-text-fit")&&r.hasIconData();if(p){const e=Math.pow(2,c.zoom-t.tileID.overscaledZ),a=i.style.map.terrain?(t,e)=>i.style.map.terrain.getElevation(o,t,e):null,s=u.translatePosition(c,t,n,l);Wi(r,d,_,h,c,f,o.posMatrix,e,p,g,u,s,o.toUnwrapped(),a);}}}(s,t,a,i,a.layout.get("text-rotation-alignment"),a.layout.get("text-pitch-alignment"),a.paint.get("text-translate"),a.paint.get("text-translate-anchor"),o),0!==a.paint.get("icon-opacity").constantOr(1)&&Xi(t,i,a,s,!1,a.paint.get("icon-translate"),a.paint.get("icon-translate-anchor"),a.layout.get("icon-rotation-alignment"),a.layout.get("icon-pitch-alignment"),a.layout.get("icon-keep-upright"),r,n),0!==a.paint.get("text-opacity").constantOr(1)&&Xi(t,i,a,s,!0,a.paint.get("text-translate"),a.paint.get("text-translate-anchor"),a.layout.get("text-rotation-alignment"),a.layout.get("text-pitch-alignment"),a.layout.get("text-keep-upright"),r,n),i.map.showCollisionBoxes&&(Gi(t,i,a,s,!0),Gi(t,i,a,s,!1));}(t,i,a,s,this.style.placement.variableOffsets);break;case"circle":!function(t,i,a,s){if("translucent"!==t.renderPass)return;const o=a.paint.get("circle-opacity"),r=a.paint.get("circle-stroke-width"),n=a.paint.get("circle-stroke-opacity"),l=!a.layout.get("circle-sort-key").isConstant();if(0===o.constantOr(1)&&(0===r.constantOr(1)||0===n.constantOr(1)))return;const h=t.context,c=h.gl,u=t.depthModeForSublayer(0,Oi.ReadOnly),d=Ui.disabled,_=t.colorModeForRenderPass(),p=[];for(let o=0;ot.sortKey-e.sortKey));for(const e of p){const{programConfiguration:i,program:s,layoutVertexBuffer:o,indexBuffer:r,uniformValues:n,terrainData:l}=e.state;s.draw(h,c.TRIANGLES,u,d,_,ji.disabled,n,l,a.id,o,r,e.segments,a.paint,t.transform.zoom,i);}}(t,i,a,s);break;case"heatmap":!function(t,i,a,s){if(0===a.paint.get("heatmap-opacity"))return;const o=t.context;if(t.style.map.terrain){for(const e of s){const s=i.getTile(e);i.hasRenderableParent(e)||("offscreen"===t.renderPass?Ji(t,s,a,e):"translucent"===t.renderPass&&Yi(t,a,e));}o.viewport.set([0,0,t.width,t.height]);}else "offscreen"===t.renderPass?function(t,i,a,s){const o=t.context,r=o.gl,n=Ui.disabled,l=new Fi([r.ONE,r.ONE],e.aM.transparent,[!0,!0,!0,!0]);((function(t,i,a){const s=t.gl;t.activeTexture.set(s.TEXTURE1),t.viewport.set([0,0,i.width/4,i.height/4]);let o=a.heatmapFbos.get(e.aU);o?(s.bindTexture(s.TEXTURE_2D,o.colorAttachment.get()),t.bindFramebuffer.set(o.framebuffer)):(o=Qi(t,i.width/4,i.height/4),a.heatmapFbos.set(e.aU,o));}))(o,t,a),o.clear({color:e.aM.transparent});for(let e=0;e20&&o.texParameterf(o.TEXTURE_2D,s.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,s.extTextureFilterAnisotropicMax);const y=t.style.map.terrain&&t.style.map.terrain.getTerrainData(a),b=y?a:null,w=b?b.posMatrix:t.transform.calculatePosMatrix(a.toUnwrapped(),d),T=Ue(w,v||[0,0],g||1,f,i);r instanceof Q?n.draw(s,o.TRIANGLES,c,Ui.disabled,l,ji.disabled,T,y,i.id,r.boundsBuffer,t.quadTriangleIndexBuffer,r.boundsSegments):n.draw(s,o.TRIANGLES,c,h[a.overscaledZ],l,ji.disabled,T,y,i.id,t.rasterBoundsBuffer,t.quadTriangleIndexBuffer,t.rasterBoundsSegments);}}(t,i,a,s);break;case"background":!function(t,e,i,a){const s=i.paint.get("background-color"),o=i.paint.get("background-opacity");if(0===o)return;const r=t.context,n=r.gl,l=t.transform,h=l.tileSize,c=i.paint.get("background-pattern");if(t.isPatternMissing(c))return;const u=!c&&1===s.a&&1===o&&t.opaquePassEnabledForLayer()?"opaque":"translucent";if(t.renderPass!==u)return;const d=Ui.disabled,_=t.depthModeForSublayer(0,"opaque"===u?Oi.ReadWrite:Oi.ReadOnly),p=t.colorModeForRenderPass(),m=t.useProgram(c?"backgroundPattern":"background"),f=a||l.coveringTiles({tileSize:h,terrain:t.style.map.terrain});c&&(r.activeTexture.set(n.TEXTURE0),t.imageManager.bind(t.context));const g=i.getCrossfadeParameters();for(const e of f){const l=a?e.posMatrix:t.transform.calculatePosMatrix(e.toUnwrapped()),u=c?He(l,o,t,c,{tileID:e,tileSize:h},g):Ve(l,o,s),f=t.style.map.terrain&&t.style.map.terrain.getTerrainData(e);m.draw(r,n.TRIANGLES,_,d,p,ji.disabled,u,f,i.id,t.tileExtentBuffer,t.quadTriangleIndexBuffer,t.tileExtentSegments);}}(t,0,a,s);break;case"custom":!function(t,e,i){const a=t.context,s=i.implementation;if("offscreen"===t.renderPass){const e=s.prerender;e&&(t.setCustomLayerDefaults(),a.setColorMode(t.colorModeForRenderPass()),e.call(s,a.gl,t.transform.customLayerMatrix()),a.setDirty(),t.setBaseState());}else if("translucent"===t.renderPass){t.setCustomLayerDefaults(),a.setColorMode(t.colorModeForRenderPass()),a.setStencilMode(Ui.disabled);const e="3d"===s.renderingMode?new Oi(t.context.gl.LEQUAL,Oi.ReadWrite,t.depthRangeFor3D):t.depthModeForSublayer(0,Oi.ReadOnly);a.setDepthMode(e),s.render(a.gl,t.transform.customLayerMatrix(),{farZ:t.transform.farZ,nearZ:t.transform.nearZ,fov:t.transform._fov,modelViewProjectionMatrix:t.transform.modelViewProjectionMatrix,projectionMatrix:t.transform.projectionMatrix}),a.setDirty(),t.setBaseState(),a.bindFramebuffer.set(null);}}(t,0,a);}}translatePosMatrix(t,i,a,s,o){if(!a[0]&&!a[1])return t;const r=o?"map"===s?this.transform.angle:0:"viewport"===s?-this.transform.angle:0;if(r){const t=Math.sin(r),e=Math.cos(r);a=[a[0]*e-a[1]*t,a[0]*t+a[1]*e];}const n=[o?a[0]:Bt(i,a[0],this.transform.zoom),o?a[1]:Bt(i,a[1],this.transform.zoom),0],l=new Float32Array(16);return e.J(l,t,n),l}saveTileTexture(t){const e=this._tileTextures[t.size[0]];e?e.push(t):this._tileTextures[t.size[0]]=[t];}getTileTexture(t){const e=this._tileTextures[t];return e&&e.length>0?e.pop():null}isPatternMissing(t){if(!t)return !1;if(!t.from||!t.to)return !0;const e=this.imageManager.getPattern(t.from.toString()),i=this.imageManager.getPattern(t.to.toString());return !e||!i}useProgram(t,e){this.cache=this.cache||{};const i=t+(e?e.cacheKey:"")+(this._showOverdrawInspector?"/overdraw":"")+(this.style.map.terrain?"/terrain":"");return this.cache[i]||(this.cache[i]=new xe(this.context,pe[t],e,We[t],this._showOverdrawInspector,this.style.map.terrain)),this.cache[i]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();}setBaseState(){const t=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(t.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new b(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy();}overLimit(){const{drawingBufferWidth:t,drawingBufferHeight:e}=this.context.gl;return this.width!==t||this.height!==e}}class xa{constructor(t,e){this.points=t,this.planes=e;}static fromInvProjectionMatrix(t,i,a){const s=Math.pow(2,a),o=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((a=>{const o=1/(a=e.af([],a,t))[3]/i*s;return e.b1(a,a,[o,o,1/a[3],o])})),r=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((t=>{const e=function(t,e){var i=e[0],a=e[1],s=e[2],o=i*i+a*a+s*s;return o>0&&(o=1/Math.sqrt(o)),t[0]=e[0]*o,t[1]=e[1]*o,t[2]=e[2]*o,t}([],function(t,e,i){var a=e[0],s=e[1],o=e[2],r=i[0],n=i[1],l=i[2];return t[0]=s*l-o*n,t[1]=o*r-a*l,t[2]=a*n-s*r,t}([],g([],o[t[0]],o[t[1]]),g([],o[t[2]],o[t[1]]))),i=-((a=e)[0]*(s=o[t[1]])[0]+a[1]*s[1]+a[2]*s[2]);var a,s;return e.concat(i)}));return new xa(o,r)}}class ya{constructor(t,e){this.min=t,this.max=e,this.center=function(t,e,i){return t[0]=.5*e[0],t[1]=.5*e[1],t[2]=.5*e[2],t}([],function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t[2]=e[2]+i[2],t}([],this.min,this.max));}quadrant(t){const e=[t%2==0,t<2],i=m(this.min),a=m(this.max);for(let t=0;t=0&&r++;if(0===r)return 0;r!==i.length&&(a=!1);}if(a)return 2;for(let e=0;e<3;e++){let i=Number.MAX_VALUE,a=-Number.MAX_VALUE;for(let s=0;sthis.max[e]-this.min[e])return 0}return 1}}class ba{constructor(t=0,e=0,i=0,a=0){if(isNaN(t)||t<0||isNaN(e)||e<0||isNaN(i)||i<0||isNaN(a)||a<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=t,this.bottom=e,this.left=i,this.right=a;}interpolate(t,i,a){return null!=i.top&&null!=t.top&&(this.top=e.y.number(t.top,i.top,a)),null!=i.bottom&&null!=t.bottom&&(this.bottom=e.y.number(t.bottom,i.bottom,a)),null!=i.left&&null!=t.left&&(this.left=e.y.number(t.left,i.left,a)),null!=i.right&&null!=t.right&&(this.right=e.y.number(t.right,i.right,a)),this}getCenter(t,i){const a=e.ac((this.left+t-this.right)/2,0,t),s=e.ac((this.top+i-this.bottom)/2,0,i);return new e.P(a,s)}equals(t){return this.top===t.top&&this.bottom===t.bottom&&this.left===t.left&&this.right===t.right}clone(){return new ba(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const wa=85.051129;class Ta{constructor(t,i,a,s,o){this.tileSize=512,this._renderWorldCopies=void 0===o||!!o,this._minZoom=t||0,this._maxZoom=i||22,this._minPitch=null==a?0:a,this._maxPitch=null==s?60:s,this.setMaxBounds(),this.width=0,this.height=0,this._center=new e.N(0,0),this._elevation=0,this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._edgeInsets=new ba,this._posMatrixCache={},this._alignedPosMatrixCache={},this._fogMatrixCache={},this.minElevationForCurrentTile=0;}clone(){const t=new Ta(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies);return t.apply(this),t}apply(t){this.tileSize=t.tileSize,this.latRange=t.latRange,this.lngRange=t.lngRange,this.width=t.width,this.height=t.height,this._center=t._center,this._elevation=t._elevation,this.minElevationForCurrentTile=t.minElevationForCurrentTile,this.zoom=t.zoom,this.angle=t.angle,this._fov=t._fov,this._pitch=t._pitch,this._unmodified=t._unmodified,this._edgeInsets=t._edgeInsets.clone(),this._calcMatrices();}get minZoom(){return this._minZoom}set minZoom(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t));}get maxZoom(){return this._maxZoom}set maxZoom(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t));}get minPitch(){return this._minPitch}set minPitch(t){this._minPitch!==t&&(this._minPitch=t,this.pitch=Math.max(this.pitch,t));}get maxPitch(){return this._maxPitch}set maxPitch(t){this._maxPitch!==t&&(this._maxPitch=t,this.pitch=Math.min(this.pitch,t));}get renderWorldCopies(){return this._renderWorldCopies}set renderWorldCopies(t){void 0===t?t=!0:null===t&&(t=!1),this._renderWorldCopies=t;}get worldSize(){return this.tileSize*this.scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new e.P(this.width,this.height)}get bearing(){return -this.angle/Math.PI*180}set bearing(t){const i=-e.b3(t,-180,180)*Math.PI/180;this.angle!==i&&(this._unmodified=!1,this.angle=i,this._calcMatrices(),this.rotationMatrix=function(){var t=new e.A(4);return e.A!=Float32Array&&(t[1]=0,t[2]=0),t[0]=1,t[3]=1,t}(),function(t,e,i){var a=e[0],s=e[1],o=e[2],r=e[3],n=Math.sin(i),l=Math.cos(i);t[0]=a*l+o*n,t[1]=s*l+r*n,t[2]=a*-n+o*l,t[3]=s*-n+r*l;}(this.rotationMatrix,this.rotationMatrix,this.angle));}get pitch(){return this._pitch/Math.PI*180}set pitch(t){const i=e.ac(t,this.minPitch,this.maxPitch)/180*Math.PI;this._pitch!==i&&(this._unmodified=!1,this._pitch=i,this._calcMatrices());}get fov(){return this._fov/Math.PI*180}set fov(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices());}get zoom(){return this._zoom}set zoom(t){const e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.tileZoom=Math.max(0,Math.floor(e)),this.scale=this.zoomScale(e),this._constrain(),this._calcMatrices());}get center(){return this._center}set center(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices());}get elevation(){return this._elevation}set elevation(t){t!==this._elevation&&(this._elevation=t,this._constrain(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}set padding(t){this._edgeInsets.equals(t)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,t,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this.width,this.height)}isPaddingEqual(t){return this._edgeInsets.equals(t)}interpolatePadding(t,e,i){this._unmodified=!1,this._edgeInsets.interpolate(t,e,i),this._constrain(),this._calcMatrices();}coveringZoomLevel(t){const e=(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize));return Math.max(0,e)}getVisibleUnwrappedCoordinates(t){const i=[new e.b4(0,t)];if(this._renderWorldCopies){const a=this.pointCoordinate(new e.P(0,0)),s=this.pointCoordinate(new e.P(this.width,0)),o=this.pointCoordinate(new e.P(this.width,this.height)),r=this.pointCoordinate(new e.P(0,this.height)),n=Math.floor(Math.min(a.x,s.x,o.x,r.x)),l=Math.floor(Math.max(a.x,s.x,o.x,r.x)),h=1;for(let a=n-h;a<=l+h;a++)0!==a&&i.push(new e.b4(a,t));}return i}coveringTiles(t){var i,a;let s=this.coveringZoomLevel(t);const o=s;if(void 0!==t.minzoom&&st.maxzoom&&(s=t.maxzoom);const r=this.pointCoordinate(this.getCameraPoint()),n=e.Z.fromLngLat(this.center),l=Math.pow(2,s),h=[l*r.x,l*r.y,0],c=[l*n.x,l*n.y,0],u=xa.fromInvProjectionMatrix(this.invModelViewProjectionMatrix,this.worldSize,s);let d=t.minzoom||0;!t.terrain&&this.pitch<=60&&this._edgeInsets.top<.1&&(d=s);const _=t.terrain?2/Math.min(this.tileSize,t.tileSize)*this.tileSize:3,p=t=>({aabb:new ya([t*l,0,0],[(t+1)*l,l,0]),zoom:0,x:0,y:0,wrap:t,fullyVisible:!1}),m=[],f=[],g=s,x=t.reparseOverscaled?o:s;if(this._renderWorldCopies)for(let t=1;t<=3;t++)m.push(p(-t)),m.push(p(t));for(m.push(p(0));m.length>0;){const s=m.pop(),o=s.x,r=s.y;let n=s.fullyVisible;if(!n){const t=s.aabb.intersects(u);if(0===t)continue;n=2===t;}const l=t.terrain?h:c,p=s.aabb.distanceX(l),y=s.aabb.distanceY(l),b=Math.max(Math.abs(p),Math.abs(y));if(s.zoom===g||b>_+(1<=d){const t=g-s.zoom,i=h[0]-.5-(o<>1),u=s.zoom+1;let d=s.aabb.quadrant(l);if(t.terrain){const o=new e.S(u,s.wrap,u,h,c),r=t.terrain.getMinMaxElevation(o),n=null!==(i=r.minElevation)&&void 0!==i?i:this.elevation,l=null!==(a=r.maxElevation)&&void 0!==a?a:this.elevation;d=new ya([d.min[0],d.min[1],n],[d.max[0],d.max[1],l]);}m.push({aabb:d,zoom:u,x:h,y:c,wrap:s.wrap,fullyVisible:n});}}return f.sort(((t,e)=>t.distanceSq-e.distanceSq)).map((t=>t.tileID))}resize(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices();}get unmodified(){return this._unmodified}zoomScale(t){return Math.pow(2,t)}scaleZoom(t){return Math.log(t)/Math.LN2}project(t){const i=e.ac(t.lat,-85.051129,wa);return new e.P(e.O(t.lng)*this.worldSize,e.Q(i)*this.worldSize)}unproject(t){return new e.Z(t.x/this.worldSize,t.y/this.worldSize).toLngLat()}get point(){return this.project(this.center)}getCameraPosition(){return {lngLat:this.pointLocation(this.getCameraPoint()),altitude:Math.cos(this._pitch)*this.cameraToCenterDistance/this._pixelPerMeter+this.elevation}}recalculateZoom(t){const i=this.elevation,a=Math.cos(this._pitch)*this.cameraToCenterDistance/this._pixelPerMeter,s=this.pointLocation(this.centerPoint,t),o=t.getElevationForLngLatZoom(s,this.tileZoom);if(!(this.elevation-o))return;const r=a+i-o,n=Math.cos(this._pitch)*this.cameraToCenterDistance/r/e.b5(1,s.lat),l=this.scaleZoom(n/this.tileSize);this._elevation=o,this._center=s,this.zoom=l;}setLocationAtPoint(t,i){const a=this.pointCoordinate(i),s=this.pointCoordinate(this.centerPoint),o=this.locationCoordinate(t),r=new e.Z(o.x-(a.x-s.x),o.y-(a.y-s.y));this.center=this.coordinateLocation(r),this._renderWorldCopies&&(this.center=this.center.wrap());}locationPoint(t,e){return e?this.coordinatePoint(this.locationCoordinate(t),e.getElevationForLngLatZoom(t,this.tileZoom),this.pixelMatrix3D):this.coordinatePoint(this.locationCoordinate(t))}pointLocation(t,e){return this.coordinateLocation(this.pointCoordinate(t,e))}locationCoordinate(t){return e.Z.fromLngLat(t)}coordinateLocation(t){return t&&t.toLngLat()}pointCoordinate(t,i){if(i){const e=i.pointCoordinate(t);if(null!=e)return e}const a=[t.x,t.y,0,1],s=[t.x,t.y,1,1];e.af(a,a,this.pixelMatrixInverse),e.af(s,s,this.pixelMatrixInverse);const o=a[3],r=s[3],n=a[1]/o,l=s[1]/r,h=a[2]/o,c=s[2]/r,u=h===c?0:(0-h)/(c-h);return new e.Z(e.y.number(a[0]/o,s[0]/r,u)/this.worldSize,e.y.number(n,l,u)/this.worldSize)}coordinatePoint(t,i=0,a=this.pixelMatrix){const s=[t.x*this.worldSize,t.y*this.worldSize,i,1];return e.af(s,s,a),new e.P(s[0]/s[3],s[1]/s[3])}getBounds(){const t=Math.max(0,this.height/2-this.getHorizon());return (new H).extend(this.pointLocation(new e.P(0,t))).extend(this.pointLocation(new e.P(this.width,t))).extend(this.pointLocation(new e.P(this.width,this.height))).extend(this.pointLocation(new e.P(0,this.height)))}getMaxBounds(){return this.latRange&&2===this.latRange.length&&this.lngRange&&2===this.lngRange.length?new H([this.lngRange[0],this.latRange[0]],[this.lngRange[1],this.latRange[1]]):null}getHorizon(){return Math.tan(Math.PI/2-this._pitch)*this.cameraToCenterDistance*.85}setMaxBounds(t){t?(this.lngRange=[t.getWest(),t.getEast()],this.latRange=[t.getSouth(),t.getNorth()],this._constrain()):(this.lngRange=null,this.latRange=[-85.051129,wa]);}calculateTileMatrix(t){const i=t.canonical,a=this.worldSize/this.zoomScale(i.z),s=i.x+Math.pow(2,i.z)*t.wrap,o=e.an(new Float64Array(16));return e.J(o,o,[s*a,i.y*a,0]),e.K(o,o,[a/e.X,a/e.X,1]),o}calculatePosMatrix(t,i=!1){const a=t.key,s=i?this._alignedPosMatrixCache:this._posMatrixCache;if(s[a])return s[a];const o=this.calculateTileMatrix(t);return e.L(o,i?this.alignedModelViewProjectionMatrix:this.modelViewProjectionMatrix,o),s[a]=new Float32Array(o),s[a]}calculateFogMatrix(t){const i=t.key,a=this._fogMatrixCache;if(a[i])return a[i];const s=this.calculateTileMatrix(t);return e.L(s,this.fogMatrix,s),a[i]=new Float32Array(s),a[i]}customLayerMatrix(){return this.mercatorMatrix.slice()}getConstrained(t,i){i=e.ac(+i,this.minZoom,this.maxZoom);const a={center:new e.N(t.lng,t.lat),zoom:i};let s=this.lngRange;if(!this._renderWorldCopies&&null===s){const t=180-1e-10;s=[-t,t];}const o=this.tileSize*this.zoomScale(a.zoom);let r=0,n=o,l=0,h=o,c=0,u=0;const{x:d,y:_}=this.size;if(this.latRange){const t=this.latRange;r=e.Q(t[1])*o,n=e.Q(t[0])*o,n-r<_&&(c=_/(n-r));}s&&(l=e.b3(e.O(s[0])*o,0,o),h=e.b3(e.O(s[1])*o,0,o),hn&&(g=n-t);}if(s){const t=(l+h)/2;let i=p;this._renderWorldCopies&&(i=e.b3(p,t-o/2,t+o/2));const a=d/2;i-ah&&(f=h-a);}if(void 0!==f||void 0!==g){const t=new e.P(null!=f?f:p,null!=g?g:m);a.center=this.unproject.call({worldSize:o},t).wrap();}return a}_constrain(){if(!this.center||!this.width||!this.height||this._constraining)return;this._constraining=!0;const t=this._unmodified,{center:e,zoom:i}=this.getConstrained(this.center,this.zoom);this.center=e,this.zoom=i,this._unmodified=t,this._constraining=!1;}_calcMatrices(){if(!this.height)return;const t=this.centerOffset,i=this.point.x,a=this.point.y;this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height,this._pixelPerMeter=e.b5(1,this.center.lat)*this.worldSize;let s=e.an(new Float64Array(16));e.K(s,s,[this.width/2,-this.height/2,1]),e.J(s,s,[1,-1,0]),this.labelPlaneMatrix=s,s=e.an(new Float64Array(16)),e.K(s,s,[1,-1,1]),e.J(s,s,[-1,-1,0]),e.K(s,s,[2/this.width,2/this.height,1]),this.glCoordMatrix=s;const o=this.cameraToCenterDistance+this._elevation*this._pixelPerMeter/Math.cos(this._pitch),r=Math.min(this.elevation,this.minElevationForCurrentTile),n=o-r*this._pixelPerMeter/Math.cos(this._pitch),l=r<0?n:o,h=Math.PI/2+this._pitch,c=this._fov*(.5+t.y/this.height),u=Math.sin(c)*l/Math.sin(e.ac(Math.PI-h-c,.01,Math.PI-.01)),d=this.getHorizon(),_=2*Math.atan(d/this.cameraToCenterDistance)*(.5+t.y/(2*d)),p=Math.sin(_)*l/Math.sin(e.ac(Math.PI-h-_,.01,Math.PI-.01)),m=Math.min(u,p);this.farZ=1.01*(Math.cos(Math.PI/2-this._pitch)*m+l),this.nearZ=this.height/50,s=new Float64Array(16),e.b6(s,this._fov,this.width/this.height,this.nearZ,this.farZ),s[8]=2*-t.x/this.width,s[9]=2*t.y/this.height,this.projectionMatrix=e.ae(s),e.K(s,s,[1,-1,1]),e.J(s,s,[0,0,-this.cameraToCenterDistance]),e.b7(s,s,this._pitch),e.ad(s,s,this.angle),e.J(s,s,[-i,-a,0]),this.mercatorMatrix=e.K([],s,[this.worldSize,this.worldSize,this.worldSize]),e.K(s,s,[1,1,this._pixelPerMeter]),this.pixelMatrix=e.L(new Float64Array(16),this.labelPlaneMatrix,s),e.J(s,s,[0,0,-this.elevation]),this.modelViewProjectionMatrix=s,this.invModelViewProjectionMatrix=e.as([],s),this.fogMatrix=new Float64Array(16),e.b6(this.fogMatrix,this._fov,this.width/this.height,o,this.farZ),this.fogMatrix[8]=2*-t.x/this.width,this.fogMatrix[9]=2*t.y/this.height,e.K(this.fogMatrix,this.fogMatrix,[1,-1,1]),e.J(this.fogMatrix,this.fogMatrix,[0,0,-this.cameraToCenterDistance]),e.b7(this.fogMatrix,this.fogMatrix,this._pitch),e.ad(this.fogMatrix,this.fogMatrix,this.angle),e.J(this.fogMatrix,this.fogMatrix,[-i,-a,0]),e.K(this.fogMatrix,this.fogMatrix,[1,1,this._pixelPerMeter]),e.J(this.fogMatrix,this.fogMatrix,[0,0,-this.elevation]),this.pixelMatrix3D=e.L(new Float64Array(16),this.labelPlaneMatrix,s);const f=this.width%2/2,g=this.height%2/2,v=Math.cos(this.angle),x=Math.sin(this.angle),y=i-Math.round(i)+v*f+x*g,b=a-Math.round(a)+v*g+x*f,w=new Float64Array(s);if(e.J(w,w,[y>.5?y-1:y,b>.5?b-1:b,0]),this.alignedModelViewProjectionMatrix=w,s=e.as(new Float64Array(16),this.pixelMatrix),!s)throw new Error("failed to invert matrix");this.pixelMatrixInverse=s,this._posMatrixCache={},this._alignedPosMatrixCache={},this._fogMatrixCache={};}maxPitchScaleFactor(){if(!this.pixelMatrixInverse)return 1;const t=this.pointCoordinate(new e.P(0,0)),i=[t.x*this.worldSize,t.y*this.worldSize,0,1];return e.af(i,i,this.pixelMatrix)[3]/this.cameraToCenterDistance}getCameraPoint(){const t=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new e.P(0,t))}getCameraQueryGeometry(t){const i=this.getCameraPoint();if(1===t.length)return [t[0],i];{let a=i.x,s=i.y,o=i.x,r=i.y;for(const e of t)a=Math.min(a,e.x),s=Math.min(s,e.y),o=Math.max(o,e.x),r=Math.max(r,e.y);return [new e.P(a,s),new e.P(o,s),new e.P(o,r),new e.P(a,r),new e.P(a,s)]}}lngLatToCameraDepth(t,i){const a=this.locationCoordinate(t),s=[a.x*this.worldSize,a.y*this.worldSize,i,1];return e.af(s,s,this.modelViewProjectionMatrix),s[2]/s[3]}}function Ia(t,e){let i,a=!1,s=null,o=null;const r=()=>{s=null,a&&(t.apply(o,i),s=setTimeout(r,e),a=!1);};return (...t)=>(a=!0,o=this,i=t,s||r(),s)}class Ea{constructor(t){this._getCurrentHash=()=>{const t=window.location.hash.replace("#","");if(this._hashName){let e;return t.split("&").map((t=>t.split("="))).forEach((t=>{t[0]===this._hashName&&(e=t);})),(e&&e[1]||"").split("/")}return t.split("/")},this._onHashChange=()=>{const t=this._getCurrentHash();if(t.length>=3&&!t.some((t=>isNaN(t)))){const e=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(t[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:e,pitch:+(t[4]||0)}),!0}return !1},this._updateHashUnthrottled=()=>{const t=window.location.href.replace(/(#.+)?$/,this.getHashString());window.history.replaceState(window.history.state,null,t);},this._removeHash=()=>{const t=this._getCurrentHash();if(0===t.length)return;const e=t.join("/");let i=e;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${e}`);let a=window.location.hash.replace(i,"");a.startsWith("#&")?a=a.slice(0,1)+a.slice(2):"#"===a&&(a="");let s=window.location.href.replace(/(#.+)?$/,a);s=s.replace("&&","&"),window.history.replaceState(window.history.state,null,s);},this._updateHash=Ia(this._updateHashUnthrottled,300),this._hashName=t&&encodeURIComponent(t);}addTo(t){return this._map=t,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(t){const e=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,a=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),s=Math.pow(10,a),o=Math.round(e.lng*s)/s,r=Math.round(e.lat*s)/s,n=this._map.getBearing(),l=this._map.getPitch();let h="";if(h+=t?`/${o}/${r}/${i}`:`${i}/${r}/${o}`,(n||l)&&(h+="/"+Math.round(10*n)/10),l&&(h+=`/${Math.round(l)}`),this._hashName){const t=this._hashName;let e=!1;const i=window.location.hash.slice(1).split("&").map((i=>{const a=i.split("=")[0];return a===t?(e=!0,`${a}=${h}`):i})).filter((t=>t));return e||i.push(`${t}=${h}`),`#${i.join("&")}`}return `#${h}`}}const Pa={linearity:.3,easing:e.b8(0,0,.3,1)},Ca=e.e({deceleration:2500,maxSpeed:1400},Pa),Sa=e.e({deceleration:20,maxSpeed:1400},Pa),Da=e.e({deceleration:1e3,maxSpeed:360},Pa),za=e.e({deceleration:1e3,maxSpeed:90},Pa);class Ma{constructor(t){this._map=t,this.clear();}clear(){this._inertiaBuffer=[];}record(t){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:o.now(),settings:t});}_drainInertiaBuffer(){const t=this._inertiaBuffer,e=o.now();for(;t.length>0&&e-t[0].time>160;)t.shift();}_onMoveEnd(t){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,pan:new e.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:t}of this._inertiaBuffer)i.zoom+=t.zoomDelta||0,i.bearing+=t.bearingDelta||0,i.pitch+=t.pitchDelta||0,t.panDelta&&i.pan._add(t.panDelta),t.around&&(i.around=t.around),t.pinchAround&&(i.pinchAround=t.pinchAround);const a=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,s={};if(i.pan.mag()){const o=Ra(i.pan.mag(),a,e.e({},Ca,t||{}));s.offset=i.pan.mult(o.amount/i.pan.mag()),s.center=this._map.transform.center,Aa(s,o);}if(i.zoom){const t=Ra(i.zoom,a,Sa);s.zoom=this._map.transform.zoom+t.amount,Aa(s,t);}if(i.bearing){const t=Ra(i.bearing,a,Da);s.bearing=this._map.transform.bearing+e.ac(t.amount,-179,179),Aa(s,t);}if(i.pitch){const t=Ra(i.pitch,a,za);s.pitch=this._map.transform.pitch+t.amount,Aa(s,t);}if(s.zoom||s.bearing){const t=void 0===i.pinchAround?i.around:i.pinchAround;s.around=t?this._map.unproject(t):this._map.getCenter();}return this.clear(),e.e(s,{noMoveStart:!0})}}function Aa(t,e){(!t.duration||t.durationi.unproject(t))),l=o.reduce(((t,e,i,a)=>t.add(e.div(a.length))),new e.P(0,0));super(t,{points:o,point:l,lngLats:n,lngLat:i.unproject(l),originalEvent:a}),this._defaultPrevented=!1;}}class Fa extends e.k{preventDefault(){this._defaultPrevented=!0;}get defaultPrevented(){return this._defaultPrevented}constructor(t,e,i){super(t,{originalEvent:i}),this._defaultPrevented=!1;}}class Ba{constructor(t,e){this._map=t,this._clickTolerance=e.clickTolerance;}reset(){delete this._mousedownPos;}wheel(t){return this._firePreventable(new Fa(t.type,this._map,t))}mousedown(t,e){return this._mousedownPos=e,this._firePreventable(new ka(t.type,this._map,t))}mouseup(t){this._map.fire(new ka(t.type,this._map,t));}click(t,e){this._mousedownPos&&this._mousedownPos.dist(e)>=this._clickTolerance||this._map.fire(new ka(t.type,this._map,t));}dblclick(t){return this._firePreventable(new ka(t.type,this._map,t))}mouseover(t){this._map.fire(new ka(t.type,this._map,t));}mouseout(t){this._map.fire(new ka(t.type,this._map,t));}touchstart(t){return this._firePreventable(new La(t.type,this._map,t))}touchmove(t){this._map.fire(new La(t.type,this._map,t));}touchend(t){this._map.fire(new La(t.type,this._map,t));}touchcancel(t){this._map.fire(new La(t.type,this._map,t));}_firePreventable(t){if(this._map.fire(t),t.defaultPrevented)return {}}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Oa{constructor(t){this._map=t;}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent;}mousemove(t){this._map.fire(new ka(t.type,this._map,t));}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1;}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new ka("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(t){this._delayContextMenu?this._contextMenuEvent=t:this._ignoreContextMenu||this._map.fire(new ka(t.type,this._map,t)),this._map.listens("contextmenu")&&t.preventDefault();}isEnabled(){return !0}isActive(){return !1}enable(){}disable(){}}class Na{constructor(t){this._map=t;}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return {lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(t){return this.transform.pointLocation(e.P.convert(t),this._map.terrain)}}class Ua{constructor(t,e){this._map=t,this._tr=new Na(t),this._el=t.getCanvasContainer(),this._container=t.getContainer(),this._clickTolerance=e.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=!0);}disable(){this.isEnabled()&&(this._enabled=!1);}mousedown(t,e){this.isEnabled()&&t.shiftKey&&0===t.button&&(r.disableDrag(),this._startPos=this._lastPos=e,this._active=!0);}mousemoveWindow(t,e){if(!this._active)return;const i=e;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)t.fitScreenCoordinates(a,s,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",t);}keydown(t){this._active&&27===t.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",t));}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(r.remove(this._box),this._box=null),r.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(t,i){return this._map.fire(new e.k(t,{originalEvent:i}))}}function ja(t,e){if(t.length!==e.length)throw new Error(`The number of touches and points are not equal - touches ${t.length}, points ${e.length}`);const i={};for(let a=0;athis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=t.timeStamp),a.length===this.numTouches&&(this.centroid=function(t){const i=new e.P(0,0);for(const e of t)i._add(e);return i.div(t.length)}(i),this.touches=ja(a,i)));}touchmove(t,e,i){if(this.aborted||!this.centroid)return;const a=ja(i,e);for(const t in this.touches){const e=a[t];(!e||e.dist(this.touches[t])>30)&&(this.aborted=!0);}}touchend(t,e,i){if((!this.centroid||t.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){const t=!this.aborted&&this.centroid;if(this.reset(),t)return t}}}class Ga{constructor(t){this.singleTap=new Za(t),this.numTaps=t.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(t,e,i){this.singleTap.touchstart(t,e,i);}touchmove(t,e,i){this.singleTap.touchmove(t,e,i);}touchend(t,e,i){const a=this.singleTap.touchend(t,e,i);if(a){const e=t.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(a)<30;if(e&&i||this.reset(),this.count++,this.lastTime=t.timeStamp,this.lastTap=a,this.count===this.numTaps)return this.reset(),a}}}class qa{constructor(t){this._tr=new Na(t),this._zoomIn=new Ga({numTouches:1,numTaps:2}),this._zoomOut=new Ga({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(t,e,i){this._zoomIn.touchstart(t,e,i),this._zoomOut.touchstart(t,e,i);}touchmove(t,e,i){this._zoomIn.touchmove(t,e,i),this._zoomOut.touchmove(t,e,i);}touchend(t,e,i){const a=this._zoomIn.touchend(t,e,i),s=this._zoomOut.touchend(t,e,i),o=this._tr;return a?(this._active=!0,t.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:e=>e.easeTo({duration:300,zoom:o.zoom+1,around:o.unproject(a)},{originalEvent:t})}):s?(this._active=!0,t.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:e=>e.easeTo({duration:300,zoom:o.zoom-1,around:o.unproject(s)},{originalEvent:t})}):void 0}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class Va{constructor(t){this._enabled=!!t.enable,this._moveStateManager=t.moveStateManager,this._clickTolerance=t.clickTolerance||1,this._moveFunction=t.move,this._activateOnStart=!!t.activateOnStart,t.assignEvents(this),this.reset();}reset(t){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(t);}_move(...t){const e=this._moveFunction(...t);if(e.bearingDelta||e.pitchDelta||e.around||e.panDelta)return this._active=!0,e}dragStart(t,e){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(t)&&(this._moveStateManager.startMove(t),this._lastPoint=e.length?e[0]:e,this._activateOnStart&&this._lastPoint&&(this._active=!0));}dragMove(t,e){if(!this.isEnabled())return;const i=this._lastPoint;if(!i)return;if(t.preventDefault(),!this._moveStateManager.isValidMoveEvent(t))return void this.reset(t);const a=e.length?e[0]:e;return !this._moved&&a.dist(i){t.mousedown=t.dragStart,t.mousemoveWindow=t.dragMove,t.mouseup=t.dragEnd,t.contextmenu=t=>{t.preventDefault();};},Ka=({enable:t,clickTolerance:e,bearingDegreesPerPixelMoved:i=.8})=>{const a=new Wa({checkCorrectEvent:t=>0===r.mouseButton(t)&&t.ctrlKey||2===r.mouseButton(t)});return new Va({clickTolerance:e,move:(t,e)=>({bearingDelta:(e.x-t.x)*i}),moveStateManager:a,enable:t,assignEvents:Xa})},Ja=({enable:t,clickTolerance:e,pitchDegreesPerPixelMoved:i=-.5})=>{const a=new Wa({checkCorrectEvent:t=>0===r.mouseButton(t)&&t.ctrlKey||2===r.mouseButton(t)});return new Va({clickTolerance:e,move:(t,e)=>({pitchDelta:(e.y-t.y)*i}),moveStateManager:a,enable:t,assignEvents:Xa})};class Ya{constructor(t,e){this._clickTolerance=t.clickTolerance||1,this._map=e,this.reset();}reset(){this._active=!1,this._touches={},this._sum=new e.P(0,0);}_shouldBePrevented(t){return t<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(t,e,i){return this._calculateTransform(t,e,i)}touchmove(t,e,i){if(this._active){if(!this._shouldBePrevented(i.length))return t.preventDefault(),this._calculateTransform(t,e,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",t);}}touchend(t,e,i){this._calculateTransform(t,e,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(t,i,a){a.length>0&&(this._active=!0);const s=ja(a,i),o=new e.P(0,0),r=new e.P(0,0);let n=0;for(const t in s){const e=s[t],i=this._touches[t];i&&(o._add(e),r._add(e.sub(i)),n++,s[t]=e);}if(this._touches=s,this._shouldBePrevented(n)||!r.mag())return;const l=r.div(n);return this._sum._add(l),this._sum.mag()Math.abs(t.x)}class rs extends Qa{constructor(t){super(),this._currentTouchCount=0,this._map=t;}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints;}touchstart(t,e,i){super.touchstart(t,e,i),this._currentTouchCount=i.length;}_start(t){this._lastPoints=t,os(t[0].sub(t[1]))&&(this._valid=!1);}_move(t,e,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const a=t[0].sub(this._lastPoints[0]),s=t[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(a,s,i.timeStamp),this._valid?(this._lastPoints=t,this._active=!0,{pitchDelta:(a.y+s.y)/2*-.5}):void 0}gestureBeginsVertically(t,e,i){if(void 0!==this._valid)return this._valid;const a=t.mag()>=2,s=e.mag()>=2;if(!a&&!s)return;if(!a||!s)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;const o=t.y>0==e.y>0;return os(t)&&os(e)&&o}}const ns={panStep:100,bearingStep:15,pitchStep:10};class ls{constructor(t){this._tr=new Na(t);const e=ns;this._panStep=e.panStep,this._bearingStep=e.bearingStep,this._pitchStep=e.pitchStep,this._rotationDisabled=!1;}reset(){this._active=!1;}keydown(t){if(t.altKey||t.ctrlKey||t.metaKey)return;let e=0,i=0,a=0,s=0,o=0;switch(t.keyCode){case 61:case 107:case 171:case 187:e=1;break;case 189:case 109:case 173:e=-1;break;case 37:t.shiftKey?i=-1:(t.preventDefault(),s=-1);break;case 39:t.shiftKey?i=1:(t.preventDefault(),s=1);break;case 38:t.shiftKey?a=1:(t.preventDefault(),o=-1);break;case 40:t.shiftKey?a=-1:(t.preventDefault(),o=1);break;default:return}return this._rotationDisabled&&(i=0,a=0),{cameraAnimation:r=>{const n=this._tr;r.easeTo({duration:300,easeId:"keyboardHandler",easing:hs,zoom:e?Math.round(n.zoom)+e*(t.shiftKey?2:1):n.zoom,bearing:n.bearing+i*this._bearingStep,pitch:n.pitch+a*this._pitchStep,offset:[-s*this._panStep,-o*this._panStep],center:n.center},{originalEvent:t});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0;}enableRotation(){this._rotationDisabled=!1;}}function hs(t){return t*(2-t)}const cs=4.000244140625;class us{constructor(t,e){this._onTimeout=t=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(t);},this._map=t,this._tr=new Na(t),this._triggerRenderFrame=e,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=.0022222222222222222;}setZoomRate(t){this._defaultZoomRate=t;}setWheelZoomRate(t){this._wheelZoomRate=t;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||void 0!==this._finishTimeout}isZooming(){return !!this._zooming}enable(t){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!t&&"center"===t.around);}disable(){this.isEnabled()&&(this._enabled=!1);}_shouldBePrevented(t){return !!this._map.cooperativeGestures.isEnabled()&&!(t.ctrlKey||this._map.cooperativeGestures.isBypassed(t))}wheel(t){if(!this.isEnabled())return;if(this._shouldBePrevented(t))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",t);let e=t.deltaMode===WheelEvent.DOM_DELTA_LINE?40*t.deltaY:t.deltaY;const i=o.now(),a=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==e&&e%cs==0?this._type="wheel":0!==e&&Math.abs(e)<4?this._type="trackpad":a>400?(this._type=null,this._lastValue=e,this._timeout=setTimeout(this._onTimeout,40,t)):this._type||(this._type=Math.abs(a*e)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,e+=this._lastValue)),t.shiftKey&&e&&(e/=4),this._type&&(this._lastWheelEvent=t,this._delta-=e,this._active||this._start(t)),t.preventDefault();}_start(t){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=r.mousePos(this._map.getCanvas(),t),a=this._tr;this._around=i.y>a.transform.height/2-a.transform.getHorizon()?e.N.convert(this._aroundCenter?a.center:a.unproject(i)):e.N.convert(a.center),this._aroundPoint=a.transform.locationPoint(this._around),this._frameId||(this._frameId=!0,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const t=this._tr.transform;if(0!==this._delta){const e="wheel"===this._type&&Math.abs(this._delta)>cs?this._wheelZoomRate:this._defaultZoomRate;let i=2/(1+Math.exp(-Math.abs(this._delta*e)));this._delta<0&&0!==i&&(i=1/i);const a="number"==typeof this._targetZoom?t.zoomScale(this._targetZoom):t.scale;this._targetZoom=Math.min(t.maxZoom,Math.max(t.minZoom,t.scaleZoom(a*i))),"wheel"===this._type&&(this._startZoom=t.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"==typeof this._targetZoom?this._targetZoom:t.zoom,a=this._startZoom,s=this._easing;let r,n=!1;const l=o.now()-this._lastWheelEventTime;if("wheel"===this._type&&a&&s&&l){const t=Math.min(l/200,1),o=s(t);r=e.y.number(a,i,o),t<1?this._frameId||(this._frameId=!0):n=!0;}else r=i,n=!0;return this._active=!0,n&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout;}),200)),{noInertia:!0,needsRenderFrame:!n,zoomDelta:r-t.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(t){let i=e.b9;if(this._prevEase){const t=this._prevEase,a=(o.now()-t.start)/t.duration,s=t.easing(a+.01)-t.easing(a),r=.27/Math.sqrt(s*s+1e-4)*.01,n=Math.sqrt(.0729-r*r);i=e.b8(r,n,.25,1);}return this._prevEase={start:o.now(),duration:t,easing:i},i}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class ds{constructor(t,e){this._clickZoom=t,this._tapZoom=e;}enable(){this._clickZoom.enable(),this._tapZoom.enable();}disable(){this._clickZoom.disable(),this._tapZoom.disable();}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class _s{constructor(t){this._tr=new Na(t),this.reset();}reset(){this._active=!1;}dblclick(t,e){return t.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(t.shiftKey?-1:1),around:this._tr.unproject(e)},{originalEvent:t});}}}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ps{constructor(){this._tap=new Ga({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(t,e,i){if(!this._swipePoint)if(this._tapTime){const a=e[0],s=t.timeStamp-this._tapTime<500,o=this._tapPoint.dist(a)<30;s&&o?i.length>0&&(this._swipePoint=a,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(t,e,i);}touchmove(t,e,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const a=e[0],s=a.y-this._swipePoint.y;return this._swipePoint=a,t.preventDefault(),this._active=!0,{zoomDelta:s/128}}}else this._tap.touchmove(t,e,i);}touchend(t,e,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const a=this._tap.touchend(t,e,i);a&&(this._tapTime=t.timeStamp,this._tapPoint=a);}}touchcancel(){this.reset();}enable(){this._enabled=!0;}disable(){this._enabled=!1,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ms{constructor(t,e,i){this._el=t,this._mousePan=e,this._touchPan=i;}enable(t){this._inertiaOptions=t||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan");}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan");}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class fs{constructor(t,e,i){this._pitchWithRotate=t.pitchWithRotate,this._mouseRotate=e,this._mousePitch=i;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}}class gs{constructor(t,e,i,a){this._el=t,this._touchZoom=e,this._touchRotate=i,this._tapDragZoom=a,this._rotationDisabled=!1,this._enabled=!0;}enable(t){this._touchZoom.enable(t),this._rotationDisabled||this._touchRotate.enable(t),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate");}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate");}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class vs{constructor(t,e){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=t,this._options=e,this._enabled=!1;}isActive(){return !1}reset(){}_setupUI(){if(this._container)return;const t=this._map.getCanvasContainer();t.classList.add("maplibregl-cooperative-gestures"),this._container=r.create("div","maplibregl-cooperative-gesture-screen",t);let e=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(e=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),a=document.createElement("div");a.className="maplibregl-desktop-message",a.textContent=e,this._container.appendChild(a);const s=document.createElement("div");s.className="maplibregl-mobile-message",s.textContent=i,this._container.appendChild(s),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(r.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=!0;}disable(){this._enabled=!1,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(t){return t[this._bypassKey]}notifyGestureBlocked(t,i){this._enabled&&(this._map.fire(new e.k("cooperativegestureprevented",{gestureType:t,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const xs=t=>t.zoom||t.drag||t.pitch||t.rotate;class ys extends e.k{}function bs(t){return t.panDelta&&t.panDelta.mag()||t.zoomDelta||t.bearingDelta||t.pitchDelta}class ws{constructor(t,e){this.handleWindowEvent=t=>{this.handleEvent(t,`${t.type}Window`);},this.handleEvent=(t,e)=>{if("blur"===t.type)return void this.stop(!0);this._updatingCamera=!0;const i="renderFrame"===t.type?void 0:t,a={needsRenderFrame:!1},s={},o={},n=t.touches,l=n?this._getMapTouches(n):void 0,h=l?r.touchPos(this._map.getCanvas(),l):r.mousePos(this._map.getCanvas(),t);for(const{handlerName:r,handler:n,allowed:c}of this._handlers){if(!n.isEnabled())continue;let u;this._blockedByActive(o,c,r)?n.reset():n[e||t.type]&&(u=n[e||t.type](t,h,l),this.mergeHandlerResult(a,s,u,r,i),u&&u.needsRenderFrame&&this._triggerRenderFrame()),(u||n.isActive())&&(o[r]=n);}const c={};for(const t in this._previousActiveHandlers)o[t]||(c[t]=i);this._previousActiveHandlers=o,(Object.keys(c).length||bs(a))&&(this._changes.push([a,s,c]),this._triggerRenderFrame()),(Object.keys(o).length||bs(a))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:u}=a;u&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],u(this._map));},this._map=t,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Ma(t),this._bearingSnap=e.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(e);const i=this._el;this._listeners=[[i,"touchstart",{passive:!0}],[i,"touchmove",{passive:!1}],[i,"touchend",void 0],[i,"touchcancel",void 0],[i,"mousedown",void 0],[i,"mousemove",void 0],[i,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[i,"mouseover",void 0],[i,"mouseout",void 0],[i,"dblclick",void 0],[i,"click",void 0],[i,"keydown",{capture:!1}],[i,"keyup",void 0],[i,"wheel",{passive:!1}],[i,"contextmenu",void 0],[window,"blur",void 0]];for(const[t,e,i]of this._listeners)r.addEventListener(t,e,t===document?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[t,e,i]of this._listeners)r.removeEventListener(t,e,t===document?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(t){const e=this._map,i=e.getCanvasContainer();this._add("mapEvent",new Ba(e,t));const a=e.boxZoom=new Ua(e,t);this._add("boxZoom",a),t.interactive&&t.boxZoom&&a.enable();const s=e.cooperativeGestures=new vs(e,t.cooperativeGestures);this._add("cooperativeGestures",s),t.cooperativeGestures&&s.enable();const o=new qa(e),n=new _s(e);e.doubleClickZoom=new ds(n,o),this._add("tapZoom",o),this._add("clickZoom",n),t.interactive&&t.doubleClickZoom&&e.doubleClickZoom.enable();const l=new ps;this._add("tapDragZoom",l);const h=e.touchPitch=new rs(e);this._add("touchPitch",h),t.interactive&&t.touchPitch&&e.touchPitch.enable(t.touchPitch);const c=Ka(t),u=Ja(t);e.dragRotate=new fs(t,c,u),this._add("mouseRotate",c,["mousePitch"]),this._add("mousePitch",u,["mouseRotate"]),t.interactive&&t.dragRotate&&e.dragRotate.enable();const d=(({enable:t,clickTolerance:e})=>{const i=new Wa({checkCorrectEvent:t=>0===r.mouseButton(t)&&!t.ctrlKey});return new Va({clickTolerance:e,move:(t,e)=>({around:e,panDelta:e.sub(t)}),activateOnStart:!0,moveStateManager:i,enable:t,assignEvents:Xa})})(t),_=new Ya(t,e);e.dragPan=new ms(i,d,_),this._add("mousePan",d),this._add("touchPan",_,["touchZoom","touchRotate"]),t.interactive&&t.dragPan&&e.dragPan.enable(t.dragPan);const p=new ss,m=new is;e.touchZoomRotate=new gs(i,m,p,l),this._add("touchRotate",p,["touchPan","touchZoom"]),this._add("touchZoom",m,["touchPan","touchRotate"]),t.interactive&&t.touchZoomRotate&&e.touchZoomRotate.enable(t.touchZoomRotate);const f=e.scrollZoom=new us(e,(()=>this._triggerRenderFrame()));this._add("scrollZoom",f,["mousePan"]),t.interactive&&t.scrollZoom&&e.scrollZoom.enable(t.scrollZoom);const g=e.keyboard=new ls(e);this._add("keyboard",g),t.interactive&&t.keyboard&&e.keyboard.enable(),this._add("blockableMapEvent",new Oa(e));}_add(t,e,i){this._handlers.push({handlerName:t,handler:e,allowed:i}),this._handlersById[t]=e;}stop(t){if(!this._updatingCamera){for(const{handler:t}of this._handlers)t.reset();this._inertia.clear(),this._fireEvents({},{},t),this._changes=[];}}isActive(){for(const{handler:t}of this._handlers)if(t.isActive())return !0;return !1}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(xs(this._eventsInProgress))||this.isZooming()}_blockedByActive(t,e,i){for(const a in t)if(a!==i&&(!e||e.indexOf(a)<0))return !0;return !1}_getMapTouches(t){const e=[];for(const i of t)this._el.contains(i.target)&&e.push(i);return e}mergeHandlerResult(t,i,a,s,o){if(!a)return;e.e(t,a);const r={handlerName:s,originalEvent:a.originalEvent||o};void 0!==a.zoomDelta&&(i.zoom=r),void 0!==a.panDelta&&(i.drag=r),void 0!==a.pitchDelta&&(i.pitch=r),void 0!==a.bearingDelta&&(i.rotate=r);}_applyChanges(){const t={},i={},a={};for(const[s,o,r]of this._changes)s.panDelta&&(t.panDelta=(t.panDelta||new e.P(0,0))._add(s.panDelta)),s.zoomDelta&&(t.zoomDelta=(t.zoomDelta||0)+s.zoomDelta),s.bearingDelta&&(t.bearingDelta=(t.bearingDelta||0)+s.bearingDelta),s.pitchDelta&&(t.pitchDelta=(t.pitchDelta||0)+s.pitchDelta),void 0!==s.around&&(t.around=s.around),void 0!==s.pinchAround&&(t.pinchAround=s.pinchAround),s.noInertia&&(t.noInertia=s.noInertia),e.e(i,o),e.e(a,r);this._updateMapTransform(t,i,a),this._changes=[];}_updateMapTransform(t,e,i){const a=this._map,s=a._getTransformForUpdate(),o=a.terrain;if(!(bs(t)||o&&this._terrainMovement))return this._fireEvents(e,i,!0);let{panDelta:r,zoomDelta:n,bearingDelta:l,pitchDelta:h,around:c,pinchAround:u}=t;void 0!==u&&(c=u),a._stop(!0),c=c||a.transform.centerPoint;const d=s.pointLocation(r?c.sub(r):c);l&&(s.bearing+=l),h&&(s.pitch+=h),n&&(s.zoom+=n),o?this._terrainMovement||!e.drag&&!e.zoom?e.drag&&this._terrainMovement?s.center=s.pointLocation(s.centerPoint.sub(r)):s.setLocationAtPoint(d,c):(this._terrainMovement=!0,this._map._elevationFreeze=!0,s.setLocationAtPoint(d,c)):s.setLocationAtPoint(d,c),a._applyUpdatedTransform(s),this._map._update(),t.noInertia||this._inertia.record(t),this._fireEvents(e,i,!0);}_fireEvents(t,i,a){const s=xs(this._eventsInProgress),r=xs(t),n={};for(const e in t){const{originalEvent:i}=t[e];this._eventsInProgress[e]||(n[`${e}start`]=i),this._eventsInProgress[e]=t[e];}!s&&r&&this._fireEvent("movestart",r.originalEvent);for(const t in n)this._fireEvent(t,n[t]);r&&this._fireEvent("move",r.originalEvent);for(const e in t){const{originalEvent:i}=t[e];this._fireEvent(e,i);}const l={};let h;for(const t in this._eventsInProgress){const{handlerName:e,originalEvent:a}=this._eventsInProgress[t];this._handlersById[e].isActive()||(delete this._eventsInProgress[t],h=i[e]||a,l[`${t}end`]=h);}for(const t in l)this._fireEvent(t,l[t]);const c=xs(this._eventsInProgress),u=(s||r)&&!c;if(u&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const t=this._map._getTransformForUpdate();t.recalculateZoom(this._map.terrain),this._map._applyUpdatedTransform(t);}if(a&&u){this._updatingCamera=!0;const t=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=t=>0!==t&&-this._bearingSnap{delete this._frameId,this.handleEvent(new ys("renderFrame",{timeStamp:t})),this._applyChanges();}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame());}}class Ts extends e.E{constructor(t,e){super(),this._renderFrameCallback=()=>{const t=Math.min((o.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(t)),t<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=!1,this._zooming=!1,this.transform=t,this._bearingSnap=e.bearingSnap,this.on("moveend",(()=>{delete this._requestedCameraState;}));}getCenter(){return new e.N(this.transform.center.lng,this.transform.center.lat)}setCenter(t,e){return this.jumpTo({center:t},e)}panBy(t,i,a){return t=e.P.convert(t).mult(-1),this.panTo(this.transform.center,e.e({offset:t},i),a)}panTo(t,i,a){return this.easeTo(e.e({center:t},i),a)}getZoom(){return this.transform.zoom}setZoom(t,e){return this.jumpTo({zoom:t},e),this}zoomTo(t,i,a){return this.easeTo(e.e({zoom:t},i),a)}zoomIn(t,e){return this.zoomTo(this.getZoom()+1,t,e),this}zoomOut(t,e){return this.zoomTo(this.getZoom()-1,t,e),this}getBearing(){return this.transform.bearing}setBearing(t,e){return this.jumpTo({bearing:t},e),this}getPadding(){return this.transform.padding}setPadding(t,e){return this.jumpTo({padding:t},e),this}rotateTo(t,i,a){return this.easeTo(e.e({bearing:t},i),a)}resetNorth(t,i){return this.rotateTo(0,e.e({duration:1e3},t),i),this}resetNorthPitch(t,i){return this.easeTo(e.e({bearing:0,pitch:0,duration:1e3},t),i),this}snapToNorth(t,e){return Math.abs(this.getBearing()){if(this._zooming&&(s.zoom=e.y.number(r,g,a)),this._rotating&&(s.bearing=e.y.number(n,c,a)),this._pitching&&(s.pitch=e.y.number(l,u,a)),this._padding&&(s.interpolatePadding(h,d,a),p=s.centerPoint.add(_)),this.terrain&&!t.freezeElevation&&this._updateElevation(a),b)s.setLocationAtPoint(b,w);else {const t=s.zoomScale(s.zoom-r),e=g>r?Math.min(2,y):Math.max(.5,y),i=Math.pow(e,1-a),o=s.unproject(v.add(x.mult(a*i)).mult(t));s.setLocationAtPoint(s.renderWorldCopies?o.wrap():o,p);}this._applyUpdatedTransform(s),this._fireMoveEvents(i);}),(e=>{this.terrain&&t.freezeElevation&&this._finalizeElevation(),this._afterEase(i,e);}),t),this}_prepareEase(t,i,a={}){this._moving=!0,i||a.moving||this.fire(new e.k("movestart",t)),this._zooming&&!a.zooming&&this.fire(new e.k("zoomstart",t)),this._rotating&&!a.rotating&&this.fire(new e.k("rotatestart",t)),this._pitching&&!a.pitching&&this.fire(new e.k("pitchstart",t));}_prepareElevation(t){this._elevationCenter=t,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(t,this.transform.tileZoom),this._elevationFreeze=!0;}_updateElevation(t){this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(t<1&&i!==this._elevationTarget){const e=this._elevationTarget-this._elevationStart;this._elevationStart+=t*(e-(i-(e*t+this._elevationStart))/(1-t)),this._elevationTarget=i;}this.transform.elevation=e.y.number(this._elevationStart,this._elevationTarget,t);}_finalizeElevation(){this._elevationFreeze=!1,this.transform.recalculateZoom(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(t){const e=t.getCameraPosition(),i=this.terrain.getElevationForLngLatZoom(e.lngLat,t.zoom);if(e.altitudethis._elevateCameraIfInsideTerrain(t))),this.transformCameraUpdate&&e.push((t=>this.transformCameraUpdate(t))),!e.length)return;const i=t.clone();for(const t of e){const e=i.clone(),{center:a,zoom:s,pitch:o,bearing:r,elevation:n}=t(e);a&&(e.center=a),void 0!==s&&(e.zoom=s),void 0!==o&&(e.pitch=o),void 0!==r&&(e.bearing=r),void 0!==n&&(e.elevation=n),i.apply(e);}this.transform.apply(i);}_fireMoveEvents(t){this.fire(new e.k("move",t)),this._zooming&&this.fire(new e.k("zoom",t)),this._rotating&&this.fire(new e.k("rotate",t)),this._pitching&&this.fire(new e.k("pitch",t));}_afterEase(t,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const a=this._zooming,s=this._rotating,o=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,a&&this.fire(new e.k("zoomend",t)),s&&this.fire(new e.k("rotateend",t)),o&&this.fire(new e.k("pitchend",t)),this.fire(new e.k("moveend",t));}flyTo(t,i){var a;if(!t.essential&&o.prefersReducedMotion){const a=e.M(t,["center","zoom","bearing","pitch","around"]);return this.jumpTo(a,i)}this.stop(),t=e.e({offset:[0,0],speed:1.2,curve:1.42,easing:e.b9},t);const s=this._getTransformForUpdate(),r=s.zoom,n=s.bearing,l=s.pitch,h=s.padding,c="bearing"in t?this._normalizeBearing(t.bearing,n):n,u="pitch"in t?+t.pitch:l,d="padding"in t?t.padding:s.padding,_=e.P.convert(t.offset);let p=s.centerPoint.add(_);const m=s.pointLocation(p),{center:f,zoom:g}=s.getConstrained(e.N.convert(t.center||m),null!==(a=t.zoom)&&void 0!==a?a:r);this._normalizeCenter(f,s);const v=s.zoomScale(g-r),x=s.project(m),y=s.project(f).sub(x);let b=t.curve;const w=Math.max(s.width,s.height),T=w/v,I=y.mag();if("minZoom"in t){const i=e.ac(Math.min(t.minZoom,r,g),s.minZoom,s.maxZoom),a=w/s.zoomScale(i-r);b=Math.sqrt(a/I*2);}const E=b*b;function P(t){const e=(T*T-w*w+(t?-1:1)*E*E*I*I)/(2*(t?T:w)*E*I);return Math.log(Math.sqrt(e*e+1)-e)}function C(t){return (Math.exp(t)-Math.exp(-t))/2}function S(t){return (Math.exp(t)+Math.exp(-t))/2}const D=P(!1);let z=function(t){return S(D)/S(D+b*t)},M=function(t){return w*((S(D)*(C(e=D+b*t)/S(e))-C(D))/E)/I;var e;},A=(P(!0)-D)/b;if(Math.abs(I)<1e-6||!isFinite(A)){if(Math.abs(w-T)<1e-6)return this.easeTo(t,i);const e=T0,z=t=>Math.exp(e*b*t);}return t.duration="duration"in t?+t.duration:1e3*A/("screenSpeed"in t?+t.screenSpeed/b:+t.speed),t.maxDuration&&t.duration>t.maxDuration&&(t.duration=0),this._zooming=!0,this._rotating=n!==c,this._pitching=u!==l,this._padding=!s.isPaddingEqual(d),this._prepareEase(i,!1),this.terrain&&this._prepareElevation(f),this._ease((a=>{const o=a*A,m=1/z(o);s.zoom=1===a?g:r+s.scaleZoom(m),this._rotating&&(s.bearing=e.y.number(n,c,a)),this._pitching&&(s.pitch=e.y.number(l,u,a)),this._padding&&(s.interpolatePadding(h,d,a),p=s.centerPoint.add(_)),this.terrain&&!t.freezeElevation&&this._updateElevation(a);const v=1===a?f:s.unproject(x.add(y.mult(M(o))).mult(m));s.setLocationAtPoint(s.renderWorldCopies?v.wrap():v,p),this._applyUpdatedTransform(s),this._fireMoveEvents(i);}),(()=>{this.terrain&&t.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),t),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(t,e){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const t=this._onEaseEnd;delete this._onEaseEnd,t.call(this,e);}return t||null===(i=this.handlers)||void 0===i||i.stop(!1),this}_ease(t,e,i){!1===i.animate||0===i.duration?(t(1),e()):(this._easeStart=o.now(),this._easeOptions=i,this._onEaseFrame=t,this._onEaseEnd=e,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(t,i){t=e.b3(t,-180,180);const a=Math.abs(t-i);return Math.abs(t-360-i)180?-360:i<-180?360:0;}queryTerrainElevation(t){return this.terrain?this.terrain.getElevationForLngLatZoom(e.N.convert(t),this.transform.tileZoom)-this.transform.elevation:null}}const Is={compact:!0,customAttribution:'MapLibre'};class Es{constructor(t=Is){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=t=>{!t||"metadata"!==t.sourceDataType&&"visibility"!==t.sourceDataType&&"style"!==t.dataType&&"terrain"!==t.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=t;}getDefaultPosition(){return "bottom-right"}onAdd(t){return this._map=t,this._compact=this.options.compact,this._container=r.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=r.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=r.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){r.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._attribHTML=void 0;}_setElementTitle(t,e){const i=this._map._getUIString(`AttributionControl.${e}`);t.title=i,t.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let t=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?t=t.concat(this.options.customAttribution.map((t=>"string"!=typeof t?"":t))):"string"==typeof this.options.customAttribution&&t.push(this.options.customAttribution)),this._map.style.stylesheet){const t=this._map.style.stylesheet;this.styleOwner=t.owner,this.styleId=t.id;}const e=this._map.style.sourceCaches;for(const i in e){const a=e[i];if(a.used||a.usedForTerrain){const e=a.getSource();e.attribution&&t.indexOf(e.attribution)<0&&t.push(e.attribution);}}t=t.filter((t=>String(t).trim())),t.sort(((t,e)=>t.length-e.length)),t=t.filter(((e,i)=>{for(let a=i+1;a=0)return !1;return !0}));const i=t.join(" | ");i!==this._attribHTML&&(this._attribHTML=i,t.length?(this._innerContainer.innerHTML=i,this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Ps{constructor(t={}){this._updateCompact=()=>{const t=this._container.children;if(t.length){const e=t[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&e.classList.add("maplibregl-compact"):e.classList.remove("maplibregl-compact");}},this.options=t;}getDefaultPosition(){return "bottom-left"}onAdd(t){this._map=t,this._compact=this.options&&this.options.compact,this._container=r.create("div","maplibregl-ctrl");const e=r.create("a","maplibregl-ctrl-logo");return e.target="_blank",e.rel="noopener nofollow",e.href="https://maplibre.org/",e.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),e.setAttribute("rel","noopener nofollow"),this._container.appendChild(e),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){r.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0;}}class Cs{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;}add(t){const e=++this._id;return this._queue.push({callback:t,id:e,cancelled:!1}),e}remove(t){const e=this._currentlyRunning,i=e?this._queue.concat(e):this._queue;for(const e of i)if(e.id===t)return void(e.cancelled=!0)}run(t=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const e=this._currentlyRunning=this._queue;this._queue=[];for(const i of e)if(!i.cancelled&&(i.callback(t),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1;}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];}}var Ss=e.Y([{name:"a_pos3d",type:"Int16",components:3}]);class Ds extends e.E{constructor(t){super(),this.sourceCache=t,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.deltaZoom=1,t.usedForTerrain=!0,t.tileSize=this.tileSize*2**this.deltaZoom;}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null;}update(t,i){this.sourceCache.update(t,i),this._renderableTilesKeys=[];const a={};for(const s of t.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:i}))a[s.key]=!0,this._renderableTilesKeys.push(s.key),this._tiles[s.key]||(s.posMatrix=new Float64Array(16),e.aP(s.posMatrix,0,e.X,0,e.X,0,1),this._tiles[s.key]=new lt(s,this.tileSize));for(const t in this._tiles)a[t]||delete this._tiles[t];}freeRtt(t){for(const e in this._tiles){const i=this._tiles[e];(!t||i.tileID.equals(t)||i.tileID.isChildOf(t)||t.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((t=>this.getTileByID(t)))}getTileByID(t){return this._tiles[t]}getTerrainCoords(t){const i={};for(const a of this._renderableTilesKeys){const s=this._tiles[a].tileID;if(s.canonical.equals(t.canonical)){const s=t.clone();s.posMatrix=new Float64Array(16),e.aP(s.posMatrix,0,e.X,0,e.X,0,1),i[a]=s;}else if(s.canonical.isChildOf(t.canonical)){const o=t.clone();o.posMatrix=new Float64Array(16);const r=s.canonical.z-t.canonical.z,n=s.canonical.x-(s.canonical.x>>r<>r<>r;e.aP(o.posMatrix,0,h,0,h,0,1),e.J(o.posMatrix,o.posMatrix,[-n*h,-l*h,0]),i[a]=o;}else if(t.canonical.isChildOf(s.canonical)){const o=t.clone();o.posMatrix=new Float64Array(16);const r=t.canonical.z-s.canonical.z,n=t.canonical.x-(t.canonical.x>>r<>r<>r;e.aP(o.posMatrix,0,e.X,0,e.X,0,1),e.J(o.posMatrix,o.posMatrix,[n*h,l*h,0]),e.K(o.posMatrix,o.posMatrix,[1/2**r,1/2**r,0]),i[a]=o;}}return i}getSourceTile(t,e){const i=this.sourceCache._source;let a=t.overscaledZ-this.deltaZoom;if(a>i.maxzoom&&(a=i.maxzoom),a=i.minzoom&&(!s||!s.dem);)s=this.sourceCache.getTileByID(t.scaledTo(a--).key);return s}tilesAfterTime(t=Date.now()){return Object.values(this._tiles).filter((e=>e.timeAdded>=t))}}class zs{constructor(t,e,i){this.painter=t,this.sourceCache=new Ds(e),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}getDEMElevation(t,i,a,s=e.X){var o;if(!(i>=0&&i=0&&at.canonical.z&&(t.canonical.z>=a?s=t.canonical.z-a:e.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const o=t.canonical.x-(t.canonical.x>>s<>s<>8<<4|t>>8,i[e+3]=0;const a=new e.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),s=new b(t,a,t.gl.RGBA,{premultiply:!1});return s.bind(t.gl.NEAREST,t.gl.CLAMP_TO_EDGE),this._coordsTexture=s,s}pointCoordinate(t){this.painter.maybeDrawDepthAndCoords(!0);const i=new Uint8Array(4),a=this.painter.context,s=a.gl,o=Math.round(t.x*this.painter.pixelRatio/devicePixelRatio),r=Math.round(t.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);a.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),s.readPixels(o,n-r-1,1,1,s.RGBA,s.UNSIGNED_BYTE,i),a.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),h=i[1]+((15&i[2])<<8),c=this.coordsIndex[255-i[3]],u=c&&this.sourceCache.getTileByID(c);if(!u)return null;const d=this._coordsTextureSize,_=(1<t.id!==e)),this._recentlyUsed.push(t.id);}stampObject(t){t.stamp=++this._stamp;}getOrCreateFreeObject(){for(const t of this._recentlyUsed)if(!this._objects[t].inUse)return this._objects[t];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const t=this._createObject(this._objects.length);return this._objects.push(t),t}freeObject(t){t.inUse=!1;}freeAllObjects(){for(const t of this._objects)this.freeObject(t);}isFull(){return !(this._objects.length!t.inUse))}}const As={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0};class Rs{constructor(t,e){this.painter=t,this.terrain=e,this.pool=new Ms(t.context,30,e.sourceCache.tileSize*e.qualityFactor);}destruct(){this.pool.destruct();}getTexture(t){return this.pool.getObjectForId(t.rtt[this._stacks.length-1].id).texture}prepareForRender(t,e){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=t._order.filter((i=>!t._layers[i].isHidden(e))),this._coordsDescendingInv={};for(const e in t.sourceCaches){this._coordsDescendingInv[e]={};const i=t.sourceCaches[e].getVisibleCoordinates();for(const t of i){const i=this.terrain.sourceCache.getTerrainCoords(t);for(const t in i)this._coordsDescendingInv[e][t]||(this._coordsDescendingInv[e][t]=[]),this._coordsDescendingInv[e][t].push(i[t]);}}this._coordsDescendingInvStr={};for(const e of t._order){const i=t._layers[e],a=i.source;if(As[i.type]&&!this._coordsDescendingInvStr[a]){this._coordsDescendingInvStr[a]={};for(const t in this._coordsDescendingInv[a])this._coordsDescendingInvStr[a][t]=this._coordsDescendingInv[a][t].map((t=>t.key)).sort().join();}}for(const t of this._renderableTiles)for(const e in this._coordsDescendingInvStr){const i=this._coordsDescendingInvStr[e][t.tileID.key];i&&i!==t.rttCoords[e]&&(t.rtt=[]);}}renderLayer(t){if(t.isHidden(this.painter.transform.zoom))return !1;const i=t.type,a=this.painter,s=this._renderableLayerIds[this._renderableLayerIds.length-1]===t.id;if(As[i]&&(this._prevType&&As[this._prevType]||this._stacks.push([]),this._prevType=i,this._stacks[this._stacks.length-1].push(t.id),!s))return !0;if(As[this._prevType]||As[i]&&s){this._prevType=i;const t=this._stacks.length-1,s=this._stacks[t]||[];for(const i of this._renderableTiles){if(this.pool.isFull()&&(fa(this.painter,this.terrain,this._rttTiles),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(i),i.rtt[t]){const e=this.pool.getObjectForId(i.rtt[t].id);if(e.stamp===i.rtt[t].stamp){this.pool.useObject(e);continue}}const o=this.pool.getOrCreateFreeObject();this.pool.useObject(o),this.pool.stampObject(o),i.rtt[t]={id:o.id,stamp:o.stamp},a.context.bindFramebuffer.set(o.fbo.framebuffer),a.context.clear({color:e.aM.transparent,stencil:0}),a.currentStencilSource=void 0;for(let t=0;t{t.touchstart=t.dragStart,t.touchmoveWindow=t.dragMove,t.touchend=t.dragEnd;},Os={showCompass:!0,showZoom:!0,visualizePitch:!1};class Ns{constructor(t,i,a=!1){this.mousedown=t=>{this.startMouse(e.e({},t,{ctrlKey:!0,preventDefault:()=>t.preventDefault()}),r.mousePos(this.element,t)),r.addEventListener(window,"mousemove",this.mousemove),r.addEventListener(window,"mouseup",this.mouseup);},this.mousemove=t=>{this.moveMouse(t,r.mousePos(this.element,t));},this.mouseup=t=>{this.mouseRotate.dragEnd(t),this.mousePitch&&this.mousePitch.dragEnd(t),this.offTemp();},this.touchstart=t=>{1!==t.targetTouches.length?this.reset():(this._startPos=this._lastPos=r.touchPos(this.element,t.targetTouches)[0],this.startTouch(t,this._startPos),r.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),r.addEventListener(window,"touchend",this.touchend));},this.touchmove=t=>{1!==t.targetTouches.length?this.reset():(this._lastPos=r.touchPos(this.element,t.targetTouches)[0],this.moveTouch(t,this._lastPos));},this.touchend=t=>{0===t.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this.mouseRotate.reset(),this.mousePitch&&this.mousePitch.reset(),this.touchRotate.reset(),this.touchPitch&&this.touchPitch.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10;const s=t.dragRotate._mouseRotate.getClickTolerance(),o=t.dragRotate._mousePitch.getClickTolerance();this.element=i,this.mouseRotate=Ka({clickTolerance:s,enable:!0}),this.touchRotate=(({enable:t,clickTolerance:e,bearingDegreesPerPixelMoved:i=.8})=>{const a=new $a;return new Va({clickTolerance:e,move:(t,e)=>({bearingDelta:(e.x-t.x)*i}),moveStateManager:a,enable:t,assignEvents:Bs})})({clickTolerance:s,enable:!0}),this.map=t,a&&(this.mousePitch=Ja({clickTolerance:o,enable:!0}),this.touchPitch=(({enable:t,clickTolerance:e,pitchDegreesPerPixelMoved:i=-.5})=>{const a=new $a;return new Va({clickTolerance:e,move:(t,e)=>({pitchDelta:(e.y-t.y)*i}),moveStateManager:a,enable:t,assignEvents:Bs})})({clickTolerance:o,enable:!0})),r.addEventListener(i,"mousedown",this.mousedown),r.addEventListener(i,"touchstart",this.touchstart,{passive:!1}),r.addEventListener(i,"touchcancel",this.reset);}startMouse(t,e){this.mouseRotate.dragStart(t,e),this.mousePitch&&this.mousePitch.dragStart(t,e),r.disableDrag();}startTouch(t,e){this.touchRotate.dragStart(t,e),this.touchPitch&&this.touchPitch.dragStart(t,e),r.disableDrag();}moveMouse(t,e){const i=this.map,{bearingDelta:a}=this.mouseRotate.dragMove(t,e)||{};if(a&&i.setBearing(i.getBearing()+a),this.mousePitch){const{pitchDelta:a}=this.mousePitch.dragMove(t,e)||{};a&&i.setPitch(i.getPitch()+a);}}moveTouch(t,e){const i=this.map,{bearingDelta:a}=this.touchRotate.dragMove(t,e)||{};if(a&&i.setBearing(i.getBearing()+a),this.touchPitch){const{pitchDelta:a}=this.touchPitch.dragMove(t,e)||{};a&&i.setPitch(i.getPitch()+a);}}off(){const t=this.element;r.removeEventListener(t,"mousedown",this.mousedown),r.removeEventListener(t,"touchstart",this.touchstart,{passive:!1}),r.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),r.removeEventListener(window,"touchend",this.touchend),r.removeEventListener(t,"touchcancel",this.reset),this.offTemp();}offTemp(){r.enableDrag(),r.removeEventListener(window,"mousemove",this.mousemove),r.removeEventListener(window,"mouseup",this.mouseup),r.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),r.removeEventListener(window,"touchend",this.touchend);}}let Us;function js(t,i,a){const s=new e.N(t.lng,t.lat);if(t=new e.N(t.lng,t.lat),i){const s=new e.N(t.lng-360,t.lat),o=new e.N(t.lng+360,t.lat),r=a.locationPoint(t).distSqr(i);a.locationPoint(s).distSqr(i)180;){const e=a.locationPoint(t);if(e.x>=0&&e.y>=0&&e.x<=a.width&&e.y<=a.height)break;t.lng>a.center.lng?t.lng-=360:t.lng+=360;}return t.lng!==s.lng&&a.locationPoint(t).y>a.height/2-a.getHorizon()?t:s}const Zs={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Gs(t,e,i){const a=t.classList;for(const t in Zs)a.remove(`maplibregl-${i}-anchor-${t}`);a.add(`maplibregl-${i}-anchor-${e}`);}class qs extends e.E{constructor(t){if(super(),this._onKeyPress=t=>{const e=t.code,i=t.charCode||t.keyCode;"Space"!==e&&"Enter"!==e&&32!==i&&13!==i||this.togglePopup();},this._onMapClick=t=>{const e=t.originalEvent.target,i=this._element;this._popup&&(e===i||i.contains(e))&&this.togglePopup();},this._update=t=>{var e;if(!this._map)return;const i=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==t?void 0:t.type)||"render"===(null==t?void 0:t.type)&&!i)&&this._map.once("render",this._update),this._lngLat=this._map.transform.renderWorldCopies?js(this._lngLat,this._flatPos,this._map.transform):null===(e=this._lngLat)||void 0===e?void 0:e.wrap(),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationPoint(this._lngLat)._add(this._offset));let a="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?a=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(a=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let s="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?s="rotateX(0deg)":"map"===this._pitchAlignment&&(s=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||t&&"moveend"!==t.type||(this._pos=this._pos.round()),r.setTransform(this._element,`${Zs[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${s} ${a}`),o.frameAsync(new AbortController).then((()=>{this._updateOpacity(t&&"moveend"===t.type);})).catch((()=>{}));},this._onMove=t=>{if(!this._isDragging){const e=this._clickTolerance||this._map._clickTolerance;this._isDragging=t.point.dist(this._pointerdownPos)>=e;}this._isDragging&&(this._pos=t.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new e.k("dragstart"))),this.fire(new e.k("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new e.k("dragend")),this._state="inactive";},this._addDragHandler=t=>{this._element.contains(t.originalEvent.target)&&(t.preventDefault(),this._positionDelta=t.point.sub(this._pos).add(this._offset),this._pointerdownPos=t.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},this._anchor=t&&t.anchor||"center",this._color=t&&t.color||"#3FB1CE",this._scale=t&&t.scale||1,this._draggable=t&&t.draggable||!1,this._clickTolerance=t&&t.clickTolerance||0,this._subpixelPositioning=t&&t.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=t&&t.rotation||0,this._rotationAlignment=t&&t.rotationAlignment||"auto",this._pitchAlignment=t&&t.pitchAlignment&&"auto"!==t.pitchAlignment?t.pitchAlignment:this._rotationAlignment,this.setOpacity(),this.setOpacity(null==t?void 0:t.opacity,null==t?void 0:t.opacityWhenCovered),t&&t.element)this._element=t.element,this._offset=e.P.convert(t&&t.offset||[0,0]);else {this._defaultMarker=!0,this._element=r.create("div");const i=r.createNS("http://www.w3.org/2000/svg","svg"),a=41,s=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${a}px`),i.setAttributeNS(null,"width",`${s}px`),i.setAttributeNS(null,"viewBox",`0 0 ${s} ${a}`);const o=r.createNS("http://www.w3.org/2000/svg","g");o.setAttributeNS(null,"stroke","none"),o.setAttributeNS(null,"stroke-width","1"),o.setAttributeNS(null,"fill","none"),o.setAttributeNS(null,"fill-rule","evenodd");const n=r.createNS("http://www.w3.org/2000/svg","g");n.setAttributeNS(null,"fill-rule","nonzero");const l=r.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"transform","translate(3.0, 29.0)"),l.setAttributeNS(null,"fill","#000000");const h=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const t of h){const e=r.createNS("http://www.w3.org/2000/svg","ellipse");e.setAttributeNS(null,"opacity","0.04"),e.setAttributeNS(null,"cx","10.5"),e.setAttributeNS(null,"cy","5.80029008"),e.setAttributeNS(null,"rx",t.rx),e.setAttributeNS(null,"ry",t.ry),l.appendChild(e);}const c=r.createNS("http://www.w3.org/2000/svg","g");c.setAttributeNS(null,"fill",this._color);const u=r.createNS("http://www.w3.org/2000/svg","path");u.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"),c.appendChild(u);const d=r.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");const _=r.createNS("http://www.w3.org/2000/svg","path");_.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"),d.appendChild(_);const p=r.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(6.0, 7.0)"),p.setAttributeNS(null,"fill","#FFFFFF");const m=r.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(8.0, 8.0)");const f=r.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#000000"),f.setAttributeNS(null,"opacity","0.25"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962");const g=r.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#FFFFFF"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962"),m.appendChild(f),m.appendChild(g),n.appendChild(l),n.appendChild(c),n.appendChild(d),n.appendChild(p),n.appendChild(m),i.appendChild(n),i.setAttributeNS(null,"height",a*this._scale+"px"),i.setAttributeNS(null,"width",s*this._scale+"px"),this._element.appendChild(i),this._offset=e.P.convert(t&&t.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(t=>{t.preventDefault();})),this._element.addEventListener("mousedown",(t=>{t.preventDefault();})),Gs(this._element,this._anchor,"marker"),t&&t.className)for(const e of t.className.split(" "))this._element.classList.add(e);this._popup=null;}addTo(t){return this.remove(),this._map=t,this._element.setAttribute("aria-label",t._getUIString("Marker.Title")),t.getCanvasContainer().appendChild(this._element),t.on("move",this._update),t.on("moveend",this._update),t.on("terrain",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),r.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(t){return this._lngLat=e.N.convert(t),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(t){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),t){if(!("offset"in t.options)){const e=38.1,i=13.5,a=Math.abs(i)/Math.SQRT2;t.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-e],"bottom-left":[a,-1*(e-i+a)],"bottom-right":[-a,-1*(e-i+a)],left:[i,-1*(e-i)],right:[-i,-1*(e-i)]}:this._offset;}this._popup=t,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(t){return this._subpixelPositioning=t,this}getPopup(){return this._popup}togglePopup(){const t=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:t?(t.isOpen()?t.remove():(t.setLngLat(this._lngLat),t.addTo(this._map)),this):this}_updateOpacity(t=!1){var i,a;if(!(null===(i=this._map)||void 0===i?void 0:i.terrain))return void(this._element.style.opacity!==this._opacity&&(this._element.style.opacity=this._opacity));if(t)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const s=this._map,o=s.terrain.depthAtPoint(this._pos),r=s.terrain.getElevationForLngLatZoom(this._lngLat,s.transform.tileZoom);if(s.transform.lngLatToCameraDepth(this._lngLat,r)-o<.006)return void(this._element.style.opacity=this._opacity);const n=-this._offset.y/s.transform._pixelPerMeter,l=Math.sin(s.getPitch()*Math.PI/180)*n,h=s.terrain.depthAtPoint(new e.P(this._pos.x,this._pos.y-this._offset.y)),c=s.transform.lngLatToCameraDepth(this._lngLat,r+l)-h>.006;(null===(a=this._popup)||void 0===a?void 0:a.isOpen())&&c&&this._popup.remove(),this._element.style.opacity=c?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(t){return this._offset=e.P.convert(t),this._update(),this}addClassName(t){this._element.classList.add(t);}removeClassName(t){this._element.classList.remove(t);}toggleClassName(t){return this._element.classList.toggle(t)}setDraggable(t){return this._draggable=!!t,this._map&&(t?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(t){return this._rotation=t||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(t){return this._rotationAlignment=t||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(t){return this._pitchAlignment=t&&"auto"!==t?t:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(t,e){return void 0===t&&void 0===e&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==t&&(this._opacity=t),void 0!==e&&(this._opacityWhenCovered=e),this._map&&this._updateOpacity(!0),this}}const Vs={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let Hs=0,Ws=!1;const $s={maxWidth:100,unit:"metric"};function Xs(t,e,i){const a=i&&i.maxWidth||100,s=t._container.clientHeight/2,o=t.unproject([0,s]),r=t.unproject([a,s]),n=o.distanceTo(r);if(i&&"imperial"===i.unit){const i=3.2808*n;i>5280?Ks(e,a,i/5280,t._getUIString("ScaleControl.Miles")):Ks(e,a,i,t._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?Ks(e,a,n/1852,t._getUIString("ScaleControl.NauticalMiles")):n>=1e3?Ks(e,a,n/1e3,t._getUIString("ScaleControl.Kilometers")):Ks(e,a,n,t._getUIString("ScaleControl.Meters"));}function Ks(t,e,i,a){const s=function(t){const e=Math.pow(10,`${Math.floor(t)}`.length-1);let i=t/e;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(t){const e=Math.pow(10,Math.ceil(-Math.log(t)/Math.LN10));return Math.round(t*e)/e}(i),e*i}(i);t.style.width=e*(s/i)+"px",t.innerHTML=`${s} ${a}`;}const Js={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1},Ys=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function Qs(t){if(t){if("number"==typeof t){const i=Math.round(Math.abs(t)/Math.SQRT2);return {center:new e.P(0,0),top:new e.P(0,t),"top-left":new e.P(i,i),"top-right":new e.P(-i,i),bottom:new e.P(0,-t),"bottom-left":new e.P(i,-i),"bottom-right":new e.P(-i,-i),left:new e.P(t,0),right:new e.P(-t,0)}}if(t instanceof e.P||Array.isArray(t)){const i=e.P.convert(t);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:e.P.convert(t.center||[0,0]),top:e.P.convert(t.top||[0,0]),"top-left":e.P.convert(t["top-left"]||[0,0]),"top-right":e.P.convert(t["top-right"]||[0,0]),bottom:e.P.convert(t.bottom||[0,0]),"bottom-left":e.P.convert(t["bottom-left"]||[0,0]),"bottom-right":e.P.convert(t["bottom-right"]||[0,0]),left:e.P.convert(t.left||[0,0]),right:e.P.convert(t.right||[0,0])}}return Qs(new e.P(0,0))}const to=i;t.AJAXError=e.bh,t.Evented=e.E,t.LngLat=e.N,t.MercatorCoordinate=e.Z,t.Point=e.P,t.addProtocol=e.bi,t.config=e.a,t.removeProtocol=e.bj,t.AttributionControl=Es,t.BoxZoomHandler=Ua,t.CanvasSource=et,t.CooperativeGesturesHandler=vs,t.DoubleClickZoomHandler=ds,t.DragPanHandler=ms,t.DragRotateHandler=fs,t.EdgeInsets=ba,t.FullscreenControl=class extends e.E{constructor(t={}){super(),this._onFullscreenChange=()=>{var t;let e=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(t=null==e?void 0:e.shadowRoot)||void 0===t?void 0:t.fullscreenElement;)e=e.shadowRoot.fullscreenElement;e===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=!1,t&&t.container&&(t.container instanceof HTMLElement?this._container=t.container:e.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(t){return this._map=t,this._container||(this._container=this._map.getContainer()),this._controlContainer=r.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){r.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const t=this._fullscreenButton=r.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);r.create("span","maplibregl-ctrl-icon",t).setAttribute("aria-hidden","true"),t.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const t=this._getTitle();this._fullscreenButton.setAttribute("aria-label",t),this._fullscreenButton.title=t;}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new e.k("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new e.k("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},t.GeoJSONSource=J,t.GeolocateControl=class extends e.E{constructor(t){super(),this._onSuccess=t=>{if(this._map){if(this._isOutOfMapMaxBounds(t))return this._setErrorState(),this.fire(new e.k("outofmaxbounds",t)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=t,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(t),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(t),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new e.k("geolocate",t)),this._finish();}},this._updateCamera=t=>{const i=new e.N(t.coords.longitude,t.coords.latitude),a=t.coords.accuracy,s=this._map.getBearing(),o=e.e({bearing:s},this.options.fitBoundsOptions),r=H.fromLngLat(i,a);this._map.fitBounds(r,o,{geolocateSource:!0});},this._updateMarker=t=>{if(t){const i=new e.N(t.coords.longitude,t.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=t.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onZoom=()=>{this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();},this._onError=t=>{if(this._map){if(this.options.trackUserLocation)if(1===t.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const t=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=t,this._geolocateButton.setAttribute("aria-label",t),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===t.code&&Ws)return;this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new e.k("error",t)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(t=>t.preventDefault())),this._geolocateButton=r.create("button","maplibregl-ctrl-geolocate",this._container),r.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0);},this._finishSetupUI=t=>{if(this._map){if(!1===t){e.w("Geolocation support is not available so the GeolocateControl will be disabled.");const t=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=t,this._geolocateButton.setAttribute("aria-label",t);}else {const t=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=t,this._geolocateButton.setAttribute("aria-label",t);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=r.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new qs({element:this._dotElement}),this._circleElement=r.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new qs({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(t=>{t.geolocateSource||"ACTIVE_LOCK"!==this._watchState||t.originalEvent&&"resize"===t.originalEvent.type||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new e.k("trackuserlocationend")),this.fire(new e.k("userlocationlostfocus")));}));}},this.options=e.e({},Vs,t);}onAdd(t){return this._map=t,this._container=r.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return e._(this,arguments,void 0,(function*(t=!1){if(void 0!==Us&&!t)return Us;if(void 0===window.navigator.permissions)return Us=!!window.navigator.geolocation,Us;try{const t=yield window.navigator.permissions.query({name:"geolocation"});Us="denied"!==t.state;}catch(t){Us=!!window.navigator.geolocation;}return Us}))}().then((t=>this._finishSetupUI(t))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),r.remove(this._container),this._map.off("zoom",this._onZoom),this._map=void 0,Hs=0,Ws=!1;}_isOutOfMapMaxBounds(t){const e=this._map.getMaxBounds(),i=t.coords;return e&&(i.longitudee.getEast()||i.latitudee.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadius(){const t=this._map.getBounds(),e=t.getSouthEast(),i=t.getNorthEast(),a=e.distanceTo(i),s=Math.ceil(this._accuracy/(a/this._map._container.clientHeight)*2);this._circleElement.style.width=`${s}px`,this._circleElement.style.height=`${s}px`;}trigger(){if(!this._setup)return e.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new e.k("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":Hs--,Ws=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new e.k("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new e.k("trackuserlocationstart")),this.fire(new e.k("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let t;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),Hs++,Hs>1?(t={maximumAge:6e5,timeout:0},Ws=!0):(t=this.options.positionOptions,Ws=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,t);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},t.Hash=Ea,t.ImageSource=Q,t.KeyboardHandler=ls,t.LngLatBounds=H,t.LogoControl=Ps,t.Map=class extends Ts{constructor(t){e.bf.mark(e.bg.create);const i=Object.assign(Object.assign({},Fs),t);if(null!=i.minZoom&&null!=i.maxZoom&&i.minZoom>i.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=i.minPitch&&null!=i.maxPitch&&i.minPitch>i.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=i.minPitch&&i.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=i.maxPitch&&i.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");if(super(new Ta(i.minZoom,i.maxZoom,i.minPitch,i.maxPitch,i.renderWorldCopies),{bearingSnap:i.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new Cs,this._controls=[],this._mapId=e.a4(),this._contextLost=t=>{t.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new e.k("webglcontextlost",{originalEvent:t}));},this._contextRestored=t=>{this._setupPainter(),this.resize(),this._update(),this.fire(new e.k("webglcontextrestored",{originalEvent:t}));},this._onMapScroll=t=>{if(t.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update();},this._interactive=i.interactive,this._maxTileCacheSize=i.maxTileCacheSize,this._maxTileCacheZoomLevels=i.maxTileCacheZoomLevels,this._failIfMajorPerformanceCaveat=!0===i.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=!0===i.preserveDrawingBuffer,this._antialias=!0===i.antialias,this._trackResize=!0===i.trackResize,this._bearingSnap=i.bearingSnap,this._refreshExpiredTiles=!0===i.refreshExpiredTiles,this._fadeDuration=i.fadeDuration,this._crossSourceCollisions=!0===i.crossSourceCollisions,this._collectResourceTiming=!0===i.collectResourceTiming,this._locale=Object.assign(Object.assign({},ks),i.locale),this._clickTolerance=i.clickTolerance,this._overridePixelRatio=i.pixelRatio,this._maxCanvasSize=i.maxCanvasSize,this.transformCameraUpdate=i.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===i.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=_.addThrottleControl((()=>this.isMoving())),this._requestManager=new p(i.transformRequest),"string"==typeof i.container){if(this._container=document.getElementById(i.container),!this._container)throw new Error(`Container '${i.container}' not found.`)}else {if(!(i.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=i.container;}if(i.maxBounds&&this.setMaxBounds(i.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))).on("moveend",(()=>this._update(!1))).on("zoom",(()=>this._update(!0))).on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0);})).once("idle",(()=>{this._idleTriggered=!0;})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let t=!1;const e=Ia((t=>{this._trackResize&&!this._removed&&(this.resize(t),this.redraw());}),50);this._resizeObserver=new ResizeObserver((i=>{t?e(i):t=!0;})),this._resizeObserver.observe(this._container);}this.handlers=new ws(this,i),this._hash=i.hash&&new Ea("string"==typeof i.hash&&i.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:i.center,zoom:i.zoom,bearing:i.bearing,pitch:i.pitch}),i.bounds&&(this.resize(),this.fitBounds(i.bounds,e.e({},i.fitBoundsOptions,{duration:0})))),this.resize(),this._localIdeographFontFamily=i.localIdeographFontFamily,this._validateStyle=i.validateStyle,i.style&&this.setStyle(i.style,{localIdeographFontFamily:i.localIdeographFontFamily}),i.attributionControl&&this.addControl(new Es("boolean"==typeof i.attributionControl?void 0:i.attributionControl)),i.maplibreLogo&&this.addControl(new Ps,i.logoPosition),this.on("style.load",(()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet);})),this.on("data",(t=>{this._update("style"===t.dataType),this.fire(new e.k(`${t.dataType}data`,t));})),this.on("dataloading",(t=>{this.fire(new e.k(`${t.dataType}dataloading`,t));})),this.on("dataabort",(t=>{this.fire(new e.k("sourcedataabort",t));}));}_getMapId(){return this._mapId}addControl(t,i){if(void 0===i&&(i=t.getDefaultPosition?t.getDefaultPosition():"top-right"),!t||!t.onAdd)return this.fire(new e.j(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const a=t.onAdd(this);this._controls.push(t);const s=this._controlPositions[i];return -1!==i.indexOf("bottom")?s.insertBefore(a,s.firstChild):s.appendChild(a),this}removeControl(t){if(!t||!t.onRemove)return this.fire(new e.j(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(t);return i>-1&&this._controls.splice(i,1),t.onRemove(this),this}hasControl(t){return this._controls.indexOf(t)>-1}calculateCameraOptionsFromTo(t,e,i,a){return null==a&&this.terrain&&(a=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(t,e,i,a)}resize(t){var i;const a=this._containerDimensions(),s=a[0],o=a[1],r=this._getClampedPixelRatio(s,o);if(this._resizeCanvas(s,o,r),this.painter.resize(s,o,r),this.painter.overLimit()){const t=this.painter.context.gl;this._maxCanvasSize=[t.drawingBufferWidth,t.drawingBufferHeight];const e=this._getClampedPixelRatio(s,o);this._resizeCanvas(s,o,e),this.painter.resize(s,o,e);}this.transform.resize(s,o),null===(i=this._requestedCameraState)||void 0===i||i.resize(s,o);const n=!this._moving;return n&&(this.stop(),this.fire(new e.k("movestart",t)).fire(new e.k("move",t))),this.fire(new e.k("resize",t)),n&&this.fire(new e.k("moveend",t)),this}_getClampedPixelRatio(t,e){const{0:i,1:a}=this._maxCanvasSize,s=this.getPixelRatio(),o=t*s,r=e*s;return Math.min(o>i?i/o:1,r>a?a/r:1)*s}getPixelRatio(){var t;return null!==(t=this._overridePixelRatio)&&void 0!==t?t:devicePixelRatio}setPixelRatio(t){this._overridePixelRatio=t,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(t){return this.transform.setMaxBounds(H.convert(t)),this._update()}setMinZoom(t){if((t=null==t?-2:t)>=-2&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(t){if((t=null==t?0:t)<0)throw new Error("minPitch must be greater than or equal to 0");if(t>=0&&t<=this.transform.maxPitch)return this.transform.minPitch=t,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(t>=this.transform.minPitch)return this.transform.maxPitch=t,this._update(),this.getPitch()>t&&this.setPitch(t),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(t){return this.transform.renderWorldCopies=t,this._update()}project(t){return this.transform.locationPoint(e.N.convert(t),this.style&&this.terrain)}unproject(t){return this.transform.pointLocation(e.P.convert(t),this.terrain)}isMoving(){var t;return this._moving||(null===(t=this.handlers)||void 0===t?void 0:t.isMoving())}isZooming(){var t;return this._zooming||(null===(t=this.handlers)||void 0===t?void 0:t.isZooming())}isRotating(){var t;return this._rotating||(null===(t=this.handlers)||void 0===t?void 0:t.isRotating())}_createDelegatedListener(t,e,i){if("mouseenter"===t||"mouseover"===t){let a=!1;const s=s=>{const o=e.filter((t=>this.getLayer(t))),r=0!==o.length?this.queryRenderedFeatures(s.point,{layers:o}):[];r.length?a||(a=!0,i.call(this,new ka(t,this,s.originalEvent,{features:r}))):a=!1;};return {layers:e,listener:i,delegates:{mousemove:s,mouseout:()=>{a=!1;}}}}if("mouseleave"===t||"mouseout"===t){let a=!1;const s=s=>{const o=e.filter((t=>this.getLayer(t)));(0!==o.length?this.queryRenderedFeatures(s.point,{layers:o}):[]).length?a=!0:a&&(a=!1,i.call(this,new ka(t,this,s.originalEvent)));},o=e=>{a&&(a=!1,i.call(this,new ka(t,this,e.originalEvent)));};return {layers:e,listener:i,delegates:{mousemove:s,mouseout:o}}}{const a=t=>{const a=e.filter((t=>this.getLayer(t))),s=0!==a.length?this.queryRenderedFeatures(t.point,{layers:a}):[];s.length&&(t.features=s,i.call(this,t),delete t.features);};return {layers:e,listener:i,delegates:{[t]:a}}}}_saveDelegatedListener(t,e){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[t]=this._delegatedListeners[t]||[],this._delegatedListeners[t].push(e);}_removeDelegatedListener(t,e,i){if(!this._delegatedListeners||!this._delegatedListeners[t])return;const a=this._delegatedListeners[t];for(let t=0;te.includes(t)))){for(const t in s.delegates)this.off(t,s.delegates[t]);return void a.splice(t,1)}}}on(t,e,i){if(void 0===i)return super.on(t,e);const a=this._createDelegatedListener(t,"string"==typeof e?[e]:e,i);this._saveDelegatedListener(t,a);for(const t in a.delegates)this.on(t,a.delegates[t]);return this}once(t,e,i){if(void 0===i)return super.once(t,e);const a="string"==typeof e?[e]:e,s=this._createDelegatedListener(t,a,i);for(const e in s.delegates){const o=s.delegates[e];s.delegates[e]=(...e)=>{this._removeDelegatedListener(t,a,i),o(...e);};}this._saveDelegatedListener(t,s);for(const t in s.delegates)this.once(t,s.delegates[t]);return this}off(t,e,i){return void 0===i?super.off(t,e):(this._removeDelegatedListener(t,"string"==typeof e?[e]:e,i),this)}queryRenderedFeatures(t,i){if(!this.style)return [];let a;const s=t instanceof e.P||Array.isArray(t),o=s?t:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(s?{}:t)||{},o instanceof e.P||"number"==typeof o[0])a=[e.P.convert(o)];else {const t=e.P.convert(o[0]),i=e.P.convert(o[1]);a=[t,new e.P(i.x,t.y),i,new e.P(t.x,i.y),t];}return this.style.queryRenderedFeatures(a,i,this.transform)}querySourceFeatures(t,e){return this.style.querySourceFeatures(t,e)}setStyle(t,i){return !1!==(i=e.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&t?(this._diffStyle(t,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(t,i))}setTransformRequest(t){return this._requestManager.setTransformRequest(t),this}_getUIString(t){const e=this._locale[t];if(null==e)throw new Error(`Missing UI string '${t}'`);return e}_updateStyle(t,e){if(e.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(t,e)));const i=this.style&&e.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!t)),t?(this.style=new de(this,e||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof t?this.style.loadURL(t,e,i):this.style.loadJSON(t,e,i),this):(delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new de(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(t,i){if("string"==typeof t){const a=this._requestManager.transformRequest(t,"Style");e.h(a,new AbortController).then((t=>{this._updateDiff(t.data,i);})).catch((t=>{t&&this.fire(new e.j(t));}));}else "object"==typeof t&&this._updateDiff(t,i);}_updateDiff(t,i){try{this.style.setState(t,i)&&this._update(!0);}catch(a){e.w(`Unable to perform style diff: ${a.message||a.error||a}. Rebuilding the style from scratch.`),this._updateStyle(t,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():e.w("There is no style added to the map.")}addSource(t,e){return this._lazyInitEmptyStyle(),this.style.addSource(t,e),this._update(!0)}isSourceLoaded(t){const i=this.style&&this.style.sourceCaches[t];if(void 0!==i)return i.loaded();this.fire(new e.j(new Error(`There is no source with ID '${t}'`)));}setTerrain(t){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),t){const i=this.style.sourceCaches[t.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${t.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const a=this.style._layers[i];"hillshade"===a.type&&a.source===t.source&&e.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");}this.terrain=new zs(this.painter,i,t),this.painter.renderToTexture=new Rs(this.painter,this.terrain),this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom),this.transform.elevation=this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom),this._terrainDataCallback=e=>{"style"===e.dataType?this.terrain.sourceCache.freeRtt():"source"===e.dataType&&e.tile&&(e.sourceId!==t.source||this._elevationFreeze||(this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom),this.transform.elevation=this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.terrain.sourceCache.freeRtt(e.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.minElevationForCurrentTile=0,this.transform.elevation=0;return this.fire(new e.k("terrain",{terrain:t})),this}getTerrain(){var t,e;return null!==(e=null===(t=this.terrain)||void 0===t?void 0:t.options)&&void 0!==e?e:null}areTilesLoaded(){const t=this.style&&this.style.sourceCaches;for(const e in t){const i=t[e]._tiles;for(const t in i){const e=i[t];if("loaded"!==e.state&&"errored"!==e.state)return !1}}return !0}removeSource(t){return this.style.removeSource(t),this._update(!0)}getSource(t){return this.style.getSource(t)}addImage(t,i,a={}){const{pixelRatio:s=1,sdf:r=!1,stretchX:n,stretchY:l,content:h,textFitWidth:c,textFitHeight:u}=a;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||e.b(i))){if(void 0===i.width||void 0===i.height)return this.fire(new e.j(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:a,height:o,data:d}=i,_=i;return this.style.addImage(t,{data:new e.R({width:a,height:o},new Uint8Array(d)),pixelRatio:s,stretchX:n,stretchY:l,content:h,textFitWidth:c,textFitHeight:u,sdf:r,version:0,userImage:_}),_.onAdd&&_.onAdd(this,t),this}}{const{width:a,height:d,data:_}=o.getImageData(i);this.style.addImage(t,{data:new e.R({width:a,height:d},_),pixelRatio:s,stretchX:n,stretchY:l,content:h,textFitWidth:c,textFitHeight:u,sdf:r,version:0});}}updateImage(t,i){const a=this.style.getImage(t);if(!a)return this.fire(new e.j(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const s=i instanceof HTMLImageElement||e.b(i)?o.getImageData(i):i,{width:r,height:n,data:l}=s;if(void 0===r||void 0===n)return this.fire(new e.j(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(r!==a.data.width||n!==a.data.height)return this.fire(new e.j(new Error("The width and height of the updated image must be that same as the previous version of the image")));const h=!(i instanceof HTMLImageElement||e.b(i));return a.data.replace(l,h),this.style.updateImage(t,a),this}getImage(t){return this.style.getImage(t)}hasImage(t){return t?!!this.style.getImage(t):(this.fire(new e.j(new Error("Missing required image id"))),!1)}removeImage(t){this.style.removeImage(t);}loadImage(t){return _.getImage(this._requestManager.transformRequest(t,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(t,e){return this._lazyInitEmptyStyle(),this.style.addLayer(t,e),this._update(!0)}moveLayer(t,e){return this.style.moveLayer(t,e),this._update(!0)}removeLayer(t){return this.style.removeLayer(t),this._update(!0)}getLayer(t){return this.style.getLayer(t)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(t,e,i){return this.style.setLayerZoomRange(t,e,i),this._update(!0)}setFilter(t,e,i={}){return this.style.setFilter(t,e,i),this._update(!0)}getFilter(t){return this.style.getFilter(t)}setPaintProperty(t,e,i,a={}){return this.style.setPaintProperty(t,e,i,a),this._update(!0)}getPaintProperty(t,e){return this.style.getPaintProperty(t,e)}setLayoutProperty(t,e,i,a={}){return this.style.setLayoutProperty(t,e,i,a),this._update(!0)}getLayoutProperty(t,e){return this.style.getLayoutProperty(t,e)}setGlyphs(t,e={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(t,e),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(t,e,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(t,e,i,(t=>{t||this._update(!0);})),this}removeSprite(t){return this._lazyInitEmptyStyle(),this.style.removeSprite(t),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(t,e={}){return this._lazyInitEmptyStyle(),this.style.setSprite(t,e,(t=>{t||this._update(!0);})),this}setLight(t,e={}){return this._lazyInitEmptyStyle(),this.style.setLight(t,e),this._update(!0)}getLight(){return this.style.getLight()}setSky(t){return this._lazyInitEmptyStyle(),this.style.setSky(t),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(t,e){return this.style.setFeatureState(t,e),this._update()}removeFeatureState(t,e){return this.style.removeFeatureState(t,e),this._update()}getFeatureState(t){return this.style.getFeatureState(t)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let t=0,e=0;return this._container&&(t=this._container.clientWidth||400,e=this._container.clientHeight||300),[t,e]}_setupContainer(){const t=this._container;t.classList.add("maplibregl-map");const e=this._canvasContainer=r.create("div","maplibregl-canvas-container",t);this._interactive&&e.classList.add("maplibregl-interactive"),this._canvas=r.create("canvas","maplibregl-canvas",e),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),a=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],a);const s=this._controlContainer=r.create("div","maplibregl-control-container",t),o=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((t=>{o[t]=r.create("div",`maplibregl-ctrl-${t} `,s);})),this._container.addEventListener("scroll",this._onMapScroll,!1);}_resizeCanvas(t,e,i){this._canvas.width=Math.floor(i*t),this._canvas.height=Math.floor(i*e),this._canvas.style.width=`${t}px`,this._canvas.style.height=`${e}px`;}_setupPainter(){const t={alpha:!0,stencil:!0,depth:!0,failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1};let e=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{e={requestedAttributes:t},i&&(e.statusMessage=i.statusMessage,e.type=i.type);}),{once:!0});const i=this._canvas.getContext("webgl2",t)||this._canvas.getContext("webgl",t);if(!i){const t="Failed to initialize WebGL";throw e?(e.message=t,new Error(JSON.stringify(e))):new Error(t)}this.painter=new va(i,this.transform),n.testSupport(i);}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(t){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||t,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(t){return this._update(),this._renderTaskQueue.add(t)}_cancelRenderFrame(t){this._renderTaskQueue.remove(t);}_render(t){const i=this._idleTriggered?this._fadeDuration:0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(t),this._removed)return;let a=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const t=this.transform.zoom,s=o.now();this.style.zoomHistory.update(t,s);const r=new e.z(t,{now:s,fadeDuration:i,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),n=r.crossFadingFactor();1===n&&n===this._crossFadingFactor||(a=!0,this._crossFadingFactor=n),this.style.update(r);}this.style&&this._sourcesDirty&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.minElevationForCurrentTile=this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom),this._elevationFreeze||(this.transform.elevation=this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.minElevationForCurrentTile=0,this.transform.elevation=0),this._placementDirty=this.style&&this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,i,this._crossSourceCollisions),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:i,showPadding:this.showPadding}),this.fire(new e.k("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,e.bf.mark(e.bg.load),this.fire(new e.k("load"))),this.style&&(this.style.hasTransitions()||a)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const s=this._sourcesDirty||this._styleDirty||this._placementDirty;return s||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new e.k("idle")),!this._loaded||this._fullyLoaded||s||(this._fullyLoaded=!0,e.bf.mark(e.bg.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var t;this._hash&&this._hash.remove();for(const t of this._controls)t.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),_.removeThrottleControl(this._imageQueueHandle),null===(t=this._resizeObserver)||void 0===t||t.disconnect();const i=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==i?void 0:i.loseContext)&&i.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),r.remove(this._canvasContainer),r.remove(this._controlContainer),this._container.classList.remove("maplibregl-map"),e.bf.clearMetrics(),this._removed=!0,this.fire(new e.k("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,o.frameAsync(this._frameRequest).then((t=>{e.bf.frame(t),this._frameRequest=null,this._render(t);})).catch((()=>{})));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(t){this._showTileBoundaries!==t&&(this._showTileBoundaries=t,this._update());}get showPadding(){return !!this._showPadding}set showPadding(t){this._showPadding!==t&&(this._showPadding=t,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(t){this._showCollisionBoxes!==t&&(this._showCollisionBoxes=t,t?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(t){this._showOverdrawInspector!==t&&(this._showOverdrawInspector=t,this._update());}get repaint(){return !!this._repaint}set repaint(t){this._repaint!==t&&(this._repaint=t,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(t){this._vertices=t,this._update();}get version(){return Ls}getCameraTargetElevation(){return this.transform.elevation}},t.MapMouseEvent=ka,t.MapTouchEvent=La,t.MapWheelEvent=Fa,t.Marker=qs,t.NavigationControl=class{constructor(t){this._updateZoomButtons=()=>{const t=this._map.getZoom(),e=t===this._map.getMaxZoom(),i=t===this._map.getMinZoom();this._zoomInButton.disabled=e,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",e.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{const t=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitch*(Math.PI/180)),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${this._map.transform.angle*(180/Math.PI)}deg)`:`rotate(${this._map.transform.angle*(180/Math.PI)}deg)`;this._compassIcon.style.transform=t;},this._setButtonTitle=(t,e)=>{const i=this._map._getUIString(`NavigationControl.${e}`);t.title=i,t.setAttribute("aria-label",i);},this.options=e.e({},Os,t),this._container=r.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(t=>t.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(t=>this._map.zoomIn({},{originalEvent:t}))),r.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(t=>this._map.zoomOut({},{originalEvent:t}))),r.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(t=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:t}):this._map.resetNorth({},{originalEvent:t});})),this._compassIcon=r.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(t){return this._map=t,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new Ns(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){r.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(t,e){const i=r.create("button",t,this._container);return i.type="button",i.addEventListener("click",e),i}},t.Popup=class extends e.E{constructor(t){super(),this.remove=()=>(this._content&&r.remove(this._content),this._container&&(r.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new e.k("close"))),this),this._onMouseUp=t=>{this._update(t.point);},this._onMouseMove=t=>{this._update(t.point);},this._onDrag=t=>{this._update(t.point);},this._update=t=>{var e;if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=r.create("div","maplibregl-popup",this._map.getContainer()),this._tip=r.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const t of this.options.className.split(" "))this._container.classList.add(t);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer");}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=this._map.transform.renderWorldCopies&&!this._trackPointer?js(this._lngLat,this._flatPos,this._map.transform):null===(e=this._lngLat)||void 0===e?void 0:e.wrap(),this._trackPointer&&!t)return;const i=this._flatPos=this._pos=this._trackPointer&&t?t:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&t?t:this._map.transform.locationPoint(this._lngLat));let a=this.options.anchor;const s=Qs(this.options.offset);if(!a){const t=this._container.offsetWidth,e=this._container.offsetHeight;let o;o=i.y+s.bottom.ythis._map.transform.height-e?["bottom"]:[],i.xthis._map.transform.width-t/2&&o.push("right"),a=0===o.length?"bottom":o.join("-");}let o=i.add(s[a]);this.options.subpixelPositioning||(o=o.round()),r.setTransform(this._container,`${Zs[a]} translate(${o.x}px,${o.y}px)`),Gs(this._container,a,"popup");},this._onClose=()=>{this.remove();},this.options=e.e(Object.create(Js),t);}addTo(t){return this._map&&this.remove(),this._map=t,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new e.k("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(t){return this._lngLat=e.N.convert(t),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(t){return this.setDOMContent(document.createTextNode(t))}setHTML(t){const e=document.createDocumentFragment(),i=document.createElement("body");let a;for(i.innerHTML=t;a=i.firstChild,a;)e.appendChild(a);return this.setDOMContent(e)}getMaxWidth(){var t;return null===(t=this._container)||void 0===t?void 0:t.style.maxWidth}setMaxWidth(t){return this.options.maxWidth=t,this._update(),this}setDOMContent(t){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=r.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(t),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(t){return this._container&&this._container.classList.add(t),this}removeClassName(t){return this._container&&this._container.classList.remove(t),this}setOffset(t){return this.options.offset=t,this._update(),this}toggleClassName(t){if(this._container)return this._container.classList.toggle(t)}setSubpixelPositioning(t){this.options.subpixelPositioning=t;}_createCloseButton(){this.options.closeButton&&(this._closeButton=r.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const t=this._container.querySelector(Ys);t&&t.focus();}},t.RasterDEMTileSource=K,t.RasterTileSource=X,t.ScaleControl=class{constructor(t){this._onMove=()=>{Xs(this._map,this._container,this.options);},this.setUnit=t=>{this.options.unit=t,Xs(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},$s),t);}getDefaultPosition(){return "bottom-left"}onAdd(t){return this._map=t,this._container=r.create("div","maplibregl-ctrl maplibregl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){r.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;}},t.ScrollZoomHandler=us,t.Style=de,t.TerrainControl=class{constructor(t){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=t;}onAdd(t){return this._map=t,this._container=r.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=r.create("button","maplibregl-ctrl-terrain",this._container),r.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){r.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0;}},t.TwoFingersTouchPitchHandler=rs,t.TwoFingersTouchRotateHandler=ss,t.TwoFingersTouchZoomHandler=is,t.TwoFingersTouchZoomRotateHandler=gs,t.VectorTileSource=$,t.VideoSource=tt,t.addSourceType=(t,i)=>e._(void 0,void 0,void 0,(function*(){if(at(t))throw new Error(`A source type called "${t}" already exists.`);((t,e)=>{it[t]=e;})(t,i);})),t.clearPrewarmedResources=function(){const t=B;t&&(t.isPreloaded()&&1===t.numActive()?(t.release(k),B=null):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()"));},t.getMaxParallelImageRequests=function(){return e.a.MAX_PARALLEL_IMAGE_REQUESTS},t.getRTLTextPluginStatus=function(){return nt().getRTLTextPluginStatus()},t.getVersion=function(){return to},t.getWorkerCount=function(){return L.workerCount},t.getWorkerUrl=function(){return e.a.WORKER_URL},t.importScriptInWorkers=function(t){return j().broadcast("IS",t)},t.prewarm=function(){N().acquire(k);},t.setMaxParallelImageRequests=function(t){e.a.MAX_PARALLEL_IMAGE_REQUESTS=t;},t.setRTLTextPlugin=function(t,e){return nt().setRTLTextPlugin(t,e)},t.setWorkerCount=function(t){L.workerCount=t;},t.setWorkerUrl=function(t){e.a.WORKER_URL=t;};})); + +// +// Our custom intro provides a specialized "define()" function, called by the +// AMD modules below, that sets up the worker blob URL and then executes the +// main module, storing its exported value as 'maplibregl' + + +var maplibregl$1 = maplibregl; + +return maplibregl$1; + +})); +//# sourceMappingURL=maplibre-gl.js.map